CODING-GUIDELINES 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511
  1. == Asterisk Patch/Coding Guidelines ==
  2. --------------------------------------
  3. We are looking forward to your contributions to Asterisk - the
  4. Open Source PBX! As Asterisk is a large and in some parts very
  5. time-sensitive application, the code base needs to conform to
  6. a common set of coding rules so that many developers can enhance
  7. and maintain the code. Code also needs to be reviewed and tested
  8. so that it works and follows the general architecture and guide-
  9. lines, and is well documented.
  10. Asterisk is published under a dual-licensing scheme by Digium.
  11. To be accepted into the codebase, all non-trivial changes must be
  12. disclaimed to Digium or placed in the public domain. For more information
  13. see http://bugs.digium.com
  14. Patches should be in the form of a unified (-u) diff, made from the directory
  15. above the top-level Asterisk source directory. For example:
  16. - the base code you are working from is in ~/work/asterisk-base
  17. - the changes are in ~/work/asterisk-new
  18. ~/work$ diff -urN asterisk-base asterisk-new
  19. If you are changing within a fresh SVN working copy, you can create
  20. a patch with
  21. $ svn diff <mycodefile>.c
  22. * General rules
  23. ---------------
  24. - All code, filenames, function names and comments must be in ENGLISH.
  25. - Don't annotate your changes with comments like "/* JMG 4/20/04 */";
  26. Comments should explain what the code does, not when something was changed
  27. or who changed it. If you have done a larger contribution, make sure
  28. that you are added to the CREDITS file.
  29. - Don't make unnecessary whitespace changes throughout the code.
  30. If you make changes, submit them to the tracker as separate patches
  31. that only include whitespace and formatting changes.
  32. - Don't use C++ type (//) comments.
  33. - Try to match the existing formatting of the file you are working on.
  34. - Use spaces instead of tabs when aligning in-line comments or #defines (this makes
  35. your comments aligned even if the code is viewed with another tabsize)
  36. * Declaration of functions and variables
  37. ----------------------------------------
  38. - Do not declare variables mid-block (e.g. like recent GNU compilers support)
  39. since it is harder to read and not portable to GCC 2.95 and others.
  40. - Functions and variables that are not intended to be used outside the module
  41. must be declared static.
  42. - When reading integer numeric input with scanf (or variants), do _NOT_ use '%i'
  43. unless you specifically want to allow non-base-10 input; '%d' is always a better
  44. choice, since it will not silently turn numbers with leading zeros into base-8.
  45. - Strings that are coming from input should not be used as a first argument to
  46. a formatted *printf function.
  47. * Use the internal API
  48. ----------------------
  49. - Make sure you are aware of the string and data handling functions that exist
  50. within Asterisk to enhance portability and in some cases to produce more
  51. secure and thread-safe code. Check utils.c/utils.h for these.
  52. * Code formatting
  53. -----------------
  54. Roughly, Asterisk code formatting guidelines are generally equivalent to the
  55. following:
  56. # indent -i4 -ts4 -br -brs -cdw -cli0 -ce -nbfda -npcs -nprs -npsl -saf -sai -saw foo.c
  57. this means in verbose:
  58. -i4: indent level 4
  59. -ts4: tab size 4
  60. -br: braces on if line
  61. -brs: braces on struct decl line
  62. -cdw: cuddle do while
  63. -cli0: case indentation 0
  64. -ce: cuddle else
  65. -nbfda: dont break function decl args
  66. -npcs: no space after function call names
  67. -nprs: no space after parentheses
  68. -npsl: dont break procedure type
  69. -saf: space after for
  70. -sai: space after if
  71. -saw: space after while
  72. Function calls and arguments should be spaced in a consistent way across
  73. the codebase.
  74. GOOD: foo(arg1, arg2);
  75. GOOD: foo(arg1,arg2); /* Acceptable but not preferred */
  76. BAD: foo (arg1, arg2);
  77. BAD: foo( arg1, arg2 );
  78. BAD: foo(arg1, arg2,arg3);
  79. Don't treat keywords (if, while, do, return) as if they were functions;
  80. leave space between the keyword and the expression used (if any). For 'return',
  81. don't even put parentheses around the expression, since they are not
  82. required.
  83. There is no shortage of whitespace characters :-) Use them when they make
  84. the code easier to read. For example:
  85. for (str=foo;str;str=str->next)
  86. is harder to read than
  87. for (str = foo; str; str = str->next)
  88. Following are examples of how code should be formatted.
  89. - Functions:
  90. int foo(int a, char *s)
  91. {
  92. return 0;
  93. }
  94. - If statements:
  95. if (foo) {
  96. bar();
  97. } else {
  98. blah();
  99. }
  100. - Case statements:
  101. switch (foo) {
  102. case BAR:
  103. blah();
  104. break;
  105. case OTHER:
  106. other();
  107. break;
  108. }
  109. - No nested statements without braces, e.g.:
  110. for (x = 0; x < 5; x++)
  111. if (foo)
  112. if (bar)
  113. baz();
  114. instead do:
  115. for (x = 0; x < 5; x++) {
  116. if (foo) {
  117. if (bar)
  118. baz();
  119. }
  120. }
  121. - Don't build code like this:
  122. if (foo) {
  123. /* .... 50 lines of code ... */
  124. } else {
  125. result = 0;
  126. return;
  127. }
  128. Instead, try to minimize the number of lines of code that need to be
  129. indented, by only indenting the shortest case of the 'if'
  130. statement, like so:
  131. if !(foo) {
  132. result = 0;
  133. return;
  134. }
  135. .... 50 lines of code ....
  136. When this technique is used properly, it makes functions much easier to read
  137. and follow, especially those with more than one or two 'setup' operations
  138. that must succeed for the rest of the function to be able to execute.
  139. - Labels/goto are acceptable
  140. Proper use of this technique may occasionally result in the need for a
  141. label/goto combination so that error/failure conditions can exit the
  142. function while still performing proper cleanup. This is not a bad thing!
  143. Use of goto in this situation is encouraged, since it removes the need
  144. for excess code indenting without requiring duplication of cleanup code.
  145. - Never use an uninitialized variable
  146. Make sure you never use an uninitialized variable. The compiler will
  147. usually warn you if you do so. However, do not go too far the other way,
  148. and needlessly initialize variables that do not require it. If the first
  149. time you use a variable in a function is to store a value there, then
  150. initializing it at declaration is pointless, and will generate extra
  151. object code and data in the resulting binary with no purpose. When in doubt,
  152. trust the compiler to tell you when you need to initialize a variable;
  153. if it does not warn you, initialization is not needed.
  154. - Do not cast 'void *'
  155. Do not explicitly cast 'void *' into any other type, nor should you cast any
  156. other type into 'void *'. Implicit casts to/from 'void *' are explicitly
  157. allowed by the C specification. This means the results of malloc(), calloc(),
  158. alloca(), and similar functions do not _ever_ need to be cast to a specific
  159. type, and when you are passing a pointer to (for example) a callback function
  160. that accepts a 'void *' you do not need to cast into that type.
  161. * Variable naming
  162. -----------------
  163. - Global variables
  164. Name global variables (or local variables when you have a lot of them or
  165. are in a long function) something that will make sense to aliens who
  166. find your code in 100 years. All variable names should be in lower
  167. case, except when following external APIs or specifications that normally
  168. use upper- or mixed-case variable names; in that situation, it is
  169. preferable to follow the external API/specification for ease of
  170. understanding.
  171. Make some indication in the name of global variables which represent
  172. options that they are in fact intended to be global.
  173. e.g.: static char global_something[80]
  174. - Don't use un-necessary typedef's
  175. Don't use 'typedef' just to shorten the amount of typing; there is no substantial
  176. benefit in this:
  177. struct foo {
  178. int bar;
  179. };
  180. typedef foo_t struct foo;
  181. In fact, don't use 'variable type' suffixes at all; it's much preferable to
  182. just type 'struct foo' rather than 'foo_s'.
  183. - Use enums instead of #define where possible
  184. Use enums rather than long lists of #define-d numeric constants when possible;
  185. this allows structure members, local variables and function arguments to
  186. be declared as using the enum's type. For example:
  187. enum option {
  188. OPT_FOO = 1
  189. OPT_BAR = 2
  190. OPT_BAZ = 4
  191. };
  192. static enum option global_option;
  193. static handle_option(const enum option opt)
  194. {
  195. ...
  196. }
  197. Note: The compiler will _not_ force you to pass an entry from the enum
  198. as an argument to this function; this recommendation serves only to make
  199. the code clearer and somewhat self-documenting. In addition, when using
  200. switch/case blocks that switch on enum values, the compiler will warn
  201. you if you forget to handle one or more of the enum values, which can be
  202. handy.
  203. * String handling
  204. -----------------
  205. Don't use strncpy for copying whole strings; it does not guarantee that the
  206. output buffer will be null-terminated. Use ast_copy_string instead, which
  207. is also slightly more efficient (and allows passing the actual buffer
  208. size, which makes the code clearer).
  209. Don't use ast_copy_string (or any length-limited copy function) for copying
  210. fixed (known at compile time) strings into buffers, if the buffer is something
  211. that has been allocated in the function doing the copying. In that case, you
  212. know at the time you are writing the code whether the buffer is large enough
  213. for the fixed string or not, and if it's not, your code won't work anyway!
  214. Use strcpy() for this operation, or directly set the first two characters
  215. of the buffer if you are just trying to store a one-character string in the
  216. buffer. If you are trying to 'empty' the buffer, just store a single
  217. NULL character ('\0') in the first byte of the buffer; nothing else is
  218. needed, and any other method is wasteful.
  219. In addition, if the previous operations in the function have already
  220. determined that the buffer in use is adequately sized to hold the string
  221. you wish to put into it (even if you did not allocate the buffer yourself),
  222. use a direct strcpy(), as it can be inlined and optimized to simple
  223. processor operations, unlike ast_copy_string().
  224. * Use of functions
  225. ------------------
  226. When making applications, always ast_strdupa(data) to a local pointer if
  227. you intend to parse the incoming data string.
  228. if (data)
  229. mydata = ast_strdupa(data);
  230. - Separating arguments to dialplan applications and functions
  231. Use ast_app_separate_args() to separate the arguments to your application
  232. once you have made a local copy of the string.
  233. - Parsing strings with strsep
  234. Use strsep() for parsing strings when possible; there is no worry about
  235. 're-entrancy' as with strtok(), and even though it modifies the original
  236. string (which the man page warns about), in many cases that is exactly
  237. what you want!
  238. - Create generic code!
  239. If you do the same or a similar operation more than one time, make it a
  240. function or macro.
  241. Make sure you are not duplicating any functionality already found in an
  242. API call somewhere. If you are duplicating functionality found in
  243. another static function, consider the value of creating a new API call
  244. which can be shared.
  245. * Handling of pointers and allocations
  246. --------------------------------------
  247. - Dereference or localize pointers
  248. Always dereference or localize pointers to things that are not yours like
  249. channel members in a channel that is not associated with the current
  250. thread and for which you do not have a lock.
  251. channame = ast_strdupa(otherchan->name);
  252. - Use const on pointer arguments if possible
  253. Use const on pointer arguments which your function will not be modifying, as this
  254. allows the compiler to make certain optimizations. In general, use 'const'
  255. on any argument that you have no direct intention of modifying, as it can
  256. catch logic/typing errors in your code when you use the argument variable
  257. in a way that you did not intend.
  258. - Do not create your own linked list code - reuse!
  259. As a common example of this point, make an effort to use the lockable
  260. linked-list macros found in include/asterisk/linkedlists.h. They are
  261. efficient, easy to use and provide every operation that should be
  262. necessary for managing a singly-linked list (if something is missing,
  263. let us know!). Just because you see other open-coded list implementations
  264. in the source tree is no reason to continue making new copies of
  265. that code... There are also a number of common string manipulation
  266. and timeval manipulation functions in asterisk/strings.h and asterisk/time.h;
  267. use them when possible.
  268. - Avoid needless allocations!
  269. Avoid needless malloc(), strdup() calls. If you only need the value in
  270. the scope of your function try ast_strdupa() or declare structs on the
  271. stack and pass a pointer to them. However, be careful to _never_ call
  272. alloca(), ast_strdupa() or similar functions in the argument list
  273. of a function you are calling; this can cause very strange stack
  274. arrangements and produce unexpected behavior.
  275. -Allocations for structures
  276. When allocating/zeroing memory for a structure, try to use code like this:
  277. struct foo *tmp;
  278. ...
  279. tmp = malloc(sizeof(*tmp));
  280. if (tmp)
  281. memset(tmp, 0, sizeof(*tmp));
  282. This eliminates duplication of the 'struct foo' identifier, which makes the
  283. code easier to read and also ensures that if it is copy-and-pasted it won't
  284. require as much editing. In fact, you can even use:
  285. struct foo *tmp;
  286. ...
  287. tmp = calloc(1, sizeof(*tmp));
  288. This will allocate and zero the memory in a single operation.
  289. * CLI Commands
  290. --------------
  291. New CLI commands should be named using the module's name, followed by a verb
  292. and then any parameters that the command needs. For example:
  293. *CLI> iax2 show peer <peername>
  294. not
  295. *CLI> show iax2 peer <peername>
  296. * New dialplan applications/functions
  297. -------------------------------------
  298. There are two methods of adding functionality to the Asterisk
  299. dialplan: applications and functions. Applications (found generally in
  300. the apps/ directory) should be collections of code that interact with
  301. a channel and/or user in some significant way. Functions (which can be
  302. provided by any type of module) are used when the provided
  303. functionality is simple... getting/retrieving a value, for
  304. example. Functions should also be used when the operation is in no way
  305. related to a channel (a computation or string operation, for example).
  306. Applications are registered and invoked using the
  307. ast_register_application function; see the apps/app_skel.c file for an
  308. example.
  309. Functions are registered using 'struct ast_custom_function'
  310. structures and the ast_custom_function_register function.
  311. * Doxygen API Documentation Guidelines
  312. --------------------------------------
  313. When writing Asterisk API documentation the following format should be
  314. followed. Do not use the javadoc style.
  315. /*!
  316. * \brief Do interesting stuff.
  317. * \param thing1 interesting parameter 1.
  318. * \param thing2 interesting parameter 2.
  319. *
  320. * This function does some interesting stuff.
  321. *
  322. * \return zero on success, -1 on error.
  323. */
  324. int ast_interesting_stuff(int thing1, int thing2)
  325. {
  326. return 0;
  327. }
  328. Notice the use of the \param, \brief, and \return constructs. These should be
  329. used to describe the corresponding pieces of the function being documented.
  330. Also notice the blank line after the last \param directive. All doxygen
  331. comments must be in one /*! */ block. If the function or struct does not need
  332. an extended description it can be left out.
  333. Please make sure to review the doxygen manual and make liberal use of the \a,
  334. \code, \c, \b, \note, \li and \e modifiers as appropriate.
  335. When documenting a 'static' function or an internal structure in a module,
  336. use the \internal modifier to ensure that the resulting documentation
  337. explicitly says 'for internal use only'.
  338. Structures should be documented as follows.
  339. /*!
  340. * \brief A very interesting structure.
  341. */
  342. struct interesting_struct
  343. {
  344. /*! \brief A data member. */
  345. int member1;
  346. int member2; /*!< \brief Another data member. */
  347. }
  348. Note that /*! */ blocks document the construct immediately following them
  349. unless they are written, /*!< */, in which case they document the construct
  350. preceding them.
  351. * Finishing up before you submit your code
  352. ------------------------------------------
  353. - Look at the code once more
  354. When you achieve your desired functionalty, make another few refactor
  355. passes over the code to optimize it.
  356. - Read the patch
  357. Before submitting a patch, *read* the actual patch file to be sure that
  358. all the changes you expect to be there are, and that there are no
  359. surprising changes you did not expect. During your development, that
  360. part of Asterisk may have changed, so make sure you compare with the
  361. latest SVN.
  362. - Listen to advice
  363. If you are asked to make changes to your patch, there is a good chance
  364. the changes will introduce bugs, check it even more at this stage.
  365. Also remember that the bug marshal or co-developer that adds comments
  366. is only human, they may be in error :-)
  367. - Optimize, optimize, optimize
  368. If you are going to reuse a computed value, save it in a variable
  369. instead of recomputing it over and over. This can prevent you from
  370. making a mistake in subsequent computations, making it easier to correct
  371. if the formula has an error and may or may not help optimization but
  372. will at least help readability.
  373. Just an example (so don't over analyze it, that'd be a shame):
  374. const char *prefix = "pre";
  375. const char *postfix = "post";
  376. char *newname;
  377. char *name = "data";
  378. if (name && (newname = alloca(strlen(name) + strlen(prefix) + strlen(postfix) + 3)))
  379. snprintf(newname, strlen(name) + strlen(prefix) + strlen(postfix) + 3, "%s/%s/%s", prefix, name, postfix);
  380. ...vs this alternative:
  381. const char *prefix = "pre";
  382. const char *postfix = "post";
  383. char *newname;
  384. char *name = "data";
  385. int len = 0;
  386. if (name && (len = strlen(name) + strlen(prefix) + strlen(postfix) + 3) && (newname = alloca(len)))
  387. snprintf(newname, len, "%s/%s/%s", prefix, name, postfix);
  388. -----------------------------------------------
  389. Welcome to the Asterisk development community!
  390. Meet you on the asterisk-dev mailing list.
  391. Subscribe at http://lists.digium.com!
  392. Mark Spencer, Kevin P. Fleming and
  393. the Asterisk.org Development Team