pipadoced the faultinjection macros
[nobug.git] / README
blobce9403ef17388e4f34b87202cb09ac47352286ed
1 NoBug Documentation
3   * "Everyone makes errors, but with NoBug you won't make them twice!"
5 Nobug is a simple debugging library for instrumenting C and C++ programs
6 inspired by ideas originating from Design-by-Contract.
8 Overview
10 NoBug provides you with the following:
12   * Three different levels for checks - in depth to final no-overhead
13   * Scope tags - tell whenever a function or loop is considered to be bug free
14   * Precondition, Postcondition and Invariant checks, generic assertions
15   * Debugger support (actions are only executed while running under a
16     debugger), currently only valgrind used.
17   * Datastructures can be dumped
18   * Logging your application's activities
19   * Runtime customizable logging via an environment variable
20   * Different logging targets (stderr, syslog, debugger...)
21   * Annotation of your sourcecode about known bugs, things to do, etc.
22   * Tracking resources (files, locks, etc.) used by your program; help in
23     detecting misuse
24   * Detecting deadlocks
26 In contrast to traditional debuggers, NoBug is a non-interactive debugger which
27 is linked to your application doing hard-coded tests in an efficient,
28 low-overhead way.
30 Building and Installing
32 Release Tarballs
34 Release tarballs are attached to this wiki at:
36   * http://pipawiki/NoBug?action=AttachFile
38 I am using gpg signed tarballs for distribution. The first step involves
39 checking the signature:
41 $ gpg nobug-X.Y.tar.gz.gpg
43 This will produce a nobug-X.Y.tar.gz and report if the signature could be
44 validated.
46 Since they are built with gnu autotools, the usual build and install procedure
47 will work:
49 $ tar xzvf nobug-X.Y.tar.gz
50 $ cd nobug-X.Y
51 $ ./configure
52 $ make
53 $ make install
55 Development Version via git
57 The development version is available via git from 'git://git.pipapo.org/nobug'
58 or mirrored at repo.or.cz 'git://repo.or.cz/nobug.git'.
60 After you have cloned the repository, you'll then have to bootstrap the
61 autotools first:
63 $ autoreconf -i
65 Then the usual ./configure && make && make install will work.
67 There is a special makefile target make meta to bring several files (README,
68 AUTHORS, NEWS) in sync with the NoBug documentation wiki and update the
69 changelog.
71 What Is Installed
73 Currently, NoBug installs the following:
75   * A single nobug.h headerfile which your code will use
76   * Two libs that are used by statically linking:
77       + 'libnobug.a' for singlethreaded programs.
78       + 'libnobugmt.a' for multithreaded programs.
80 Using NoBug
82 You can make NoBug features available either by installing it as described
83 above or by shipping the nobug sources along with your project.
85 To use NoBug, some controlling preprocessor macros have to be defined. The
86 nobug.h header should then be included.
88 A project using NoBug should use autoconf to check for execinfo.h and valgrind/
89 valgrind.h
91 AC_CHECK_HEADERS([execinfo.h valgrind/valgrind.h])
93 For Multithreaded programs, you should also check for pthread.h.
95 When the resulting HAVE_PTHREAD_H, HAVE_EXECINFO_H and HAVE_VALGRIND_VALGRIND_H
96 are defined by the configure script, the corresponding features become
97 available.
99 NoBug then defines 'NOBUG_USE_PTHREAD', 'NOBUG_USE_VALGRIND' and
100 'NOBUG_USE_EXECINFO' to 1. If you do not want to use any of these features in
101 NoBug, you can define these macros to 0 before including nobug.h.
103 If NVALGRIND is defined, valgrind support will not be available.
105 There are many other macros which can be set and overridden by the user to
106 control behavior. Please edit the wiki documentation if you find them useful.
108 To use NoBug with single threaded programmes, link libnobug.a to your project;
109 multi-threaded programmes should link with libnobugmt.a. The Library must be
110 initialized with NOBUG_INIT before any features can be used or a thread is
111 created. This is discussed in more detail at NoBug/Documentation/Macros/
112 MultiThreading.
114 Debug Control
116 Build Levels
118 The following degrees to which checks can be performed are available to NoBug:
120   * ALPHA
121       + for expensive testing and logging during the development phase of the
122         software
123     BETA
124       + for testers and users who want to try out the software
125     RELEASE
126       + final version for end users
128 Release builds remove all assertions, but some logging is still kept. We make
129 the assumption that bugs which were not covered in alpha and beta builds will
130 not easily show up in releases because the assertions there were not
131 sufficient. Furthermore, end users are not test bunnies and will not provide
132 good bug reports anyway. If there is a problem in a release build, try to track
133 down the cause using a beta build from the same source.
135 To define a debug level for compilation, just use '-DEBUG_ALPHA' or
136 '-DEBUG_BETA' for debug builds and use the standard '-DNDEBUG' for a release
137 build. NoBug will complain if the debug level has not been defined.
139 Scope Checks
141 The programmer can tag any scope as UNCHECKED or CHECKED. In ALPHA and BETA
142 builds, a global UNCHECKED is implied. In RELEASE builds, UNCHECKED scopes are
143 not allowed.
145 Test Matrix
147 Here is a table of the basic assertions that are checked depending on the level
148 /scope combination:
150           ALPHA                          BETA                   RELEASE
151 UNCHECKED Preconditions, Postconditions, Preconditions,         compiling will
152           Invariants                     Postconditions         abort
153 CHECKED   Preconditions, Postconditions  Preconditions
155 Macros
157 The NoBug interface is almost completely implemented using preprocessor macros.
158 This is required because NoBug uses the __FILE__ and __LINE__ macros to log
159 information on the current file and the current line number within that file.
160 Moreover, all the flat namespace uppercase identifiers make it ease to
161 recognise the macros in source code.
163 All macros are available without condition with the 'NOBUG' prefix. Macros are
164 also available without the NOBUG prefix as a convenience, however macros
165 without this prefix must not have been previously defined. All assertion and
166 logging macros have a corresponding form postfixed by '_DBG'. Such macros will
167 only be active within a debugger and are only available in ALPHA builds.
169 When NOBUG_DISABLE_SHORTNAMES is defined by the user, then only the NOBUG_
170 prefixed macros are available and the short forms will never be defined.
172 A set of macros are provided by NoBug that are postfixed by '_IF'. These macros
173 are wrappers around assert from the C lib. These macros have the following
174 form:
176   * WHATEVER_IF(when, ...)
178 We assert that when is true, if it is not, the assertion will fail. For
179 example:
181   * REQUIRE_IF(foo!=NULL, foo->something == constrained)
183 The assertion will only be performed if foo points to some memory, or is non
184 NULL.
186 Debugger versions are available using _IF_DBG postfixed to the name of the
187 macro.
189 Parameters types:
191 when    Assertion is only performed if expression 'when' is true at runtime
192 expr    Test without side effects
193 fmt     printf-like format string
194 ...     If not preceded by 'fmt', then printf-like format string; otherwise,
195         only its arguments
196 flag    Flag to enable custom logging groups
197 type    Data type to be checked as a single identifier name
198 pointer Pointer to type
199 lvl     Log level
200 depth   Depth for invariants and dumps
202 Initialization
204 Global init
206 You have to call
208   * NOBUG_INIT
210 before using any other NoBug feature. Probably in main or any other library
211 initialization routine. Calling NOBUG_INIT more than once is supported and each
212 subsequent call will be a no-op, thus initialization in main and in libraries
213 won't interfere.
215 Control Flags
217 If you want to use environment variable controlled debuging, then you have to
218 initialize each flag with
220   * NOBUG_INIT_FLAG(flagname)
224   * NOBUG_INIT_FLAG_LIMIT(flagname, default)
226 This is documented later in NoBug/Documentation/Macros/LoggingConfiguration.
228   * <!> These two macros call NOBUG_INIT for backward compatibility.
230 Threads
232 In Multithreaded programs you should assign an identifier to each thread after
233 it is created with
235   * NOBUG_THREAD_ID_SET(name)
237 If you don't call it, then NoBug will assign a automatic identifier. This is
238 documented in NoBug/Documentation/Macros/MultiThreading.
240 Assertions
242   * REQUIRE(expr, ...)
243       + Precondition (input) check. Use these macros to validate input a
244         function receives. The checks are enabled in ALPHA and BETA builds and
245         optimized out in RELEASE builds.
247     ENSURE(expr, ...)
248       + Postcondition (progress/output) check. Use these macros to validate the
249         data a function produces (example: return value). The checks enabled
250         unconditionally in ALPHA builds and optimized out in BETA builds for
251         scopes which are tagged as CHECKED. In RELEASE builds this checks are
252         always optimized out, but scopes tagged as UNCHECKED are not permitted.
254     ASSERT(expr, ...)
255       + Generic check. Use these macros when you want to validate something
256         which doesn't fall into one of the above categories. A example is when
257         a library function can return a unexpected result (scanf with syntax
258         error in the formatstring, when a constant/literal formatstring is
259         expected). The checks are enabled in ALPHA and BETA builds and
260         optimized out in RELEASE builds.
262     assert(expr)
263       + NoBug overrides the standard assert macro in ALPHA and BETA builds.
264         This is just a compatibility feature, its use is not suggested.
266     INVARIANT(type, pointer, depth)
267       + Checking invariants. You can provide more complex checking functions
268         which test the validity of datastructures. Invariants are only enabled
269         in ALPHA builds for scopes which are not tagged as CHECKED and
270         otherwise optimized out. (TODO: document how to write invariants)
272 Logging
274 Nearly all NoBug Macros emit some log message. NoBug gives the user fine
275 grained control over these log messages to display only interesting information
276 without loosing details.
278 Log messages are routed to different destinations which are:
280   * RINGBUFFER
281       + The underlying storage backend. Messages are appended to the end of the
282         buffer, overwriting older messages at the front of the buffer. NoBug
283         comes with a highly efficient ringbuffer implementation. This
284         ringbuffer is temporary by default but can be made persistent. NoBug
285         comes with a 'nobug_rbdump' tool to get a log out of such a ringbuffer.
286   * CONSOLE
287       + This is either just stderr or if running under valgrind then valgrind
288         facilities to include messages into its log will be used.
289   * FILE
290       + The user can open Files for log messages.
291   * SYSLOG
292       + Messages are send to the standard system logging daemon.
293   * APPLICATION
294       + There is a hook which allows the programmer to catch logmessages and
295         display them in a application defined way.
297 Each logmessage has a priority describing its severity in the same way as
298 syslog messages do.
300 All non-fatal messages are associated with a programmer defined flag describing
301 the source of the message (subsystem, module, ...).
303 Putting it all together: A user can define which source/flag shall be logged at
304 what priority level and to which destination. To make this all easier NoBug
305 tries to give reasonable defaults.
307 Configuration
309 Log Levels
311 Each Log macro has a explicit or implicit Log-Level which correspondends to
312 syslog levels. Logging is only emitted when the messages is more severe than a
313 defined limit.
315 The defaults look like:
317             ALPHA BETA    RELEASE
318 ringbuffer  TRACE INFO    NOTICE  ringbuffer must always be most verbose
319 console     INFO  NOTICE  -1      no log to console in release
320 file        TRACE NOTICE  WARNING
321 syslog      -1    NOTICE  WARNING no syslog for test runs
322 application INFO  WARNING ERROR
324 Depending on the build level there is a default logging target and a default
325 limit which is choosen when the user doesn't specify one.
327 The default limits are:
329   * In ALPHA builds, NOBUG_LOG_LIMIT_ALPHA is used which defaults to LOG_INFO
330   * In BETA builds, NOBUG_LOG_LIMIT_BETA is used and defaults to LOG_WARNING
331   * In RELEASE builds, NOBUG_LOG_LIMIT_RELEASE is used and defaults to LOG_CRIT
333 The default targets are:
335   * In ALPHA builds, NOBUG_LOG_TARGET_ALPHA is used which defaults to
336     NOBUG_TARGET_CONSOLE
337   * In BETA builds, NOBUG_LOG_TARGET_BETA is used and defaults to
338     NOBUG_TARGET_FILE
339   * In RELEASE builds, NOBUG_LOG_TARGET_RELEASE is used and defaults to
340     NOBUG_TARGET_SYSLOG
342 You can override all of those values with your own preference. Alternatively
343 NOBUG_LOG_LIMIT and NOBUG_LOG_TARGET can be defined by the user to override all
344 defaults.
346 Log Flags
348 Flags are used to tell NoBug about subsystems/modules or even finer grained
349 parts of the code.
351 A Flag should be declared with
353   * NOBUG_DECLARE_FLAG(flagname)
355 preferably in one of your headers
357 Further it must be defined with
359   * NOBUG_DEFINE_FLAG(flagname)
363   * NOBUG_DEFINE_FLAG_LIMIT(flagname, limit)
365 in one of your source files
367 There are also macros which take a 'parent' flag as parameter which is then
368 used to initialize the defaults from another flag
370   * NOBUG_DEFINE_FLAG_PARENT(flagname, parent)
374   * NOBUG_DEFINE_FLAG_PARENT_LIMIT(flagname, parent, limit)
376 This can be used to create hierachies of flags
378 Next you should call
380   * NOBUG_INIT_FLAG(flagname)
384   * NOBUG_INIT_FLAG_LIMIT(flagname, default)
386 once at the start of your program for every flag.
388 For flags defined with NOBUG_DEFINE_FLAG(flagname) the defaults are initialized
389 as in the table above, while NOBUG_DEFINE_FLAG_LIMIT(flagname, level) is used
390 to initialize the default target (depending on build level) to limit. Calling
391 NOBUG_INIT_FLAG(flagname) is optional for limit initialized flags.
393 NOBUG_INIT_FLAG(flagname) parses the environment variable '$NOBUG_LOG' for
394 flagname, the syntax is as following:
396 logdecl_list --> logdecl, any( ',' logdecl_list).
398 logdecl --> flag, opt(limitdecl, any(targetdecl))
400 flag --> "identifier of a flag"
402 limitdecl --> ':', "LIMITNAME"
404 targetdecl --> '@', "targetname", opt(targetopts)
406 targetopts --> '(', "options for target", ')', opt(targetopts)
408 Roughly speaking, NOBUG_LOG contains a comma separated list of declarations for
409 flags which are the name of the flag followed by a limit which is written in
410 all uppercase letters and preceeded by a colon, followed by target declarations
411 which are names of the targets, introduced by a at sign. Target declarations
412 can have options in future which is not yet implemented. Limit and target
413 declarations are optional and then choosen from the defaults table above. These
414 defaults are currently just an guess what should be useable and might be
415 redefined in future.
417 Options
419 The Following options are implemented:
421   * @ringbuffer
422       + (file=filename) set filename backing the ringbuffer
423         (size=nnn)      set size of the ringbuffer
424         (append)        don't erase existing ringbuffer
425         (keep)          keep file after application end
426         (temp)          unlink file instantly at creation
428     @console
429       + (fd=n) redirect console output to fd n
431     @file
432       + (name=filename) log to filename
433         (append)                        append to (existing) log
435     @syslog
436       + (ident=name) global prefix for syslog
437         (cons)       log to system console if syslog is down
438         (pid)        include pid in log
439         (perror)     log to stderr as well
441 Examples:
443 NOBUG_LOG='flag,other'                        # set the limit of the default target a default limit (see table above)
444 NOBUG_LOG='flag:DEBUG'                        # set the limit of the default target to DEBUG
445 NOBUG_LOG='flag:DEBUG@console@syslog'         # set console and syslog limits for flag to DEBUG
446 NOBUG_LOG='flag:DEBUG,other:TRACE@ringbuffer(file=log.rb)(size=8192)(keep)' # trace 'other' to a persistent ringbuffer
448 There is a predefined flag NOBUG_ON which is always enabled.
450 Example code:
452    1 #include "nobug.h"
453    2 NOBUG_DEFINE_FLAG (test);
454    3
455    4 int
456    5 main()
457    6 {
458    7   NOBUG_INIT_FLAG (test);
459    8
460    9   INFO (test, "Logging enabled");
461   10   INFO (NOBUG_ON, "Always on");
462   11 }
464 test it:
466 $ tcc -DEBUG_ALPHA -run example.c
467 example.c:10: debug: INFO: main: Always on
469 $ NOBUG_LOG=test tcc -DEBUG_ALPHA -run example.c
470 example.c:9: debug: INFO: main: Logging enabled
471 example.c:10: debug: INFO: main: Always on
473 C++ support
475 When used in C++ programms the following additional marocs are available:
477   * NOBUG_CPP_DEFINE_FLAG(name)
478     NOBUG_CPP_DEFINE_FLAG_PARENT(name, parent)
479     NOBUG_CPP_DEFINE_FLAG_LIMIT(name, default)
480     NOBUG_CPP_DEFINE_FLAG_PARENT_LIMIT(name, parent, default)
482 This macros statically initialize the flags at definition time, there is no
483 need to call NOBUG_INIT_FLAG().
485 The Logging Macros
487 These macros log with implicit Log Level, note that there are no more severe
488 levels than LOG_ERROR since these should be handled by Assertions in a
489 debugging library.
491   * ERROR(flag, fmt, ...)
492     ERROR_IF(expr, rflag, fmt, ...)
493       + Application takes a error handling brach
495     WARN(flag, fmt, ...)
496     WARN_IF(expr, flag, fmt, ...)
497       + Rare, handled but unexpected branch
499     INFO(flag, fmt, ...)
500     INFO_IF(expr, flag, fmt, ...)
501       + Message about program progress
503     NOTICE(flag, fmt, ...)
504     NOTICE_IF(expr, flag, fmt, ...)
505       + More detailed
507     TRACE(flag, fmt, ...)
508     TRACE_IF(expr, flag, fmt, ...)
509       + Very fine grained messages
511 Note that TRACE corresponds to LOG_DEBUG, using 'DEBUG' could be ambiguous.
513 There is one generic LOG macro which takes the level explicitly:
515   * LOG(flag, lvl, fmt, ...)
516     LOG_IF(expr, flag, lvl, fmt, ...)
518 Dumping Datastructures
520   * DUMP(flag, type, pointer, depth)
521       + Dump a datastructure
522     DUMP_IF(expr, flag, type, pointer, depth)
523       + Dump datastructure if expr is true
525 How to write DUMP handlers
527 if you have a
529    1 struct STRUCTNAME
530    2 {
531    3   int INTEGER_MEMBER;
532    4   char * STRING_MEMBER;
533    5   struct STRUCTNAME* next;
534    6 }
536 then you define a function like:
538    1 void
539    2 nobug_STRUCTNAME_dump (const struct STRUCTNAME* self,
540    3                        const int depth,
541    4                        const char* file,
542    5                        const int line,
543    6                        const char* func)
544    7 {
545    8   // check for self != NULL and that the depth
546    9   // limit did not exceed in recursive datastructures
547   10   if (self && depth)
548   11   {
549   12     // use DUMP_LOG not LOG to print the data
550   13     DUMP_LOG("STRUCTNAME %p: int is %d, string is %s", self,
551   14                              self->INTEGER_MEMBER,
552   15                              self->STRING_MEMBER);
553   16     // now recurse with decremented depth
554   17     nobug_STRUCTNAME_dump (self->next, depth-1, file, line, func);
555   18   }
556   19 }
558 now you can use the DUMP() macros within the code
560    1 example()
561    2 {
562    3   struct STRUCTNAME foo;
563    4   init(&foo);
564    5   DUMP (my_flag, STRUCTNAME, &foo, 2);
565    6 }
567 Dumping is by default done on level LOG_DEBUG, this can be overridden by
568 defining NOBUG_DUMP_LEVEL to some other level, further DUMP_IF is the only
569 enabled dumping macro for the RELEASE build level.
571 Source Annotations
573 One can tagging features as:
575   * DEPRECATED(...)
576       + Something which shouldn't be used in future.
577     UNIMPLEMENTED(...)
578       + important, not yet finished feature
579     PLANNED(...)
580       + planned for future feature
581     FIXME(...)
582       + known bug to be fixed later
583     TODO(...)
584       + enhancement to be done soon
585     NOTREACHED
586       + used to tag code-path which shall be never executed (defaults in switch
587         statements, else NOTREACHED after series of if's)
589 The advantage of this tagging over plain source comments is that we can take
590 some actions if we run in such a tag at compile or runtime:
592 the action to be taken when such a macro is hit depends on the build level:
594               ALPHA BETA         RELEASE
595 DEPRECATED    log   nothing      wont compile
596 UNIMPLEMENTED abort abort        wont compile
597 FIXME         log   wont compile wont compile
598 TODO          log   log          wont compile
599 PLANNED       log   nothing      nothing
600 NOTREACHED    abort abort        removed
602 Legend:
604   * abort means first log and then abort
605   * log will only log once for each sourceline (not on each hit)
606   * wont compile will abort compilation with a error message
607   * nothing optimized out, sane way
608   * removed optimized out for performance reasons
610 Resource Tracking
612 With little effort, NoBug can watch all kinds of resources a program uses. This
613 becomes useful for resources which are distributed over a multithreaded
614 program. Resource tracking is only active in ALPHA builds and optimized out in
615 BETA and RELEASE builds.
617 Concepts
619 Resources are abstracted, NoBug has little knowledge about the semantics of a
620 resource, it only keeps records of resources and the code using it and ensures
621 basic constraints. Detailed usage checks of resource have to be done with other
622 NoBug facilities.
624 Resources are identified by a arbitrary identifier which is just a pointer and
625 if using threads, NoBug's thread identifier. Additionally a name, the type and
626 the source locations which announced the resource are stored.
628 Code which wants to use a resource calls a enter macro with its own identifier
629 and state, then might alter the state and finally a leave macro when finished
630 with it.
632 When a resource is used one has to pass one of three states:
634   * NOBUG_RESOURCE_WAITING
635       + For resources where acquisition could block (locks) you enter it with a
636         WAITING state and as soon you aacquired it you change the state to one
637         of the following.
638   * NOBUG_RESOURCE_EXCLUSIVE
639       + Acquired the resource exclusively, this means for NoBug that trying to
640         get the resource again with the same identifier would be fatal, other
641         parts of the program could still enter it.
642   * NOBUG_RESOURCE_RECURSIVE
643       + The resource might be entered multiple times from the same identifier,
644         NoBug keeps a reference count and only deletes the record when the
645         resource is left as much times the state was changed to
646         NOBUG_RESOURCE_RECURSIVE
648 Possible state transitions:
650   * [ResourceTr]
652 The macros
654 Resources are accessed through handles, these handles are defined with
656   * RESOURCE_HANDLE(name)
658 This macro takes care that the declaration is optimized out in the same manner
659 the rest of the resource tracker would be disabled. You can still instantiate
660 handles as struct nobug_resource_record* in structures which must have a
661 constant size unconditional of the build level.
663 Resources are published by
665   * RESOURCE_ANNOUNCE(flag, type, name, identifier, handle)
667 Resources must be unique, it is a fatal error when a resource it tried to be
668 announced more than one time.
670   * 'flag' is nobug flag which turns logging on for this macro.
671   * 'type' is a cstring which should denote the domain of the resource,
672     examples are "file" "mutex" "lock" "database" and so on.
673   * 'name' is the actual name of a named resource this is a cstring which
674     together with type forms a unique identifier of the resource. 'type' and
675     'name' must be available through the entire lifetime of the resource, using
676     literal strings is recommended.
677   * 'identifier' is a pointer which should be unique for this resource, any
678     kind of pointer will suffice, it is only used for identification. In
679     multithreaded applications the thread identifier becomes an additional
680     identifier.
681   * 'handle' is a nobug_resource_record* which will be initialized to point to
682     the newly created resource.
684 When a resource becomes unavailable it is removed from the registry by
686   * RESOURCE_FORGET(flag, handle)
688 The resource must still exist and no users must be attached to it, else a fatal
689 error is raised.
691 Code which wants to use a resource attaches to it by
693   * RESOURCE_ENTER(flag, announced, name, identifier, state, handle)
694   * 'flag' is nobug flag which turns logging on for this macro.
695   * 'announced' is the handle set by RESOURCE_ANNOUNCE
696   * 'name' is a free-form identifier
697   * 'identifier' is some pointer which must be unique for the user of the
698     resource (see above)
699   * 'state' is the initial state, one of NOBUG_RESOURCE_WAITING,
700     NOBUG_RESOURCE_EXCLUSIVE or NOBUG_RESOURCE_RECURSIVE
701   * 'handle' is a nobug_resource_record* which will be initialized to the
702     entering node.
704 For some uses one can change the state with
706   * NOBUG_RESOURCE_STATE(flag, entered, state)
707   * 'flag' is nobug flag which turns logging on for this macro.
708   * 'entered' is the handle set by RESOURCE_ENTER
709   * 'state' is the new state Note that only certain state transitions are
710     allowed, see discussion/diagram above
712 When finished with using the resource you disconnect from it either with the
713 handle you initialized when entering it
715   * RESOURCE_LEAVE(flag, handle)
716   * 'flag' is nobug flag which turns logging on for this macro.
717   * 'handle' is the handle you got while entering the resource.
719 or by looking it up in the announced resource by its identifier
721   * RESOURCE_LEAVE_LOOKUP(flag, resource, identifier)
722   * 'flag' is nobug flag which turns logging on for this macro.
723   * 'resource' is the handle you got from announcing the resource.
724   * 'identifier' is the pointer you gave it when creating it
726 Resources keep track of the thread which used them, you cant ANNOUNCE/FORGET
727 ENTER/LEAVE the same handle from different threads.
729 Just a simple example:
731    1 NOBUG_DEFINE_FLAG_LIMIT(test, LOG_DEBUG);
732    2
733    3 void example()
734    4 {
735    5
736    6   // define a mutex and announce it
737    7   pthread_mutex_t my_mutex = PTHREAD_MUTEX_INITIALIZER;
738    8   RESOURCE_HANDLE(resource)
739    9   // 'example' is just a pointer to this function which suffices as unique id
740   10   RESOURCE_ANNOUNCE(test, "mutex", "my_mutex", example, resource);
741   11
742   12   // the following would be actually done in a different thread in a real program
743   13   RESOURCE_HANDLE(test, enter);                            // define a handle
744   14   RESOURCE_ENTER_NAME(test, resource, "example", &enter, NOBUG_RESOURCE_WAITING, enter);
745   15                                                            // announce that we want to use the resource
746   16                                                            // &enter also suffices as unique pointer
747   17   pthread_mutex_lock (&my_mutex);                          // this might block
748   18   RESOURCE_STATE(test, enter, NOBUG_RESOURCE_EXCLUSIVE);   // we got it, now announce that
749   19
750   20   // program does something useful here
751   21
752   22
753   23   pthread_mutex_lock (&my_mutex);                          // and instantly unlock
754   24   RESOURCE_LEAVE(test, enter);                             // we don't need it anymore
755   25
756   26   // back in the main thread
757   27   RESOURCE_FORGET(test, resource);                         // remove the resource from the public registry
758   28 }
760 Deadlock Detection
762 The Resource Tracker is able to detect potential deadlocks. This is done by
763 learning the relations between locks (precedence). A possible deadlock results
764 in a log message and a fatal abort. Note that only waiting on resources can
765 lead to a deadlock. Deadlock detection is implemented in the Resource Tracker
766 and active in ALPHA builds.
768 Logging Control
770 Unless the user defines NOBUG_RESOURCE_LOGGING to 0 each of the above macros
771 will emit a log message at NOBUG_RESOURCE_LOG_LEVEL which defaults to
772 LOG_DEBUG.
774 Notes
776 The Resource Tracker is neither bullet-proof nor exact. There are small race
777 conditions in the time we announce/forget/enter/remove resources and doing the
778 actual call to a resource. These race conditions affect the reporting exactness
779 and are a design decision, for there is no danger for practical use.
781 More important is that the Resource Tracker relies on that announce/forget and
782 enter/leave are properly paired. The programmer should ensure that this is done
783 right, else it will become unusable. This will be addressed in future NoBug
784 versions.
786 The underlying resource-tracking library may report errors, all these errors
787 are fatal for NoBug and trigger an abort(). When such an error occurs the
788 Resource Tracker is left in a locked state, which is harmless and intended for
789 generating reports prior the abort.
791 Multithreading
793 It is important that NoBug protects certain operations with locks in
794 multithreaded programs. You have to ensure that 'HAVE_PTHREAD_H' is defined by
795 the configuration system and use the 'libnobugmt.a' library for linking. It is
796 particular important that libraries using NoBug are compiled with
797 'HAVE_PTHREAD_H' enabled when they are intended to be used in multithreaded
798 programs.
800 When Multithreading is used, log messages contain a identifier of the
801 originating thread. This identifier should be set by
803   * NOBUG_THREAD_ID_SET(name)
805 right after thread creation. name is a string describing the purpose of the
806 thread. Nobug will assemble a unique identifier by appending a underscore and a
807 number to name, for example NOBUG_THREAD_ID_SET("gui") will result in a
808 identifier like "gui_5". When you don't set a thread identifier, then NoBug
809 assigns one automatically with the name 'thread' preprended if needed. Thread
810 identifiers are immutable once set.
812 For querying the thread identifier you use
814   * NOBUG_THREAD_ID_GET
816 which will return a const char* to the thread id in multithreaded programs and
817 a pointer to a literal "" in singlethreaded programs.
819 Tool Macros
821   * BACKTRACE(...)
822       + Log a stacktrace
823     ABORT
824       + just calls abort()
826 Best Practices
828 <!> this section is very work in progress
830 Workflow
832  1. Development
833       + Write a testsuite, build your program with -O0 -g -DEBUG_ALPHA and run
834         the testsuite under valgrind control. Hack until the program fits the
835         requirements defined by the testsuite.
836  2. Beta Test
837       + Build with desired optimization level and -g -DEBUG_BETA and give the
838         program to your beta testers.
839  3. Release
840       + Just build it with optimization and without -g -DEBUG_*
842 What and when to check
844   * Add REQUIRE checks on your interfaces (incoming parameters). Especially if
845     a argument might not cover the whole range of the underlying type.
846   * Don't waste your and your CPU's time with unnecessary checks. The testsuite
847     should validate your program. NoBug aids in debugging. You can add
848     Postconditions (ENSURE) and Invariants when you have a bug somewhere and
849     want to nail it down.
850   * Added checks don't need to be removed.
851   * When you use the CHECKED/UNCHECKED features then don't forget C scoping
852     rules, tag things as CHECKED from the leaves to the root.
854 Tips & Tricks
856   * TRACE(flagname) or TRACE_DBG(flagname) at the begin of every nontrivial
857     function will easily log the progress of your application.
858   * Trying a RELEASE build will abort on certain conditions (known BUG, TODO's,
859     UNCHECKED code), you can use this to find these spots.
861 This Documentation is maintained at:
863   * http://www.pipapo.org/pipawiki/NoBug/Documentation
865 NoBug/Documentation (last edited 2008-04-02 10:19:58 by 193)