1\input texinfo @c -*-texinfo-*- 2@include version.texi 3@settitle Nana: improved support for assertions and logging in C and C++ 4@setfilename nana.info 5@c send all the index entries to the concept index 6@syncodeindex fn cp 7@syncodeindex vr cp 8@syncodeindex ky cp 9@syncodeindex pg cp 10@syncodeindex tp cp 11 12@iftex 13@c Select A4 Paper (remove for imperialist letter paper) 14@afourpaper 15@end iftex 16 17@ifinfo 18@format 19START-INFO-DIR-ENTRY 20* Nana: (nana). The Nana library (assertions, logging, forall,etc) 21END-INFO-DIR-ENTRY 22@end format 23@end ifinfo 24 25@ifinfo 26This file documents the features and implementation of the GNU Nana library. 27 28Copyright (C) 1996, 1997, 1998, 1999 P.J.Maker, Quoll Systems Pty Ltd. 29 30Permission is granted to make and distribute verbatim copies of 31this manual provided the copyright notice and this permission notice 32are preserved on all copies. 33 34@ignore 35Permission is granted to process this file through @TeX{} and print the 36results, provided the printed document carries copying permission 37notice identical to this one except for the removal of this paragraph 38(this paragraph not being relevant to the printed manual). 39 40@end ignore 41@end ifinfo 42 43@iftex 44@finalout 45@c @smallbook 46@c @cropmarks 47@end iftex 48 49@setchapternewpage odd 50 51@titlepage 52@title Nana 53@subtitle Improved support for assertions and logging in C and C++ 54@subtitle last updated @value{UPDATED} for version @value{VERSION} 55@author P.J.Maker (pjm@@gnu.org) 56@page 57@vskip 0pt plus 1filll 58Copyright @copyright{} 1996, 1997, 1998, 1999 P.J.Maker, Quoll Systems Pty Ltd. 59 60Permission is granted to make and distribute verbatim copies of 61this manual provided the copyright notice and this permission notice 62are preserved on all copies. 63@end titlepage 64 65@ifinfo 66@node Top, Introduction, (dir), (dir) 67 68This manual documents how to install and use the Nana library which 69provides improved support for assertion checking and logging in C and C++. 70 71@end ifinfo 72 73@menu 74* Introduction:: Overview 75* Installation:: Installing nana 76* Invoking:: Compiling, linking and generating gdb commands 77* Interface:: Interface to nana library functions 78* Shortform:: Nana shortform generation 79* Performance:: 80* Tracing:: 81* Usage:: Some examples 82* FAQ:: Frequently Asked Questions 83* Future:: Future work/projects 84* Index:: 85 86@detailmenu 87 --- The Detailed Node Listing --- 88 89Introduction 90 91* Related work:: 92* Assert:: 93* Scope:: 94 95Installing the Nana library 96 97* Required Software:: 98* Optional Software :: 99* Configure:: 100* Variables:: 101* Supported Platforms:: 102* Supported Debuggers:: 103* Known Problems:: 104* Bug Reports:: 105* New Versions:: 106 107Interface 108 109* nana.h:: 110* WITHOUT_NANA:: 111* I.h:: 112* DI.h:: 113* L.h:: 114* L_buffer.h:: 115* L_times.h:: 116* DL.h:: 117* GDB.h:: 118* Q.h:: 119* Qstl.h:: 120* now.h:: 121* cycles.h:: 122* eiffel.h:: 123* assert.h:: 124* calls.h:: 125 126cycles.h: access to CPU cycle counting registers. 127 128* RDTSC:: 129 130eiffel.h: eiffel type assertions 131 132* EIFFEL_CHECK:: 133* DOEND:: 134* REQUIRE...:: 135 136Tracing tools 137 138* Statement:: 139* Library:: 140 141Using Nana 142 143* Simplest:: 144* Syslog:: 145* GNU:: 146* Embedded Systems:: 147* Realtime:: 148* A database:: 149* Visualisation:: 150 151@end detailmenu 152@end menu 153 154@node Introduction, Installation, Top, Top 155@chapter Introduction 156 157Nana is a library that provides support for assertion checking 158and logging in a space and time efficient manner. The aim is to put 159common good practice@footnote{Which is unfortunately quite uncommon in 160the authors experience.} into a library that can be reused rather than 161writing this stuff every time you begin a new project. 162 163In addition assertion checking and logging code can be implemented using 164a debugger rather than as inline code with a large saving in code space. 165 166Nana aims to solve the following problems: 167 168@enumerate 169@item Avoid the two executables problem (one with asserts in and another 170without any). 171 172The code space and time costs of having assertion checking and detailed 173logging code in a program can be high. Normally people construct two 174versions of the program, one with checking code for testing and one 175without checking code for production use. 176 177With nana one version of the executable can be 178built for both testing and release since debugger based checking has 179negligible space and time impact. 180 181@item Configurable: the nana library is designed to be reconfigured by 182the user according to their needs. For example we can: 183@itemize @bullet 184@item Modify the behavior on assertion failure, e.g. to attempt 185a system restart rather than just shutting down. 186@item Selectively enable and disable assertion checking and 187logging both at compile and run time. 188@item Send the logging information off to various locations, e.g. 189@itemize @minus 190@item Users terminal 191@item A file for later checking. 192@item Another process, e.g. a plotting program or a 193program that verifies that the system is behaving itself. 194@item A circular buffer in memory. 195 196This is an old embedded systems trick and is very useful 197for production systems. The time cost of logging into 198memory is not large and when your production system in 199the field has problems you can then see what was happening 200in the minutes before its unfortunate demise rather than 201asking some user what was happening before it died. 202@end itemize 203@end itemize 204 205@item Time and space efficient. 206 207For example the obvious @samp{assert.h} implementation uses 53 bytes for 208@samp{assert(i>=0)} on a i386. The nana version using the i386 @samp{stp} 209instruction on assert fail uses 10 bytes. If you're willing to accept the 210time penalty this can be reduced to 0 or 1 byte by using debugger based 211assertions. 212 213@item Support for formal methods. 214 215@itemize @bullet 216@item Before and after state (e.g. x,x' in the Z notation). 217 218Specifications are often written in terms of the state of 219variables before and after an operation. For example the 220@samp{isempty} operation on a stack should leave the stack 221unchanged. To verify this in nana we could use: 222 223@example 224bool isempty()@{ /* true iff stack is empty */ 225 DS($s = s); /* copy s into $s in the debugger */ 226 ...; /* code to do the operation */ 227 DI($s == s); /* verify that s hasn't been changed */ 228@} 229@end example 230 231These @samp{$..} variables are called convenience variables 232and are implemented by gdb. They have a global scope and are 233dynamically typed and initialised automatically to 0. 234 235In addition a C only version of before and after state is provided. 236For example: 237 238@example 239bool isempty() @{ /* true iff stack is empty */ 240 ID(int olds); /* declare variable to hold old value */ 241 IS(olds = s); /* copy s into $s in the debugger */ 242 ...; /* code to do the operation */ 243 I(olds == s); /* verify that s hasn't been changed */ 244@} 245@end example 246 247@item Support for Predicate Calculus. 248 249Nana provides some support for universal (forall) and 250existential (exists one or more) quantification. For example to specify 251that the string v contains only lower case letters we could use: 252 253@example 254 I(A(char *p = v, *p != '\0', p++, islower(*p))); 255@end example 256 257These macros can be nested and used as normal boolean values in 258control constructs as well as assertions. Unfortunately they 259depend on the GNU CC statement value extensions and so are not 260portable. The following macros are defined in @samp{Q.h}: 261 262@ftable @code 263@item A 264For all values the expression must be true. 265@item E 266There exists one or more values for which the expression is 267true. 268@item E1 269There exists a single value for which the expression is true. 270@item C 271Returns the number of times the expression is true. 272@item S 273Returns the sum of the expressions. 274@item P 275Returns the product of the expressions. 276@end ftable 277 278@item A C/C++ based shortform generator similar to Eiffel which 279can produce a HTML summary of your code. 280 281The shortform of a program consists of the function headers 282together with their preconditions@footnote{Precondition: 283a boolean expression which must be true if the operation is to 284succeed. For example the @samp{sort(int *v, int n)} might have 285have precondition that @samp{v != NULL && n >= 0}.} 286and postconditions@footnote{Postcondition: a boolean expression that 287must be true if the operation is correct (and the precondition 288was true on entry).} 289 290@item Performance measurement. 291 292A small package which measures the time and space overhead of 293code fragments is provided. This is used to analyse the space/time 294requirements of the nana library and could be used for other types 295of measurement. 296 297@item Verifying timing. 298 299As well as using nana to verify timings with assertions using a 300hardware supported timer you can also a simulator (e.g. the 301PSIM power pc simulator by Cagney) with gdb. These simulators can 302model time and provide a register called @samp{$cycles} which 303represents the current cycle count of the program. This can be 304used to check that timing constraints are being meet. 305 306@example 307void process_events() @{ 308 for(;;)@{ 309 DS($start = $cycles); 310 switch(get_event())@{ 311 case TOO_HOT: 312 ...; 313 DI($cycles - $start <= 120); 314 break; 315 case TOO_COLD: 316 ...; 317 DI($cycles - $start <= 240); 318 break; 319 @} 320 @} 321@} 322@end example 323@end itemize 324@end enumerate 325 326The intended audience for Nana includes: 327 328@itemize @bullet 329@item Software Engineers. 330@item Formal methods community. 331@item Real time programmers. 332@item System testers. 333@item People teaching programming. 334@end itemize 335 336@menu 337* Related work:: 338* Assert:: 339* Scope:: 340@end menu 341 342@node Related work, Assert, Introduction, Introduction 343@section Related work 344The Nana project was inspired by some other projects, in particular: 345 346@itemize @bullet 347@item Anna - Anna stands for "Annotated Ada" where the programmer inserts 348various assertions into the code which can be automatically validated. 349To quote from the WWW Virtual Library entry on Anna: 350 351@quotation 352Anna is a language for formally specifying the intended behaviour of Ada 353programs. It extends Ada with various different kinds of specification 354constructs from ones as simple as assertions, to as complex as algebraic 355specifications. A tool set has been implemented at Stanford for 356Anna, including: 357 358@enumerate 359@item standard DIANA extension packages, parsers, pretty-printers; 360@item a semantic checker; 361@item a specification analyser; 362@item an annotation transformer; and 363@item a special debugger that allows program debugging based on formal specifications 364@end enumerate 365 366All tools have been developed in Ada and are therefore extremely 367portable. Anna has thus been ported to many platforms. For more 368information send e-mail to "anna-request@@anna.stanford.edu". Before 369down loading the huge Anna release, you may wish to copy and read some 370Anna LaTeX reports. 371 372@end quotation 373 374Anna is available from: @code{ftp://anna.stanford.edu/pub/anna} 375 376@item Eiffel - the Eiffel programming language provides support in the language 377flexible assertion checking. To quote from the Eiffel page in WWW 378Virtual library: 379 380@quotation 381 382Eiffel is a pure object-oriented language featuring multiple 383inheritance, polymorphism, static typing and dynamic binding, genericity 384(constrained and unconstrained), a disciplined exception mechanism, 385systematic use of assertions to promote programming by contract, and 386deferred classes for high-level design and analysis. 387@end quotation 388 389@item APP - Annotation PreProcessor. 390The APP was written by David S. Rosenblum and provides assertion checking 391functions for C and C++. It is implemented using a preprocessor wrapper 392around the C preprocessor and supports quantifiers and before/after state. 393 394See "A Practical Approach to Programming with Assertions" in 395Vol 21, No. 1, January 1995 of IEEE Transactions on Software Engineering 396for an interesting paper describing APP@. Unfortunately the APP tool 397doesn't seem to be freely available (I'm willing to be corrected on this). 398Note that any similarity between my examples and David's are due 399to morphic resonance. 400 401@item ADL - the Assertion Definition Language. 402 403To quote from @code{http://www.sunlabs.com/research/adl/}: 404 405@quotation 406ADL (Assertion Definition Language) is a specification 407language for programming interfaces. It can be used to describe the 408programmer's interface to any C-callable function, library or system 409call. 410 411The Practical Specification Language. 412 413ADL is the world's most practical specification language because: 414 415@itemize @bullet 416@item Even partial specifications are useful 417@item Test programs can be automatically generated from ADL specifications 418@item Specifications are external to the implementation of the interface, so that they are vendor-independent. 419@end itemize 420 421An Automated Test Generator. 422 423An ADL specification is not just a paper document. It can be compiled 424by ADLT (the ADL translator). ADLT generates: 425 426@itemize @bullet 427@item Header files, that can be used in an implementation 428@item Test programs, that ensure that any implementation meets the 429specification 430@item Natural-language documentation, derived directly from the specification 431@end itemize 432 433ADLT can be used: 434 435As a test generator, to create tests for existing software or for 436existing standards As a development tool, to ensure that 437documentation, software, and tests are aligned, and to 438enable concurrent work on all three aspects of software production. 439@end quotation 440@end itemize 441 442Nana is essentially a poor mans implementation of some of these ideas 443which works for C and C++. Ideally in the best of all possible worlds 444you might want to look at Eiffel or in the military world Ada and Anna. 445If you use TCL/TK you might also be interested in Jon Cook's 446@samp{AsserTCL} package. 447 448@node Assert, Scope, Related work, Introduction 449@section Assert.h considered harmful 450Most C programmers become familiar with assertions from the the 451@code{assert.h} header. As such its a very good thing and has a nice 452simple implementation. However it is also inefficient and leads some 453people to the conclusion that assertion checking is an expensive luxury. 454 455The implementation of @code{assert.h} as distributed with @code{gcc} 456looks like the following (after a bit of editing): 457 458@example 459# ifndef NDEBUG 460# define _assert(ex) @{if (!(ex)) \ 461 @{(void)fprintf(stderr, \ 462 "Assertion failed: file \"%s\", line %d\n", \ 463 __FILE__, __LINE__);exit(1);@}@} 464# define assert(ex) _assert(ex) 465# else 466# define _assert(ex) 467# define assert(ex) 468# endif 469@end example 470 471There are are two main problems with this: 472 473@enumerate 474@item Code space overhead: each call to @samp{assert} generates 2 function 475calls with 4 and 1 arguments plus strings for error messages. 476If @code{assert.h} had library code support we could make the implementation 477much more space efficient, e.g. by calling a single function on error 478detection. 479@item The default behaviour simply prints a message and dies, ideally 480you like to be able to use a debugger to determine why the assertion 481failed. Even if you run this under the debugger you can't observe the 482failures of variables are an assert failure because the process exits 483rather than aborting back to the debugger. 484@end enumerate 485 486Of course everyone merely rewrites their own @samp{assert} macro so 487these are not significant objections. The only problem is if the author 488uses the libraries without modification. 489 490@node Scope, , Assert, Introduction 491@section Scope of this document 492This document aims to both describe the library and provide a tutorial 493in its use. Further work is required, particularly on the tutorial sections. 494If anyone has any suggestions please send them to me. 495 496@node Installation, Invoking, Introduction, Top 497@chapter Installing the Nana library 498Nana uses the normal GNU install method in the same way as @samp{gcc} 499and @samp{gdb}. To install nana in the default location 500@samp{/usr/local/@{bin,lib,include@}} you would use: 501 502@example 503% gzcat nana-1.10.tar.gz | tar xvf - 504% cd nana-1.10 505% ./configure 506% make 507% make install 508% make check 509% make check-mail 510% make subscribe 511@end example 512 513If you wish to produce space and time efficient code then replace 514the @samp{./configure} with: 515 516@example 517% I_DEFAULT=fast ./configure 518@end example 519 520If you are using a Pentium compatiable CPU which supports the 521@samp{RDTSC} instruction you may wish to enable cycle level timing 522in @samp{cycles.h} by using: 523 524@example 525% ./configure --enable-rdtsc 526@end example 527 528The @var{check-mail} and @var{subscribe} targets both send e-mail. If 529you need to change the mailer used try something like: 530 531@example 532% make MAILER=elm subscribe 533@end example 534 535@strong{Note:} we need to install nana before running the @samp{make check} 536target. The @samp{check-mail} target sends the test report 537via e-mail to the @samp{gnuware@@cs.ntu.edu.au}. 538 539Of course things are never that simple. If you want to install Nana in 540a different location or change the behaviour on error detection see @ref{Configure}. 541 542Each of the sub-directories nana can be compiled and installed 543separately, e.g. if you don't need the documentation you can just 544compile and install from the @samp{src} sub-directory after doing the 545configure statement. 546 547Note that some of the subdirectories contain code that you may 548wish to install, improve or inspect. In particular: 549 550@itemize @bullet 551@item @samp{emacs} -- a protype emacs mode for browsing log files. 552@item @samp{examples} -- some small examples. 553@item @samp{gdb} -- some tools for use with gdb, in particular a statement 554 level trace utility and some gdb patches. 555@item @samp{perf} -- a tool for measuring space/time of code fragments. 556@item @samp{shortform} -- a shortform generator which produces a HTML 557summary of your codes interface. 558@item @samp{tcl} -- a prototype TCL driver. We actually have a few more 559TCL tools in the works so if you're interested contact the author. 560@end itemize 561 562@menu 563* Required Software:: 564* Optional Software :: 565* Configure:: 566* Variables:: 567* Supported Platforms:: 568* Supported Debuggers:: 569* Known Problems:: 570* Bug Reports:: 571* New Versions:: 572@end menu 573 574@node Required Software, Optional Software , Installation, Installation 575@section Required Software 576The following software is possibly required to run nana. 577 578@ftable @code 579@item gcc-2.7.2 580Nana makes use of two GNU extensions in its library so you really should 581be using @samp{gcc}. Some of the code can be used with any C compiler, 582though it may not be worth the bother. The dependencies on gcc are in 583@samp{Q.h} which uses the statement value extension and in @samp{L.h} 584which uses the variable number of arguments extension to @samp{cpp}. 585@item gdb-4.16+ 586A recent version of @samp{gdb} is worthwhile, some early 4.?? versions 587had problems setting a large number of breakpoints. Note that 588@samp{gdb-4.17} is available and has a few improvement which are useful 589for some parts of this package including the tools in @samp{gdb}. 590@item gmake 591The @samp{configure} script and @samp{Makefiles} are generated using the 592@samp{automake} and @samp{autoconf} programs. They should be reasonably 593portable but if you have problems try using GNU make. For example on 594some old DEC boxes we have had strange behaviour using the system make. 595@end ftable 596 597For a listing of porting results including software versions see: 598 599@center @samp{http://www.cs.ntu.edu.au/homepages/pjm/nana-bug/} 600 601@node Optional Software , Configure, Required Software, Installation 602@section Optional Software 603 604In addition to the required software you might also be interested 605in: 606 607@itemize @bullet 608@item @samp{http://www.cs.tu-bs.de/softech/ddd/} -- a smart frontend for 609gdb which can display dynamic data structures such as linked lists, etc. 610@item @samp{ftp://ftp.ci.com.au/pub/psim/} -- a cycle level simulator 611for the PowerPC@. A fine piece of work. 612@end itemize 613 614@node Configure, Variables, Optional Software , Installation 615@comment node-name, next, previous, up 616@section Configure 617Nana uses a standard GNU @code{autoconf} generated @code{configure} 618script. The @code{configure} script checks the setup on your machine and 619then generates the appropriate Makefiles. Some of the things checked by 620configure include: 621 622@enumerate 623@item Which compiler, compiler flags and libraries to use, e.g. you 624might need to include a @code{-lposix} flag to the linker to build programs 625on your machine. 626@item Which header (.h) files are available on this machine, e.g. is 627 @code{unistd.h} available on this machine. 628@item Where to install programs, header file, man pages, etc. 629@end enumerate 630 631In addition @samp{configure} uses the host architecture and operating system 632to generate the @samp{nana-config.h} file. This file contains some macro 633definitions which define how nana works on particular operating systems 634and hardware architectures. 635 636For example on @samp{i386} machines we would use the @samp{asm("hlt")} 637instruction whenever an assertion fails, on a @samp{sparc} we would use 638@samp{asm("unimp")}. Otherwise we would default to a plain C call to 639@samp{abort()} If @samp{configure} does not recognise your machine it 640uses plain C code. 641 642You may wish to change these defaults on installation, one method is to edit 643a local copy of the @samp{nana-config.h} file. Alternately you can define 644the code yourself in the call to @samp{configure}. For example 645to redefine the action we take when an error is detected by the @code{I} 646macro we can use: 647 648@example 649I_DEFAULT_HANDLER="restart_system()" ./configure 650@end example 651 652As well as simple calls to routines various other bits of information 653are passed off to the @samp{I_DEFAULT_HANDLER} such as the expression 654that failure and a failure code. For example: 655 656@example 657% I_DEFAULT_HANDLER="restart(line,file,param)" ./configure 658@end example 659 660The default for @samp{I_DEFAULT_HANDLER} calls a function which prints a 661message and then dumps core. Different behaviour on failure can be 662organised by setting the @samp{I_DEFAULT} to @samp{fast}, i.e. plain 663core dump or @samp{verbose} which prints an error messsage and then does 664the core dump. 665 666@example 667% I_DEFAULT=fast ./configure 668@end example 669 670For nana the following examples may be useful: 671 672@enumerate 673@item @code{./configure} 674 675Accept the default values for everything. In particular the files will 676be installed in: 677 678 679@center @samp{/usr/local/@{bin,include,lib,man,info@}} 680 681@item @code{./configure --prefix=~project/tools} 682 683Install the files into: 684 685@center @samp{~project/tools/@{bin,include,lib,man,info@}} 686 687@item @code{./configure --bindir=~project/bin --libdir=~/project/lib \@* 688--includedir=~/project/headers --infodir=/usr/local/info \@* 689--mandir=~/project/doc} 690 691The install directory for program (@samp{bin}), etc can all be set with 692command line arguments to @samp{configure}. 693 694@item @code{CC=xacc LIBS=-lposix ./configure sun3} 695 696If the defaults chosen by @samp{configure} are not correct you can 697override them by setting variables such as @code{CC} before calling 698 @samp{configure}. The @samp{sun3} argument is used to identify the 699machine we are running on and may be necessary on some machines. 700 701@item @code{./configure --help} 702 703And of course when in doubt ask for help. 704@end enumerate 705 706For even more details see the file @samp{INSTALL.con} which contains the 707generic instructions for use with @samp{autoconf} generated 708@samp{configure} scripts. 709 710@node Variables, Supported Platforms, Configure, Installation 711@section Variables for ./configure 712The configure program uses the following shell variables to change 713various defaults. Another method is simply to edit the 714@samp{nana-config.h} file. Most of these values should be auto detected, 715so you can ignore this section until your need to save a few 716bytes of store by using @samp{asm("hlt")} instead of a call to 717@samp{abort()}. 718 719@ftable @code 720@item DI_MAKE_VALID_BREAKPOINT 721This text is inserted when the @samp{DI.h} library needs to set a 722breakpoint in the generated code. It should ideally update all 723variables which being kept in registers etc so that gdb gets the 724correct values for each variable. 725 726Possible values include: 727 728@enumerate 729@item @samp{asm("nop")} -- a single @samp{nop} instruction to set the 730breakpoint at. 731 732This is the default. 733 734@item @samp{_vi = 0} -- where @samp{_vi} is a global volatile int. 735@item @samp{_vi = (exprn)} -- where @var{exprn} is the expression 736we are checking for this assertion. 737@item @samp{/* nothing */} -- nothing at all, this means the breakpoint 738will be set at the start of the next statement which works most of the 739time. However for some examples this will do the wrong thing. 740@end enumerate 741@item DL_MAKE_VALID_BREAKPOINT 742Used for the same purpose as @samp{DI_MAKE_VALID_BREAKPOINT} for 743@samp{DL.h}. It also defaults to @samp{asm("nop")}. 744@item I_DEFAULT_HANDLER 745The code called when @samp{I.h} detects an error. 746@ftable @code 747@item asm("hlt") 748Some machines use a @samp{hlt} instruction. 749@item asm("unimp") 750And other machines use a @samp{unimp} instruction. 751@item abort() 752Or we could use a call to @samp{abort} which is at least standard C@. On 753some machines this is significantly larger than a single @samp{hlt} 754instruction. 755@item restart() 756Or a call to a function which attempts to restart the system. 757@end ftable 758@item ALWAYS_INCLUDE_MALLOC 759This is a dodgey for some versions of Linux which don't seem to include 760@samp{malloc} when you include @samp{stdio.h} and use @samp{print}. This 761causes problems for @samp{gdb} since it uses @samp{malloc} in the 762executable to implement parts of its functionality. 763 764This kludge should be removed! 765@item GDB 766This is the pathname of the version of GDB you wish to use. 767For example on my FreeBSD box we have gdb-4.16 installed in @samp{/usr/bin} 768and gdb-4.17 in @samp{/usr/local/bin/} to optimise confusion. If you 769wish nana to use 4.17 try something like: 770 771@example 772GDB=/usr/local/bin/gdb ./configure 773@end example 774@end ftable 775 776@node Supported Platforms, Supported Debuggers, Variables, Installation 777@comment node-name, next, previous, up 778@section Supported Platforms 779Nana has been tested on the following platforms: 780 781@enumerate 782@item i386-unknown-linux, gcc-2.7.0, gdb-4.16 783@item sparc-sun-sunos4.1.4, gcc-2.7.2.f.1, gdb-4.16 784@item sparc-sun-solaris2.3, gcc-2.7.2, gdb-4.16 785@item alpha-dec-osf3.2, gcc-2.7.2, gdb-4.16 786@item mips-sgi-irix5.3, gcc-2.7.0, gdb-4.16 787@item powerpc-ibm-aix3.2.5, gcc-2.6.3, gdb-4.16 788@end enumerate 789 790The @samp{alpha-dec-osf3.2}, @samp{mips-sgi-irix5.3} and 791@samp{powerpc-ibm-aix3.2.5} implementations have problems when you 792compile with @samp{-O2} or @samp{-O3} optimisation. This causes some 793errors in the the debugger based assertion and logging code since 794variables can be removed or changed by optimisation. At @samp{-O} 795everything passes. Regardless of optimisation the C based checking code 796passes all tests on these platforms. 797 798If you use nana on a new platform please send the report file 799to me via the @samp{make check-mail} 800command. A machine generated list of this information is available 801at: 802 803@center @samp{http://www.cs.ntu.edu.au/homepages/gnuware/nana} 804 805(Warning this page is out of date and may be fixed shortly) 806 807@node Supported Debuggers, Known Problems, Supported Platforms, Installation 808@comment node-name, next, previous, up 809@section Supported Debuggers 810 811Currently Nana works with the GNU GDB debugger which is available on a 812wide range of platforms including embedded systems and even provides 813support for remote debugging. 814Porting to any reasonable debugger with conditional 815breakpoints and commands is not very difficult. 816 817As an example of an unreasonable debugger, Nana has been ported to 818work with the Microsoft CodeView debugger. The port is small (60 lines of 819code) but suffers from a problem with variable scoping in CodeView. If 820a breakpoint is set at a point in the code the expressions are not 821evaluated from that particular scope. For example setting a breakpoint 822in the function @code{f} cannot access a variable local to @code{f} 823directly. CodeView has a unique (expletive deleted) scope operator 824which you must use to set the scope @samp{@{...@}}. This makes the 825interface somewhat less than beautiful. 826 827Another good thing about CodeView is to try a debug command which prints a 828message which contains a single open @samp{@{}. This of course causes it 829to hang and was the main problem during the porting to CodeView which 830took a whole day.@footnote{And about 60 reset cycles where the machine 831went off into hyperspace.} 832 833If anyone is interested I may release the CodeView implementation, 834please contact me if you are interested. Of course a better bet is probably 835to move to the @samp{gdbserver} system. I think @samp{gdb} has been released 836as a native even for some Microsoft operating systems. 837 838Other debuggers like DBX don't seem to be worth the trouble since gdb 839works on those machines. A redesign of the nana internals may also be useful 840if we decide portability between debuggers is actually useful. 841 842@node Known Problems, Bug Reports, Supported Debuggers, Installation 843@comment node-name, next, previous, up 844@section Known Problems 845Nana has the following known features (or perhaps problems): 846 847@enumerate 848@item Nana macros which use the debugger 849such as @code{DI} or @code{DL} should be on lines by themselves. If you 850mix code and nana macros on the same line you will get errors, e.g: 851 852@example 853main()@{ 854 int x; 855 x = 5; x--; DI(x == 4); 856@} 857@end example 858 859This doesn't work since breakpoints are set at line boundaries rather 860than statement ones. Of course anyone who writes code like this deserves 861whatever happens to them. 862 863@item Optimisation can remove variables so that debugger based 864assertions (@samp{DI.h}) do not work correctly. As usual the 865interaction between the debugger and the compiler is rather 866complicated. This may not be a problem if the appropriate compile-time 867flags are selected, e.g. @samp{-O0 and -O1} work on most platforms. 868 869@item The @samp{Q.h} macros depend on the statement value extension to 870GNU CC so if you wish to use them you must use GCC@. This can be fixed 871for C++ in a possibly useful manner, I can't see any solution for C@. 872 873@item The logging macros depend on the Var Args extension provided by the 874GNU C Preprocessor.@footnote{This allows a variable number of arguments to 875C preprocessor macros.} We could (probably will) implement a fix for this 876based on the tricks in the C FAQ@. Unfortunately these tricks are not pretty. 877For now interested users could simply replace their CPP with the GNU CPP 878if they wished to stay with non-standard compilers. 879 880@item The @samp{Q.h} macros do not work in the debugger since @samp{gdb} 881does support the statement expression extension. 882 883@item Multiline expressions do not work as expected in the debugger since 884you need to use a blackslash as an escape at the end of the line. 885For example: 886 887@example 888 DI(x + 889 10 > 30); 890@end example 891A few backslashes may solve this particular problem. 892 893@item Problems with the @samp{configure} script. 894 895The @samp{configure} script automatically detects the target operating 896system and architecture and then generates @samp{nana-config.h}. If the 897options selected in @samp{nana-config.h} are incorrect they can be 898edited by hand and installed in the usual include directory. The easiest 899method is simply to delete all macros in @samp{nana-config.h} since the 900system defaults to more portable (and less efficient) 901implementations. If you wish to do this from the configure script you 902can try giving a unsupported machine type, e.g. 903 904@example 905% ./configure pdp11-dec-ultrix 906@end example 907 908@item Some users have reported problems with the @code{configure} 909script detecting @code{vsnprintf}. If @code{configure} doesn't find it 910and it does exist then simply define it in @samp{nana-config.h} as per 911the previous question. 912 913If @code{vsnprintf} really doesn't exist then get a new C library, 914possibly the GNU libc. 915 916@item The use of @code{vsprintf} opens a security hole since no 917bounds checking is done by it. Nana attempts to use @code{vsnprintf} 918which is safe when it exists but it will resort to @code{vsprintf} 919if it can't find @code{vsnprintf}. All careful people should make 920sure that they have a library with @code{vsnprintf}. 921 922@item @code{Qstl.h} doesn't work since the STL library has not 923 been installed along with C++. This can of course be fixed by installing 924 STL@. See: 925 926@center @samp{http://www.stl.org} 927 928@item @code{STL} header file errors due to nana. 929 930The C++ @code{STL} header files for version 3.0 at least must 931be included before the @code{Q.h} file. 932 933The problem is caused by the STL files using @code{S} as a template 934argument. Of course @code{Q.h} uses @code{S} for summing a 935series. As usual namespace pollution strikes again. 936 937(Thanks to Han Holl for this particular problem). 938 939@item If you try to use the debugger based macros 940such as @code{DI.h} or @code{DL.h} on code that has not 941been compiled with @code{-g} then misery follows. 942 943(Thanks to Eugen Dedu for this one) 944@end enumerate 945 946@node Bug Reports, New Versions, Known Problems, Installation 947@comment node-name, next, previous, up 948@section Bug Reports 949 950If you think you have found a bug in the Nana library, please 951investigate it and report it. 952 953@itemize @bullet 954@item Please make sure that the bug is really in the Nana library. 955@item You have to send us a test case that makes it possible for us to 956reproduce the bug. 957@item You also have to explain what is wrong; if you get a crash, or if the 958results printed are not good and in that case, in what way. 959Make sure that the bug report includes all information you would 960need to fix this kind of bug for someone else. 961@end itemize 962 963If your bug report is good, we will do our best to help you to get a 964corrected version of the library; if the bug report is poor, we won't do 965anything about it (apart from asking you to send better bug reports). 966 967Send your bug report to: 968 969@center @samp{nana-bug@@cs.ntu.edu.au} 970 971Copies of bug reports will be kept at: 972 973@center @samp{http://www.cs.ntu.edu.au/homepages/pjm/nana-bug/} 974 975@node New Versions, , Bug Reports, Installation 976@comment node-name, next, previous, up 977@section New Versions 978New versions of nana will be made available at: 979 980@center @samp{ftp://ftp.cs.ntu.edu.au/pub/nana/} 981 982If you wish to be informed about new 983releases of nana then subscribe to the nana mailing list. 984Send a message containing @samp{subscribe} <your e-mail address> to: 985 986@center @samp{mailto:nana-request@@it.ntu.edu.au}. 987 988A hypermail archive of this list is kept at: 989 990@center @samp{http://www.cs.ntu.edu.au/hypermail/nana-archive} 991 992If you wish to send a message to the list send it to 993@samp{mailto:nana@@it.ntu.edu.au}. 994 995@node Invoking, Interface, Installation, Top 996@chapter Invoking Nana 997The functions defined by Nana are implemented either as pure C code or 998as a set of commands which are generated for the debugger. 999To use the C based support for assertion checking you would use 1000something like: 1001 1002@example 1003#include <nana.h> /* this file includes the other nana .h files */ 1004 1005int floor_sqrt(int i) @{ /* returns floor(sqrt(i) */ 1006 int answer; 1007 I(i >= 0); /* assert(i >= 0) if i -ve then exit */ 1008 ...; /* code to calculate sqrt(i) */ 1009 L("floor_sqrt(%d) == %d\n", 1010 i, answer); /* logs a printf style message */ 1011@} 1012@end example 1013 1014To compile and link the previous code you may need to use the @samp{-Ipath} 1015or @samp{-lnana} flags with the compiler. For example: 1016 1017@example 1018% gcc toy.c -lnana 1019@end example 1020 1021If the nana headers have been installed in a strange location you may 1022need to do something like: 1023 1024@example 1025% gcc -I<strange location>/include toy.c -L<strange location>/lib -lnana 1026@end example 1027 1028The next example uses the debugger versions of @samp{L} and @samp{I}. 1029If the code is run under the debugger these checks will occur, otherwise 1030they take up a negligible amount of space and time. 1031 1032@example 1033#include <nana.h> /* this includes the other nana .h files */ 1034 1035int floor_sqrt(int i)@{ 1036 int answer; 1037 DI(i >= 0); /* assert(i >= 0) if i -ve then exit */ 1038 ...; /* code to calculate sqrt(i) */ 1039 DL("floor_sqrt(%d) == %d\n", i, answer); /* logs a printf style message */ 1040@} 1041@end example 1042 1043To generate the debugger commands from the C source we just run the 1044@samp{nana} filter over the program and then execute the commands 1045under gdb using the @samp{source} command. You also need to compile 1046the program with the @samp{-g} option so the debugger works. So 1047something like: 1048 1049@example 1050% gcc -g sqrt.c 1051% nana sqrt.c >sqrt.gdb 1052% gdb a.out 1053(gdb) source sqrt.gdb 1054breakpoint insert: ... 1055(gdb) run 1056... 1057(gdb) quit 1058@end example 1059 1060Note that any C preprocessor flags which you use must be passed off to 1061the @samp{nana} command. The best way to do this of course is in a 1062Makefile. Something like the following works for GNU Make: 1063 1064@example 1065%.nana: %.c 1066 nana $(CFLAGS) $< >$@@ 1067@end example 1068 1069The @samp{nana} filter can also be run over multiple source files in a 1070single run if thats more convenient. 1071 1072For convenience a number of other simple scripts are provided, in 1073particular to: 1074 1075@ftable @code 1076@item nana-run 1077Run a program under the debugger without prompting, etc. 1078For example: 1079 1080@example 1081% nana-run a.out -x main.gdb 1082output from program 1083@end example 1084 1085@item nana-clg 1086Compiles the program, generates the debugger commands and the runs the 1087program using @samp{nana-run}. For example: 1088 1089@example 1090% nana-clg -O3 main.c 1091output from program 1092@end example 1093 1094You can change the compiler invoked by @samp{nana-clg} by redefining 1095the @samp{NANACC} environment variable. For example: 1096 1097@example 1098% NANACC=g++ nana-clg -O3 main.cc 1099@end example 1100 1101The installation also @samp{nana-c++lg} which compiles your code 1102using a GNU C++ compiler. 1103 1104@item nana-trace 1105Generates a line by line trace of the execution of a program 1106using GDB@. For example: 1107 1108@example 1109% nana-trace a.out 111054 printf("main()\n"); 111155 x = distance(5,-5); 1112distance (i=5, j=-5) at test.c:47 111347 i = -i; 111448 j = -j; 1115... 1116@end example 1117 1118The arguments to @samp{nana-trace} are passed directly to GDB@. If you 1119wish display variables or call procedures on each line then could use 1120something like: 1121 1122@example 1123% nana-trace -x mycommands.gdb a.out 1124@end example 1125 1126Where the @samp{mycommands.gdb} contains the GDB commands such as 1127@samp{display x} which causes @samp{x} to be printed every time the 1128debugger gets control of the program. 1129 1130@end ftable 1131 1132@node Interface, Shortform, Invoking, Top 1133@chapter Interface 1134This section describes the details of the interface to nana library. 1135 1136All of the files can be included multiple times without 1137ill--effect since they use the C preprocessor to make sure the header 1138declarations are only seen the first by the compiler. 1139Each of the files can also be included individually. 1140 1141@menu 1142* nana.h:: 1143* WITHOUT_NANA:: 1144* I.h:: 1145* DI.h:: 1146* L.h:: 1147* L_buffer.h:: 1148* L_times.h:: 1149* DL.h:: 1150* GDB.h:: 1151* Q.h:: 1152* Qstl.h:: 1153* now.h:: 1154* cycles.h:: 1155* eiffel.h:: 1156* assert.h:: 1157* calls.h:: 1158@end menu 1159 1160If any of the following routines have an internal problem (e.g. malloc 1161fails due to lack of memory) they will call the @samp{nana_error} function 1162defined in @samp{nana_error.c}. By default this function prints a message 1163and dumps core using @samp{abort}. If you wish to override this behaviour 1164you should define your own handler before linking in the nana library. 1165 1166@node nana.h, WITHOUT_NANA, Interface, Interface 1167@section nana.h: the main header file 1168The @samp{nana.h} file includes most of the other files in the 1169library. In particular it @samp{#include's} the following 1170files: 1171 1172@ftable @code 1173@item I.h 1174@item DI.h 1175@item L.h 1176@item DL.h 1177@item Q.h 1178@item GDB.h 1179@end ftable 1180 1181@node WITHOUT_NANA, I.h, nana.h, Interface 1182@section WITHOUT_NANA: disabling all nana code for portability. 1183If you wish to disable all nana code you can @samp{#define} the 1184@samp{WITHOUT_NANA} macro. This selects versions of the 1185macros defined in @samp{I.h},@samp{L.h}, etc which map to 1186@samp{/* empty */}. 1187 1188So if you are using nana for your development but don't wish to 1189force your customers to use it you can add an option to your 1190@samp{configure} script to define/undefine @samp{WITHOUT_NANA}. 1191In addition you will need to distribute copies of the nana header 1192files with your package to get the stubs. 1193 1194Note that the @samp{L.h} and @samp{DL.h} macros use the 1195macro variable number of arguments extension provided by 1196GNU C@. If you wish your code to be portable you should use 1197the macros @samp{VL((..))}, etc rather than @samp{L(..)} to 1198avoid problems with non GNU C preprocessors which only take a fixed 1199number of arguments. 1200 1201@node I.h, DI.h, WITHOUT_NANA, Interface 1202@comment node-name, next, previous, up 1203@section I.h: C based invariant checking 1204This implements the C based invariant checking code and is a 1205replacement for @samp{assert.h}. The first two macros are the normal 1206user interface; the remainder are used for configuring the behaviour on 1207failure, etc. 1208 1209@deftypefn Macro void I (bool @var{exprn}) 1210The @var{exprn} should always be true if the program is correct. If the 1211@var{exprn} is false a message will be printed, followed by core 1212dump.@footnote{If you don't want a core dump then look at stopping the core 1213dumps with @code{ulimit} rather than changing the handler.} 1214 1215Checking can be enabled and disabled by using the @var{I_LEVEL} 1216and @var{I_DEFAULT_GUARD} macros. See the definitions below for these 1217macros for further details. 1218 1219Note that @var{exprn} should have no side-effects@footnote{Side-effects 1220include such operations as input/output or assignments, e.g. @samp{x++}.} 1221since disabling checking shouldn't change your programs behaviour. 1222 1223@example 1224 I(z != 0); 1225 x = y / z; 1226@end example 1227@end deftypefn 1228 1229@deftypefn Macro void N (bool @var{exprn}) 1230The opposite of @samp{I}, i.e. the expression must never ever be true if 1231the program is working properly. It is equivelant to @code{I(!(e))} and 1232exists as a piece of syntactic sugar which may be helpful for complicated 1233boolean expressions. 1234 1235@example 1236char* strdup(char *s) @{ 1237 N(s == NULL); 1238 ...; 1239@} 1240@end example 1241@end deftypefn 1242 1243@deftypefn Macro int I_LEVEL 1244The @samp{I_LEVEL} macro is used to globally enable and disable 1245checking by the macros in this file. It can take on one of three values: 1246 1247@ftable @code 1248@item 0 1249Disable all checking. Regardless of anything else no code will be 1250generated for @code{I}, @code{N}, etc. 1251@item 1 1252Enable checking only if the corresponding guard condition is true. The 1253guard condition can be used to enable and disable checking at compile 1254and run time. 1255@item 2 1256Enable all checking regardless of guard conditions. 1257@end ftable 1258 1259@code{I_LEVEL} defaults to @code{1}. 1260@end deftypefn 1261 1262@deftypefn Macro bool I_DEFAULT_GUARD 1263The @code{I_DEFAULT_GUARD} is used to selectively enable or disable 1264checking at compile or run time. 1265 1266@code{I_DEFAULT_GUARD} defaults to @code{TRUE}, i.e. always enabled. 1267 1268A user would typically define @code{I_DEFAULT_GUARD} to be global or local 1269variable which is used to turn checking on or off at run--time. For 1270example: 1271 1272@example 1273#define I_DEFAULT_GUARD i_guard > 0 1274 1275extern int i_guard; 1276@end example 1277@end deftypefn 1278 1279@deftypefn Macro text I_DEFAULT_PARAMS 1280This is passed off to the @code{I_DEFAULT_HANDLER} and defaults to 1281nothing, it is just some text and is intended to pass failure codes 1282(e.g. @code{IEH303}) or requests (e.g. @code{HW_DEAD}) information off 1283to the handler. 1284 1285@code{I_DEFAULT_PARAMS} defaults to nothing. 1286@end deftypefn 1287 1288@deftypefn Macro void I_DEFAULT_HANDLER (char *@var{exprn}, char *@var{file}, int @var{line}, @var{param}) 1289 1290When an error is detected the @code{I_DEFAULT_HANDLER} will be called to 1291handle the error. The arguments are: 1292 1293@ftable @code 1294@item exprn 1295A string representation of the expression that has failed, e.g. @code{"I(i>=0)"}. 1296@item file 1297The file that this error occurred in, i.e. @code{__FILE__}. 1298@item line 1299The line number for the error, i.e. @code{__LINE__}. 1300@item param 1301An optional parameter which can be passed across which defaults to 1302@code{I_DEFAULT_PARAMS}. This can be used to pass failure codes or other 1303information from the checking code to the handler. 1304@end ftable 1305@end deftypefn 1306 1307All of the remaining macros are used to individually override the 1308default values defined above. Normally these macros would be used in a 1309system wide header file to define macros appropriate for the 1310application. For example you might use @samp{IH} to define 1311different checking macros for hardware and software faults. 1312 1313@deftypefn Macro void I (bool @var{e}) 1314@deftypefnx Macro void IG (bool @var{e}, bool @var{g}) 1315@deftypefnx Macro void IH (bool @var{e}, Macro @var{h}) 1316@deftypefnx Macro void IP (bool @var{e}, Text @var{p}) 1317@deftypefnx Macro void IGH (bool @var{e}, bool @var{g}, Macro @var{h}) 1318@deftypefnx Macro void IGP (bool @var{e}, bool @var{g}, Text @var{p}) 1319@deftypefnx Macro void IHP (bool @var{e}, Macro @var{h}, Text @var{p}) 1320@deftypefnx Macro void IGHP (bool @var{e}, bool @var{g}, Macro @var{h}, Text @var{p}) 1321@deftypefnx Macro void N (bool @var{e}) 1322@deftypefnx Macro void NG (bool @var{e}, bool @var{g}) 1323@deftypefnx Macro void NH (bool @var{e}, Macro @var{h}) 1324@deftypefnx Macro void NP (bool @var{e}, Text @var{p}) 1325@deftypefnx Macro void NGH (bool @var{e}, bool @var{g}, Macro @var{h}) 1326@deftypefnx Macro void NGP (bool @var{e}, bool @var{g}, Text @var{p}) 1327@deftypefnx Macro void NHP (bool @var{e}, Macro @var{h}, Text @var{p}) 1328@deftypefnx Macro void NGHP (bool @var{e}, bool @var{g}, Macro @var{h}, Text @var{p}) 1329@end deftypefn 1330 1331We also provide support for referring to previous values of variables in 1332postconditions. The @code{ID} macro is used to create variables to 1333save the old state in. The @code{IS} and @code{ISG} macros are to 1334set these values. 1335 1336@deftypefn Macro void ID (Text @var{decln}) 1337@deftypefnx Macro void IS (Text @var{assignment}) 1338@deftypefnx Macro void ISG (Text @var{decln}, bool @var{g}) 1339@end deftypefn 1340 1341For example: 1342@example 1343void ex(int &r) @{ 1344 ID(int oldr = r); /* save parameter */ 1345 g(r); 1346 I(oldr == r); /* check r is unchanged */ 1347 while(more()) @{ 1348 IS(oldr = r); /* assign r to oldr */ 1349 h(r); 1350 I(oldr == r * r); 1351 @} 1352@} 1353@end example 1354 1355@node DI.h, L.h, I.h, Interface 1356@comment node-name, next, previous, up 1357@section DI.h: debugger based invariant checking 1358This implements the debugger based invariant checking code. 1359The first two macros are the normal 1360user interface; the remainder are used for configuring the behaviour on 1361failure, etc. Note that these macros have no effect unless you run your 1362program under the debugger and read in the commands generated by the 1363@samp{nana} command. You also need to compile the program with 1364the @samp{-g} option. 1365 1366@deftypefn Macro void DI (bool @var{exprn}) 1367The @var{exprn} should always be true if the program is working. 1368If it is true then nothing happens otherwise the code given by 1369@samp{DI_DEFAULT_HANDLER} will be called which by default prints 1370a message and dies just like @samp{assert.h}. 1371 1372The checking using @var{DI} can be enabled and disabled by using the 1373@var{DI_LEVEL} and @var{DI_DEFAULT_GUARD} macros. See the definitions 1374below for these macros for further details. 1375 1376Note that @var{exprn} should have no side-effects@footnote{Side-effects 1377include operations like input/output or assignments.} since 1378disabling the checking shouldn't change your programs behaviour. 1379@end deftypefn 1380 1381@deftypefn Macro void DN (bool @var{exprn}) 1382The opposite of @samp{DI}, i.e. the expression must never ever be true if 1383the program is working properly. It is equivelant to @code{I(!(e))} and 1384exists as piece of syntactic sugar which is helpful for complicated 1385boolean expressions. 1386@end deftypefn 1387 1388@deftypefn Macro int DI_LEVEL 1389The @samp{DI_LEVEL} macro is used to globally enable and disable 1390checking, in particular it can take on one of three values: 1391 1392@ftable @code 1393@item 0 1394Disable all checking. Regardless of anything else no code will be 1395generated for @code{DI}, @code{DN}, etc. 1396@item 1 1397Enable checking only if the corresponding guard condition is true. The 1398guard condition can be used to enable and disable checking at compile 1399and run time. 1400@item 2 1401Enable all checking regardless of guard conditions, etc. 1402@end ftable 1403 1404@code{DI_LEVEL} defaults to @code{1}. 1405@end deftypefn 1406 1407@deftypefn Macro bool DI_DEFAULT_GUARD 1408The @code{DI_DEFAULT_GUARD} is used to selectively enable or disable 1409checking at compile or run time. 1410 1411@code{DI_DEFAULT_GUARD} defaults to @code{TRUE}, i.e. always enabled. 1412 1413A user would typically define @code{DI_DEFAULT_GUARD} to be global or local 1414variable which is used to turn checking on or off at run--time. For 1415example: 1416 1417@example 1418#define DI_DEFAULT_GUARD (i_guard) 1419 1420extern int i_guard; 1421@end example 1422@end deftypefn 1423 1424@deftypefn Macro text DI_DEFAULT_PARAMS 1425This is passed off to the @code{DI_DEFAULT_HANDLER} and defaults to 1426nothing, it is just some text and is intended to pass failure codes 1427(e.g. @code{IEH303}) or requests (e.g. @code{HW_DEAD}) information off 1428to the handler. 1429 1430@code{DI_DEFAULT_PARAMS} defaults to nothing. 1431@end deftypefn 1432 1433@deftypefn Macro void DI_DEFAULT_HANDLER (char *@var{exprn}, char *@var{file}, int @var{line}, @var{param}) 1434 1435When an error is detected the @code{DI_DEFAULT_HANDLER} will be called to 1436handle the error. The arguments are: 1437 1438@ftable @code 1439@item exprn 1440A string representation of the expression that has failed, e.g. @code{"I(i>=0)"}. 1441@item file 1442The file that this error occurred in, i.e. @code{__FILE__}. 1443@item line 1444The line number for the error, i.e. @code{__LINE__}. 1445@item param 1446An optional parameter which can be passed across which defaults to 1447@code{DI_DEFAULT_PARAMS}. This can be used to pass failure codes or other 1448information from the checking code to the handler. 1449@end ftable 1450@end deftypefn 1451 1452@deftypefn Macro void DI_MAKE_VALID_BREAKPOINT (exprn @var{e}) 1453This macro is used to ensure that a breakpoint can be set at the 1454location we are checking using @code{DI}, etc. It defaults to 1455@code{asm("nop")} and can be redefined by the user. 1456@end deftypefn 1457 1458@deftypefn Macro void DI (bool @var{e}) 1459@deftypefnx Macro void DIG (bool @var{e}, bool @var{g}) 1460@deftypefnx Macro void DIH (bool @var{e}, Macro @var{h}) 1461@deftypefnx Macro void DIP (bool @var{e}, Text @var{p}) 1462@deftypefnx Macro void DIGH (bool @var{e}, bool @var{g}, Macro @var{h}) 1463@deftypefnx Macro void DIGP (bool @var{e}, bool @var{g}, Text @var{p}) 1464@deftypefnx Macro void DIHP (bool @var{e}, Macro @var{h}, Text @var{p}) 1465@deftypefnx Macro void DIGHP (bool @var{e}, bool @var{g}, Macro @var{h}, Text @var{p}) 1466@deftypefnx Macro void DN (bool @var{e}) 1467@deftypefnx Macro void DNG (bool @var{e}, bool @var{g}) 1468@deftypefnx Macro void DNH (bool @var{e}, Macro @var{h}) 1469@deftypefnx Macro void DNP (bool @var{e}, Text @var{p}) 1470@deftypefnx Macro void DNGH (bool @var{e}, bool @var{g}, Macro @var{h}) 1471@deftypefnx Macro void DNGP (bool @var{e}, bool @var{g}, Text @var{p}) 1472@deftypefnx Macro void DNHP (bool @var{e}, Macro @var{h}, Text @var{p}) 1473@deftypefnx Macro void DNGHP (bool @var{e}, bool @var{g}, Macro @var{h}, Text @var{p}) 1474 1475All of these macros are used to individually override the 1476default values defined above. Normally these macros 1477would be used in a system wide header file to define macros appropriate 1478for the application. 1479@end deftypefn 1480 1481@deftypefn Macro void DS (@var{e}) 1482@deftypefnx Macro void DSG (@var{e}, @var{g}) 1483These macros are used to assign values to convenience variables in the 1484debugger. Convenience variables are dynamically typed, global in scope 1485and initialised to 0. They start with a single @code{$} and can be used be 1486used for saving the state of program or for counting events. The 1487@samp{DS} macro executes @var{e} under the same rules as @code{DI}. 1488The @samp{DSG} macro executes @var{e} only if the the expression 1489@var{g} is true. 1490 1491Note that @samp{DS} and @samp{DSG} can also be used for modifying 1492C variables and calling functions. 1493@end deftypefn 1494 1495@node L.h, L_buffer.h, DI.h, Interface 1496@section L.h: support for printf style logging 1497These routines are used to provide logging functions. Messages can be 1498divided into classes and separately enabled and disabled. 1499 1500@deftypefn Macro void L (@var{args}...) 1501Used to log a message in a similar way to printf. 1502 1503Defaults to a using @code{fprintf} on @code{stderr}. 1504@end deftypefn 1505 1506@deftypefn Macro void LG (bool @var{guard}, @var{args}...) 1507@deftypefnx Macro void LH (function @var{handler}, @var{args}...) 1508@deftypefnx Macro void LP (text @var{param}, @var{args}...) 1509@deftypefnx Macro void LGP (bool @var{guard}, text @var{param}, @var{args}...) 1510@deftypefnx Macro void LHP (function @var{handler}, text @var{param}, @var{args}...) 1511@deftypefnx Macro void LGHP (bool @var{guard}, function @var{handler}, text @var{param}, @var{args}...) 1512And all of the special functions. 1513 1514@end deftypefn 1515 1516The macros such as @samp{L} depend on the GNU CC variable number of arguments 1517to macros extension. If you wish to compile your code on other systems 1518you might wish to use the following variations on @samp{L}, etc. 1519 1520@deftypefn Macro void VL ((@var{args}...)) 1521@deftypefnx Macro void VLG ((bool @var{guard}, @var{args}...)) 1522@deftypefnx Macro void VLH ((function @var{handler}, @var{args}...)) 1523@deftypefnx Macro void VLP ((text @var{param}, @var{args}...)) 1524@deftypefnx Macro void VLGP ((bool @var{guard}, @var{text param}, @var{args}...)) 1525@deftypefnx Macro void VLHP ((function @var{handler}, text @var{param}, @var{args}...)) 1526@deftypefnx Macro void VLGHP ((bool @var{guard}, function @var{handler}, text @var{param}, @var{args}...)) 1527Each of these macros calls the corresponding function from the previous 1528group, i.e. by default @samp{VLG} is the same as a call to @samp{LG}. 1529If you define @samp{WITHOUT_NANA} all these macros are translated 1530to @samp{/* empty */}. 1531 1532Thus you can have nana under GCC whilst the code is still portable 1533to other compilers. However debugging information will not be available 1534on other platforms. 1535 1536@strong{Note:} the argument list is surrounded by @strong{two} sets of 1537brackets. For example: 1538 1539@example 1540 VL(("haze in darwin = %d\n", 3.4)); 1541@end example 1542@end deftypefn 1543 1544@deftypefn Macro void L_LEVEL 1545Used to enable and disable logging independently of guard expressions. 1546 1547@ftable @code 1548@item 2 1549Always print message 1550@item 1 1551Print message only if the guard expression is true. 1552@item 0 1553Never print any messages. 1554@end ftable 1555 1556Defaults to @code{1}. 1557@end deftypefn 1558 1559@deftypefn Macro text L_DEFAULT_HANDLER 1560The default handler for printing which is simply the name of the 1561logging function or macro. 1562 1563Defaults to @code{fprintf} 1564@end deftypefn 1565 1566@deftypefn Macro bool L_DEFAULT_GUARD 1567The default guard condition for logging. 1568 1569Defaults to @code{TRUE}. 1570@end deftypefn 1571 1572@deftypefn Macro text L_DEFAULT_PARAMS 1573The default parameter passed off to the logging function or macro. 1574 1575Defaults to @code{stderr} 1576@end deftypefn 1577 1578@deftypefn Macro void L_SHOW_TIME 1579If defined then display the time in front of each message. 1580@end deftypefn 1581 1582@deftypefn Macro char* L_SHOW_TIME_FORMAT 1583A format string for the time stamp in the log. By default it prints the 1584time out in seconds. 1585@end deftypefn 1586 1587@deftypefn Macro value L_SHOW_TIME_NOW 1588The name of a function that returns the time for the time stamp. This 1589defaults to the @samp{now} function from @samp{now.h}. 1590@end deftypefn 1591 1592@node L_buffer.h, L_times.h, L.h, Interface 1593@section L_buffer.h: a circular buffer for logging. 1594A traditional embedded systems trick is to log messages to a circular 1595buffer in core. This has the following benefits: 1596 1597@enumerate 1598@item Speed -- writing to a in core buffer is much faster than spitting 1599out messages to a file on disk. It is often fast enough to leave at least 1600most of the messages in the final product. 1601@item Field debugging -- what the ... was the user doing before the 1602system crashed. Oh lets ask them, I'm sure they'll give us a good 1603problem report. 1604@end enumerate 1605 1606@deftypefn Type struct L_BUFFER 1607Used to define buffer variables, it is similar to @samp{FILE*} type in 1608@samp{stdio.h}. To create an instance use @samp{L_buffer_create}. 1609@end deftypefn 1610 1611@deftypefn Function L_BUFFER* L_buffer_create (size_t @var{size}) 1612@deftypefnx Function L_BUFFER* L_buffer_delete (L_BUFFER @var{*b}) 1613These are used to create or delete a buffer which can contain @var{size} 1614characters. 1615 1616@example 1617 L_BUFFER *lbuffer; 1618 1619 lbuffer = L_buffer_create(32*1024); /* create a 32K buffer */ 1620 ...; 1621 L_buffer_delete(lbuffer); /* and delete it after use */ 1622@end example 1623@end deftypefn 1624 1625@deftypefn Function void L_buffer_wraparound (L_BUFFER @var{*b}, int @var{w}) 1626A buffer created by @samp{L_buffer_create} is set up so that the new 1627messages will overwrite the older messages in the buffer. If you wish 1628to disable this overwriting, e.g. to keep the first 32K bytes 1629of your system startup messages you should use @samp{L_buffer_wraparound}. 1630For example: 1631 1632@example 1633 L_BUFFER *lb = L_buffer_create(32*1024); 1634 L_buffer_wraparound(lb, 0); /* disable wraparound */ 1635@end example 1636@end deftypefn 1637 1638@deftypefn Function void L_buffer_printf (L_BUFFER @var{*b}, const char @var{*fmt}, ...) 1639@deftypefnx Function void L_buffer_puts (L_BUFFER @var{*b}, const char @var{*str}) 1640@deftypefnx Function void L_buffer_putchar (L_BUFFER @var{*b}, char @var{ch}) 1641These are the routines which do that actual printing to the buffer. 1642 1643@example 1644 L_buffer_printf(lbuffer, "U: user input %c\n", c); 1645 L_buffer_puts(lbuffer, "warning: its too hot"); 1646 L_buffer_putchar(lbuffer, '*'); 1647@end example 1648 1649Note: a null pointer passed to the @samp{L_buffer_puts} function prints 1650as @samp{(null)}. @footnote{This was suggested by Phil Blecker.} 1651@end deftypefn 1652 1653@deftypefn Function void L_buffer_clear (L_BUFFER @var{*b}) 1654Clear the log, i.e. remove all messages and start again. 1655@end deftypefn 1656 1657@deftypefn Function void L_buffer_dump (L_BUFFER @var{*b}, FILE *@var{fp}) 1658Dump the contents of the log @var{*b} to the file descriptor @var{*fp}. 1659Typically @var{*fp} would be @samp{stderr}. 1660 1661Note that this does not change the contents of the buffer. This is 1662important since we may have a hardware or software problem part of the 1663way through the dump operation and you don't want to loose anything. 1664 1665To reset the buffer after a successful dump use @samp{L_buffer_clear}. 1666 1667The output of @samp{L_buffer_dump} consists of a starting message 1668followed by the contents of the log. If a character in the log is not 1669printable we print it out in hex on a line by itself. 1670 1671@example 1672* L_buffer_dump = 1673log message 1674and another 1675* non-printable character 0x1 1676more log messages 1677* end of dump 1678@end example 1679@end deftypefn 1680 1681You also need to be able to integrate these functions into your 1682design. See @samp{examples/ott.c} for a complicated example. Here we 1683will provide a simplified version which implements a new logging macro 1684called @samp{LFAST} which does a @samp{printf} to the @samp{log_buffer}. 1685If you want to have all messages going to a @samp{L_BUFFER} then you can 1686redefine @samp{L_DEFAULT_HANDLER}. 1687 1688@example 1689/* project.h - the project wide include file */ 1690 1691#include <nana.h> 1692#include <L_buffer.h> 1693 1694/* LFAST(char *, ...) - log a message to the log_buffer */ 1695/* ##f translates as the rest of the arguments to LFAST */ 1696 1697#define LFAST(f...) LHP(L_buffer_printf,log_buffer,##f) 1698 1699extern L_BUFFER *log_buffer; /* the log buffer */ 1700@end example 1701 1702The main program merely creates the @var{log_buffer} and eventually 1703calls @samp{L_buffer_dump} to print out the buffer when the system dies. 1704@example 1705/* main.c - initialise the system and start things */ 1706 1707#include <project.h> 1708 1709L_BUFFER *log_buffer; 1710 1711main() @{ 1712 log_buffer = L_buffer_create(16000); 1713 if(log_buffer == NULL) @{ /* not enough store */ 1714 ... 1715 @} 1716 LFAST("system starting at %f\n", now()); 1717 ...; 1718@} 1719 1720void fatal_error() @{ /* called on fatal errors */ 1721 FILE *f = fopen("project.errors","w"); 1722 L_buffer_dump(b, stderr); /* print log to stderr */ 1723 L_buffer_dump(b, f); /* print log to file */ 1724@} 1725@end example 1726 1727@node L_times.h, DL.h, L_buffer.h, Interface 1728@section L_times.h: recording events and times. 1729This component is used to record events and times with a lower time 1730and space overhead than the @samp{L_buffer.h} component. Instead 1731of using a @samp{printf} style string we simply record the time 1732and a pointer to a string identifying the event in a circular buffer. 1733 1734@strong{Note 0:} the string arguments should not be modified after 1735a call since we record pointers to the strings rather 1736than the strings themselves. 1737 1738@strong{Note 1:} there is no @var{printf} style formatting, e.g. 1739@samp{%d} in this package. 1740 1741@deftypefn Type struct L_TIMES 1742Used to define buffers, it is similar to @samp{FILE*} type in 1743@samp{stdio.h}. To create an instance use @samp{L_times_create}. 1744@end deftypefn 1745 1746@deftypefn Function L_TIMES* L_times_create (int @var{size}) 1747@deftypefnx Function L_TIMES* L_times_delete (L_BUFFER @var{*b}) 1748These are used to create or delete a buffer which can contain @var{size} 1749messages. 1750@end deftypefn 1751 1752@deftypefn Function void L_times_wraparound (L_TIMES @var{*b}, int @var{w}) 1753A buffer created by @samp{L_times_create} is set up so that the new 1754messages will overwrite the oldest messages in the buffer. If you wish 1755to disable this overwriting, e.g. to keep the first few messages 1756messages you could use @samp{L_times_wraparound(b,0)}. 1757@end deftypefn 1758 1759@deftypefn Function void L_times_add (L_BUFFER @var{*b}, char @var{*m}, NANA_TIME @var{t}) 1760Add an event identified by message @var{m} at time @var{t} to @var{b}. 1761The type @var{NANA_TIME} defaults to @samp{double}. 1762@end deftypefn 1763 1764@deftypefn Function void L_times_dump (L_TIMES @var{*b}, FILE @var{*fd}) 1765Dump the contents of the buffer out. 1766@end deftypefn 1767 1768@deftypefn Function void L_times_clear (L_TIMES @var{*b}) 1769Clear all the messages from @var{b}. 1770@end deftypefn 1771 1772@node DL.h, GDB.h, L_times.h, Interface 1773@section DL.h: support for printf style logging 1774These routines are used to provide logging functions. Messages can be 1775divided into classes and separately enabled and disabled. 1776Note that these macros have no effect unless you run your 1777program under the debugger and read in the commands generated by the 1778@samp{nana} command. You also need to compile the program with 1779the @samp{-g} option. 1780 1781@deftypefn Macro void DL (@var{args}...) 1782Used to log a message. 1783 1784Defaults to a using @code{fprintf} on @code{stderr}. 1785@end deftypefn 1786 1787@deftypefn Macro void DLG (bool @var{guard}, @var{args}...) 1788@deftypefnx Macro void DLH (function @var{handler}, @var{args}...) 1789@deftypefnx Macro void DLP (text @var{param}, @var{args}...) 1790@deftypefnx Macro void DLGP (bool @var{guard}, text @var{param}, @var{args}...) 1791@deftypefnx Macro void DLHP (function @var{handler}, @var{args}...) 1792@deftypefnx Macro void DLGHP (bool @var{guard}, function @var{handler}, @var{args}...) 1793And all of the special functions. 1794 1795@end deftypefn 1796 1797The macros such as @samp{DL} depend on the GNU CC variable number of arguments 1798to macros extension. If you wish to compile your code on other systems 1799you might wish to use the following variations on @samp{DL}, etc. 1800 1801@deftypefn Macro void VDL ((@var{args}...)) 1802@deftypefnx Macro void VDLG ((bool @var{guard}, @var{args}...)) 1803@deftypefnx Macro void VDLH ((function @var{handler}, @var{args}...)) 1804@deftypefnx Macro void VDLP ((text @var{param}, @var{args}...)) 1805@deftypefnx Macro void VDLGP ((bool @var{guard}, @var{text param}, @var{args}...)) 1806@deftypefnx Macro void VDLHP ((function @var{handler}, @var{args}...)) 1807@deftypefnx Macro void VDLGHP ((bool @var{guard}, function @var{handler}, @var{args}...)) 1808Each of these macros calls the corresponding function from the previous 1809group, i.e. by default @samp{VDL} is equivelant to a call to @samp{DL}. 1810If @samp{WITHOUT_NANA} is defined then the call too @samp{VDL} is 1811equivelant to @samp{/* empty */}. 1812 1813Thus you can have debugging under GCC whilst the code is still portable 1814to other compilers. However debugging information will not be available 1815on other platforms. 1816 1817@strong{Note:} the argument list is surrounded by @strong{two} sets of 1818brackets. For example: 1819 1820@example 1821 VDL(("haze in darwin = %d\n", 3.4)); 1822@end example 1823@end deftypefn 1824 1825@deftypefn Macro int DL_LEVEL 1826Used to enable and disable logging independently of guard expressions. 1827 1828@ftable @code 1829@item 2 1830Always print message 1831@item 1 1832Print message only if the guard expression is true. 1833@item 0 1834Never print any messages. 1835@end ftable 1836 1837Defaults to @code{1}. 1838@end deftypefn 1839 1840@deftypefn Macro text DL_DEFAULT_HANDLER 1841The default handler for printing which is simply the name of the 1842printing function. 1843 1844Defaults to @code{printf} 1845@end deftypefn 1846 1847@deftypefn Macro bool DL_DEFAULT_GUARD 1848 1849Defaults to @code{TRUE}. 1850@end deftypefn 1851 1852@deftypefn Macro text DL_DEFAULT_PARAMS 1853Defaults to @code{stderr} 1854@end deftypefn 1855 1856@deftypefn Macro flag DL_SHOW_TIME 1857Each message can be given an individual time stamp by defining 1858@code{DL_SHOW_TIME}. This causes the @code{_L_gettime} routine to be 1859called before each message which generates the timestamp. A default 1860version is provided by the nana library. 1861@end deftypefn 1862 1863@node GDB.h, Q.h, DL.h, Interface 1864@section GDB.h: sending plain gdb commands to the debugger 1865@samp{GDB.h} provides macros for generating user specified commands in 1866the output of the @samp{nana} command. 1867They are not included by default in the @samp{nana.h} file. 1868Note that these macros have no effect unless you run your 1869program under the debugger and read in the commands generated by the 1870@samp{nana} command. You also need to compile the program with 1871the @samp{-g} option. 1872 1873@deftypefn Macro void GDB (@var{command}) 1874Emit a single line command when running this file through @samp{nana}. 1875Note that each line must be passed off separately to the @samp{GDB} 1876macro. 1877 1878This could be used to set debugger options or to define procedures 1879inside @samp{gdb}, e.g. 1880 1881@example 1882 GDB(define checkstack); 1883 GDB( if 0 <= n && n <= 10); 1884 GDB( print "stack ok"); 1885 GDB( else); 1886 GDB( print "stack corrupted"); 1887 GDB( end); 1888 GDB(end); 1889@end example 1890@end deftypefn 1891 1892@deftypefn Macro void GDBCALL (@var{command}) 1893Causes a single gdb @var{command} to be executed whenever control 1894passes through this line of code. After the user's command is executed 1895control automatically returns to the program. 1896 1897@example 1898 GDBCALL(set memory_check = 1) 1899@end example 1900@end deftypefn 1901 1902These macros could used for instrumenting code or setting up test 1903harnesses, e.g. 1904 1905@example 1906 1907GDB(set $siocall = 0); 1908GDB(set $sioerr = 0); 1909 1910void sio_driver() @{ 1911 GDBCALL(set $siocall++) 1912 if(SIO_REQ & 0x010) @{ 1913 GDBCALL(set $sioerr++); 1914 ... 1915 @} 1916@} 1917@end example 1918 1919@node Q.h, Qstl.h, GDB.h, Interface 1920@section Q.h: support for quantifiers 1921@samp{Q.h} provides support for the quantifiers of predicate logic. For 1922example to check that all elements in a data structure have some 1923property we would use universal (forall, upside down A) quantification. 1924To check that one or more values in a data structure have some property 1925we would use existential (exists, back the front E) quantification. For 1926example: 1927 1928@example 1929 /* all values in a[] must be between 0 and 10 */ 1930 I(A(int i = 0, i < n_array, i++, 0 <= a[i] && a[i] <= 10)); 1931 1932 /* there exists a value in linked list l which is smaller than 10 */ 1933 I(E(node *p = l, p != NULL, p = p->next, p->data <= 10)); 1934@end example 1935 1936The first three arguments to @samp{A} and @samp{E} are similar 1937to a C @samp{for} loop which iterates over the values we wish to 1938check. The final argument is the expression that must be true. 1939 1940The only minor difference from the C @samp{for} loop is that variables 1941may be declared at the start of the loop, even if you are using C rather 1942than C++ which already supports this.@footnote{ANSI C does not allow 1943variable declarations at the beginning of loops unlike C++. The 1944 @samp{Q.h} macros get around this by starting each loop with a new 1945scope.} 1946 1947The @samp{Q.h} macros can also be nested and used anywhere a boolean 1948value is required. For example: 1949 1950@example 1951 if(A(int i = 0, i < MAXX, i++, 1952 A(int j = 0, j < MAXY, j++, 1953 m[i][j] == (i == j ? 1 : 0)))) @{ 1954 /* identity matrix, i.e. all 0's except for 1's on */ 1955 /* the diagonal */ 1956 ... 1957 @} else @{ 1958 /* not an identity matrix */ 1959 ... 1960 @} 1961@end example 1962 1963The results from these 1964macros can also be combined using boolean operations, e.g. 1965 1966@example 1967 /* the values in a[i] are either ALL positive or ALL negative */ 1968 I(A(int i = 0, i < MAX, i++, a[i] >= 0) 1969 || 1970 A(int i = 0, i < MAX, i++, a[i] < 0)); 1971@end example 1972 1973@strong{Portability:} note the macros in this file require the GNU 1974CC/C++ statement expression extension of GCC to work. If you're not using GNU CC 1975then for now you are out of luck. At some time in the future we may 1976implement a method which will work for standard C++, standard C is a bit of 1977a challenge. 1978 1979@strong{Portability:} unfortunately these macros do not work for the 1980@samp{DI} and @samp{DL} macros since the statement expression extension has 1981not been implemented in GDB@. 1982 1983@deftypefn Macro bool A (@var{init},@var{condition},@var{next},@var{exprn}) 1984For all values generated by 1985 @samp{for(@var{int};@var{condition};@var{next})} the @var{exprn} must be 1986true. 1987@example 1988 I(A(int i = 0, i < MAX, i++, a[i] >= 0)); /* all a[i] are +ve */ 1989@end example 1990@end deftypefn 1991 1992@deftypefn Macro bool E (@var{init},@var{condition},@var{next},@var{exprn}) 1993There exists at least one value for @var{exprn} generated by 1994 @samp{for (@var{int};@var{condition};@var{next})} which is true. 1995 1996@example 1997 /* one or more a[i] >= 0 */ 1998 I(E(int i = 0, i < MAX, i++, a[i] >= 0)); 1999@end example 2000@end deftypefn 2001 2002@deftypefn Macro long C (@var{init},@var{condition},@var{next},@var{exprn}) 2003Returns the number of times the @var{exprn} is true over the values 2004generated by @samp{for(@var{int};@var{condition};@var{next})}. 2005 2006@example 2007 /* 3 elements of a[] are +ve */ 2008 I(C(int i = 0, i < MAX, i++, a[i] >= 0) == 3); 2009@end example 2010@end deftypefn 2011 2012@deftypefn Macro bool E1 (@var{init},@var{condition},@var{next},@var{exprn}) 2013There exists only one value generated by 2014 @samp{for(@var{int};@var{condition};@var{next})} for which the @var{exprn} 2015is true. 2016 2017@example 2018 /* a single elements of a[] is +ve */ 2019 I(E1(int i = 0, i < MAX, i++, a[i] >= 0)); 2020@end example 2021@end deftypefn 2022 2023@deftypefn Macro typeof(@var{exprn}) S (@var{init},@var{condition},@var{next},@var{exprn}) 2024Sum the values generated by @var{exprn} for all values given by 2025 @samp{for(@var{int};@var{condition};@var{next})}. The type of the value 2026returned is given by the type of the @var{exprn}.@footnote{This uses yet 2027another GNU CC extension, however since we are already using statement 2028expressions we might as well use @samp{typeof} as well.} 2029 2030@example 2031 /* sum of a[] is 10 */ 2032 I(S(int i = 0, i < MAX, i++, a[i]) == 10); 2033 2034 /* sum of all +ve numbers in a[] is 10 */ 2035 I(S(int i = 0, i < MAX, i++, a[i] >= 0 ? a[i] : 0) == 10); 2036@end example 2037@end deftypefn 2038 2039@deftypefn Macro typeof(@var{exprn}) P (@var{init},@var{condition},@var{next},@var{exprn}) 2040Returns the product of the 2041values generated by @var{exprn} for all values given by 2042 @samp{for(@var{int};@var{condition};@var{next})}. 2043The type returned is the type of the expression. 2044 2045@example 2046 /* product of all the values in a[] is 10 */ 2047 I(P(int i = 0, i < MAX, i++, a[i]) == 10); 2048 2049 /* a = x^y i.e. x*x..*x y times */ 2050 I(P(int i = 0, i < y, i++, x) == a); 2051@end example 2052@end deftypefn 2053 2054@node Qstl.h, now.h, Q.h, Interface 2055@section Qstl.h: quantifiers for STL containers. 2056The Standard Template Library (STL) is a library for C++ that makes 2057extensive use of templates to implement the standard container 2058classes and much more. Each of the container classes provides an 2059interface to iterate over all the objects in the container, e.g. 2060 2061@example 2062// MAP is an associate array from location(lat,long) onto the name. 2063typedef map<location,string,locationlt> MAP; 2064 2065void print_map_names(MAP& m) @{ // print out all the names in the map 2066 for(MAP::iterator i = m.begin(); i != m.end(); ++i) @{ 2067 cout << (*i).second << "\n"; 2068 @} 2069@} 2070@end example 2071 2072@samp{Qstl.h} provides the same facilities as @samp{Q.h} but uses the 2073standard STL iterator protocol shown above. The names in @samp{Qstl.h} 2074are generated by appending a @samp{O} (O not zero!) to the names in 2075@samp{Q.h}. In particular: 2076 2077@deftypefn Macro bool AO (@var{name},@var{container},@var{predicate}) 2078For all values in the @var{container} class the @var{predicate} must 2079be true. The @var{predicate} refers to individual values using 2080@var{name}. See the STL documentation for more details. 2081Another way of putting this is forall @var{name} in 2082@var{container} the @var{predicate} must be true. 2083 2084@example 2085 map<int,char *,ltint> m; 2086 // all keys (or indexes) into m are positive 2087 I(AO(i, m, (*i).first >= 0)); 2088@end example 2089@end deftypefn 2090 2091@deftypefn Macro bool EO (@var{name},@var{container},@var{predicate}) 2092There exists one or more values in the @var{container} class for which 2093the @var{predicate} is true. 2094 2095@example 2096 map<int,char,ltint> m; 2097 2098 // one or more characters in m are '$' 2099 I(EO(i, m, (*i).second == '$')); 2100@end example 2101@end deftypefn 2102 2103@deftypefn Macro bool E1O (@var{name},@var{container},@var{predicate}) 2104There exists one value in the @var{container} for which 2105the @var{predicate} is true. 2106 2107@example 2108 map<int,char,ltint> m; 2109 2110 // one characters in m is a '$' 2111 I(E1O(i, m, (*i).second == '$')); 2112@end example 2113@end deftypefn 2114 2115@deftypefn Macro int CO (@var{name},@var{container},@var{predicate}) 2116Returns the number of times the @var{predicate} was true for all 2117values in the @var{container}. 2118 2119@example 2120 map<int,char,ltint> m; 2121 int nalpha; 2122 // count the number of alphabetic chars in the map 2123 nalpha = CO(i, m, isalpha((*i).second)); 2124@end example 2125@end deftypefn 2126 2127@deftypefn Macro typeof(@var{exprn}) SO (@var{name},@var{container},@var{exprn}) 2128Sum the @var{exprn} for all values in the @var{container}. 2129 2130@example 2131 map<int,float,ltint> m; 2132 float sum; 2133 // sum all the values in m 2134 sum = SO(i, m, (*i).second); 2135@end example 2136@end deftypefn 2137 2138@deftypefn Macro typeof(@var{exprn}) PO (@var{name},@var{container},@var{exprn}) 2139Take the product of the @var{exprn} for all values in the @var{container}. 2140 2141@example 2142 map<int,float,ltint> m; 2143 float product; 2144 // multiply all the values in m 2145 product = PO(i, m, (*i).second); 2146@end example 2147@end deftypefn 2148 2149@node now.h, cycles.h, Qstl.h, Interface 2150@section now.h: measuring time 2151The @samp{now.h} file provides some simple time measurement routines. 2152It is @emph{not} included in @samp{nana.h} so you must include this file 2153separately. 2154 2155It uses the @samp{gettimeofday} system call and has an accuracy of 2156between 1us and 10ms depending on the operating system and hardware 2157configuration. 2158 2159See the IPM package if you require better measurement tools.@footnote{In 2160the fullness of time, we may integrate these routines in here.} 2161 2162@deftypefn Function double now () 2163Returns the time in seconds since the beginning of time as defined by 2164your system. If you call @samp{now_reset} the time will start again at 21650. 2166@end deftypefn 2167 2168@deftypefn Function double now_reset () 2169Reset the times returned by @samp{now} to 0. 2170@end deftypefn 2171 2172@deftypefn Function double now_delta (double *@var{dp}) 2173Returns the elapsed time between @var{*dp} and @var{now()}. It then sets 2174@var{*dp} to @var{now}, thus giving a delta time between particular 2175events. 2176 2177@example 2178 t = now(); 2179 for(;;) @{ 2180 ...; /* code that must finish in 50ms */ 2181 I(now_delta(&t) <= 0.050); 2182 @} 2183@end example 2184@end deftypefn 2185 2186@node cycles.h, eiffel.h, now.h, Interface 2187@section cycles.h: access to CPU cycle counting registers. 2188Some modern CPU's provide user accessible registers or special intstructions 2189which can access a counter driven directly by the CPU clock. 2190The @samp{cycles.h} library provides access to these instructions 2191together with some calibration and utility routines. 2192 2193Currently we only provide support for Pentium/Cyrix machines using the 2194@samp{RDTSC} instruction. If you want to use these routines you 2195need to run the @samp{configure} script with the @samp{--enable-rdtsc} 2196option. Other machine architectures will be supported as time goes on. 2197 2198@deftp typedef CYCLES long long 2199The CPU cycle measurement type, typically a 64 bit unsigned integer. 2200@end deftp 2201 2202@deftypefn Macro CYCLES cycles () 2203Returns the current value for the cycle counter. 2204@end deftypefn 2205 2206@deftypefn Function CYCLES cycles_per_second (double @var{t}, int @var{n}) 2207Returns an estimate of the number of cycles per second using the 2208@samp{now.h} library. The measurement is taken @var{n} times using 2209a measurement period of @var{t} seconds for each measurement. 2210The minimum and maximum values for the measurement are set by 2211each call to @samp{cycles_per_second} and are available from the 2212next two functions. 2213@end deftypefn 2214 2215@deftypefn Function CYCLES cycles_per_second_min () 2216@deftypefnx Function CYCLES cycles_per_second_max () 2217Return the minimum or maximum of the measurements carried out 2218by the previous call to @samp{cycles_per_second}. 2219@end deftypefn 2220 2221@deftypefn Function double cycles_diff (CYCLES @var{start}, CYCLES @var{stop}) 2222Returns the time difference between @var{start} and @var{stop} cycles 2223in seconds as a double. As usual there are a few requirements: 2224 2225@itemize @bullet 2226@item @samp{cycles_per_second} must be called before hand to calibrate 2227the cycle time with the real time clock. 2228@item @var{start} must be less than or equal to @var{stop}. 2229Note we do not handle wraparound currently since the counters start at 0 2230and are 64 bits long and so will not overflow in a reasonable period. 2231@footnote{Famous last words I know but: (2^64)/(1e9*60*60*24*365) = 584 yrs.} 2232 2233@item The difference between the @var{start} and @var{stop} times should be 2234able to be represented in a @samp{double}, lest overflow and misery follow. 2235@item CPU clocks tend to vary a bit with temperature etc, trust this and 2236die. 2237@end itemize 2238@end deftypefn 2239 2240@menu 2241* RDTSC:: 2242@end menu 2243 2244@node RDTSC, , cycles.h, cycles.h 2245@subsection RDTSC: cycle timing for Pentium, Cyrix, etc 2246 2247The @var{RDTSC} instruction is used for cycle timing on Pentiums and 2248other compatible CPUs such as the Cyrix chip set. Note that this 2249instruction does @emph{not} exist on earlier CPUs in the series. 2250 2251We could of course try to discover the CPU type at compile or 2252run time and then use the appropriate instruction. This has 2253all sorts of problems, e.g. if we compile on a i586 does that mean 2254it will be run on the same CPU (no of course not....). 2255 2256For now we use the @samp{--enable-rdtsc} option for @samp{./configure}. 2257 2258@node eiffel.h, assert.h, cycles.h, Interface 2259@section eiffel.h: eiffel type assertions 2260Eiffel is a very nice language which provides the assertion checking 2261facilities of nana inside the language itself. The @samp{eiffel.h} 2262library is intended to provide a similar setup to Eiffel in the C++ 2263language. 2264 2265@menu 2266* EIFFEL_CHECK:: 2267* DOEND:: 2268* REQUIRE...:: 2269@end menu 2270 2271@node EIFFEL_CHECK, DOEND, eiffel.h, eiffel.h 2272@subsection EIFFEL_CHECK: enabling and disabling checking. 2273 2274Assertion checking is controlled by the @var{EIFFEL_CHECK} 2275macro which can take on any of the following values: 2276 2277@ftable @code 2278@item CHECK_NO 2279Disable all checking. 2280@item CHECK_REQUIRE 2281Check the preconditions for each method. 2282@item CHECK_ENSURE 2283And also check the postconditions. 2284@item CHECK_INVARIANT 2285And also check the class invariant before and after each method is 2286called. The programmer should provide a class method called 2287@samp{invariant} which returns @samp{true} if the object is consistent, 2288@samp{false} otherwise. 2289@item CHECK_LOOP 2290And also check the loop invariants. 2291@item CHECK_ALL 2292And also check any assertions using the @samp{CHECK} instruction. 2293@end ftable 2294 2295Note that the default value for @code{EIFFEL_CHECK} is 2296@code{CHECK_REQUIRE}, i.e. check preconditions only. 2297 2298A typical compile flag to the compile might be: 2299 2300@example 2301% g++ -c -DEIFFEL_CHECK=CHECK_ALL play.cc 2302@end example 2303 2304@node DOEND, REQUIRE..., EIFFEL_CHECK, eiffel.h 2305@subsection DOEND: adding DO ... END 2306At the suggestion of Bertrand Meyer (Eiffel's author) the @code{DO} and 2307@code{END} macros have been added to @samp{eiffel.h}. Note that these 2308are only available if you define the @code{EIFFEL_DOEND} macro. To use 2309these macros each of your methods should use @code{DO} ... @code{END} as 2310their outermost brackets. For example: 2311 2312@example 2313// compiled with EIFFEL_DOEND defined 2314void Stack::push(int n) 2315DO // checks the class invariant + @{ 2316 ... 2317END // check the class invariant + @} 2318@end example 2319 2320If you do @emph{not} define the @code{EIFFEL_DOEND} macro then @samp{eiffel.h} 2321reverts to its old behaviour where @samp{REQUIRE} and @samp{ENSURE} also 2322check the class invariant. Thus to check the class invariant when you 2323are not using @code{DO} and @code{END} you would need to call 2324@code{REQUIRE} and @code{ENSURE}, for example: 2325 2326@example 2327// compile with EIFFEL_DOEND undefined (i.e. old behaviour) 2328void Stack::push(int n) 2329@{ 2330 REQUIRE(true); // checks the invariant as well as the precondition 2331 2332 ENSURE(true); // checks the invariant as well as the postcondition 2333@} 2334@end example 2335 2336As for which one to option to pick, Bertrand Meyer is in favour of the 2337@code{DO} ... @code{END} solution. 2338 2339@node REQUIRE..., , DOEND, eiffel.h 2340@subsection REQUIRE, ENSURE, CHECK, etc. 2341Here are the individual checking macros: 2342 2343@deftypefn Macro void REQUIRE (@var{exprn}) 2344Called at the beginning of each method to check its 2345precondition (requirements). For example: 2346 2347@example 2348void Stack::push(int n) @{ 2349 REQUIRE(!full()); // stack has space for push 2350 ... 2351@} 2352@end example 2353 2354If @code{EIFFEL_DOEND} is not defined this also checks 2355the class invariant. 2356@end deftypefn 2357 2358@deftypefn Macro void ENSURE (@var{exprn}) 2359Called at the end of each method. 2360This checks the postcondition for a method and the class invariant. 2361 2362@example 2363void Stack::push(int n) @{ 2364 ... 2365 ENSURE(!empty()); // it can't be empty after a push! 2366@} 2367@end example 2368 2369If @code{EIFFEL_DOEND} is not defined this also checks 2370the class invariant. 2371@end deftypefn 2372 2373@deftypefn Macro void INVARIANT (@var{exprn}) 2374Used to check a loop invariant. 2375@end deftypefn 2376 2377@deftypefn Macro void CHECK (@var{exprn}) 2378Used for any other inline assertions. For example: 2379 2380@example 2381 CHECK(z != 0); 2382 x = y / z; 2383@end example 2384@end deftypefn 2385 2386And finally a small example: 2387 2388@example 2389#include <eiffel.h> 2390 2391class example @{ 2392 int nobjects; 2393 map<location,string,locationlt> layer; 2394public: 2395 bool invariant(); // is this object consistent 2396 void changeit(location l); 2397@}; 2398 2399bool example::invariant() @{ 2400 return AO(i,layer,valid_location((*i).first)) && 2401 nobjects >= 0; 2402@} 2403 2404void example::changeit(string n, location l) @{ 2405 REQUIRE(E1O(i,layer,(*i).second == n)); 2406 ...; 2407 while(..) @{ 2408 INVARIANT(...); 2409 ... 2410 INVARIANT(...); 2411 @} 2412 ... 2413 CHECK(x == 5); 2414 ... 2415 ENSURE(layer[l] == n); 2416@} 2417@end example 2418 2419Note that the invariant checking macro @samp{example::invariant} 2420is called automatically on function entry/exit using the 2421@samp{REQUIRE} and @samp{ENSURE} macros if @samp{EIFFEL_CHECK} is 2422not defined. 2423 2424@node assert.h, calls.h, eiffel.h, Interface 2425@section assert.h: a drop in replacement for assert.h 2426A drop in replacement for @samp{assert.h} is provided in the @samp{src} 2427directory. It is @strong{not} installed by default. If you wish to use 2428it then you need to copy it to your include directory by hand. 2429 2430This might be of use if you are already using @samp{assert.h} and 2431wish to save some code space since the nana implementation is more 2432space efficient. 2433 2434Calls to @samp{assert} are translated to calls to @samp{I} and 2435can be disabled by defining @samp{NDEBUG}. 2436 2437@node calls.h, , assert.h, Interface 2438@section calls.h: checking/printing many objects/facts. 2439The @samp{calls} module implements a simple list of functions which can be 2440modified and executed at run-time. It is similar in spirit to the 2441ANSI C @samp{atexit} function. It is intended to be used for: 2442 2443@itemize @bullet 2444@item Checking the consistency of the components in your system. 2445 2446For example each module could register a self checking function which 2447uses the rest of the nana library. All of these functions would then be 2448called using @samp{calls.h} to check that the entire system is consistent. 2449 2450@item Printing out the state of your program in a readable format. 2451@end itemize 2452 2453@deftp Type typedef FUNC 2454A pointer to a @samp{void} function which takes a single @samp{void*} 2455argument. The @samp{void *} argument is intended to be used to pass 2456information such as arguments or pointers to objects (e.g. @samp{this} 2457in C++). All of the checking/printing functions must be of this type, e.g. 2458 2459@example 2460void print_object(void *f) @{ 2461 ...; 2462@} 2463@end example 2464@end deftp 2465 2466@deftp Type struct CALL 2467This structure represents a single call to a function, i.e. a function 2468pointer (@samp{FUNC}) and the @samp{void*} argument. 2469 2470@example 2471 CALL *head = 0; 2472@end example 2473@end deftp 2474 2475@deftypefn Function void calls_add (CALL **head, FUNC fp, *arg) 2476Adds a call to function @samp{fp} with argument @samp{arg} to 2477the list pointed to by @samp{head}. 2478 2479@example 2480 CALL *global_checks = 0; 2481 2482 calls_add(&global_checks,complex_ok,(void *)x); 2483@end example 2484@end deftypefn 2485 2486@deftypefn Function void calls_exec (CALL **head, FUNC fp, void *arg) 2487Execute all/some of the calls in the list given by @samp{head}. 2488The arguments @samp{fp} and @samp{arg} must both 2489match for each individual call. The null pointer (@samp{0}) matches 2490anything whilst any other value requires an exact match between 2491the @samp{CALL} and the arguments to @samp{calls_exec}. 2492For example: 2493 2494@example 2495calls_exec(&l,0,0); /* execute all functions in l */ 2496calls_exec(&l,complex_print,0); /* calls complex_print(*) in l */ 2497calls_exec(&l,0,(void*) &b); /* calls *(&b) in l */ 2498calls_exec(&l,f,(void*) &b); /* calls f(&b) in l */ 2499@end example 2500@end deftypefn 2501 2502@deftypefn Function void calls_delete (CALL **head, FUNC fp, void *arg) 2503Delete all/some of the calls in the list given by @samp{head}. 2504The arguments @samp{fp} and @samp{arg} must both 2505match for each individual call. The null pointer (@samp{0}) matches 2506anything whilst any other value requires an exact match between 2507the @samp{CALL} and the arguments to @samp{calls_delete}. 2508For example: 2509 2510@example 2511calls_delete(&l,0,0); /* delete all functions in l */ 2512calls_delete(&l,complex_print,0); /* delete complex_print(*) in l */ 2513calls_delete(&l,0,(void*) &b); /* delete *(&b) in l */ 2514calls_delete(&l,f,(void*) &b); /* delete f(&b) in l */ 2515@end example 2516@end deftypefn 2517 2518@strong{Note:} that calls are added to the head of the list rather than the 2519tail. This means that the most recently added call will be 2520executed first (as in a stack). 2521 2522 2523@node Shortform, Performance, Interface, Top 2524@chapter Nana Shortform Generator. 2525The Eiffel language provides a shortform of a class which consists of 2526the exported methods and their pre and post conditions. The private 2527part of the class such as the code is hidden in this form leaving only: 2528 2529@enumerate 2530@item Arguments and return values for methods. 2531@item @samp{REQUIRE} and @samp{ENSURE} calls which specify 2532the precondition and postconditions of each method. 2533@end enumerate 2534 2535This is useful to provide a summary of what the code does and 2536how to use it rather than how it works. 2537 2538Nana provides a similar service which can be used to generated a HTML 2539version of the short form of your program automatically. The code for 2540this is kept in @samp{shortform}. Do a @samp{make example} to build 2541an example document.@footnote{Note you need to install the GLOBAL package 2542first. This is installed by default on FreeBSD systems. If you do not 2543have the GLOBAL package read on.} 2544 2545Consider the following program: 2546 2547@example 2548/* smallex.c - a small example */ 2549 2550#include <stdio.h> 2551#include <math.h> 2552#include <eiffel.h> 2553 2554void sort(int *v, int n) @{ 2555 int i; 2556 REQUIRE(v != NULL && 2557 0 <= n); 2558 2559 for(i = 0; < n; i++) @{ /* at last, an O(n) sort! */ 2560 v[i] = i; 2561 @} 2562 /* And no, this isn't what most people think of as sorting */ 2563 2564 ENSURE(A(int i = 0, i < n - 1, i++, 2565 v[i] <= v[i+1])); 2566@} 2567@end example 2568 2569Its short form can be generated by using the @samp{nana-sfg}@footnote{The 2570name @samp{nana-sfg} stands for either Nana Short Form Generator or 2571Nana Science Fiction Generator. Personally I prefer the later derivation.} 2572program which generates: 2573 2574@example 2575% nana-sfg smallex.c 2576... 2577#include <stdio.h> 2578#include <math.h> 2579#include <eiffel.h> 2580... 2581void sort(int *v, int n) @{ 2582 ... 2583 REQUIRE(v != NULL && 2584 n >= 0); 2585 ... 2586 ENSURE(A(int i = 0, i < n, i++, 2587 v[i] <= v[i+1])); 2588@} 2589% 2590@end example 2591 2592The @samp{nana-sfg} program is a small AWK program which processes its 2593arguments into shortform and always writes to the standard output. If it 2594is passed no arguments it works as a normal UNIX filter reading from the 2595standard input. 2596 2597It is suggested that a copy of @samp{nana-sfg} be kept in each projects 2598@samp{bin} directory so that it can be modified for local taste. The 2599user will probably wish to modify the rules for short form generation. 2600For example you might add rules such as: 2601 2602@example 2603/^\/\// @{ emit(); @} # print out C++ comments in column 1 2604/^\/\*\+/,/\*\// @{ emit(); @} # print out multi-line /*+ ... */ comments 2605@end example 2606 2607Of course for a real project you need to run @samp{nana-sfg} over the 2608entire source tree. To do this you can use the @samp{nana-sfdir} 2609program. 2610 2611@example 2612% nana-sfdir 2613@end example 2614 2615This command simply creates a copy of the source tree in the current 2616directory under @samp{NANASF} using the @samp{nana-sfg} program. You can 2617then run a source code to HTML translator over the @samp{NANASF} 2618directory. Currently we are using the GLOBAL package which was written 2619by Shigio Yamaguchi which available from: 2620 2621@itemize @bullet 2622@item @samp{http://wafu.netgate.net/tama/unix/global.html} -- the GLOBAL 2623 homepage. 2624@item @samp{ftp://ftp.cs.ntu.edu/pub/nana/global-2.24.tar.gz} -- a local 2625 (well for Darwin at least) copy of the GLOBAL package. 2626@end itemize 2627 2628The alert reader will perhaps be asking themselves why we did not simply 2629modify GLOBAL@. Well that was the original idea, however after a bit 2630of thinking it seemed better to separate the generation of the short 2631form of the code from the generation of the HTML@. This gives us the 2632ability to use other translators and other tools. It also simplifies the 2633interaction between nana and GLOBAL@. 2634For information on other translators see: 2635 2636@itemize @bullet 2637@item @samp{http://www.zib.de/Visual/software/doc++/index.html} -- DOC++ 2638 homepage. 2639@item @samp{http://www.webnz.com/webnz/robert/cpp_site.html#Documentation} -- 2640 an index of other translation tools (e.g. to LaTeX). 2641@end itemize 2642 2643@node Performance, Tracing, Shortform, Top 2644@chapter Nana Performance Measurement 2645A tool is provided for measuring code/time requirements for arbitrary 2646code fragments. This is kept in the @samp{perf} directory and is @strong{not} 2647built by default. If you wish to use this tool use the following targets: 2648 2649@example 2650% cd perf 2651% make perf 2652@end example 2653 2654The output is @samp{perf.tex}, @samp{perf.dvi} and @samp{perf/index.html}. 2655 2656Note that the measurement requires the following: 2657 2658@itemize @bullet 2659@item GNU CC -- it uses the GNU address of label extension to calculate 2660 the size in bytes of a code fragment. 2661@item Time is measured using the nana @samp{now()} function. 2662@item LaTeX -- to generate the document from @samp{perf.tex}. 2663@item LaTeX2HTML -- to generate a HTML version of @samp{perf.tex}. 2664@end itemize 2665 2666As an indication of the values you can expect here is part of the 2667results for @samp{make perf} on a 200Mhz Cyrix MMX (i386) chip which runs 2668at about 200 BogoMips under FreeBSD 2.2.6 with @samp{-O}. 2669 2670@samp{assert(i >= 2);} 28 bytes, 19ns. 2671 2672@samp{TRAD_assert(i >= 2);} 47 bytes, 20ns.@footnote{This is the traditional assert which 2673uses @samp{fprintf} and @samp{exit} in a macro. The BSD @samp{assert} 2674macro used in FreeBSD is a bit smarter and calls a function to do the 2675message printing and exiting. Note that the real cost of this function 2676is even higher since we are only measuring the code space requirements, 2677not the space required for the message strings.} 2678 2679@samp{I(i >= 2);} 9 bytes, 18ns. 2680 2681@samp{DI(i >= 2);} 1 byte, 147.4us. 2682 2683@samp{I(A(int i=0, i!=10, i++, a[i]>=0));} 28 bytes, 287ns. 2684 2685@samp{d = now();} 8 bytes, 3.1us. 2686 2687@samp{printf("helloworld\n");} 13 bytes, 9.1us. 2688 2689@samp{L("helloworld\n");} 18 bytes, 8.9us. 2690 2691@samp{DL("helloworld\n");} 1 byte, 26.4us. 2692 2693Note that these measurements were on a system that was configured 2694with @samp{I_DEFAULT=fast ./configure}. The default output of 2695@samp{./configure} produces nice error messages at the cost of increased 2696code space. 2697 2698@node Tracing, Usage, Performance, Top 2699@chapter Tracing tools 2700A few tools for execution tracing and logging are available in the 2701@samp{gdb} directory and are installed by default. They are simple shell 2702scripts and may be of some use in testing/development. Note that 2703@samp{gdb-4.17} may be required on some machines for this stuff to work 2704properly. 2705 2706@menu 2707* Statement:: 2708* Library:: 2709@end menu 2710 2711@node Statement, Library, Tracing, Tracing 2712@section Statement level tracing 2713The @samp{nana-trace} executes a program and generates a message 2714for each line of code executed (a statement trace). The statement 2715level trace is useful for things such as: 2716 2717@itemize @bullet 2718@item Understanding code. 2719@item Measuring test coverage. 2720@item Comparing runs of the code when regression testing, e.g. 2721verifying that change X only changes the behaviour of 2722program P for test case Z@. 2723@end itemize 2724 2725For example the @samp{make ex-trace} command in @samp{gdb} generates: 2726 2727@example 2728% make ex-trace 2729gcc -g test.c 2730sh ./nana-trace a.out 273147 setbuf(stdout, NULL); /* disable buffering */ 273249 printf("** main()\n"); 2733** main() 273450 printf("** 1: %d\n", distance(1,-5)); 2735distance (i=1, j=-5) at test.c:43 273643 return abs(i - j); 2737abs (i=6) at test.c:35 273835 if(i >= 0) @{ 273936 return i; 274040 @} 2741distance (i=1, j=-5) at test.c:44 274244 @} 2743** 1: 6 2744main () at test.c:51 274551 printf("** 2: %d\n", distance(twice(1),-5)); 2746twice (i=1) at test.c:29 274729 i = i * 2; 274831 return i ; 274932 @} 2750distance (i=2, j=-5) at test.c:43 275143 return abs(i - j); 2752abs (i=7) at test.c:35 275335 if(i >= 0) @{ 275436 return i; 275540 @} 2756distance (i=2, j=-5) at test.c:44 275744 @} 2758** 2: 7 2759main () at test.c:52 276052 printf("** 3: %d\n", distance(3,-5)); 2761distance (i=3, j=-5) at test.c:43 276243 return abs(i - j); 2763abs (i=8) at test.c:35 276435 if(i >= 0) @{ 276536 return i; 276640 @} 2767distance (i=3, j=-5) at test.c:44 276844 @} 2769** 3: 8 2770main () at test.c:53 277153 @} 2772@end example 2773 2774@node Library, , Statement, Tracing 2775@section Library tracing 2776On most UNIX machines there exists a tool for tracing the system 2777calls executed by a program. If you haven't used one of these 2778tools (e.g. ktrace) then now is a good time to learn. Being able 2779to trace the User/Kernel interface is an excellent way to understand 2780complex applications. 2781 2782The @samp{nana-libtrace} facility generalises this idea to provide a GDB 2783based function call tracer for all functions in which are defined in a 2784particular library. For example the @samp{make ex-libtrace} command in 2785the @samp{gdb} directory produces a trace of all calls to @samp{libc}. 2786 2787 2788@itemize @bullet 2789@item @samp{nana-libtrace a.out} -- reads a list of function names one per line 2790from the standard input and writes the corresponding gdb(1) script to 2791the standard output. Note that all functions specified in the input must 2792exist in the executable for them to be passed through to the 2793output. This may require compilation of your program with @samp{-static} 2794linking.@footnote{If possible we should replace the call to @samp{nm} 2795with a call to something which can print all the symbols for a 2796dynamically linked library. Unfortunately GDB gets upset if you try to 2797set a breakpoint for a function that does not exist. I suppose we could 2798use gdb to print the symbol list out.} For example: 2799 2800@example 2801% gcc -g -static test.c -lm 2802% ./nana-libtrace a.out >test.gdb 2803printf 2804write 2805% cat test.gdb 2806break printf 2807command $bpnum 2808silent 2809where 1 2810cont 2811end 2812break write 2813command $bpnum 2814silent 2815where 1 2816cont 2817end 2818% nana-run a.out -x test.gdb 2819Breakpoint 1 at 0x1483: file /usr/.../libc/stdio/printf.c, line 65. 2820Breakpoint 2 at 0x8c78 2821#0 printf (fmt=0x1116 "** main()\n") 2822 at /usr/src/lib/libc/../libc/stdio/printf.c:65 2823#0 0x8c78 in write () 2824** main() 2825#0 printf (fmt=0x1121 "** 1: %d\n") 2826 at /usr/src/lib/libc/../libc/stdio/printf.c:65 2827#0 0x8c78 in write () 2828** 1: 6 2829#0 printf (fmt=0x112b "** 2: %d\n") 2830 at /usr/src/lib/libc/../libc/stdio/printf.c:65 2831#0 0x8c78 in write () 2832** 2: 7 2833#0 printf (fmt=0x1135 "** 3: %d\n") 2834 at /usr/src/lib/libc/../libc/stdio/printf.c:65 2835#0 0x8c78 in write () 2836** 3: 8 2837 2838Program exited with code 010. 2839@end example 2840 2841@item @samp{nana-libtrace a.out /usr/lib/libc.a} -- trace all calls to 2842@samp{libc} from @samp{a.out}. A subset of the output is given below: 2843 2844@example 2845#0 printf (fmt=0x1135 "** 3: %d\n") 2846 at /usr/src/lib/libc/../libc/stdio/printf.c:65 2847#0 vfprintf (fp=0xa1d4, fmt0=0x1135 "** 3: %d\n", ap=0xefbfd888 "\b") 2848 at /usr/src/lib/libc/../libc/stdio/vfprintf.c:428 2849#0 vfprintf (fp=0xefbfd5b8, fmt0=0x1135 "** 3: %d\n", ap=0xefbfd888 "\b") 2850 at /usr/src/lib/libc/../libc/stdio/vfprintf.c:428 2851#0 __sfvwrite (fp=0xefbfd5b8, uio=0xefbfd184) 2852 at /usr/src/lib/libc/../libc/stdio/fvwrite.c:68 2853#0 0x8ff8 in memcpy () 2854#0 0x8ff8 in memcpy () 2855#0 __sfvwrite (fp=0xefbfd5b8, uio=0xefbfd184) 2856 at /usr/src/lib/libc/../libc/stdio/fvwrite.c:68 2857#0 0x8ff8 in memcpy () 2858#0 fflush (fp=0xefbfd5b8) at /usr/src/lib/libc/../libc/stdio/fflush.c:60 2859#0 __sflush (fp=0xefbfd5b8) at /usr/src/lib/libc/../libc/stdio/fflush.c:84 2860#0 __swrite (cookie=0xa1d4, buf=0xefbfd1b8 "** 3: 8\nain()\n", n=8) 2861 at /usr/src/lib/libc/../libc/stdio/stdio.c:78 2862#0 0x8c78 in write () 2863** 3: 8 2864@end example 2865 2866Note that your library code must be compiled with @samp{-g} to put 2867in the debugging information if you wish to have the arguments displayed 2868symbolically. This is fairly easy on most systems, e.g on FreeBSD 2869you edit the global compile options @samp{/etc/make.conf} and rebuild/install 2870the entire system. 2871 2872Ideally we would also like to be able to trace only entry calls and 2873not internal calls to libc. This can be done by inserting a counter 2874which is incremented on call and decremented on return. We print 2875the trace messages iff the counter is 1. This extension (perhaps 2876to GNU libc) may be written if people are interested. 2877@end itemize 2878 2879@node Usage, FAQ, Tracing, Top 2880@chapter Using Nana 2881This chapter is intended to provide some hopefully useful examples of 2882Nana. If any of the users of this library would be so kind as 2883to contribute a section on their usage I would be obliged. 2884 2885@strong{This section is under development} 2886 2887@menu 2888* Simplest:: 2889* Syslog:: 2890* GNU:: 2891* Embedded Systems:: 2892* Realtime:: 2893* A database:: 2894* Visualisation:: 2895@end menu 2896 2897@node Simplest, Syslog, Usage, Usage 2898@section Simplest example 2899As a nice simple, indeed trivial example consider the following: 2900 2901@enumerate 2902@item Include @samp{nana.h} in your project wide include file. 2903@item Use @samp{I} to check invariants in your code. In particular 2904all functions or methods should be required to check their pre and post 2905conditions. 2906@item Use @samp{DL} to print debugging messages in your code. This means 2907that debugging messages only occur when you run the program under the 2908debugger.@footnote{Of course you also need to use the gdb commands 2909generated by the @samp{nana} command, perhaps using @samp{nana-clg}.} 2910@end enumerate 2911 2912@node Syslog, GNU, Simplest, Usage 2913@section Syslog 2914@samp{syslog} is a comprehensive logging system written by Eric Allman 2915which is available on most UNIX systems. It provides facilities for 2916sorting messages by source or severity and mechanisms for sending 2917messages off to files, terminals or other machines. See chapter 12 of 2918the "UNIX System Administration Handbook (2nd Edition)" 2919by Nemeth, Snyder, Seebass and Hein for an excellent tutorial on 2920@samp{syslog}. 2921 2922The rules used by @samp{syslog} are normally defined in 2923@samp{/etc/syslog.conf}. Each line specifies the destination for 2924messages with particular sources and priorities. For example: 2925 2926@example 2927# log mail messages at priority info to mailinfo 2928mail.info /var/log/mailinfo 2929# log all ftp information to syslog on a remote machine 2930ftp.* @@remote-machine.cs.ntu.edu.au 2931# all critical errors to console 2932*.crit /dev/console 2933@end example 2934 2935To use @samp{syslog} we merely redefine the default handlers and 2936parameter values for @samp{nana}. For example: 2937 2938@example 2939#include <syslog.h> 2940#define L_DEFAULT_HANDLER syslog /* replaces fprintf(3) by syslog(3) */ 2941#define L_DEFAULT_PARAMS LOG_USER /* default priority for syslog info */ 2942#include <nana.h> 2943 2944int main() @{ 2945 openlog("nana", /* identifier for these log messages */ 2946 LOG_PID, /* also log the process id */ 2947 LOG_DAEMON /* facility */ 2948 ); 2949 2950 L("temperature is falling to %d", 35); /* logged at LOG_USER priority */ 2951 LP(LOG_CRIT, "the snow is falling in Darwin"); /* LOG_CRIT message */ 2952 2953 closelog(); 2954 return 0; 2955@} 2956@end example 2957 2958This program results in the following addition to @samp{/var/adm/messages}: 2959 2960@example 2961Jun 12 16:04:46 chingiz nana[2671]: the temperature is falling to 35 2962Jun 12 16:04:46 chingiz nana[2671]: the snow is falling in Darwin 2963@end example 2964 2965In addition the @samp{LOG_CRIT} message about snow falling in Darwin is 2966sent to the console for immediate action. 2967 2968@strong{Note:} @samp{syslog} normally uses @samp{UDP} for its network 2969communications and that @samp{UDP} does not guarantee delivery. 2970 2971@node GNU, Embedded Systems, Syslog, Usage 2972@section GNU Programs: how to avoid nana sometimes 2973Imagine you@footnote{Gordon Matzigkeit contributed some of the 2974ideas presented here and raised this problem.} are building a GNU program. 2975Ideally it should run on systems without any other software including 2976GCC, GDB and even Nana. 2977 2978To achieve this noble goal you can provide your configure script 2979with a @samp{--without-nana}@footnote{Or add a @samp{--with-nana} flag 2980to configure that does the opposite.} flag which then @samp{#define's} 2981@samp{WITHOUT_NANA}. You should also use the @samp{VL} macro rather than 2982@samp{L} macro since @samp{L} takes a variable number of arguments and 2983will break non GNU C preprocessors. 2984 2985@example 2986int half(int n) @{ 2987 /* Don't use L(...) since it takes a variable number of args! */ 2988 VL(("hello world = %d\n", 10)); /* Note the doubled (( */ 2989 ...; 2990@} 2991@end example 2992 2993@node Embedded Systems, Realtime, GNU, Usage 2994@section Embedded Systems: testing non-deterministic systems. 2995One of the uses (in fact the original use) for nana is in the 2996testing of non-deterministic systems. These systems behave in a 2997different way each time they are run because of timing or measurement 2998noise. Thus you can't just @samp{diff} the results against a known good run 2999since they run differently each time. 3000 3001Instead you can use a series of programs which execute over a 3002the results of the program and check that the behaviour meets the 3003specification automatically. 3004 3005@node Realtime, A database, Embedded Systems, Usage 3006@section Realtime Systems 3007Assertions for the timing behaviour of you system can be done in nana 3008nicely. You might also consider using an instruction level simulator 3009such as PSIM and use the @samp{cycles} variable to test realtime 3010constraints. 3011 3012@node A database, Visualisation, Realtime, Usage 3013@section A database 3014Ah databases, business boffins using assertions. It would nice 3015to get a real example for this one! 3016 3017@node Visualisation, , A database, Usage 3018@section Program Visualisation: pretty pictures 3019One nice way to use @samp{L}, @samp{DL}, etc is to punt off the messages 3020off to a program which displays the information. You would use the 3021@samp{L_DEFAULT_PARAM} argument to send commands off to a pipe with 3022gnuplot or TCL/TK interpreter running at the end. 3023 3024For a small example of this, see @samp{tcl/status.c}. 3025 3026@node FAQ, Future, Usage, Top 3027@chapter FAQ 3028This chapter is intended to answer some general questions about the 3029usage of Nana. Most of the material (perhaps) has been presented elsewhere, 3030my apologies for repeating myself. 3031 3032@enumerate 3033@item Can I use GNU Nana in a commercial product? 3034 3035See the license details in the file @samp{COPYING}. In summary GNU Nana 3036is Free software which has been released under a license that allows 3037commercial use provided the copyright is maintained. It is not under 3038the GPL@. 3039 3040@item How do you completely disable assertion checking? 3041 3042Set the @samp{I_LEVEL} command to @samp{0} using @samp{-D} or 3043@samp{#define} before including @samp{nana.h}. 3044 3045@item How do I find out about future releases? 3046 3047Subscribe to the nana mailing list by using the @samp{make subscribe} 3048target in the nana root directory. 3049 3050@item Where do I send bug reports, suggestions, etc? 3051 3052@samp{nana-bug@@it.ntu.edu.au} -- bug archive 3053 3054@samp{nana@@it.ntu.edu.au} -- mailing list 3055 3056@samp{pjm@@gnu.org} -- the author 3057 3058@end enumerate 3059 3060@node Future, Index, FAQ, Top 3061@chapter Future work 3062As usual, there is more work to be done than time to do it in. 3063Workers or test pilots are invited to apply for the following 3064tasks which may get down in the fullness of time minister. 3065I'm particularly interested in which projects people think 3066are worthwhile (or rubbish). 3067 3068@enumerate 3069@item Ada support - pre 1.00 versions of nana provided support for 3070 Ada. Adding a full version of nana into the GNATS compiler 3071 would probably be useful, particularly the real time part. 3072@item FORTRAN support. 3073@item Message browsing (@samp{emacs/fess.el}) - a very prototypical mode for 3074browsing message logs is distributed with nana. Features include hiding/showing 3075lines by regular expression or predicate. If someone who knows what they 3076are doing rewrites this that would be a good thing. Or perhaps a modified 3077version of @samp{less} would be useful. 3078@item Program Visualisation (@samp{tcl/status.c}) - another prototype 3079which uses a small TCL/TK library and nana logging to generate some 3080nice pictures showing the behaviour of the program. For example 3081the history of variables over time can be recorded, graphs drawn and 3082long message logs kept. A new version of this has been created 3083and may be released shortly. 3084@item Automated Testing - combine nana logs with a workbench 3085that lets you verify properties of the logs using programs @samp{gawk} 3086or the @samp{PRECC} (LL infinity version of YACC). This technique has 3087been used on industrial strength products quite successfully. 3088@item GNU standards - perhaps it would be worthwhile to set up 3089a prototype for checking and logging in GNU tools. 3090@item Extend GDB(1) so that we can support @samp{Q.h} style quantifiers 3091in @samp{DI.h} expressions. Basically we need to add a restricted form 3092of the statement value expression to GDB@. 3093@item Support for other (particularly ANSI only) compilers. 3094@end enumerate 3095 3096@node Index, , Future, Top 3097@appendix Index 3098@printindex cp 3099 3100@summarycontents 3101@contents 3102@bye 3103