Relay-Version: version B 2.10 5/3/83; site utzoo.UUCP Posting-Version: version B 2.10.1 6/24/83; site unisoft.UUCP Path: utzoo!watmath!clyde!burl!ulysses!allegra!mit-eddie!godot!harvard!seismo!hao!hplabs!intelca!qantel!dual!unisoft!fnf From: fnf@unisoft.UUCP (Fred Fish) Newsgroups: net.sources Subject: C debugging package (2 of 2 reposted) Message-ID: <377@unisoft.UUCP> Date: Thu, 3-Jan-85 13:22:09 EST Article-I.D.: unisoft.377 Posted: Thu Jan 3 13:22:09 1985 Date-Received: Sun, 6-Jan-85 00:39:28 EST Organization: UniSoft Corp., Berkeley Lines: 1164 After receiving postings on a couple bug fixes in "dbug", several people have sent mail saying that the original source posting never reached their site. So here is another, up-to-date posting. #--------CUT---------CUT---------CUT---------CUT--------# ######################################################### # # # This is a shell archive file. To extract files: # # # # 1) Make a directory for the files. # # 2) Write a file, such as "file.shar", containing # # this archive file into the directory. # # 3) Type "sh file.shar". Do not use csh. # # # ######################################################### # # echo Extracting example1.c: sed 's/^Z//' >example1.c <<\STUNKYFLUFF Z#include Z Zmain (argc, argv) Zint argc; Zchar *argv[]; Z{ Z printf ("argv[0] = %d\n", argv[0]); Z /* Z * Rest of program Z */ Z printf ("== done ==\n"); Z} STUNKYFLUFF set `sum example1.c` if test 55211 != $1 then echo example1.c: Checksum error. Is: $1, should be: 55211. fi # # echo Extracting example2.c: sed 's/^Z//' >example2.c <<\STUNKYFLUFF Z#include Z Zint debug = 0; Z Zmain (argc, argv) Zint argc; Zchar *argv[]; Z{ Z /* printf ("argv = %x\n", argv) */ Z if (debug) printf ("argv[0] = %d\n", argv[0]); Z /* Z * Rest of program Z */ Z#ifdef DEBUG Z printf ("== done ==\n"); Z#endif Z} STUNKYFLUFF set `sum example2.c` if test 55108 != $1 then echo example2.c: Checksum error. Is: $1, should be: 55108. fi # # echo Extracting example3.c: sed 's/^Z//' >example3.c <<\STUNKYFLUFF Z#include Z Zmain (argc, argv) Zint argc; Zchar *argv[]; Z{ Z# ifdef DEBUG Z printf ("argv[0] = %d\n", argv[0]); Z# endif Z /* Z * Rest of program Z */ Z# ifdef DEBUG Z printf ("== done ==\n"); Z# endif Z} STUNKYFLUFF set `sum example3.c` if test 54881 != $1 then echo example3.c: Checksum error. Is: $1, should be: 54881. fi # # echo Extracting factorial.c: sed 's/^Z//' >factorial.c <<\STUNKYFLUFF Z#include Z#include Z Zint factorial (value) Zregister int value; Z{ Z DBUG_ENTER ("factorial"); Z DBUG_3 ("find", "find %d factorial", value); Z if (value > 1) { Z value *= factorial (value - 1); Z } Z DBUG_3 ("result", "result is %d", value); Z DBUG_RETURN (value); Z} STUNKYFLUFF set `sum factorial.c` if test 21597 != $1 then echo factorial.c: Checksum error. Is: $1, should be: 21597. fi # # echo Extracting llib-ldbug.c: sed 's/^Z//' >llib-ldbug.c <<\STUNKYFLUFF Z/************************************************************************ Z * * Z * Copyright (c) 1984, Fred Fish * Z * All Rights Reserved * Z * * Z * This software and/or documentation is released into the * Z * public domain for personal, non-commercial use only. * Z * Limited rights to use, modify, and redistribute are hereby * Z * granted for non-commercial purposes, provided that all * Z * copyright notices remain intact and all changes are clearly * Z * documented. The author makes no warranty of any kind with * Z * respect to this product and explicitly disclaims any implied * Z * warranties of merchantability or fitness for any particular * Z * purpose. * Z * * Z ************************************************************************ Z */ Z Z Z/* Z * FILE Z * Z * llib-ldbug.c lint library source for debugging package Z * Z * SCCS ID Z * Z * @(#)llib-ldbug.c 1.4 1/3/85 Z * Z * DESCRIPTION Z * Z * Function definitions for use in building lint library. Z * Note that these must stay in syncronization with actual Z * declarations in "dbug.c". Z * Z */ Z Z Z/*LINTLIBRARY*/ Z Z#include Z#define VOID void Z#define FALSE 0 Z Zint _db_on_ = FALSE; ZFILE *_db_fp_ = stderr; Zchar *_db_process_ = "dbug"; Z ZVOID _db_push_ (control) Zchar *control; Z{ Z} Z ZVOID _db_pop_ () Z{ Z} Z ZVOID _db_enter_ (_func_, _file_, _line_, _sfunc_, _sfile_, _slevel_) Zchar *_func_; Zchar *_file_; Zint _line_; Zchar **_sfunc_; Zchar **_sfile_; Zint *_slevel_; Z{ Z} Z ZVOID _db_return_ (_line_, _sfunc_, _sfile_, _slevel_) Zint _line_; Zchar **_sfunc_; Zchar **_sfile_; Zint *_slevel_; Z{ Z} Z Z/*VARARGS3*/ ZVOID _db_printf_ (_line_, keyword, format, Z a0, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11) Zint _line_; Zchar *keyword, *format; Zint a0, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11; Z{ Z} Z Zint _db_keyword_ (keyword) Zchar *keyword; Z{ Z return (0); Z} STUNKYFLUFF set `sum llib-ldbug.c` if test 26037 != $1 then echo llib-ldbug.c: Checksum error. Is: $1, should be: 26037. fi # # echo Extracting main.c: sed 's/^Z//' >main.c <<\STUNKYFLUFF Z#include Z#include Z Zmain (argc, argv) Zint argc; Zchar *argv[]; Z{ Z register int flag, result, ix; Z extern int factorial (), atoi (); Z Z DBUG_ENTER ("main"); Z DBUG_PROCESS (argv[0]); Z for (ix = 1; ix < argc && argv[ix][0] == '-'; ix++) { Z switch (argv[ix][1]) { Z case '#': Z DBUG_PUSH (&(argv[ix][2])); Z break; Z } Z } Z for (; ix < argc; ix++) { Z DBUG_4 ("args", "argv[%d] = %s", ix, argv[ix]); Z result = factorial (atoi (argv[ix])); Z printf ("%d\n", result); Z } Z DBUG_RETURN (0); Z} STUNKYFLUFF set `sum main.c` if test 00434 != $1 then echo main.c: Checksum error. Is: $1, should be: 00434. fi # # echo Extracting user.r: sed 's/^Z//' >user.r <<\STUNKYFLUFF Z.\" @(#)user.r 1.2 1/3/85 Z.\" Z.\" DBUG (Macro Debugger Package) nroff source Z.\" Z.\" nroff -mm user.r >user.t Z.\" Z.\" =================================================== Z.\" Z.\" === Some sort of black magic, but I forget... Z.tr ~ Z.\" === Hyphenation control (1 = on) Z.\".nr Hy 1 Z.\" === Force all first level headings to start on new page Z.nr Ej 1 Z.\" === Set for breaks after headings for levels 1-3 Z.nr Hb 3 Z.\" === Set for space after headings for levels 1-3 Z.nr Hs 3 Z.\" === Set standard indent for one/half inch Z.nr Si 10 Z.\" === Set page header Z.PH "/DBUG User Manual/(preliminary)/\*(DT/" Z.\" === Set page footer Z.PF "// - % - //" Z.\" === Set page offset Z.\".po 0.60i Z.\" === Set line length Z.\".ll 6.5i Z.TL ZD B U G Z.P 0 ZC Program Debugging Package Z.P 0 Zby Z.AU "Fred Fish" Z.AF "" Z.SA 1 Z.\" === All paragraphs indented. Z.nr Pt 1 Z.AS 1 ZThis document introduces Z.I dbug , Za macro based C debugging Zpackage which has proven to be a very flexible and useful tool Zfor debugging, testing, and porting C programs. Z Z.P ZAll of the features of the Z.I dbug Zpackage can be enabled or disabled dynamically at execution time. ZThis means that production programs will run normally when Zdebugging is not enabled, and eliminates the need to maintain two Zseparate versions of a program. Z Z.P ZMany of the things easily accomplished with conventional debugging Ztools, such as symbolic debuggers, are difficult or impossible with this Zpackage, and vice versa. ZThus the Z.I dbug Zpackage should Z.I not Zbe thought of as a replacement or substitute for Zother debugging tools, but simply as a useful Z.I addition Zto the Zprogram development and maintenance environment. Z Z.AE Z.MT 4 Z.SK Z.B ZINTRODUCTION Z.R Z Z.P ZAlmost every program development environment worthy of the name Zprovides some sort of debugging facility. ZUsually this takes the form of a program which is capable of Zcontrolling execution of other programs and examining the internal Zstate of other executing programs. ZThese types of programs will be referred to as external debuggers Zsince the debugger is not part of the executing program. ZExamples of this type of debugger include the Z.B adb Zand Z.B sdb Zdebuggers provided with the Z.B UNIX\*F Z.FS ZUNIX is a trademark of AT&T Bell Laboratories. Z.FE Zoperating system. Z Z.P ZOne of the problems associated with developing programs in an environment Zwith good external debuggers is that developed programs tend to have Zlittle or no internal instrumentation. ZThis is usually not a problem for the developer since he is, Zor at least should be, intimately familiar with the internal organization, Zdata structures, and control flow of the program being debugged. ZIt is a serious problem for maintenance programmers, who Zare unlikely to have such familiarity with the program being Zmaintained, modified, or ported to another environment. ZIt is also a problem, even for the developer, when the program is Zmoved to an environment with a primitive or unfamiliar debugger, Zor even no debugger. Z Z.P ZOn the other hand, Z.I dbug Zis an example of an internal debugger. ZBecause it requires internal instrumentation of a program, Zand its usage does not depend on any special capabilities of Zthe execution environment, it is always available and will Zexecute in any environment that the program itself will Zexecute in. ZIn addition, since it is a complete package with a specific Zuser interface, all programs which use it will be provided Zwith similar debugging capabilities. ZThis is in sharp contrast to other forms of internal instrumentation Zwhere each developer has their own, usually less capable, form Zof internal debugger. ZIn summary, Zbecause Z.I dbug Zis an internal debugger it provides consistency across operating Zenvironments, Zand because it is available to all developers it provides Zconsistency across all programs in the same environment. Z Z.P ZThe Z.I dbug Zpackage imposes only a slight speed penalty on executing Zprograms, typically much less than 10 percent, and a modest size Zpenalty, typically 10 to 20 percent. ZBy defining a specific C preprocessor symbol both of these Zcan be reduced to zero with no changes required to the Zsource code. Z Z.P ZThe following list is a quick summary of the capabilities Zof the Z.I dbug Zpackage. ZEach capability can be individually enabled or disabled Zat the time a program is invoked by specifying the appropriate Zcommand line arguments. Z.SP 1 Z.ML o 1i Z.LI ZExecution trace showing function level control flow in a Zsemi-graphically manner using indentation to indicate nesting Zdepth. Z.LI ZOutput the values of all, or any subset of, key internal variables. Z.LI ZLimit actions to a specific set of named functions. Z.LI ZLimit function trace to a specified nesting depth. Z.LI ZLabel each output line with source file name and line number. Z.LI ZLabel each output line with name of current process. Z.LI ZPush or pop internal debugging state to allow execution with Zbuilt in debugging defaults. Z.LI ZRedirect the debug output stream to standard output (stdout) Zor a named file. ZThe default output stream is standard error (stderr). ZThe redirection mechanism is completely independent of Znormal command line redirection to avoid output conflicts. Z.LE Z Z.SK Z.B ZPRIMITIVE DEBUGGING TECHNIQUES Z.R Z Z.P ZInternal instrumentation is already a familiar concept Zto most programmers, since it is usually the first debugging Ztechnique learned. ZTypically, "print\ statements" are inserted in the source Zcode at interesting points, the code is recompiled and executed, Zand the resulting output is examined in an attempt to determine Zwhere the problem is. Z ZThe procedure is iterative, with each iteration yielding more Zand more output, and hopefully the source of the problem is Zdiscovered before the output becomes too large to deal with Zor previously inserted statements need to be removed. ZFigure 1 is an example of this type of primitive debugging Ztechnique. Z.DS I N Z.SP 2 Z.so example1.r Z.SP 2 Z.ll -5 Z.ce ZFigure 1 Z.ce ZPrimitive Debugging Technique Z.ll +5 Z.SP 2 Z.DE Z Z.P ZEventually, and usually after at least several iterations, the Zproblem will be found and corrected. ZAt this point, the newly inserted print statements must be Zdealt with. ZOne obvious solution is to simply delete them all. ZBeginners usually do this a few times until they have to Zrepeat the entire process every time a new bug pops up. ZThe second most obvious solution is to somehow disable Zthe output, either through the source code comment facility, Zcreation of a debug variable to be switched on or off, or by using the ZC preprocessor. ZFigure 2 is an example of all three techniques. Z.DS I N Z.SP 2 Z.so example2.r Z.SP 2 Z.ll -5 Z.ce ZFigure 2 Z.ce ZDebug Disable Techniques Z.ll +5 Z.SP 2 Z.DE Z Z.P ZEach technique has its advantages and disadvantages with respect Zto dynamic vs static activation, source code overhead, recompilation Zrequirements, ease of use, program readability, etc. ZOveruse of the preprocessor solution quickly leads to problems with Zsource code readability and maintainability when multiple Z.B #ifdef Zsymbols are to be defined or undefined based on specific types Zof debug desired. ZThe source code can be made slightly more readable by suitable indentation Zof the Z.B #ifdef Zarguments to match the indentation of the code, but Znot all C preprocessors allow this. ZThe only requirement for the standard Z.B UNIX ZC preprocessor is for the '#' character to appear Zin the first column, but even this seems Zlike an arbitrary and unreasonable restriction. ZFigure 3 is an example of this usage. Z.DS I N Z.SP 2 Z.so example3.r Z.SP 2 Z.ll -5 Z.ce ZFigure 3 Z.ce ZMore Readable Preprocessor Usage Z.ll +5 Z.SP 2 Z.DE Z Z.SK Z.B ZFUNCTION TRACE EXAMPLE Z.R Z Z.P ZWe will start off learning about the capabilities of the Z.I dbug Zpackage by using a simple minded program which computes the Zfactorial of a number. ZIn order to better demonstrate the function trace mechanism, this Zprogram is implemented recursively. ZFigure 4 is the main function for this factorial program. Z.DS I N Z.SP 2 Z.so main.r Z.SP 2 Z.ll -5 Z.ce ZFigure 4 Z.ce ZFactorial Program Mainline Z.ll +5 Z.SP 2 Z.DE Z Z.P ZThe Z.B main Zfunction is responsible for processing any command line Zoption arguments and then computing and printing the factorial of Zeach non-option argument. Z.P ZFirst of all, notice that all of the debugger functions are implemented Zvia preprocessor macros. ZThis does not detract from the readability of the code and makes disabling Zall debug compilation trivial (a single preprocessor symbol, Z.B DBUG_OFF , Zforces the macro expansions to be null). Z.P ZAlso notice the inclusion of the header file Z.B dbug.h Zfrom the standard header file directory. ZThis file contains all the definitions for the debugger macros, which Zall have the form Z.B DBUG_XX...XX . Z Z.P ZThe Z.B DBUG_ENTER Zmacro informs that debugger that we have entered the Zfunction named Z.B main . ZIt must be the very first "executable" line in a function, after Zall declarations and before any other executable line. ZThe Z.B DBUG_PROCESS Zmacro is generally used only once per program to Zinform the debugger what name the program was invoked with. ZThe Z.B DBUG_PUSH Zmacro modifies the current debugger state by Zsaving the previous state and setting a new state based on the Zcontrol string passed as its argument. ZThe Z.B DBUG_4 Zmacro is used to print the values of each argument Zfor which a factorial is to be computed. ZThe Z.B DBUG_RETURN Zmacro tells the debugger that the end of the current Zfunction has been reached and returns a value to the calling Zfunction. ZAll of these macros will be fully explained in subsequent sections. Z.P ZTo use the debugger, the factorial program is invoked with a command Zline of the form: Z.DS CB N Zfactorial -#d:t 1 2 3 Z.DE ZThe Z.B main Zfunction recognizes the "-#d:t" string as a debugger control Zstring, and passes the debugger arguments ("d:t") to the Z.I dbug Zruntime support routines via the Z.B DBUG_PUSH Zmacro. ZThis particular string enables output from the Z.B DBUG_4 Zmacro with the 'd' flag and enables function tracing with the 't' flag. ZThe factorial function is then called three times, with the arguments Z"1", "2", and "3". Z Z.P ZDebug control strings consist of a header, the "-#", followed Zby a colon separated list of debugger arguments. ZEach debugger argument is a single character flag followed Zby an optional comma separated list of argments specific Zto the given flag. ZSome examples are: Z.DS CB N Z-#d:t:o Z-#d,in,out:f,main:F:L Z.DE ZNote that previously enabled debugger actions can be disabled by the Zcontrol string "-#". Z Z.P ZThe definition of the factorial function, symbolized as "N!", is Zgiven by: Z.DS CB N ZN! = N * N-1 * ... 2 * 1 Z.DE ZFigure 5 is the factorial function which implements this algorithm Zrecursively. ZNote that this is not necessarily the best way to do factorials Zand error conditions are ignored completely. Z.DS I N Z.SP 2 Z.so factorial.r Z.SP 2 Z.ll -5 Z.ce ZFigure 5 Z.ce ZFactorial Function Z.ll +5 Z.SP 2 Z.DE Z Z.P ZOne advantage (some may not consider it so) to using the Z.I dbug Zpackage is that it strongly encourages fully structured coding Zwith only one entry and one exit point in each function. ZMultiple exit points, such as early returns to escape a loop, Zmay be used, but each such point requires the use of an Zappropriate Z.B DBUG_RETURN Zor Z.B DBUG_VOID_RETURN Zmacro. Z Z.P ZTo build the factorial program on a Z.B UNIX Zsystem, compile and Zlink with the command: Z.DS CB N Zcc -o factorial main.c factorial.c -ldbug Z.DE ZThe "-ldbug" argument tells the loader to link in the Zruntime support modules for the Z.I dbug Zpackage. ZExecuting the factorial program with a command of the form: Z.DS CB N Zfactorial 1 2 3 4 5 Z.DE Zgenerates the output shown in figure 6. Z.DS I N Z.SP 2 Z.so output1.r Z.SP 2 Z.ll -5 Z.ce ZFigure 6 Z.ce Zfactorial 1 2 3 4 5 Z.ll +5 Z.SP 2 Z.DE Z Z.P ZFunction level tracing is enabled by passing the debugger Zthe 't' flag in the debug control string. ZFigure 7 is the output resulting from the command Z"factorial\ -#t:o\ 3\ 2". Z.DS I N Z.SP 2 Z.so output2.r Z.SP 2 Z.ll -5 Z.ce ZFigure 7 Z.ce Zfactorial -#t:o 3 2 Z.ll +5 Z.SP 2 Z.DE Z Z.P ZEach entry to or return from a function is indicated by '>' for the Zentry point and '<' for the exit point, connected by Zvertical bars to allow matching points to be easily found Zwhen separated by large distances. Z Z.P ZThis trace output indicates that there was an initial call Zto factorial from main (to compute 2!), followed by Za single recursive call to factorial to compute 1!. ZThe main program then output the result for 2! and called the Zfactorial function again with the second argument, 3. ZFactorial called itself recursively to compute 2! and 1!, then Zreturned control to main, which output the value for 3! and exited. Z Z.P ZNote that there is no matching entry point "main>" for the Zreturn point "\ %s", stp, stp\ ->\ name); Z.LE Z Z.SK Z.B ZDEBUG CONTROL STRING Z.R Z Z.P ZThe debug control string is used to set the state of the debugger Zvia the Z.B DBUG_PUSH Zmacro. ZThis section summarizes the currently available debugger options Zand the flag characters which enable or disable them. ZArgument lists enclosed in '[' and ']' are optional. Z.SP 2 Z.BL 22 Z.LI d[,keywords] ZEnable output from macros with specified keywords. ZA null list of keywords implies that all keywords are selected. Z.LI f[,functions] ZLimit debugger actions to the specified list of functions. ZA null list of functions implies that all functions are selected. Z.LI F ZMark each debugger output line with the name of the source file Zcontaining the macro causing the output. Z.LI L ZMark each debugger output line with the source file line number of Zthe macro causing the output. Z.LI n ZMark each debugger output line with the current function nesting depth. Z.LI o[,file] ZRedirect the debugger output stream to the specified file. ZThe default output stream is stderr. ZA null argument list causes output to be redirected to stdout. Z.LI p[,processes] ZLimit debugger actions to the specified processes. ZA null list implies all processes. ZThis is useful for processes which run child processes. ZNote that each debugger output line can be marked with the name of Zthe current process via the 'P' flag. ZThe process name must match the argument passed to the Z.B DBUG_PROCESS Zmacro. Z.LI P ZMark each debugger output line with the name of the current process. ZMost useful when used with a process which runs child processes that Zare also being debugged. ZNote that the parent process must arrange for the debugger control Zstring to be passed to the child processes. Z.LI r ZUsed in conjunction with the Z.B DBUG_PUSH Zmacro to reset the current Zindentation level back to zero. ZMost useful with Z.B DBUG_PUSH Zmacros used to temporarily alter the Zdebugger state. Z.LI t[,N] ZEnable function control flow tracing. ZThe maximum nesting depth is specified by N, and defaults to Z200. Z.LE Z.SK Z.B ZHINTS AND MISCELLANEOUS Z.R Z Z.P ZOne of the most useful capabilities of the Z.I dbug Zpackage is to compare the executions of a given program in two Zdifferent environments. ZThis is typically done by executing the program in the environment Zwhere it behaves properly and saving the debugger output in a Zreference file. ZThe program is then run with identical inputs in the environment where Zit misbehaves and the output is again captured in a reference file. ZThe two reference files can then be differentially compared to Zdetermine exactly where execution of the two processes diverges. Z Z.P ZA related usage is regression testing where the execution of a current Zversion is compared against executions of previous versions. ZThis is most useful when there are only minor changes. Z Z.P ZIt is not difficult to modify an existing compiler to implement Zsome of the functionality of the Z.I dbug Zpackage automatically, without source code changes to the Zprogram being debugged. ZIn fact, such changes were implemented in a version of the ZPortable C Compiler by the author in less than a day. ZHowever, it is strongly encouraged that all newly Zdeveloped code continue to use the debugger macros Zfor the portability reasons noted earlier. ZThe modified compiler should be used only for testing existing Zprograms. Z Z.SK Z.B ZCAVEATS Z.R Z Z.P ZThe Z.I dbug Zpackage works best with programs which have "line\ oriented" Zoutput, such as text processors, general purpose utilities, etc. ZIt can be interfaced with screen oriented programs such as Zvisual editors by redefining the appropriate macros to call Zspecial functions for displaying the debugger results. ZOf course, this caveat is not applicable if the debugger output Zis simply dumped into a file for post-execution examination. Z Z.P ZPrograms which use memory allocation functions other than Z.B malloc Zwill usually have problems using the standard Z.I dbug Zpackage. ZThe most common problem is multiply allocated memory. Z.CS STUNKYFLUFF set `sum user.r` if test 01012 != $1 then echo user.r: Checksum error. Is: $1, should be: 01012. fi echo ALL DONE BUNKY! exit 0