3
0

style-guide.txt 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714
  1. Busybox Style Guide
  2. ===================
  3. This document describes the coding style conventions used in Busybox. If you
  4. add a new file to Busybox or are editing an existing file, please format your
  5. code according to this style. If you are the maintainer of a file that does
  6. not follow these guidelines, please -- at your own convenience -- modify the
  7. file(s) you maintain to bring them into conformance with this style guide.
  8. Please note that this is a low priority task.
  9. To help you format the whitespace of your programs, an ".indent.pro" file is
  10. included in the main Busybox source directory that contains option flags to
  11. format code as per this style guide. This way you can run GNU indent on your
  12. files by typing 'indent myfile.c myfile.h' and it will magically apply all the
  13. right formatting rules to your file. Please _do_not_ run this on all the files
  14. in the directory, just your own.
  15. Declaration Order
  16. -----------------
  17. Here is the preferred order in which code should be laid out in a file:
  18. - commented program name and one-line description
  19. - commented author name and email address(es)
  20. - commented GPL boilerplate
  21. - commented longer description / notes for the program (if needed)
  22. - #includes of .h files with angle brackets (<>) around them
  23. - #includes of .h files with quotes ("") around them
  24. - #defines (if any, note the section below titled "Avoid the Preprocessor")
  25. - const and global variables
  26. - function declarations (if necessary)
  27. - function implementations
  28. Whitespace and Formatting
  29. -------------------------
  30. This is everybody's favorite flame topic so let's get it out of the way right
  31. up front.
  32. Tabs vs. Spaces in Line Indentation
  33. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  34. The preference in Busybox is to indent lines with tabs. Do not indent lines
  35. with spaces and do not indents lines using a mixture of tabs and spaces. (The
  36. indentation style in the Apache and Postfix source does this sort of thing:
  37. \s\s\s\sif (expr) {\n\tstmt; --ick.) The only exception to this rule is
  38. multi-line comments that use an asterisk at the beginning of each line, i.e.:
  39. \t/*
  40. \t * This is a block comment.
  41. \t * Note that it has multiple lines
  42. \t * and that the beginning of each line has a tab plus a space
  43. \t * except for the opening '/*' line where the slash
  44. \t * is used instead of a space.
  45. \t */
  46. Furthermore, The preference is that tabs be set to display at four spaces
  47. wide, but the beauty of using only tabs (and not spaces) at the beginning of
  48. lines is that you can set your editor to display tabs at *whatever* number of
  49. spaces is desired and the code will still look fine.
  50. Operator Spacing
  51. ~~~~~~~~~~~~~~~~
  52. Put spaces between terms and operators. Example:
  53. Don't do this:
  54. for(i=0;i<num_items;i++){
  55. Do this instead:
  56. for (i = 0; i < num_items; i++) {
  57. While it extends the line a bit longer, the spaced version is more
  58. readable. An allowable exception to this rule is the situation where
  59. excluding the spacing makes it more obvious that we are dealing with a
  60. single term (even if it is a compound term) such as:
  61. if (str[idx] == '/' && str[idx-1] != '\\')
  62. or
  63. if ((argc-1) - (optind+1) > 0)
  64. Bracket Spacing
  65. ~~~~~~~~~~~~~~~
  66. If an opening bracket starts a function, it should be on the
  67. next line with no spacing before it. However, if a bracket follows an opening
  68. control block, it should be on the same line with a single space (not a tab)
  69. between it and the opening control block statement. Examples:
  70. Don't do this:
  71. while (!done)
  72. {
  73. do
  74. {
  75. Don't do this either:
  76. while (!done){
  77. do{
  78. And for heaven's sake, don't do this:
  79. while (!done)
  80. {
  81. do
  82. {
  83. Do this instead:
  84. while (!done) {
  85. do {
  86. If you have long logic statements that need to be wrapped, then uncuddling
  87. the bracket to improve readability is allowed. Generally, this style makes
  88. it easier for reader to notice that 2nd and following lines are still
  89. inside 'if':
  90. if (some_really_long_checks && some_other_really_long_checks
  91. && some_more_really_long_checks
  92. && even_more_of_long_checks
  93. ) {
  94. do_foo_now;
  95. Spacing around Parentheses
  96. ~~~~~~~~~~~~~~~~~~~~~~~~~~
  97. Put a space between C keywords and left parens, but not between function names
  98. and the left paren that starts it's parameter list (whether it is being
  99. declared or called). Examples:
  100. Don't do this:
  101. while(foo) {
  102. for(i = 0; i < n; i++) {
  103. Do this instead:
  104. while (foo) {
  105. for (i = 0; i < n; i++) {
  106. But do functions like this:
  107. static int my_func(int foo, char bar)
  108. ...
  109. baz = my_func(1, 2);
  110. Also, don't put a space between the left paren and the first term, nor between
  111. the last arg and the right paren.
  112. Don't do this:
  113. if ( x < 1 )
  114. strcmp( thisstr, thatstr )
  115. Do this instead:
  116. if (x < 1)
  117. strcmp(thisstr, thatstr)
  118. Cuddled Elses
  119. ~~~~~~~~~~~~~
  120. Also, please "cuddle" your else statements by putting the else keyword on the
  121. same line after the right bracket that closes an 'if' statement.
  122. Don't do this:
  123. if (foo) {
  124. stmt;
  125. }
  126. else {
  127. stmt;
  128. }
  129. Do this instead:
  130. if (foo) {
  131. stmt;
  132. } else {
  133. stmt;
  134. }
  135. The exception to this rule is if you want to include a comment before the else
  136. block. Example:
  137. if (foo) {
  138. stmts...
  139. }
  140. /* otherwise, we're just kidding ourselves, so re-frob the input */
  141. else {
  142. other_stmts...
  143. }
  144. Labels
  145. ~~~~~~
  146. Labels should start at the beginning of the line, not indented to the block
  147. level (because they do not "belong" to block scope, only to whole function).
  148. if (foo) {
  149. stmt;
  150. label:
  151. stmt2;
  152. stmt;
  153. }
  154. (Putting label at position 1 prevents diff -p from confusing label for function
  155. name, but it's not a policy of busybox project to enforce such a minor detail).
  156. Variable and Function Names
  157. ---------------------------
  158. Use the K&R style with names in all lower-case and underscores occasionally
  159. used to separate words (e.g., "variable_name" and "numchars" are both
  160. acceptable). Using underscores makes variable and function names more readable
  161. because it looks like whitespace; using lower-case is easy on the eyes.
  162. Frowned upon:
  163. hitList
  164. TotalChars
  165. szFileName
  166. pf_Nfol_TriState
  167. Preferred:
  168. hit_list
  169. total_chars
  170. file_name
  171. sensible_name
  172. Exceptions:
  173. - Enums, macros, and constant variables are occasionally written in all
  174. upper-case with words optionally separated by underscores (i.e. FIFO_TYPE,
  175. ISBLKDEV()).
  176. - Nobody is going to get mad at you for using 'pvar' as the name of a
  177. variable that is a pointer to 'var'.
  178. Converting to K&R
  179. ~~~~~~~~~~~~~~~~~
  180. The Busybox codebase is very much a mixture of code gathered from a variety of
  181. sources. This explains why the current codebase contains such a hodge-podge of
  182. different naming styles (Java, Pascal, K&R, just-plain-weird, etc.). The K&R
  183. guideline explained above should therefore be used on new files that are added
  184. to the repository. Furthermore, the maintainer of an existing file that uses
  185. alternate naming conventions should, at his own convenience, convert those
  186. names over to K&R style. Converting variable names is a very low priority
  187. task.
  188. If you want to do a search-and-replace of a single variable name in different
  189. files, you can do the following in the busybox directory:
  190. $ perl -pi -e 's/\bOldVar\b/new_var/g' *.[ch]
  191. If you want to convert all the non-K&R vars in your file all at once, follow
  192. these steps:
  193. - In the busybox directory type 'examples/mk2knr.pl files-to-convert'. This
  194. does not do the actual conversion, rather, it generates a script called
  195. 'convertme.pl' that shows what will be converted, giving you a chance to
  196. review the changes beforehand.
  197. - Review the 'convertme.pl' script that gets generated in the busybox
  198. directory and remove / edit any of the substitutions in there. Please
  199. especially check for false positives (strings that should not be
  200. converted).
  201. - Type './convertme.pl same-files-as-before' to perform the actual
  202. conversion.
  203. - Compile and see if everything still works.
  204. Please be aware of changes that have cascading effects into other files. For
  205. example, if you're changing the name of something in, say utility.c, you
  206. should probably run 'examples/mk2knr.pl utility.c' at first, but when you run
  207. the 'convertme.pl' script you should run it on _all_ files like so:
  208. './convertme.pl *.[ch]'.
  209. Avoid The Preprocessor
  210. ----------------------
  211. At best, the preprocessor is a necessary evil, helping us account for platform
  212. and architecture differences. Using the preprocessor unnecessarily is just
  213. plain evil.
  214. The Folly of #define
  215. ~~~~~~~~~~~~~~~~~~~~
  216. Use 'const <type> var' for declaring constants.
  217. Don't do this:
  218. #define CONST 80
  219. Do this instead, when the variable is in a header file and will be used in
  220. several source files:
  221. enum { CONST = 80 };
  222. Although enum may look ugly to some people, it is better for code size.
  223. With "const int" compiler may fail to optimize it out and will reserve
  224. a real storage in rodata for it! (Hopefully, newer gcc will get better
  225. at it...). With "define", you have slight risk of polluting namespace
  226. (#define doesn't allow you to redefine the name in the inner scopes),
  227. and complex "define" are evaluated each time they uesd, not once
  228. at declarations like enums. Also, the preprocessor does _no_ type checking
  229. whatsoever, making it much more error prone.
  230. The Folly of Macros
  231. ~~~~~~~~~~~~~~~~~~~
  232. Use 'static inline' instead of a macro.
  233. Don't do this:
  234. #define mini_func(param1, param2) (param1 << param2)
  235. Do this instead:
  236. static inline int mini_func(int param1, param2)
  237. {
  238. return (param1 << param2);
  239. }
  240. Static inline functions are greatly preferred over macros. They provide type
  241. safety, have no length limitations, no formatting limitations, have an actual
  242. return value, and under gcc they are as cheap as macros. Besides, really long
  243. macros with backslashes at the end of each line are ugly as sin.
  244. The Folly of #ifdef
  245. ~~~~~~~~~~~~~~~~~~~
  246. Code cluttered with ifdefs is difficult to read and maintain. Don't do it.
  247. Instead, put your ifdefs at the top of your .c file (or in a header), and
  248. conditionally define 'static inline' functions, (or *maybe* macros), which are
  249. used in the code.
  250. Don't do this:
  251. ret = my_func(bar, baz);
  252. if (!ret)
  253. return -1;
  254. #ifdef CONFIG_FEATURE_FUNKY
  255. maybe_do_funky_stuff(bar, baz);
  256. #endif
  257. Do this instead:
  258. (in .h header file)
  259. #if ENABLE_FEATURE_FUNKY
  260. static inline void maybe_do_funky_stuff(int bar, int baz)
  261. {
  262. /* lotsa code in here */
  263. }
  264. #else
  265. static inline void maybe_do_funky_stuff(int bar, int baz) {}
  266. #endif
  267. (in the .c source file)
  268. ret = my_func(bar, baz);
  269. if (!ret)
  270. return -1;
  271. maybe_do_funky_stuff(bar, baz);
  272. The great thing about this approach is that the compiler will optimize away
  273. the "no-op" case (the empty function) when the feature is turned off.
  274. Note also the use of the word 'maybe' in the function name to indicate
  275. conditional execution.
  276. Notes on Strings
  277. ----------------
  278. Strings in C can get a little thorny. Here's some guidelines for dealing with
  279. strings in Busybox. (There is surely more that could be added to this
  280. section.)
  281. String Files
  282. ~~~~~~~~~~~~
  283. Put all help/usage messages in usage.c. Put other strings in messages.c.
  284. Putting these strings into their own file is a calculated decision designed to
  285. confine spelling errors to a single place and aid internationalization
  286. efforts, if needed. (Side Note: we might want to use a single file - maybe
  287. called 'strings.c' - instead of two, food for thought).
  288. Testing String Equivalence
  289. ~~~~~~~~~~~~~~~~~~~~~~~~~~
  290. There's a right way and a wrong way to test for string equivalence with
  291. strcmp():
  292. The wrong way:
  293. if (!strcmp(string, "foo")) {
  294. ...
  295. The right way:
  296. if (strcmp(string, "foo") == 0){
  297. ...
  298. The use of the "equals" (==) operator in the latter example makes it much more
  299. obvious that you are testing for equivalence. The former example with the
  300. "not" (!) operator makes it look like you are testing for an error. In a more
  301. perfect world, we would have a streq() function in the string library, but
  302. that ain't the world we're living in.
  303. Avoid Dangerous String Functions
  304. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  305. Unfortunately, the way C handles strings makes them prone to overruns when
  306. certain library functions are (mis)used. The following table offers a summary
  307. of some of the more notorious troublemakers:
  308. function overflows preferred
  309. -------------------------------------------------
  310. strcpy dest string safe_strncpy
  311. strncpy may fail to 0-terminate dst safe_strncpy
  312. strcat dest string strncat
  313. gets string it gets fgets
  314. getwd buf string getcwd
  315. [v]sprintf str buffer [v]snprintf
  316. realpath path buffer use with pathconf
  317. [vf]scanf its arguments just avoid it
  318. The above is by no means a complete list. Be careful out there.
  319. Avoid Big Static Buffers
  320. ------------------------
  321. First, some background to put this discussion in context: static buffers look
  322. like this in code:
  323. /* in a .c file outside any functions */
  324. static char buffer[BUFSIZ]; /* happily used by any function in this file,
  325. but ick! big! */
  326. The problem with these is that any time any busybox app is run, you pay a
  327. memory penalty for this buffer, even if the applet that uses said buffer is
  328. not run. This can be fixed, thusly:
  329. static char *buffer;
  330. ...
  331. other_func()
  332. {
  333. strcpy(buffer, lotsa_chars); /* happily uses global *buffer */
  334. ...
  335. foo_main()
  336. {
  337. buffer = xmalloc(sizeof(char)*BUFSIZ);
  338. ...
  339. However, this approach trades bss segment for text segment. Rather than
  340. mallocing the buffers (and thus growing the text size), buffers can be
  341. declared on the stack in the *_main() function and made available globally by
  342. assigning them to a global pointer thusly:
  343. static char *pbuffer;
  344. ...
  345. other_func()
  346. {
  347. strcpy(pbuffer, lotsa_chars); /* happily uses global *pbuffer */
  348. ...
  349. foo_main()
  350. {
  351. char *buffer[BUFSIZ]; /* declared locally, on stack */
  352. pbuffer = buffer; /* but available globally */
  353. ...
  354. This last approach has some advantages (low code size, space not used until
  355. it's needed), but can be a problem in some low resource machines that have
  356. very limited stack space (e.g., uCLinux).
  357. A macro is declared in busybox.h that implements compile-time selection
  358. between xmalloc() and stack creation, so you can code the line in question as
  359. RESERVE_CONFIG_BUFFER(buffer, BUFSIZ);
  360. and the right thing will happen, based on your configuration.
  361. Another relatively new trick of similar nature is explained
  362. in keep_data_small.txt.
  363. Miscellaneous Coding Guidelines
  364. -------------------------------
  365. The following are important items that don't fit into any of the above
  366. sections.
  367. Model Busybox Applets After GNU Counterparts
  368. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  369. When in doubt about the proper behavior of a Busybox program (output,
  370. formatting, options, etc.), model it after the equivalent GNU program.
  371. Doesn't matter how that program behaves on some other flavor of *NIX; doesn't
  372. matter what the POSIX standard says or doesn't say, just model Busybox
  373. programs after their GNU counterparts and it will make life easier on (nearly)
  374. everyone.
  375. The only time we deviate from emulating the GNU behavior is when:
  376. - We are deliberately not supporting a feature (such as a command line
  377. switch)
  378. - Emulating the GNU behavior is prohibitively expensive (lots more code
  379. would be required, lots more memory would be used, etc.)
  380. - The difference is minor or cosmetic
  381. A note on the 'cosmetic' case: output differences might be considered
  382. cosmetic, but if the output is significant enough to break other scripts that
  383. use the output, it should really be fixed.
  384. Scope
  385. ~~~~~
  386. If a const variable is used only in a single source file, put it in the source
  387. file and not in a header file. Likewise, if a const variable is used in only
  388. one function, do not make it global to the file. Instead, declare it inside
  389. the function body. Bottom line: Make a conscious effort to limit declarations
  390. to the smallest scope possible.
  391. Inside applet files, all functions should be declared static so as to keep the
  392. global name space clean. The only exception to this rule is the "applet_main"
  393. function which must be declared extern.
  394. If you write a function that performs a task that could be useful outside the
  395. immediate file, turn it into a general-purpose function with no ties to any
  396. applet and put it in the utility.c file instead.
  397. Brackets Are Your Friends
  398. ~~~~~~~~~~~~~~~~~~~~~~~~~
  399. Please use brackets on all if and else statements, even if it is only one
  400. line. Example:
  401. Don't do this:
  402. if (foo)
  403. stmt1;
  404. stmt2
  405. stmt3;
  406. Do this instead:
  407. if (foo) {
  408. stmt1;
  409. }
  410. stmt2
  411. stmt3;
  412. The "bracketless" approach is error prone because someday you might add a line
  413. like this:
  414. if (foo)
  415. stmt1;
  416. new_line();
  417. stmt2;
  418. stmt3;
  419. And the resulting behavior of your program would totally bewilder you. (Don't
  420. laugh, it happens to us all.) Remember folks, this is C, not Python.
  421. Function Declarations
  422. ~~~~~~~~~~~~~~~~~~~~~
  423. Do not use old-style function declarations that declare variable types between
  424. the parameter list and opening bracket. Example:
  425. Don't do this:
  426. int foo(parm1, parm2)
  427. char parm1;
  428. float parm2;
  429. {
  430. ....
  431. Do this instead:
  432. int foo(char parm1, float parm2)
  433. {
  434. ....
  435. The only time you would ever need to use the old declaration syntax is to
  436. support ancient, antediluvian compilers. To our good fortune, we have access
  437. to more modern compilers and the old declaration syntax is neither necessary
  438. nor desired.
  439. Emphasizing Logical Blocks
  440. ~~~~~~~~~~~~~~~~~~~~~~~~~~
  441. Organization and readability are improved by putting extra newlines around
  442. blocks of code that perform a single task. These are typically blocks that
  443. begin with a C keyword, but not always.
  444. Furthermore, you should put a single comment (not necessarily one line, just
  445. one comment) before the block, rather than commenting each and every line.
  446. There is an optimal amount of commenting that a program can have; you can
  447. comment too much as well as too little.
  448. A picture is really worth a thousand words here, the following example
  449. illustrates how to emphasize logical blocks:
  450. while (line = xmalloc_fgets(fp)) {
  451. /* eat the newline, if any */
  452. chomp(line);
  453. /* ignore blank lines */
  454. if (strlen(file_to_act_on) == 0) {
  455. continue;
  456. }
  457. /* if the search string is in this line, print it,
  458. * unless we were told to be quiet */
  459. if (strstr(line, search) && !be_quiet) {
  460. puts(line);
  461. }
  462. /* clean up */
  463. free(line);
  464. }
  465. Processing Options with getopt
  466. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  467. If your applet needs to process command-line switches, please use getopt32() to
  468. do so. Numerous examples can be seen in many of the existing applets, but
  469. basically it boils down to two things: at the top of the .c file, have this
  470. line in the midst of your #includes, if you need to parse long options:
  471. #include <getopt.h>
  472. Then have long options defined:
  473. static const struct option <applet>_long_options[] = {
  474. { "list", 0, NULL, 't' },
  475. { "extract", 0, NULL, 'x' },
  476. { NULL, 0, NULL, 0 }
  477. };
  478. And a code block similar to the following near the top of your applet_main()
  479. routine:
  480. char *str_b;
  481. opt_complementary = "cryptic_string";
  482. applet_long_options = <applet>_long_options; /* if you have them */
  483. opt = getopt32(argc, argv, "ab:c", &str_b);
  484. if (opt & 1) {
  485. handle_option_a();
  486. }
  487. if (opt & 2) {
  488. handle_option_b(str_b);
  489. }
  490. if (opt & 4) {
  491. handle_option_c();
  492. }
  493. If your applet takes no options (such as 'init'), there should be a line
  494. somewhere in the file reads:
  495. /* no options, no getopt */
  496. That way, when people go grepping to see which applets need to be converted to
  497. use getopt, they won't get false positives.
  498. For more info and examples, examine getopt32.c, tar.c, wget.c etc.