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 format specifier, including
423 integers and floats. A good length for both integers and floats is 30, as
424 this is more than generous, even if you're using doubles or long integers.
429 For the sake of uclibc, do not use index, bcopy or bzero; use strchr(), memset(),
430 and memmove() instead. uclibc can be configured to supply these functions, but
431 we can save these users time and consternation if we abstain from using these
434 When making applications, always ast_strdupa(data) to a local pointer if you
435 intend to parse the incoming data string.
438 mydata = ast_strdupa(data);
441 - Use the argument parsing macros to declare arguments and parse them, i.e.:
443 AST_DECLARE_APP_ARGS(args,
448 parse = ast_strdupa(data);
449 AST_STANDARD_APP_ARGS(args, parse);
451 - Create generic code!
452 If you do the same or a similar operation more than one time, make it a
455 Make sure you are not duplicating any functionality already found in an
456 API call somewhere. If you are duplicating functionality found in
457 another static function, consider the value of creating a new API call
460 * Handling of pointers and allocations
461 --------------------------------------
463 - Dereference or localize pointers
464 Always dereference or localize pointers to things that are not yours like
465 channel members in a channel that is not associated with the current
466 thread and for which you do not have a lock.
467 channame = ast_strdupa(otherchan->name);
469 - Use const on pointer arguments if possible
470 Use const on pointer arguments which your function will not be modifying, as this
471 allows the compiler to make certain optimizations. In general, use 'const'
472 on any argument that you have no direct intention of modifying, as it can
473 catch logic/typing errors in your code when you use the argument variable
474 in a way that you did not intend.
476 - Do not create your own linked list code - reuse!
477 As a common example of this point, make an effort to use the lockable
478 linked-list macros found in include/asterisk/linkedlists.h. They are
479 efficient, easy to use and provide every operation that should be
480 necessary for managing a singly-linked list (if something is missing,
481 let us know!). Just because you see other open-coded list implementations
482 in the source tree is no reason to continue making new copies of
483 that code... There are also a number of common string manipulation
484 and timeval manipulation functions in asterisk/strings.h and asterisk/time.h;
485 use them when possible.
487 - Avoid needless allocations!
488 Avoid needless malloc(), strdup() calls. If you only need the value in
489 the scope of your function try ast_strdupa() or declare structs on the
490 stack and pass a pointer to them. However, be careful to _never_ call
491 alloca(), ast_strdupa() or similar functions in the argument list
492 of a function you are calling; this can cause very strange stack
493 arrangements and produce unexpected behavior.
495 - Allocations for structures
496 When allocating/zeroing memory for a structure, use code like this:
502 tmp = ast_calloc(1, sizeof(*tmp));
504 Avoid the combination of ast_malloc() and memset(). Instead, always use
505 ast_calloc(). This will allocate and zero the memory in a single operation.
506 In the case that uninitialized memory is acceptable, there should be a comment
507 in the code that states why this is the case.
509 Using sizeof(*tmp) instead of sizeof(struct foo) eliminates duplication of the
510 'struct foo' identifier, which makes the code easier to read and also ensures
511 that if it is copy-and-pasted it won't require as much editing.
513 The ast_* family of functions for memory allocation are functionally the same.
514 They just add an Asterisk log error message in the case that the allocation
515 fails for some reason. This eliminates the need to generate custom messages
516 throughout the code to log that this has occurred.
518 - String Duplications
520 The functions strdup and strndup can *not* accept a NULL argument. This results
521 in having code like this:
524 newstr = strdup(str);
528 However, the ast_strdup and ast_strdupa functions will happily accept a NULL
529 argument without generating an error. The same code can be written as:
531 newstr = ast_strdup(str);
533 Furthermore, it is unnecessary to have code that malloc/calloc's for the length
534 of a string (+1 for the terminating '\0') and then using strncpy to copy the
535 copy the string into the resulting buffer. This is the exact same thing as
541 New CLI commands should be named using the module's name, followed by a verb
542 and then any parameters that the command needs. For example:
544 *CLI> iax2 show peer <peername>
548 *CLI> show iax2 peer <peername>
550 * New dialplan applications/functions
551 -------------------------------------
553 There are two methods of adding functionality to the Asterisk
554 dialplan: applications and functions. Applications (found generally in
555 the apps/ directory) should be collections of code that interact with
556 a channel and/or user in some significant way. Functions (which can be
557 provided by any type of module) are used when the provided
558 functionality is simple... getting/retrieving a value, for
559 example. Functions should also be used when the operation is in no way
560 related to a channel (a computation or string operation, for example).
562 Applications are registered and invoked using the
563 ast_register_application function; see the apps/app_skel.c file for an
566 Functions are registered using 'struct ast_custom_function'
567 structures and the ast_custom_function_register function.
569 * Doxygen API Documentation Guidelines
570 --------------------------------------
572 When writing Asterisk API documentation the following format should be
573 followed. Do not use the javadoc style.
576 * \brief Do interesting stuff.
578 * \param thing1 interesting parameter 1.
579 * \param thing2 interesting parameter 2.
581 * This function does some interesting stuff.
583 * \retval zero on success
584 * \retval -1 on error.
586 int ast_interesting_stuff(int thing1, int thing2)
591 Notice the use of the \param, \brief, and \return constructs. These should be
592 used to describe the corresponding pieces of the function being documented.
593 Also notice the blank line after the last \param directive. All doxygen
594 comments must be in one /*! */ block. If the function or struct does not need
595 an extended description it can be left out.
597 Please make sure to review the doxygen manual and make liberal use of the \a,
598 \code, \c, \b, \note, \li and \e modifiers as appropriate.
600 When documenting a 'static' function or an internal structure in a module,
601 use the \internal modifier to ensure that the resulting documentation
602 explicitly says 'for internal use only'.
604 When adding new API you should also attach a \since note because this will
605 indicate to developers that this API did not exist before this version. It
606 also has the benefit of making the resulting HTML documentation to group
607 the changes for a single version.
609 Structures should be documented as follows.
612 * \brief A very interesting structure.
614 struct interesting_struct
616 /*! \brief A data member. */
619 int member2; /*!< \brief Another data member. */
622 Note that /*! */ blocks document the construct immediately following them
623 unless they are written, /*!< */, in which case they document the construct
626 It is very much preferred that documentation is not done inline, as done in
627 the previous example for member2. The first reason for this is that it tends
628 to encourage extremely brief, and often pointless, documentation since people
629 try to keep the comment from making the line extremely long. However, if you
630 insist on using inline comments, please indent the documentation with spaces!
631 That way, all of the comments are properly aligned, regardless of what tab
632 size is being used for viewing the code.
634 * Finishing up before you submit your code
635 ------------------------------------------
637 - Look at the code once more
638 When you achieve your desired functionality, make another few refactor
639 passes over the code to optimize it.
642 Before submitting a patch, *read* the actual patch file to be sure that
643 all the changes you expect to be there are, and that there are no
644 surprising changes you did not expect. During your development, that
645 part of Asterisk may have changed, so make sure you compare with the
649 If you are asked to make changes to your patch, there is a good chance
650 the changes will introduce bugs, check it even more at this stage.
651 Also remember that the bug marshal or co-developer that adds comments
652 is only human, they may be in error :-)
654 - Optimize, optimize, optimize
655 If you are going to reuse a computed value, save it in a variable
656 instead of recomputing it over and over. This can prevent you from
657 making a mistake in subsequent computations, making it easier to correct
658 if the formula has an error and may or may not help optimization but
659 will at least help readability.
661 Just an example (so don't over analyze it, that'd be a shame):
663 const char *prefix = "pre";
664 const char *postfix = "post";
668 if (name && (newname = alloca(strlen(name) + strlen(prefix) + strlen(postfix) + 3)))
669 snprintf(newname, strlen(name) + strlen(prefix) + strlen(postfix) + 3, "%s/%s/%s", prefix, name, postfix);
671 ...vs this alternative:
673 const char *prefix = "pre";
674 const char *postfix = "post";
679 if (name && (len = strlen(name) + strlen(prefix) + strlen(postfix) + 3) && (newname = alloca(len)))
680 snprintf(newname, len, "%s/%s/%s", prefix, name, postfix);
682 * Creating new manager events?
683 ------------------------------
684 If you create new AMI events, please read manager.txt. Do not re-use
685 existing headers for new purposes, but please re-use existing headers
686 for the same type of data.
688 Manager events that signal a status are required to have one
689 event name, with a status header that shows the status.
690 The old style, with one event named "ThisEventOn" and another named
691 "ThisEventOff", is no longer approved.
693 Check manager.txt for more information on manager and existing
694 headers. Please update this file if you add new headers.
696 * Locking in Asterisk
697 -----------------------------
699 A) Locking Fundamentals
701 Asterisk is a heavily multithreaded application. It makes extensive
702 use of locking to ensure safe access to shared resources between
705 When more that one lock is involved in a given code path, there is the
706 potential for deadlocks. A deadlock occurs when a thread is stuck
707 waiting for a resource that it will never acquire. Here is a classic
708 example of a deadlock:
711 ------------ ------------
712 Holds Lock A Holds Lock B
713 Waiting for Lock B Waiting for Lock A
715 In this case, there is a deadlock between threads 1 and 2.
716 This deadlock would have been avoided if both threads had
717 agreed that one must acquire Lock A before Lock B.
719 In general, the fundamental rule for dealing with multiple locks is
721 an order _must_ be established to acquire locks, and then all threads
722 must respect that order when acquiring locks.
725 A.1) Establishing a locking order
727 Because any ordering for acquiring locks is ok, one could establish
728 the rule arbitrarily, e.g. ordering by address, or by some other criterion.
729 The main issue, though, is defining an order that
730 i) is easy to check at runtime;
731 ii) reflects the order in which the code executes.
732 As an example, if a data structure B is only accessible through a
733 data structure A, and both require locking, then the natural order
734 is locking first A and then B.
735 As another example, if we have some unrelated data structures to
736 be locked in pairs, then a possible order can be based on the address
737 of the data structures themselves.
739 B) Minding the boundary between channel drivers and the Asterisk core
741 The #1 cause of deadlocks in Asterisk is by not properly following the
742 locking rules that exist at the boundary between Channel Drivers and
743 the Asterisk core. The Asterisk core allocates an ast_channel, and
744 Channel Drivers allocate "technology specific private data" (PVT) that is
745 associated with an ast_channel. Typically, both the ast_channel and
746 PVT have their own lock. There are _many_
747 code paths that require both objects to be locked.
749 The locking order in this situation is the following:
754 Channel Drivers implement the ast_channel_tech interface to provide a
755 channel implementation for Asterisk. Most of the channel_tech
756 interface callbacks are called with the associated ast_channel
757 locked. When accessing technology specific data, the PVT can be locked
758 directly because the locking order is respected.
760 C) Preventing lock ordering reversals.
762 There are some code paths which make it extremely difficult to
763 respect the locking order.
764 Consider for example the following situation:
766 1) A message comes in over the "network"
767 2) The Channel Driver (CD) monitor thread receives the message
768 3) The CD associates the message with a PVT and locks the PVT
769 4) While processing the message, the CD must do something that requires
770 locking the ast_channel associated to the PVT
772 This is the point that must be handled carefully.
773 The following psuedo-code
779 is _not_ correct for two reasons:
781 i) first and foremost, unlocking the PVT means that other threads
782 can acquire the lock and believe it is safe to modify the
783 associated data. When reacquiring the lock, the original thread
784 might find unexpected changes in the protected data structures.
785 This essentially means that the original thread must behave as if
786 the lock on the pvt was not held, in which case it could have
787 released it itself altogether;
789 ii) Asterisk uses the so called "recursive" locks, which allow a thread
790 to issue a lock() call multiple times on the same lock. Recursive
791 locks count the number of calls, and they require an equivalent
792 number of unlock() to be actually released.
794 For this reason, just calling unlock() once does not guarantee that the
795 lock is actually released -- it all depends on how many times lock()
798 An alternative, but still incorrect, construct is widely used in
799 the asterisk code to try and improve the situation:
801 while (trylock(ast_channel) == FAILURE) {
803 usleep(1); /* yield to other threads */
807 Here the trylock() is non blocking, so we do not deadlock if the ast_channel
808 is already locked by someone else: in this case, we try to unlock the PVT
809 (which happens only if the PVT lock counter is 1), yield the CPU to
810 give other threads a chance to run, and then acquire the lock again.
812 This code is not correct for two reasons:
813 i) same as in the previous example, it releases the lock when the thread
814 probably did not expect it;
815 ii) if the PVT lock counter is greater than 1 we will not
816 really release the lock on the PVT. We might be lucky and have the
817 other contender actually release the lock itself, and so we will "win"
818 the race, but if both contenders have their lock counts > 1 then
819 they will loop forever (basically replacing deadlock with livelock).
821 Another variant of this code is the following:
823 if (trylock(ast_channel) == FAILURE) {
829 which has the same issues as the while(trylock...) code, but just
830 deadlocks instead of looping forever in case of lock counts > 1.
832 The deadlock/livelock could be in principle spared if one had an
833 unlock_all() function that calls unlock as many times as needed to
834 actually release the lock, and reports the count. Then we could do:
836 if (trylock(ast_channel) == FAILURE) {
839 while (n-- > 0) lock(pvt);
842 The issue with unexpected unlocks remains, though.
844 C) Locking multiple channels.
846 The next situation to consider is what to do when you need a lock on
847 multiple ast_channels (or multiple unrelated data structures).
849 If we are sure that we do not hold any of these locks, then the
850 following construct is sufficient:
852 lock(MIN(chan1, chan2));
853 lock(MAX(chan1, chan2));
855 That type of code would follow an established locking order of always
856 locking the channel that has a lower address first. Also keep in mind
857 that to use this construct for channel locking, one would have to go
858 through the entire codebase to ensure that when two channels are locked,
859 this locking order is used.
860 However, if we enter the above section of code with some lock held
861 (which would be incorrect using non-recursive locks, but is completely
862 legal using recursive mutexes) then the locking order is not guaranteed
863 anymore because it depends on which locks we already hold. So we have
864 to go through the same tricks used for the channel+PVT case.
868 As you can see from the above discussion, getting locking right is all
869 but easy. So please follow these recommendations when using locks:
871 *) Use locks only when really necessary
872 Please try to use locks only when strictly necessary, and only for
873 the minimum amount of time required to run critical sections of code.
874 A common use of locks in the current code is to protect a data structure
875 from being released while you use it.
876 With the use of reference-counted objects (astobj2) this should not be
879 *) Do not sleep while holding a lock
880 If possible, do not run any blocking code while holding a lock,
881 because you will also block other threads trying to access the same
882 lock. In many cases, you can hold a reference to the object to avoid
883 that it is deleted while you sleep, perhaps set a flag in the object
884 itself to report other threads that you have some pending work to
885 complete, then release and acquire the lock around the blocking path,
886 checking the status of the object after you acquire the lock to make
887 sure that you can still perform the operation you wanted to.
889 *) Try not to exploit the 'recursive' feature of locks.
890 Recursive locks are very convenient when coding, as you don't have to
891 worry, when entering a section of code, whether or not you already
892 hold the lock -- you can just protect the section with a lock/unlock
893 pair and let the lock counter track things for you.
894 But as you have seen, exploiting the features of recursive locks
895 make it a lot harder to implement proper deadlock avoidance strategies.
896 So please try to analyse your code and determine statically whether you
897 already hold a lock when entering a section of code.
898 If you need to call some function foo() with and without a lock held,
899 you could define two function as below:
901 ... do something, assume lock held
906 ret = foo_locked(...)
910 and call them according to the needs.
912 *) Document locking rules.
913 Please document the locking order rules are documented for every
914 lock introduced into Asterisk. This is done almost nowhere in the
915 existing code. However, it will be expected to be there for newly
916 introduced code. Over time, this information should be added for
917 all of the existing lock usage.
919 -----------------------------------------------------------------------
922 ------------------------------------
923 == PART TWO: BUILD ARCHITECTURE ==
924 ------------------------------------
926 The asterisk build architecture relies on autoconf to detect the
927 system configuration, and on a locally developed tool (menuselect) to
928 select build options and modules list, and on gmake to do the build.
930 The first step, usually to be done soon after a checkout, is running
931 "./configure", which will store its findings in two files:
933 + include/asterisk/autoconfig.h
934 contains C macros, normally #define HAVE_FOO or HAVE_FOO_H ,
935 for all functions and headers that have been detected at build time.
936 These are meant to be used by C or C++ source files.
939 contains variables that can be used by Makefiles.
940 In addition to the usual CC, LD, ... variables pointing to
941 the various build tools, and prefix, includedir ... which are
942 useful for generic compiler flags, there are variables
943 for each package detected.
944 These are normally of the form FOO_INCLUDE=... FOO_LIB=...
945 FOO_DIR=... indicating, for each package, the useful libraries
948 The next step is to run "make menuselect", to extract the dependencies existing
949 between files and modules, and to store build options.
950 menuselect produces two files, both to be read by the Makefile:
952 + menuselect.makeopts
953 Contains for each subdirectory a list of modules that must be
954 excluded from the build, plus some additional informatiom.
955 + menuselect.makedeps
956 Contains, for each module, a list of packages it depends on.
957 For each of these packages, we can collect the relevant INCLUDE
958 and LIB files from makeopts. This file is based on information
959 in the .c source code files for each module.
961 The top level Makefile is in charge of setting up the build environment,
962 creating header files with build options, and recursively invoking the
963 subdir Makefiles to produce modules and the main executable.
965 The sources are split in multiple directories, more or less divided by
966 module type (apps/ channels/ funcs/ res/ ...) or by function, for the main
973 -----------------------------------------------
974 Welcome to the Asterisk development community!
975 Meet you on the asterisk-dev mailing list.
976 Subscribe at http://lists.digium.com!
978 -- The Asterisk.org Development Team