This is release 201008.1
[nobug.git] / README
blob263fa4eb6f6d5dbed51f449332c75a845b0e2073
1 NoBug Reference Manual
2 ======================
3 Christian_Thäter,_Benny_Lyons
5 [abstract]
6 *****************************************************************
7 NoBug is a debugging library for instrumenting C and C++ programs
8 inspired by ideas originating from Design-by-Contract.
9 *****************************************************************
11 [quote]
12 __________________________________________________________________
13 Everyone makes mistakes, but with NoBug you won't make them twice!
14 __________________________________________________________________
16 Contents
17 --------
19 Overview
20 --------
22 The following features are provided by NoBug:
24   * Three different check levels: from detailed to final no-overhead
25   * Scope tags: tell whenever a function or loop is considered to be bug free
26   * Precondition, Postcondition and Invariant checks and generic assertions
27   * Data structures can be dumped
28   * Application activities can be logged
29   * Runtime customizable logging via an environment variable
30   * Different logging targets to stderr, syslog, debugger, ...
31   * Annotation of your sourcecode about known bugs, things to do, etc.
32   * Tracking resources (files, locks, etc.) used by your program; help in
33     detecting misuse
34   * Detecting potential deadlocks
35   * Simulate errors by injecting faults
36   * Coverage checking to find out if all (instrumentated) errors are properly handled
37   * Additionally, the NoBug project is used to maintain a script and
38     some tools to setup testsuites
40 In contrast to traditional debuggers, NoBug is a non-interactive debugger that
41 is linked to your application doing hard-coded tests in an efficient way
42 without much overhead. Depending on the build level you choose, NoBug features
43 will be an integral part of your application making it possible to gather
44 debugging data for each stage of the application development, including
45 collecting debugging info for finally deployed applications.
48 .What NoBug can't do
50 NoBug is a (macro-)library, it is not a C/C++ language extension. This
51 means that code must be called at runtime to benefit from the set up
52 contracts. What's not tested is likely slipping through the net. Being
53 part of the program itself, it is affected by memory corruption.
54 Certain kinds of misuse may introduce new bugs (assert expressions with
55 side effects for example).
58 Support
59 ~~~~~~~
61 When you need help with NoBug, have some ideas about potential features or
62 think you found a bug, then you can contact the NoBug community and developers
63 by sending mail to the NoBug mailinglist. Subscription is available at
64 http://lists.pipapo.org/cgi-bin/mailman/listinfo/nobug[].
66 Building and Installing
67 -----------------------
69 Supported Platforms
70 ~~~~~~~~~~~~~~~~~~~
72 NoBug has been developed on Linux, using GCC. It should be possible to port
73 it to any other POSIX compliant operating system. Platform/compiler
74 specific things are kept optional. Currently Linux with a GCC that conforms to
75 C99 is supported for both 32 and 64 bit architectures. For non-GCC compilers,
76 some features are not available or degraded.
78 [frame="topbot",options="header", cols="<,<,<,<"]
79 |=================================================================================
80 |CPU    |OS          |Compiler    |State
81 |x86_64 |Debian      |gcc4        |supported footnote:[Reference Platform]
82 |x86    |other Linux |gcc4        |supported footnote:[Please report distro specific problems]
83 |armel  |maemo5      |gcc4        |supported footnote:[check fails in SDK (emulator bug)]
84 |x86*   |Mac OS X    |gcc4        |supported
85 |x86    |OpenSolaris |gcc4        |supported
86 |x86    |OpenSolaris |suncc       |mostly    footnote:[some features are not
87 available, needs more testing]
88 |       |*BSD        |            |planned   footnote:[Need volunteer for testing]
89 |=================================================================================
91 NoBug has few mandatory dependencies on other software and libraries,
92 some things such as valgrind support are optional and should be automatically
93 detected by `./configure`. Nevertheless it
94 requires 'pkg-config' to be installed or you'll get some weird errors at
95 bootstrapping (`autoreconf`) already.
98 Release Tarballs
99 ~~~~~~~~~~~~~~~~
101 Releases are available at:
102  http://www.pipapo.org/nobug-releases/[]
104 Gpg signed tarballs are being used for distribution. The first step involves
105 checking the signature:
107  $ gpg nobug-VERSION.tar.gz.gpg
109 This will produce a nobug-VERSION.tar.gz and report if the signature could be
110 validated.
112 Since they are built with GNU Autotools, the usual build and install procedure
113 will work:
115  $ tar xzvf nobug-VERSION.tar.gz
116  $ cd nobug-VERSION
117  $ mkdir -p build
118  $ cd build
119  $ ../configure
120  $ make
121  $ make check           # optional, runs the testsuite
122  $ make install         # to be done as root,
123                         # depending on distribution and setup
126 Development Version via Git
127 ~~~~~~~~~~~~~~~~~~~~~~~~~~~
129 You can obtain a development version using Git.  The Git repository can be
130 cloned from `git://git.pipapo.org/nobug`.
132 Clone the Git repository with:
134  $ git clone git://git.pipapo.org/nobug
136 After cloning the repository, then bootstrap the Autotools:
138  $ cd nobug
139  $ autoreconf -i                # creates the configure file
141 Then the usual
143  $ cd build && ../configure && make && make install
145 (as above) will work. Careful users may run
147  $ make check
149 to run a testsuite before installing.
152 Keeping Git Up To Date
153 ^^^^^^^^^^^^^^^^^^^^^^
155 To update to any new revision, just enter the nobug dir and
157  $ git pull
159 After that you can build as above
161  $ cd build && ../configure && make && make install
163 This default pull will update from the 'master' branch which is meant to be an
164 on-going stable version (latest release and bugfixes).
166 Major new releases are assembled in the 'devel' branch, generally this is not
167 considered production ready.
169 All other branches are volatile and may be deleted or rebased anytime without
170 further notice.
173 What Is Installed
174 ~~~~~~~~~~~~~~~~~
176 Currently, NoBug installs the following:
178   * A single nobug.h headerfile. Include this in your code.
179   * Static libraries. Statically link these to your application:
180     - `libnobug.a` for singlethreaded programs.
181     - `libnobugmt.a` for multithreaded programs.
182   * Dynamic Libraries. Dynamically link these to your application:
183     - `libnobug.so` for singlethreaded programs.
184     - `libnobugmt.so` for multithreaded programs.
185     - associated libtool descriptors (`libnobug*.la`)
186   * Pkgconfig control files:
187     - `nobug.pc` for singlethreaded programs.
188     - `nobugmt.pc` for multithreaded programs.
189   * The `nobug_rbdump` utility to inspect NoBug ringbuffers.
192 Generating This Documentation
193 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
195 There are Makefile targets for generating the documentation, either one of the
196 following does what you might expect:
198  $ make nobug_manual.txt nobug_manual.html nobug_manual.pdf
200 Alternatively, you can generate all the documentation in one go as follows:
202   $ make doc
204 Building the documentation has quite some more dependencies than building
205 NoBug itself. Unless you are a packager you may prefer to refer to the online
206 documentation or the shipped 'README' which is the complete NoBug reference
207 manual in text form. Generating the documentation requires: gawk, asciidoc,
208 graphviz and LaTeX. Check the `[header]` section of doc/latex.conf for required
209 packages.
211 Using NoBug
212 -----------
214 Your application will have to include the header file 'nobug.h' before NoBug
215 can be used. Prior including this, a Build-level has to be choosen,
216 Build-levels are discussed later, c.f., xref:buildlevel[buildlevel].
217 Build-levels are used to define the amount of information NoBug provides to
218 you. Maximum information is generally required while developing an application
219 and the ALPHA build-level is most apropriate during this phase; whereas the
220 released phase of an application will usually only require sparse information,
221 for which the RELEASE build-level has been conceived.
223 A build-level must always be specified, otherwise the compiler will complain
224 while attempting to compile your application.  You can specifiy a build level in
225 one of two ways: use a define statement in one of your modules, or pass the
226 build-level using the -D flag to your compiler.  Assuming we'd like to select
227 the ALPHA build-level in your application, then your module would assume the
228 following form:
230  #define EBUG_ALPHA
231  #include <nobug.h>
233 Subsequently you'll have to link the appropriate library to your application.
235 A number of different libraries are available to link depending on whether you
236 require to statically or dynamically link, or whether your application is multi
237 or single threaded.  The link order is important on your link line.  Link the NoBug
238 library 'after' your application's modules.  Here's how to statically link,
239 single-threaded applications:
241 [source,sh]
242 ----------------
243 gcc -o mybinary  $(WHATEVER_FLAGS) \
244        mymodules.o ... -lnobug
245 ----------------
247 However, for more flexibility in selecting a build-level, you might wish to
248 define various targets in your makefile, one for each build-level.  In such
249 cases, the -D flag in your makefile is most appropriate; so your link line for
250 an ALPHA build with multi-threaded support would look like the following:
252 [source,sh]
253 ----------------
254 gcc -o mybinary -DEBUG_ALPHA $(WHATEVER_FLAGS) \
255        mymodules.o -lnobugmt
256 ----------------
258 The NoBug libraries must be initialised before they can be used. To initialise
259 it call the `NOBUG_INIT` macro, which must be used before any NoBug features
260 can be used or any thread is created. This is discussed in more detail in the
261 xref:multithreading[multithreading] chapter.
263 So putting all this together, our application using NoBug might look something
264 like the following:
267 [source,C]
268 ----------------
269 #define EBUG_ALPHA   /* If we don't use the -D Flag to cc */
270 #include <nobug.h>   /* Include the NoBug API */
272 int main()
274         NOBUG_INIT;  /* Initialise NoBug libs */
276         ...
278 ----------------
282 Many aspects of NoBug can be configured by overriding macros before 'nobug.h' is
283 included.
286 Autotools Support
287 ~~~~~~~~~~~~~~~~~
289 A project using NoBug can use autoconf to check for execinfo and
290 valgrind:
292 [source,sh]
293 ----------------
294 AC_CHECK_HEADER([execinfo.h], AC_DEFINE(HAVE_EXECINFO_H))
295 PKG_CHECK_MODULES(VALGRIND, [valgrind],
296                             [AC_DEFINE(HAVE_VALGRIND_H)])
297 ----------------
299 For Multithreaded programs, you should also check for the availability of pthreads
300 and flavour with the `ACX_PTHREAD` maxro, see:
302 +http://ac-archive.sourceforge.net/ac-archive/acx_pthread.html[]+
304 When the resulting `HAVE_PTHREAD`, `HAVE_EXECINFO_H` and
305 `HAVE_VALGRIND_H` are defined by the configure script, the
306 relevant features become available.
308 `NOBUG_USE_PTHREAD`, `NOBUG_USE_VALGRIND` and `NOBUG_USE_EXECINFO` will be
309 defined depeding on the information gathered by configuration. If you do not
310 want to use any of these features in NoBug, you can override these macros by
311 setting them to `0` before including 'nobug.h'.
313 If `NVALGRIND` is defined, there will be no support for valgrind.
315 There are many other macros which can be set and overridden by the user to
316 control behavior. Your help would be appreciated in expanding this documentation
317 if you find some features useful; or simply contact any of the authors.
320 .Using Nobug from a Project using autoconf/automake
322 Here is a rather elaborate snippet how to put this all together into a
323 `configure.ac` file:
325 [source,sh]
326 ----------------
327 # define autoheader templates for the config macros
328 AH_TEMPLATE(EBUG_ALPHA,
329         [Define to 1 for selecting NoBug ALPHA build level])
330 AH_TEMPLATE(EBUG_BETA,
331         [Define to 1 for selecting NoBug BETA build level])
332 AH_TEMPLATE(NDEBUG,
333         [Define to 1 for selecting NoBug RELEASE build level])
335 # set configure options up
336 AC_ARG_ENABLE(alpha, AC_HELP_STRING([--enable-alpha],
337                 [select NoBug ALPHA build level]),
338         nobug_level=alpha
339         AC_DEFINE(EBUG_ALPHA),
341 AC_ARG_ENABLE(beta, AC_HELP_STRING([--enable-beta],
342                 [select NoBug BETA build level]),
343         nobug_level=beta
344         AC_DEFINE(EBUG_BETA),
346 AC_ARG_ENABLE(release, AC_HELP_STRING([--enable-release],
347                 [select NoBug RELEASE build level]),
348         nobug_level=release
349         AC_DEFINE(NDEBUG),
351 # default to ALPHA
352         nobug_level=alpha
353         AC_DEFINE(EBUG_ALPHA)
354 )])])
356 # check for required and optional packages
357 ACX_PTHREAD
358 AC_CHECK_HEADER([execinfo.h], AC_DEFINE(HAVE_EXECINFO_H))
359 PKG_CHECK_MODULES(VALGRIND, [valgrind],
360         AC_DEFINE(HAVE_VALGRIND_H))
362 # finally check for nobug itself, multithreaded here
363 PKG_CHECK_MODULES(NOBUGMT_EXAMPLE, [nobugmt >= 201006.1],
364         AC_DEFINE(HAVE_NOBUGMT_H),
365         AC_MSG_ERROR([NoBug pkg-config metadata missing])
367 ----------------
369 Additional Tools
370 ~~~~~~~~~~~~~~~~
372 Various peripheral tools can be used by NoBug depending on the requirements
373 of the application and the detail desired by the user.  Such tools can provide
374 additional, detailed information on the application and its behaviour.
375 However, some applications may not require such detail and the associated
376 overhead in information, and users may decide to omit excess information by
377 excluding such tools.
379 At the moment NoBug supports the optional inclusion of gdb, valgrind and support
380 for multi-threaded applications and the information that can be provided by
381 these tools.  However, support for other tools may be supplied in the future,
382 e.g. the dbx debugger on OpenSolaris.
385 Link Appropriate Library
386 ~~~~~~~~~~~~~~~~~~~~~~~~
388 Finally, the appropriate library (for either single or multi-threaded
389 applications) is linked to the project.
391    *libnobug*:: Link-in this library for single threaded applications.
392    *libnobugmt*:: Link with this library for multi-threaded applications.
394 NoBug installed static and dynamic libraries. When your application
395 uses multiple dynamic libraries which use NoBug or you build a dynamic
396 library, then you have to link against the dynamic library.
398 You can use the `pkg-config` tool to gather information about NoBug in
399 your build system. For example you can query the NoBug version which is
400 installed on your system:
402  $ pkg-config --modversion nobug
403  201006.1
405 Initialization
406 --------------
408 Global Initialization
409 ~~~~~~~~~~~~~~~~~~~~~
411 Before anything from NoBug can be used, NoBug must be initialised. This
412 is archived by calling the `NOBUG_INIT()` macro before using any other of the
413 NoBug facilities.
415 `NOBUG_INIT` can be called more than once, subsequent calls will be a no-op,
416 thus initialising in main and in libraries won't interfere with one another.
418 Care must be taken when one already using NoBug features from dynamic
419 initialized things in C++, one has to ensure that NoBug gets initialized first
420 possibly by pulling up a singleton at very first.
423 Destroying NoBug
424 ~~~~~~~~~~~~~~~~
426 Since NoBug is intended to be available throughout its whole lifetime,
427 destroying it is not to be advised. Nevertheless, there is a destroy function
429  void nobug_destroy (void);
431 to shutdown NoBug, and this frees all resources associated with it.
432 This is mostly used in the NoBug testsuite itself to check for leaks,
433 and it might be useful for other programs which employ some kind of
434 leak checker.
437 Init logging Flags
438 ~~~~~~~~~~~~~~~~~~
440 If you want to use environment variable controlled debuging, then you have to
441 initialize each defined flag with
443   NOBUG_INIT_FLAG(flagname)
447   NOBUG_INIT_FLAG_LIMIT(flagname, default)
449 or one of the C++ compatibility macros.
451 This is documented later in the xref:logconfig[logging configuration] chapter.
454 Threads
455 ~~~~~~~
457 In Multithreaded programs you should assign an identifier to each
458 thread. A thread identifier is a string which will be automatically
459 appended with an underscore and an incrementing integer. It is is
460 created using the following:
462   NOBUG_THREAD_ID_SET(name)
464 For example, calling `NOBUG_THREAD_ID_SET("worker")` will result in a thread
465 identifier 'worker_1'.
467 If you don't set an identifier, then NoBug will automatically assign
468 one.  This is further documented in the xref:multithreading[multi threading]
469 section of this manual.
472 .Initialization example
474 Thus the boilerplate code to pulling up NoBug in a multithreaded program looks
475 like (omit `NOBUG_THREAD_ID_SET()` in single threaded programs):
476 [source,C]
477 -------------------------------------------------------
478 #include <nobug.h>
479 NOBUG_DEFINE_FLAG(example);
483 int main()
485     NOBUG_INIT();
486     NOBUG_THREAD_ID_SET("main");
487     NOBUG_INIT_FLAG(example);
489     ...
491 -------------------------------------------------------
493 Debugging Information Granularity: The Build Levels
494 ---------------------------------------------------
496 There are three different levels of debugging information available: alpha, beta
497 and release.  One of these levels must be specified before compiling, otherwise
498 an error while compiling will occur.
501   *ALPHA*::
502         This debugging level is envisaged for the development phase of a project
503         where exhaustive testing and logging are required. All NoBug features
504         are enabled.
505   *BETA*::
506         This debugging level is more appropriate for projects beyond the
507         development phase and ready for field-testing with users willing to
508         test the software. The most expensive debugging features are disabled
509         at this level.
510   *RELEASE*::
511         This level is for final, end-users. Logging is mostly retained but
512         assertions and other checking is disabled.
514 .Select a Build Level
515 A logging level can be selected by either using a define before including
516 `nobug.h`, or by passing the appropriate level using the -D switch
517 to the compiler:
519     *ALPHA*::
520        `-DEBUG_ALPHA` / `#define EBUG_ALPHA`
522     *BETA*::
523        `-DEBUG_BETA` / `#define EBUG_BETA`
525     *RELEASE*::
526        `-DNDEBUG` / `#define NDEBUG`
528 If a log level has not been selected, NoBug will abort the
529 compilation with an error.
531 Logging Concepts
532 ----------------
534 Nearly all NoBug Macros emit some xref:logformat[log message]. NoBug gives
535 the user fine grained control over these log messages to display only
536 interesting information without loosing details.
538 Log messages can be routed to various destinations.  The following destintaions
539 are available:
541   *RINGBUFFER*::
542         The underlying storage backend. Messages are appended to the
543         end of the buffer, overwriting older messages at the front of
544         the buffer. NoBug comes with a highly efficient ringbuffer
545         implementation. This ringbuffer is temporary by default but
546         can be made persistent on disk which can be inspected with the
547         'nobug_rbdump' tool.
549   *CONSOLE*::
550         This is either just stderr, or, if running under a supported
551         debugger, the debuggers facilities to print messages will be used.
553   *FILE*::
554         The user can open files for log messages.
556   *SYSLOG*::
557         Messages are sent to the standard system logging daemon.
559   *APPLICATION*::
560         There are hooks which allow the programmer to catch logmessages and
561         display them in an application which are defined by the application.
563 Each log message has a priority describing its severity in the same way as
564 syslog messages do.
566 All non-fatal messages are associated with a programmer defined flag
567 describing the source of the message (subsystem, module, ...). This is
568 referred to as 'channels' in other logging systems. xref:logflags[Flags] make
569 it possible to configure logging in much detail at runtime.
571 Putting this all together: A user can define which source/flag will be logged at
572 what priority level and to which destination. To make this all easier, NoBug
573 tries to provide reasonable defaults.
575 Configuration
576 ~~~~~~~~~~~~~
578 .Log Levels
580 Each log macro has an explicit or implicit log-level which
581 correspondends to syslog levels. Logging is only emitted when the
582 message is more severe or the same as a defined limit.
584 INDEX Default levels for logging;loggingleveldefaults; table showing defaults log levels
585 [frame="topbot",options="header"]
586 |===============================================================================
587 |            |ALPHA    |BETA    |RELEASE
588 |ringbuffer footnote:[ringbuffer must always be most verbose] |TRACE    |INFO    |NOTICE
589 |console     |INFO     |NOTICE  |-1 footnote:[no log to console in release]
590 |file        |TRACE    |NOTICE  |WARNING
591 |syslog      |-1 footnote:[no syslog for test runs]      |NOTICE  |WARNING
592 |application |INFO     |WARNING |ERROR
593 |===============================================================================
595 Depending on the build level, there is a default logging target and a default
596 limit which is selected when the user doesn't specify one.
598 .The following default limits are
600   In *ALPHA* builds::
601      `NOBUG_LOG_LIMIT_ALPHA` is used which defaults to `LOG_INFO`
602   In *BETA* builds::
603      `NOBUG_LOG_LIMIT_BETA` is used and defaults to `LOG_WARNING`
604   In *RELEASE* builds::
605      `NOBUG_LOG_LIMIT_RELEASE` is used and defaults to `LOG_CRIT`
607 .The default targets are
609   In *ALPHA* builds::
610     `NOBUG_LOG_TARGET_ALPHA` defaulting to `NOBUG_TARGET_CONSOLE`
611   In *BETA* builds::
612      `NOBUG_LOG_TARGET_BETA` defaulting to `NOBUG_TARGET_FILE`
613   In *RELEASE* builds::
614      `NOBUG_LOG_TARGET_RELEASE` defaulting to `NOBUG_TARGET_SYSLOG`
616 You can override all these values with other limits or targets before
617 including 'nobug.h'. As an alternative, `NOBUG_LOG_LIMIT` and
618 `NOBUG_LOG_TARGET` can be defined to override all defaults at once.
620 Log Flags
621 ~~~~~~~~~
623 Flags are used to inform NoBug about subsystems/modules or even finer
624 grained sections of the code. These are referred to as 'channels' in other
625 logging libraries.
627 Flags are generally used as follows:
629     . Declare the flag.
630     . Define the flag.
631     . Initialise the flag.
633 To declare a flag, it is suggested to do so in a header file:
635  NOBUG_DECLARE_FLAG(flagname)
637 The flag should then be defined most appropriately in some implementation file
638 by using one of the following macros:
640  NOBUG_DEFINE_FLAG(flagname)
644  NOBUG_DEFINE_FLAG_LIMIT(flagname, limit)
646 Moreover, macros are available that accept a 'parent' flag as a parameter, which is then
647 used to initialize the defaults from another flag:
649  NOBUG_DEFINE_FLAG_PARENT(flagname, parent)
653  NOBUG_DEFINE_FLAG_PARENT_LIMIT(flagname, parent, limit)
655 This can be used to create hierarchies of flags.
658 C\++ support, C++ logflags
659 ^^^^^^^^^^^^^^^^^^^^^^^^^^
661 Additional macros are available for applications written in C++:
663  NOBUG_CPP_DEFINE_FLAG(name)
664  NOBUG_CPP_DEFINE_FLAG_PARENT(name, parent)
665  NOBUG_CPP_DEFINE_FLAG_LIMIT(name, default)
666  NOBUG_CPP_DEFINE_FLAG_PARENT_LIMIT(name, parent, default)
668 These macros statically initialize the flags when they are defined, there is no
669 need to call `NOBUG_INIT_FLAG()` (see below).
672 Logging Flag Initialization
673 ^^^^^^^^^^^^^^^^^^^^^^^^^^^
675 After a flag has been declared and defined, it has to be initialised:
677  NOBUG_INIT_FLAG(flagname)
681  NOBUG_INIT_FLAG_LIMIT(flagname, default)
683 Use either of these macros once at the begining your program for each flag.
684 This macros will parse the '$NOBUG_LOG' envirionment variable at runtime
685 initializing the given flag dynamically.
687 For flags defined with `NOBUG_DEFINE_FLAG(flagname)` the defaults are
688 initialized as in the xref:loggingleveldefaults[table above], while
689 `NOBUG_DEFINE_FLAG_LIMIT(flagname, level)` is used to initialize the default
690 target (depending on build level) to `level`.
693 Force declarations only
694 ^^^^^^^^^^^^^^^^^^^^^^^
696 When `NOBUG_DECLARE_ONLY` defined to be `1` then all flag definitions here become
697 declarations only. When this is defined to be `0` (which is the default) then
698 all definitions behave as described. This can be used to construct a
699 headerfile which only contains definitions, but, by default, yield only
700 declarations. This provides one convenient single point to maintain flag
701 configurations.
703 .flags.h
704 [source,c]
705 ----
706 #include <nobug.h>
709  if not included from flags.c then declare the flags,
710  else define them
711  */
712 #ifndef FLAGS_C
713 #define NOBUG_DECLARE_ONLY 1
714 #endif
716 /* use only DEFINE_FLAG here */
717 NOBUG_DEFINE_FLAG(example);
720  Reset it to 0 to cause no trouble
721  */
722 #ifndef FLAGS_C
723 #undef NOBUG_DECLARE_ONLY
724 #define NOBUG_DECLARE_ONLY 0
725 #endif
726 ----
728 .flags.c
729 [source,C]
730 ----
731 #define FLAGS_C
732 #include "flags.h"
734 ----
736 Controlling what gets logged
737 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
739 The `NOBUG_INIT_FLAG...` series of macros parse the environment variable
740 '$NOBUG_LOG'. This enviromnet variable is thus used to configure what is
741 logged at runtime. Its syntax is as following:
743 [source,prolog]
744 ----
745 logdecl_list --> logdecl, any( ',' logdecl_list).
747 logdecl --> flag, opt(limitdecl, any(targetdecl)).
749 flag --> "identifier of a flag".
751 limitdecl --> ':', "LIMITNAME".
753 targetdecl --> '@', "targetname", opt(targetopts).
755 targetopts --> '(', "options for target", ')', opt(targetopts).
756 ----
758 Roughly speaking, '$NOBUG_LOG' contains a comma separated list of declarations
759 for flags, which is the name of the flag followed by a limit which is all
760 written in uppercase letters and preceeded by a colon, followed by target
761 declarations which are the names of targets, introduced by an at sign. Target
762 declarations can have options, which are described in the next section. Limit
763 and target declarations are optional and defaults are selected from the
764 xref:loggingleveldefaults[table above]. The defaults presented here are
765 currently an approximation of what might be viable. The default values used
766 here may be redefined in a future release.
768 Targets and Options
769 ^^^^^^^^^^^^^^^^^^^
771 The Following options are available:
773 `@ringbuffer`::
774   `(file=`'filename'`)`:::
775     set 'filename' for the backing ringbuffer
776   `(size=`'nnn'`)`:::
777     set size of the ringbuffer to 'nnn' bytes, rounded-off up to the next page
778     boudary
779   `(append)`:::
780     don't erase existing ringbuffer, start where it left off
781   `(keep)`:::
782     keep file after application ends
783   `(temp)`:::
784     unlink file instantly at creation
786 The default ringbuffer is a temporary file in '/tmp' with the `temp` option.
787 This means it will not be available and accessible for inspection, but it also
788 won't leave any stale data behind when the application ends.
791 `@console`::
792   `(fd=`'n'`)`:::
793     redirect console output to fd 'n'
795 When running under a debugger, NoBug tries to use debugger facilities
796 to print console messages.
798 `@file`::
799   `(name=`'filename'`)`:::
800     log to 'filename'
801   `(append)`:::
802     append to (existing) logfile
804 `@syslog`::
805   `(ident=`'name'`)`:::
806     global prefix for syslog
807   `(cons)`:::
808     log to system console if syslog is down
809   `(pid)`:::
810     include the process identifier in the log
811   `(perror)`:::
812     log to stderr as well (Not available on all systems)
815 .How $NOBUG_LOG is used
816 [source,sh]
817 ----
818 # set limit to the default target and default limit
819 # (see table above)
820 NOBUG_LOG='flag,other'
822 # set the limit of the default target to DEBUG
823 NOBUG_LOG='flag:DEBUG'
825 # set console and syslog limits for flag to DEBUG
826 NOBUG_LOG='flag:DEBUG@console@syslog'
828 # trace 'other' to a persistent ringbuffer
829 NOBUG_LOG=\
830  'other:TRACE@ringbuffer(file=log.rb)(size=8192)(keep)'
831 ----
832 Predefined Flags
833 ~~~~~~~~~~~~~~~~
835 There are some debugging flags which are predefined by NoBug.
837 .NOBUG_ON
839 The flag `NOBUG_ON` is always enabled at LOG_DEBUG level. This is
840 static and can not be changed.
842 .NOBUG_ANN
844 The flag `NOBUG_ANN` is used for the source annotations. This is
845 static and can not be changed. It differs from `NOBUG_ON` as in
846 never logging to syslog and only define a LOG_WARNING limit for the
847 application callback.
849 .nobug
851 Actions on NoBug itself will be logged under the `nobug` flag itself.
852 To see whats going on you can enable it with `NOBUG_LOG=nobug:TRACE`.
853 This is particulary useful to check if `NOBUG_INIT_FLAG()` is called on all flags.
856 .Using log flags (example.c)
857 [source,c]
858 ----
859 #include <nobug.h>
861 NOBUG_DEFINE_FLAG (test);
863 int main()
865    NOBUG_INIT;
866    NOBUG_INIT_FLAG (test);
868    TRACE (test, "Logging enabled");
869    TRACE (NOBUG_ON, "Always on");
870    return 0;
872 ----
874 .test it:
875 [source,sh]
876 ----
877 $ cc -DEBUG_ALPHA -lnobug example.c
878 $ ./a.out
879 0000000003: TRACE: example.c:11: -: main: Always on
881 $ NOBUG_LOG=test:TRACE ./a.out
882 0000000003: TRACE: example.c:10: -: main: Logging enabled
883 0000000004: TRACE: example.c:11: -: main: Always on
884 ----
886 Log Line Format
887 ~~~~~~~~~~~~~~~
889 Logging follows a rather rigid format and is not configurable. This is
890 intentional to make it easier to compare and process logs afterwards. NoBug is
891 designed with the goal to effectively do very fine grained logging and then
892 analyze this logs later, either manually or with further tools.
894 A typical log looks like:
896  0000000003: TRACE: test.c:10: thread_1: main: message
897  0000000003! TRACE: test.c:10: thread_1: main: continued
898  0000000005: NOTICE: test.c:15: thread_1: main: next
900 The components are delimited by ": " or in one case by "! " are as following:
902  . *Sequence Number* +
903    Each logging event increments a counter, for preformance (and privacy)
904    reasons we do not use timestamps here. The sequence number is represented by
905    ten decimal digits, overflows are not specially handled. There is a special
906    case that when the final message (see below) spans more log lines, then the
907    delimiter after the sequence number is a "! " and not ": ". The sequence
908    numbers in a log can be sparse because not every event is send to the log,
909    the left out lines are still available in the ringbuffer.
911  . *NoBug Facility* +
912    Describes what NoBug macro produced the output. This can be a simple
913    annotation or logging as well as assertions or one of the more complex
914    NoBug facilities.
916  . *File and Linenumber* +
917    The filename is only printed without it's path. This is important for some
918    reasons. First it makes the log vastly more readable and second depending
919    on source location and build system and configuration thereof paths are not
920    easily reproducible, this makes it hard to use simple tools like grep or
921    diff on logs generated on different systems. For some messages the filename
922    and/or the linenumber is not available or meaningless, a "-" is used then.
924  . *Thread Identifier* +
925    Shows which thread generated this message. The single threaded version of
926    NoBug uses always "-".
928  . *Function Name* +
929    Gives the function in which the logging occured. For a lot macros it is
930    possible to pass a context (file, line and function name) around to make it
931    possible to delegate validation and logging to some special functions while
932    still being able to present the context where the call originated. NoBug
933    only uses the function name as identifier here no pretty printed prototype
934    or demangled C++ method. The reason for this is that neither is well
935    specified an may yield to non unique results which may even interfere with
936    the logging format syntax and thus make it very unreliable to write tools
937    to process logs. Some contexts dont provide a function name, a "-" is used
938    then.
940  . *Message* +
941    The rest of the log line is the user-defined and optional message part.
942    There are no constraints on the format and one should constrain himself to
943    print only meaningful textual information. Embedded newlines will always be
944    translated into a new logging line as shown in the example above.
946 Macros Overview
947 ---------------
949 The NoBug interface is almost completely implemented using
950 preprocessor macros. This is required because NoBug uses the
951 +$$__FILE__$$+, +$$__LINE__$$+ and +$$__func__$$+ macros to
952 log information on the current file, line number and function.
953 Moreover, all the flat namespace uppercase identifiers make it easy
954 to recognise the macros in source code.
956 All macros are available without condition with a `NOBUG_...` prefix. Many
957 macros (the common cases) are also available without this prefix as a
958 convenience, however macros without this prefix must not have been previously
959 defined. When `NOBUG_DISABLE_SHORTNAMES` is defined before including
960 'nobug.h', then only the `NOBUG_` prefixed macros are available and the short
961 forms will never be defined.
963 A set of macros are provided by NoBug that are postfixed by `..._IF`. These
964 macros have the following form:
966   * `..._IF(when, ...)`
968 They perform the desired action only if `when` is true. For example:
970   * `REQUIRE_IF(foo != NULL, foo->something == constrained)`
972 The assertion will only be performed if `foo` is non `NULL`.
974 NoBug also contains a facility to pass the xref:NOBUGCONTEXT[source context]
975 (file, line, function) around, this can be used to write functions which
976 handle things where one is more interested in the context of the caller rather
977 than the location where the macro appears.
979 These macros are postfixed with `..._CTX` and take an extra context
980 parameter (usually at last but before the logging format specifier and
981 any variable argument list). The context parameter must be of type
982 `const struct nobug_context`.
984 When the `_CTX` context form is used together with the conditional `_IF`
985 form then the suffix of the macros is always `..._IF_CTX`.
987 Macros that can accept a context have no short form and must always be
988 prefixed with `NOBUG_...`.
990 Parameters types
991 ~~~~~~~~~~~~~~~~
993 We use names for parameters which describe their type. These names are
994 orthogonal through all macro definitions.
996 [cols="1,5",frame="topbot"]
997 |==============================================================================
998 |`when`    |Assertion is only performed if expression `when` is true at runtime
999 |`expr`    |Test without side effects
1000 |`flag`    |Destination flag for control logging at runtime
1001 |`type`    |Data type to be checked as a single identifier name
1002 |`pointer` |Pointer to type
1003 |`lvl`     |Log level
1004 |`depth`   |Depth for invariants and dumps
1005 |`context` |Source context of type `struct nobug_context`
1006 |`...`     |printf-like format string followed by its arguments
1007 |==============================================================================
1009 Source Contexts
1010 ~~~~~~~~~~~~~~~
1012  NOBUG_CONTEXT
1013  NOBUG_CONTEXT_NOFUNC
1015 NoBug passes information about the source location of a given statement in
1016 `const struct nobug_context` structures. These can be generated with
1017 `NOBUG_CONTEXT` or `NOBUG_CONTEXT_NOFUNC`. The later one doesn't define a
1018 function name and must be used when the function context is not available
1019 like in static initialization etc..
1021 Macros for Assertions
1022 ---------------------
1024 The assertion set of macros provide a convenient status check on whether
1025 to continue running, or abort execution as some condition was not fulfilled.
1026 Assertion failures are fatal and must abort the application immediately by
1027 calling the xref:ABORT[NOBUG_ABORT] macro which in turn may call a user defined
1028 xref:abortcallback[abort hook].
1030 .CHECK
1032  CHECK(expr, ...)
1033  CHECK_IF(when, expr, ...)
1035 This assertion is never optimized out. Its main purpose is in implementing
1036 test suites where one would like to assert tests independent of the build level.
1038 .REQUIRE
1040  REQUIRE(expr, ...)
1041  REQUIRE_IF(when, expr, ...)
1042  NOBUG_REQUIRE_CTX(expr, context,...)
1043  NOBUG_REQUIRE_IF_CTX(when, expr, context, ...)
1045 Precondition (input) check. Use these macros to validate the input a
1046 function receives. The checks are enabled in *ALPHA* and *BETA* builds,
1047 but have not effect in *RELEASE* builds.
1049 .ENSURE
1051  ENSURE(expr, ...)
1052  ENSURE_IF(when, expr, ...)
1053  NOBUG_ENSURE_CTX(expr, context, ...)
1054  NOBUG_ENSURE_IF_CTX(when, expr, context, ...)
1056 Postcondition (progress/output) check. Use these macros to validate the
1057 data a function produces (example: return value). `ENSURE` is enabled
1058 unconditionally in *ALPHA* builds and have no effect in *BETA* builds for
1059 scopes which are tagged as `CHECKED`.
1061 The `ENSURE_IF` variants are enabled in *ALPHA* and *BETA* builds.
1063 In *RELEASE* builds these checks are optimized out.
1065 .ASSERT
1067  ASSERT(expr, ...)
1068  ASSERT_IF(when, expr, ...)
1069  NOBUG_ASSERT_CTX(expr, context, ...)
1070  NOBUG_ASSERT_IF_CTX(when, expr, context, ...)
1072 Generic check. Use these macros when you want to validate something
1073 which doesn't fall into one of the above categories. Generally to be
1074 avoided! The checks are enabled in *ALPHA* and *BETA* builds and
1075 have no effect in *RELEASE* builds.
1077 .assert
1079  assert(expr)
1081 NoBug overrides the standard `assert` macro, using `NOBUG_ASSERT`.
1082 This is just a compatibility feature, its use is not suggested.
1084 .INVARIANT
1086  INVARIANT(type, pointer, depth)
1087  INVARIANT_IF(when,type, pointer, depth)
1088  INVARIANT_ASSERT(expr, ...)
1090 Checking invariants. You can provide more complex checking functions
1091 which test the validity of datastructures. Invariants are only enabled
1092 in *ALPHA* builds for scopes which are not tagged as `CHECKED` and
1093 otherwise optimized out.
1095  TODO: describe how to create invariant checks
1097 Macros That Log Information
1098 ---------------------------
1100 Logging targets a flag (except for `ECHO`) and is done at a log-level related to syslog levels.
1102 .ECHO
1104  ECHO(...)
1106 Never optimized out, logs at LOG_NOTICE level. Its main purpose is for implementing
1107 testsuites where one would like to print and log messages independent of the build level
1109 .ALERT
1111  ALERT(flag, ...)
1112  ALERT_IF(when, flag, ...)
1113  NOBUG_ALERT_CTX(flag, context, ...)
1114  NOBUG_ALERT_IF_CTX(when, flag, context, ...)
1116 This is the most critical condition that might be registered by
1117 an application. Situations might arise when the application
1118 encounters such a serious error that can only be adequately treated
1119 by, for example, safely shutting down the application.
1121 .CRITICAL
1123  CRITICAL(flag, ...)
1124  CRITICAL_IF(when, flag, ...)
1125  NOBUG_CRITICAL_CTX(flag, context, ...)
1126  NOBUG_CRITICAL_IF_CTX(when, flag, context, ...)
1128 An error which can not be handled occured but the application does not need to be
1129 shutdowen, perhaps waiting for an operator to fix the cause.
1131 .ERROR
1133  ERROR(flag, ...)
1134  ERROR_IF(when, flag, ...)
1135  NOBUG_ERROR_CTX(flag, context, ...)
1136  NOBUG_ERROR_IF_CTX(when, flag, context, ...)
1138 This is used when an application registers an error
1139 and appropriate action will have to be taken.
1141 .WARN
1143  WARN(flag, ...)
1144  WARN_IF(when, flag, ...)
1145  NOBUG_WARN_CTX(flag, context, ...)
1146  NOBUG_WARN_IF_CTX(when, flag, context, ...)
1148 When an application encounters a rare and unexpected
1149 situation, these macros can be used.
1151 .INFO
1153  INFO(flag, ...)
1154  INFO_IF(when, flag, ...)
1155  NOBUG_INFO_CTX(flag, context, ...)
1156  NOBUG_INFO_IF_CTX(when, flag, context, ...)
1158 It may be benificial to output information at various
1159 locations throughout the code, e.g., messages on programm
1160 progress.
1162 .NOTICE
1164  NOTICE(flag, ...)
1165  NOTICE_IF(when, flag, ...)
1166  NOBUG_NOTICE_CTX(flag, context, ...)
1167  NOBUG_NOTICE_IF_CTX(when, flag, context, ...)
1169 Same as the INFO() macros, except more verbose.
1171 .TRACE
1173  TRACE(flag, ...)
1174  TRACE_IF(when, flag, ...)
1175  NOBUG_TRACE_CTX(flag, context, ...)
1176  NOBUG_TRACE_IF_CTX(when, flag, context, ...)
1178 The same as the NOTICE() macros, except very fine-grained information.
1179 a common use case is to put just `TRACE(debugflag)` just at the begin of every
1180 non-trivial function. This allows to watch fine grained application progress in the log.
1182 NOTE: `TRACE` corresponds to `LOG_DEBUG`, because using `DEBUG` could be ambiguous.
1184 .LOG
1186  NOBUG_LOG_CTX(flag, lvl, context, ...)
1187  NOBUG_LOG_IF_CTX(when, flag, lvl, context, ...)
1189 Generic logging macro which takes the level explicitly.
1190 Avoid this, unless you implement your own logging facilities.
1193 NOTE: there is no logging macro for `LOG_EMERG`, this is only used by the assertions as a fatal message
1195 .LOG_BASELIMIT
1197  NOBUG_LOG_BASELIMIT_ALPHA
1198  NOBUG_LOG_BASELIMIT_BETA
1199  NOBUG_LOG_BASELIMIT_RELEASE
1200  NOBUG_LOG_BASELIMIT
1202 Anything more detailed than this base limits will be optimized out.
1203 This is used to reduce the logging overhead for *RELEASE* builds.
1204 By default the limit is set to `LOG_DEBUG` for *ALPHA* and *BETA*
1205 builds, so all logging is retained and `LOG_NOTICE` in *RELEASE*
1206 builds to log the application progress only coarsely.
1208 These macros can be defined before including 'nobug.h' to some other
1209 log level (as defined in 'syslog.h').
1211 Dumping Data Structures
1212 -----------------------
1214 One can write functions to dump complex data structures using the NoBug
1215 facilities. This is done by writing a custom function for each
1216 data structure to be dumped, which may recursively call other dumping
1217 functions. There are macros that can log within such a dumper function
1218 and to initialise a dump of a given data structure.
1220 A dump function has the prototype:
1222 [source,c]
1223 -------------------------------------------------------
1224 void
1225 nobug_NAME_dump (const struct NAME* POINTER,
1226                  const int DEPTH,
1227                  const struct nobug_context context,
1228                  void* EXTRA);
1229 -------------------------------------------------------
1231 where 'NAME' is the identifier for what you want to dump, 'POINTER' is a pointer
1232 to the data to be dumped, 'DEPTH' is an integer which will be decremented when
1233 recursing into the data structure dumper (your dump function does that, see
1234 below) to limit the recursion depth, 'context' is a source context generated by
1235 nobug when you call DUMP() and 'EXTRA' is a pointer transparently passed around
1236 that you can use to store some additional state. The 'context' variable must
1237 be named `context` because the `DUMP_LOG()` macro relies on this.
1239 .DUMP
1241  DUMP(flag, type, pointer, depth, extra)
1242  DUMP_IF(when, flag, type, pointer, depth, extra)
1244 These macros call a data structure dump of the object (`pointer`) in question.
1245 `DUMP` has only effect in *ALPHA* and *BETA* builds, `DUMP_IF` is also
1246 enabled for RELEASE builds.
1248 `extra` is a void* which is transparently passed around and can be used to
1249 pass a particular state around. NoBug does not alter this.
1251 .DUMP_LOG
1253  DUMP_LOG(...)
1254  DUMP_LOG_IF(when, ...)
1256 Any output from `DUMP` handlers should be done by these macros.
1258 .DUMP_LEVEL
1260  #define NOBUG_DUMP_LEVEL ...
1262 Dumping is by default done at `LOG_DEBUG` level, this can be overridden by
1263 defining `NOBUG_DUMP_LEVEL` to some other logging level.
1265 .How to use the DUMP facilities
1267 [source,c]
1268 -------------------------------------------------------
1269 struct STRUCTNAME
1271   int INTEGER_MEMBER;
1272   char * STRING_MEMBER;
1273   struct STRUCTNAME* next;
1275 -------------------------------------------------------
1277 Thereafter, define a funcion as follows:
1279 [source,c]
1280 -------------------------------------------------------
1281 void
1282 nobug_STRUCTNAME_dump (const struct STRUCTNAME* self,
1283                        const int depth,
1284                        const struct nobug_context context,
1285                        void* extra)
1287   /* check for self != NULL and that the depth limit
1288      was not exceeded in recursive data structures */
1289   if (self && depth)
1290   {
1291     /* you may or may not do something with the extra
1292        parameter here, extra is transparently
1293        passed around */
1294     (void) extra;
1296     /* use DUMP_LOG not LOG to print the data */
1297     DUMP_LOG("STRUCTNAME %p: int is %d, string is %s", self,
1298                              self->INTEGER_MEMBER,
1299                              self->STRING_MEMBER);
1301     /* now recurse while decrementing depth */
1302     nobug_STRUCTNAME_dump (self->next,
1303                            depth-1,
1304                            context,
1305                            extra);
1306   }
1308 -------------------------------------------------------
1310 Now you can use the DUMP() macros within the code
1312 [source,c]
1313 -------------------------------------------------------
1314 example()
1316   struct STRUCTNAME foo;
1317   init(&foo);
1319   /* extra can be anything,
1320      NULL is suggested when you don't use it */
1321   DUMP (my_flag, STRUCTNAME, &foo, 2, NULL);
1323 -------------------------------------------------------
1325 Source Code Annotations
1326 -----------------------
1328 Obsolete, buggy or precarious code can be marked in the code itself in
1329 comments at the location where the code occurs.  However these code
1330 locations can be easily overlooked, especially in large projects. NoBug
1331 provides macros to tag code with such annotations. This provides an additional
1332 instrument to alert or remind the programmer that there is still dubious
1333 code embedded in the application. This tagging scheme not only informs
1334 the programmer at compile time that there is code in the application
1335 that needs attending to, but long after compilitation a test team
1336 might become aware of dubious code due to runtime messages.
1339 .DEPRECATED
1341  DEPRECATED(...)
1343 Use this macro to identify code that is depreciated
1344 and should not be used in future or productive code.
1346 .UNIMPLEMENTED
1348  UNIMPLEMENTED(...)
1350 Use this macro to identify code that is functionally
1351 not yet complete and should not be used. This is convenient
1352 for code under development or being reviewed.
1354 .FIXME
1356  FIXME(...)
1358 Use this macro to mark a known and unfixed bug.
1360 .TODO
1362  TODO(...)
1364 Enhancement or non-critical bug to be done soon.
1366 .PLANNED
1368  PLANNED(...)
1370 Future enhancement, optimization to similar which has no side effect on the current program.
1372 .NOTREACHED
1374  NOTREACHED(...)
1376 Code which must never be reached.
1378 .ELSE_NOTREACHED
1380  ELSE_NOTREACHED(...)
1382 This macro is the same as `else NOTREACHED()`, but completely
1383 optimized out in release builds.
1386 Annotation Semantics
1387 ~~~~~~~~~~~~~~~~~~~~
1389 The action that should be taken when an annotated source line is reached
1390 depends on the build level.
1392 [frame="topbot",options="header"]
1393 |================================================
1394 |              |ALPHA |BETA         |RELEASE
1395 |DEPRECATED    |
1396 log footnote:[will only log once for each source line (not on each hit)] |
1397 nothing footnote:[optimized out, irrelevant] |
1398 won't compile footnote:[aborts compilation with an error message]
1400 |UNIMPLEMENTED |abort footnote:[spew a log message, then abort the program] |
1401 abort |won't compile
1403 |FIXME         |log   |won't compile |won't compile
1404 |TODO          |log   |log          |won't compile
1405 |PLANNED       |log   |nothing      |nothing
1406 |NOTREACHED    |abort |abort        |removed footnote:[optmized out, size]
1407 |================================================
1409 Scope Checks
1410 ------------
1412 The programmer can tag any scope as `UNCHECKED` or `CHECKED`. In *ALPHA* and *BETA*
1413 builds, a global `UNCHECKED` is implied. In *RELEASE* builds, `UNCHECKED` scopes are
1414 not allowed.
1416 [source,C]
1417 -------
1419 myfunc()
1421    /* the outer scope of this function is not validated yet*/
1422    UNCHECKED;
1424    if (...)
1425    {
1426       /* everything in this scope is considered ok */
1427       CHECKED;
1428       ...
1429    }
1430    return ...;
1432 -------
1434 .Assertions active depending on Build level and Scope
1436 [cols="2h,3*3",frame="topbot",options="header",autowidth="something"]
1437 |============================================================================================
1438 |          |ALPHA                                     |BETA                          |RELEASE
1439 |UNCHECKED |Preconditions, Postconditions, Invariants |Preconditions, Postconditions |compiling will abort
1440 |CHECKED   |Preconditions, Postconditions             |Preconditions                 |
1441 |============================================================================================
1443 Fault injection
1444 ---------------
1446 NoBug has some macros which can be used to simulate erroneous behaviour,
1447 in other words, we can inject errors, or faults, into the code
1448 using NoBug.
1450 .INJECT_GOODBAD
1452  INJECT_GOODBAD(expr, good, bad)
1454 Substitutes to an expression and returns 'good' when expr is false and
1455 'bad' when expr is true. In BETA and RELEASE builds 'good' is always returned.
1457 .INJECT_FAULT
1459  INJECT_FAULT(expr, bad)
1461 Substitutes to a statement which executes 'bad'
1462 when expr is true. This is only available in ALPHA builds and
1463 is optimitsed out in BETA and RELEASE builds.
1465 .Setting the logging level for fault injections
1466 In both cases, when a fault is injected, it will be logged at
1467 `NOBUG_INJECT_LEVEL` (default: `LOG_NOTICE`). This can be defined
1468 before including 'nobug.h' to override it.
1470 Fault coverage checking
1471 -----------------------
1473 CAUTION: Fault coverage checking is an experimental feature!
1475 NoBug can automatically inject faults at instrumented points and permute
1476 through all potential error paths of an application by restarting it with the
1477 state from a former run. It can be used to provide information on whether a
1478 particular error is adequately treated in an application. Fault coverage
1479 checking is only available in ALPHA builds; it is optimized out in all other
1480 builds.
1482 NOTE: This kind of testing is very expensive on performance.
1484 How Does Automatic Fault Injection Work?
1485 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1487 First, NoBug checks if the `NOBUG_COVERAGE` environment variable is set. If it
1488 is set, it must contain a space, comma or a semicolon separated list of
1489 filenames which are the logs from a previous run. These logs are then parsed
1490 storing the old state in a lookup tree.
1492 The application will then proceed to run as usual. When an instrumented
1493 coverage point is hit, its status is checked against all states that have been
1494 recorded previously. Any failure point that is encountered for a first time
1495 causes a fault to be injected; the last seen but previously failed point will
1496 now be passed, all other fault injection points behave as in their previous
1497 run. This ensures that each successive run of the application changes only one
1498 injection point and, thus, permutes through all possible code paths.
1500 Fault injection points are identified by a 64bit hash over the backtrace
1501 (return addresses on the stack) leading to it. This means each unique way to
1502 reach an injection point is recorded. Parameters and threads are intentionally
1503 not considered in this calculation.
1506 How to Invoke Fault-Coverage Checking
1507 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1509 Each fault-injection point emits a logging message about its identity and
1510 state, this logging uses the normal NoBug logging facilities. Thus, one can
1511 control logging with the `NOBUG_LOG` environment variable. Furthermore, fault
1512 coverage checking is only active when the `NOBUG_COVERAGE` environment
1513 variable has been set to point to log files which are the results from a
1514 previous run. NoBug comes with a `tests/coverage.sh` example script which
1515 permutes through all possible error paths.
1517 Coverage checking Macros
1518 ~~~~~~~~~~~~~~~~~~~~~~~~
1520 .COVERAGE_FAULT
1522  COVERAGE_FAULT(flag, ...)
1524 Injects the statement at `...` when simulating a failure. Only active in
1525 ALPHA builds.
1527 .COVERAGE_GOODBAD
1529  COVERAGE_GOODBAD(flag, good, bad)
1531 Substitutes to an expression and injects `bad` when simulating a failure and `good`
1532 otherwise. Only active in ALPHA builds.
1534 .COVERAGE_LEVEL
1536  #define NOBUG_COVERAGE_LEVEL ...
1538 Define the logging level in which fault-coverage logging is emitted.
1540 NOTE: Supressing log output with this level will not supress fault injection,
1541       actually the opposite is true since every newly seen failure path gets injected.
1542       This might be changed in future releases.
1544 .Disabling and enabling fault-coverage checks
1546  NOBUG_COVERAGE_DISABLE
1547  NOBUG_COVERAGE_ENABLE
1549 Sometimes fault injection yields false positives, errors which may never happen in real life
1550 (and are possibly enforced with an ENSURE afterwards). For this cases coverage fault injection can be
1551 disabled temporarly and reenabled later. Disabling/enabling may nest and must properly match.
1553 Resource Tracking
1554 -----------------
1556 With little effort, NoBug can watch all kinds of resources a program uses. This
1557 becomes useful for resources which are distributed over a multithreaded
1558 program. Resource tracking includes logging actions on resource and checking
1559 locking policies over acquired resources. Resource logging is active in ALPHA
1560 and BETA builds when NOBUG_RESOURCE_LOGGING is defined to 1 (the default).
1561 The resource tracker which supervises locking policies is only enabled in
1562 ALPHA builds.
1564 Concepts
1565 ~~~~~~~~
1567 Resources are an abstract entity for NoBug, which has little knowledge about the
1568 kinds of resources; it only keeps records of resources and the code using
1569 these resources and ensures basic constraints. More detailed checks on resource
1570 usage have to be done with other NoBug facilities.
1572 Resources are identified by an arbitrary identifier which is just a
1573 pointer. Additionally a name, the type and the source locations which
1574 registered the resource are stored.
1576 Code which requiring to use a resource, calls an 'ENTER' macro, supplying
1577 an identifier and state. The state can be altered. Thereafter a 'LEAVE' macro is
1578 used when the the code is finished with the resources.
1580 When a resource is used, one has to pass one of these states:
1582   `NOBUG_RESOURCE_WAITING`::
1583         For resources which might need to be blocked (locks),  enter with a
1584         WAITING state first, as soon at the resource is acquired, change the
1585         state to one of the following.
1586   `NOBUG_RESOURCE_EXCLUSIVE`::
1587         Acquired the resource exclusively. The resource must not be acquired
1588         again, not even from the same thread.
1589   `NOBUG_RESOURCE_RECURSIVE`::
1590         The resource might be entered multiple times from the same
1591         thread with this state.
1592   `NOBUG_RESOURCE_SHARED`::
1593         The resource might be entered multiple times from any thread
1594         with this state.
1596 ["graphviz", "resource-transitions.eps"]
1597 ---------------------------------------------------------------------
1598 strict digraph G
1600         edge [fontname=Courier fontsize=10]
1602         start [shape=ellipse]
1604         node [shape=box]
1606         start -> Waiting [label="ENTER()"]
1607         start -> Exclusive [label="ENTER()"]
1608         start -> Recursive [label="ENTER()"]
1610         Waiting -> Exclusive [label="STATE()"]
1611         Waiting -> Recursive [label="STATE()"]
1613         Recursive -> Recursive [label="ENTER()\nSTATE()"]
1615         Waiting -> end [label="LEAVE()"]
1616         Exclusive -> end [label="LEAVE()"]
1617         Recursive -> end [label="LEAVE()"]
1619         end [shape=ellipse]
1621 ---------------------------------------------------------------------
1623 Notes
1624 ~~~~~
1626 The Resource Tracker relies on proper announce/forget and enter/leave
1627 are properly paired. The programmer should ensure that this is correctly 
1628 done, otherwise the results are unpredictable.
1630 Resource tracking macros
1631 ~~~~~~~~~~~~~~~~~~~~~~~~
1633 Unless the user defines `NOBUG_RESOURCE_LOGGING` to 0 each of the above macros
1634 will emit a log message at `NOBUG_RESOURCE_LOG_LEVEL` which defaults to
1635 `LOG_DEBUG`.
1637 .RESOURCE_HANDLE
1639  RESOURCE_HANDLE(name)
1640  RESOURCE_HANDLE_INIT(name)
1641  RESOURCE_USER(name)
1642  RESOURCE_USER_INIT(name)
1644 Define and initialize handles for to track resources.
1646  `name`::
1647      identifer to be used for the handle
1649 There are two kinds of handles. Resource themself are abstracted with a
1650 `RESOURCE_HANDLE` while uses of a resources are tracked by `RESOURCE_USER`
1651 handle. These macros takes care that the declaration is optimized out
1652 in the same manner as the rest of the resource tracker would be disabled.
1653 You can still instantiate handles as `struct nobug_resource_record*` or
1654 `struct nobug_resource_user*` in structures which must have a constant size
1655 unconditional of the build level. The two `*_INIT` macros can be used to initialize
1656 resource handles and are optimized out when the resource tracker gets disabled.
1658 .RESOURCE_ANNOUNCE
1660  RESOURCE_ANNOUNCE(flag, type, name, identifier, handle){}
1661  NOBUG_RESOURCE_ANNOUNCE_RAW(flagptr, type, name, ptr, handle){}
1662  NOBUG_RESOURCE_ANNOUNCE_RAW_CTX(flagptr, type, name,
1663                                  ptr, handle, context){}
1665 Publishes resources.
1667  `flag`::
1668      the NoBug flag name which turns logging on for this macro
1669  `type`::
1670      a string which should denote the domain of the resource,
1671      examples are "file", "mutex", "lock", "database" and so on
1672  `name`::
1673      the actual name of a named resource this as string. `type` and
1674      `name` must be available through the entire lifetime of the resource, using
1675      literal strings is recommended
1676  `identifier`::
1677      a pointer which must be unique for this resource, any
1678      kind of pointer will suffice, it is only used for identification. In
1679      multithreaded applications the thread identifier becomes an additional
1680      identifier
1681  `handle`::
1682      a `NOBUG_RESOURCE_HANDLE` which will be initialized to point to
1683      the newly created resource.
1685 Resources must be unique, it is a fatal error when a resource it tried to be
1686 announced more than one time.
1688 `RESOURCE_ANNOUNCE()` acts like the head of a C loop statement, it ties to the following
1689 (block-) statement which will be handled atomic.
1690 This statement must not be left by break, return or any other kind of jump.
1692 .RESOURCE_FORGET
1694  RESOURCE_FORGET(flag, handle){}
1695  NOBUG_RESOURCE_FORGET_RAW(flagptr, handle){}
1696  NOBUG_RESOURCE_FORGET_RAW_CTX(flagptr, handle, context){}
1698 Removes resources that have become unavailable from the registry.
1700 `flag`::
1701     the NoBug flag which turns logging on for this macro
1702 `handle`::
1703     the `NOBUG_RESOURCE_HANDLE` used to track this resource
1705 The resource must still exist and no users must be attached to it, else a fatal
1706 error is raised.
1708 `RESOURCE_FORGET()` acts like the head of a C loop statement, it ties to the following
1709 (block-) statement which will be handled atomic.
1710 This statement must not be left by break, return or any other kind of jump.
1712 .RESOURCE_RESETALL
1714  RESOURCE_RESETALL(flag)
1715  NOBUG_RESOURCE_RESETALL_RAW(flagptr)
1716  NOBUG_RESOURCE_RESETALL_RAW_CTX(flagptr, context)
1718 Sometimes the resource tracker can give false positives when it finds a locking order violation
1719 while the programmer knows that this will never happen in the real program, because for example
1720 this is only used at initialization or shutdown and never overlaps. This macro can then be used
1721 to reset all whats learnt about all resources and start over.
1723 `flag`::
1724     the NoBug flag which turns logging on for this macro
1726 .RESOURCE_RESET
1728  RESOURCE_RESET(flag, handle)
1729  NOBUG_RESOURCE_RESET_RAW(flagptr, handle)
1730  NOBUG_RESOURCE_RESET_RAW_CTX(flagptr, handle, context)
1732 Sometimes the resource tracker can give false positives when it finds a locking order violation
1733 while the programmer knows that this will never happen in the real program, because for example
1734 this is only used at initialization or shutdown and never overlaps. This macro can then be used
1735 to reset all whats learnt about a single resources and start over.
1737 `flag`::
1738     the NoBug flag which turns logging on for this macro
1739 `handle`::
1740     the `NOBUG_RESOURCE_HANDLE` used to track this resource
1742 .RESOURCE_ENTER
1744  RESOURCE_ENTER(flag, announced, user, state, handle){}
1745  NOBUG_RESOURCE_ENTER_CTX(flag, resource, user, state,
1746                           handle, context){}
1748 Acquire a resource.
1750 `flag`::
1751     nobug flag which turns logging on for this macro
1752 `announced`::
1753     the handle set by `RESOURCE_ANNOUNCE`
1754 `user`::
1755     a literal string defining the purpose
1756 `state`::
1757     the state to enter
1758 `handle`::
1759     a `NOBUG_RESOURCE_HANDLE` which will be initialized to the
1760     entering node
1762 `RESOURCE_ENTER()` acts like the head of a C loop statement, it ties to the following
1763 (block-) statement which will be handled atomic.
1764 This statement must not be left by break, return or any other kind of jump.
1766 .RESOURCE_WAIT
1768  RESOURCE_WAIT(flag, resource, user, handle){}
1769  NOBUG_RESOURCE_WAIT_CTX(flag, resource, user, handle, context){}
1771 This is just an alias for
1773  RESOURCE_ENTER(flag, resource, user,
1774                 NOBUG_RESOURCE_WAITING, handle)
1776 .How to use it
1777 [source,c]
1778 ----
1779 RESOURCE_WAIT(flag, resource, user, handle);
1780 if (lock_my_resource() == ERROR)
1781   NOBUG_RESOURCE_LEAVE(flag, handle);
1782 else
1783   RESOURCE_STATE(flag, NOBUG_RESOURCE_EXCLUSIVE, handle);
1784 ----
1786 .RESOURCE_TRY
1788  RESOURCE_TRY(flag, resource, user, handle){}
1789  NOBUG_RESOURCE_TRY_CTX(flag, resource, user, handle, context){}
1791 This is just an alias for
1793  RESOURCE_ENTER(flag, resource, user,
1794                 NOBUG_RESOURCE_TRYING, handle)
1796 Trying on a resource is similar to waiting but will not trigger a deadlock check. This can be used
1797 when a deadlock is expected at runtime and one handles this otherwise (by a timed wait or something like that).
1799 .RESOURCE_STATE
1801  RESOURCE_STATE(flag, entered, state){}
1802  NOBUG_RESOURCE_STATE_CTX(flag, state, entered, context){}
1803  NOBUG_RESOURCE_STATE_RAW(flagptr, state, entered){}
1804  NOBUG_RESOURCE_STATE_RAW_CTX(flagptr, state, entered, context){}
1806 Changes resource's state.
1808 `flag`::
1809     is nobug flag which turns logging on for this macro
1810 `state`::
1811     the new state Note that only certain state transitions are
1812     allowed, see discussion/diagram above
1813 `entered`::
1814     the handle set by `RESOURCE_ENTER`
1816 `RESOURCE_STATE()` acts like the head of a C loop statement, it ties to the following
1817 (block-) statement which will be handled atomic.
1818 This statement must not be left by break, return or any other kind of jump.
1820 .RESOURCE_LEAVE
1822  RESOURCE_LEAVE(flag, handle){}
1823  NOBUG_RESOURCE_LEAVE_RAW(flagptr, handle){}
1824  NOBUG_RESOURCE_LEAVE_RAW_CTX(flagptr, handle, context){}
1826 Disconnect from a resource identified with its handle.
1828 `flag`::
1829     nobug flag which turns logging on for this macro
1830 `handle`::
1831     the handle you got while entering the resource
1833 `RESOURCE_LEAVE()` acts like the head of a C loop statement, it ties to the following
1834 (block-) statement which will be handled atomic.
1835 This statement must not be left by break, return or any other kind of jump.
1837 .How to use it
1838 [source,c]
1839 ----
1840 NOBUG_RESOURCE_LEAVE(flag, handle)
1841   {
1842     unlock_my_resource();
1843   }
1844 ----
1846 .RESOURCE_ASSERT_STATE
1848  RESOURCE_ASSERT_STATE(resource, state)
1849  RESOURCE_ASSERT_STATE_IF(when, resource, state)
1850  NOBUG_RESOURCE_ASSERT_STATE_CTX(resource, state, context)
1851  NOBUG_RESOURCE_ASSERT_STATE_IF_CTX(when, resource,
1852                                     state, context)
1854 Assert that we have a resource in a given state. For multithreaded programms the topmost
1855 state of the calling thread is checked, for non threadeded programs the most recent state on
1856 resource is used.
1858 `when`::
1859     Condition which must be true for testing the assertion
1860 `resource`::
1861     Resource handle
1862 `state`::
1863     The expected state
1865 .RESOURCE_DUMP
1867  NOBUG_RESOURCE_DUMP(flag, handle)
1868  NOBUG_RESOURCE_DUMP_IF(when, flag, handle)
1870 Dump the state of a single resource.
1872 `when`::
1873     Condition which must be true to dump the resource
1874 `flag`::
1875     Nobug flag for the log channel
1876 `handle`::
1877     handle of the resource to be dumped
1879 .RESOURCE_DUMPALL
1881  NOBUG_RESOURCE_DUMPALL(flag)
1882  NOBUG_RESOURCE_DUMPALL_IF(when, flag)
1884 Dump the state of all resources.
1886 `when`::
1887     Condition which must be true to dump the resources
1888 `flag`::
1889     Nobug flag for the log channel
1891 .RESOURCE_LIST
1893  NOBUG_RESOURCE_LIST(flag)
1894  NOBUG_RESOURCE_LIST_IF(when, flag)
1896 List all registered resources.
1898 `when`::
1899     Condition which must be true to list the resources
1900 `flag`::
1901     Nobug flag for the log channel
1903 .How to use the Resourcetracker
1904 [source,c]
1905 ----
1906 NOBUG_DEFINE_FLAG_LIMIT(test, LOG_DEBUG);
1908 void example()
1910   /* define a mutex and announce it */
1911   pthread_mutex_t my_mutex = PTHREAD_MUTEX_INITIALIZER;
1912   RESOURCE_HANDLE(resource);
1914   /* 'example' is just a pointer to this function
1915      which suffices as unique identifier */
1916   RESOURCE_ANNOUNCE(test, "mutex", "my_mutex",
1917                     example, resource);
1919   /* the following would be done in a
1920      different thread in a real program */
1922   /* define a handle */
1923   RESOURCE_HANDLE(enter);
1925   /* announce that we want to use the resource
1926      &enter also suffices as unique pointer,
1927      which is all we need as identifer here */
1928   RESOURCE_WAIT(flag, resource, &enter, enter)
1929     {
1930       /* lock() might block */
1931       pthread_mutex_lock (&my_mutex);
1932       /* assume no errors, got it, change the state */
1933       RESOURCE_STATE(test, NOBUG_RESOURCE_EXCLUSIVE, enter);
1934     }
1936   /***************************************
1937   ** program does something useful here **
1938   ***************************************/
1940   /* we don't need it anymore */
1941   RESOURCE_LEAVE(test, enter)  /* << no semicolon! */
1942     pthread_mutex_unlock (&my_mutex);
1944   /* back in the main thread */
1946   /* remove the resource from the public registry */
1947   RESOURCE_FORGET(test, resource);
1949 ----
1951 Deadlock Detection
1952 ~~~~~~~~~~~~~~~~~~
1954 The Resource Tracker is able to detect potential deadlocks. This is done by
1955 learning the relations between locks (precedence) and watching the order in
1956 which resources are acquired. It has some heuristics to detect certain
1957 patterns which are deadlock free. A possible deadlock results in a log message
1958 and a fatal abort. Note that only waiting on resources can lead to a deadlock.
1959 Deadlock detection is implemented in the Resource Tracker and active in ALPHA
1960 builds and optimized out on any other build level.
1962 For details about the deadlock detection algorithm see
1963 xref:deadlockdetection[Appendix: Resource Tracking Alorithm].
1965 Callbacks
1966 ---------
1968 NoBug provides callbacks, applications can use these
1969 to present logging information in some custom way or hook some special processing in.
1970 The callbacks are initialized to NULL and never modified by NoBug, it is the sole responsibility
1971 of the user to manage them.
1973 CAUTION: There are certain constraints what and what not can be done in callbacks
1974          documented below which must be followed.
1976 .logging callback prototype
1978  typedef void (*nobug_logging_cb)(const struct nobug_flag* flag,
1979                                   int priority,
1980                                   const char *log,
1981                                   void* data)
1983  `flag`::
1984     Flag structure which defines the logging configuration for this event
1985  `priority`::
1986     Log level of the current event
1987  `log`::
1988     Pointing to the current log line in the ringbuffer or `NULL`
1989  `data`::
1990     Global pointer defined by the user, passed arround (see below)
1992 .abort callback prototype
1994  typedef void (*nobug_abort_cb)(void* data)
1996  `data`::
1997     Global data defined by the user, passed arround (see below)
1999 .passing data to callbacks
2001  void* nobug_callback_data
2003 This global variable is initialized to `NULL` and will never be touched by NoBug. One can use it
2004 to pass extra data to the callback functions.
2006 .callback when logging
2008  nobug_logging_cb nobug_logging_callback
2010 This callback gets called when something gets logged.
2011 NoBug will still hold its mutexes when calling this hook, calling NoBug logging or resource tracking
2012 functions from here recursively will deadlock and must be avoided.
2013 The `log` parameter points to the logging message in the ringbuffer.
2014 Unlike other logging targets it is not automatically limited to the log level configured
2015 in the flag but called unconditionally. The callback should implement its own limiting.
2017 When one wants to do complex calls which may include recursion into logging and resource tracking
2018 functions, the intended way is to pass contextual information possibly including a __copy__ of the
2019 `log` parameter in xref:THREADDATA[NOBUG_THREAD_DATA] to the postlogging callback (see below).
2020 Other internal NoBug facilties, like the ringbuffer etc, are protected by the mutexes and may be accessed
2021 from this function.
2023 .callback after logging
2025  nobug_logging_cb nobug_postlogging_callback
2027 This callback gets called after something got logged. The `log` parameter is always NULL and all
2028 NoBug mutexes are released. This means that this function may call any complex things, including
2029 calling logging and resource tracking, but may not call internal NoBug facilities.
2030 Contextual created in the `nobug_logging_callback` and stored in xref:THREADDATA[NOBUG_THREAD_DATA] can be
2031 retrieved here and may need to be cleaned up here.
2033 .callback for aborting
2035  nobug_abort_cb nobug_abort_callback
2037 This callback gets called when the application shall be terminated due an error.
2038 It can be used to hook exceptions or similar things in. When it returns, `abort()`
2039 is called.
2041 IMPORTANT: Errors detected by NoBug are always fatal. If one handles and possible
2042            throws an exception here, the application must shut down as soon as possible.
2043            Most causes for aborts are optimitzed out in `RELEASE` builds.
2045 Tool Macros
2046 -----------
2048 .NOBUG_FLAG_RAW
2050  NOBUG_FLAG_RAW(ptr)
2052 Using this macro one can pass a direct pointer to a flag where a name would
2053 be expected. This is sometimes convinient when flag pointers are passed around
2054 in management strutures and one wants to tie logging to dynamic targets.
2056 [source,c]
2057 ----
2058 NOBUG_DEFINE_FLAG(myflag);
2060 struct nobug_flag* ptr = &NOBUG_FLAG(myflag);
2061 TRACE(NOBUG_FLAG_RAW(ptr), "Passed flag by pointer")
2062 ----
2064 .Backtraces
2066  BACKTRACE
2067  NOBUG_BACKTRACE_CTX(context)
2069 The backtrace macro logs a stacktrace using the NoBug facilities.
2070 This is automatically called when NoBug finds an error and is due
2071 to abort. But one might call it manually too.
2073 .Aborting
2075  NOBUG_ABORT_
2077 This is the default implementation for aborting the program, it first syncs all ringbuffers to disk, then
2078 calls the abort callback if defined and then `abort()`.
2080  NOBUG_ABORT
2082 If not overridden, evaluates to `NOBUG_ABORT_`. One can override this before including
2083 `nobug.h` to customize abortion behaviour. This will be local to the translation unit then.
2085 .NOBUG_ALPHA_COMMA
2087  NOBUG_ALPHA_COMMA(something)
2088  NOBUG_ALPHA_COMMA_NULL
2090 Sometimes it is useful to have initializer code only in *ALPHA* builds, for example when you
2091 conditionally include resource handles only in *ALPHA* versions. An initializer can then
2092 use this macros to append a comma and something else only in *ALPHA* builds as in:
2094 [source,C]
2095 ----
2096 struct foo = {"foo", "bar" NOBUG_ALPHA_COMMA_NULL };
2097 ----
2099 Becomes the following in *ALPHA* builds
2101 [source,C]
2102 ----
2103 struct foo = {"foo", "bar", NULL};
2104 ----
2108 [source,C]
2109 ----
2110 struct foo = {"foo", "bar"};
2111 ----
2113 in *BETA* and *RELEASE* builds.
2115 .NOBUG_IF_*
2117  NOBUG_IF_ALPHA(...)
2118  NOBUG_IF_NOT_ALPHA(...)
2119  NOBUG_IF_BETA(...)
2120  NOBUG_IF_NOT_BETA(...)
2121  NOBUG_IF_RELEASE(...)
2122  NOBUG_IF_NOT_RELEASE(...)
2124 This macros allow one to conditionally include the code in '(...)' only if the
2125 criteria on the build level is met. If not, nothing gets substituted. Mostly used
2126 internally, but can also be used for custom things.
2128 Multithreading
2129 --------------
2131 It is important that NoBug protects certain operations with locks in
2132 multithreaded programs. You have to ensure that 'HAVE_PTHREAD_H' is defined by
2133 the configuration system and use the 'libnobugmt' library for linking. It is
2134 particular important that libraries using NoBug are compiled with
2135 'HAVE_PTHREAD_H' enabled when they are intended to be used in multithreaded
2136 programs.
2138 When Multithreading is used, log messages contain a identifier of the
2139 originating thread. This identifier should be set by
2141 .NOBUG_THREAD_ID_SET
2143  NOBUG_THREAD_ID_SET(name)
2145 `name`::
2146         New name for the thread
2148 Nobug will assemble a unique identifier by appending a underscore and a
2149 number to name, for example `NOBUG_THREAD_ID_SET("gui")` will result in a
2150 identifier like 'gui_5'. When you don't set a thread identifier, then NoBug
2151 assigns one automatically with the name 'thread' preprended if needed. Thread
2152 identifiers may be reset with a new call to this macro.
2154 .NOBUG_THREAD_ID_GET
2156  NOBUG_THREAD_ID_GET
2158 Will return a const char* of the thread id in multithreaded programs and
2159 a pointer to a literal empty string in singlethreaded programs.
2161 .NOBUG_THREAD_DATA
2163  NOBUG_THREAD_DATA
2165 Evaluates to a variable of type `void*` which can be used to store
2166 thread local information. This is useable for xref:callbacks[callbacks] which may
2167 prepare context information to be reused later.
2169 This macro is also available in singlethreaded programs, refering to a
2170 single global variable.
2172 Nobug initializes this variable to `NULL` and then touches it never again.
2174 Dumping Persistent Ringbuffers
2175 ------------------------------
2177 NoBug installs the `nobug_rbdump` tool for dumping the content of a persistent
2178 ringbuffer. It is invoked with the filename of the ringbuffer, the content is then
2179 printed to stdout.
2181  $ NOBUG_LOG='test:TRACE@ringbuffer(file=test.rb)(keep)' ./a.out
2182  0000000004: TRACE: example.c:11: -: main: Always on
2183  $ nobug_rbdump test.rb
2184  0000000003: TRACE: example.c:10: -: main: Logging
2185  0000000003! TRACE: example.c:10: -: main:  enabled
2187 Best Practices
2188 --------------
2190 NOTE: this section is very work in progress
2192 .Workflow
2194  1. Development
2195       * Write a testsuite, build your program with -O0 -g -DEBUG_ALPHA and run
2196         the testsuite under valgrind control. Hack until the program meets the
2197         specifications defined by the testsuite.
2198  2. Beta Test
2199       * Build with desired optimization level and -g -DEBUG_BETA and give the
2200         program to your beta testers.
2201  3. Release
2202       * Build it with optimization and without -g -DEBUG_*
2204 .What and when to check
2206   * Add REQUIRE checks on your interfaces (incoming parameters). Especially if
2207     an argument might not cover the whole range of the underlying type.
2208   * Don't waste your and your CPU's time with unnecessary checks. The testsuite
2209     should validate your program. NoBug aids in debugging. You can add
2210     Postconditions (ENSURE) and Invariants when you have a bug somewhere and
2211     want to nail it down.
2212   * Added checks don't need to be removed.
2213   * When you use the CHECKED/UNCHECKED features then don't forget C scoping
2214     rules, tag things as CHECKED from the leaves to the root.
2216 .Tips & Tricks
2218   * TRACE(flagname) at the begin of every nontrivial function will easily log
2219     the progress of your application.
2220   * Trying a RELEASE build will abort on certain conditions (known BUG, TODO's,
2221     UNCHECKED code), you can use this to find these spots.
2223 Appendix
2224 --------
2226 The Resource Tracking Algorithm
2227 -------------------------------
2229 Each resource registers a global 'resource_record'.
2231 Every new locking path discovered is stored as 'resource_node' structures which refer to the associated
2232 'resource_record'.
2234 Threads keep a trail of 'resource_user' structures for each resource entered. This 'resource_user' struct
2235 refer to the 'resource_nodes' and thus indirectly to the associated 'resource_record'.
2237 The deadlock checker uses this information to test if the acqusition of a new resource would yield a
2238 potential deadlock.
2240 Entering Resources
2241 ~~~~~~~~~~~~~~~~~~
2243 In multithreaded programs, whenever a thread wants to wait for a 'resource_record'
2244 the deadlock checker jumps in.
2246 The deadlock checking algorithm is anticipatory as it will find and abort on conditions which may lead
2247 to a potential deadlock by violating the locking order learned earlier.
2249 Each thread holds a stack (list) of each 'resource_user' it created. Leaving
2250 a resource will remove it from this stacklist.
2252 Each 'resource_record' stores the trail which other 'resource_records' are already entered. This relations
2253 are implemented with the 'resource_node' helper structure.
2255 ////
2256 TODO: insert diagram here
2257   2-3
2259   3-4-2
2261 1-3-2-4
2263 3-4-2
2265 1-4-2
2267 ////
2269 First we find out if there is already a node from the to be acquired resource back to
2270 the topmost node of the current threads user stack.
2272 [source,c]
2273 ---------------------------------------------------------------------
2274 struct nobug_resource_user* user = NULL;
2275 struct nobug_resource_node* node = NULL;
2277 if (!llist_is_empty (&tls->res_stack))
2279   user = LLIST_TO_STRUCTP (llist_tail (&tls->res_stack),
2280                            struct nobug_resource_user,
2281                            res_stack);
2283   struct nobug_resource_node templ =
2284    {
2285     ...
2286     user->current->resource,
2287     ...
2288    };
2290   node = (struct nobug_resource_node*)
2291    llist_ufind (&resource->nodes,
2292                 &templ.node,
2293                 nobug_resource_node_resource_cmpfn,
2294                 NULL);
2297 ---------------------------------------------------------------------
2299 Deadlock checking is only done when the node is entered in `WAITING` state and only
2300 available in multithreaded programs.
2302 [source,c]
2303 ---------------------------------------------------------------------
2304 if (state == NOBUG_RESOURCE_WAITING)
2306 #if NOBUG_USE_PTHREAD
2307   ...
2308 ---------------------------------------------------------------------
2310 If node was found above, then this locking path is already validated and no deadlock can happen,
2311 else, if this stack already holds a resource (user is set) we have to go on with checking.
2313 [source,c]
2314 ---------------------------------------------------------------------
2315 if (!node && user)
2317   ...
2318 ---------------------------------------------------------------------
2320 If not then its checked that the resource to be entered is not on any parent trail of the current topmost resource,
2321 if it is then this could be a deadlock which needs to be further investigated.
2323 [source,c]
2324 ---------------------------------------------------------------------
2325 LLIST_FOREACH (&user->current->resource->nodes, n)
2327   for (struct nobug_resource_node* itr =
2328          ((struct nobug_resource_node*)n)->parent;
2329        itr;
2330        itr = itr->parent)
2331    {
2332     if (itr->resource == resource)
2333      {
2334        ...
2335 ---------------------------------------------------------------------
2337 if the resource was on the trail, we search if there is a common ancestor before the resource
2338 on the trail and the threads current chain,
2339 if yes then this ancestor protects against deadlocks and we can continue.
2341 [source,c]
2342 ---------------------------------------------------------------------
2343 for (struct nobug_resource_node* itr2 = itr->parent;
2344      itr2;
2345      itr2 = itr2->parent)
2347   LLIST_FOREACH_REV (&tls->res_stack, p)
2348    {
2349     struct nobug_resource_user* user =
2350      LLIST_TO_STRUCTP (p,
2351                        struct nobug_resource_user,
2352                        res_stack);
2353     if (user->current->resource == itr2->resource)
2354      goto done;
2355    }
2356   ...
2357 ---------------------------------------------------------------------
2359 If no ancestor found, we finally abort with a potential deadlock condition.
2361 [source,c]
2362 ---------------------------------------------------------------------
2363 nobug_resource_error = "possible deadlock detected";
2364 return NULL;
2365 ---------------------------------------------------------------------
2368 Leaving Resources
2369 ~~~~~~~~~~~~~~~~~
2371 store the tail and next aside, we need it later
2373 [source,c]
2374 ---------------------------------------------------------------------
2375 #if NOBUG_USE_PTHREAD
2376 struct nobug_resource_user* tail =
2377  LLIST_TO_STRUCTP (llist_tail (&user->thread->res_stack),
2378                    struct nobug_resource_user,
2379                    res_stack);
2380 struct nobug_resource_user* next =
2381  LLIST_TO_STRUCTP (llist_next (&user->res_stack),
2382                    struct nobug_resource_user,
2383                    res_stack);
2385 ---------------------------------------------------------------------
2387 remove user struct from thread stack
2388 The res_stack is now like it is supposed to look like with the 'user' removed.
2389 We now need to fix the node tree up to match this list.
2391 [source,c]
2392 ---------------------------------------------------------------------
2393 llist_unlink_fast_ (&user->res_stack);
2395 ---------------------------------------------------------------------
2397 When the the user node was not the tail or only node of the thread stack, we have to check
2398 (and possibly construct) a new node chain for it. No valdation of this chain needs to be done,
2399 since it was already validated when entering the resources first.
2401 [source,c]
2402 ---------------------------------------------------------------------
2403 if (user != tail && !llist_is_empty (&user->thread->res_stack))
2405   struct nobug_resource_user* parent = NULL;
2406   if (llist_head (&user->thread->res_stack)!= &next->res_stack)
2407    {
2408     parent =
2409      LLIST_TO_STRUCTP (llist_prev (&next->res_stack),
2410                        struct nobug_resource_user,
2411                        res_stack);
2412    }
2413   ...
2414 ---------------------------------------------------------------------
2416 iterate over all users following the removed node, finding nodes pointing to this users or
2417 create new nodes.
2419 [source,c]
2420 ---------------------------------------------------------------------
2421 LLIST_FORRANGE (&next->res_stack, &user->thread->res_stack, n)
2423   struct nobug_resource_user* cur =
2424    LLIST_TO_STRUCTP (n,
2425                      struct nobug_resource_user,
2426                      res_stack);
2428   struct nobug_resource_record* resource =
2429    cur->current->resource;
2430   ...
2431 ---------------------------------------------------------------------
2433 find the node pointing back to parent, create a new one if not found, rinse repeat
2435 [source,c]
2436 ---------------------------------------------------------------------
2437 struct nobug_resource_node templ =
2439   ...
2440   parent?parent->current:NULL,
2441   ...
2442  };
2444 struct nobug_resource_node* node =
2445  (struct nobug_resource_node*)
2446  llist_ufind (&resource->nodes,
2447               &templ.node,
2448               nobug_resource_node_parent_cmpfn,
2449               NULL);
2451 if (!node)
2453   node = nobug_resource_node_new (resource,
2454                                   parent?parent->current:NULL);
2455   if (!node)
2456    {
2457     nobug_resource_error = "internal allocation error";
2458     return 0;
2459    }
2462 parent = cur;
2463 ---------------------------------------------------------------------
2466 Reference Index
2467 ---------------
2469 [dotted]
2471 License
2472 -------
2474  NoBug
2475  Copyright (C)
2476  2006, 2007, 2008, 2009, 2010   Christian Thäter <ct@pipapo.org>
2478  This program is free software; you can redistribute it and/or
2479  modify it under the terms of the GNU General Public License
2480  as published by the Free Software Foundation; either version 2
2481  of the License, or (at your option) any later version.
2483  This program is distributed in the hope that it will be useful,
2484  but WITHOUT ANY WARRANTY; without even the implied warranty of
2485  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
2486  GNU General Public License for more details.
2488  You should have received a copy of the GNU General Public
2489  License along with this program; if not, write to the Free
2490  Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
2491  Boston, MA 02110-1301 USA.
2493 .License Rationale
2495 NoBug is released under the "GNU General Public License version 2 or
2496 any later" to protect its freedom. If one wants to use NoBug in a
2497 propietary program, please contact the main author for
2498 acknowledging relicensing terms.
2500 For BSD license style Free Software, this means you can not distribute
2501 binaries linking NoBug without making its source available. To make
2502 this compatible, it is suggested that you dual-license your software
2503 with your prefered BSD like license and the GPL. As long as it uses
2504 NoBug, the GPL will take over and you have to make the source
2505 available, while one can ship a BSD or LGPL Licensed headerfile which
2506 defines all NoBug macros as empty macros and remove libnobug from the
2507 linking, then NoBug isn't used anymore and you may apply BSD license
2508 terms for resulting binaries.
2511 .Contributor Agreement
2513 Improvements and patches must be licensed as "GPL v2 or any later" to
2514 be acceptable. Further a contributor must either assign his copyright
2515 to the main NoBug author or agree with the possibility that NoBug can
2516 be relicensed for propietary use:
2518  Independent of the GPL license as stated above, The main author
2519  of NoBug explicitly reserve the right to relicense NoBug under
2520  different, even propietary terms. Any contributor agrees to
2521  such a possiblility by sending his contribution to be included
2522  into the official releases.
2524  This agreement is bilateral, every contributor who worked on a
2525  substantial part of NoBug has the right to relicense it after
2526  negotiation with the NoBug main author. Exact terms of such
2527  relicensing are worked out on a per case base.
2529 The intention is that anyone who worked on NoBug should be able to
2530 benefit from his work. This means one should be able to use it at his
2531 workplace, to gain a job or as well as relicense it for a customer.
2532 Unlike other projects which simply ask for transfering the copyright
2533 to the main author, NoBug tries to make it possible to retain the
2534 copyright by anyone who helped the project.
2536 This additional agreement has no impact on the GPL, it's sole purpose
2537 is to define relicensing policies between the NoBug main author and
2538 contributors. When you recieve NoBug it will be licensed under
2539 GPL unless you personally acknowledged other terms with the NoBug main
2540 author (or any other main contributor).
2542 If anyone feels he is not credited in the 'AUTHORS' file or in any
2543 copyright notice, please contact the main author for inclusion.
2545 Credits
2546 -------
2548 Design, implementation::
2549  Christian Thaeter $$<ct@pipapo.org>$$ +
2551 Testsuite::
2552  Christian Thaeter $$<ct@pipapo.org>$$ +
2554 Documentation::
2555  Christian Thaeter $$<ct@pipapo.org>$$ +
2556  Benny Lyons $$<benny.lyons@uniserv.com>$$ +
2557  François KUBLER $$<ih8tehuman@free.fr>$$ +
2558  Andreas Hermann Braml $$<andreas@braml.org>$$ +
2560 Autoconf build system improvements::
2561  Peter Simons $$<simons@cryp.to>$$ +
2562  Luca Barbato $$<lu_zero@gentoo.org>$$ +
2563  Michael Ploujnikov $$<ploujj@gmail.com>$$ +
2565 Ringbuffer dump tool::
2566  Simeon Voelkel $$<simeon_voelkel@arcor.de>$$ +
2568 Logo::
2569  Pablo Lizardo $$<pablo_lizardo@yahoo.com.ar>$$ +