Last batch of 'static' qualifiers for module-level global variables.
[asterisk/asterisk.git] / doc / CODING-GUIDELINES
1             --------------------------------------
2             == Asterisk Coding Guidelines ==
3             --------------------------------------
4
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.
9
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
12 new code.
13
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.
21
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/.
26
27 Patches should be in the form of a unified (-u) diff, made from a checkout
28 from subversion.
29
30 /usr/src/asterisk$ svn diff > mypatch
31
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:
34
35 /usr/src/asterisk$ svn diff somefile.c someotherfile.c > mypatch
36
37                 -----------------------------------
38                 ==  PART ONE: CODING GUIDELINES  ==
39                 -----------------------------------
40
41 * General rules
42 ---------------
43
44 - All code, filenames, function names and comments must be in ENGLISH.
45
46 - Don't annotate your changes with comments like "/* JMG 4/20/04 */";
47   Comments should explain what the code does, not when something was changed
48   or who changed it. If you have done a larger contribution, make sure
49   that you are added to the CREDITS file.
50
51 - Don't make unnecessary whitespace changes throughout the code.
52   If you make changes, submit them to the tracker as separate patches
53   that only include whitespace and formatting changes.
54
55 - Don't use C++ type (//) comments.
56
57 - Try to match the existing formatting of the file you are working on.
58
59 - Use spaces instead of tabs when aligning in-line comments or #defines (this makes
60   your comments aligned even if the code is viewed with another tabsize)
61
62 * File structure and header inclusion
63 -------------------------------------
64
65 Every C source file should start with a proper copyright
66 and a brief description of the content of the file.
67 Following that, you should immediately put the following lines:
68
69 #include "asterisk.h"
70 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
71
72 "asterisk.h" resolves OS and compiler dependencies for the basic
73 set of unix functions (data types, system calls, basic I/O
74 libraries) and the basic Asterisk APIs.
75 ASTERISK_FILE_VERSION() stores in the executable information
76 about the file.
77
78 Next, you should #include extra headers according to the functionality
79 that your file uses or implements. For each group of functions that
80 you use there is a common header, which covers OS header dependencies
81 and defines the 'external' API of those functions (the equivalent
82 of 'public' members of a class).  As an example:
83
84     asterisk/module.h
85         if you are implementing a module, this should be included in one
86         of the files that are linked with the module.
87
88     asterisk/io.h
89         access to extra file I/O functions (stat, fstat, playing with
90         directories etc)
91
92     asterisk/network.h
93         basic network I/O - all of the socket library, select/poll,
94         and asterisk-specific (usually either thread-safe or reentrant
95         or both) functions to play with socket addresses.
96
97     asterisk/app.h
98         parsing of application arguments
99
100     asterisk/channel.h
101         struct ast_channel and functions to manipulate it
102
103 For more information look at the headers in include/asterisk/ .
104 These files are usually self-sufficient, i.e. they recursively #include
105 all the extra headers they need.
106
107 The equivalent of 'private' members of a class are either directly in
108 the C source file, or in files named asterisk/mod_*.h to make it clear
109 that they are not for inclusion by generic code.
110
111 Keep the number of header files small by not including them unnecessarily.
112 Don't cut&paste list of header files from other sources, but only include
113 those you really need. Apart from obvious cases (e.g. module.h which
114 is almost always necessary) write a short comment next to each #include to
115 explain why you need it.
116
117 * Declaration of functions and variables
118 ----------------------------------------
119
120 - Do not declare variables mid-block (e.g. like recent GNU compilers support)
121   since it is harder to read and not portable to GCC 2.95 and others.
122
123 - Functions and variables that are not intended to be used outside the module
124   must be declared static. If you are compiling on a Linux platform that has the
125   'dwarves' package available, you can use the 'pglobal' tool from that package
126   to check for unintended global variables or functions being exposed in your
127   object files. Usage is very simple:
128
129   $ pglobal -vf <path to .o file>
130
131 - When reading integer numeric input with scanf (or variants), do _NOT_ use '%i'
132   unless you specifically want to allow non-base-10 input; '%d' is always a better
133   choice, since it will not silently turn numbers with leading zeros into base-8.
134
135 - Strings that are coming from input should not be used as the format argument to
136   any printf-style function.
137
138 * Structure alignment and padding
139 ---------------------------------
140
141 On many platforms, structure fields (in structures that are not marked 'packed')
142 will be laid out by the compiler with gaps (padding) between them, in order to
143 satisfy alignment requirements. As a simple example:
144
145 struct foo {
146        int bar;
147        void *xyz;
148 }
149
150 On nearly every 64-bit platform, this will result in 4 bytes of dead space between
151 'bar' and 'xyz', because pointers on 64-bit platforms must be aligned on 8-byte
152 boundaries. Once you have your code written and tested, it may be worthwhile to review
153 your structure definitions to look for problems of this nature. If you are on a Linux
154 platform with the 'dwarves' package available, the 'pahole' tool from that package
155 can be used to both check for padding issues of this type and also propose reorganized
156 structure definitions to eliminate it. Usage is quite simple; for a structure named 'foo',
157 the command would look something like this:
158
159 $ pahole --reorganize --show_reorg_steps -C foo <path to module>
160
161 The 'pahole' tool has many other modes available, including some that will list all the
162 structures declared in the module and the amount of padding in each one that could possibly
163 be recovered.
164
165 * Use the internal API
166 ----------------------
167
168 - Make sure you are aware of the string and data handling functions that exist
169   within Asterisk to enhance portability and in some cases to produce more
170   secure and thread-safe code. Check utils.c/utils.h for these.
171
172 - If you need to create a detached thread, use the ast_pthread_create_detached()
173   normally or ast_pthread_create_detached_background() for a thread with a smaller
174   stack size.  This reduces the replication of the code to handle the pthread_attr_t
175   structure.
176
177 * Code formatting
178 -----------------
179
180 Roughly, Asterisk code formatting guidelines are generally equivalent to the
181 following:
182
183 # indent -i4 -ts4 -br -brs -cdw -lp -ce -nbfda -npcs -nprs -npsl -nbbo -saf -sai -saw -cs -l90 foo.c
184
185 this means in verbose:
186  -i4:    indent level 4
187  -ts4:   tab size 4
188  -br:    braces on if line
189  -brs:   braces on struct decl line
190  -cdw:   cuddle do while
191  -lp:    line up continuation below parenthesis
192  -ce:    cuddle else
193  -nbfda: dont break function decl args
194  -npcs:  no space after function call names
195  -nprs:  no space after parentheses
196  -npsl:  dont break procedure type
197  -saf:   space after for
198  -sai:   space after if
199  -saw:   space after while
200  -cs:    space after cast
201  -l90:  line length 90 columns
202
203 Function calls and arguments should be spaced in a consistent way across
204 the codebase.
205         GOOD: foo(arg1, arg2);
206         BAD: foo(arg1,arg2);
207         BAD: foo (arg1, arg2);
208         BAD: foo( arg1, arg2 );
209         BAD: foo(arg1, arg2,arg3);
210
211 Don't treat keywords (if, while, do, return) as if they were functions;
212 leave space between the keyword and the expression used (if any). For 'return',
213 don't even put parentheses around the expression, since they are not
214 required.
215
216 There is no shortage of whitespace characters :-) Use them when they make
217 the code easier to read. For example:
218
219         for (str=foo;str;str=str->next)
220
221 is harder to read than
222
223         for (str = foo; str; str = str->next)
224
225 Following are examples of how code should be formatted.
226
227 - Functions:
228 int foo(int a, char *s)
229 {
230         return 0;
231 }
232
233 - If statements:
234 if (foo) {
235         bar();
236 } else {
237         blah();
238 }
239
240 - Case statements:
241 switch (foo) {
242 case BAR:
243         blah();
244         break;
245 case OTHER:
246         other();
247         break;
248 }
249
250 - No nested statements without braces, e.g.:
251
252 for (x = 0; x < 5; x++)
253         if (foo)
254                 if (bar)
255                         baz();
256
257 instead do:
258 for (x = 0; x < 5; x++) {
259         if (foo) {
260                 if (bar) {
261                         baz();
262                 }
263         }
264 }
265
266 - Always use braces around the statements following an if/for/while construct,
267 even if not strictly necessary, as it reduces future possible problems.
268
269 - Don't build code like this:
270
271 if (foo) {
272         /* .... 50 lines of code ... */
273 } else {
274         result = 0;
275         return;
276 }
277
278 Instead, try to minimize the number of lines of code that need to be
279 indented, by only indenting the shortest case of the 'if'
280 statement, like so:
281
282 if (!foo) {
283         result = 0;
284         return;
285 }
286
287 .... 50 lines of code ....
288
289 When this technique is used properly, it makes functions much easier to read
290 and follow, especially those with more than one or two 'setup' operations
291 that must succeed for the rest of the function to be able to execute.
292
293 - Labels/goto are acceptable
294 Proper use of this technique may occasionally result in the need for a
295 label/goto combination so that error/failure conditions can exit the
296 function while still performing proper cleanup. This is not a bad thing!
297 Use of goto in this situation is encouraged, since it removes the need
298 for excess code indenting without requiring duplication of cleanup code.
299
300 - Never use an uninitialized variable
301 Make sure you never use an uninitialized variable.  The compiler will
302 usually warn you if you do so. However, do not go too far the other way,
303 and needlessly initialize variables that do not require it. If the first
304 time you use a variable in a function is to store a value there, then
305 initializing it at declaration is pointless, and will generate extra
306 object code and data in the resulting binary with no purpose. When in doubt,
307 trust the compiler to tell you when you need to initialize a variable;
308 if it does not warn you, initialization is not needed.
309
310 - Do not cast 'void *'
311 Do not explicitly cast 'void *' into any other type, nor should you cast any
312 other type into 'void *'. Implicit casts to/from 'void *' are explicitly
313 allowed by the C specification. This means the results of malloc(), calloc(),
314 alloca(), and similar functions do not _ever_ need to be cast to a specific
315 type, and when you are passing a pointer to (for example) a callback function
316 that accepts a 'void *' you do not need to cast into that type.
317
318 * Function naming
319 -----------------
320
321 All public functions (those not marked 'static'), must be named "ast_<something>"
322 and have a descriptive name.
323
324 As an example, suppose you wanted to take a local function "find_feature", defined
325 as static in a file, and used only in that file, and make it public, and use it
326 in other files. You will have to remove the "static" declaration and define a
327 prototype in an appropriate header file (usually in include/asterisk). A more
328 specific name should be given, such as "ast_find_call_feature".
329
330 * Variable function argument parsing
331 ------------------------------------
332
333 Functions with a variable amount of arguments need a 'sentinel' when called.
334 Newer GNU C compilers are fine if you use NULL for this. Older versions (pre 4)
335 don't like this.
336 You should use the constant SENTINEL.
337 This one is defined in include/asterisk/compiler.h
338
339 * Variable naming
340 -----------------
341
342 - Global variables
343 Name global variables (or local variables when you have a lot of them or
344 are in a long function) something that will make sense to aliens who
345 find your code in 100 years.  All variable names should be in lower
346 case, except when following external APIs or specifications that normally
347 use upper- or mixed-case variable names; in that situation, it is
348 preferable to follow the external API/specification for ease of
349 understanding.
350
351 Make some indication in the name of global variables which represent
352 options that they are in fact intended to be global.
353  e.g.: static char global_something[80]
354
355 - Don't use unnecessary typedef's
356 Don't use 'typedef' just to shorten the amount of typing; there is no substantial
357 benefit in this:
358 struct foo { int bar; }; typedef struct foo foo_t;
359
360 In fact, don't use 'variable type' suffixes at all; it's much preferable to
361 just type 'struct foo' rather than 'foo_s'.
362
363 - Use enums instead of #define where possible
364 Use enums rather than long lists of #define-d numeric constants when possible;
365 this allows structure members, local variables and function arguments to
366 be declared as using the enum's type. For example:
367
368 enum option {
369   OPT_FOO = 1,
370   OPT_BAR = 2,
371   OPT_BAZ = 4,
372 };
373
374 static enum option global_option;
375
376 static handle_option(const enum option opt)
377 {
378   ...
379 }
380
381 Note: The compiler will _not_ force you to pass an entry from the enum
382 as an argument to this function; this recommendation serves only to make
383 the code clearer and somewhat self-documenting. In addition, when using
384 switch/case blocks that switch on enum values, the compiler will warn
385 you if you forget to handle one or more of the enum values, which can be
386 handy.
387
388 * String handling
389 -----------------
390
391 Don't use strncpy for copying whole strings; it does not guarantee that the
392 output buffer will be null-terminated. Use ast_copy_string instead, which
393 is also slightly more efficient (and allows passing the actual buffer
394 size, which makes the code clearer).
395
396 Don't use ast_copy_string (or any length-limited copy function) for copying
397 fixed (known at compile time) strings into buffers, if the buffer is something
398 that has been allocated in the function doing the copying. In that case, you
399 know at the time you are writing the code whether the buffer is large enough
400 for the fixed string or not, and if it's not, your code won't work anyway!
401 Use strcpy() for this operation, or directly set the first two characters
402 of the buffer if you are just trying to store a one character string in the
403 buffer. If you are trying to 'empty' the buffer, just store a single
404 NULL character ('\0') in the first byte of the buffer; nothing else is
405 needed, and any other method is wasteful.
406
407 In addition, if the previous operations in the function have already
408 determined that the buffer in use is adequately sized to hold the string
409 you wish to put into it (even if you did not allocate the buffer yourself),
410 use a direct strcpy(), as it can be inlined and optimized to simple
411 processor operations, unlike ast_copy_string().
412
413 * Use of functions
414 ------------------
415
416 For the sake of uclibc, do not use index, bcopy or bzero; use strchr(), memset(),
417 and memmove() instead. uclibc can be configured to supply these functions, but
418 we can save these users time and consternation if we abstain from using these
419 functions.
420
421 When making applications, always ast_strdupa(data) to a local pointer if you
422 intend to parse the incoming data string.
423
424         if (data)
425                 mydata = ast_strdupa(data);
426
427
428 - Use the argument parsing macros to declare arguments and parse them, i.e.:
429
430         AST_DECLARE_APP_ARGS(args,
431                 AST_APP_ARG(arg1);
432                 AST_APP_ARG(arg2);
433                 AST_APP_ARG(arg3);
434         );
435         parse = ast_strdupa(data);
436         AST_STANDARD_APP_ARGS(args, parse);
437
438 - Create generic code!
439 If you do the same or a similar operation more than one time, make it a
440 function or macro.
441
442 Make sure you are not duplicating any functionality already found in an
443 API call somewhere.  If you are duplicating functionality found in
444 another static function, consider the value of creating a new API call
445 which can be shared.
446
447 * Handling of pointers and allocations
448 --------------------------------------
449
450 - Dereference or localize pointers
451 Always dereference or localize pointers to things that are not yours like
452 channel members in a channel that is not associated with the current
453 thread and for which you do not have a lock.
454         channame = ast_strdupa(otherchan->name);
455
456 - Use const on pointer arguments if possible
457 Use const on pointer arguments which your function will not be modifying, as this
458 allows the compiler to make certain optimizations. In general, use 'const'
459 on any argument that you have no direct intention of modifying, as it can
460 catch logic/typing errors in your code when you use the argument variable
461 in a way that you did not intend.
462
463 - Do not create your own linked list code - reuse!
464 As a common example of this point, make an effort to use the lockable
465 linked-list macros found in include/asterisk/linkedlists.h. They are
466 efficient, easy to use and provide every operation that should be
467 necessary for managing a singly-linked list (if something is missing,
468 let us know!). Just because you see other open-coded list implementations
469 in the source tree is no reason to continue making new copies of
470 that code... There are also a number of common string manipulation
471 and timeval manipulation functions in asterisk/strings.h and asterisk/time.h;
472 use them when possible.
473
474 - Avoid needless allocations!
475 Avoid needless malloc(), strdup() calls. If you only need the value in
476 the scope of your function try ast_strdupa() or declare structs on the
477 stack and pass a pointer to them. However, be careful to _never_ call
478 alloca(), ast_strdupa() or similar functions in the argument list
479 of a function you are calling; this can cause very strange stack
480 arrangements and produce unexpected behavior.
481
482 - Allocations for structures
483 When allocating/zeroing memory for a structure, use code like this:
484
485 struct foo *tmp;
486
487 ...
488
489 tmp = ast_calloc(1, sizeof(*tmp));
490
491 Avoid the combination of ast_malloc() and memset().  Instead, always use
492 ast_calloc(). This will allocate and zero the memory in a single operation.
493 In the case that uninitialized memory is acceptable, there should be a comment
494 in the code that states why this is the case.
495
496 Using sizeof(*tmp) instead of sizeof(struct foo) eliminates duplication of the
497 'struct foo' identifier, which makes the code easier to read and also ensures
498 that if it is copy-and-pasted it won't require as much editing.
499
500 The ast_* family of functions for memory allocation are functionally the same.
501 They just add an Asterisk log error message in the case that the allocation
502 fails for some reason. This eliminates the need to generate custom messages
503 throughout the code to log that this has occurred.
504
505 - String Duplications
506
507 The functions strdup and strndup can *not* accept a NULL argument. This results
508 in having code like this:
509
510         if (str)
511                 newstr = strdup(str);
512         else
513                 newstr = NULL;
514
515 However, the ast_strdup and ast_strdupa functions will happily accept a NULL
516 argument without generating an error.  The same code can be written as:
517
518         newstr = ast_strdup(str);
519
520 Furthermore, it is unnecessary to have code that malloc/calloc's for the length
521 of a string (+1 for the terminating '\0') and then using strncpy to copy the
522 copy the string into the resulting buffer.  This is the exact same thing as
523 using ast_strdup.
524
525 * CLI Commands
526 --------------
527
528 New CLI commands should be named using the module's name, followed by a verb
529 and then any parameters that the command needs. For example:
530
531 *CLI> iax2 show peer <peername>
532
533 not
534
535 *CLI> show iax2 peer <peername>
536
537 * New dialplan applications/functions
538 -------------------------------------
539
540 There are two methods of adding functionality to the Asterisk
541 dialplan: applications and functions. Applications (found generally in
542 the apps/ directory) should be collections of code that interact with
543 a channel and/or user in some significant way. Functions (which can be
544 provided by any type of module) are used when the provided
545 functionality is simple... getting/retrieving a value, for
546 example. Functions should also be used when the operation is in no way
547 related to a channel (a computation or string operation, for example).
548
549 Applications are registered and invoked using the
550 ast_register_application function; see the apps/app_skel.c file for an
551 example.
552
553 Functions are registered using 'struct ast_custom_function'
554 structures and the ast_custom_function_register function.
555
556 * Doxygen API Documentation Guidelines
557 --------------------------------------
558
559 When writing Asterisk API documentation the following format should be
560 followed. Do not use the javadoc style.
561
562 /*!
563  * \brief Do interesting stuff.
564  *
565  * \param thing1 interesting parameter 1.
566  * \param thing2 interesting parameter 2.
567  *
568  * This function does some interesting stuff.
569  *
570  * \retval zero on success
571  * \retval -1 on error.
572  */
573 int ast_interesting_stuff(int thing1, int thing2)
574 {
575         return 0;
576 }
577
578 Notice the use of the \param, \brief, and \return constructs.  These should be
579 used to describe the corresponding pieces of the function being documented.
580 Also notice the blank line after the last \param directive.  All doxygen
581 comments must be in one /*! */ block.  If the function or struct does not need
582 an extended description it can be left out.
583
584 Please make sure to review the doxygen manual and make liberal use of the \a,
585 \code, \c, \b, \note, \li and \e modifiers as appropriate.
586
587 When documenting a 'static' function or an internal structure in a module,
588 use the \internal modifier to ensure that the resulting documentation
589 explicitly says 'for internal use only'.
590
591 Structures should be documented as follows.
592
593 /*!
594  * \brief A very interesting structure.
595  */
596 struct interesting_struct
597 {
598         /*! \brief A data member. */
599         int member1;
600
601         int member2; /*!< \brief Another data member. */
602 }
603
604 Note that /*! */ blocks document the construct immediately following them
605 unless they are written, /*!< */, in which case they document the construct
606 preceding them.
607
608 It is very much preferred that documentation is not done inline, as done in
609 the previous example for member2.  The first reason for this is that it tends
610 to encourage extremely brief, and often pointless, documentation since people
611 try to keep the comment from making the line extremely long.  However, if you
612 insist on using inline comments, please indent the documentation with spaces!
613 That way, all of the comments are properly aligned, regardless of what tab
614 size is being used for viewing the code.
615
616 * Finishing up before you submit your code
617 ------------------------------------------
618
619 - Look at the code once more
620 When you achieve your desired functionality, make another few refactor
621 passes over the code to optimize it.
622
623 - Read the patch
624 Before submitting a patch, *read* the actual patch file to be sure that
625 all the changes you expect to be there are, and that there are no
626 surprising changes you did not expect. During your development, that
627 part of Asterisk may have changed, so make sure you compare with the
628 latest SVN.
629
630 - Listen to advice
631 If you are asked to make changes to your patch, there is a good chance
632 the changes will introduce bugs, check it even more at this stage.
633 Also remember that the bug marshal or co-developer that adds comments
634 is only human, they may be in error :-)
635
636 - Optimize, optimize, optimize
637 If you are going to reuse a computed value, save it in a variable
638 instead of recomputing it over and over.  This can prevent you from
639 making a mistake in subsequent computations, making it easier to correct
640 if the formula has an error and may or may not help optimization but
641 will at least help readability.
642
643 Just an example (so don't over analyze it, that'd be a shame):
644
645 const char *prefix = "pre";
646 const char *postfix = "post";
647 char *newname;
648 char *name = "data";
649
650 if (name && (newname = alloca(strlen(name) + strlen(prefix) + strlen(postfix) + 3)))
651         snprintf(newname, strlen(name) + strlen(prefix) + strlen(postfix) + 3, "%s/%s/%s", prefix, name, postfix);
652
653 ...vs this alternative:
654
655 const char *prefix = "pre";
656 const char *postfix = "post";
657 char *newname;
658 char *name = "data";
659 int len = 0;
660
661 if (name && (len = strlen(name) + strlen(prefix) + strlen(postfix) + 3) && (newname = alloca(len)))
662         snprintf(newname, len, "%s/%s/%s", prefix, name, postfix);
663
664 * Creating new manager events?
665 ------------------------------
666 If you create new AMI events, please read manager.txt. Do not re-use
667 existing headers for new purposes, but please re-use existing headers
668 for the same type of data.
669
670 Manager events that signal a status are required to have one
671 event name, with a status header that shows the status.
672 The old style, with one event named "ThisEventOn" and another named
673 "ThisEventOff", is no longer approved.
674
675 Check manager.txt for more information on manager and existing
676 headers. Please update this file if you add new headers.
677
678 * Locking in Asterisk
679 -----------------------------
680
681 A) Locking Fundamentals
682
683 Asterisk is a heavily multithreaded application.  It makes extensive
684 use of locking to ensure safe access to shared resources between
685 different threads.
686
687 When more that one lock is involved in a given code path, there is the
688 potential for deadlocks.  A deadlock occurs when a thread is stuck
689 waiting for a resource that it will never acquire.  Here is a classic
690 example of a deadlock:
691
692    Thread 1                   Thread 2
693    ------------               ------------
694    Holds Lock A               Holds Lock B
695    Waiting for Lock B         Waiting for Lock A
696
697 In this case, there is a deadlock between threads 1 and 2.
698 This deadlock would have been avoided if both threads had
699 agreed that one must acquire Lock A before Lock B.
700
701 In general, the fundamental rule for dealing with multiple locks is
702
703     an order _must_ be established to acquire locks, and then all threads
704     must respect that order when acquiring locks.
705
706
707 A.1) Establishing a locking order
708
709 Because any ordering for acquiring locks is ok, one could establish
710 the rule arbitrarily, e.g. ordering by address, or by some other criterion.
711 The main issue, though, is defining an order that
712   i) is easy to check at runtime;
713   ii) reflects the order in which the code executes.
714 As an example, if a data structure B is only accessible through a
715 data structure A, and both require locking, then the natural order
716 is locking first A and then B.
717 As another example, if we have some unrelated data structures to
718 be locked in pairs, then a possible order can be based on the address
719 of the data structures themselves.
720
721 B) Minding the boundary between channel drivers and the Asterisk core
722
723 The #1 cause of deadlocks in Asterisk is by not properly following the
724 locking rules that exist at the boundary between Channel Drivers and
725 the Asterisk core.  The Asterisk core allocates an ast_channel, and
726 Channel Drivers allocate "technology specific private data" (PVT) that is
727 associated with an ast_channel.  Typically, both the ast_channel and
728 PVT have their own lock.  There are _many_
729 code paths that require both objects to be locked.
730
731 The locking order in this situation is the following:
732
733     1) ast_channel
734     2) PVT
735
736 Channel Drivers implement the ast_channel_tech interface to provide a
737 channel implementation for Asterisk.  Most of the channel_tech
738 interface callbacks are called with the associated ast_channel
739 locked.  When accessing technology specific data, the PVT can be locked
740 directly because the locking order is respected.
741
742 C) Preventing lock ordering reversals.
743
744 There are some code paths which make it extremely difficult to
745 respect the locking order.
746 Consider for example the following situation:
747
748     1) A message comes in over the "network"
749     2) The Channel Driver (CD) monitor thread receives the message
750     3) The CD associates the message with a PVT and locks the PVT
751     4) While processing the message, the CD must do something that requires
752        locking the ast_channel associated to the PVT
753
754 This is the point that must be handled carefully.
755 The following psuedo-code
756
757       unlock(pvt);
758       lock(ast_channel);
759       lock(pvt);
760
761 is _not_ correct for two reasons:
762
763 i) first and foremost, unlocking the PVT means that other threads
764    can acquire the lock and believe it is safe to modify the
765    associated data. When reacquiring the lock, the original thread
766    might find unexpected changes in the protected data structures.
767    This essentially means that the original thread must behave as if
768    the lock on the pvt was not held, in which case it could have
769    released it itself altogether;
770
771 ii) Asterisk uses the so called "recursive" locks, which allow a thread
772    to issue a lock() call multiple times on the same lock. Recursive
773    locks count the number of calls, and they require an equivalent
774    number of unlock() to be actually released.
775
776    For this reason, just calling unlock() once does not guarantee that the
777    lock is actually released -- it all depends on how many times lock()
778    was called before.
779
780 An alternative, but still incorrect, construct is widely used in
781 the asterisk code to try and improve the situation:
782
783       while (trylock(ast_channel) == FAILURE) {
784           unlock(pvt);
785           usleep(1); /* yield to other threads */
786           lock(pvt);
787       }
788
789 Here the trylock() is non blocking, so we do not deadlock if the ast_channel
790 is already locked by someone else: in this case, we try to unlock the PVT
791 (which happens only if the PVT lock counter is 1), yield the CPU to
792 give other threads a chance to run, and then acquire the lock again.
793
794 This code is not correct for two reasons:
795   i) same as in the previous example, it releases the lock when the thread
796      probably did not expect it;
797   ii) if the PVT lock counter is greater than 1 we will not
798      really release the lock on the PVT. We might be lucky and have the
799      other contender actually release the lock itself, and so we will "win"
800      the race, but if both contenders have their lock counts > 1 then
801      they will loop forever (basically replacing deadlock with livelock).
802
803 Another variant of this code is the following:
804
805     if (trylock(ast_channel) == FAILURE) {
806         unlock(pvt);
807         lock(ast_channel);
808         lock(pvt);
809     }
810
811 which has the same issues as the while(trylock...) code, but just
812 deadlocks instead of looping forever in case of lock counts > 1.
813
814 The deadlock/livelock could be in principle spared if one had an
815 unlock_all() function that calls unlock as many times as needed to
816 actually release the lock, and reports the count. Then we could do:
817
818     if (trylock(ast_channel) == FAILURE) {
819         n = unlock_all(pvt);
820         lock(ast_channel)
821         while (n-- > 0) lock(pvt);
822     }
823
824 The issue with unexpected unlocks remains, though.
825
826 C) Locking multiple channels.
827
828 The next situation to consider is what to do when you need a lock on
829 multiple ast_channels (or multiple unrelated data structures).
830
831 If we are sure that we do not hold any of these locks, then the
832 following construct is sufficient:
833
834          lock(MIN(chan1, chan2));
835          lock(MAX(chan1, chan2));
836
837 That type of code would follow an established locking order of always
838 locking the channel that has a lower address first.  Also keep in mind
839 that to use this construct for channel locking, one would have to go
840 through the entire codebase to ensure that when two channels are locked,
841 this locking order is used.
842    However, if we enter the above section of code with some lock held
843 (which would be incorrect using non-recursive locks, but is completely
844 legal using recursive mutexes) then the locking order is not guaranteed
845 anymore because it depends on which locks we already hold. So we have
846 to go through the same tricks used for the channel+PVT case.
847
848 D) Recommendations
849
850 As you can see from the above discussion, getting locking right is all
851 but easy. So please follow these recommendations when using locks:
852
853 *) Use locks only when really necessary
854     Please try to use locks only when strictly necessary, and only for
855     the minimum amount of time required to run critical sections of code.
856     A common use of locks in the current code is to protect a data structure
857     from being released while you use it.
858     With the use of reference-counted objects (astobj2) this should not be
859     necessary anymore.
860
861 *) Do not sleep while holding a lock
862     If possible, do not run any blocking code while holding a lock,
863     because you will also block other threads trying to access the same
864     lock. In many cases, you can hold a reference to the object to avoid
865     that it is deleted while you sleep, perhaps set a flag in the object
866     itself to report other threads that you have some pending work to
867     complete, then release and acquire the lock around the blocking path,
868     checking the status of the object after you acquire the lock to make
869     sure that you can still perform the operation you wanted to.
870
871 *) Try not to exploit the 'recursive' feature of locks.
872     Recursive locks are very convenient when coding, as you don't have to
873     worry, when entering a section of code, whether or not you already
874     hold the lock -- you can just protect the section with a lock/unlock
875     pair and let the lock counter track things for you.
876        But as you have seen, exploiting the features of recursive locks
877     make it a lot harder to implement proper deadlock avoidance strategies.
878     So please try to analyse your code and determine statically whether you
879     already hold a lock when entering a section of code.
880        If you need to call some function foo() with and without a lock held,
881     you could define two function as below:
882         foo_locked(...) {
883             ... do something, assume lock held
884         }
885
886         foo(...) {
887             lock(xyz)
888             ret = foo_locked(...)
889             unlock(xyz)
890             return ret;
891         }
892     and call them according to the needs.
893
894 *) Document locking rules.
895     Please document the locking order rules are documented for every
896     lock introduced into Asterisk.  This is done almost nowhere in the
897     existing code.  However, it will be expected to be there for newly
898     introduced code.  Over time, this information should be added for
899     all of the existing lock usage.
900
901 -----------------------------------------------------------------------
902
903
904             ------------------------------------
905             ==  PART TWO: BUILD ARCHITECTURE  ==
906             ------------------------------------
907
908 The asterisk build architecture relies on autoconf to detect the
909 system configuration, and on a locally developed tool (menuselect) to
910 select build options and modules list, and on gmake to do the build.
911
912 The first step, usually to be done soon after a checkout, is running
913 "./configure", which will store its findings in two files:
914
915     + include/asterisk/autoconfig.h
916         contains C macros, normally #define HAVE_FOO or HAVE_FOO_H ,
917         for all functions and headers that have been detected at build time.
918         These are meant to be used by C or C++ source files.
919
920     + makeopts
921         contains variables that can be used by Makefiles.
922         In addition to the usual CC, LD, ... variables pointing to
923         the various build tools, and prefix, includedir ... which are
924         useful for generic compiler flags, there are variables
925         for each package detected.
926         These are normally of the form FOO_INCLUDE=... FOO_LIB=...
927         FOO_DIR=... indicating, for each package, the useful libraries
928         and header files.
929
930 The next step is to run "make menuselect", to extract the dependencies existing
931 between files and modules, and to store build options.
932 menuselect produces two files, both to be read by the Makefile:
933
934     + menuselect.makeopts
935         Contains for each subdirectory a list of modules that must be
936         excluded from the build, plus some additional informatiom.
937     + menuselect.makedeps
938         Contains, for each module, a list of packages it depends on.
939         For each of these packages, we can collect the relevant INCLUDE
940         and LIB files from makeopts. This file is based on information
941         in the .c source code files for each module.
942
943 The top level Makefile is in charge of setting up the build environment,
944 creating header files with build options, and recursively invoking the
945 subdir Makefiles to produce modules and the main executable.
946
947 The sources are split in multiple directories, more or less divided by
948 module type (apps/ channels/ funcs/ res/ ...) or by function, for the main
949 binary (main/ pbx/).
950
951
952 TO BE COMPLETED
953
954
955 -----------------------------------------------
956 Welcome to the Asterisk development community!
957 Meet you on the asterisk-dev mailing list.
958 Subscribe at http://lists.digium.com!
959
960 -- The Asterisk.org Development Team