1 --------------------------------------
2 == Asterisk Coding Guidelines ==
3 --------------------------------------
5 This document gives some basic indication on how the asterisk code
6 is structured. The first part covers the structure and style of
7 individual files. The second part (TO BE COMPLETED) covers the
8 overall code structure and the build architecture.
10 Please read it to the end to understand in detail how the asterisk
11 code is organized, and to know how to extend asterisk or contribute
14 We are looking forward to your contributions to Asterisk - the
15 Open Source PBX! As Asterisk is a large and in some parts very
16 time-sensitive application, the code base needs to conform to
17 a common set of coding rules so that many developers can enhance
18 and maintain the code. Code also needs to be reviewed and tested
19 so that it works and follows the general architecture and guide-
20 lines, and is well documented.
22 Asterisk is published under a dual-licensing scheme by Digium.
23 To be accepted into the codebase, all non-trivial changes must be
24 licensed to Digium. For more information, see the electronic license
25 agreement on https://issues.asterisk.org/.
27 Patches should be in the form of a unified (-u) diff, made from a checkout
30 /usr/src/asterisk$ svn diff > mypatch
32 If you would like to only include changes to certain files in the patch, you
33 can list them in the "svn diff" command:
35 /usr/src/asterisk$ svn diff somefile.c someotherfile.c > mypatch
37 -----------------------------------
38 == PART ONE: CODING GUIDELINES ==
39 -----------------------------------
44 - Indent code using tabs, not spaces.
46 - All code, filenames, function names and comments must be in ENGLISH.
48 - Don't annotate your changes with comments like "/* JMG 4/20/04 */";
49 Comments should explain what the code does, not when something was changed
50 or who changed it. If you have done a larger contribution, make sure
51 that you are added to the CREDITS file.
53 - Don't make unnecessary whitespace changes throughout the code.
54 If you make changes, submit them to the tracker as separate patches
55 that only include whitespace and formatting changes.
57 - Don't use C++ type (//) comments.
59 - Try to match the existing formatting of the file you are working on.
61 - Use spaces instead of tabs when aligning in-line comments or #defines (this makes
62 your comments aligned even if the code is viewed with another tabsize)
64 * File structure and header inclusion
65 -------------------------------------
67 Every C source file should start with a proper copyright
68 and a brief description of the content of the file.
69 Following that, you should immediately put the following lines:
72 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
74 "asterisk.h" resolves OS and compiler dependencies for the basic
75 set of unix functions (data types, system calls, basic I/O
76 libraries) and the basic Asterisk APIs.
77 ASTERISK_FILE_VERSION() stores in the executable information
80 Next, you should #include extra headers according to the functionality
81 that your file uses or implements. For each group of functions that
82 you use there is a common header, which covers OS header dependencies
83 and defines the 'external' API of those functions (the equivalent
84 of 'public' members of a class). As an example:
87 if you are implementing a module, this should be included in one
88 of the files that are linked with the module.
91 access to extra file I/O functions (stat, fstat, playing with
95 basic network I/O - all of the socket library, select/poll,
96 and asterisk-specific (usually either thread-safe or reentrant
97 or both) functions to play with socket addresses.
100 parsing of application arguments
103 struct ast_channel and functions to manipulate it
105 For more information look at the headers in include/asterisk/ .
106 These files are usually self-sufficient, i.e. they recursively #include
107 all the extra headers they need.
109 The equivalent of 'private' members of a class are either directly in
110 the C source file, or in files named asterisk/mod_*.h to make it clear
111 that they are not for inclusion by generic code.
113 Keep the number of header files small by not including them unnecessarily.
114 Don't cut&paste list of header files from other sources, but only include
115 those you really need. Apart from obvious cases (e.g. module.h which
116 is almost always necessary) write a short comment next to each #include to
117 explain why you need it.
119 * Declaration of functions and variables
120 ----------------------------------------
122 - Do not declare variables mid-block (e.g. like recent GNU compilers support)
123 since it is harder to read and not portable to GCC 2.95 and others.
125 - Functions and variables that are not intended to be used outside the module
126 must be declared static. If you are compiling on a Linux platform that has the
127 'dwarves' package available, you can use the 'pglobal' tool from that package
128 to check for unintended global variables or functions being exposed in your
129 object files. Usage is very simple:
131 $ pglobal -vf <path to .o file>
133 - When reading integer numeric input with scanf (or variants), do _NOT_ use '%i'
134 unless you specifically want to allow non-base-10 input; '%d' is always a better
135 choice, since it will not silently turn numbers with leading zeros into base-8.
137 - Strings that are coming from input should not be used as the format argument to
138 any printf-style function.
140 * Structure alignment and padding
141 ---------------------------------
143 On many platforms, structure fields (in structures that are not marked 'packed')
144 will be laid out by the compiler with gaps (padding) between them, in order to
145 satisfy alignment requirements. As a simple example:
152 On nearly every 64-bit platform, this will result in 4 bytes of dead space between
153 'bar' and 'xyz', because pointers on 64-bit platforms must be aligned on 8-byte
154 boundaries. Once you have your code written and tested, it may be worthwhile to review
155 your structure definitions to look for problems of this nature. If you are on a Linux
156 platform with the 'dwarves' package available, the 'pahole' tool from that package
157 can be used to both check for padding issues of this type and also propose reorganized
158 structure definitions to eliminate it. Usage is quite simple; for a structure named 'foo',
159 the command would look something like this:
161 $ pahole --reorganize --show_reorg_steps -C foo <path to module>
163 The 'pahole' tool has many other modes available, including some that will list all the
164 structures declared in the module and the amount of padding in each one that could possibly
167 * Use the internal API
168 ----------------------
170 - Make sure you are aware of the string and data handling functions that exist
171 within Asterisk to enhance portability and in some cases to produce more
172 secure and thread-safe code. Check utils.c/utils.h for these.
174 - If you need to create a detached thread, use the ast_pthread_create_detached()
175 normally or ast_pthread_create_detached_background() for a thread with a smaller
176 stack size. This reduces the replication of the code to handle the pthread_attr_t
182 Roughly, Asterisk code formatting guidelines are generally equivalent to the
185 # indent -i4 -ts4 -br -brs -cdw -lp -ce -nbfda -npcs -nprs -npsl -nbbo -saf -sai -saw -cs -l90 foo.c
187 this means in verbose:
190 -br: braces on if line
191 -brs: braces on struct decl line
192 -cdw: cuddle do while
193 -lp: line up continuation below parenthesis
195 -nbfda: dont break function decl args
196 -npcs: no space after function call names
197 -nprs: no space after parentheses
198 -npsl: dont break procedure type
199 -saf: space after for
201 -saw: space after while
202 -cs: space after cast
203 -l90: line length 90 columns
205 Function calls and arguments should be spaced in a consistent way across
207 GOOD: foo(arg1, arg2);
209 BAD: foo (arg1, arg2);
210 BAD: foo( arg1, arg2 );
211 BAD: foo(arg1, arg2,arg3);
213 Don't treat keywords (if, while, do, return) as if they were functions;
214 leave space between the keyword and the expression used (if any). For 'return',
215 don't even put parentheses around the expression, since they are not
218 There is no shortage of whitespace characters :-) Use them when they make
219 the code easier to read. For example:
221 for (str=foo;str;str=str->next)
223 is harder to read than
225 for (str = foo; str; str = str->next)
227 Following are examples of how code should be formatted.
230 int foo(int a, char *s)
252 - No nested statements without braces, e.g.:
254 for (x = 0; x < 5; x++)
260 for (x = 0; x < 5; x++) {
268 - Always use braces around the statements following an if/for/while construct,
269 even if not strictly necessary, as it reduces future possible problems.
271 - Don't build code like this:
274 /* .... 50 lines of code ... */
280 Instead, try to minimize the number of lines of code that need to be
281 indented, by only indenting the shortest case of the 'if'
289 .... 50 lines of code ....
291 When this technique is used properly, it makes functions much easier to read
292 and follow, especially those with more than one or two 'setup' operations
293 that must succeed for the rest of the function to be able to execute.
295 - Labels/goto are acceptable
296 Proper use of this technique may occasionally result in the need for a
297 label/goto combination so that error/failure conditions can exit the
298 function while still performing proper cleanup. This is not a bad thing!
299 Use of goto in this situation is encouraged, since it removes the need
300 for excess code indenting without requiring duplication of cleanup code.
302 - Never use an uninitialized variable
303 Make sure you never use an uninitialized variable. The compiler will
304 usually warn you if you do so. However, do not go too far the other way,
305 and needlessly initialize variables that do not require it. If the first
306 time you use a variable in a function is to store a value there, then
307 initializing it at declaration is pointless, and will generate extra
308 object code and data in the resulting binary with no purpose. When in doubt,
309 trust the compiler to tell you when you need to initialize a variable;
310 if it does not warn you, initialization is not needed.
312 - Do not cast 'void *'
313 Do not explicitly cast 'void *' into any other type, nor should you cast any
314 other type into 'void *'. Implicit casts to/from 'void *' are explicitly
315 allowed by the C specification. This means the results of malloc(), calloc(),
316 alloca(), and similar functions do not _ever_ need to be cast to a specific
317 type, and when you are passing a pointer to (for example) a callback function
318 that accepts a 'void *' you do not need to cast into that type.
323 All public functions (those not marked 'static'), must be named "ast_<something>"
324 and have a descriptive name.
326 As an example, suppose you wanted to take a local function "find_feature", defined
327 as static in a file, and used only in that file, and make it public, and use it
328 in other files. You will have to remove the "static" declaration and define a
329 prototype in an appropriate header file (usually in include/asterisk). A more
330 specific name should be given, such as "ast_find_call_feature".
332 * Variable function argument parsing
333 ------------------------------------
335 Functions with a variable amount of arguments need a 'sentinel' when called.
336 Newer GNU C compilers are fine if you use NULL for this. Older versions (pre 4)
338 You should use the constant SENTINEL.
339 This one is defined in include/asterisk/compiler.h
345 Name global variables (or local variables when you have a lot of them or
346 are in a long function) something that will make sense to aliens who
347 find your code in 100 years. All variable names should be in lower
348 case, except when following external APIs or specifications that normally
349 use upper- or mixed-case variable names; in that situation, it is
350 preferable to follow the external API/specification for ease of
353 Make some indication in the name of global variables which represent
354 options that they are in fact intended to be global.
355 e.g.: static char global_something[80]
357 - Don't use unnecessary typedef's
358 Don't use 'typedef' just to shorten the amount of typing; there is no substantial
360 struct foo { int bar; }; typedef struct foo foo_t;
362 In fact, don't use 'variable type' suffixes at all; it's much preferable to
363 just type 'struct foo' rather than 'foo_s'.
365 - Use enums instead of #define where possible
366 Use enums rather than long lists of #define-d numeric constants when possible;
367 this allows structure members, local variables and function arguments to
368 be declared as using the enum's type. For example:
376 static enum option global_option;
378 static handle_option(const enum option opt)
383 Note: The compiler will _not_ force you to pass an entry from the enum
384 as an argument to this function; this recommendation serves only to make
385 the code clearer and somewhat self-documenting. In addition, when using
386 switch/case blocks that switch on enum values, the compiler will warn
387 you if you forget to handle one or more of the enum values, which can be
393 Don't use strncpy for copying whole strings; it does not guarantee that the
394 output buffer will be null-terminated. Use ast_copy_string instead, which
395 is also slightly more efficient (and allows passing the actual buffer
396 size, which makes the code clearer).
398 Don't use ast_copy_string (or any length-limited copy function) for copying
399 fixed (known at compile time) strings into buffers, if the buffer is something
400 that has been allocated in the function doing the copying. In that case, you
401 know at the time you are writing the code whether the buffer is large enough
402 for the fixed string or not, and if it's not, your code won't work anyway!
403 Use strcpy() for this operation, or directly set the first two characters
404 of the buffer if you are just trying to store a one character string in the
405 buffer. If you are trying to 'empty' the buffer, just store a single
406 NULL character ('\0') in the first byte of the buffer; nothing else is
407 needed, and any other method is wasteful.
409 In addition, if the previous operations in the function have already
410 determined that the buffer in use is adequately sized to hold the string
411 you wish to put into it (even if you did not allocate the buffer yourself),
412 use a direct strcpy(), as it can be inlined and optimized to simple
413 processor operations, unlike ast_copy_string().
418 When converting from strings to integers or floats, use the sscanf function
419 in preference to the atoi and atof family of functions, as sscanf detects
420 errors. Always check the return value of sscanf to verify that your numeric
421 variables successfully scanned before using them. Also, to avoid a potential
422 libc bug, always specify a maximum width for each conversion specifier,
423 including integers and floats. A good length for both integers and floats is
424 30, as this is more than generous, even if you're using doubles or long
430 For the sake of uclibc, do not use index, bcopy or bzero; use strchr(), memset(),
431 and memmove() instead. uclibc can be configured to supply these functions, but
432 we can save these users time and consternation if we abstain from using these
435 When making applications, always ast_strdupa(data) to a local pointer if you
436 intend to parse the incoming data string.
439 mydata = ast_strdupa(data);
442 - Use the argument parsing macros to declare arguments and parse them, i.e.:
444 AST_DECLARE_APP_ARGS(args,
449 parse = ast_strdupa(data);
450 AST_STANDARD_APP_ARGS(args, parse);
452 - Create generic code!
453 If you do the same or a similar operation more than one time, make it a
456 Make sure you are not duplicating any functionality already found in an
457 API call somewhere. If you are duplicating functionality found in
458 another static function, consider the value of creating a new API call
461 * Handling of pointers and allocations
462 --------------------------------------
464 - Dereference or localize pointers
465 Always dereference or localize pointers to things that are not yours like
466 channel members in a channel that is not associated with the current
467 thread and for which you do not have a lock.
468 channame = ast_strdupa(otherchan->name);
470 - Use const on pointer arguments if possible
471 Use const on pointer arguments which your function will not be modifying, as this
472 allows the compiler to make certain optimizations. In general, use 'const'
473 on any argument that you have no direct intention of modifying, as it can
474 catch logic/typing errors in your code when you use the argument variable
475 in a way that you did not intend.
477 - Do not create your own linked list code - reuse!
478 As a common example of this point, make an effort to use the lockable
479 linked-list macros found in include/asterisk/linkedlists.h. They are
480 efficient, easy to use and provide every operation that should be
481 necessary for managing a singly-linked list (if something is missing,
482 let us know!). Just because you see other open-coded list implementations
483 in the source tree is no reason to continue making new copies of
484 that code... There are also a number of common string manipulation
485 and timeval manipulation functions in asterisk/strings.h and asterisk/time.h;
486 use them when possible.
488 - Avoid needless allocations!
489 Avoid needless malloc(), strdup() calls. If you only need the value in
490 the scope of your function try ast_strdupa() or declare structs on the
491 stack and pass a pointer to them. However, be careful to _never_ call
492 alloca(), ast_strdupa() or similar functions in the argument list
493 of a function you are calling; this can cause very strange stack
494 arrangements and produce unexpected behavior.
496 - Allocations for structures
497 When allocating/zeroing memory for a structure, use code like this:
503 tmp = ast_calloc(1, sizeof(*tmp));
505 Avoid the combination of ast_malloc() and memset(). Instead, always use
506 ast_calloc(). This will allocate and zero the memory in a single operation.
507 In the case that uninitialized memory is acceptable, there should be a comment
508 in the code that states why this is the case.
510 Using sizeof(*tmp) instead of sizeof(struct foo) eliminates duplication of the
511 'struct foo' identifier, which makes the code easier to read and also ensures
512 that if it is copy-and-pasted it won't require as much editing.
514 The ast_* family of functions for memory allocation are functionally the same.
515 They just add an Asterisk log error message in the case that the allocation
516 fails for some reason. This eliminates the need to generate custom messages
517 throughout the code to log that this has occurred.
519 - String Duplications
521 The functions strdup and strndup can *not* accept a NULL argument. This results
522 in having code like this:
525 newstr = strdup(str);
529 However, the ast_strdup and ast_strdupa functions will happily accept a NULL
530 argument without generating an error. The same code can be written as:
532 newstr = ast_strdup(str);
534 Furthermore, it is unnecessary to have code that malloc/calloc's for the length
535 of a string (+1 for the terminating '\0') and then using strncpy to copy the
536 copy the string into the resulting buffer. This is the exact same thing as
542 New CLI commands should be named using the module's name, followed by a verb
543 and then any parameters that the command needs. For example:
545 *CLI> iax2 show peer <peername>
549 *CLI> show iax2 peer <peername>
551 * New dialplan applications/functions
552 -------------------------------------
554 There are two methods of adding functionality to the Asterisk
555 dialplan: applications and functions. Applications (found generally in
556 the apps/ directory) should be collections of code that interact with
557 a channel and/or user in some significant way. Functions (which can be
558 provided by any type of module) are used when the provided
559 functionality is simple... getting/retrieving a value, for
560 example. Functions should also be used when the operation is in no way
561 related to a channel (a computation or string operation, for example).
563 Applications are registered and invoked using the
564 ast_register_application function; see the apps/app_skel.c file for an
567 Functions are registered using 'struct ast_custom_function'
568 structures and the ast_custom_function_register function.
570 * Doxygen API Documentation Guidelines
571 --------------------------------------
573 When writing Asterisk API documentation the following format should be
574 followed. Do not use the javadoc style.
577 * \brief Do interesting stuff.
579 * \param thing1 interesting parameter 1.
580 * \param thing2 interesting parameter 2.
582 * This function does some interesting stuff.
584 * \retval zero on success
585 * \retval -1 on error.
587 int ast_interesting_stuff(int thing1, int thing2)
592 Notice the use of the \param, \brief, and \return constructs. These should be
593 used to describe the corresponding pieces of the function being documented.
594 Also notice the blank line after the last \param directive. All doxygen
595 comments must be in one /*! */ block. If the function or struct does not need
596 an extended description it can be left out.
598 Please make sure to review the doxygen manual and make liberal use of the \a,
599 \code, \c, \b, \note, \li and \e modifiers as appropriate.
601 When documenting a 'static' function or an internal structure in a module,
602 use the \internal modifier to ensure that the resulting documentation
603 explicitly says 'for internal use only'.
605 When adding new API you should also attach a \since note because this will
606 indicate to developers that this API did not exist before this version. It
607 also has the benefit of making the resulting HTML documentation to group
608 the changes for a single version.
610 Structures should be documented as follows.
613 * \brief A very interesting structure.
615 struct interesting_struct
617 /*! \brief A data member. */
620 int member2; /*!< \brief Another data member. */
623 Note that /*! */ blocks document the construct immediately following them
624 unless they are written, /*!< */, in which case they document the construct
627 It is very much preferred that documentation is not done inline, as done in
628 the previous example for member2. The first reason for this is that it tends
629 to encourage extremely brief, and often pointless, documentation since people
630 try to keep the comment from making the line extremely long. However, if you
631 insist on using inline comments, please indent the documentation with spaces!
632 That way, all of the comments are properly aligned, regardless of what tab
633 size is being used for viewing the code.
635 * Finishing up before you submit your code
636 ------------------------------------------
638 - Look at the code once more
639 When you achieve your desired functionality, make another few refactor
640 passes over the code to optimize it.
643 Before submitting a patch, *read* the actual patch file to be sure that
644 all the changes you expect to be there are, and that there are no
645 surprising changes you did not expect. During your development, that
646 part of Asterisk may have changed, so make sure you compare with the
650 If you are asked to make changes to your patch, there is a good chance
651 the changes will introduce bugs, check it even more at this stage.
652 Also remember that the bug marshal or co-developer that adds comments
653 is only human, they may be in error :-)
655 - Optimize, optimize, optimize
656 If you are going to reuse a computed value, save it in a variable
657 instead of recomputing it over and over. This can prevent you from
658 making a mistake in subsequent computations, making it easier to correct
659 if the formula has an error and may or may not help optimization but
660 will at least help readability.
662 Just an example (so don't over analyze it, that'd be a shame):
664 const char *prefix = "pre";
665 const char *postfix = "post";
669 if (name && (newname = alloca(strlen(name) + strlen(prefix) + strlen(postfix) + 3)))
670 snprintf(newname, strlen(name) + strlen(prefix) + strlen(postfix) + 3, "%s/%s/%s", prefix, name, postfix);
672 ...vs this alternative:
674 const char *prefix = "pre";
675 const char *postfix = "post";
680 if (name && (len = strlen(name) + strlen(prefix) + strlen(postfix) + 3) && (newname = alloca(len)))
681 snprintf(newname, len, "%s/%s/%s", prefix, name, postfix);
683 * Creating new manager events?
684 ------------------------------
685 If you create new AMI events, please read manager.txt. Do not re-use
686 existing headers for new purposes, but please re-use existing headers
687 for the same type of data.
689 Manager events that signal a status are required to have one
690 event name, with a status header that shows the status.
691 The old style, with one event named "ThisEventOn" and another named
692 "ThisEventOff", is no longer approved.
694 Check manager.txt for more information on manager and existing
695 headers. Please update this file if you add new headers.
697 * Locking in Asterisk
698 -----------------------------
700 A) Locking Fundamentals
702 Asterisk is a heavily multithreaded application. It makes extensive
703 use of locking to ensure safe access to shared resources between
706 When more that one lock is involved in a given code path, there is the
707 potential for deadlocks. A deadlock occurs when a thread is stuck
708 waiting for a resource that it will never acquire. Here is a classic
709 example of a deadlock:
712 ------------ ------------
713 Holds Lock A Holds Lock B
714 Waiting for Lock B Waiting for Lock A
716 In this case, there is a deadlock between threads 1 and 2.
717 This deadlock would have been avoided if both threads had
718 agreed that one must acquire Lock A before Lock B.
720 In general, the fundamental rule for dealing with multiple locks is
722 an order _must_ be established to acquire locks, and then all threads
723 must respect that order when acquiring locks.
726 A.1) Establishing a locking order
728 Because any ordering for acquiring locks is ok, one could establish
729 the rule arbitrarily, e.g. ordering by address, or by some other criterion.
730 The main issue, though, is defining an order that
731 i) is easy to check at runtime;
732 ii) reflects the order in which the code executes.
733 As an example, if a data structure B is only accessible through a
734 data structure A, and both require locking, then the natural order
735 is locking first A and then B.
736 As another example, if we have some unrelated data structures to
737 be locked in pairs, then a possible order can be based on the address
738 of the data structures themselves.
740 B) Minding the boundary between channel drivers and the Asterisk core
742 The #1 cause of deadlocks in Asterisk is by not properly following the
743 locking rules that exist at the boundary between Channel Drivers and
744 the Asterisk core. The Asterisk core allocates an ast_channel, and
745 Channel Drivers allocate "technology specific private data" (PVT) that is
746 associated with an ast_channel. Typically, both the ast_channel and
747 PVT have their own lock. There are _many_
748 code paths that require both objects to be locked.
750 The locking order in this situation is the following:
755 Channel Drivers implement the ast_channel_tech interface to provide a
756 channel implementation for Asterisk. Most of the channel_tech
757 interface callbacks are called with the associated ast_channel
758 locked. When accessing technology specific data, the PVT can be locked
759 directly because the locking order is respected.
761 C) Preventing lock ordering reversals.
763 There are some code paths which make it extremely difficult to
764 respect the locking order.
765 Consider for example the following situation:
767 1) A message comes in over the "network"
768 2) The Channel Driver (CD) monitor thread receives the message
769 3) The CD associates the message with a PVT and locks the PVT
770 4) While processing the message, the CD must do something that requires
771 locking the ast_channel associated to the PVT
773 This is the point that must be handled carefully.
774 The following psuedo-code
780 is _not_ correct for two reasons:
782 i) first and foremost, unlocking the PVT means that other threads
783 can acquire the lock and believe it is safe to modify the
784 associated data. When reacquiring the lock, the original thread
785 might find unexpected changes in the protected data structures.
786 This essentially means that the original thread must behave as if
787 the lock on the pvt was not held, in which case it could have
788 released it itself altogether;
790 ii) Asterisk uses the so called "recursive" locks, which allow a thread
791 to issue a lock() call multiple times on the same lock. Recursive
792 locks count the number of calls, and they require an equivalent
793 number of unlock() to be actually released.
795 For this reason, just calling unlock() once does not guarantee that the
796 lock is actually released -- it all depends on how many times lock()
799 An alternative, but still incorrect, construct is widely used in
800 the asterisk code to try and improve the situation:
802 while (trylock(ast_channel) == FAILURE) {
804 usleep(1); /* yield to other threads */
808 Here the trylock() is non blocking, so we do not deadlock if the ast_channel
809 is already locked by someone else: in this case, we try to unlock the PVT
810 (which happens only if the PVT lock counter is 1), yield the CPU to
811 give other threads a chance to run, and then acquire the lock again.
813 This code is not correct for two reasons:
814 i) same as in the previous example, it releases the lock when the thread
815 probably did not expect it;
816 ii) if the PVT lock counter is greater than 1 we will not
817 really release the lock on the PVT. We might be lucky and have the
818 other contender actually release the lock itself, and so we will "win"
819 the race, but if both contenders have their lock counts > 1 then
820 they will loop forever (basically replacing deadlock with livelock).
822 Another variant of this code is the following:
824 if (trylock(ast_channel) == FAILURE) {
830 which has the same issues as the while(trylock...) code, but just
831 deadlocks instead of looping forever in case of lock counts > 1.
833 The deadlock/livelock could be in principle spared if one had an
834 unlock_all() function that calls unlock as many times as needed to
835 actually release the lock, and reports the count. Then we could do:
837 if (trylock(ast_channel) == FAILURE) {
840 while (n-- > 0) lock(pvt);
843 The issue with unexpected unlocks remains, though.
845 C) Locking multiple channels.
847 The next situation to consider is what to do when you need a lock on
848 multiple ast_channels (or multiple unrelated data structures).
850 If we are sure that we do not hold any of these locks, then the
851 following construct is sufficient:
853 lock(MIN(chan1, chan2));
854 lock(MAX(chan1, chan2));
856 That type of code would follow an established locking order of always
857 locking the channel that has a lower address first. Also keep in mind
858 that to use this construct for channel locking, one would have to go
859 through the entire codebase to ensure that when two channels are locked,
860 this locking order is used.
861 However, if we enter the above section of code with some lock held
862 (which would be incorrect using non-recursive locks, but is completely
863 legal using recursive mutexes) then the locking order is not guaranteed
864 anymore because it depends on which locks we already hold. So we have
865 to go through the same tricks used for the channel+PVT case.
869 As you can see from the above discussion, getting locking right is all
870 but easy. So please follow these recommendations when using locks:
872 *) Use locks only when really necessary
873 Please try to use locks only when strictly necessary, and only for
874 the minimum amount of time required to run critical sections of code.
875 A common use of locks in the current code is to protect a data structure
876 from being released while you use it.
877 With the use of reference-counted objects (astobj2) this should not be
880 *) Do not sleep while holding a lock
881 If possible, do not run any blocking code while holding a lock,
882 because you will also block other threads trying to access the same
883 lock. In many cases, you can hold a reference to the object to avoid
884 that it is deleted while you sleep, perhaps set a flag in the object
885 itself to report other threads that you have some pending work to
886 complete, then release and acquire the lock around the blocking path,
887 checking the status of the object after you acquire the lock to make
888 sure that you can still perform the operation you wanted to.
890 *) Try not to exploit the 'recursive' feature of locks.
891 Recursive locks are very convenient when coding, as you don't have to
892 worry, when entering a section of code, whether or not you already
893 hold the lock -- you can just protect the section with a lock/unlock
894 pair and let the lock counter track things for you.
895 But as you have seen, exploiting the features of recursive locks
896 make it a lot harder to implement proper deadlock avoidance strategies.
897 So please try to analyse your code and determine statically whether you
898 already hold a lock when entering a section of code.
899 If you need to call some function foo() with and without a lock held,
900 you could define two function as below:
902 ... do something, assume lock held
907 ret = foo_locked(...)
911 and call them according to the needs.
913 *) Document locking rules.
914 Please document the locking order rules are documented for every
915 lock introduced into Asterisk. This is done almost nowhere in the
916 existing code. However, it will be expected to be there for newly
917 introduced code. Over time, this information should be added for
918 all of the existing lock usage.
920 -----------------------------------------------------------------------
923 ------------------------------------
924 == PART TWO: BUILD ARCHITECTURE ==
925 ------------------------------------
927 The asterisk build architecture relies on autoconf to detect the
928 system configuration, and on a locally developed tool (menuselect) to
929 select build options and modules list, and on gmake to do the build.
931 The first step, usually to be done soon after a checkout, is running
932 "./configure", which will store its findings in two files:
934 + include/asterisk/autoconfig.h
935 contains C macros, normally #define HAVE_FOO or HAVE_FOO_H ,
936 for all functions and headers that have been detected at build time.
937 These are meant to be used by C or C++ source files.
940 contains variables that can be used by Makefiles.
941 In addition to the usual CC, LD, ... variables pointing to
942 the various build tools, and prefix, includedir ... which are
943 useful for generic compiler flags, there are variables
944 for each package detected.
945 These are normally of the form FOO_INCLUDE=... FOO_LIB=...
946 FOO_DIR=... indicating, for each package, the useful libraries
949 The next step is to run "make menuselect", to extract the dependencies existing
950 between files and modules, and to store build options.
951 menuselect produces two files, both to be read by the Makefile:
953 + menuselect.makeopts
954 Contains for each subdirectory a list of modules that must be
955 excluded from the build, plus some additional informatiom.
956 + menuselect.makedeps
957 Contains, for each module, a list of packages it depends on.
958 For each of these packages, we can collect the relevant INCLUDE
959 and LIB files from makeopts. This file is based on information
960 in the .c source code files for each module.
962 The top level Makefile is in charge of setting up the build environment,
963 creating header files with build options, and recursively invoking the
964 subdir Makefiles to produce modules and the main executable.
966 The sources are split in multiple directories, more or less divided by
967 module type (apps/ channels/ funcs/ res/ ...) or by function, for the main
974 -----------------------------------------------
975 Welcome to the Asterisk development community!
976 Meet you on the asterisk-dev mailing list.
977 Subscribe at http://lists.digium.com!
979 -- The Asterisk.org Development Team