cosmetics and copyright years updates
[nobug.git] / README
blob56e4906b8419e3be287cbfe4ce7a5f0f1a46533e
1 NoBug
2 =====
3 Christian_Thäter,_Benny_Lyons
5 ____
6 Everyone makes mistakes, but with NoBug you won't make them twice!
7 ____
9 Nobug is a debugging library for instrumenting C and C++ programs
10 inspired by ideas originating from Design-by-Contract.
12 Overview
13 --------
15 The following features are provided by NoBug:
17   * Three different check levels: from detailed to final no-overhead
18   * Scope tags: tell whenever a function or loop is considered to be bug free
19   * Precondition, Postcondition and Invariant checks and generic assertions
20   * Data structures can be dumped
21   * Application activities can be logged
22   * Runtime customizable logging via an environment variable
23   * Different logging targets to stderr, syslog, debugger, ...
24   * Annotation of your sourcecode about known bugs, things to do, etc.
25   * Tracking resources (files, locks, etc.) used by your program; help in
26     detecting misuse
27   * Detecting potential deadlocks
28   * Simulate errors by injecting faults
29   * Additionally, the NoBug project is used to maintain a script and
30     some tools to setup testsuites
32 In contrast to traditional debuggers, NoBug is a non-interactive debugger which
33 is linked to your application doing hard-coded tests in an efficient,
34 low-overhead way.
36 .What NoBug can not do
38 NoBug is a (macro-)library, it is not a C/C++ language extension. This
39 means that code must be called at runtime to benefit from the set up
40 contracts. Whats not tested is likely slipping through the net. Being
41 part of the program itself it is affected by memory corruption,
42 certain kinds of misuse may introduce new bugs (test expressions with
43 side effects for example).
45 Building and Installing
46 -----------------------
48 Supported Platforms
49 ~~~~~~~~~~~~~~~~~~~
51 NoBug has been developed on linux, using gcc. It should be possible to port
52 it to any other POSIX compliant operating system. Platform/compiler
53 specific things are kept optional. Currently Linux with a gcc that conforms to
54 C99 is supported for both 32 and 64 bit architectures.
56 [grid="all"]
57 `-------`---------------`---------------`--------------------------------------
58 CPU     OS              State           Notes
59 -------------------------------------------------------------------------------
60 x86_64  Debian          supported       Reference Platform
61 x86     other Linux     supported       Please report distro specific problems
62 armel   maemo5          supported       check fails in SDK (emulator bug)
63 x86*    MacOS X         supported
64 x86     OpenSolaris     mostly          Builds, but target check fails
65         *BSD            planned         Need volunteer for testing
66 -------------------------------------------------------------------------------
68 NoBug has few mandatory dependencies on other software and libraries,
69 some things such as valgrind support are optional and should be automatially
70 detected during the build, i.e., when ./configure is called. Nevertheless it
71 requires 'pkg-config' to be installed, you get some weird errors already at
72 bootstrapping (autoreconf) when this is not available.
75 Release Tarballs
76 ~~~~~~~~~~~~~~~~
78 Releases are available on:
79   http://www.pipapo.org/nobug-releases/
81 Gpg signed tarballs are being used for distribution. The first step involves
82 checking the signature:
84  $ gpg nobug-VERSION.tar.gz.gpg
86 This will produce a nobug-VERSION.tar.gz and report if the signature could be
87 validated.
89 Since they are built with gnu autotools, the usual build and install procedure
90 will work:
92  $ tar xzvf nobug-VERSION.tar.gz
93  $ cd nobug-VERSION
94  $ mkdir -p build
95  $ cd build
96  $ ../configure
97  $ make
98  $ make check           # optional, run the testsuite
99  $ make install         # depending on distribution and setup, do this as root
102 Development Version via git
103 ~~~~~~~~~~~~~~~~~~~~~~~~~~~
104 You can obtain a development version by using git.  The git repository can be
105 cloned via:
106 `git://git.pipapo.org/nobug` or mirrored at repo.or.cz
107 `git://repo.or.cz/nobug.git`.
109 Clone the git repository by:
111  $ git clone git://git.pipapo.org/nobug
113 After cloning the repository, then bootstrap the autotools:
115  $ cd nobug
116  $ autoreconf -i                # creates the configure file
118 Then the usual `cd build && ../configure && make && make install` (as above) will work.
119 Careful users may run `make check` to run a testsuite before installing.
122 Keeping Git Up To Date
123 ^^^^^^^^^^^^^^^^^^^^^^
125 To update to any new revision, just enter the nobug dir and
127  $ git pull
129 After that you can build as above (cd build && ../configure && make && make install).
130 This default pull will update from the 'master' branch which is meant to be an on-going
131 stable version (latest release + bugfixes).
133 What Is Installed
134 ~~~~~~~~~~~~~~~~~
136 Currently, NoBug installs the following:
138   * A single nobug.h headerfile. Include this in your code.
139   * Static libraries. Statically link these to your application:
140     - `libnobug.a` for singlethreaded programs.
141     - `libnobugmt.a` for multithreaded programs.
142   * Dynamic Libraries. Dynamically link these to your application:
143     - `libnobug.so` for singlethreaded programs.
144     - `libnobugmt.so` for multithreaded programs.
145     - associated libtool descriptors (`libnobug*.la`)
146   * Pkgconfig control files:
147     - `nobug.pc` for singlethreaded programs.
148     - `nobugmt.pc` for multithreaded programs.
149   * The `nobug_rbdump` utility to inspect NoBug ringbuffers.
152 .Generating This Documentation
154 There are Makefile targets for generating the documentation, Either one of the
155 following does what you may expect:
157  $ make nobug_manual.txt nobug_manual.html nobug_manual.pdf
159 building the documentation has quite some more dependencies than building
160 NoBug itself. Unless you are a packager you may want to refer to the online
161 doc or the shipped 'README' which is actually this full nobug manual.
162 Generating the documentation requires: gawk, asciidoc, graphviz and some
163 toolchains to further process docbook (dblatex, ...).
165 Using NoBug
166 -----------
168 Your application will have to include the header file 'nobug.h' before NoBug
169 can be used:
171  #include <nobug.h>
174 Once you've included the NoBug API in your application, you'll then have to select
175 a 'build-level'.  Build-levels are discussed later, c.f.,
176 xref:buildlevel[buildlevel].   Build-levels are used to define the amount of
177 information NoBug provides to you.  Maximum information is generally required while
178 developing an application and the ALPHA build-level is most apropriate during
179 this phase; whereas the released phase of an application will usually only require
180 sparse information, for which the RELEASE build-level has been conceived.
182 A build-level must always be specified, otherwise the compiler will complain
183 while attempting to compile your application.  You can specifiy a build level in
184 one of two ways: use a define statement in one of your modules, or pass the
185 build-level using the -D flag to your compiler.  Assuming we'd like to select
186 the ALPHA build-level in your application, then your module would assume the
187 following form:
190  #define EBUG_ALPHA
191  #include <nobug.h>
195 Subsequently you'll have to link the appropriate library to your application.
197 A number of different libraries are available to link depending on whether you
198 require to statically or dynamically link, or whether your application is multi
199 or single threaded.  The link order is important on your link line.  Link the NoBug
200 library 'after' your application's modules.  Here's how to statically link,
201 single-threaded applications:
203 [source,sh]
204 ----------------
205 gcc -o mybinary $(WHATEVER_FLAGS) mymodule1.o ... mymodulen.o  ..../libs/libnobug.a 
206 ----------------
208 However, for more flexibility in selecting a build-level, you might wish to
209 define various targets in your makefile, one for each build-level.  In such
210 cases, the -D flag in your makefile is most appropriate; so your link line for
211 an ALPHA build with multi-threaded support would look like the following: 
213 [source,sh]
214 ----------------
215 gcc -o mybinary -DEBUG_ALPHA $(WHATEVER_FLAGS) mymodule1.o ... mymodulen.o  ..../libs/libnobugmt.a 
216 ----------------
218 Both libraries must be initialised  before they can be used.  There are a number
219 of different ways to initialise the NoBug libraries.  One of the easiest ways
220 to initialise the NoBug libraries is to use the `NOBUG_INIT` macro, which must
221 be used before any features can be used or any thread is created. This is
222 discussed in more detail in the xref:multithreading[multithreading] chapter.  
224 So putting all this together, our application using NoBug might look something
225 like the following:
228 [source,sh]
229 ----------------
230 #include <nobug.h>   /* Include the NoBug API */
231 #define EBUG_ALPHA   /* If we have not used the -D Flag in our makefile */
233 int main()
235         NOBUG_INIT;  /* Initialise NoBug libs */
237         ...
239 ----------------
246 Many aspects of NoBug can be configured by overriding macros before 'nobug.h' is
247 included.
249 A project using NoBug can use autoconf to check for execinfo and
250 valgrind:
252  AC_CHECK_HEADER([execinfo.h], AC_DEFINE(HAVE_EXECINFO_H))
253  PKG_HAVE_DEFINE_WITH_MODULES(VALGRIND, [valgrind])
255 For Multithreaded programs, you should also check for the availability of pthreads
256 and flavour
258  ACX_PTHREAD
260 When the resulting `HAVE_PTHREAD`, `HAVE_EXECINFO_H` and
261 `HAVE_VALGRIND_H` are defined by the configure script, the
262 relevant features become available.
264 NoBug then defines `NOBUG_USE_PTHREAD`, `NOBUG_USE_VALGRIND` and
265 `NOBUG_USE_EXECINFO` to 1. If you do not want to use any of these features in
266 NoBug, you can override these macros by setting to 0 before including nobug.h.
268 If `NVALGRIND` is defined, there will be no support for valgrind.
272 There are many other macros which can be set and overridden by the user to
273 control behavior. Your help would be appreciated in expanding this documentation
274 if you find some features useful; or simply contact any of the authors.
278 .Using Nobug from a Project using autoconf
279 [source,sh]
280 ----------------
281 PKG_CHECK_MODULES(NOBUGMT_LUMIERA, [nobugmt >= 0.3rc1],
282                                  AC_DEFINE(HAVE_NOBUGMT_H),
283                                  AC_MSG_ERROR([NoBug pkg-config metadata missing])
285 ----------------
287 Checking for Additional Tools
288 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
290 Various peripheral tools can be used by NoBug depending on the requirements
291 of the application and the detail desired by the user.  Such tools can provide
292 additional, detailed information on the application and its behaviour.
293 However, some applications may not require such detail and the associated
294 overhead in information, and users may decide to omit excess information by
295 excluding such tools.
297 At the moment NoBug supports the optional inclusion of gdb, valgrind and support
298 for multi-threaded applications and the information that can be provided by
299 these tools.  However, support for other tools may be supplied in the future,
300 e.g. the dbx debugger on OpenSolaris. 
302 Such tools can be easily queried on the system and if they are available on a
303 particular system, they can be used by NoBug to provide even more information on
304 the application using NoBug.  If such tools are not available or are not
305 required by the user for one reason or other, then NoBug will happily function
306 as usual, just without the extra information.
308 Testing the availability of such tools on a particular system can be achieved
309 using autoconf, as illustrated in the following:
311 `*NOBUG_USE_VALGRIND*`::
312    `1`:: Use valgrind
313    `0`:: Do not use valgrind
315 `*NOBUG_USE_PTHREAD*`::
316    `1`:: Support for multi-thread applications
317    `0`:: Single-threaded applications
319 `*NOBUG_USE_EXECINFO*`::
320    `1`:: Backtrace information
321    `0`:: No backtrace information
323 These macros are then automatically defined when the configuration system
324 provides the associated `HAVE_*` macros, but can then be overridden by the user,
325 depending on the user's requirements.
328 Link Appropriate Library
329 ~~~~~~~~~~~~~~~~~~~~~~~~
331 Finally, the appropriate library (for either single or multi-threaded
332 applications) is linked to the project.
334    *libnobug*:: Link-in this library for single threaded applications.
335    *libnobugmt*:: Link with this library for multi-threaded applications.
337 NoBug installed static and dynamic libraries. When your application
338 uses multiple dynamic libraries which use NoBug or you build a dynamic
339 library, then you have to link against the dynamic library.
341 You can use the `pkg-config` tool to gather information about NoBug in
342 your build system.
344 Release builds remove all assertions, but logging is still kept. We
345 make the assumption that bugs which were not covered in alpha and beta
346 builds will not easily show up in releases because the assertions
347 there were not sufficient. Furthermore, end users are not test bunnies
348 and will not provide good bug reports anyway. If there is a problem in
349 a release build, try to track down the cause using a beta build from
350 the same source.
352 Initialization
353 --------------
355 Global init
356 ~~~~~~~~~~~
358 Before anything from NoBug can be used, NoBug must be initialised.  This is
359 performed by calling one of the `NOBUG_INIT_` macros.
361 The simpliest such macro among the initialising set is the following:
363   NOBUG_INIT()
365 `NOBUG_INIT` can be called more than once, subsequent calls will be a no-op,
366 thus initialising in main and in libraries won't interfere with one another.
368 In other words, `NOBUG_INIT` is usually the first call to NoBug.
370 .Destroying NoBug
371 Since NoBug is intended to be available throughout its whole lifetime,
372 destroying it is not to be advised. Nevertheless, there is a destroy function
373  void nobug_destroy (void)
375 to shutdown NoBug, and this frees all resources associated with it.
376 This is mostly used in the NoBug testsuite itself to check for leaks,
377 and it might be useful for other programs which employ some kind of
378 leak checker.
380 Init logging Flags
381 ~~~~~~~~~~~~~~~~~~
383 If you want to use environment variable controlled debuging, then you have to
384 initialize each defined flag with
386   NOBUG_INIT_FLAG(flagname)
390   NOBUG_INIT_FLAG_LIMIT(flagname, default)
392 or one of the C++ compatibility macros.
394 This is documented later in the xref:logconfig[logging configuration] chapter.
396 Threads
397 ~~~~~~~
399 In Multithreaded programs you should assign an identifier to each
400 thread. A thread identifier is a string which will be automatically
401 appended with an underscore and a incrementing integer. It is is created with:
403   NOBUG_THREAD_ID_SET(name)
405 Calling `NOBUG_THREAD_ID_SET("worker")` will yield in a thread
406 identifier 'worker_1' for example.
408 If you don't set an identifier, then NoBug will assign an automatic one.
409 This is further documented in the xref:multithreading[multi threading]
410 section of this manual.
412 [[initexample]]
413 .Initialization
414 [source,c]
415 -------------------------------------------------------
416 #include "nobug.h"
417 NOBUG_DEFINE_FLAG(example);
421 int main()
423     NOBUG_INIT();
424     NOBUG_THREAD_ID_SET("main");
425     NOBUG_INIT_FLAG(example);
427     ...
429 -------------------------------------------------------
431 [[buildlevel]]
432 Debugging Information Granuality: The Build Levels
433 --------------------------------------------------
435 There are three different levels of debugging information available: alpha, beta
436 and release.  One of these levels must be specified before compiling, otherwise
437 an error while compiling will occur.
440   *ALPHA*::
441         This debugging level is envisaged for the development phase of a project
442         where exhaustive testing and logging are required.
443   *BETA*::
444         This debugging level is more appropriate for projects beyond the
445         development phase and ready for trials in the field and users willing to
446         test the software.
447   *RELEASE*::
448         This level is for final, end-users.
450 .Select a Build Level
451 A logging level can be selected by either using a define in one of the
452 applications' modules, or by passing the appropriate level using the -D switch
453 to the compiler:
455     *ALPHA*::   -DEBUG_ALPHA (`#define EBUG_ALPHA`)
457     *BETA*::    -DEBUG_BETA (`#define EBUG_BETA`)
459     *RELEASE*:: -DNDEBUG (`#define NDEBUG`)
461 If none of the above switches has been set, NoBug will abort the
462 compilation with an error.
464 Logging
465 -------
467 Nearly all NoBug Macros emit some log message. NoBug gives the user fine
468 grained control over these log messages to display only interesting information
469 without loosing details.
471 Log messages can be routed to various destinations.  The following destintaions
472 are available: 
474   *RINGBUFFER*::
475         The underlying storage backend. Messages are appended to the
476         end of the buffer, overwriting older messages at the front of
477         the buffer. NoBug comes with a highly efficient ringbuffer
478         implementation. This ringbuffer is temporary by default but
479         can be made persistent on disk which can be inspected with the
480         'nobug_rbdump' tool.
482   *CONSOLE*::
483         This is either just stderr, or, if running under a supported
484         debugger, the debuggers facilities to print messages will be used.
486   *FILE*::
487         The user can open files for log messages.
489   *SYSLOG*::
490         Messages are sent to the standard system logging daemon.
492   *APPLICATION*::
493         There are hooks which allow the programmer to catch logmessages and
494         display them in an application which are defined by the application.
496 Each logmessage has a priority describing its severity in the same way as
497 syslog messages do.
499 All non-fatal messages are associated with a programmer defined flag describing
500 the source of the message (subsystem, module, ...).
502 Putting this all together: A user can define which source/flag will be logged at
503 what priority level and to which destination. To make this all easier, NoBug
504 tries to provide reasonable defaults.
506 [[logconfig]]
507 Configuration
508 ~~~~~~~~~~~~~
510 .Log Levels
512 Each log macro has an explicit or implicit log-level which
513 correspondends to syslog levels. Logging is only emitted when the
514 message is more severe or the same as a defined limit.
516 [[logdefaults]]
517 .Default levels for logging
518 [grid="all"]
519 `````~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
520              , ALPHA, BETA   , RELEASE,
521 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
522 *ringbuffer* , TRACE, INFO   , NOTICE , ringbuffer must always be most verbose
523 *console*    , INFO , NOTICE , -1     , no log to console in release
524 *file*       , TRACE, NOTICE , WARNING,
525 *syslog*     , -1   , NOTICE , WARNING, no syslog for test runs
526 *application*, INFO , WARNING, ERROR  ,
527 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
529 Depending on the build level, there is a default logging target and a default
530 limit which is selected when the user doesn't specify one.
532 The following default limits are available:
534   * In *ALPHA* builds, `NOBUG_LOG_LIMIT_ALPHA` is used which defaults to `LOG_INFO`
535   * In *BETA* builds, `NOBUG_LOG_LIMIT_BETA` is used and defaults to `LOG_WARNING`
536   * In *RELEASE* builds, `NOBUG_LOG_LIMIT_RELEASE` is used and defaults to `LOG_CRIT`
538 The default targets are:
540   * In *ALPHA* builds, `NOBUG_LOG_TARGET_ALPHA` is used which defaults to
541     `NOBUG_TARGET_CONSOLE`
542   * In *BETA* builds, `NOBUG_LOG_TARGET_BETA` is used and defaults to
543     `NOBUG_TARGET_FILE`
544   * In *RELEASE* builds, `NOBUG_LOG_TARGET_RELEASE` is used and defaults to
545     `NOBUG_TARGET_SYSLOG`
548 You can override all these values with your own values. As an alternative,
549 `NOBUG_LOG_LIMIT` and `NOBUG_LOG_TARGET` can be defined before
550 including "nobug.h" to override all defaults.
552 [[logflags]]
553 Log Flags
554 ~~~~~~~~~
556 Flags are used to inform NoBug about subsystems/modules or even finer
557 grained sections of the code. These are referred to as 'channels' in other 
558 logging libraries.
560 A flag should be declared in a headerfile using the following mechanism:
562 [[DECLARE_FLAG]]
563  NOBUG_DECLARE_FLAG(flagname)
565 It is advisable to do so in one of your header files.
567 Furthermore, the flag must be defined in some implementation file by using one
568 of the following schemes:
570 [[DEFINE_FLAG]]
571  NOBUG_DEFINE_FLAG(flagname)
575 [[DEFINE_FLAG_LIMIT]]
576  NOBUG_DEFINE_FLAG_LIMIT(flagname, limit)
578 Moreover, macros are available that accept a 'parent' flag as a parameter, which is then
579 used to initialize the defaults from another flag:
581 [[DEFINE_FLAG_PARENT]]
582  NOBUG_DEFINE_FLAG_PARENT(flagname, parent)
586 [[DEFINE_FLAG_PARENT_LIMIT]]
587  NOBUG_DEFINE_FLAG_PARENT_LIMIT(flagname, parent, limit)
589 This can be used to create hierachies of flags
592 [[Cplusplus_logflags]]
593 .C++ support, C++ logflags
595 Additional macros are available for applications written in C++:
597  NOBUG_CPP_DEFINE_FLAG(name)
598  NOBUG_CPP_DEFINE_FLAG_PARENT(name, parent)
599  NOBUG_CPP_DEFINE_FLAG_LIMIT(name, default)
600  NOBUG_CPP_DEFINE_FLAG_PARENT_LIMIT(name, parent, default)
602 These macros statically initialize the flags when they are defined, there is no
603 need to call `NOBUG_INIT_FLAG()` (see below).
606 .Force declarations only
608 When the the following preprocessor constant is defined to be `1`:
610 [[DECLARE_ONLY]]
611  NOBUG_DECLARE_ONLY
613 then *all* definitions here (`NOBUG_DEFINE_*`)
614 become declarations only.  When this is defined to be `0` (which is the
615 default) then all definitions behave as described.
616 This can be used to construct a headerfile which only contains
617 definitions, but, by default, yield only declarations. This provides one
618 convenient single point to maintain flag configurations.
620 .Maintaining flags in a single header 'flags.h'
621 [source,c]
622 ----
623 #include <nobug.h>
626  if not included from flags.c then declare the flags,
627  else define them
628  */
629 #ifndef FLAGS_C
630 #define NOBUG_DECLARE_ONLY 1
631 #endif
633 /* use only DEFINE_FLAG here */
634 NOBUG_DEFINE_FLAG(example);
637  Reset it to 0 to cause no trouble
638  */
639 #ifndef FLAGS_C
640 #undef NOBUG_DECLARE_ONLY
641 #define NOBUG_DECLARE_ONLY 0
642 #endif
643 ----
645 .flags.c
646 [source,c]
647 ----
648 #define FLAGS_C
649 #include "flags.h"
651 ----
654 .Logging Flag Initialization
656 Next you should call
658  NOBUG_INIT_FLAG(flagname)
662  NOBUG_INIT_FLAG_LIMIT(flagname, default)
664 once at the start of your program for each flag.
666 For flags defined with `NOBUG_DEFINE_FLAG(flagname)` the defaults are initialized
667 as in the xref:logdefaults[table above], while
668 `NOBUG_DEFINE_FLAG_LIMIT(flagname, level)` is used to initialize the
669 default target (depending on build level) to `level`.
671 [[NOBUG_ENV]]
672 Control what gets logged
673 ~~~~~~~~~~~~~~~~~~~~~~~~
675 The `NOBUG_INIT_FLAG...` calls parsing the environment variable
676 'NOBUG_LOG' to configure what gets logged at runtime. The syntax is as
677 following:
679 .Formal Syntax for log control
680 [source,prolog]
681 ----
682  logdecl_list --> logdecl, any( ',' logdecl_list).
684  logdecl --> flag, opt(limitdecl, any(targetdecl)).
686  flag --> "identifier of a flag".
688  limitdecl --> ':', "LIMITNAME".
690  targetdecl --> '@', "targetname", opt(targetopts).
692  targetopts --> '(', "options for target", ')', opt(targetopts).
693 ----
695 Roughly speaking, 'NOBUG_LOG' contains a comma separated list of declarations for
696 flags which are the name of the flag followed by a limit which is written in
697 all uppercase letters and preceeded by a colon, followed by target declarations
698 which are names of the targets, introduced by a at sign. Target declarations
699 can have option, described in the next section. Limit and target
700 declarations are optional and then choosen from the defaults table above. These
701 defaults are currently just an guess what should be useable and might be
702 redefined in future.
704 .Targets and Options
706 The Following options are available:
708  `@ringbuffer`::
709    `(file=_filename_)`:: set filename backing the ringbuffer
710    `(size=_nnn_)`::      set size of the ringbuffer
711    `(append)`::          don't erase existing ringbuffer
712    `(keep)`::            keep file after application end
713    `(temp)`::            unlink file instantly at creation
715  `@console`::
716    `(fd=n)`::            redirect console output to fd n
718  `@file`::
719    `(name=_filename_)`:: log to filename
720    `(append)`::          append to (existing) log
722  `@syslog`::
723    `(ident=_name_)`::    global prefix for syslog
724    `(cons)`::            log to system console if syslog is down
725    `(pid)`::             include pid in log
726    `(perror)`::          log to stderr as well
729 .How the NOBUG_LOG is used
730 [source,sh]
731 ----
732 # set the limit of the default target a default limit (see table above)
733 NOBUG_LOG='flag,other'
735 # set the limit of the default target to DEBUG
736 NOBUG_LOG='flag:DEBUG'
738 # set console and syslog limits for flag to DEBUG
739 NOBUG_LOG='flag:DEBUG@console@syslog'
741 # trace 'other' to a persistent ringbuffer
742 NOBUG_LOG='other:TRACE@ringbuffer(file=log.rb)(size=8192)(keep)'
743 ----
745 .Using log flags (example.c)
746 [source,c]
747 ----
748 #include "nobug.h"
750 NOBUG_DEFINE_FLAG (test);
752 int main()
754    /* NOBUG_INIT;  // not needed because of NOBUG_INIT_FLAG */
755    NOBUG_INIT_FLAG (test);
757    TRACE (test, "Logging enabled");
758    TRACE (NOBUG_ON, "Always on");
760 ----
762 .test it:
763 [source,sh]
764 ----
765 $ cc -DEBUG_ALPHA -lnobug example.c
766 $ ./a.out
767 0000000002: TRACE: example.c:11: main: Always on
769 $ NOBUG_LOG=test:TRACE ./a.out
770 0000000001: TRACE: example.c:10: main: Logging enabled
771 0000000002: TRACE: example.c:11: main: Always on
772 ----
774 Predefined Flags
775 ~~~~~~~~~~~~~~~~
777 There are some debugging flags which are predefined by NoBug.
779 [[NOBUG_ON]]
780 .NOBUG_ON
782 The flag `NOBUG_ON` is always enabled at LOG_DEBUG level. This is
783 static and can not be changed.
785 [[NOBUG_ANN]]
786 .NOBUG_ANN
788 The flag `NOBUG_ANN` is used for the source annotations. This is
789 static and can not be changed. It differs from `NOBUG_ON` as in
790 never logging to syslog and only define a LOG_WARNING limit for the
791 application callback.
793 [[nobug_flag]]
794 .nobug (flag)
796 Actions on NoBug itself will be logged under the `nobug` flag itself.
797 When you want to see whats going on (useful to check if you call
798 `NOBUG_INIT_FLAG()` on all flags) you can enable it with `NOBUG_LOG=nobug:TRACE`.
800 Macros
801 ------
803 The NoBug interface is almost completely implemented using
804 preprocessor macros. This is required because NoBug uses the
805 `+++__FILE__+++`, `+++__LINE__+++` and `+++__func__+++` macros to
806 log information on the current file, line number and function.
807 Moreover, all the flat namespace uppercase identifiers make it ease
808 to recognise the macros in source code.
810 All macros are available without condition with a `NOBUG_...` prefix.
811 Many macros (the common cases) are also available without this prefix
812 as a convenience, however macros without this prefix must not have
813 been previously defined. When `NOBUG_DISABLE_SHORTNAMES` is defined
814 before including 'nobug.h', then only the `NOBUG_` prefixed macros
815 are available and the short forms will never be defined.
817 A set of macros are provided by NoBug that are postfixed by `..._IF`.
818 These macros have the following form:
820   * `..._IF(when, ...)`
822 They perform the desired action only if `when` is true. For example:
824   * `REQUIRE_IF(foo != NULL, foo->something == constrained)`
826 The assertion will only be performed if `foo` is non `NULL`.
828 NoBug also also contains a facility to pass the source context (file,
829 line, function) around, this can be used to write functions which
830 handle things where one is more interested in the context of the caller
831 than the location where the macros appears.
833 This macros are postfixed with `..._CTX` and take an extra context
834 parameter (usually at last but before the logging format specifier and
835 any variable argument list). The context parameter must be of type
836 `const struct nobug_context`.
838 When the `_CTX` context form is used together with the conditional `_IF`
839 form then the suffix of the macros is always `..._IF_CTX`.
841 The macros which take a context have no short form and must always be
842 prefixed with `NOBUG_...`.
844 Parameters types
845 ~~~~~~~~~~~~~~~~
847 We use names for parameters which describe their type. These names are
848 orthogonal through all macro definitions.
850 [grid="all"]
851 `---------`------------------------------------------------------------------
852 `when`    Assertion is only performed if expression `when` is true at runtime
853 `expr`    Test without side effects
854 `flag`    Flag to enable custom logging groups
855 `type`    Data type to be checked as a single identifier name
856 `pointer` Pointer to type
857 `lvl`     Log level
858 `depth`   Depth for invariants and dumps
859 `context` Source context of type `struct nobug_context`
860 `...`     printf-like format string followed by its arguments
861 ---------------------------------------------------------------------------
863 [[NOBUG_CONTEXT]]
864 Source Contexts
865 ~~~~~~~~~~~~~~~
866  NOBUG_CONTEXT
867  NOBUG_CONTEXT_NOFUNC
869 NoBug passes information about the source location of a given statement in
870 `const struct nobug_context` structures. These can be generated with
871 `NOBUG_CONTEXT` or `NOBUG_CONTEXT_NOFUNC`. The later one doesn't define a
872 function name and must be used when the function context is not available
873 like in static initialization etc..
875 Assertions
876 ----------
878 [[CHECK]]
879 .CHECK
880  CHECK(expr, ...)
881  CHECK_IF(when, expr, ...)
883 This assertion is never optimized out. Its main purpose is for implementing
884 testsuites where one want to assert tests independent of the build level
886 [[REQUIRE]]
887 .REQUIRE
888  REQUIRE(expr, ...)
889  REQUIRE_IF(when, expr, ...)
890  NOBUG_REQUIRE_CTX(expr, context,...)
891  NOBUG_REQUIRE_IF_CTX(when, expr, context, ...)
893 Precondition (input) check. Use these macros to validate input a
894 function receives. The checks are enabled in *ALPHA* and *BETA* builds and
895 optimized out in *RELEASE* builds.
897 [[ENSURE]]
898 .ENSURE
899  ENSURE(expr, ...)
900  ENSURE_IF(when, expr, ...)
901  NOBUG_ENSURE_CTX(expr, context, ...)
902  NOBUG_ENSURE_IF_CTX(when, expr, context, ...)
904 Postcondition (progress/output) check. Use these macros to validate the
905 data a function produces (example: return value). `ENSURE` is enabled
906 unconditionally in *ALPHA* builds and optimized out in *BETA* builds for
907 scopes which are tagged as `CHECKED`.
909 The `ENSURE_IF` variants are enabled in *ALPHA* and *BETA* builds.
911 In *RELEASE* builds this checks are
912 always optimized out, scopes tagged as `UNCHECKED` are not permitted.
914 [[ASSERT]]
915 .ASSERT
916  ASSERT(expr, ...)
917  ASSERT_IF(when, expr, ...)
918  NOBUG_ASSERT_CTX(expr, context, ...)
919  NOBUG_ASSERT_IF_CTX(when, expr, context, ...)
921 Generic check. Use these macros when you want to validate something
922 which doesn't fall into one of the above categories. A example is when
923 a library function can return a unexpected result (scanf with syntax
924 error in the formatstring, when a constant/literal formatstring is
925 expected). The checks are enabled in *ALPHA* and *BETA* builds and
926 optimized out in *RELEASE* builds.
928 [[assert]]
929 .assert
930  assert(expr)
932 NoBug overrides the standard `assert` macro, using `NOBUG_ASSERT`.
933 This is just a compatibility feature, its use is not suggested.
935 [[INVARIANT]]
936 .INVARIANT
937  INVARIANT(type, pointer, depth)
938  INVARIANT_IF(when,type, pointer, depth)
939  INVARIANT_ASSERT(expr, ...)
941 Checking invariants. You can provide more complex checking functions
942 which test the validity of datastructures. Invariants are only enabled
943 in *ALPHA* builds for scopes which are not tagged as `CHECKED` and
944 otherwise optimized out.
946  TODO: describe how to create invariant checks
948 Logging Macros
949 --------------
951 Logging targets a flag (except for `ECHO`) and is done at a log-level relating to syslog levels.
953 NOTE: there is no logging macro for `LOG_EMERG`, this is only used by the assertions as fatal message
955 [[ECHO]]
956 .ECHO
957  ECHO(...)
959 Never optimized out, logs at LOG_NOTICE level. Its main purpose is for implementing
960 testsuites where one want to print and log messages independent of the build level
962 [[ALERT]]
963 .ALERT
964  ALERT(flag, ...)
965  ALERT_IF(when, flag, ...)
966  NOBUG_ALERT_CTX(flag, context, ...)
967  NOBUG_ALERT_IF_CTX(when, flag, context, ...)
969 This is the most critical condition an application might log. This might be used
970 if an error occurs which can not be handled except a safe shutdown for example.
972 [[CRITICAL]]
973 .CRITICAL
974  CRITICAL(flag, ...)
975  CRITICAL_IF(when, flag, ...)
976  NOBUG_CRITICAL_CTX(flag, context, ...)
977  NOBUG_CRITICAL_IF_CTX(when, flag, context, ...)
979 An error which can not be handled occured but the application does not need to be
980 shutdowen, perhaps waiting for an operator to fix the cause.
982 [[ERROR]]
983 .ERROR
984  ERROR(flag, ...)
985  ERROR_IF(when, flag, ...)
986  NOBUG_ERROR_CTX(flag, context, ...)
987  NOBUG_ERROR_IF_CTX(when, flag, context, ...)
989 Application takes a error handling brach
991 [[WARN]]
992 .WARN
993  WARN(flag, ...)
994  WARN_IF(when, flag, ...)
995  NOBUG_WARN_CTX(flag, context, ...)
996  NOBUG_WARN_IF_CTX(when, flag, context, ...)
998 Rare, handled but unexpected branch
1000 [[INFO]]
1001 .INFO
1002  INFO(flag, ...)
1003  INFO_IF(when, flag, ...)
1004  NOBUG_INFO_CTX(flag, context, ...)
1005  NOBUG_INFO_IF_CTX(when, flag, context, ...)
1007 Message about program progress
1009 [[NOTICE]]
1010 .NOTICE
1011  NOTICE(flag, ...)
1012  NOTICE_IF(when, flag, ...)
1013  NOBUG_NOTICE_CTX(flag, context, ...)
1014  NOBUG_NOTICE_IF_CTX(when, flag, context, ...)
1016 More detailed progress message
1018 [[TRACE]]
1019 .TRACE
1020  TRACE(flag, ...)
1021  TRACE_IF(when, flag, ...)
1022  NOBUG_TRACE_CTX(flag, context, ...)
1023  NOBUG_TRACE_IF_CTX(when, flag, context, ...)
1025 Very fine grained messages
1027 NOTE: that `TRACE` corresponds to `LOG_DEBUG`, because using `DEBUG` could be ambiguous.
1029 [[LOG]]
1030 .LOG
1031  NOBUG_LOG_CTX(flag, lvl, context, ...)
1032  NOBUG_LOG_IF_CTX(when, flag, lvl, context, ...)
1034 Generic logging macro which takes the level explicitly,
1035 avoid this, unless you implement your own logging facilities.
1037 [[LOG_BASELIMIT]]
1038 .LOG_BASELIMIT
1039  NOBUG_LOG_BASELIMIT_ALPHA
1040  NOBUG_LOG_BASELIMIT_BETA
1041  NOBUG_LOG_BASELIMIT_RELEASE
1042  NOBUG_LOG_BASELIMIT
1044 anything more detailed than this base limits will be optimized out.
1045 This is used to reduce the logging overhead for *RELEASE* builds.
1046 By default the limit is set to `LOG_DEBUG` for *ALPHA* and *BETA*
1047 builds, so all logging is retained and `LOG_NOTICE` in *RELEASE*
1048 builds to log the application progress only coarsely then.
1050 This macros can be defined before including 'nobug.h' to some other
1051 log level (as defined in 'syslog.h').
1053 [[dumping]]
1054 Dumping Datastructures
1055 ----------------------
1057 TODO How to write DUMP handlers
1059 One can write functions for dumping complex datastructures using the NoBug
1060 facilities. This is done by writing a custom function for each
1061 datastructure to be dumped which may recursively call other dumping
1062 functions. There are macros for logging within such a dumper function
1063 and for initiating a dump of a given datastructure.
1065 A dump function has the prototype:
1067 [source,c]
1068 -------------------------------------------------------
1069 void
1070 nobug_NAME_dump (const struct NAME* POINTER,
1071                  const int DEPTH,
1072                  const struct nobug_context CONTEXT,
1073                  void* EXTRA);
1074 -------------------------------------------------------
1076 where NAME is the identifier for what you want to dump, POINTER is a pointer
1077 to the data to be dumped, DEPTH is a integer which will be decremented when
1078 recursing into the datastructure dumper (your dump function does that, see
1079 below) to limit the recursion depth, CONTEXT is a source context generated by
1080 nobug when you call DUMP() and EXTRA is a pointer transparently passed around
1081 you can use to store some extra state.
1082 [[DUMP]]
1083 .DUMP
1084  DUMP(flag, type, pointer, depth, extra)
1085  DUMP_IF(when, flag, type, pointer, depth, extra)
1087 This macros call a datastructure dump of the object (`pointer`) in question.
1088 `DUMP` is only available in *ALPHA* and *BETA* builds, `DUMP_IF` is also
1089 enabled for the RELEASE builds.
1091 `extra` is a void* which is transparently passed around and can be used to
1092 pass some state around. NoBug does not touch it.
1094 [[DUMP_LOG]]
1095 .DUMP_LOG
1096  DUMP_LOG(...)
1097  DUMP_LOG_IF(when, ...)
1099 Any output from `DUMP` handlers should be done by these macros.
1101 Dumping is by default done on level `LOG_DEBUG`, this can be overridden by
1102 defining `NOBUG_DUMP_LEVEL` to some other level.
1104 .How to use the DUMP facilities
1106 [source,c]
1107 -------------------------------------------------------
1108 struct STRUCTNAME
1110   int INTEGER_MEMBER;
1111   char * STRING_MEMBER;
1112   struct STRUCTNAME* next;
1114 -------------------------------------------------------
1116 then you define a function like:
1118 [source,c]
1119 -------------------------------------------------------
1120 void
1121 nobug_STRUCTNAME_dump (const struct STRUCTNAME* self,
1122                        const int depth,
1123                        const struct nobug_context context,
1124                        void* extra)
1126   // check for self != NULL and that the depth
1127   // limit did not exceed in recursive datastructures
1128   if (self && depth)
1129   {
1130     // you may or may not do something with the extra parameter here
1131     // extra is transparently passed around
1132     (void) extra;
1134     // use DUMP_LOG not LOG to print the data
1135     DUMP_LOG("STRUCTNAME %p: int is %d, string is %s", self,
1136                              self->INTEGER_MEMBER,
1137                              self->STRING_MEMBER);
1139     // now recurse with decremented depth
1140     nobug_STRUCTNAME_dump (self->next, depth-1, context, extra);
1141   }
1143 -------------------------------------------------------
1145 now you can use the DUMP() macros within the code
1147 [source,c]
1148 -------------------------------------------------------
1149 example()
1151   struct STRUCTNAME foo;
1152   init(&foo);
1154   // extra can be anything, NULL is suggested when you don't use it
1155   DUMP (my_flag, STRUCTNAME, &foo, 2, NULL);
1157 -------------------------------------------------------
1159 Source Annotations
1160 ------------------
1162 One can tag features as:
1164 [[DEPRECATED]]
1165 .DEPRECATED
1166  DEPRECATED(...)
1168 Something which shouldn't be used in future
1170 [[UNIMPLEMENTED]]
1171 .UNIMPLEMENTED
1172  UNIMPLEMENTED(...)
1174 not yet finished feature
1176 [[FIXME]]
1177 .FIXME
1178  FIXME(...)
1180 known bug to be fixed later
1182 [[TODO]]
1183 .TODO
1184  TODO(...)
1186 enhancement to be done soon
1188 [[PLANNED]]
1189 .PLANNED
1190  PLANNED(...)
1192 future enhancement
1194 [[NOTREACHED]]
1195 .NOTREACHED
1196  NOTREACHED(...)
1198 used to tag code-path which shall be never executed.
1200 [[ELSE_NOTREACHED]]
1201 .ELSE_NOTREACHED
1202  ELSE_NOTREACHED(...)
1204 same as `else NOTREACHED()`, but wholly optimized out in release builds.
1207 The advantage of this tagging over plain source comments is that we can take
1208 some actions if we run in such a tag at compile or runtime:
1210 the action to be taken when such a macro is hit depends on the build level:
1212 [grid="all"]
1213 `-------------`-----`------------`-----------------------------------------
1214               ALPHA BETA         RELEASE
1215 ---------------------------------------------------------------------------
1216 DEPRECATED    log   nothing      wont compile
1217 UNIMPLEMENTED abort abort        wont compile
1218 FIXME         log   wont compile wont compile
1219 TODO          log   log          wont compile
1220 PLANNED       log   nothing      nothing
1221 NOTREACHED    abort abort        removed
1222 ---------------------------------------------------------------------------
1224 Legend:
1226   * abort means first log and then abort
1227   * log will only log once for each sourceline (not on each hit)
1228   * wont compile will abort compilation with a error message
1229   * nothing optimized out, sane way
1230   * removed optimized out for performance reasons
1232 [[CHECKED]]
1233 Scope Checks
1234 ------------
1235 [[UNCHECKED]]
1237 The programmer can tag any scope as `UNCHECKED` or `CHECKED`. In *ALPHA* and *BETA*
1238 builds, a global `UNCHECKED` is implied. In *RELEASE* builds, `UNCHECKED` scopes are
1239 not allowed.
1241 .Assertions active depending on Build level and Scope
1242 [grid="all"]
1243 `-----------`-----------------------------------------`-----------------------------`-------------------
1244             *ALPHA*                                   *BETA*                        *RELEASE*
1245 *UNCHECKED* Preconditions, Postconditions, Invariants Preconditions, Postconditions compiling will abort
1246 *CHECKED*   Preconditions, Postconditions             Preconditions
1247 ------------------------------------------------------------------------------------------------------
1249 Fault injection
1250 ---------------
1252 NoBug has some macros which can be used to simulate errorneous behaviour:
1254 [[INJECT_GOODBAD]]
1255 .INJECT_GOODBAD
1256  INJECT_GOODBAD(expr, good, bad)
1258 substitutes to an expression and returns good when expr is false and
1259 bad when expr is true. In BETA and RELEASE builds 'good' is always returned.
1261 [[INJECT_FAULT]]
1262 .INJECT_FAULT
1263  INJECT_FAULT(expr, bad)
1265 substitutes to a statement which executes 'bad'
1266 when expr is true. Optimitzed out in BETA and RELEASE builds.
1268 [[INJECT_LEVEL]]
1269 .INJECT_LEVEL
1270 In both cases, when a fault is injected it will be logged at
1271 `NOBUG_INJECT_LEVEL` (default: `LOG_NOTICE`). This can be defined
1272 before including 'nobug.h' to override it.
1274 Fault coverage checking
1275 -----------------------
1277 CAUTION: Fault coverage checking is a experimental feature!
1279 Nobug can automatically inject faults at instrumented points and permute
1280 through all potential error paths of an application by restarting it with the
1281 state from the former run. It can be used to give answers to the question if
1282 any possible error is sufficiently handled in the application. Fault coverage
1283 checking is only available in ALPHA builds and optimized out otherwise.
1285 NOTE: This kind of testing is very expensive.
1287 How does automatic fault injection work
1288 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1290 First NoBug checks if the environment variable `NOBUG_COVERAGE` is set, if yes
1291 it must contain a space, comma or semicolon separated list of filename which
1292 are the logs from the previous run. This logs are then parsed for the states
1293 of the previous run, storing these in a lookup tree.
1295 After that the application proceeds as usual, when it then hits an
1296 instrumented coverage point it is checked against the already recorded states.
1297 Any so far unseen failure point injects a fault, the last seen but previously
1298 failed point will be pass now, all other fault injection points act like on
1299 their previous run. This ensures that each successive run of the application
1300 changes only one injection point and thus permutes through all possible code
1301 paths.
1303 Fault injection points are identified by a 64bit hash over the backtrace
1304 (return addresses on the stack) leading to it. This means each unique way to
1305 reach a injection point is recorded. Parameters and threads are intentionally
1306 not considered in this calculation.
1309 How to invoke fault-coverage checking
1310 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1312 Each fault-injection point emits a logging message about its identity and
1313 state, this logging uses the normal NoBug logging facilities. Thus one can
1314 control the logging with the `NOBUG_LOG` environment variable. Additionally
1315 fault coverage checking is only active when the `NOBUG_COVERAGE` environment
1316 variable was set to point some log files which are the results from the
1317 previous run. NoBug comes with a `tests/coverage.sh` example script which
1318 permutes through all possible error paths.
1320 Coverage checking Macros
1321 ------------------------
1323 [[COVERAGE_FAULT]]
1324 .COVERAGE_FAULT
1325  COVERAGE_FAULT(flag, ...)
1327 Injects the statement at `...` when simulating an failure. Only active in
1328 ALPHA builds.
1330 [[COVERAGE_GOODBAD]]
1331 .COVERAGE_GOODBAD
1332  COVERAGE_GOODBAD(flag, good, bad)
1334 Substitutes to an expression and injects `bad` when simulating an failure and `good`
1335 otherwise. Only active in ALPHA builds.
1337 [[COVERAGE_LEVEL]]
1338 .COVERAGE_LEVEL
1339  #define NOBUG_COVERAGE_LEVEL ...
1341 Logging level at what fault-coverage logging is emitted.
1343 NOTE: Supressing log output with this level will not supress fault injection,
1344       actually the opposite is true since every new seen failure path gets injected.
1345       This might be changed in future releases.
1347 [[COVERAGE_DISABLE]]
1348 .Disabling and enabling fault-coverage checks
1349  NOBUG_COVERAGE_DISABLE
1350  NOBUG_COVERAGE_ENABLE
1352 Sometimes fault injection yields false positives, errors which may never happen in real life
1353 (and are possibly enforced with a ENSURE afterwards). For this cases coverage fault injection can be
1354 disabled temporarly and reenabled later. Disabling/enabling may nest and must properly match.
1356 Resource Tracking
1357 -----------------
1359 With little effort, NoBug can watch all kinds of resources a program uses. This
1360 becomes useful for resources which are distributed over a multithreaded
1361 program. Resource tracking includes logging actions on resource and checking
1362 locking policies over acquired resources. Resource logging is active in ALPHA
1363 and BETA builds when NOBUG_RESOURCE_LOGGING is defined to 1 (the default).
1364 The resource tracker which supervises locking policies is only enabled in
1365 ALPHA builds.
1367 Concepts
1368 ~~~~~~~~
1370 Resources are abstracted, NoBug has little knowledge about the semantics of a
1371 resource, it only keeps records of resources and the code using it and ensures
1372 basic constraints. Detailed usage checks of resource have to be done with other
1373 NoBug facilities.
1375 Resources are identified by a arbitrary identifier which is just a
1376 pointer. Additionally a name, the type and the source locations which
1377 announced the resource are stored.
1379 Code which wants to use a resource calls a enter macro with its own identifier
1380 and state, then might alter the state and finally a leave macro when finished
1381 with it.
1383 When a resource is used one has to pass one of this states:
1385   * NOBUG_RESOURCE_WAITING
1386       + For resources where acquisition could block (locks) you enter it with a
1387         WAITING state first and as soon you acquired it you change the state to one
1388         of the following.
1389   * NOBUG_RESOURCE_EXCLUSIVE
1390       + Acquired the resource exclusively. It must not be acquired
1391         again, not even from the same thread.
1392   * NOBUG_RESOURCE_RECURSIVE
1393       + The resource might be entered multiple times from the same
1394         thread with this state.
1395   * NOBUG_RESOURCE_SHARED
1396       + The resource might be entered multiple times from any thread
1397         with this state.
1399 Possible state transitions:
1401 ["graphviz", "resource-transistinons.png"]
1402 ---------------------------------------------------------------------
1403 strict digraph G
1405         edge [fontname=Courier fontsize=10]
1407         start [shape=ellipse]
1409         node [shape=box]
1411         start -> Waiting [label="ENTER()"]
1412         start -> Exclusive [label="ENTER()"]
1413         start -> Recursive [label="ENTER()"]
1415         Waiting -> Exclusive [label="STATE()"]
1416         Waiting -> Recursive [label="STATE()"]
1418         Recursive -> Recursive [label="ENTER()\nSTATE()"]
1420         Waiting -> end [label="LEAVE()"]
1421         Exclusive -> end [label="LEAVE()"]
1422         Recursive -> end [label="LEAVE()"]
1424         end [shape=ellipse]
1426 ---------------------------------------------------------------------
1428 Notes
1429 ~~~~~
1431 There are small race conditions between logging and checking resource tracking
1432 and the actual call to the resource using function. This is a design decision
1433 there is no way to account for this exactly when the function call may block.
1435 The Resource Tracker relies on proper announce/forget and enter/leave
1436 are properly pairing. The programmer should ensure that this is done
1437 right, otherwise the results are unpredictable.
1439 Resource tracking macros
1440 ~~~~~~~~~~~~~~~~~~~~~~~~
1442 [[RESOURCE_LOGGING]]
1443 [[RESOURCE_LOG_LEVEL]]
1445 Unless the user defines `NOBUG_RESOURCE_LOGGING` to 0 each of the above macros
1446 will emit a log message at `NOBUG_RESOURCE_LOG_LEVEL` which defaults to
1447 `LOG_DEBUG`.
1449 [[RESOURCE_HANDLE]]
1450 .RESOURCE_HANDLE
1451  RESOURCE_HANDLE(name)
1452  RESOURCE_HANDLE_INIT(name)
1453  RESOURCE_USER(name)
1454  RESOURCE_USER_INIT(name)
1456 Define and initialize handles for to track resources.
1458  `name`::
1459      identifer to be used for the handle
1461 There are two kinds of handles, each resource itself is abstracted with a
1462 `RESOURCE_HANDLE` and every access to this resources is tracked through a
1463 `RESOURCE_USER` handle. These macros takes care that the declaration is optimized
1464 out in the same manner as the rest of the resource tracker would be disabled.
1465 You can still instantiate handles as `struct nobug_resource_record*` or
1466 `struct nobug_resource_user*` in structures which must have a constant size
1467 unconditional of the build level. The two `*_INIT` macros can be used to initialize
1468 resource handles and are optimized out when the resource tracker gets disabled.
1470 [[RESOURCE_ANNOUNCE]]
1471 .RESOURCE_ANNOUNCE
1472  RESOURCE_ANNOUNCE(flag, type, name, identifier, handle)
1473  NOBUG_RESOURCE_ANNOUNCE_RAW(flagptr, type, name, ptr, handle)
1474  NOBUG_RESOURCE_ANNOUNCE_RAW_CTX(flagptr, type, name, ptr, handle, context)
1476 Publishes resources.
1478  `flag`::
1479      the NoBug flag name which turns logging on for this macro
1480  `type`::
1481      a string which should denote the domain of the resource,
1482      examples are "file", "mutex", "lock", "database" and so on
1483  `name`::
1484      the actual name of a named resource this as string which
1485      together with type forms a unique identifier of the resource. `type` and
1486      `name` must be available through the entire lifetime of the resource, using
1487      literal strings is recommended
1488  `identifier`::
1489      a pointer which should be unique for this resource, any
1490      kind of pointer will suffice, it is only used for identification. In
1491      multithreaded applications the thread identifier becomes an additional
1492      identifier
1493  `handle`::
1494      a `NOBUG_RESOURCE_HANDLE` which will be initialized to point to
1495      the newly created resource.
1497 Resources must be unique, it is a fatal error when a resource it tried to be
1498 announced more than one time.
1500 'RESOURCE_ANNOUNCE()' acts like the head of a C loop statement, it ties to the following
1501 (block-) statement. Leaving and the user defined following statement are atomic.
1502 This statement must not be left by break, return or any other kind of jump.
1504 [[RESOURCE_FORGET]]
1505 .RESOURCE_FORGET
1506  RESOURCE_FORGET(flag, handle)
1507  NOBUG_RESOURCE_FORGET_RAW(flagptr, handle)
1508  NOBUG_RESOURCE_FORGET_RAW_CTX(flagptr, handle, context)
1510 Removes resources that have become unavailable from the registry.
1512 `flag`::
1513     the NoBug flag which turns logging on for this macro
1514 `handle`::
1515     the `NOBUG_RESOURCE_HANDLE` used to track this resource
1517 The resource must still exist and no users must be attached to it, else a fatal
1518 error is raised.
1520 'RESOURCE_FORGET()' acts like the head of a C loop statement, it ties to the following
1521 (block-) statement. Leaving and the user defined following statement are atomic.
1522 This statement must not be left by break, return or any other kind of jump.
1524 [[RESOURCE_RESETALL]]
1525 .RESOURCE_RESETALL
1526  RESOURCE_RESETALL(flag)
1527  NOBUG_RESOURCE_RESETALL_RAW(flagptr)
1528  NOBUG_RESOURCE_RESETALL_RAW_CTX(flagptr, context)
1530 Sometimes the resource tracker can give false positives when it finds a locking order violation
1531 while the programmer knows that this will never happen in the real program, because for example
1532 this is only used at initialization or shutdown and never overlaps. This macro can then be used
1533 to reset all whats learnt about all resources and start over.
1535 `flag`::
1536     the NoBug flag which turns logging on for this macro
1538 [[RESOURCE_RESET]]
1539 .RESOURCE_RESET
1540  RESOURCE_RESET(flag, handle)
1541  NOBUG_RESOURCE_RESETALL_RAW(flagptr, handle)
1542  NOBUG_RESOURCE_RESETALL_RAW_CTX(flagptr, handle, context)
1544 Sometimes the resource tracker can give false positives when it finds a locking order violation
1545 while the programmer knows that this will never happen in the real program, because for example
1546 this is only used at initialization or shutdown and never overlaps. This macro can then be used
1547 to reset all whats learnt about a single resources and start over.
1549 `flag`::
1550     the NoBug flag which turns logging on for this macro
1551 `handle`::
1552     the `NOBUG_RESOURCE_HANDLE` used to track this resource
1554 [[RESOURCE_ENTER]]
1555 .RESOURCE_ENTER
1556  RESOURCE_ENTER(flag, announced, user, state, handle)
1557  NOBUG_RESOURCE_ENTER_CTX(flag, resource, user, state, handle, context)
1559 Acquire a resource.
1561 `flag`::
1562     nobug flag which turns logging on for this macro
1563 `announced`::
1564     the handle set by `RESOURCE_ANNOUNCE`
1565 `user`::
1566     a free-form identifier
1567 `state`::
1568     the initial state, one of `NOBUG_RESOURCE_WAITING`, `NOBUG_RESOURCE_TRYING`,
1569     `NOBUG_RESOURCE_EXCLUSIVE`, `NOBUG_RESOURCE_RECURSIVE` or `NOBUG_RESOURCE_SHARED`
1570 `handle`::
1571     a `NOBUG_RESOURCE_HANDLE` which will be initialized to the
1572     entering node
1574 'RESOURCE_ENTER()' acts like the head of a C loop statement, it ties to the following
1575 (block-) statement. Leaving and the user defined following statement are atomic.
1576 This statement must not be left by break, return or any other kind of jump.
1578 [[RESOURCE_WAIT]]
1579 .RESOURCE_WAIT
1580  RESOURCE_WAIT(flag, resource, user, handle)
1581  NOBUG_RESOURCE_WAIT_CTX(flag, resource, user, handle, context)
1583 This is just an alias for RESOURCE_ENTER(flag, resource, user, NOBUG_RESOURCE_WAITING, handle)
1585 .How to use it
1586 [source,c]
1587 ----
1588 RESOURCE_WAIT(flag, resource, user, handle);
1589 if (lock_my_resource() == ERROR)
1590   NOBUG_RESOURCE_LEAVE(flag, handle);
1591 else
1592   RESOURCE_STATE(flag, NOBUG_RESOURCE_EXCLUSIVE, handle);
1593 ----
1595 [[RESOURCE_TRY]]
1596 .RESOURCE_TRY
1597  RESOURCE_TRY(flag, resource, user, handle)
1598  NOBUG_RESOURCE_TRY_CTX(flag, resource, user, handle, context)
1600 This is just an alias for RESOURCE_ENTER(flag, resource, user, NOBUG_RESOURCE_TRYING, handle).
1601 Trying on a resource is similar to waiting but will not trigger a deadlock check. This can be used
1602 when a deadlock is expected at runtime and one handles this otherwise (by a timed wait or something like that).
1604 [[RESOURCE_STATE]]
1605 .RESOURCE_STATE
1606  RESOURCE_STATE(flag, entered, state)
1607  NOBUG_RESOURCE_STATE_CTX(flag, state, entered, context)
1608  NOBUG_RESOURCE_STATE_RAW(flagptr, state, entered)
1609  NOBUG_RESOURCE_STATE_RAW_CTX(flagptr, nstate, entered, context)
1611 Changes resource's state.
1613 `flag`::
1614     is nobug flag which turns logging on for this macro
1615 `state`::
1616     the new state Note that only certain state transitions are
1617     allowed, see discussion/diagram above
1618 `entered`::
1619     the handle set by `RESOURCE_ENTER`
1621 'RESOURCE_STATE()' acts like the head of a C loop statement, it ties to the following
1622 (block-) statement. Leaving and the user defined following statement are atomic.
1623 This statement must not be left by break, return or any other kind of jump.
1625 [[RESOURCE_LEAVE]]
1626 .RESOURCE_LEAVE
1627  RESOURCE_LEAVE(flag, handle){}
1628  NOBUG_RESOURCE_LEAVE_RAW(flagptr, handle){}
1629  NOBUG_RESOURCE_LEAVE_RAW_CTX(flagptr, handle, context){}
1631 Disconnect from a resource identified with its handle.
1633 `flag`::
1634     nobug flag which turns logging on for this macro
1635 `handle`::
1636     the handle you got while entering the resource
1638 'RESOURCE_LEAVE()' acts like the head of a C loop statement, it ties to the following
1639 (block-) statement. Leaving and the user defined following statement are atomic.
1640 This statement must not be left by break, return or any other kind of jump.
1642 .How to use it
1643 [source,c]
1644 ----
1645 NOBUG_RESOURCE_LEAVE(flag, handle)
1646   {
1647     unlock_my_resource();
1648   }
1649 ----
1651 [[RESOURCE_ASSERT_STATE]]
1652 .RESOURCE_ASSERT_STATE
1653  RESOURCE_ASSERT_STATE(resource, state)
1654  RESOURCE_ASSERT_STATE_IF(when, resource, state)
1655  NOBUG_RESOURCE_ASSERT_STATE_CTX(resource, state, context)
1656  NOBUG_RESOURCE_ASSERT_STATE_IF_CTX(when, resource, state, context)
1658 Assert that we have a resource in a given state. For multithreaded programms the topmost
1659 state of the calling thread is checked, for non threadeded programs the most recent state on
1660 resource is used.
1662 `when`::
1663     Condition which must be true for testing the assertion
1664 `resource`::
1665     Resource handle
1666 `state`::
1667     The expected state
1669 [[RESOURCE_DUMP]]
1670 .RESOURCE_DUMP
1671  NOBUG_RESOURCE_DUMP(flag, handle)
1672  NOBUG_RESOURCE_DUMP_IF(when, flag, handle)
1674 Dump the state of a single resource.
1676 `when`::
1677     Condition which must be true to dump the resource
1678 `flag`::
1679     Nobug flag for the log channel
1680 `handle`::
1681     handle of the resource to be dumped
1683 [[RESOURCE_DUMPALL]]
1684 .RESOURCE_DUMPALL
1685  NOBUG_RESOURCE_DUMPALL(flag)
1686  NOBUG_RESOURCE_DUMPALL_IF(when, flag)
1688 Dump the state of all resources.
1690 `when`::
1691     Condition which must be true to dump the resources
1692 `flag`::
1693     Nobug flag for the log channel
1695 [[RESOURCE_LIST]]
1696 .RESOURCE_LIST
1697  NOBUG_RESOURCE_LIST(flag)
1698  NOBUG_RESOURCE_LIST_IF(when, flag)
1700 List all registered resources.
1702 `when`::
1703     Condition which must be true to list the resources
1704 `flag`::
1705     Nobug flag for the log channel
1707 .How to use the Resourcetracker
1708 [source,c]
1709 ----
1710 NOBUG_DEFINE_FLAG_LIMIT(test, LOG_DEBUG);
1712 void example()
1714   // define a mutex and announce it
1715   pthread_mutex_t my_mutex = PTHREAD_MUTEX_INITIALIZER;
1716   RESOURCE_HANDLE(resource);
1718   // 'example' is just a pointer to this function which suffices as unique id
1719   RESOURCE_ANNOUNCE(test, "mutex", "my_mutex", example, resource);
1721   // the following would be done in a different thread in a real program
1722   // define a handle
1723   RESOURCE_HANDLE(enter);
1725   // announce that we want to use the resource
1726   // &enter also suffices as unique pointer, which is all we need as identifer here
1727   RESOURCE_WAIT(flag, resource, &enter, enter)
1728     {
1729       // lock() might block
1730       pthread_mutex_lock (&my_mutex);
1731       // assume no errors, got it, change the state
1732       RESOURCE_STATE(test, NOBUG_RESOURCE_EXCLUSIVE, enter);
1733     }
1735   ////////////////////////////////////////
1736   // program does something useful here //
1737   ////////////////////////////////////////
1739   // we don't need it anymore
1740   RESOURCE_LEAVE(test, enter)  // << no semicolon
1741     pthread_mutex_unlock (&my_mutex);
1743   // back in the main thread
1744   RESOURCE_FORGET(test, resource);                         // remove the resource from the public registry
1746 ----
1748 Deadlock Detection
1749 ~~~~~~~~~~~~~~~~~~
1751 The Resource Tracker is able to detect potential deadlocks. This is done by
1752 learning the relations between locks (precedence). A possible deadlock results
1753 in a log message and a fatal abort. Note that only waiting on resources can
1754 lead to a deadlock. Deadlock detection is implemented in the Resource Tracker
1755 and active in ALPHA builds and optimized out on any other build level.
1757 For details about the deadlock detection algorithm see
1758 xref:deadlock_detection[Appendix: Resource Tracking Alorithm].
1760 Callbacks
1761 ---------
1763 NoBug provides callbacks, applications can use these
1764 to present logging information in some custom way or hook some special processing in.
1765 The callbacks are initialized to NULL and never modified by NoBug, its the solve responsibility
1766 of the user to manage them.
1768 CAUTION: There are certain constraints what and what not can be done in callbacks
1769          documented below which must be followed.
1771 [[logging_cb]]
1772 .type of logging callbacks
1773  typedef void (*nobug_logging_cb)(const struct nobug_flag* flag, int priority, const char *log, void* data)
1775 used for the logging callbacks
1777  `flag`::
1778     Flag structure which defines the logging configuration for this event
1779  `priority`::
1780     Log level of the current event
1781  `log`::
1782     Pointing to the current log line in the ringbuffer or `NULL`
1783  `data`::
1784     Global pointer defined by the user, passed arround (see below)
1786 [[abort_cb]]
1787 .type of abort callback
1788  typedef void (*nobug_abort_cb)(void* data)
1790 used for the abort callback
1792  `data`::
1793     Global data defined by the user, passed arround (see below)
1795 [[callback_data]]
1796 .passing data to callbacks
1797  void* nobug_callback_data
1799 This global variable is initialized to `NULL` and will never be touched by NoBug. One can use it
1800 to pass extra data to the callback functions.
1802 [[logging_callback]]
1803 .callback when logging
1804  nobug_logging_cb nobug_logging_callback
1806 This callback gets called when something gets logged.
1807 NoBug will still hold its mutexes when calling this hook, calling NoBug logging or resource tracking
1808 functions from here recursively will deadlock and must be avoided.
1809 The `log` parameter points to the logging message in the ringbuffer.
1810 Unlike other logging targets it is not automatically limited to the log level configured
1811 in the flag but called unconditionally. The callback should implement its own limiting.
1813 When one wants to do complex calls which may include recursion into logging and resource tracking
1814 functions, the intended way is to pass contextual information possibly including a __copy__ of the
1815 `log` parameter in xref:THREAD_DATA[NOBUG_THREAD_DATA] to the postlogging callback (see below).
1816 Other internal NoBug facilties, like the ringbuffer etc, are protected by the mutexes and may be accessed
1817 from this function.
1819 [[postlogging_callback]]
1820 .callback after logging
1821  nobug_logging_cb nobug_postlogging_callback
1823 This callback gets called after something got logged. The `log` parameter is always NULL and all
1824 NoBug mutexes are released. This means that this function may call any complex things, including
1825 calling logging and resource tracking, but may not call internal NoBug facilities.
1826 Contextual created in the `nobug_logging_callback` and stored in xref:THREAD_DATA[NOBUG_THREAD_DATA] can be
1827 retrieved here and may need to be cleaned up here.
1829 [[abort_callback]]
1830 .callback for aborting
1831  nobug_abort_cb nobug_abort_callback
1833 This callback gets called when the application shall be terminated due an error.
1834 It can be used to hook exceptions or similar things in. When it returns, `abort()`
1835 is called.
1837 IMPORTANT: Errors detected by NoBug are always fatal. If one handles and possible
1838            throws an exception here, the application must shut down as soon as possible.
1839            Most causes for aborts are optimitzed out in `RELEASE` builds.
1841 Tool Macros
1842 -----------
1844 [[NOBUG_FLAG_RAW]]
1845 .NOBUG_FLAG_RAW
1846  NOBUG_FLAG_RAW(ptr)
1848 Using this macro one can pass a direct pointer to a flag where a name would
1849 be expected. This is sometimes convinient when flag pointers are passed around
1850 in management strutures and one wants to tie logging to dynamic targets.
1852 [source,c]
1853 ----
1854 NOBUG_DEFINE_FLAG(myflag);
1856 struct nobug_flag* ptr = &NOBUG_FLAG(myflag);
1857 TRACE(NOBUG_FLAG_RAW(ptr), "Passed flag by pointer")
1858 ----
1860 [[BACKTRACE]]
1861 .Backtraces
1862  BACKTRACE
1863  NOBUG_BACKTRACE_CTX(context)
1865 The backtrace macro logs a stacktrace using the NoBug facilities.
1866 This is automatically called when NoBug finds an error and is due
1867 to abort. But one might call it manually too.
1869 [[ABORT]]
1870 .Aborting
1871  NOBUG_ABORT_
1873 This is the default implementation for aborting the program, it first syncs all ringbuffers to disk, then
1874 calls the abort callback if defined and then `abort()`.
1876  NOBUG_ABORT
1878 If not overridden, evaluates to `NOBUG_ABORT_`. One can override this before including
1879 `nobug.h` to customize abortion behaviour. This will be local to the translation unit then.
1881 [[NOBUG_ALPHA_COMMA]]
1882 .NOBUG_ALPHA_COMMA
1883  NOBUG_ALPHA_COMMA(something)
1884  NOBUG_ALPHA_COMMA_NULL
1886 Sometimes it is useful to have initializer code only in *ALPHA* builds, for example when you
1887 conditionally include resource handles only in *ALPHA* versions. An initializer can then
1888 use this macros to append a comman and something else only in *ALPHA* builds as in:
1889  struct foo = {"foo", "bar" NOBUG_ALPHA_COMMA_NULL };
1891 [[NOBUG_IF]]
1892 .NOBUG_IF_*
1893  NOBUG_IF_ALPHA(...)
1894  NOBUG_IF_NOT_ALPHA(...)
1895  NOBUG_IF_BETA(...)
1896  NOBUG_IF_NOT_BETA(...)
1897  NOBUG_IF_RELEASE(...)
1898  NOBUG_IF_NOT_RELEASE(...)
1900 This macros allow one to conditionally include the code in '(...)' only if the
1901 criteria on the build level is met. If not, nothing gets substituted. Mostly used
1902 internally, but can also be used for custom things.
1904 [[multithreading]]
1905 Multithreading
1906 --------------
1908 It is important that NoBug protects certain operations with locks in
1909 multithreaded programs. You have to ensure that 'HAVE_PTHREAD_H' is defined by
1910 the configuration system and use the 'libnobugmt' library for linking. It is
1911 particular important that libraries using NoBug are compiled with
1912 'HAVE_PTHREAD_H' enabled when they are intended to be used in multithreaded
1913 programs.
1915 When Multithreading is used, log messages contain a identifier of the
1916 originating thread. This identifier should be set by
1918 [[THREAD_ID_SET]]
1919 .NOBUG_THREAD_ID_SET
1920  NOBUG_THREAD_ID_SET(name)
1922 `name`::
1923         New name for the thread
1925 Nobug will assemble a unique identifier by appending a underscore and a
1926 number to name, for example `NOBUG_THREAD_ID_SET("gui")` will result in a
1927 identifier like "gui_5". When you don't set a thread identifier, then NoBug
1928 assigns one automatically with the name 'thread' preprended if needed. Thread
1929 identifiers may be reset with a new call to this macro.
1931 [[THREAD_ID_GET]]
1932 .NOBUG_THREAD_ID_GET
1933  NOBUG_THREAD_ID_GET
1935 Will return a const char* of the thread id in multithreaded programs and
1936 a pointer to a literal empty string in singlethreaded programs.
1938 [[THREAD_DATA]]
1939 .NOBUG_THREAD_DATA
1940  NOBUG_THREAD_DATA
1942 Evaluates to a variable of type `void*` which can be used to store
1943 thread local information. This is useable for xref:_callbacks[callbacks] which may
1944 prepare context information to be reused later.
1946 This macro is also available in singlethreaded programs, refering to a
1947 single global variable.
1949 Nobug initializes this variable to `NULL` and then touches it never again.
1951 [[rbdump]]
1952 Dumping Persistent Ringbuffers
1953 ------------------------------
1955 NoBug installs the `nobug_rbdump` tool for dumping the content of a persistent
1956 ringbuffer. It is invoked with the filename of the ringbuffer, the content is then
1957 printed to stdout.
1959 Testsuite
1960 ---------
1962  TODO Documentation to be written, use the source Luke!
1964 NoBug maintains a `test.sh` script which drives extensive testsuites.
1965 Look at into the 'tests/' folder about how to apply this.
1967 Best Practices
1968 --------------
1970 NOTE: this section is very work in progress
1972 .Workflow
1974  1. Development
1975       * Write a testsuite, build your program with -O0 -g -DEBUG_ALPHA and run
1976         the testsuite under valgrind control. Hack until the program mets the
1977         specifications defined by the testsuite.
1978  2. Beta Test
1979       * Build with desired optimization level and -g -DEBUG_BETA and give the
1980         program to your beta testers.
1981  3. Release
1982       * Build it with optimization and without -g -DEBUG_*
1984 .What and when to check
1986   * Add REQUIRE checks on your interfaces (incoming parameters). Especially if
1987     a argument might not cover the whole range of the underlying type.
1988   * Don't waste your and your CPU's time with unnecessary checks. The testsuite
1989     should validate your program. NoBug aids in debugging. You can add
1990     Postconditions (ENSURE) and Invariants when you have a bug somewhere and
1991     want to nail it down.
1992   * Added checks don't need to be removed.
1993   * When you use the CHECKED/UNCHECKED features then don't forget C scoping
1994     rules, tag things as CHECKED from the leaves to the root.
1996 .Tips & Tricks
1998   * TRACE(flagname) at the begin of every nontrivial function will easily log
1999     the progress of your application.
2000   * Trying a RELEASE build will abort on certain conditions (known BUG, TODO's,
2001     UNCHECKED code), you can use this to find these spots.
2003 Appendix
2004 --------
2006 [[deadlock_detection]]
2007 The Resource Tracking Algorithm
2008 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2010 Each resource registers a global 'resource_record'.
2012 Every new locking path discovered is stored as 'resource_node' structures which refer to the associated
2013 'resource_record'.
2015 Threads keep a trail of 'resource_user' strcutures for each resource entered. This 'resource_user' struct
2016 refer to the 'resource_nodes' and thus indirectly to the associated 'resource_record'.
2018 The deadlock checker uses this information to test if the acqusition of a new resource would yield a
2019 potential deadlock.
2021 [[nobug_resource_enter]]
2022 Entering Resources
2023 ^^^^^^^^^^^^^^^^^^
2025 In multithreaded programs, whenever a thread wants to wait for a 'resource_record'
2026 the deadlock checker jumps in.
2028 The deadlock checking algorithm is anticipatory as it will find and abort on conditions which may lead
2029 to a potential deadlock by violating the locking order learned earlier.
2031 Each thread holds a stack (list) of each 'resource_user' it created. Leaving
2032 a resource will remove it from this stacklist.
2034 Each 'resource_record' stores the trail which other 'resource_records' are already entered. This relations
2035 are implemented with the 'resource_node' helper structure.
2037 ////
2038 TODO: insert diagram here
2039   2-3
2041   3-4-2
2043 1-3-2-4
2045 3-4-2
2047 1-4-2
2049 ////
2051 First we find out if there is already a node from the to be acquired resource back to
2052 the topmost node of the current threads user stack.
2054 [source,c]
2055 ---------------------------------------------------------------------
2056   struct nobug_resource_user* user = NULL;
2057   struct nobug_resource_node* node = NULL;
2059   if (!llist_is_empty (&tls->res_stack))
2060     {
2061       user = LLIST_TO_STRUCTP (llist_tail (&tls->res_stack),
2062                                struct nobug_resource_user,
2063                                res_stack);
2065       struct nobug_resource_node templ =
2066         {
2067          ...
2068           user->current->resource,
2069          ...
2070         };
2072       node = (struct nobug_resource_node*)
2073         llist_ufind (&resource->nodes,
2074                      &templ.node,
2075                      nobug_resource_node_resource_cmpfn,
2076                      NULL);
2077     }
2078   ...
2079 ---------------------------------------------------------------------
2081 Deadlock checking is only done when the node is entered in `WAITING` state and only
2082 available in multithreaded programs.
2084 [source,c]
2085 ---------------------------------------------------------------------
2086   if (state == NOBUG_RESOURCE_WAITING)
2087     {
2088 #if NOBUG_USE_PTHREAD
2089       ...
2090 ---------------------------------------------------------------------
2092 If node was found above, then this locking path is already validated and no deadlock can happen,
2093 else, if this stack already holds a resource (user is set) we have to go on with checking.
2095 [source,c]
2096 ---------------------------------------------------------------------
2097       if (!node && user)
2098         {
2099           ...
2100 ---------------------------------------------------------------------
2102 If not then its checked that the resource to be entered is not on any parent trail of the current topmost resource,
2103 if it is then this could be a deadlock which needs to be further investigated.
2105 [source,c]
2106 ---------------------------------------------------------------------
2107           LLIST_FOREACH (&user->current->resource->nodes, n)
2108             {
2109               for (struct nobug_resource_node* itr =
2110                      ((struct nobug_resource_node*)n)->parent;
2111                    itr;
2112                    itr = itr->parent)
2113                 {
2114                   if (itr->resource == resource)
2115                     {
2116                       ...
2117 ---------------------------------------------------------------------
2119 if the resource was on the trail, we search if there is a common ancestor before the resource
2120 on the trail and the threads current chain,
2121 if yes then this ancestor protects against deadlocks and we can continue.
2123 [source,c]
2124 ---------------------------------------------------------------------
2125                       for (struct nobug_resource_node* itr2 = itr->parent;
2126                            itr2;
2127                            itr2 = itr2->parent)
2128                         {
2129                           LLIST_FOREACH_REV (&tls->res_stack, p)
2130                             {
2131                               struct nobug_resource_user* user =
2132                                 LLIST_TO_STRUCTP (p,
2133                                                   struct nobug_resource_user,
2134                                                   res_stack);
2135                               if (user->current->resource == itr2->resource)
2136                                 goto done;
2137                             }
2138 ---------------------------------------------------------------------
2140 If no ancestor found, we finally abort with a potential deadlock condition.
2142 [source,c]
2143 ---------------------------------------------------------------------
2144                           nobug_resource_error = "possible deadlock detected";
2145                           return NULL;
2146                           ...
2147 ---------------------------------------------------------------------
2150 [[nobug_resource_leave]]
2151 Leaving Resources
2152 ^^^^^^^^^^^^^^^^^
2154 store the tail and next aside, we need it later
2156 [source,c]
2157 ---------------------------------------------------------------------
2158 #if NOBUG_USE_PTHREAD
2159       struct nobug_resource_user* tail =
2160         LLIST_TO_STRUCTP (llist_tail (&user->thread->res_stack),
2161                           struct nobug_resource_user,
2162                           res_stack);
2163       struct nobug_resource_user* next =
2164         LLIST_TO_STRUCTP (llist_next (&user->res_stack),
2165                           struct nobug_resource_user,
2166                           res_stack);
2167 ---------------------------------------------------------------------
2169 remove user struct from thread stack
2170 The res_stack is now like it is supposed to look like with the 'user' removed.
2171 We now need to fix the node tree up to match this list.
2173 [source,c]
2174 ---------------------------------------------------------------------
2175       llist_unlink_fast_ (&user->res_stack);
2176 ---------------------------------------------------------------------
2178 When the the user node was not the tail or only node of the thread stack, we have to check
2179 (and possibly construct) a new node chain for it. No valdation of this chain needs to be done,
2180 since it was already validated when entering the resources first.
2182 [source,c]
2183 ---------------------------------------------------------------------
2184       if (user != tail && !llist_is_empty (&user->thread->res_stack))
2185         {
2186           struct nobug_resource_user* parent = NULL;
2187           if (llist_head (&user->thread->res_stack) != &next->res_stack)
2188             {
2189               parent =
2190                 LLIST_TO_STRUCTP (llist_prev (&next->res_stack),
2191                                   struct nobug_resource_user,
2192                                   res_stack);
2193             }
2194 ---------------------------------------------------------------------
2196 iterate over all users following the removed node, finding nodes pointing to this users or
2197 create new nodes.
2199 [source,c]
2200 ---------------------------------------------------------------------
2201           LLIST_FORRANGE (&next->res_stack, &user->thread->res_stack, n)
2202             {
2203               struct nobug_resource_user* cur =
2204                 LLIST_TO_STRUCTP (n,
2205                                   struct nobug_resource_user,
2206                                   res_stack);
2208 ---------------------------------------------------------------------
2210 find the node pointing back to parent, create a new one if not found, rinse repeat
2212 [source,c]
2213 ---------------------------------------------------------------------
2214               struct nobug_resource_node templ =
2215                 {
2216                   ...
2217                   NULL,
2218                   ...
2219                 };
2221               struct nobug_resource_node* node = (struct nobug_resource_node*)
2222                 llist_ufind (&resource->nodes,
2223                              &templ.node,
2224                              nobug_resource_node_parent_cmpfn,
2225                              NULL);
2227               if (!node)
2228                 {
2229                   node = nobug_resource_node_new (resource,
2230                                                   parent?parent->current:NULL);
2231                   if (!node)
2232                     {
2233                       nobug_resource_error = "internal allocation error";
2234                       return 0;
2235                     }
2236                 }
2238               parent = cur;
2239             }
2240         }
2241 ---------------------------------------------------------------------
2244 Index
2245 -----
2247 xref:ABORT[Aborting]:: abort the program
2248 xref:abort_callback[callback for aborting]:: hook to handle a termination
2249 xref:abort_cb[type of abort callback]:: type of a abort callback function
2250 xref:ALERT[ALERT]:: about to die
2251 xref:ASSERT[ASSERT]:: generic assertion
2252 xref:assert[assert]:: C standard assertion
2253 xref:BACKTRACE[Backtraces]:: generate a backtrace
2254 xref:buildlevel[Build Levels]:: selecting the build level
2255 xref:callback_data[passing data to callbacks]:: data to be passed to callbacks
2256 xref:CHECK[CHECK]:: unnconditional assertion for testsuites
2257 xref:CHECKED[CHECKED, Scope]:: tag scope as reviewed
2258 xref:COVERAGE_DISABLE[Disabling and enabling fault-coverage checks]:: handle false positives
2259 xref:COVERAGE_FAULT[COVERAGE_FAULT]:: coverage fault injection, statement
2260 xref:COVERAGE_GOODBAD[COVERAGE_GOODBAD]:: coverage fault injection, expression
2261 xref:COVERAGE_LEVEL[COVERAGE_LEVEL]:: coverage fault injection log level
2262 xref:Cplusplus_logflags[C++ support, C++ logflags]:: C++ support for log flags
2263 xref:CRITICAL[CRITICAL]:: can not continue
2264 xref:deadlock_detection[The Resource Tracking Algorithm]:: how resources are tracked
2265 xref:DECLARE_FLAG[DECLARE_FLAG]:: declaring a flag
2266 xref:DECLARE_ONLY[DECLARE_ONLY]:: force flag declarations only
2267 xref:DEFINE_FLAG[DEFINE_FLAG]:: defining a flag
2268 xref:DEFINE_FLAG_LIMIT[DEFINE_FLAG_LIMIT]:: defining a flag w/ log limit
2269 xref:DEFINE_FLAG_PARENT[DEFINE_FLAG_PARENT]:: defining a flag hierarchy
2270 xref:DEFINE_FLAG_PARENT_LIMIT[DEFINE_FLAG_PARENT_LIMIT]:: defining a flag hierarchy, w/ log limit
2271 xref:DEPRECATED[DEPRECATED]:: to be discarded in future
2272 xref:DUMP[DUMP]:: dumping datastructures
2273 xref:DUMP_LOG[DUMP_LOG]:: logging helper for dumping
2274 xref:ECHO[ECHO]:: unconditional logging for tests
2275 xref:ELSE_NOTREACHED[ELSE_NOTREACHED]:: alternative never taken
2276 xref:ENSURE[ENSURE]:: postconditions (computation outcomes)
2277 xref:ERROR[ERROR]:: something gone wrong
2278 xref:FIXME[FIXME]:: known bug
2279 xref:INFO[INFO]:: progress message
2280 xref:INJECT_FAULT[INJECT_FAULT]:: fault injection statement
2281 xref:INJECT_GOODBAD[INJECT_GOODBAD]:: fault injection expression
2282 xref:INJECT_LEVEL[INJECT_LEVEL]:: log level for fault injection
2283 xref:INVARIANT[INVARIANT]:: validate invariant state
2284 xref:LOG[LOG]:: generic logging
2285 xref:LOG_BASELIMIT[LOG_BASELIMIT]:: minimum compliled-in logging limit
2286 xref:logflags[Log Flags]:: define hierarchies for logging output
2287 xref:logging_callback[callback when logging]:: hook when something get logged
2288 xref:logging_cb[type of logging callbacks]:: type of a logging callback function
2289 xref:multithreading[Multithreading]:: using NoBug in multithreaded programs
2290 xref:NOBUG_ALPHA_COMMA[NOBUG_ALPHA_COMMA]:: append something after a comma in *ALPHA* builds
2291 xref:NOBUG_ANN[NOBUG_ANN]:: log flag for annotations
2292 xref:NOBUG_CONTEXT[Source Contexts]:: pass information about the source location
2293 xref:NOBUG_ENV[Control what gets logged]:: environment variable for loging control
2294 xref:nobug_flag[nobug (flag)]:: log flag used to show nobug actions
2295 xref:NOBUG_FLAG_RAW[NOBUG_FLAG_RAW]:: pass direct flag pointer
2296 xref:NOBUG_IF[NOBUG_IF_*]:: include code conditionally on build level
2297 xref:NOBUG_ON[NOBUG_ON]:: log flag which is always enabled
2298 xref:nobug_resource_enter[Entering Resources]:: deadlock check on enter
2299 xref:nobug_resource_leave[Leaving Resources]:: fix resource lists
2300 xref:NOTICE[NOTICE]:: detailed progress message
2301 xref:NOTREACHED[NOTREACHED]:: code path never taken
2302 xref:PLANNED[PLANNED]:: ideas for future
2303 xref:postlogging_callback[callback after logging]:: hook after something get logged
2304 xref:rbdump[Dumping Persistent Ringbuffers]:: dumping persistent ringbuffers
2305 xref:REQUIRE[REQUIRE]:: preconditions (input parameters)
2306 xref:RESOURCE_ANNOUNCE[RESOURCE_ANNOUNCE]:: publish new resources
2307 xref:RESOURCE_ASSERT_STATE[RESOURCE_ASSERT_STATE]:: assert the state of a resource
2308 xref:RESOURCE_DUMP[RESOURCE_DUMP]:: dump the state of a single resource
2309 xref:RESOURCE_DUMPALL[RESOURCE_DUMPALL]:: dump the state of all resources
2310 xref:RESOURCE_ENTER[RESOURCE_ENTER]:: claim a resource
2311 xref:RESOURCE_FORGET[RESOURCE_FORGET]:: remove resources
2312 xref:RESOURCE_HANDLE[RESOURCE_HANDLE]:: define resource handles
2313 xref:RESOURCE_LEAVE[RESOURCE_LEAVE]:: relinquish a claimed resource
2314 xref:RESOURCE_LIST[RESOURCE_LIST]:: enumerate all registered resources
2315 xref:RESOURCE_LOG_LEVEL[RESOURCE_LOG_LEVEL]:: select the log level for resource logging
2316 xref:RESOURCE_LOGGING[RESOURCE_LOGGING]:: switch resource logging on and off
2317 xref:RESOURCE_RESET[RESOURCE_RESET]:: reset a single resource to a pristine state
2318 xref:RESOURCE_RESETALL[RESOURCE_RESETALL]:: reset the resource tracker to a pristine state
2319 xref:RESOURCE_STATE[RESOURCE_STATE]:: change the state of a resource
2320 xref:RESOURCE_TRY[RESOURCE_TRY]:: wait for a resource to become available
2321 xref:RESOURCE_WAIT[RESOURCE_WAIT]:: wait for a resource to become available
2322 xref:THREAD_DATA[NOBUG_THREAD_DATA]:: thread local data for application use
2323 xref:THREAD_ID_GET[NOBUG_THREAD_ID_GET]:: query thread id
2324 xref:THREAD_ID_SET[NOBUG_THREAD_ID_SET]:: set or reset thread id
2325 xref:TODO[TODO]:: things to be done
2326 xref:TRACE[TRACE]:: debugging level message
2327 xref:UNCHECKED[UNCHECKED, Scope]:: tag scope as unreviewed
2328 xref:UNIMPLEMENTED[UNIMPLEMENTED]:: not yet implemented
2329 xref:WARN[WARN]:: unexpected fixable error
2331 License
2332 -------
2334     NoBug
2335     Copyright (C) 2009          Christian Thäter <ct@pipapo.org>
2337     This program is free software; you can redistribute it and/or modify
2338     it under the terms of the GNU General Public License as published by
2339     the Free Software Foundation; either version 2 of the License, or
2340     (at your option) any later version.
2342     This program is distributed in the hope that it will be useful,
2343     but WITHOUT ANY WARRANTY; without even the implied warranty of
2344     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
2345     GNU General Public License for more details.
2347     You should have received a copy of the GNU General Public License along
2348     with this program; if not, write to the Free Software Foundation, Inc.,
2349     51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
2351 .License Rationale
2353 NoBug is released under the "GNU General Public License version 2 or
2354 any later" to protect its freedom. If one wants to use NoBug in a
2355 propietary program, please contact the main author for
2356 acknowledging relicensing terms.
2358 For BSD license style Free Software, this means you can not distribute
2359 binaries linking NoBug without making its source available. To make
2360 this compatible, it is suggested that you dual-license your software
2361 with your prefered BSD like license and the GPL. As long as it uses
2362 NoBug, the GPL will take over and you have to make the source
2363 available, while one can ship a BSD or LGPL Licensed headerfile which
2364 defines all NoBug macros as empty macros and remove libnobug from the
2365 linking, then NoBug isn't used anymore and you may apply BSD license
2366 terms for resulting binaries.
2369 Contributor Agreement
2370 ~~~~~~~~~~~~~~~~~~~~~
2372 Improvements and patches must be licensed as "GPL v2 or any later" to
2373 be acceptable. Further a contributor must either assign his copyright
2374 to the main NoBug author or agree with the possibility that NoBug can
2375 be relicensed for propietary use:
2377  Independent of the GPL license as stated above, The main author of
2378  NoBug explicitly reserve the right to relicense NoBug under
2379  different, even propietary terms. Any contributor agrees to such
2380  a possiblility by sending his contribution to be included into
2381  the official releases.
2383  This agreement is bilateral, every contributor who worked on a
2384  substantial part of NoBug has the right to relicense it after
2385  negotiation with the NoBug main author. Exact terms of such
2386  relicensing are worked out on a per case base.
2388 The intention is that anyone who worked on NoBug should be able to
2389 benefit from his work. This means one should be able to use it at his
2390 workplace, to gain a job or as well as relicense it for a customer.
2391 Unlike other projects which simply ask for transfering the copyright
2392 to the main author, NoBug tries to make it possible to retain the
2393 copyright by anyone who helped the project.
2395 This additional agreement has no impact on the GPL, it's sole purpose
2396 is to define relicensing policies between the NoBug main author and
2397 contributors. When you recieve NoBug it will be licensed under
2398 GPL unless you personally acknowledged other terms with the NoBug main
2399 author (or any other main contributor).
2401 If anyone feels he is not credited in the 'AUTHORS' file or in any
2402 copyright notice, please contact the main author for inclusion.