3 Christian_Thäter,_Benny_Lyons
5 // doc/overview.txt:1 //
7 Everyone makes mistakes, but with NoBug you won't make them twice!
10 Nobug is a debugging library for instrumenting C and C++ programs
11 inspired by ideas originating from Design-by-Contract.
16 The following features are provided by NoBug:
18 * Three different check levels: from detailed to final no-overhead
19 * Scope tags: tell whenever a function or loop is considered to be bug free
20 * Precondition, Postcondition and Invariant checks and generic assertions
21 * Data structures can be dumped
22 * Application activities can be logged
23 * Runtime customizable logging via an environment variable
24 * Different logging targets to stderr, syslog, debugger, ...
25 * Annotation of your sourcecode about known bugs, things to do, etc.
26 * Tracking resources (files, locks, etc.) used by your program; help in
28 * Detecting potential deadlocks
29 * Simulate errors by injecting faults
30 * Additionally, the NoBug project is used to maintain a script and
31 some tools to setup testsuites
33 In contrast to traditional debuggers, NoBug is a non-interactive debugger which
34 is linked to your application doing hard-coded tests in an efficient,
37 .What NoBug can not do
39 NoBug is a (macro-)library, it is not a C/C++ language extension. This
40 means that code must be called at runtime to benefit from the set up
41 contracts. Whats not tested is likely slipping through the net. Being
42 part of the program itself it is affected by memory corruption,
43 certain kinds of misuse may introduce new bugs (test expressions with
44 side effects for example).
46 // doc/buildinstall.txt:1 //
47 Building and Installing
48 -----------------------
53 NoBug has been developed on linux, using gcc. It should be possible to port
54 it to any other POSIX compliant operating system. Platform/compiler
55 specific things are kept optional. Currently Linux with a gcc that conforms to
56 C99 is supported for both 32 and 64 bit architectures.
59 `-------`---------------`---------------`--------------------------------------
61 -------------------------------------------------------------------------------
62 x86_64 Debian supported Reference Platform
63 x86 other Linux supported Please report distro specific problems
64 armel maemo5 supported check fails in SDK (emulator bug)
65 x86* MacOS X supported
66 x86 OpenSolaris mostly Builds, but target check fails
67 *BSD planned Need volunteer for testing
68 -------------------------------------------------------------------------------
70 NoBug has no mandatory dependencies on other software and libraries,
71 some things such as valgrind support are optional and should be automatially
72 detected during the build, i.e., when ./configure is called.
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
89 Since they are built with gnu autotools, the usual build and install procedure
92 $ tar xzvf nobug-VERSION.tar.gz
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
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:
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
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).
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.
163 // doc/using.txt:1 //
167 Your application will have to include the header file 'nobug.h' before NoBug
173 Once you've included the NoBug API in your application, you'll then have to select
174 a 'build-level'. Build-levels are discussed later, c.f.,
175 xref:buildlevel[buildlevel]. Build-levels are used to define the amount of
176 information NoBug provides to you. Maximum information is generally required while
177 developing an application and the ALPHA build-level is most apropriate during
178 this phase; whereas the released phase of an application will usually only require
179 sparse information, for which the RELEASE build-level has been conceived.
181 A build-level must always be specified, otherwise the compiler will complain
182 while attempting to compile your application. You can specifiy a build level in
183 one of two ways: use a define statement in one of your modules, or pass the
184 build-level using the -D flag to your compiler. Assuming we'd like to select
185 the ALPHA build-level in your application, then your module would assume the
194 Subsequently you'll have to link the appropriate library to your application.
196 A number of different libraries are available to link depending on whether you
197 require to statically or dynamically link, or whether your application is multi
198 or single threaded. The link order is important on your link line. Link the NoBug
199 library 'after' your application's modules. Here's how to statically link,
200 single-threaded applications:
204 gcc -o mybinary $(WHATEVER_FLAGS) mymodule1.o ... mymodulen.o ..../libs/libnobug.a
207 However, for more flexibility in selecting a build-level, you might wish to
208 define various targets in your makefile, one for each build-level. In such
209 cases, the -D flag in your makefile is most appropriate; so your link line for
210 an ALPHA build with multi-threaded support would look like the following:
214 gcc -o mybinary -DEBUG_ALPHA $(WHATEVER_FLAGS) mymodule1.o ... mymodulen.o ..../libs/libnobugmt.a
217 Both libraries must be initialised before they can be used. There are a number
218 of different ways to initialise the NoBug libraries. One of the easiest ways
219 to initialise the NoBug libraries is to use the `NOBUG_INIT` macro, which must
220 be used before any features can be used or any thread is created. This is
221 discussed in more detail in the xref:multithreading[multithreading] chapter.
223 So putting all this together, our application using NoBug might look something
229 #include <nobug.h> /* Include the NoBug API */
230 #define EBUG_ALPHA /* If we have not used the -D Flag in our makefile */
234 NOBUG_INIT; /* Initialise NoBug libs */
245 Many aspects of NoBug can be configured by overriding macros before 'nobug.h' is
248 A project using NoBug can use autoconf to check for execinfo and
251 AC_CHECK_HEADER([execinfo.h], AC_DEFINE(HAVE_EXECINFO_H))
252 PKG_HAVE_DEFINE_WITH_MODULES(VALGRIND, [valgrind])
254 For Multithreaded programs, you should also check for the availability of pthreads
259 When the resulting `HAVE_PTHREAD`, `HAVE_EXECINFO_H` and
260 `HAVE_VALGRIND_H` are defined by the configure script, the
261 relevant features become available.
263 NoBug then defines `NOBUG_USE_PTHREAD`, `NOBUG_USE_VALGRIND` and
264 `NOBUG_USE_EXECINFO` to 1. If you do not want to use any of these features in
265 NoBug, you can override these macros by setting to 0 before including nobug.h.
267 If `NVALGRIND` is defined, there will be no support for valgrind.
271 There are many other macros which can be set and overridden by the user to
272 control behavior. Your help would be appreciated in expanding this documentation
273 if you find some features useful; or simply contact any of the authors.
277 .Using Nobug from a Project using autoconf
280 PKG_CHECK_MODULES(NOBUGMT_LUMIERA, [nobugmt >= 0.3rc1],
281 AC_DEFINE(HAVE_NOBUGMT_H),
282 AC_MSG_ERROR([NoBug pkg-config metadata missing])
286 // doc/additional.txt:1 //
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*`::
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 // doc/whichlibrary.txt:1 //
329 Link Appropriate Library
330 ~~~~~~~~~~~~~~~~~~~~~~~~
332 Finally, the appropriate library (for either single or multi-threaded
333 applications) is linked to the project.
335 *libnobug*:: Link-in this library for single threaded applications.
336 *libnobugmt*:: Link with this library for multi-threaded applications.
338 NoBug installed static and dynamic libraries. When your application
339 uses multiple dynamic libraries which use NoBug or you build a dynamic
340 library, then you have to link against the dynamic library.
342 You can use the `pkg-config` tool to gather information about NoBug in
345 Release builds remove all assertions, but logging is still kept. We
346 make the assumption that bugs which were not covered in alpha and beta
347 builds will not easily show up in releases because the assertions
348 there were not sufficient. Furthermore, end users are not test bunnies
349 and will not provide good bug reports anyway. If there is a problem in
350 a release build, try to track down the cause using a beta build from
353 // doc/initialization.txt:1 //
360 Before anything from NoBug can be used, NoBug must be initialised. This is
361 performed by calling one of the `NOBUG_INIT_` macros.
363 The simpliest such macro among the initialising set is the following:
367 `NOBUG_INIT` can be called more than once, subsequent calls will be a no-op,
368 thus initialising in main and in libraries won't interfere with one another.
370 In other words, `NOBUG_INIT` is usually the first call to NoBug.
373 Since NoBug is intended to be available throughout its whole lifetime,
374 destroying it is not to be advised. Nevertheless, there is a destroy function
375 void nobug_destroy (void)
377 to shutdown NoBug, and this frees all resources associated with it.
378 This is mostly used in the NoBug testsuite itself to check for leaks,
379 and it might be useful for other programs which employ some kind of
385 If you want to use environment variable controlled debuging, then you have to
386 initialize each defined flag with
388 NOBUG_INIT_FLAG(flagname)
392 NOBUG_INIT_FLAG_LIMIT(flagname, default)
394 or one of the C++ compatibility macros.
396 This is documented later in the xref:logconfig[logging configuration] chapter.
401 In Multithreaded programs you should assign an identifier to each
402 thread. A thread identifier is a string which will be automatically
403 appended with an underscore and a incrementing integer. It is is created with:
405 NOBUG_THREAD_ID_SET(name)
407 Calling `NOBUG_THREAD_ID_SET("worker")` will yield in a thread
408 identifier 'worker_1' for example.
410 If you don't set an identifier, then NoBug will assign an automatic one.
411 This is further documented in the xref:multithreading[multi threading]
412 section of this manual.
417 -------------------------------------------------------
419 NOBUG_DEFINE_FLAG(example);
426 NOBUG_THREAD_ID_SET("main");
427 NOBUG_INIT_FLAG(example);
431 -------------------------------------------------------
433 // doc/buildlevels.txt:1 //
435 Debugging Information Granuality: The Build Levels
436 --------------------------------------------------
438 There are three different levels of debugging information available: alpha, beta
439 and release. One of these levels must be specified before compiling, otherwise
440 an error while compiling will occur.
444 This debugging level is envisaged for the development phase of a project
445 where exhaustive testing and logging are required.
447 This debugging level is more appropriate for projects beyond the
448 development phase and ready for trials in the field and users willing to
451 This level is for final, end-users.
453 .Select a Build Level
454 A logging level can be selected by either using a define in one of the
455 applications' modules, or by passing the appropriate level using the -D switch
458 *ALPHA*:: -DEBUG_ALPHA (`#define EBUG_ALPHA`)
460 *BETA*:: -DEBUG_BETA (`#define EBUG_BETA`)
462 *RELEASE*:: -DNDEBUG (`#define NDEBUG`)
464 If none of the above switches has been set, NoBug will abort the
465 compilation with an error.
467 // doc/logging.txt:1 //
471 Nearly all NoBug Macros emit some log message. NoBug gives the user fine
472 grained control over these log messages to display only interesting information
473 without loosing details.
475 Log messages can be routed to various destinations. The following destintaions
479 The underlying storage backend. Messages are appended to the
480 end of the buffer, overwriting older messages at the front of
481 the buffer. NoBug comes with a highly efficient ringbuffer
482 implementation. This ringbuffer is temporary by default but
483 can be made persistent on disk which can be inspected with the
487 This is either just stderr, or, if running under a supported
488 debugger, the debuggers facilities to print messages will be used.
491 The user can open files for log messages.
494 Messages are sent to the standard system logging daemon.
497 There are hooks which allow the programmer to catch logmessages and
498 display them in an application which are defined by the application.
500 Each logmessage has a priority describing its severity in the same way as
503 All non-fatal messages are associated with a programmer defined flag describing
504 the source of the message (subsystem, module, ...).
506 Putting this all together: A user can define which source/flag will be logged at
507 what priority level and to which destination. To make this all easier, NoBug
508 tries to provide reasonable defaults.
510 // doc/logconfiguration.txt:1 //
517 Each log macro has an explicit or implicit log-level which
518 correspondends to syslog levels. Logging is only emitted when the
519 message is more severe or the same as a defined limit.
522 .Default levels for logging
524 `````~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
525 , ALPHA, BETA , RELEASE,
526 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
527 *ringbuffer* , TRACE, INFO , NOTICE , ringbuffer must always be most verbose
528 *console* , INFO , NOTICE , -1 , no log to console in release
529 *file* , TRACE, NOTICE , WARNING,
530 *syslog* , -1 , NOTICE , WARNING, no syslog for test runs
531 *application*, INFO , WARNING, ERROR ,
532 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
534 Depending on the build level, there is a default logging target and a default
535 limit which is selected when the user doesn't specify one.
537 The following default limits are available:
539 * In *ALPHA* builds, `NOBUG_LOG_LIMIT_ALPHA` is used which defaults to `LOG_INFO`
540 * In *BETA* builds, `NOBUG_LOG_LIMIT_BETA` is used and defaults to `LOG_WARNING`
541 * In *RELEASE* builds, `NOBUG_LOG_LIMIT_RELEASE` is used and defaults to `LOG_CRIT`
543 The default targets are:
545 * In *ALPHA* builds, `NOBUG_LOG_TARGET_ALPHA` is used which defaults to
546 `NOBUG_TARGET_CONSOLE`
547 * In *BETA* builds, `NOBUG_LOG_TARGET_BETA` is used and defaults to
549 * In *RELEASE* builds, `NOBUG_LOG_TARGET_RELEASE` is used and defaults to
550 `NOBUG_TARGET_SYSLOG`
553 You can override all these values with your own values. As an alternative,
554 `NOBUG_LOG_LIMIT` and `NOBUG_LOG_TARGET` can be defined before
555 including "nobug.h" to override all defaults.
557 // doc/logflags.txt:1 //
562 Flags are used to inform NoBug about subsystems/modules or even finer
563 grained sections of the code. These are referred to as 'channels' in other
566 A flag should be declared in a headerfile using the following mechanism:
569 NOBUG_DECLARE_FLAG(flagname)
571 It is advisable to do so in one of your header files.
573 Furthermore, the flag must be defined in some implementation file by using one
574 of the following schemes:
577 NOBUG_DEFINE_FLAG(flagname)
581 [[DEFINE_FLAG_LIMIT]]
582 NOBUG_DEFINE_FLAG_LIMIT(flagname, limit)
584 Moreover, macros are available that accept a 'parent' flag as a parameter, which is then
585 used to initialize the defaults from another flag:
587 [[DEFINE_FLAG_PARENT]]
588 NOBUG_DEFINE_FLAG_PARENT(flagname, parent)
592 [[DEFINE_FLAG_PARENT_LIMIT]]
593 NOBUG_DEFINE_FLAG_PARENT_LIMIT(flagname, parent, limit)
595 This can be used to create hierachies of flags
598 [[Cplusplus_logflags]]
599 .C++ support, C++ logflags
601 Additional macros are available for applications written in C++:
603 NOBUG_CPP_DEFINE_FLAG(name)
604 NOBUG_CPP_DEFINE_FLAG_PARENT(name, parent)
605 NOBUG_CPP_DEFINE_FLAG_LIMIT(name, default)
606 NOBUG_CPP_DEFINE_FLAG_PARENT_LIMIT(name, parent, default)
608 These macros statically initialize the flags when they are defined, there is no
609 need to call `NOBUG_INIT_FLAG()` (see below).
612 .Force declarations only
614 When the the following preprocessor constant is defined to be `1`:
619 then *all* definitions here (`NOBUG_DEFINE_*`)
620 become declarations only. When this is defined to be `0` (which is the
621 default) then all definitions behave as described.
622 This can be used to construct a headerfile which only contains
623 definitions, but, by default, yield only declarations. This provides one
624 convenient single point to maintain flag configurations.
626 .Maintaining flags in a single header 'flags.h'
632 if not included from flags.c then declare the flags,
636 #define NOBUG_DECLARE_ONLY 1
639 /* use only DEFINE_FLAG here */
640 NOBUG_DEFINE_FLAG(example);
643 Reset it to 0 to cause no trouble
646 #undef NOBUG_DECLARE_ONLY
647 #define NOBUG_DECLARE_ONLY 0
660 .Logging Flag Initialization
664 NOBUG_INIT_FLAG(flagname)
668 NOBUG_INIT_FLAG_LIMIT(flagname, default)
670 once at the start of your program for each flag.
672 For flags defined with `NOBUG_DEFINE_FLAG(flagname)` the defaults are initialized
673 as in the xref:logdefaults[table above], while
674 `NOBUG_DEFINE_FLAG_LIMIT(flagname, level)` is used to initialize the
675 default target (depending on build level) to `level`.
677 // doc/logflagsenv.txt:1 //
679 Control what gets logged
680 ~~~~~~~~~~~~~~~~~~~~~~~~
682 The `NOBUG_INIT_FLAG...` calls parsing the environment variable
683 'NOBUG_LOG' to configure what gets logged at runtime. The syntax is as
686 .Formal Syntax for log control
689 logdecl_list --> logdecl, any( ',' logdecl_list).
691 logdecl --> flag, opt(limitdecl, any(targetdecl)).
693 flag --> "identifier of a flag".
695 limitdecl --> ':', "LIMITNAME".
697 targetdecl --> '@', "targetname", opt(targetopts).
699 targetopts --> '(', "options for target", ')', opt(targetopts).
702 Roughly speaking, 'NOBUG_LOG' contains a comma separated list of declarations for
703 flags which are the name of the flag followed by a limit which is written in
704 all uppercase letters and preceeded by a colon, followed by target declarations
705 which are names of the targets, introduced by a at sign. Target declarations
706 can have option, described in the next section. Limit and target
707 declarations are optional and then choosen from the defaults table above. These
708 defaults are currently just an guess what should be useable and might be
713 The Following options are available:
716 `(file=_filename_)`:: set filename backing the ringbuffer
717 `(size=_nnn_)`:: set size of the ringbuffer
718 `(append)`:: don't erase existing ringbuffer
719 `(keep)`:: keep file after application end
720 `(temp)`:: unlink file instantly at creation
723 `(fd=n)`:: redirect console output to fd n
726 `(name=_filename_)`:: log to filename
727 `(append)`:: append to (existing) log
730 `(ident=_name_)`:: global prefix for syslog
731 `(cons)`:: log to system console if syslog is down
732 `(pid)`:: include pid in log
733 `(perror)`:: log to stderr as well
736 .How the NOBUG_LOG is used
739 # set the limit of the default target a default limit (see table above)
740 NOBUG_LOG='flag,other'
742 # set the limit of the default target to DEBUG
743 NOBUG_LOG='flag:DEBUG'
745 # set console and syslog limits for flag to DEBUG
746 NOBUG_LOG='flag:DEBUG@console@syslog'
748 # trace 'other' to a persistent ringbuffer
749 NOBUG_LOG='other:TRACE@ringbuffer(file=log.rb)(size=8192)(keep)'
752 .Using log flags (example.c)
757 NOBUG_DEFINE_FLAG (test);
761 /* NOBUG_INIT; // not needed because of NOBUG_INIT_FLAG */
762 NOBUG_INIT_FLAG (test);
764 TRACE (test, "Logging enabled");
765 TRACE (NOBUG_ON, "Always on");
772 $ cc -DEBUG_ALPHA -lnobug example.c
774 0000000002: TRACE: example.c:11: main: Always on
776 $ NOBUG_LOG=test:TRACE ./a.out
777 0000000001: TRACE: example.c:10: main: Logging enabled
778 0000000002: TRACE: example.c:11: main: Always on
785 There are some debugging flags which are predefined by NoBug.
790 The flag `NOBUG_ON` is always enabled at LOG_DEBUG level. This is
791 static and can not be changed.
796 The flag `NOBUG_ANN` is used for the source annotations. This is
797 static and can not be changed. It differs from `NOBUG_ON` as in
798 never logging to syslog and only define a LOG_WARNING limit for the
799 application callback.
804 Actions on NoBug itself will be logged under the `nobug` flag itself.
805 When you want to see whats going on (useful to check if you call
806 `NOBUG_INIT_FLAG()` on all flags) you can enable it with `NOBUG_LOG=nobug:TRACE`.
808 // doc/macros.txt:1 //
812 The NoBug interface is almost completely implemented using
813 preprocessor macros. This is required because NoBug uses the
814 `+++__FILE__+++`, `+++__LINE__+++` and `+++__func__+++` macros to
815 log information on the current file, line number and function.
816 Moreover, all the flat namespace uppercase identifiers make it ease
817 to recognise the macros in source code.
819 All macros are available without condition with a `NOBUG_...` prefix.
820 Many macros (the common cases) are also available without this prefix
821 as a convenience, however macros without this prefix must not have
822 been previously defined. When `NOBUG_DISABLE_SHORTNAMES` is defined
823 before including 'nobug.h', then only the `NOBUG_` prefixed macros
824 are available and the short forms will never be defined.
826 A set of macros are provided by NoBug that are postfixed by `..._IF`.
827 These macros have the following form:
829 * `..._IF(when, ...)`
831 They perform the desired action only if `when` is true. For example:
833 * `REQUIRE_IF(foo != NULL, foo->something == constrained)`
835 The assertion will only be performed if `foo` is non `NULL`.
837 NoBug also also contains a facility to pass the source context (file,
838 line, function) around, this can be used to write functions which
839 handle things where one is more interested in the context of the caller
840 than the location where the macros appears.
842 This macros are postfixed with `..._CTX` and take an extra context
843 parameter (usually at last but before the logging format specifier and
844 any variable argument list). The context parameter must be of type
845 `const struct nobug_context`.
847 When the `_CTX` context form is used together with the conditional `_IF`
848 form then the suffix of the macros is always `..._IF_CTX`.
850 The macros which take a context have no short form and must always be
851 prefixed with `NOBUG_...`.
853 // doc/parametertable.txt:1 //
857 We use names for parameters which describe their type. These names are
858 orthogonal through all macro definitions.
861 `---------`------------------------------------------------------------------
862 `when` Assertion is only performed if expression `when` is true at runtime
863 `expr` Test without side effects
864 `flag` Flag to enable custom logging groups
865 `type` Data type to be checked as a single identifier name
866 `pointer` Pointer to type
868 `depth` Depth for invariants and dumps
869 `context` Source context of type `struct nobug_context`
870 `...` printf-like format string followed by its arguments
871 ---------------------------------------------------------------------------
873 // src/nobug.h:632 //
880 NoBug passes information about the source location of a given statement in
881 `const struct nobug_context` structures. These can be generated with
882 `NOBUG_CONTEXT` or `NOBUG_CONTEXT_NOFUNC`. The later one doesn't define a
883 function name and must be used when the function context is not available
884 like in static initialization etc..
886 // src/nobug.h:104 //
893 CHECK_IF(when, expr, ...)
895 This assertion is never optimized out. Its main purpose is for implementing
896 testsuites where one want to assert tests independent of the build level
901 REQUIRE_IF(when, expr, ...)
902 NOBUG_REQUIRE_CTX(expr, context,...)
903 NOBUG_REQUIRE_IF_CTX(when, expr, context, ...)
905 Precondition (input) check. Use these macros to validate input a
906 function receives. The checks are enabled in *ALPHA* and *BETA* builds and
907 optimized out in *RELEASE* builds.
912 ENSURE_IF(when, expr, ...)
913 NOBUG_ENSURE_CTX(expr, context, ...)
914 NOBUG_ENSURE_IF_CTX(when, expr, context, ...)
916 Postcondition (progress/output) check. Use these macros to validate the
917 data a function produces (example: return value). `ENSURE` is enabled
918 unconditionally in *ALPHA* builds and optimized out in *BETA* builds for
919 scopes which are tagged as `CHECKED`.
921 The `ENSURE_IF` variants are enabled in *ALPHA* and *BETA* builds.
923 In *RELEASE* builds this checks are
924 always optimized out, scopes tagged as `UNCHECKED` are not permitted.
929 ASSERT_IF(when, expr, ...)
930 NOBUG_ASSERT_CTX(expr, context, ...)
931 NOBUG_ASSERT_IF_CTX(when, expr, context, ...)
933 Generic check. Use these macros when you want to validate something
934 which doesn't fall into one of the above categories. A example is when
935 a library function can return a unexpected result (scanf with syntax
936 error in the formatstring, when a constant/literal formatstring is
937 expected). The checks are enabled in *ALPHA* and *BETA* builds and
938 optimized out in *RELEASE* builds.
944 NoBug overrides the standard `assert` macro, using `NOBUG_ASSERT`.
945 This is just a compatibility feature, its use is not suggested.
949 INVARIANT(type, pointer, depth)
950 INVARIANT_IF(when,type, pointer, depth)
951 INVARIANT_ASSERT(expr, ...)
953 Checking invariants. You can provide more complex checking functions
954 which test the validity of datastructures. Invariants are only enabled
955 in *ALPHA* builds for scopes which are not tagged as `CHECKED` and
956 otherwise optimized out.
958 TODO: describe how to create invariant checks
960 // src/nobug.h:366 //
964 Logging targets a flag (except for `ECHO`) and is done at a log-level relating to syslog levels.
966 NOTE: there is no logging macro for `LOG_EMERG`, this is only used by the assertions as fatal message
972 Never optimized out, logs at LOG_NOTICE level. Its main purpose is for implementing
973 testsuites where one want to print and log messages independent of the build level
978 ALERT_IF(when, flag, ...)
979 NOBUG_ALERT_CTX(flag, context, ...)
980 NOBUG_ALERT_IF_CTX(when, flag, context, ...)
982 This is the most critical condition an application might log. This might be used
983 if an error occurs which can not be handled except a safe shutdown for example.
988 CRITICAL_IF(when, flag, ...)
989 NOBUG_CRITICAL_CTX(flag, context, ...)
990 NOBUG_CRITICAL_IF_CTX(when, flag, context, ...)
992 An error which can not be handled occured but the application does not need to be
993 shutdowen, perhaps waiting for an operator to fix the cause.
998 ERROR_IF(when, flag, ...)
999 NOBUG_ERROR_CTX(flag, context, ...)
1000 NOBUG_ERROR_IF_CTX(when, flag, context, ...)
1002 Application takes a error handling brach
1007 WARN_IF(when, flag, ...)
1008 NOBUG_WARN_CTX(flag, context, ...)
1009 NOBUG_WARN_IF_CTX(when, flag, context, ...)
1011 Rare, handled but unexpected branch
1016 INFO_IF(when, flag, ...)
1017 NOBUG_INFO_CTX(flag, context, ...)
1018 NOBUG_INFO_IF_CTX(when, flag, context, ...)
1020 Message about program progress
1025 NOTICE_IF(when, flag, ...)
1026 NOBUG_NOTICE_CTX(flag, context, ...)
1027 NOBUG_NOTICE_IF_CTX(when, flag, context, ...)
1029 More detailed progress message
1034 TRACE_IF(when, flag, ...)
1035 NOBUG_TRACE_CTX(flag, context, ...)
1036 NOBUG_TRACE_IF_CTX(when, flag, context, ...)
1038 Very fine grained messages
1040 NOTE: that `TRACE` corresponds to `LOG_DEBUG`, because using `DEBUG` could be ambiguous.
1044 NOBUG_LOG_CTX(flag, lvl, context, ...)
1045 NOBUG_LOG_IF_CTX(when, flag, lvl, context, ...)
1047 Generic logging macro which takes the level explicitly,
1048 avoid this, unless you implement your own logging facilities.
1052 NOBUG_LOG_BASELIMIT_ALPHA
1053 NOBUG_LOG_BASELIMIT_BETA
1054 NOBUG_LOG_BASELIMIT_RELEASE
1057 anything more detailed than this base limits will be optimized out.
1058 This is used to reduce the logging overhead for *RELEASE* builds.
1059 By default the limit is set to `LOG_DEBUG` for *ALPHA* and *BETA*
1060 builds, so all logging is retained and `LOG_NOTICE` in *RELEASE*
1061 builds to log the application progress only coarsely then.
1063 This macros can be defined before including 'nobug.h' to some other
1064 log level (as defined in 'syslog.h').
1066 // doc/dumping.txt:1 //
1068 Dumping Datastructures
1069 ----------------------
1071 TODO How to write DUMP handlers
1073 One can write functions for dumping complex datastructures using the NoBug
1074 facilities. This is done by writing a custom function for each
1075 datastructure to be dumped which may recursively call other dumping
1076 functions. There are macros for logging within such a dumper function
1077 and for initiating a dump of a given datastructure.
1079 // src/nobug.h:308 //
1082 DUMP(flag, type, pointer, depth, extra)
1083 DUMP_IF(when, flag, type, pointer, depth, extra)
1085 This macros call a datastructure dump of the object (`pointer`) in question.
1086 `DUMP` is only available in *ALPHA* and *BETA* builds, `DUMP_IF` is also
1087 enabled for the RELEASE builds.
1089 `extra` is a void* which is transparently passed around
1094 DUMP_LOG_IF(when, ...)
1096 Any output from `DUMP` handlers should be done by these macros.
1098 Dumping is by default done on level `LOG_DEBUG`, this can be overridden by
1099 defining `NOBUG_DUMP_LEVEL` to some other level.
1101 // doc/dumpexample.txt:1 //
1102 .How to use the DUMP facilities
1105 -------------------------------------------------------
1109 char * STRING_MEMBER;
1110 struct STRUCTNAME* next;
1112 -------------------------------------------------------
1114 then you define a function like:
1117 -------------------------------------------------------
1119 nobug_STRUCTNAME_dump (const struct STRUCTNAME* self,
1125 // check for self != NULL and that the depth
1126 // limit did not exceed in recursive datastructures
1129 // use DUMP_LOG not LOG to print the data
1130 DUMP_LOG("STRUCTNAME %p: int is %d, string is %s", self,
1131 self->INTEGER_MEMBER,
1132 self->STRING_MEMBER);
1133 // now recurse with decremented depth
1134 nobug_STRUCTNAME_dump (self->next, depth-1, file, line, func);
1137 -------------------------------------------------------
1139 now you can use the DUMP() macros within the code
1142 -------------------------------------------------------
1145 struct STRUCTNAME foo;
1147 DUMP (my_flag, STRUCTNAME, &foo, 2);
1149 -------------------------------------------------------
1151 // src/nobug.h:652 //
1155 One can tag features as:
1161 Something which shouldn't be used in future
1167 not yet finished feature
1173 known bug to be fixed later
1179 enhancement to be done soon
1191 used to tag code-path which shall be never executed.
1195 ELSE_NOTREACHED(...)
1197 same as `else NOTREACHED()`, but wholly optimized out in release builds.
1199 // doc/annotationtable.txt:1 //
1201 The advantage of this tagging over plain source comments is that we can take
1202 some actions if we run in such a tag at compile or runtime:
1204 the action to be taken when such a macro is hit depends on the build level:
1207 `-------------`-----`------------`-----------------------------------------
1209 ---------------------------------------------------------------------------
1210 DEPRECATED log nothing wont compile
1211 UNIMPLEMENTED abort abort wont compile
1212 FIXME log wont compile wont compile
1213 TODO log log wont compile
1214 PLANNED log nothing nothing
1215 NOTREACHED abort abort removed
1216 ---------------------------------------------------------------------------
1220 * abort means first log and then abort
1221 * log will only log once for each sourceline (not on each hit)
1222 * wont compile will abort compilation with a error message
1223 * nothing optimized out, sane way
1224 * removed optimized out for performance reasons
1226 // doc/scopechecks.txt:1 //
1232 The programmer can tag any scope as `UNCHECKED` or `CHECKED`. In *ALPHA* and *BETA*
1233 builds, a global `UNCHECKED` is implied. In *RELEASE* builds, `UNCHECKED` scopes are
1236 // doc/assertiontable.txt:1 //
1237 .Assertions active depending on Build level and Scope
1239 `-----------`-----------------------------------------`-----------------------------`-------------------
1240 *ALPHA* *BETA* *RELEASE*
1241 *UNCHECKED* Preconditions, Postconditions, Invariants Preconditions, Postconditions compiling will abort
1242 *CHECKED* Preconditions, Postconditions Preconditions
1243 ------------------------------------------------------------------------------------------------------
1245 // src/nobug.h:779 //
1249 NoBug has some macros which can be used to simulate errorneous behaviour:
1253 INJECT_GOODBAD(expr, good, bad)
1255 substitutes to an expression and returns good when expr is false and
1256 bad when expr is true. In BETA and RELEASE builds 'good' is always returned.
1260 INJECT_FAULT(expr, bad)
1262 substitutes to a statement which executes 'bad'
1263 when expr is true. Optimitzed out in BETA and RELEASE builds.
1267 In both cases, when a fault is injected it will be logged at
1268 `NOBUG_INJECT_LEVEL` (default: `LOG_NOTICE`). This can be defined
1269 before including 'nobug.h' to override it.
1271 // doc/resourcetracking.txt:1 //
1275 With little effort, NoBug can watch all kinds of resources a program uses. This
1276 becomes useful for resources which are distributed over a multithreaded
1277 program. Resource tracking includes logging actions on resource and checking
1278 locking policies over acquired resources. Resource logging is active in ALPHA
1279 and BETA builds when NOBUG_RESOURCE_LOGGING is defined to 1 (the default).
1280 The resource tracker which supervises locking policies is only enabled in
1286 Resources are abstracted, NoBug has little knowledge about the semantics of a
1287 resource, it only keeps records of resources and the code using it and ensures
1288 basic constraints. Detailed usage checks of resource have to be done with other
1291 Resources are identified by a arbitrary identifier which is just a
1292 pointer. Additionally a name, the type and the source locations which
1293 announced the resource are stored.
1295 Code which wants to use a resource calls a enter macro with its own identifier
1296 and state, then might alter the state and finally a leave macro when finished
1299 When a resource is used one has to pass one of this states:
1301 * NOBUG_RESOURCE_WAITING
1302 + For resources where acquisition could block (locks) you enter it with a
1303 WAITING state first and as soon you acquired it you change the state to one
1305 * NOBUG_RESOURCE_EXCLUSIVE
1306 + Acquired the resource exclusively. It must not be acquired
1307 again, not even from the same thread.
1308 * NOBUG_RESOURCE_RECURSIVE
1309 + The resource might be entered multiple times from the same
1310 thread with this state.
1311 * NOBUG_RESOURCE_SHARED
1312 + The resource might be entered multiple times from any thread
1315 Possible state transitions:
1317 ["graphviz", "resource-transistinons.png"]
1318 ---------------------------------------------------------------------
1321 edge [fontname=Courier fontsize=10]
1323 start [shape=ellipse]
1327 start -> Waiting [label="ENTER()"]
1328 start -> Exclusive [label="ENTER()"]
1329 start -> Recursive [label="ENTER()"]
1331 Waiting -> Exclusive [label="STATE()"]
1332 Waiting -> Recursive [label="STATE()"]
1334 Recursive -> Recursive [label="ENTER()\nSTATE()"]
1336 Waiting -> end [label="LEAVE()"]
1337 Exclusive -> end [label="LEAVE()"]
1338 Recursive -> end [label="LEAVE()"]
1342 ---------------------------------------------------------------------
1347 There are small race conditions between logging and checking resource tracking
1348 and the actual call to the resource using function. This is a design decision
1349 there is no way to account for this exactly when the function call may block.
1351 The Resource Tracker relies on proper announce/forget and enter/leave
1352 are properly pairing. The programmer should ensure that this is done
1353 right, otherwise the results are unpredictable.
1355 // src/nobug.h:996 //
1356 Resource tracking macros
1357 ~~~~~~~~~~~~~~~~~~~~~~~~
1359 [[RESOURCE_LOGGING]]
1360 [[RESOURCE_LOG_LEVEL]]
1362 Unless the user defines `NOBUG_RESOURCE_LOGGING` to 0 each of the above macros
1363 will emit a log message at `NOBUG_RESOURCE_LOG_LEVEL` which defaults to
1368 RESOURCE_HANDLE(name)
1369 RESOURCE_HANDLE_INIT(name)
1371 RESOURCE_USER_INIT(name)
1373 Define and initialize handles for to track resources.
1376 identifer to be used for the handle
1378 There are two kinds of handles, each resource itself is abstracted with a
1379 `RESOURCE_HANDLE` and every access to this resources is tracked through a
1380 `RESOURCE_USER` handle. These macros takes care that the declaration is optimized
1381 out in the same manner as the rest of the resource tracker would be disabled.
1382 You can still instantiate handles as `struct nobug_resource_record*` or
1383 `struct nobug_resource_user*` in structures which must have a constant size
1384 unconditional of the build level. The two `*_INIT` macros can be used to initialize
1385 resource handles and are optimized out when the resource tracker gets disabled.
1387 [[RESOURCE_ANNOUNCE]]
1389 RESOURCE_ANNOUNCE(flag, type, name, identifier, handle)
1390 NOBUG_RESOURCE_ANNOUNCE_RAW(flagptr, type, name, ptr, handle)
1391 NOBUG_RESOURCE_ANNOUNCE_RAW_CTX(flagptr, type, name, ptr, handle, context)
1393 Publishes resources.
1396 the NoBug flag name which turns logging on for this macro
1398 a string which should denote the domain of the resource,
1399 examples are "file", "mutex", "lock", "database" and so on
1401 the actual name of a named resource this as string which
1402 together with type forms a unique identifier of the resource. `type` and
1403 `name` must be available through the entire lifetime of the resource, using
1404 literal strings is recommended
1406 a pointer which should be unique for this resource, any
1407 kind of pointer will suffice, it is only used for identification. In
1408 multithreaded applications the thread identifier becomes an additional
1411 a `NOBUG_RESOURCE_HANDLE` which will be initialized to point to
1412 the newly created resource.
1414 Resources must be unique, it is a fatal error when a resource it tried to be
1415 announced more than one time.
1417 'RESOURCE_ANNOUNCE()' acts like the head of a C loop statement, it ties to the following
1418 (block-) statement. Leaving and the user defined following statement are atomic.
1419 This statement must not be left by break, return or any other kind of jump.
1423 RESOURCE_FORGET(flag, handle)
1424 NOBUG_RESOURCE_FORGET_RAW(flagptr, handle)
1425 NOBUG_RESOURCE_FORGET_RAW_CTX(flagptr, handle, context)
1427 Removes resources that have become unavailable from the registry.
1430 the NoBug flag which turns logging on for this macro
1432 the `NOBUG_RESOURCE_HANDLE` used to track this resource
1434 The resource must still exist and no users must be attached to it, else a fatal
1437 'RESOURCE_FORGET()' acts like the head of a C loop statement, it ties to the following
1438 (block-) statement. Leaving and the user defined following statement are atomic.
1439 This statement must not be left by break, return or any other kind of jump.
1443 RESOURCE_ENTER(flag, announced, user, state, handle)
1444 NOBUG_RESOURCE_ENTER_CTX(flag, resource, user, state, handle, context)
1449 nobug flag which turns logging on for this macro
1451 the handle set by `RESOURCE_ANNOUNCE`
1453 a free-form identifier
1455 the initial state, one of `NOBUG_RESOURCE_WAITING`, `NOBUG_RESOURCE_TRYING`,
1456 `NOBUG_RESOURCE_EXCLUSIVE`, `NOBUG_RESOURCE_RECURSIVE` or `NOBUG_RESOURCE_SHARED`
1458 a `NOBUG_RESOURCE_HANDLE` which will be initialized to the
1461 'RESOURCE_ENTER()' acts like the head of a C loop statement, it ties to the following
1462 (block-) statement. Leaving and the user defined following statement are atomic.
1463 This statement must not be left by break, return or any other kind of jump.
1467 RESOURCE_WAIT(flag, resource, user, handle)
1468 NOBUG_RESOURCE_WAIT_CTX(flag, resource, user, handle, context)
1470 This is just an alias for RESOURCE_ENTER(flag, resource, user, NOBUG_RESOURCE_WAITING, handle)
1475 RESOURCE_WAIT(flag, resource, user, handle);
1476 if (lock_my_resource() == ERROR)
1477 NOBUG_RESOURCE_LEAVE(flag, handle);
1479 RESOURCE_STATE(flag, NOBUG_RESOURCE_EXCLUSIVE, handle);
1484 RESOURCE_TRY(flag, resource, user, handle)
1485 NOBUG_RESOURCE_TRY_CTX(flag, resource, user, handle, context)
1487 This is just an alias for RESOURCE_ENTER(flag, resource, user, NOBUG_RESOURCE_TRYING, handle).
1488 Trying on a resource is similar to waiting but will not trigger a deadlock check. This can be used
1489 when a deadlock is expected at runtime and one handles this otherwise (by a timed wait or something like that).
1493 RESOURCE_STATE(flag, entered, state)
1494 NOBUG_RESOURCE_STATE_CTX(flag, state, entered, context)
1495 NOBUG_RESOURCE_STATE_RAW(flagptr, state, entered)
1496 NOBUG_RESOURCE_STATE_RAW_CTX(flagptr, nstate, entered, context)
1498 Changes resource's state.
1501 is nobug flag which turns logging on for this macro
1503 the new state Note that only certain state transitions are
1504 allowed, see discussion/diagram above
1506 the handle set by `RESOURCE_ENTER`
1508 'RESOURCE_STATE()' acts like the head of a C loop statement, it ties to the following
1509 (block-) statement. Leaving and the user defined following statement are atomic.
1510 This statement must not be left by break, return or any other kind of jump.
1514 RESOURCE_LEAVE(flag, handle){}
1515 NOBUG_RESOURCE_LEAVE_RAW(flagptr, handle){}
1516 NOBUG_RESOURCE_LEAVE_RAW_CTX(flagptr, handle, context){}
1518 Disconnect from a resource identified with its handle.
1521 nobug flag which turns logging on for this macro
1523 the handle you got while entering the resource
1525 'RESOURCE_LEAVE()' acts like the head of a C loop statement, it ties to the following
1526 (block-) statement. Leaving and the user defined following statement are atomic.
1527 This statement must not be left by break, return or any other kind of jump.
1532 NOBUG_RESOURCE_LEAVE(flag, handle)
1534 unlock_my_resource();
1538 [[RESOURCE_ASSERT_STATE]]
1539 .RESOURCE_ASSERT_STATE
1540 RESOURCE_ASSERT_STATE(resource, state)
1541 RESOURCE_ASSERT_STATE_IF(when, resource, state)
1542 NOBUG_RESOURCE_ASSERT_STATE_CTX(resource, state, context)
1543 NOBUG_RESOURCE_ASSERT_STATE_IF_CTX(when, resource, state, context)
1545 Assert that we have a resource in a given state. For multithreaded programms the topmost
1546 state of the calling thread is checked, for non threadeded programs the most recent state on
1550 Condition which must be true for testing the assertion
1558 NOBUG_RESOURCE_DUMP(flag, handle)
1559 NOBUG_RESOURCE_DUMP_IF(when, flag, handle)
1561 Dump the state of a single resource.
1564 Condition which must be true to dump the resource
1566 Nobug flag for the log channel
1568 handle of the resource to be dumped
1570 [[RESOURCE_DUMPALL]]
1572 NOBUG_RESOURCE_DUMPALL(flag)
1573 NOBUG_RESOURCE_DUMPALL_IF(when, flag)
1575 Dump the state of all resources.
1578 Condition which must be true to dump the resources
1580 Nobug flag for the log channel
1584 NOBUG_RESOURCE_LIST(flag)
1585 NOBUG_RESOURCE_LIST_IF(when, flag)
1587 List all registered resources.
1590 Condition which must be true to list the resources
1592 Nobug flag for the log channel
1594 // doc/resourceexample.txt:1 //
1595 .How to use the Resourcetracker
1598 NOBUG_DEFINE_FLAG_LIMIT(test, LOG_DEBUG);
1602 // define a mutex and announce it
1603 pthread_mutex_t my_mutex = PTHREAD_MUTEX_INITIALIZER;
1604 RESOURCE_HANDLE(resource);
1606 // 'example' is just a pointer to this function which suffices as unique id
1607 RESOURCE_ANNOUNCE(test, "mutex", "my_mutex", example, resource);
1609 // the following would be done in a different thread in a real program
1611 RESOURCE_HANDLE(enter);
1613 // announce that we want to use the resource
1614 // &enter also suffices as unique pointer, which is all we need as identifer here
1615 RESOURCE_WAIT(flag, resource, &enter, enter)
1617 // lock() might block
1618 pthread_mutex_lock (&my_mutex);
1619 // assume no errors, got it, change the state
1620 RESOURCE_STATE(test, NOBUG_RESOURCE_EXCLUSIVE, enter);
1623 ////////////////////////////////////////
1624 // program does something useful here //
1625 ////////////////////////////////////////
1627 // we don't need it anymore
1628 RESOURCE_LEAVE(test, enter) // << no semicolon
1629 pthread_mutex_unlock (&my_mutex);
1631 // back in the main thread
1632 RESOURCE_FORGET(test, resource); // remove the resource from the public registry
1636 // doc/resourcedeadlock.txt:1 //
1640 The Resource Tracker is able to detect potential deadlocks. This is done by
1641 learning the relations between locks (precedence). A possible deadlock results
1642 in a log message and a fatal abort. Note that only waiting on resources can
1643 lead to a deadlock. Deadlock detection is implemented in the Resource Tracker
1644 and active in ALPHA builds and optimized out on any other build level.
1646 For details about the deadlock detection algorithm see
1647 xref:deadlock_detection[Appendix: Resource Tracking Alorithm].
1649 // src/nobug.h:2354 //
1653 NoBug provides callbacks, applications can use these
1654 to present logging information in some custom way or hook some special processing in.
1655 The callbacks are initialized to NULL and never modified by NoBug, its the solve responsibility
1656 of the user to manage them.
1658 CAUTION: There are certain constraints what and what not can be done in callbacks
1659 documented below which must be followed.
1662 .type of logging callbacks
1663 typedef void (*nobug_logging_cb)(const struct nobug_flag* flag, int priority, const char *log, void* data)
1665 used for the logging callbacks
1668 Flag structure which defines the logging configuration for this event
1670 Log level of the current event
1672 Pointing to the current log line in the ringbuffer or `NULL`
1674 Global pointer defined by the user, passed arround (see below)
1677 .type of abort callback
1678 typedef void (*nobug_abort_cb)(void* data)
1680 used for the abort callback
1683 Global data defined by the user, passed arround (see below)
1686 .passing data to callbacks
1687 void* nobug_callback_data
1689 This global variable is initialized to `NULL` and will never be touched by NoBug. One can use it
1690 to pass extra data to the callback functions.
1692 [[logging_callback]]
1693 .callback when logging
1694 nobug_logging_cb nobug_logging_callback
1696 This callback gets called when something gets logged.
1697 NoBug will still hold its mutexes when calling this hook, calling NoBug logging or resource tracking
1698 functions from here recursively will deadlock and must be avoided.
1699 The `log` parameter points to the logging message in the ringbuffer.
1700 Unlike other logging targets it is not automatically limited to the log level configured
1701 in the flag but called unconditionally. The callback should implement its own limiting.
1703 When one wants to do complex calls which may include recursion into logging and resource tracking
1704 functions, the intended way is to pass contextual information possibly including a __copy__ of the
1705 `log` parameter in xref:THREAD_DATA[NOBUG_THREAD_DATA] to the postlogging callback (see below).
1706 Other internal NoBug facilties, like the ringbuffer etc, are protected by the mutexes and may be accessed
1709 [[postlogging_callback]]
1710 .callback after logging
1711 nobug_logging_cb nobug_postlogging_callback
1713 This callback gets called after something got logged. The `log` parameter is always NULL and all
1714 NoBug mutexes are released. This means that this function may call any complex things, including
1715 calling logging and resource tracking, but may not call internal NoBug facilities.
1716 Contextual created in the `nobug_logging_callback` and stored in xref:THREAD_DATA[NOBUG_THREAD_DATA] can be
1717 retrieved here and may need to be cleaned up here.
1720 .callback for aborting
1721 nobug_abort_cb nobug_abort_callback
1723 This callback gets called when the application shall be terminated due an error.
1724 It can be used to hook exceptions or similar things in. When it returns, `abort()`
1727 IMPORTANT: Errors detected by NoBug are always fatal. If one handles and possible
1728 throws an exception here, the application must shut down as soon as possible.
1729 Most causes for aborts are optimitzed out in `RELEASE` builds.
1731 // src/nobug.h:1583 //
1739 Using this macro one can pass a direct pointer to a flag where a name would
1740 be expected. This is sometimes convinient when flag pointers are passed around
1741 in management strutures and one wants to tie logging to dynamic targets.
1745 NOBUG_DEFINE_FLAG(myflag);
1747 struct nobug_flag* ptr = &NOBUG_FLAG(myflag);
1748 TRACE(NOBUG_FLAG_RAW(ptr), "Passed flag by pointer")
1754 NOBUG_BACKTRACE_CTX(context)
1756 The backtrace macro logs a stacktrace using the NoBug facilities.
1757 This is automatically called when NoBug finds an error and is due
1758 to abort. But one might call it manually too.
1764 This is the default implementation for aborting the program, it first syncs all ringbuffers to disk, then
1765 calls the abort callback if defined and then `abort()`.
1769 If not overridden, evaluates to `NOBUG_ABORT_`. One can override this before including
1770 `nobug.h` to customize abortion behaviour. This will be local to the translation unit then.
1772 [[NOBUG_ALPHA_COMMA]]
1774 NOBUG_ALPHA_COMMA(something)
1775 NOBUG_ALPHA_COMMA_NULL
1777 Sometimes it is useful to have initializer code only in *ALPHA* builds, for example when you
1778 conditionally include resource handles only in *ALPHA* versions. An initializer can then
1779 use this macros to append a comman and something else only in *ALPHA* builds as in:
1780 struct foo = {"foo", "bar" NOBUG_ALPHA_COMMA_NULL };
1785 NOBUG_IF_NOT_ALPHA(...)
1787 NOBUG_IF_NOT_BETA(...)
1788 NOBUG_IF_RELEASE(...)
1789 NOBUG_IF_NOT_RELEASE(...)
1791 This macros allow one to conditionally include the code in '(...)' only if the
1792 criteria on the build level is met. If not, nothing gets substituted. Mostly used
1793 internally, but can also be used for custom things.
1795 // doc/multithreading.txt:1 //
1800 It is important that NoBug protects certain operations with locks in
1801 multithreaded programs. You have to ensure that 'HAVE_PTHREAD_H' is defined by
1802 the configuration system and use the 'libnobugmt' library for linking. It is
1803 particular important that libraries using NoBug are compiled with
1804 'HAVE_PTHREAD_H' enabled when they are intended to be used in multithreaded
1807 When Multithreading is used, log messages contain a identifier of the
1808 originating thread. This identifier should be set by
1811 .NOBUG_THREAD_ID_SET
1812 NOBUG_THREAD_ID_SET(name)
1815 New name for the thread
1817 Nobug will assemble a unique identifier by appending a underscore and a
1818 number to name, for example `NOBUG_THREAD_ID_SET("gui")` will result in a
1819 identifier like "gui_5". When you don't set a thread identifier, then NoBug
1820 assigns one automatically with the name 'thread' preprended if needed. Thread
1821 identifiers may be reset with a new call to this macro.
1824 .NOBUG_THREAD_ID_GET
1827 Will return a const char* of the thread id in multithreaded programs and
1828 a pointer to a literal empty string in singlethreaded programs.
1834 Evaluates to a variable of type `void*` which can be used to store
1835 thread local information. This is useable for xref:_callbacks[callbacks] which may
1836 prepare context information to be reused later.
1838 This macro is also available in singlethreaded programs, refering to a
1839 single global variable.
1841 Nobug initializes this variable to `NULL` and then touches it never again.
1843 // src/nobug_rbdump.c:33 //
1845 Dumping Persistent Ringbuffers
1846 ------------------------------
1848 NoBug installs the `nobug_rbdump` tool for dumping the content of a persistent
1849 ringbuffer. It is invoked with the filename of the ringbuffer, the content is then
1852 // doc/testsuite.txt:1 //
1856 TODO Documentation to be written, use the source Luke!
1858 NoBug maintains a `test.sh` script which drives extensive testsuites.
1859 Look at into the 'tests/' folder about how to apply this.
1861 // doc/bestpractices.txt:1 //
1865 NOTE: this section is very work in progress
1870 * Write a testsuite, build your program with -O0 -g -DEBUG_ALPHA and run
1871 the testsuite under valgrind control. Hack until the program mets the
1872 specifications defined by the testsuite.
1874 * Build with desired optimization level and -g -DEBUG_BETA and give the
1875 program to your beta testers.
1877 * Build it with optimization and without -g -DEBUG_*
1879 .What and when to check
1881 * Add REQUIRE checks on your interfaces (incoming parameters). Especially if
1882 a argument might not cover the whole range of the underlying type.
1883 * Don't waste your and your CPU's time with unnecessary checks. The testsuite
1884 should validate your program. NoBug aids in debugging. You can add
1885 Postconditions (ENSURE) and Invariants when you have a bug somewhere and
1886 want to nail it down.
1887 * Added checks don't need to be removed.
1888 * When you use the CHECKED/UNCHECKED features then don't forget C scoping
1889 rules, tag things as CHECKED from the leaves to the root.
1893 * TRACE(flagname) at the begin of every nontrivial function will easily log
1894 the progress of your application.
1895 * Trying a RELEASE build will abort on certain conditions (known BUG, TODO's,
1896 UNCHECKED code), you can use this to find these spots.
1901 // src/nobug_resources.c:333 //
1902 [[deadlock_detection]]
1903 The Resource Tracking Algorithm
1904 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1906 Each resource registers a global 'resource_record'.
1908 Every new locking path discovered is stored as 'resource_node' structures which refer to the associated
1911 Threads keep a trail of 'resource_user' strcutures for each resource entered. This 'resource_user' struct
1912 refer to the 'resource_nodes' and thus indirectly to the associated 'resource_record'.
1914 The deadlock checker uses this information to test if the acqusition of a new resource would yield a
1917 [[nobug_resource_enter]]
1921 In multithreaded programs, whenever a thread wants to wait for a 'resource_record'
1922 the deadlock checker jumps in.
1924 The deadlock checking algorithm is anticipatory as it will find and abort on conditions which may lead
1925 to a potential deadlock by violating the locking order learned earlier.
1927 Each thread holds a stack (list) of each 'resource_user' it created. Leaving
1928 a resource will remove it from this stacklist.
1930 Each 'resource_record' stores the trail which other 'resource_records' are already entered. This relations
1931 are implemented with the 'resource_node' helper structure.
1934 TODO: insert diagram here
1947 First we find out if there is already a node from the to be acquired resource back to
1948 the topmost node of the current threads user stack.
1951 ---------------------------------------------------------------------
1952 struct nobug_resource_user* user = NULL;
1953 struct nobug_resource_node* node = NULL;
1955 if (!llist_is_empty (&tls->res_stack))
1957 user = LLIST_TO_STRUCTP (llist_tail (&tls->res_stack),
1958 struct nobug_resource_user,
1961 struct nobug_resource_node templ =
1964 user->current->resource,
1968 node = (struct nobug_resource_node*)
1969 llist_ufind (&resource->nodes,
1971 nobug_resource_node_resource_cmpfn,
1975 ---------------------------------------------------------------------
1977 Deadlock checking is only done when the node is entered in `WAITING` state and only
1978 available in multithreaded programs.
1981 ---------------------------------------------------------------------
1982 if (state == NOBUG_RESOURCE_WAITING)
1984 #if NOBUG_USE_PTHREAD
1986 ---------------------------------------------------------------------
1988 If node was found above, then this locking path is already validated and no deadlock can happen,
1989 else, if this stack already holds a resource (user is set) we have to go on with checking.
1992 ---------------------------------------------------------------------
1996 ---------------------------------------------------------------------
1998 If not then its checked that the resource to be entered is not on any parent trail of the current topmost resource,
1999 if it is then this could be a deadlock which needs to be further investigated.
2002 ---------------------------------------------------------------------
2003 LLIST_FOREACH (&user->current->resource->nodes, n)
2005 for (struct nobug_resource_node* itr =
2006 ((struct nobug_resource_node*)n)->parent;
2010 if (itr->resource == resource)
2013 ---------------------------------------------------------------------
2015 if the resource was on the trail, we search if there is a common ancestor before the resource
2016 on the trail and the threads current chain,
2017 if yes then this ancestor protects against deadlocks and we can continue.
2020 ---------------------------------------------------------------------
2021 for (struct nobug_resource_node* itr2 = itr->parent;
2023 itr2 = itr2->parent)
2025 LLIST_FOREACH_REV (&tls->res_stack, p)
2027 struct nobug_resource_user* user =
2028 LLIST_TO_STRUCTP (p,
2029 struct nobug_resource_user,
2031 if (user->current->resource == itr2->resource)
2034 ---------------------------------------------------------------------
2036 If no ancestor found, we finally abort with a potential deadlock condition.
2039 ---------------------------------------------------------------------
2040 nobug_resource_error = "possible deadlock detected";
2043 ---------------------------------------------------------------------
2046 [[nobug_resource_leave]]
2050 store the tail and next aside, we need it later
2053 ---------------------------------------------------------------------
2054 #if NOBUG_USE_PTHREAD
2055 struct nobug_resource_user* tail =
2056 LLIST_TO_STRUCTP (llist_tail (&user->thread->res_stack),
2057 struct nobug_resource_user,
2059 struct nobug_resource_user* next =
2060 LLIST_TO_STRUCTP (llist_next (&user->res_stack),
2061 struct nobug_resource_user,
2063 ---------------------------------------------------------------------
2065 remove user struct from thread stack
2066 The res_stack is now like it is supposed to look like with the 'user' removed.
2067 We now need to fix the node tree up to match this list.
2070 ---------------------------------------------------------------------
2071 llist_unlink_fast_ (&user->res_stack);
2072 ---------------------------------------------------------------------
2074 When the the user node was not the tail or only node of the thread stack, we have to check
2075 (and possibly construct) a new node chain for it. No valdation of this chain needs to be done,
2076 since it was already validated when entering the resources first.
2079 ---------------------------------------------------------------------
2080 if (user != tail && !llist_is_empty (&user->thread->res_stack))
2082 struct nobug_resource_user* parent = NULL;
2083 if (llist_head (&user->thread->res_stack) != &next->res_stack)
2086 LLIST_TO_STRUCTP (llist_prev (&next->res_stack),
2087 struct nobug_resource_user,
2090 ---------------------------------------------------------------------
2092 iterate over all users following the removed node, finding nodes pointing to this users or
2096 ---------------------------------------------------------------------
2097 LLIST_FORRANGE (&next->res_stack, &user->thread->res_stack, n)
2099 struct nobug_resource_user* cur =
2100 LLIST_TO_STRUCTP (n,
2101 struct nobug_resource_user,
2104 ---------------------------------------------------------------------
2105 // src/nobug_resources.c:694 //
2107 find the node pointing back to parent, create a new one if not found, rinse repeat
2110 ---------------------------------------------------------------------
2111 struct nobug_resource_node templ =
2118 struct nobug_resource_node* node = (struct nobug_resource_node*)
2119 llist_ufind (&resource->nodes,
2121 nobug_resource_node_parent_cmpfn,
2126 node = nobug_resource_node_new (resource,
2127 parent?parent->current:NULL);
2130 nobug_resource_error = "internal allocation error";
2138 ---------------------------------------------------------------------
2144 xref:ABORT[Aborting]:: abort the program
2145 xref:abort_callback[callback for aborting]:: hook to handle a termination
2146 xref:abort_cb[type of abort callback]:: type of a abort callback function
2147 xref:ALERT[ALERT]:: about to die
2148 xref:ASSERT[ASSERT]:: generic assertion
2149 xref:assert[assert]:: C standard assertion
2150 xref:BACKTRACE[Backtraces]:: generate a backtrace
2151 xref:buildlevel[Build Levels]:: selecting the build level
2152 xref:callback_data[passing data to callbacks]:: data to be passed to callbacks
2153 xref:CHECK[CHECK]:: unnconditional assertion for testsuites
2154 xref:CHECKED[CHECKED, Scope]:: tag scope as reviewed
2155 xref:Cplusplus_logflags[C++ support, C++ logflags]:: C++ support for log flags
2156 xref:CRITICAL[CRITICAL]:: can not continue
2157 xref:deadlock_detection[The Resource Tracking Algorithm]:: how resources are tracked
2158 xref:DECLARE_FLAG[DECLARE_FLAG]:: declaring a flag
2159 xref:DECLARE_ONLY[DECLARE_ONLY]:: force flag declarations only
2160 xref:DEFINE_FLAG[DEFINE_FLAG]:: defining a flag
2161 xref:DEFINE_FLAG_LIMIT[DEFINE_FLAG_LIMIT]:: defining a flag w/ log limit
2162 xref:DEFINE_FLAG_PARENT[DEFINE_FLAG_PARENT]:: defining a flag hierarchy
2163 xref:DEFINE_FLAG_PARENT_LIMIT[DEFINE_FLAG_PARENT_LIMIT]:: defining a flag hierarchy, w/ log limit
2164 xref:DEPRECATED[DEPRECATED]:: to be discarded in future
2165 xref:DUMP[DUMP]:: dumping datastructures
2166 xref:DUMP_LOG[DUMP_LOG]:: logging helper for dumping
2167 xref:ECHO[ECHO]:: unconditional logging for tests
2168 xref:ELSE_NOTREACHED[ELSE_NOTREACHED]:: alternative never taken
2169 xref:ENSURE[ENSURE]:: postconditions (computation outcomes)
2170 xref:ERROR[ERROR]:: something gone wrong
2171 xref:FIXME[FIXME]:: known bug
2172 xref:INFO[INFO]:: progress message
2173 xref:INJECT_FAULT[INJECT_FAULT]:: fault injection statement
2174 xref:INJECT_GOODBAD[INJECT_GOODBAD]:: fault injection expression
2175 xref:INJECT_LEVEL[INJECT_LEVEL]:: log level for fault injection
2176 xref:INVARIANT[INVARIANT]:: validate invariant state
2177 xref:LOG[LOG]:: generic logging
2178 xref:LOG_BASELIMIT[LOG_BASELIMIT]:: minimum compliled-in logging limit
2179 xref:logflags[Log Flags]:: define hierarchies for logging output
2180 xref:logging_callback[callback when logging]:: hook when something get logged
2181 xref:logging_cb[type of logging callbacks]:: type of a logging callback function
2182 xref:multithreading[Multithreading]:: using NoBug in multithreaded programs
2183 xref:NOBUG_ALPHA_COMMA[NOBUG_ALPHA_COMMA]:: append something after a comma in *ALPHA* builds
2184 xref:NOBUG_ANN[NOBUG_ANN]:: log flag for annotations
2185 xref:NOBUG_CONTEXT[Source Contexts]:: pass information about the source location
2186 xref:NOBUG_ENV[Control what gets logged]:: environment variable for loging control
2187 xref:nobug_flag[nobug (flag)]:: log flag used to show nobug actions
2188 xref:NOBUG_FLAG_RAW[NOBUG_FLAG_RAW]:: pass direct flag pointer
2189 xref:NOBUG_IF[NOBUG_IF_*]:: include code conditionally on build level
2190 xref:NOBUG_ON[NOBUG_ON]:: log flag which is always enabled
2191 xref:nobug_resource_enter[Entering Resources]:: deadlock check on enter
2192 xref:nobug_resource_leave[Leaving Resources]:: fix resource lists
2193 xref:NOTICE[NOTICE]:: detailed progress message
2194 xref:NOTREACHED[NOTREACHED]:: code path never taken
2195 xref:PLANNED[PLANNED]:: ideas for future
2196 xref:postlogging_callback[callback after logging]:: hook after something get logged
2197 xref:rbdump[Dumping Persistent Ringbuffers]:: dumping persistent ringbuffers
2198 xref:REQUIRE[REQUIRE]:: preconditions (input parameters)
2199 xref:RESOURCE_ANNOUNCE[RESOURCE_ANNOUNCE]:: publish new resources
2200 xref:RESOURCE_ASSERT_STATE[RESOURCE_ASSERT_STATE]:: assert the state of a resource
2201 xref:RESOURCE_DUMP[RESOURCE_DUMP]:: dump the state of a single resource
2202 xref:RESOURCE_DUMPALL[RESOURCE_DUMPALL]:: dump the state of all resources
2203 xref:RESOURCE_ENTER[RESOURCE_ENTER]:: claim a resource
2204 xref:RESOURCE_FORGET[RESOURCE_FORGET]:: remove resources
2205 xref:RESOURCE_HANDLE[RESOURCE_HANDLE]:: define resource handles
2206 xref:RESOURCE_LEAVE[RESOURCE_LEAVE]:: relinquish a claimed resource
2207 xref:RESOURCE_LIST[RESOURCE_LIST]:: enumerate all registered resources
2208 xref:RESOURCE_LOG_LEVEL[RESOURCE_LOG_LEVEL]:: select the log level for resource logging
2209 xref:RESOURCE_LOGGING[RESOURCE_LOGGING]:: switch resource logging on and off
2210 xref:RESOURCE_STATE[RESOURCE_STATE]:: change the state of a resource
2211 xref:RESOURCE_TRY[RESOURCE_TRY]:: wait for a resource to become available
2212 xref:RESOURCE_WAIT[RESOURCE_WAIT]:: wait for a resource to become available
2213 xref:THREAD_DATA[NOBUG_THREAD_DATA]:: thread local data for application use
2214 xref:THREAD_ID_GET[NOBUG_THREAD_ID_GET]:: query thread id
2215 xref:THREAD_ID_SET[NOBUG_THREAD_ID_SET]:: set or reset thread id
2216 xref:TODO[TODO]:: things to be done
2217 xref:TRACE[TRACE]:: debugging level message
2218 xref:UNCHECKED[UNCHECKED, Scope]:: tag scope as unreviewed
2219 xref:UNIMPLEMENTED[UNIMPLEMENTED]:: not yet implemented
2220 xref:WARN[WARN]:: unexpected fixable error
2222 // doc/license.txt:1 //
2227 Copyright (C) 2009 Christian Thäter <ct@pipapo.org>
2229 This program is free software; you can redistribute it and/or modify
2230 it under the terms of the GNU General Public License as published by
2231 the Free Software Foundation; either version 2 of the License, or
2232 (at your option) any later version.
2234 This program is distributed in the hope that it will be useful,
2235 but WITHOUT ANY WARRANTY; without even the implied warranty of
2236 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
2237 GNU General Public License for more details.
2239 You should have received a copy of the GNU General Public License along
2240 with this program; if not, write to the Free Software Foundation, Inc.,
2241 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
2245 NoBug is released under the "GNU General Public License version 2 or
2246 any later" to protect its freedom. If one wants to use NoBug in a
2247 propietary program, please contact the main author for
2248 acknowledging relicensing terms.
2250 For BSD license style Free Software, this means you can not distribute
2251 binaries linking NoBug without making its source available. To make
2252 this compatible, it is suggested that you dual-license your software
2253 with your prefered BSD like license and the GPL. As long as it uses
2254 NoBug, the GPL will take over and you have to make the source
2255 available, while one can ship a BSD or LGPL Licensed headerfile which
2256 defines all NoBug macros as empty macros and remove libnobug from the
2257 linking, then NoBug isn't used anymore and you may apply BSD license
2258 terms for resulting binaries.
2261 Contributor Agreement
2262 ~~~~~~~~~~~~~~~~~~~~~
2264 Improvements and patches must be licensed as "GPL v2 or any later" to
2265 be acceptable. Further a contributor must either assign his copyright
2266 to the main NoBug author or agree with the possibility that NoBug can
2267 be relicensed for propietary use:
2269 Independent of the GPL license as stated above, The main author of
2270 NoBug explicitly reserve the right to relicense NoBug under
2271 different, even propietary terms. Any contributor agrees to such
2272 a possiblility by sending his contribution to be included into
2273 the official releases.
2275 This agreement is bilateral, every contributor who worked on a
2276 substantial part of NoBug has the right to relicense it after
2277 negotiation with the NoBug main author. Exact terms of such
2278 relicensing are worked out on a per case base.
2280 The intention is that anyone who worked on NoBug should be able to
2281 benefit from his work. This means one should be able to use it at his
2282 workplace, to gain a job or as well as relicense it for a customer.
2283 Unlike other projects which simply ask for transfering the copyright
2284 to the main author, NoBug tries to make it possible to retain the
2285 copyright by anyone who helped the project.
2287 This additional agreement has no impact on the GPL, it's sole purpose
2288 is to define relicensing policies between the NoBug main author and
2289 contributors. When you recieve NoBug it will be licensed under
2290 GPL unless you personally acknowledged other terms with the NoBug main
2291 author (or any other main contributor).
2293 If anyone feels he is not credited in the 'AUTHORS' file or in any
2294 copyright notice, please contact the main author for inclusion.