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 $ make nobug_manual.txt
155 $ ascidoc -a toc nobug_manual.txt
157 // doc/using.txt:1 //
161 Your application will have to include the header file 'nobug.h' before NoBug
167 Once you've included the NoBug API in your application, you'll then have to select
168 a 'build-level'. Build-levels are discussed later, c.f.,
169 xref:buildlevel[buildlevel]. Build-levels are used to define the amount of
170 information NoBug provides to you. Maximum information is generally required while
171 developing an application and the ALPHA build-level is most apropriate during
172 this phase; whereas the released phase of an application will usually only require
173 sparse information, for which the RELEASE build-level has been conceived.
175 A build-level must always be specified, otherwise the compiler will complain
176 while attempting to compile your application. You can specifiy a build level in
177 one of two ways: use a define statement in one of your modules, or pass the
178 build-level using the -D flag to your compiler. Assuming we'd like to select
179 the ALPHA build-level in your application, then your module would assume the
188 Subsequently you'll have to link the appropriate library to your application.
190 A number of different libraries are available to link depending on whether you
191 require to statically or dynamically link, or whether your application is multi
192 or single threaded. The link order is important on your link line. Link the NoBug
193 library 'after' your application's modules. Here's how to statically link,
194 single-threaded applications:
198 gcc -o mybinary $(WHATEVER_FLAGS) mymodule1.o ... mymodulen.o ..../libs/libnobug.a
201 However, for more flexibility in selecting a build-level, you might wish to
202 define various targets in your makefile, one for each build-level. In such
203 cases, the -D flag in your makefile is most appropriate; so your link line for
204 an ALPHA build with multi-threaded support would look like the following:
208 gcc -o mybinary -DEBUG_ALPHA $(WHATEVER_FLAGS) mymodule1.o ... mymodulen.o ..../libs/libnobugmt.a
211 Both libraries must be initialised before they can be used. There are a number
212 of different ways to initialise the NoBug libraries. One of the easiest ways
213 to initialise the NoBug libraries is to use the `NOBUG_INIT` macro, which must
214 be used before any features can be used or any thread is created. This is
215 discussed in more detail in the xref:multithreading[multithreading] chapter.
217 So putting all this together, our application using NoBug might look something
223 #include "nobug.h" /* Include the NoBug API */
224 #define EBUG_ALPHA /* If we have not used the -D Flag in our makefile */
228 NOBUG_INIT; /* Initialise NoBug libs */
239 Many aspects of NoBug can be configured by overriding macros before 'nobug.h' is
242 A project using NoBug can use autoconf to check for execinfo and
245 AC_CHECK_HEADER([execinfo.h], AC_DEFINE(HAVE_EXECINFO_H))
246 PKG_HAVE_DEFINE_WITH_MODULES(VALGRIND, [valgrind])
248 For Multithreaded programs, you should also check for the availability of pthreads
253 When the resulting `HAVE_PTHREAD`, `HAVE_EXECINFO_H` and
254 `HAVE_VALGRIND_H` are defined by the configure script, the
255 relevant features become available.
257 NoBug then defines `NOBUG_USE_PTHREAD`, `NOBUG_USE_VALGRIND` and
258 `NOBUG_USE_EXECINFO` to 1. If you do not want to use any of these features in
259 NoBug, you can override these macros by setting to 0 before including nobug.h.
261 If `NVALGRIND` is defined, there will be no support for valgrind.
265 There are many other macros which can be set and overridden by the user to
266 control behavior. Your help would be appreciated in expanding this documentation
267 if you find some features useful; or simply contact any of the authors.
271 .Using Nobug from a Project using autoconf
274 PKG_CHECK_MODULES(NOBUGMT_LUMIERA, [nobugmt >= 0.3rc1],
275 AC_DEFINE(HAVE_NOBUGMT_H),
276 AC_MSG_ERROR([NoBug pkg-config metadata missing])
280 // doc/additional.txt:1 //
281 Checking for Additional Tools
282 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
284 Various peripheral tools can be used by NoBug depending on the requirements
285 of the application and the detail desired by the user. Such tools can provide
286 additional, detailed information on the application and its behaviour.
287 However, some applications may not require such detail and the associated
288 overhead in information, and users may decide to omit excess information by
289 excluding such tools.
291 At the moment NoBug supports the optional inclusion of gdb, valgrind and support
292 for multi-threaded applications and the information that can be provided by
293 these tools. However, support for other tools may be supplied in the future,
294 e.g. the dbx debugger on OpenSolaris.
296 Such tools can be easily queried on the system and if they are available on a
297 particular system, they can be used by NoBug to provide even more information on
298 the application using NoBug. If such tools are not available or are not
299 required by the user for one reason or other, then NoBug will happily function
300 as usual, just without the extra information.
302 Testing the availability of such tools on a particular system can be achieved
303 using autoconf, as illustrated in the following:
305 `*NOBUG_USE_VALGRIND*`::
307 `0`:: Do not use valgrind
309 `*NOBUG_USE_PTHREAD*`::
310 `1`:: Support for multi-thread applications
311 `0`:: Single-threaded applications
313 `*NOBUG_USE_EXECINFO*`::
314 `1`:: Backtrace information
315 `0`:: No backtrace information
317 These macros are then automatically defined when the configuration system
318 provides the associated `HAVE_*` macros, but can then be overridden by the user,
319 depending on the user's requirements.
322 // doc/whichlibrary.txt:1 //
323 Link Appropriate Library
324 ~~~~~~~~~~~~~~~~~~~~~~~~
326 Finally, the appropriate library (for either single or multi-threaded
327 applications) is linked to the project.
329 *libnobug*:: Link-in this library for single threaded applications.
330 *libnobugmt*:: Link with this library for multi-threaded applications.
332 NoBug installed static and dynamic libraries. When your application
333 uses multiple dynamic libraries which use NoBug or you build a dynamic
334 library, then you have to link against the dynamic library.
336 You can use the `pkg-config` tool to gather information about NoBug in
339 Release builds remove all assertions, but logging is still kept. We
340 make the assumption that bugs which were not covered in alpha and beta
341 builds will not easily show up in releases because the assertions
342 there were not sufficient. Furthermore, end users are not test bunnies
343 and will not provide good bug reports anyway. If there is a problem in
344 a release build, try to track down the cause using a beta build from
347 // doc/initialization.txt:1 //
354 Before anything from NoBug can be used, NoBug must be initialised. This is
355 performed by calling one of the `NOBUG_INIT_` macros.
357 The simpliest such macro among the initialising set is the following:
361 `NOBUG_INIT` can be called more than once, subsequent calls will be a no-op,
362 thus initialising in main and in libraries won't interfere with one another.
364 In other words, `NOBUG_INIT` is usually the first call to NoBug.
367 Since NoBug is intended to be available throughout its whole lifetime,
368 destroying it is not to be advised. Nevertheless, there is a destroy function
369 void nobug_destroy (void)
371 to shutdown NoBug, and this frees all resources associated with it.
372 This is mostly used in the NoBug testsuite itself to check for leaks,
373 and it might be useful for other programs which employ some kind of
379 If you want to use environment variable controlled debuging, then you have to
380 initialize each defined flag with
382 NOBUG_INIT_FLAG(flagname)
386 NOBUG_INIT_FLAG_LIMIT(flagname, default)
388 or one of the C++ compatibility macros.
390 This is documented later in the xref:logconfig[logging configuration] chapter.
395 In Multithreaded programs you should assign an identifier to each
396 thread. A thread identifier is a string which will be automatically
397 appended with an underscore and a incrementing integer. It is is created with:
399 NOBUG_THREAD_ID_SET(name)
401 Calling `NOBUG_THREAD_ID_SET("worker")` will yield in a thread
402 identifier 'worker_1' for example.
404 If you don't set an identifier, then NoBug will assign an automatic one.
405 This is further documented in the xref:multithreading[multi threading]
406 section of this manual.
411 -------------------------------------------------------
413 NOBUG_DEFINE_FLAG(example);
420 NOBUG_THREAD_ID_SET("main");
421 NOBUG_INIT_FLAG(example);
425 -------------------------------------------------------
427 // doc/buildlevels.txt:1 //
429 Debugging Information Granuality: The Build Levels
430 --------------------------------------------------
432 There are three different levels of debugging information available: alpha, beta
433 and release. One of these levels must be specified before compiling, otherwise
434 an error while compiling will occur.
438 This debugging level is envisaged for the development phase of a project
439 where exhaustive testing and logging are required.
441 This debugging level is more appropriate for projects beyond the
442 development phase and ready for trials in the field and users willing to
445 This level is for final, end-users.
447 .Select a Build Level
448 A logging level can be selected by either using a define in one of the
449 applications' modules, or by passing the appropriate level using the -D switch
452 *ALPHA*:: -DEBUG_ALPHA (`#define EBUG_ALPHA`)
454 *BETA*:: -DEBUG_BETA (`#define EBUG_BETA`)
456 *RELEASE*:: -DNDEBUG (`#define NDEBUG`)
458 If none of the above switches has been set, NoBug will abort the
459 compilation with an error.
461 // doc/logging.txt:1 //
465 Nearly all NoBug Macros emit some log message. NoBug gives the user fine
466 grained control over these log messages to display only interesting information
467 without loosing details.
469 Log messages can be routed to various destinations. The following destintaions
473 The underlying storage backend. Messages are appended to the
474 end of the buffer, overwriting older messages at the front of
475 the buffer. NoBug comes with a highly efficient ringbuffer
476 implementation. This ringbuffer is temporary by default but
477 can be made persistent on disk which can be inspected with the
481 This is either just stderr, or, if running under a supported
482 debugger, the debuggers facilities to print messages will be used.
485 The user can open files for log messages.
488 Messages are sent to the standard system logging daemon.
491 There are hooks which allow the programmer to catch logmessages and
492 display them in an application which are defined by the application.
494 Each logmessage has a priority describing its severity in the same way as
497 All non-fatal messages are associated with a programmer defined flag describing
498 the source of the message (subsystem, module, ...).
500 Putting this all together: A user can define which source/flag will be logged at
501 what priority level and to which destination. To make this all easier, NoBug
502 tries to provide reasonable defaults.
504 // doc/logconfiguration.txt:1 //
511 Each log macro has an explicit or implicit log-level which
512 correspondends to syslog levels. Logging is only emitted when the
513 message is more severe or the same as a defined limit.
516 .Default levels for logging
518 `````~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
519 , ALPHA, BETA , RELEASE,
520 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
521 *ringbuffer* , TRACE, INFO , NOTICE , ringbuffer must always be most verbose
522 *console* , INFO , NOTICE , -1 , no log to console in release
523 *file* , TRACE, NOTICE , WARNING,
524 *syslog* , -1 , NOTICE , WARNING, no syslog for test runs
525 *application*, INFO , WARNING, ERROR ,
526 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
528 Depending on the build level, there is a default logging target and a default
529 limit which is selected when the user doesn't specify one.
531 The following default limits are available:
533 * In *ALPHA* builds, `NOBUG_LOG_LIMIT_ALPHA` is used which defaults to `LOG_INFO`
534 * In *BETA* builds, `NOBUG_LOG_LIMIT_BETA` is used and defaults to `LOG_WARNING`
535 * In *RELEASE* builds, `NOBUG_LOG_LIMIT_RELEASE` is used and defaults to `LOG_CRIT`
537 The default targets are:
539 * In *ALPHA* builds, `NOBUG_LOG_TARGET_ALPHA` is used which defaults to
540 `NOBUG_TARGET_CONSOLE`
541 * In *BETA* builds, `NOBUG_LOG_TARGET_BETA` is used and defaults to
543 * In *RELEASE* builds, `NOBUG_LOG_TARGET_RELEASE` is used and defaults to
544 `NOBUG_TARGET_SYSLOG`
547 You can override all these values with your own values. As an alternative,
548 `NOBUG_LOG_LIMIT` and `NOBUG_LOG_TARGET` can be defined before
549 including "nobug.h" to override all defaults.
551 // doc/logflags.txt:1 //
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
560 A flag should be declared in a headerfile using the following mechanism:
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:
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`:
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'
626 if not included from flags.c then declare the flags,
630 #define NOBUG_DECLARE_ONLY 1
633 /* use only DEFINE_FLAG here */
634 NOBUG_DEFINE_FLAG(example);
637 Reset it to 0 to cause no trouble
640 #undef NOBUG_DECLARE_ONLY
641 #define NOBUG_DECLARE_ONLY 0
654 .Logging Flag Initialization
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 // doc/logflagsenv.txt:1 //
673 Control what gets logged
674 ~~~~~~~~~~~~~~~~~~~~~~~~
676 The `NOBUG_INIT_FLAG...` calls parsing the environment variable
677 'NOBUG_LOG' to configure what gets logged at runtime. The syntax is as
680 .Formal Syntax for log control
683 logdecl_list --> logdecl, any( ',' logdecl_list).
685 logdecl --> flag, opt(limitdecl, any(targetdecl)).
687 flag --> "identifier of a flag".
689 limitdecl --> ':', "LIMITNAME".
691 targetdecl --> '@', "targetname", opt(targetopts).
693 targetopts --> '(', "options for target", ')', opt(targetopts).
696 Roughly speaking, 'NOBUG_LOG' contains a comma separated list of declarations for
697 flags which are the name of the flag followed by a limit which is written in
698 all uppercase letters and preceeded by a colon, followed by target declarations
699 which are names of the targets, introduced by a at sign. Target declarations
700 can have option, described in the next section. Limit and target
701 declarations are optional and then choosen from the defaults table above. These
702 defaults are currently just an guess what should be useable and might be
707 The Following options are available:
710 `(file=_filename_)`:: set filename backing the ringbuffer
711 `(size=_nnn_)`:: set size of the ringbuffer
712 `(append)`:: don't erase existing ringbuffer
713 `(keep)`:: keep file after application end
714 `(temp)`:: unlink file instantly at creation
717 `(fd=n)`:: redirect console output to fd n
720 `(name=_filename_)`:: log to filename
721 `(append)`:: append to (existing) log
724 `(ident=_name_)`:: global prefix for syslog
725 `(cons)`:: log to system console if syslog is down
726 `(pid)`:: include pid in log
727 `(perror)`:: log to stderr as well
730 .How the NOBUG_LOG is used
733 # set the limit of the default target a default limit (see table above)
734 NOBUG_LOG='flag,other'
736 # set the limit of the default target to DEBUG
737 NOBUG_LOG='flag:DEBUG'
739 # set console and syslog limits for flag to DEBUG
740 NOBUG_LOG='flag:DEBUG@console@syslog'
742 # trace 'other' to a persistent ringbuffer
743 NOBUG_LOG='other:TRACE@ringbuffer(file=log.rb)(size=8192)(keep)'
746 .Using log flags (example.c)
751 NOBUG_DEFINE_FLAG (test);
755 /* NOBUG_INIT; // not needed because of NOBUG_INIT_FLAG */
756 NOBUG_INIT_FLAG (test);
758 TRACE (test, "Logging enabled");
759 TRACE (NOBUG_ON, "Always on");
766 $ cc -DEBUG_ALPHA -lnobug example.c
768 0000000002: TRACE: example.c:11: main: Always on
770 $ NOBUG_LOG=test:TRACE ./a.out
771 0000000001: TRACE: example.c:10: main: Logging enabled
772 0000000002: TRACE: example.c:11: main: Always on
779 There are some debugging flags which are predefined by NoBug.
784 The flag `NOBUG_ON` is always enabled at LOG_DEBUG level. This is
785 static and can not be changed.
790 The flag `NOBUG_ANN` is used for the source annotations. This is
791 static and can not be changed. It differs from `NOBUG_ON` as in
792 never logging to syslog and only define a LOG_WARNING limit for the
793 application callback.
798 Actions on NoBug itself will be logged under the `nobug` flag itself.
799 When you want to see whats going on (useful to check if you call
800 `NOBUG_INIT_FLAG()` on all flags) you can enable it with `NOBUG_LOG=nobug:TRACE`.
802 // doc/macros.txt:1 //
806 The NoBug interface is almost completely implemented using
807 preprocessor macros. This is required because NoBug uses the
808 `+++__FILE__+++`, `+++__LINE__+++` and `+++__func__+++` macros to
809 log information on the current file, line number and function.
810 Moreover, all the flat namespace uppercase identifiers make it ease
811 to recognise the macros in source code.
813 All macros are available without condition with a `NOBUG_...` prefix.
814 Many macros (the common cases) are also available without this prefix
815 as a convenience, however macros without this prefix must not have
816 been previously defined. When `NOBUG_DISABLE_SHORTNAMES` is defined
817 before including 'nobug.h', then only the `NOBUG_` prefixed macros
818 are available and the short forms will never be defined.
820 A set of macros are provided by NoBug that are postfixed by `..._IF`.
821 These macros have the following form:
823 * `..._IF(when, ...)`
825 They perform the desired action only if `when` is true. For example:
827 * `REQUIRE_IF(foo != NULL, foo->something == constrained)`
829 The assertion will only be performed if `foo` is non `NULL`.
831 NoBug also also contains a facility to pass the source context (file,
832 line, function) around, this can be used to write functions which
833 handle things where one is more interested in the context of the caller
834 than the location where the macros appears.
836 This macros are postfixed with `..._CTX` and take an extra context
837 parameter (usually at last but before the logging format specifier and
838 any variable argument list). The context parameter must be of type
839 `const struct nobug_context`.
841 When the `_CTX` context form is used together with the conditional `_IF`
842 form then the suffix of the macros is always `..._IF_CTX`.
844 The macros which take a context have no short form and must always be
845 prefixed with `NOBUG_...`.
847 // doc/parametertable.txt:1 //
851 We use names for parameters which describe their type. These names are
852 orthogonal through all macro definitions.
855 `---------`------------------------------------------------------------------
856 `when` Assertion is only performed if expression `when` is true at runtime
857 `expr` Test without side effects
858 `flag` Flag to enable custom logging groups
859 `type` Data type to be checked as a single identifier name
860 `pointer` Pointer to type
862 `depth` Depth for invariants and dumps
863 `context` Source context of type `struct nobug_context`
864 `...` printf-like format string followed by its arguments
865 ---------------------------------------------------------------------------
867 // src/nobug.h:627 //
874 NoBug passes information about the source location of a given statement in
875 `const struct nobug_context` structures. These can be generated with
876 `NOBUG_CONTEXT` or `NOBUG_CONTEXT_NOFUNC`. The later one doesn't define a
877 function name and must be used when the function context is not available
878 like in static initialization etc..
880 // src/nobug.h:104 //
887 CHECK_IF(when, expr, ...)
889 This assertion is never optimized out. Its main purpose is for implementing
890 testsuites where one want to assert tests independent of the build level
895 REQUIRE_IF(when, expr, ...)
896 NOBUG_REQUIRE_CTX(expr, context,...)
897 NOBUG_REQUIRE_IF_CTX(when, expr, context, ...)
899 Precondition (input) check. Use these macros to validate input a
900 function receives. The checks are enabled in *ALPHA* and *BETA* builds and
901 optimized out in *RELEASE* builds.
906 ENSURE_IF(when, expr, ...)
907 NOBUG_ENSURE_CTX(expr, context, ...)
908 NOBUG_ENSURE_IF_CTX(when, expr, context, ...)
910 Postcondition (progress/output) check. Use these macros to validate the
911 data a function produces (example: return value). `ENSURE` is enabled
912 unconditionally in *ALPHA* builds and optimized out in *BETA* builds for
913 scopes which are tagged as `CHECKED`.
915 The `ENSURE_IF` variants are enabled in *ALPHA* and *BETA* builds.
917 In *RELEASE* builds this checks are
918 always optimized out, scopes tagged as `UNCHECKED` are not permitted.
923 ASSERT_IF(when, expr, ...)
924 NOBUG_ASSERT_CTX(expr, context, ...)
925 NOBUG_ASSERT_IF_CTX(when, expr, context, ...)
927 Generic check. Use these macros when you want to validate something
928 which doesn't fall into one of the above categories. A example is when
929 a library function can return a unexpected result (scanf with syntax
930 error in the formatstring, when a constant/literal formatstring is
931 expected). The checks are enabled in *ALPHA* and *BETA* builds and
932 optimized out in *RELEASE* builds.
938 NoBug overrides the standard `assert` macro, using `NOBUG_ASSERT`.
939 This is just a compatibility feature, its use is not suggested.
943 INVARIANT(type, pointer, depth)
944 INVARIANT_IF(when,type, pointer, depth)
945 INVARIANT_ASSERT(expr, ...)
947 Checking invariants. You can provide more complex checking functions
948 which test the validity of datastructures. Invariants are only enabled
949 in *ALPHA* builds for scopes which are not tagged as `CHECKED` and
950 otherwise optimized out.
952 TODO: describe how to create invariant checks
954 // src/nobug.h:361 //
958 Logging targets a flag (except for `ECHO`) and is done at a log-level relating to syslog levels.
960 NOTE: there is no logging macro for `LOG_EMERG`, this is only used by the assertions as fatal message
966 Never optimized out, logs at LOG_NOTICE level. Its main purpose is for implementing
967 testsuites where one want to print and log messages independent of the build level
972 ALERT_IF(when, flag, ...)
973 NOBUG_ALERT_CTX(flag, context, ...)
974 NOBUG_ALERT_IF_CTX(when, flag, context, ...)
976 This is the most critical condition an application might log. This might be used
977 if an error occurs which can not be handled except a safe shutdown for example.
982 CRITICAL_IF(when, flag, ...)
983 NOBUG_CRITICAL_CTX(flag, context, ...)
984 NOBUG_CRITICAL_IF_CTX(when, flag, context, ...)
986 An error which can not be handled occured but the application does not need to be
987 shutdowen, perhaps waiting for an operator to fix the cause.
992 ERROR_IF(when, flag, ...)
993 NOBUG_ERROR_CTX(flag, context, ...)
994 NOBUG_ERROR_IF_CTX(when, flag, context, ...)
996 Application takes a error handling brach
1001 WARN_IF(when, flag, ...)
1002 NOBUG_WARN_CTX(flag, context, ...)
1003 NOBUG_WARN_IF_CTX(when, flag, context, ...)
1005 Rare, handled but unexpected branch
1010 INFO_IF(when, flag, ...)
1011 NOBUG_INFO_CTX(flag, context, ...)
1012 NOBUG_INFO_IF_CTX(when, flag, context, ...)
1014 Message about program progress
1019 NOTICE_IF(when, flag, ...)
1020 NOBUG_NOTICE_CTX(flag, context, ...)
1021 NOBUG_NOTICE_IF_CTX(when, flag, context, ...)
1023 More detailed progress message
1028 TRACE_IF(when, flag, ...)
1029 NOBUG_TRACE_CTX(flag, context, ...)
1030 NOBUG_TRACE_IF_CTX(when, flag, context, ...)
1032 Very fine grained messages
1034 NOTE: that `TRACE` corresponds to `LOG_DEBUG`, because using `DEBUG` could be ambiguous.
1038 NOBUG_LOG_CTX(flag, lvl, context, ...)
1039 NOBUG_LOG_IF_CTX(when, flag, lvl, context, ...)
1041 Generic logging macro which takes the level explicitly,
1042 avoid this, unless you implement your own logging facilities.
1046 NOBUG_LOG_BASELIMIT_ALPHA
1047 NOBUG_LOG_BASELIMIT_BETA
1048 NOBUG_LOG_BASELIMIT_RELEASE
1051 anything more detailed than this base limits will be optimized out.
1052 This is used to reduce the logging overhead for *RELEASE* builds.
1053 By default the limit is set to `LOG_DEBUG` for *ALPHA* and *BETA*
1054 builds, so all logging is retained and `LOG_NOTICE` in *RELEASE*
1055 builds to log the application progress only coarsely then.
1057 This macros can be defined before including 'nobug.h' to some other
1058 log level (as defined in 'syslog.h').
1060 // doc/dumping.txt:1 //
1062 Dumping Datastructures
1063 ----------------------
1065 TODO How to write DUMP handlers
1067 One can write functions for dumping complex datastructures using the NoBug
1068 facilities. This is done by writing a custom function for each
1069 datastructure to be dumped which may recursively call other dumping
1070 functions. There are macros for logging within such a dumper function
1071 and for initiating a dump of a given datastructure.
1073 // src/nobug.h:307 //
1076 DUMP(flag, type, pointer, depth)
1077 DUMP_IF(when, flag, type, pointer, depth)
1079 This macros call a datastructure dump of the object (`pointer`) in question.
1080 `DUMP` is only available in *ALPHA* and *BETA* builds, `DUMP_IF` is also
1081 enabled for the RELEASE builds.
1086 DUMP_LOG_IF(when, ...)
1088 Any output from `DUMP` handlers should be done by these macros.
1090 Dumping is by default done on level `LOG_DEBUG`, this can be overridden by
1091 defining `NOBUG_DUMP_LEVEL` to some other level.
1093 // doc/dumpexample.txt:1 //
1094 .How to use the DUMP facilities
1097 -------------------------------------------------------
1101 char * STRING_MEMBER;
1102 struct STRUCTNAME* next;
1104 -------------------------------------------------------
1106 then you define a function like:
1109 -------------------------------------------------------
1111 nobug_STRUCTNAME_dump (const struct STRUCTNAME* self,
1117 // check for self != NULL and that the depth
1118 // limit did not exceed in recursive datastructures
1121 // use DUMP_LOG not LOG to print the data
1122 DUMP_LOG("STRUCTNAME %p: int is %d, string is %s", self,
1123 self->INTEGER_MEMBER,
1124 self->STRING_MEMBER);
1125 // now recurse with decremented depth
1126 nobug_STRUCTNAME_dump (self->next, depth-1, file, line, func);
1129 -------------------------------------------------------
1131 now you can use the DUMP() macros within the code
1134 -------------------------------------------------------
1137 struct STRUCTNAME foo;
1139 DUMP (my_flag, STRUCTNAME, &foo, 2);
1141 -------------------------------------------------------
1143 // src/nobug.h:647 //
1147 One can tag features as:
1153 Something which shouldn't be used in future
1159 not yet finished feature
1165 known bug to be fixed later
1171 enhancement to be done soon
1183 used to tag code-path which shall be never executed.
1187 ELSE_NOTREACHED(...)
1189 same as `else NOTREACHED()`, but wholly optimized out in release builds.
1191 // doc/annotationtable.txt:1 //
1193 The advantage of this tagging over plain source comments is that we can take
1194 some actions if we run in such a tag at compile or runtime:
1196 the action to be taken when such a macro is hit depends on the build level:
1199 `-------------`-----`------------`-----------------------------------------
1201 ---------------------------------------------------------------------------
1202 DEPRECATED log nothing wont compile
1203 UNIMPLEMENTED abort abort wont compile
1204 FIXME log wont compile wont compile
1205 TODO log log wont compile
1206 PLANNED log nothing nothing
1207 NOTREACHED abort abort removed
1208 ---------------------------------------------------------------------------
1212 * abort means first log and then abort
1213 * log will only log once for each sourceline (not on each hit)
1214 * wont compile will abort compilation with a error message
1215 * nothing optimized out, sane way
1216 * removed optimized out for performance reasons
1218 // doc/scopechecks.txt:1 //
1224 The programmer can tag any scope as `UNCHECKED` or `CHECKED`. In *ALPHA* and *BETA*
1225 builds, a global `UNCHECKED` is implied. In *RELEASE* builds, `UNCHECKED` scopes are
1228 // doc/assertiontable.txt:1 //
1229 .Assertions active depending on Build level and Scope
1231 `-----------`-----------------------------------------`-----------------------------`-------------------
1232 *ALPHA* *BETA* *RELEASE*
1233 *UNCHECKED* Preconditions, Postconditions, Invariants Preconditions, Postconditions compiling will abort
1234 *CHECKED* Preconditions, Postconditions Preconditions
1235 ------------------------------------------------------------------------------------------------------
1237 // src/nobug.h:774 //
1241 NoBug has some macros which can be used to simulate errorneous behaviour:
1245 INJECT_GOODBAD(expr, good, bad)
1247 substitutes to an expression and returns good when expr is false and
1248 bad when expr is true. In BETA and RELEASE builds 'good' is always returned.
1252 INJECT_FAULT(expr, bad)
1254 substitutes to a statement which executes 'bad'
1255 when expr is true. Optimitzed out in BETA and RELEASE builds.
1259 In both cases, when a fault is injected it will be logged at
1260 `NOBUG_INJECT_LEVEL` (default: `LOG_NOTICE`). This can be defined
1261 before including 'nobug.h' to override it.
1263 // doc/resourcetracking.txt:1 //
1267 With little effort, NoBug can watch all kinds of resources a program uses. This
1268 becomes useful for resources which are distributed over a multithreaded
1269 program. Resource tracking includes logging actions on resource and checking
1270 locking policies over acquired resources. Resource logging is active in ALPHA
1271 and BETA builds when NOBUG_RESOURCE_LOGGING is defined to 1 (the default).
1272 The resource tracker which supervises locking policies is only enabled in
1278 Resources are abstracted, NoBug has little knowledge about the semantics of a
1279 resource, it only keeps records of resources and the code using it and ensures
1280 basic constraints. Detailed usage checks of resource have to be done with other
1283 Resources are identified by a arbitrary identifier which is just a
1284 pointer. Additionally a name, the type and the source locations which
1285 announced the resource are stored.
1287 Code which wants to use a resource calls a enter macro with its own identifier
1288 and state, then might alter the state and finally a leave macro when finished
1291 When a resource is used one has to pass one of this states:
1293 * NOBUG_RESOURCE_WAITING
1294 + For resources where acquisition could block (locks) you enter it with a
1295 WAITING state first and as soon you acquired it you change the state to one
1297 * NOBUG_RESOURCE_EXCLUSIVE
1298 + Acquired the resource exclusively. It must not be acquired
1299 again, not even from the same thread.
1300 * NOBUG_RESOURCE_RECURSIVE
1301 + The resource might be entered multiple times from the same
1302 thread with this state.
1303 * NOBUG_RESOURCE_SHARED
1304 + The resource might be entered multiple times from any thread
1307 Possible state transitions:
1309 ["graphviz", "resource-transistinons.png"]
1310 ---------------------------------------------------------------------
1313 edge [fontname=Courier fontsize=10]
1315 start [shape=ellipse]
1319 start -> Waiting [label="ENTER()"]
1320 start -> Exclusive [label="ENTER()"]
1321 start -> Recursive [label="ENTER()"]
1323 Waiting -> Exclusive [label="STATE()"]
1324 Waiting -> Recursive [label="STATE()"]
1326 Recursive -> Recursive [label="ENTER()\nSTATE()"]
1328 Waiting -> end [label="LEAVE()"]
1329 Exclusive -> end [label="LEAVE()"]
1330 Recursive -> end [label="LEAVE()"]
1334 ---------------------------------------------------------------------
1339 There are small race conditions between logging and checking resource tracking
1340 and the actual call to the resource using function. This is a design decision
1341 there is no way to account for this exactly when the function call may block.
1343 The Resource Tracker relies on proper announce/forget and enter/leave
1344 are properly pairing. The programmer should ensure that this is done
1345 right, otherwise the results are unpredictable.
1347 // src/nobug.h:991 //
1348 Resource tracking macros
1349 ~~~~~~~~~~~~~~~~~~~~~~~~
1351 [[RESOURCE_LOGGING]]
1352 [[RESOURCE_LOG_LEVEL]]
1354 Unless the user defines `NOBUG_RESOURCE_LOGGING` to 0 each of the above macros
1355 will emit a log message at `NOBUG_RESOURCE_LOG_LEVEL` which defaults to
1360 RESOURCE_HANDLE(name)
1361 RESOURCE_HANDLE_INIT(name)
1363 RESOURCE_USER_INIT(name)
1365 Define and initialize handles for to track resources.
1368 identifer to be used for the handle
1370 There are two kinds of handles, each resource itself is abstracted with a
1371 `RESOURCE_HANDLE` and every access to this resources is tracked through a
1372 `RESOURCE_USER` handle. These macros takes care that the declaration is optimized
1373 out in the same manner as the rest of the resource tracker would be disabled.
1374 You can still instantiate handles as `struct nobug_resource_record*` or
1375 `struct nobug_resource_user*` in structures which must have a constant size
1376 unconditional of the build level. The two `*_INIT` macros can be used to initialize
1377 resource handles and are optimized out when the resource tracker gets disabled.
1379 [[RESOURCE_ANNOUNCE]]
1381 RESOURCE_ANNOUNCE(flag, type, name, identifier, handle)
1382 NOBUG_RESOURCE_ANNOUNCE_RAW(flagptr, type, name, ptr, handle)
1383 NOBUG_RESOURCE_ANNOUNCE_RAW_CTX(flagptr, type, name, ptr, handle, context)
1385 Publishes resources.
1388 the NoBug flag name which turns logging on for this macro
1390 a string which should denote the domain of the resource,
1391 examples are "file", "mutex", "lock", "database" and so on
1393 the actual name of a named resource this as string which
1394 together with type forms a unique identifier of the resource. `type` and
1395 `name` must be available through the entire lifetime of the resource, using
1396 literal strings is recommended
1398 a pointer which should be unique for this resource, any
1399 kind of pointer will suffice, it is only used for identification. In
1400 multithreaded applications the thread identifier becomes an additional
1403 a `NOBUG_RESOURCE_HANDLE` which will be initialized to point to
1404 the newly created resource.
1406 Resources must be unique, it is a fatal error when a resource it tried to be
1407 announced more than one time.
1409 'RESOURCE_ANNOUNCE()' acts like the head of a C loop statement, it ties to the following
1410 (block-) statement. Leaving and the user defined following statement are atomic.
1411 This statement must not be left by break, return or any other kind of jump.
1415 RESOURCE_FORGET(flag, handle)
1416 NOBUG_RESOURCE_FORGET_RAW(flagptr, handle)
1417 NOBUG_RESOURCE_FORGET_RAW_CTX(flagptr, handle, context)
1419 Removes resources that have become unavailable from the registry.
1422 the NoBug flag which turns logging on for this macro
1424 the `NOBUG_RESOURCE_HANDLE` used to track this resource
1426 The resource must still exist and no users must be attached to it, else a fatal
1429 'RESOURCE_FORGET()' acts like the head of a C loop statement, it ties to the following
1430 (block-) statement. Leaving and the user defined following statement are atomic.
1431 This statement must not be left by break, return or any other kind of jump.
1435 RESOURCE_ENTER(flag, announced, user, state, handle)
1436 NOBUG_RESOURCE_ENTER_CTX(flag, resource, user, state, handle, context)
1441 nobug flag which turns logging on for this macro
1443 the handle set by `RESOURCE_ANNOUNCE`
1445 a free-form identifier
1447 the initial state, one of `NOBUG_RESOURCE_WAITING`, `NOBUG_RESOURCE_TRYING`,
1448 `NOBUG_RESOURCE_EXCLUSIVE`, `NOBUG_RESOURCE_RECURSIVE` or `NOBUG_RESOURCE_SHARED`
1450 a `NOBUG_RESOURCE_HANDLE` which will be initialized to the
1453 'RESOURCE_ENTER()' acts like the head of a C loop statement, it ties to the following
1454 (block-) statement. Leaving and the user defined following statement are atomic.
1455 This statement must not be left by break, return or any other kind of jump.
1459 RESOURCE_WAIT(flag, resource, user, handle)
1460 NOBUG_RESOURCE_WAIT_CTX(flag, resource, user, handle, context)
1462 This is just an alias for RESOURCE_ENTER(flag, resource, user, NOBUG_RESOURCE_WAITING, handle)
1467 RESOURCE_WAIT(flag, resource, user, handle);
1468 if (lock_my_resource() == ERROR)
1469 NOBUG_RESOURCE_LEAVE(flag, handle);
1471 RESOURCE_STATE(flag, NOBUG_RESOURCE_EXCLUSIVE, handle);
1476 RESOURCE_TRY(flag, resource, user, handle)
1477 NOBUG_RESOURCE_TRY_CTX(flag, resource, user, handle, context)
1479 This is just an alias for RESOURCE_ENTER(flag, resource, user, NOBUG_RESOURCE_TRYING, handle).
1480 Trying on a resource is similar to waiting but will not trigger a deadlock check. This can be used
1481 when a deadlock is expected at runtime and one handles this otherwise (by a timed wait or something like that).
1485 RESOURCE_STATE(flag, entered, state)
1486 NOBUG_RESOURCE_STATE_CTX(flag, state, entered, context)
1487 NOBUG_RESOURCE_STATE_RAW(flagptr, state, entered)
1488 NOBUG_RESOURCE_STATE_RAW_CTX(flagptr, nstate, entered, context)
1490 Changes resource's state.
1493 is nobug flag which turns logging on for this macro
1495 the new state Note that only certain state transitions are
1496 allowed, see discussion/diagram above
1498 the handle set by `RESOURCE_ENTER`
1500 'RESOURCE_STATE()' 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.
1506 RESOURCE_LEAVE(flag, handle){}
1507 NOBUG_RESOURCE_LEAVE_RAW(flagptr, handle){}
1508 NOBUG_RESOURCE_LEAVE_RAW_CTX(flagptr, handle, context){}
1510 Disconnect from a resource identified with its handle.
1513 nobug flag which turns logging on for this macro
1515 the handle you got while entering the resource
1517 'RESOURCE_LEAVE()' acts like the head of a C loop statement, it ties to the following
1518 (block-) statement. Leaving and the user defined following statement are atomic.
1519 This statement must not be left by break, return or any other kind of jump.
1524 NOBUG_RESOURCE_LEAVE(flag, handle)
1526 unlock_my_resource();
1530 [[RESOURCE_ASSERT_STATE]]
1531 .RESOURCE_ASSERT_STATE
1532 RESOURCE_ASSERT_STATE(resource, state)
1533 RESOURCE_ASSERT_STATE_IF(when, resource, state)
1534 NOBUG_RESOURCE_ASSERT_STATE_CTX(resource, state, context)
1535 NOBUG_RESOURCE_ASSERT_STATE_IF_CTX(when, resource, state, context)
1537 Assert that we have a resource in a given state. For multithreaded programms the topmost
1538 state of the calling thread is checked, for non threadeded programs the most recent state on
1542 Condition which must be true for testing the assertion
1550 NOBUG_RESOURCE_DUMP(flag, handle)
1551 NOBUG_RESOURCE_DUMP_IF(when, flag, handle)
1553 Dump the state of a single resource.
1556 Condition which must be true to dump the resource
1558 Nobug flag for the log channel
1560 handle of the resource to be dumped
1562 [[RESOURCE_DUMPALL]]
1564 NOBUG_RESOURCE_DUMPALL(flag)
1565 NOBUG_RESOURCE_DUMPALL_IF(when, flag)
1567 Dump the state of all resources.
1570 Condition which must be true to dump the resources
1572 Nobug flag for the log channel
1576 NOBUG_RESOURCE_LIST(flag)
1577 NOBUG_RESOURCE_LIST_IF(when, flag)
1579 List all registered resources.
1582 Condition which must be true to list the resources
1584 Nobug flag for the log channel
1586 // doc/resourceexample.txt:1 //
1587 .How to use the Resourcetracker
1590 NOBUG_DEFINE_FLAG_LIMIT(test, LOG_DEBUG);
1594 // define a mutex and announce it
1595 pthread_mutex_t my_mutex = PTHREAD_MUTEX_INITIALIZER;
1596 RESOURCE_HANDLE(resource);
1598 // 'example' is just a pointer to this function which suffices as unique id
1599 RESOURCE_ANNOUNCE(test, "mutex", "my_mutex", example, resource);
1601 // the following would be done in a different thread in a real program
1603 RESOURCE_HANDLE(enter);
1605 // announce that we want to use the resource
1606 // &enter also suffices as unique pointer, which is all we need as identifer here
1607 RESOURCE_WAIT(flag, resource, &enter, enter)
1609 // lock() might block
1610 pthread_mutex_lock (&my_mutex);
1611 // assume no errors, got it, change the state
1612 RESOURCE_STATE(test, NOBUG_RESOURCE_EXCLUSIVE, enter);
1615 ////////////////////////////////////////
1616 // program does something useful here //
1617 ////////////////////////////////////////
1619 // we don't need it anymore
1620 RESOURCE_LEAVE(test, enter) // << no semicolon
1621 pthread_mutex_unlock (&my_mutex);
1623 // back in the main thread
1624 RESOURCE_FORGET(test, resource); // remove the resource from the public registry
1628 // doc/resourcedeadlock.txt:1 //
1632 The Resource Tracker is able to detect potential deadlocks. This is done by
1633 learning the relations between locks (precedence). A possible deadlock results
1634 in a log message and a fatal abort. Note that only waiting on resources can
1635 lead to a deadlock. Deadlock detection is implemented in the Resource Tracker
1636 and active in ALPHA builds and optimized out on any other build level.
1638 For details about the deadlock detection algorithm see
1639 xref:deadlock_detection[Appendix: Resource Tracking Alorithm].
1641 // src/nobug.h:2349 //
1645 NoBug provides callbacks, applications can use these
1646 to present logging information in some custom way or hook some special processing in.
1647 The callbacks are initialized to NULL and never modified by NoBug, its the solve responsibility
1648 of the user to manage them.
1650 CAUTION: There are certain constraints what and what not can be done in callbacks
1651 documented below which must be followed.
1654 .type of logging callbacks
1655 typedef void (*nobug_logging_cb)(const struct nobug_flag* flag, int priority, const char *log, void* data)
1657 used for the logging callbacks
1660 Flag structure which defines the logging configuration for this event
1662 Log level of the current event
1664 Pointing to the current log line in the ringbuffer or `NULL`
1666 Global pointer defined by the user, passed arround (see below)
1669 .type of abort callback
1670 typedef void (*nobug_abort_cb)(void* data)
1672 used for the abort callback
1675 Global data defined by the user, passed arround (see below)
1678 .passing data to callbacks
1679 void* nobug_callback_data
1681 This global variable is initialized to `NULL` and will never be touched by NoBug. One can use it
1682 to pass extra data to the callback functions.
1684 [[logging_callback]]
1685 .callback when logging
1686 nobug_logging_cb nobug_logging_callback
1688 This callback gets called when something gets logged.
1689 NoBug will still hold its mutexes when calling this hook, calling NoBug logging or resource tracking
1690 functions from here recursively will deadlock and must be avoided.
1691 The `log` parameter points to the logging message in the ringbuffer.
1692 Unlike other logging targets it is not automatically limited to the log level configured
1693 in the flag but called unconditionally. The callback should implement its own limiting.
1695 When one wants to do complex calls which may include recursion into logging and resource tracking
1696 functions, the intended way is to pass contextual information possibly including a __copy__ of the
1697 `log` parameter in xref:THREAD_DATA[NOBUG_THREAD_DATA] to the postlogging callback (see below).
1698 Other internal NoBug facilties, like the ringbuffer etc, are protected by the mutexes and may be accessed
1701 [[postlogging_callback]]
1702 .callback after logging
1703 nobug_logging_cb nobug_postlogging_callback
1705 This callback gets called after something got logged. The `log` parameter is always NULL and all
1706 NoBug mutexes are released. This means that this function may call any complex things, including
1707 calling logging and resource tracking, but may not call internal NoBug facilities.
1708 Contextual created in the `nobug_logging_callback` and stored in xref:THREAD_DATA[NOBUG_THREAD_DATA] can be
1709 retrieved here and may need to be cleaned up here.
1712 .callback for aborting
1713 nobug_abort_cb nobug_abort_callback
1715 This callback gets called when the application shall be terminated due an error.
1716 It can be used to hook exceptions or similar things in. When it returns, `abort()`
1719 IMPORTANT: Errors detected by NoBug are always fatal. If one handles and possible
1720 throws an exception here, the application must shut down as soon as possible.
1721 Most causes for aborts are optimitzed out in `RELEASE` builds.
1723 // src/nobug.h:1578 //
1731 Using this macro one can pass a direct pointer to a flag where a name would
1732 be expected. This is sometimes convinient when flag pointers are passed around
1733 in management strutures and one wants to tie logging to dynamic targets.
1737 NOBUG_DEFINE_FLAG(myflag);
1739 struct nobug_flag* ptr = &NOBUG_FLAG(myflag);
1740 TRACE(NOBUG_FLAG_RAW(ptr), "Passed flag by pointer")
1746 NOBUG_BACKTRACE_CTX(context)
1748 The backtrace macro logs a stacktrace using the NoBug facilities.
1749 This is automatically called when NoBug finds an error and is due
1750 to abort. But one might call it manually too.
1756 This is the default implementation for aborting the program, it first syncs all ringbuffers to disk, then
1757 calls the abort callback if defined and then `abort()`.
1761 If not overridden, evaluates to `NOBUG_ABORT_`. One can override this before including
1762 `nobug.h` to customize abortion behaviour. This will be local to the translation unit then.
1764 [[NOBUG_ALPHA_COMMA]]
1766 NOBUG_ALPHA_COMMA(something)
1767 NOBUG_ALPHA_COMMA_NULL
1769 Sometimes it is useful to have initializer code only in *ALPHA* builds, for example when you
1770 conditionally include resource handles only in *ALPHA* versions. An initializer can then
1771 use this macros to append a comman and something else only in *ALPHA* builds as in:
1772 struct foo = {"foo", "bar" NOBUG_ALPHA_COMMA_NULL };
1777 NOBUG_IF_NOT_ALPHA(...)
1779 NOBUG_IF_NOT_BETA(...)
1780 NOBUG_IF_RELEASE(...)
1781 NOBUG_IF_NOT_RELEASE(...)
1783 This macros allow one to conditionally include the code in '(...)' only if the
1784 criteria on the build level is met. If not, nothing gets substituted. Mostly used
1785 internally, but can also be used for custom things.
1787 // doc/multithreading.txt:1 //
1792 It is important that NoBug protects certain operations with locks in
1793 multithreaded programs. You have to ensure that 'HAVE_PTHREAD_H' is defined by
1794 the configuration system and use the 'libnobugmt' library for linking. It is
1795 particular important that libraries using NoBug are compiled with
1796 'HAVE_PTHREAD_H' enabled when they are intended to be used in multithreaded
1799 When Multithreading is used, log messages contain a identifier of the
1800 originating thread. This identifier should be set by
1803 .NOBUG_THREAD_ID_SET
1804 NOBUG_THREAD_ID_SET(name)
1807 New name for the thread
1809 Nobug will assemble a unique identifier by appending a underscore and a
1810 number to name, for example `NOBUG_THREAD_ID_SET("gui")` will result in a
1811 identifier like "gui_5". When you don't set a thread identifier, then NoBug
1812 assigns one automatically with the name 'thread' preprended if needed. Thread
1813 identifiers may be reset with a new call to this macro.
1816 .NOBUG_THREAD_ID_GET
1819 Will return a const char* of the thread id in multithreaded programs and
1820 a pointer to a literal empty string in singlethreaded programs.
1826 Evaluates to a variable of type `void*` which can be used to store
1827 thread local information. This is useable for xref:_callbacks[callbacks] which may
1828 prepare context information to be reused later.
1830 This macro is also available in singlethreaded programs, refering to a
1831 single global variable.
1833 Nobug initializes this variable to `NULL` and then touches it never again.
1835 // src/nobug_rbdump.c:33 //
1837 Dumping Persistent Ringbuffers
1838 ------------------------------
1840 NoBug installs the `nobug_rbdump` tool for dumping the content of a persistent
1841 ringbuffer. It is invoked with the filename of the ringbuffer, the content is then
1844 // doc/testsuite.txt:1 //
1848 TODO Documentation to be written, use the source Luke!
1850 NoBug maintains a `test.sh` script which drives extensive testsuites.
1851 Look at into the 'tests/' folder about how to apply this.
1853 // doc/bestpractices.txt:1 //
1857 NOTE: this section is very work in progress
1862 * Write a testsuite, build your program with -O0 -g -DEBUG_ALPHA and run
1863 the testsuite under valgrind control. Hack until the program mets the
1864 specifications defined by the testsuite.
1866 * Build with desired optimization level and -g -DEBUG_BETA and give the
1867 program to your beta testers.
1869 * Build it with optimization and without -g -DEBUG_*
1871 .What and when to check
1873 * Add REQUIRE checks on your interfaces (incoming parameters). Especially if
1874 a argument might not cover the whole range of the underlying type.
1875 * Don't waste your and your CPU's time with unnecessary checks. The testsuite
1876 should validate your program. NoBug aids in debugging. You can add
1877 Postconditions (ENSURE) and Invariants when you have a bug somewhere and
1878 want to nail it down.
1879 * Added checks don't need to be removed.
1880 * When you use the CHECKED/UNCHECKED features then don't forget C scoping
1881 rules, tag things as CHECKED from the leaves to the root.
1885 * TRACE(flagname) at the begin of every nontrivial function will easily log
1886 the progress of your application.
1887 * Trying a RELEASE build will abort on certain conditions (known BUG, TODO's,
1888 UNCHECKED code), you can use this to find these spots.
1893 // src/nobug_resources.c:326 //
1894 [[deadlock_detection]]
1895 The Resource Tracking Algorithm
1896 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1898 Each resource registers a global 'resource_record'.
1900 Every new locking path discovered is stored as 'resource_node' structures which refer to the associated
1903 Threads keep a trail of 'resource_user' strcutures for each resource entered. This 'resource_user' struct
1904 refer to the 'resource_nodes' and thus indirectly to the associated 'resource_record'.
1906 The deadlock checker uses this information to test if the acqusition of a new resource would yield a
1909 [[nobug_resource_enter]]
1913 In multithreaded programs, whenever a thread wants to wait for a 'resource_record'
1914 the deadlock checker jumps in.
1916 The deadlock checking algorithm is anticipatory as it will find and abort on conditions which may lead
1917 to a potential deadlock by violating the locking order learned earlier.
1919 Each thread holds a stack (list) of each 'resource_user' it created. Leaving
1920 a resource will remove it from this stacklist.
1922 Each 'resource_record' stores the trail which other 'resource_records' are already entered. This relations
1923 are implemented with the 'resource_node' helper structure.
1926 TODO: insert diagram here
1939 First we find out if there is already a node from the to be acquired resource back to
1940 the topmost node of the current threads user stack.
1943 ---------------------------------------------------------------------
1944 struct nobug_resource_user* user = NULL;
1945 struct nobug_resource_node* node = NULL;
1947 if (!llist_is_empty (&tls->res_stack))
1949 user = LLIST_TO_STRUCTP (llist_tail (&tls->res_stack),
1950 struct nobug_resource_user,
1953 struct nobug_resource_node templ =
1956 user->current->resource,
1960 node = (struct nobug_resource_node*)
1961 llist_ufind (&resource->nodes,
1963 nobug_resource_node_resource_cmpfn,
1967 ---------------------------------------------------------------------
1969 Deadlock checking is only done when the node is entered in `WAITING` state and only
1970 available in multithreaded programs.
1973 ---------------------------------------------------------------------
1974 if (state == NOBUG_RESOURCE_WAITING)
1976 #if NOBUG_USE_PTHREAD
1978 ---------------------------------------------------------------------
1980 If node was found above, then this locking path is already validated and no deadlock can happen,
1981 else, if this stack already holds a resource (user is set) we have to go on with checking.
1984 ---------------------------------------------------------------------
1988 ---------------------------------------------------------------------
1990 If not then its checked that the resource to be entered is not on any parent trail of the current topmost resource,
1991 if it is then this could be a deadlock which needs to be further investigated.
1994 ---------------------------------------------------------------------
1995 LLIST_FOREACH (&user->current->resource->nodes, n)
1997 for (struct nobug_resource_node* itr =
1998 ((struct nobug_resource_node*)n)->parent;
2002 if (itr->resource == resource)
2005 ---------------------------------------------------------------------
2007 if the resource was on the trail, we search if there is a common ancestor before the resource
2008 on the trail and the threads current chain,
2009 if yes then this ancestor protects against deadlocks and we can continue.
2012 ---------------------------------------------------------------------
2013 for (struct nobug_resource_node* itr2 = itr->parent;
2015 itr2 = itr2->parent)
2017 LLIST_FOREACH_REV (&tls->res_stack, p)
2019 struct nobug_resource_user* user =
2020 LLIST_TO_STRUCTP (p,
2021 struct nobug_resource_user,
2023 if (user->current->resource == itr2->resource)
2026 ---------------------------------------------------------------------
2028 If no ancestor found, we finally abort with a potential deadlock condition.
2031 ---------------------------------------------------------------------
2032 nobug_resource_error = "possible deadlock detected";
2035 ---------------------------------------------------------------------
2038 [[nobug_resource_leave]]
2042 store the tail and next aside, we need it later
2045 ---------------------------------------------------------------------
2046 #if NOBUG_USE_PTHREAD
2047 struct nobug_resource_user* tail =
2048 LLIST_TO_STRUCTP (llist_tail (&user->thread->res_stack),
2049 struct nobug_resource_user,
2051 struct nobug_resource_user* next =
2052 LLIST_TO_STRUCTP (llist_next (&user->res_stack),
2053 struct nobug_resource_user,
2055 ---------------------------------------------------------------------
2057 remove user struct from thread stack
2058 The res_stack is now like it is supposed to look like with the 'user' removed.
2059 We now need to fix the node tree up to match this list.
2062 ---------------------------------------------------------------------
2063 llist_unlink_fast_ (&user->res_stack);
2064 ---------------------------------------------------------------------
2066 When the the user node was not the tail or only node of the thread stack, we have to check
2067 (and possibly construct) a new node chain for it. No valdation of this chain needs to be done,
2068 since it was already validated when entering the resources first.
2071 ---------------------------------------------------------------------
2072 if (user != tail && !llist_is_empty (&user->thread->res_stack))
2074 struct nobug_resource_user* parent = NULL;
2075 if (llist_head (&user->thread->res_stack) != &next->res_stack)
2078 LLIST_TO_STRUCTP (llist_prev (&next->res_stack),
2079 struct nobug_resource_user,
2082 ---------------------------------------------------------------------
2084 iterate over all users following the removed node, finding nodes pointing to this users or
2088 ---------------------------------------------------------------------
2089 LLIST_FORRANGE (&next->res_stack, &user->thread->res_stack, n)
2091 struct nobug_resource_user* cur =
2092 LLIST_TO_STRUCTP (n,
2093 struct nobug_resource_user,
2096 ---------------------------------------------------------------------
2097 // src/nobug_resources.c:687 //
2099 find the node pointing back to parent, create a new one if not found, rinse repeat
2102 ---------------------------------------------------------------------
2103 struct nobug_resource_node templ =
2110 struct nobug_resource_node* node = (struct nobug_resource_node*)
2111 llist_ufind (&resource->nodes,
2113 nobug_resource_node_parent_cmpfn,
2118 node = nobug_resource_node_new (resource,
2119 parent?parent->current:NULL);
2122 nobug_resource_error = "internal allocation error";
2130 ---------------------------------------------------------------------
2136 xref:ABORT[Aborting]:: abort the program
2137 xref:abort_callback[callback for aborting]:: hook to handle a termination
2138 xref:abort_cb[type of abort callback]:: type of a abort callback function
2139 xref:ALERT[ALERT]:: about to die
2140 xref:ASSERT[ASSERT]:: generic assertion
2141 xref:assert[assert]:: C standard assertion
2142 xref:BACKTRACE[Backtraces]:: generate a backtrace
2143 xref:buildlevel[Build Levels]:: selecting the build level
2144 xref:callback_data[passing data to callbacks]:: data to be passed to callbacks
2145 xref:CHECK[CHECK]:: unnconditional assertion for testsuites
2146 xref:CHECKED[CHECKED, Scope]:: tag scope as reviewed
2147 xref:Cplusplus_logflags[C++ support, C++ logflags]:: C++ support for log flags
2148 xref:CRITICAL[CRITICAL]:: can not continue
2149 xref:deadlock_detection[The Resource Tracking Algorithm]:: how resources are tracked
2150 xref:DECLARE_FLAG[DECLARE_FLAG]:: declaring a flag
2151 xref:DECLARE_ONLY[DECLARE_ONLY]:: force flag declarations only
2152 xref:DEFINE_FLAG[DEFINE_FLAG]:: defining a flag
2153 xref:DEFINE_FLAG_LIMIT[DEFINE_FLAG_LIMIT]:: defining a flag w/ log limit
2154 xref:DEFINE_FLAG_PARENT[DEFINE_FLAG_PARENT]:: defining a flag hierarchy
2155 xref:DEFINE_FLAG_PARENT_LIMIT[DEFINE_FLAG_PARENT_LIMIT]:: defining a flag hierarchy, w/ log limit
2156 xref:DEPRECATED[DEPRECATED]:: to be discarded in future
2157 xref:DUMP[DUMP]:: dumping datastructures
2158 xref:DUMP_LOG[DUMP_LOG]:: logging helper for dumping
2159 xref:ECHO[ECHO]:: unconditional logging for tests
2160 xref:ELSE_NOTREACHED[ELSE_NOTREACHED]:: alternative never taken
2161 xref:ENSURE[ENSURE]:: postconditions (computation outcomes)
2162 xref:ERROR[ERROR]:: something gone wrong
2163 xref:FIXME[FIXME]:: known bug
2164 xref:INFO[INFO]:: progress message
2165 xref:INJECT_FAULT[INJECT_FAULT]:: fault injection statement
2166 xref:INJECT_GOODBAD[INJECT_GOODBAD]:: fault injection expression
2167 xref:INJECT_LEVEL[INJECT_LEVEL]:: log level for fault injection
2168 xref:INVARIANT[INVARIANT]:: validate invariant state
2169 xref:LOG[LOG]:: generic logging
2170 xref:LOG_BASELIMIT[LOG_BASELIMIT]:: minimum compliled-in logging limit
2171 xref:logflags[Log Flags]:: define hierarchies for logging output
2172 xref:logging_callback[callback when logging]:: hook when something get logged
2173 xref:logging_cb[type of logging callbacks]:: type of a logging callback function
2174 xref:multithreading[Multithreading]:: using NoBug in multithreaded programs
2175 xref:NOBUG_ALPHA_COMMA[NOBUG_ALPHA_COMMA]:: append something after a comma in *ALPHA* builds
2176 xref:NOBUG_ANN[NOBUG_ANN]:: log flag for annotations
2177 xref:NOBUG_CONTEXT[Source Contexts]:: pass information about the source location
2178 xref:NOBUG_ENV[Control what gets logged]:: environment variable for loging control
2179 xref:nobug_flag[nobug (flag)]:: log flag used to show nobug actions
2180 xref:NOBUG_FLAG_RAW[NOBUG_FLAG_RAW]:: pass direct flag pointer
2181 xref:NOBUG_IF[NOBUG_IF_*]:: include code conditionally on build level
2182 xref:NOBUG_ON[NOBUG_ON]:: log flag which is always enabled
2183 xref:nobug_resource_enter[Entering Resources]:: deadlock check on enter
2184 xref:nobug_resource_leave[Leaving Resources]:: fix resource lists
2185 xref:NOTICE[NOTICE]:: detailed progress message
2186 xref:NOTREACHED[NOTREACHED]:: code path never taken
2187 xref:PLANNED[PLANNED]:: ideas for future
2188 xref:postlogging_callback[callback after logging]:: hook after something get logged
2189 xref:rbdump[Dumping Persistent Ringbuffers]:: dumping persistent ringbuffers
2190 xref:REQUIRE[REQUIRE]:: preconditions (input parameters)
2191 xref:RESOURCE_ANNOUNCE[RESOURCE_ANNOUNCE]:: publish new resources
2192 xref:RESOURCE_ASSERT_STATE[RESOURCE_ASSERT_STATE]:: assert the state of a resource
2193 xref:RESOURCE_DUMP[RESOURCE_DUMP]:: dump the state of a single resource
2194 xref:RESOURCE_DUMPALL[RESOURCE_DUMPALL]:: dump the state of all resources
2195 xref:RESOURCE_ENTER[RESOURCE_ENTER]:: claim a resource
2196 xref:RESOURCE_FORGET[RESOURCE_FORGET]:: remove resources
2197 xref:RESOURCE_HANDLE[RESOURCE_HANDLE]:: define resource handles
2198 xref:RESOURCE_LEAVE[RESOURCE_LEAVE]:: relinquish a claimed resource
2199 xref:RESOURCE_LIST[RESOURCE_LIST]:: enumerate all registered resources
2200 xref:RESOURCE_LOG_LEVEL[RESOURCE_LOG_LEVEL]:: select the log level for resource logging
2201 xref:RESOURCE_LOGGING[RESOURCE_LOGGING]:: switch resource logging on and off
2202 xref:RESOURCE_STATE[RESOURCE_STATE]:: change the state of a resource
2203 xref:RESOURCE_TRY[RESOURCE_TRY]:: wait for a resource to become available
2204 xref:RESOURCE_WAIT[RESOURCE_WAIT]:: wait for a resource to become available
2205 xref:THREAD_DATA[NOBUG_THREAD_DATA]:: thread local data for application use
2206 xref:THREAD_ID_GET[NOBUG_THREAD_ID_GET]:: query thread id
2207 xref:THREAD_ID_SET[NOBUG_THREAD_ID_SET]:: set or reset thread id
2208 xref:TODO[TODO]:: things to be done
2209 xref:TRACE[TRACE]:: debugging level message
2210 xref:UNCHECKED[UNCHECKED, Scope]:: tag scope as unreviewed
2211 xref:UNIMPLEMENTED[UNIMPLEMENTED]:: not yet implemented
2212 xref:WARN[WARN]:: unexpected fixable error
2214 // doc/license.txt:1 //
2219 Copyright (C) 2009 Christian Thäter <ct@pipapo.org>
2221 This program is free software; you can redistribute it and/or modify
2222 it under the terms of the GNU General Public License as published by
2223 the Free Software Foundation; either version 2 of the License, or
2224 (at your option) any later version.
2226 This program is distributed in the hope that it will be useful,
2227 but WITHOUT ANY WARRANTY; without even the implied warranty of
2228 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
2229 GNU General Public License for more details.
2231 You should have received a copy of the GNU General Public License along
2232 with this program; if not, write to the Free Software Foundation, Inc.,
2233 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
2237 NoBug is released under the "GNU General Public License version 2 or
2238 any later" to protect its freedom. If one wants to use NoBug in a
2239 propietary program, please contact the main author for
2240 acknowledging relicensing terms.
2242 For BSD license style Free Software, this means you can not distribute
2243 binaries linking NoBug without making its source available. To make
2244 this compatible, it is suggested that you dual-license your software
2245 with your prefered BSD like license and the GPL. As long as it uses
2246 NoBug, the GPL will take over and you have to make the source
2247 available, while one can ship a BSD or LGPL Licensed headerfile which
2248 defines all NoBug macros as empty macros and remove libnobug from the
2249 linking, then NoBug isn't used anymore and you may apply BSD license
2250 terms for resulting binaries.
2253 Contributor Agreement
2254 ~~~~~~~~~~~~~~~~~~~~~
2256 Improvements and patches must be licensed as "GPL v2 or any later" to
2257 be acceptable. Further a contributor must either assign his copyright
2258 to the main NoBug author or agree with the possibility that NoBug can
2259 be relicensed for propietary use:
2261 Independent of the GPL license as stated above, The main author of
2262 NoBug explicitly reserve the right to relicense NoBug under
2263 different, even propietary terms. Any contributor agrees to such
2264 a possiblility by sending his contribution to be included into
2265 the official releases.
2267 This agreement is bilateral, every contributor who worked on a
2268 substantial part of NoBug has the right to relicense it after
2269 negotiation with the NoBug main author. Exact terms of such
2270 relicensing are worked out on a per case base.
2272 The intention is that anyone who worked on NoBug should be able to
2273 benefit from his work. This means one should be able to use it at his
2274 workplace, to gain a job or as well as relicense it for a customer.
2275 Unlike other projects which simply ask for transfering the copyright
2276 to the main author, NoBug tries to make it possible to retain the
2277 copyright by anyone who helped the project.
2279 This additional agreement has no impact on the GPL, it's sole purpose
2280 is to define relicensing policies between the NoBug main author and
2281 contributors. When you recieve NoBug it will be licensed under
2282 GPL unless you personally acknowledged other terms with the NoBug main
2283 author (or any other main contributor).
2285 If anyone feels he is not credited in the 'AUTHORS' file or in any
2286 copyright notice, please contact the main author for inclusion.