style-guide.txt 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680
  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 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. Spacing around Parentheses
  87. ~~~~~~~~~~~~~~~~~~~~~~~~~~
  88. Put a space between C keywords and left parens, but not between function names
  89. and the left paren that starts it's parameter list (whether it is being
  90. declared or called). Examples:
  91. Don't do this:
  92. while(foo) {
  93. for(i = 0; i < n; i++) {
  94. Do this instead:
  95. while (foo) {
  96. for (i = 0; i < n; i++) {
  97. But do functions like this:
  98. static int my_func(int foo, char bar)
  99. ...
  100. baz = my_func(1, 2);
  101. Also, don't put a space between the left paren and the first term, nor between
  102. the last arg and the right paren.
  103. Don't do this:
  104. if ( x < 1 )
  105. strcmp( thisstr, thatstr )
  106. Do this instead:
  107. if (x < 1)
  108. strcmp(thisstr, thatstr)
  109. Cuddled Elses
  110. ~~~~~~~~~~~~~
  111. Also, please "cuddle" your else statements by putting the else keyword on the
  112. same line after the right bracket that closes an 'if' statement.
  113. Don't do this:
  114. if (foo) {
  115. stmt;
  116. }
  117. else {
  118. stmt;
  119. }
  120. Do this instead:
  121. if (foo) {
  122. stmt;
  123. } else {
  124. stmt;
  125. }
  126. The exception to this rule is if you want to include a comment before the else
  127. block. Example:
  128. if (foo) {
  129. stmts...
  130. }
  131. /* otherwise, we're just kidding ourselves, so re-frob the input */
  132. else {
  133. other_stmts...
  134. }
  135. Variable and Function Names
  136. ---------------------------
  137. Use the K&R style with names in all lower-case and underscores occasionally
  138. used to separate words (e.g., "variable_name" and "numchars" are both
  139. acceptable). Using underscores makes variable and function names more readable
  140. because it looks like whitespace; using lower-case is easy on the eyes.
  141. Frowned upon:
  142. hitList
  143. TotalChars
  144. szFileName
  145. pf_Nfol_TriState
  146. Preferred:
  147. hit_list
  148. total_chars
  149. file_name
  150. sensible_name
  151. Exceptions:
  152. - Enums, macros, and constant variables are occasionally written in all
  153. upper-case with words optionally seperatedy by underscores (i.e. FIFOTYPE,
  154. ISBLKDEV()).
  155. - Nobody is going to get mad at you for using 'pvar' as the name of a
  156. variable that is a pointer to 'var'.
  157. Converting to K&R
  158. ~~~~~~~~~~~~~~~~~
  159. The Busybox codebase is very much a mixture of code gathered from a variety of
  160. sources. This explains why the current codebase contains such a hodge-podge of
  161. different naming styles (Java, Pascal, K&R, just-plain-weird, etc.). The K&R
  162. guideline explained above should therefore be used on new files that are added
  163. to the repository. Furthermore, the maintainer of an existing file that uses
  164. alternate naming conventions should, at his own convenience, convert those
  165. names over to K&R style. Converting variable names is a very low priority
  166. task.
  167. If you want to do a search-and-replace of a single variable name in different
  168. files, you can do the following in the busybox directory:
  169. $ perl -pi -e 's/\bOldVar\b/new_var/g' *.[ch]
  170. If you want to convert all the non-K&R vars in your file all at once, follow
  171. these steps:
  172. - In the busybox directory type 'examples/mk2knr.pl files-to-convert'. This
  173. does not do the actual conversion, rather, it generates a script called
  174. 'convertme.pl' that shows what will be converted, giving you a chance to
  175. review the changes beforehand.
  176. - Review the 'convertme.pl' script that gets generated in the busybox
  177. directory and remove / edit any of the substitutions in there. Please
  178. especially check for false positives (strings that should not be
  179. converted).
  180. - Type './convertme.pl same-files-as-before' to perform the actual
  181. conversion.
  182. - Compile and see if everything still works.
  183. Please be aware of changes that have cascading effects into other files. For
  184. example, if you're changing the name of something in, say utility.c, you
  185. should probably run 'examples/mk2knr.pl utility.c' at first, but when you run
  186. the 'convertme.pl' script you should run it on _all_ files like so:
  187. './convertme.pl *.[ch]'.
  188. Avoid The Preprocessor
  189. ----------------------
  190. At best, the preprocessor is a necessary evil, helping us account for platform
  191. and architecture differences. Using the preprocessor unnecessarily is just
  192. plain evil.
  193. The Folly of #define
  194. ~~~~~~~~~~~~~~~~~~~~
  195. Use 'const <type> var' for declaring constants.
  196. Don't do this:
  197. #define var 80
  198. Do this instead, when the variable is in a header file and will be used in
  199. several source files:
  200. const int var = 80;
  201. Or do this when the variable is used only in a single source file:
  202. static const int var = 80;
  203. Declaring variables as '[static] const' gives variables an actual type and
  204. makes the compiler do type checking for you; the preprocessor does _no_ type
  205. checking whatsoever, making it much more error prone. Declaring variables with
  206. '[static] const' also makes debugging programs much easier since the value of
  207. the variable can be easily queried and displayed.
  208. The Folly of Macros
  209. ~~~~~~~~~~~~~~~~~~~
  210. Use 'static inline' instead of a macro.
  211. Don't do this:
  212. #define mini_func(param1, param2) (param1 << param2)
  213. Do this instead:
  214. static inline int mini_func(int param1, param2)
  215. {
  216. return (param1 << param2);
  217. }
  218. Static inline functions are greatly preferred over macros. They provide type
  219. safety, have no length limitations, no formatting limitations, have an actual
  220. return value, and under gcc they are as cheap as macros. Besides, really long
  221. macros with backslashes at the end of each line are ugly as sin.
  222. The Folly of #ifdef
  223. ~~~~~~~~~~~~~~~~~~~
  224. Code cluttered with ifdefs is difficult to read and maintain. Don't do it.
  225. Instead, put your ifdefs at the top of your .c file (or in a header), and
  226. conditionally define 'static inline' functions, (or *maybe* macros), which are
  227. used in the code.
  228. Don't do this:
  229. ret = my_func(bar, baz);
  230. if (!ret)
  231. return -1;
  232. #ifdef CONFIG_FEATURE_FUNKY
  233. maybe_do_funky_stuff(bar, baz);
  234. #endif
  235. Do this instead:
  236. (in .h header file)
  237. #ifdef CONFIG_FEATURE_FUNKY
  238. static inline void maybe_do_funky_stuff (int bar, int baz)
  239. {
  240. /* lotsa code in here */
  241. }
  242. #else
  243. static inline void maybe_do_funky_stuff (int bar, int baz) {}
  244. #endif
  245. (in the .c source file)
  246. ret = my_func(bar, baz);
  247. if (!ret)
  248. return -1;
  249. maybe_do_funky_stuff(bar, baz);
  250. The great thing about this approach is that the compiler will optimize away
  251. the "no-op" case (the empty function) when the feature is turned off.
  252. Note also the use of the word 'maybe' in the function name to indicate
  253. conditional execution.
  254. Notes on Strings
  255. ----------------
  256. Strings in C can get a little thorny. Here's some guidelines for dealing with
  257. strings in Busybox. (There is surely more that could be added to this
  258. section.)
  259. String Files
  260. ~~~~~~~~~~~~
  261. Put all help/usage messages in usage.c. Put other strings in messages.c.
  262. Putting these strings into their own file is a calculated decision designed to
  263. confine spelling errors to a single place and aid internationalization
  264. efforts, if needed. (Side Note: we might want to use a single file - maybe
  265. called 'strings.c' - instead of two, food for thought).
  266. Testing String Equivalence
  267. ~~~~~~~~~~~~~~~~~~~~~~~~~~
  268. There's a right way and a wrong way to test for sting equivalence with
  269. strcmp():
  270. The wrong way:
  271. if (!strcmp(string, "foo")) {
  272. ...
  273. The right way:
  274. if (strcmp(string, "foo") == 0){
  275. ...
  276. The use of the "equals" (==) operator in the latter example makes it much more
  277. obvious that you are testing for equivalence. The former example with the
  278. "not" (!) operator makes it look like you are testing for an error. In a more
  279. perfect world, we would have a streq() function in the string library, but
  280. that ain't the world we're living in.
  281. Avoid Dangerous String Functions
  282. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  283. Unfortunately, the way C handles strings makes them prone to overruns when
  284. certain library functions are (mis)used. The following table offers a summary
  285. of some of the more notorious troublemakers:
  286. function overflows preferred
  287. ----------------------------------------
  288. strcpy dest string strncpy
  289. strcat dest string strncat
  290. gets string it gets fgets
  291. getwd buf string getcwd
  292. [v]sprintf str buffer [v]snprintf
  293. realpath path buffer use with pathconf
  294. [vf]scanf its arguments just avoid it
  295. The above is by no means a complete list. Be careful out there.
  296. Avoid Big Static Buffers
  297. ------------------------
  298. First, some background to put this discussion in context: Static buffers look
  299. like this in code:
  300. /* in a .c file outside any functions */
  301. static char *buffer[BUFSIZ]; /* happily used by any function in this file,
  302. but ick! big! */
  303. The problem with these is that any time any busybox app is run, you pay a
  304. memory penalty for this buffer, even if the applet that uses said buffer is
  305. not run. This can be fixed, thusly:
  306. static char *buffer;
  307. ...
  308. other_func()
  309. {
  310. strcpy(buffer, lotsa_chars); /* happily uses global *buffer */
  311. ...
  312. foo_main()
  313. {
  314. buffer = xmalloc(sizeof(char)*BUFSIZ);
  315. ...
  316. However, this approach trades bss segment for text segment. Rather than
  317. mallocing the buffers (and thus growing the text size), buffers can be
  318. declared on the stack in the *_main() function and made available globally by
  319. assigning them to a global pointer thusly:
  320. static char *pbuffer;
  321. ...
  322. other_func()
  323. {
  324. strcpy(pbuffer, lotsa_chars); /* happily uses global *pbuffer */
  325. ...
  326. foo_main()
  327. {
  328. char *buffer[BUFSIZ]; /* declared locally, on stack */
  329. pbuffer = buffer; /* but available globally */
  330. ...
  331. This last approach has some advantages (low code size, space not used until
  332. it's needed), but can be a problem in some low resource machines that have
  333. very limited stack space (e.g., uCLinux).
  334. A macro is declared in busybox.h that implements compile-time selection
  335. between xmalloc() and stack creation, so you can code the line in question as
  336. RESERVE_CONFIG_BUFFER(buffer, BUFSIZ);
  337. and the right thing will happen, based on your configuration.
  338. Miscellaneous Coding Guidelines
  339. -------------------------------
  340. The following are important items that don't fit into any of the above
  341. sections.
  342. Model Busybox Applets After GNU Counterparts
  343. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  344. When in doubt about the proper behavior of a Busybox program (output,
  345. formatting, options, etc.), model it after the equivalent GNU program.
  346. Doesn't matter how that program behaves on some other flavor of *NIX; doesn't
  347. matter what the POSIX standard says or doesn't say, just model Busybox
  348. programs after their GNU counterparts and it will make life easier on (nearly)
  349. everyone.
  350. The only time we deviate from emulating the GNU behavior is when:
  351. - We are deliberately not supporting a feature (such as a command line
  352. switch)
  353. - Emulating the GNU behavior is prohibitively expensive (lots more code
  354. would be required, lots more memory would be used, etc.)
  355. - The difference is minor or cosmetic
  356. A note on the 'cosmetic' case: Output differences might be considered
  357. cosmetic, but if the output is significant enough to break other scripts that
  358. use the output, it should really be fixed.
  359. Scope
  360. ~~~~~
  361. If a const variable is used only in a single source file, put it in the source
  362. file and not in a header file. Likewise, if a const variable is used in only
  363. one function, do not make it global to the file. Instead, declare it inside
  364. the function body. Bottom line: Make a conscious effort to limit declarations
  365. to the smallest scope possible.
  366. Inside applet files, all functions should be declared static so as to keep the
  367. global name space clean. The only exception to this rule is the "applet_main"
  368. function which must be declared extern.
  369. If you write a function that performs a task that could be useful outside the
  370. immediate file, turn it into a general-purpose function with no ties to any
  371. applet and put it in the utility.c file instead.
  372. Brackets Are Your Friends
  373. ~~~~~~~~~~~~~~~~~~~~~~~~~
  374. Please use brackets on all if and else statements, even if it is only one
  375. line. Example:
  376. Don't do this:
  377. if (foo)
  378. stmt1;
  379. stmt2
  380. stmt3;
  381. Do this instead:
  382. if (foo) {
  383. stmt1;
  384. }
  385. stmt2
  386. stmt3;
  387. The "bracketless" approach is error prone because someday you might add a line
  388. like this:
  389. if (foo)
  390. stmt1;
  391. new_line();
  392. stmt2
  393. stmt3;
  394. And the resulting behavior of your program would totally bewilder you. (Don't
  395. laugh, it happens to us all.) Remember folks, this is C, not Python.
  396. Function Declarations
  397. ~~~~~~~~~~~~~~~~~~~~~
  398. Do not use old-style function declarations that declare variable types between
  399. the parameter list and opening bracket. Example:
  400. Don't do this:
  401. int foo(parm1, parm2)
  402. char parm1;
  403. float parm2;
  404. {
  405. ....
  406. Do this instead:
  407. int foo(char parm1, float parm2)
  408. {
  409. ....
  410. The only time you would ever need to use the old declaration syntax is to
  411. support ancient, antediluvian compilers. To our good fortune, we have access
  412. to more modern compilers and the old declaration syntax is neither necessary
  413. nor desired.
  414. Emphasizing Logical Blocks
  415. ~~~~~~~~~~~~~~~~~~~~~~~~~~
  416. Organization and readability are improved by putting extra newlines around
  417. blocks of code that perform a single task. These are typically blocks that
  418. begin with a C keyword, but not always.
  419. Furthermore, you should put a single comment (not necessarily one line, just
  420. one comment) before the block, rather than commenting each and every line.
  421. There is an optimal ammount of commenting that a program can have; you can
  422. comment too much as well as too little.
  423. A picture is really worth a thousand words here, the following example
  424. illustrates how to emphasize logical blocks:
  425. while (line = get_line_from_file(fp)) {
  426. /* eat the newline, if any */
  427. chomp(line);
  428. /* ignore blank lines */
  429. if (strlen(file_to_act_on) == 0) {
  430. continue;
  431. }
  432. /* if the search string is in this line, print it,
  433. * unless we were told to be quiet */
  434. if (strstr(line, search) && !be_quiet) {
  435. puts(line);
  436. }
  437. /* clean up */
  438. free(line);
  439. }
  440. Processing Options with getopt
  441. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  442. If your applet needs to process command-line switches, please use getopt() to
  443. do so. Numerous examples can be seen in many of the existing applets, but
  444. basically it boils down to two things: at the top of the .c file, have this
  445. line in the midst of your #includes:
  446. #include <getopt.h>
  447. And a code block similar to the following near the top of your applet_main()
  448. routine:
  449. while ((opt = getopt(argc, argv, "abc")) > 0) {
  450. switch (opt) {
  451. case 'a':
  452. do_a_opt = 1;
  453. break;
  454. case 'b':
  455. do_b_opt = 1;
  456. break;
  457. case 'c':
  458. do_c_opt = 1;
  459. break;
  460. default:
  461. show_usage(); /* in utility.c */
  462. }
  463. }
  464. If your applet takes no options (such as 'init'), there should be a line
  465. somewhere in the file reads:
  466. /* no options, no getopt */
  467. That way, when people go grepping to see which applets need to be converted to
  468. use getopt, they won't get false positives.
  469. Additional Note: Do not use the getopt_long library function and do not try to
  470. hand-roll your own long option parsing. Busybox applets should only support
  471. short options. Explanations and examples of the short options should be
  472. documented in usage.h.