Path: uunet!husc6!necntc!ncoast!allbery
From: fnf@mcdsun.UUCP (Fred Fish)
Newsgroups: comp.sources.misc
Subject: Dbug package (1 of 3)
Message-ID: <4560@ncoast.UUCP>
Date: 24 Sep 87 02:35:33 GMT
Sender: allbery@ncoast.UUCP
Lines: 2040
Approved: allbery@ncoast.UUCP
X-Archive: comp.sources.misc/8709/dbug/1

>From noao!cfa!harvard!ll-xn!scubed!MAILER-DAEMON Tue Sep 22 23:30:58 1987
Return-Path: <noao!cfa!harvard!ll-xn!scubed!MAILER-DAEMON>
Received: by noname.uucp (3.2/SMI-3.2)
	id AA00979; Tue, 22 Sep 87 23:30:54 MST
Received: by noao.arizona.edu (5.51/SAG.7)
	id AA09998; Tue, 22 Sep 87 21:23:58 MST
Received: from husc6.harvard.edu (husc6.ARPA) by cfa.HARVARD.EDU; Wed, 23 Sep 87 00:06:52 edt
Received: by husc6.harvard.edu; Wed, 23 Sep 87 00:00:03 EDT
Received: by harvard.harvard.edu; Wed, 23 Sep 87 00:08:08 EDT
Received:  by XN.LL.MIT.EDU; Tue, 22 Sep 87 23:58:47 EDT
Posted-Date: Wed, 9 Sep 87 10:35:26 MST
Received: by SCUBED.ARPA (1.2/5.20b)
	id AA07301; Tue, 22 Sep 87 20:42:56 pdt
Date: Wed, 9 Sep 87 10:35:26 MST
From: noao!cfa!harvard!ll-xn!scubed!MAILER-DAEMON (Mail Delivery Subsystem)
Subject: Returned mail: Host unknown
Message-Id: <8709230342.AA07301@SCUBED.ARPA>
To: ll-xn!ames!NOAO.ARIZONA.EDU!mcdsun!fnf@scubed
Status: R

   ----- Transcript of session follows -----
550 noao.arizona.edu.tcp... 550 Host unknown
550 seismo!adelie!necntc!ncoast!allbery@NOAO.ARIZONA.EDU... Host unknown

   ----- Unsent message follows -----
Received: by SCUBED.ARPA (1.2/5.20b)
	id AA07273; Tue, 22 Sep 87 20:42:56 pdt
Received: by SCUBED.ARPA (1.2/5.20b)
	id AA00835; Wed, 9 Sep 87 11:18:47 pdt
Received:  by XN.LL.MIT.EDU; Wed, 9 Sep 87 13:57:16 EDT
Posted-Date: Wed, 9 Sep 87 10:35:26 MST
Received: Wed, 9 Sep 87 10:59:59 PDT from HAO.UCAR.EDU by ames.arpa (5.58/1.2)
Received: by hao.UCAR.EDU (5.54/1.00.UUCP-MOD.8-11-85)
	id AA15475; Wed, 9 Sep 87 11:49:43 MDT
Received: by noao.arizona.edu (5.51/SAG.7)
	id AA04818; Wed, 9 Sep 87 10:51:44 MST
Received: by noname.uucp (3.2/SMI-3.2)
	id AA14017; Wed, 9 Sep 87 10:35:26 MST
Date: Wed, 9 Sep 87 10:35:26 MST
From: ll-xn!ames!NOAO.ARIZONA.EDU!mcdsun!fnf@scubed.scubed.arpa (Fred Fish)
Message-Id: <8709091735.AA14017@noname.uucp>
To: adelie!necntc!ncoast!allbery@NOAO.ARIZONA.EDU
Subject: My macro based C debugging package (1 of 3)


#--------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 dbug.h:
sed 's/^Z//' >dbug.h <<\STUNKYFLUFF
Z/******************************************************************************
Z *									      *
Z *	                           N O T I C E				      *
Z *									      *
Z *	              Copyright Abandoned, 1987, Fred Fish		      *
Z *									      *
Z *									      *
Z *	This previously copyrighted work has been placed into the  public     *
Z *	domain  by  the  author  and  may be freely used for any purpose,     *
Z *	private or commercial.						      *
Z *									      *
Z *	Because of the number of inquiries I was receiving about the  use     *
Z *	of this product in commercially developed works I have decided to     *
Z *	simply make it public domain to further its unrestricted use.   I     *
Z *	specifically  would  be  most happy to see this material become a     *
Z *	part of the standard Unix distributions by AT&T and the  Berkeley     *
Z *	Computer  Science  Research Group, and a standard part of the GNU     *
Z *	system from the Free Software Foundation.			      *
Z *									      *
Z *	I would appreciate it, as a courtesy, if this notice is  left  in     *
Z *	all copies and derivative works.  Thank you.			      *
Z *									      *
Z *	The author makes no warranty of any kind  with  respect  to  this     *
Z *	product  and  explicitly disclaims any implied warranties of mer-     *
Z *	chantability or fitness for any particular purpose.		      *
Z *									      *
Z ******************************************************************************
Z */
Z
Z
Z/*
Z *  FILE
Z *
Z *	dbug.h    user include file for programs using the dbug package
Z *
Z *  SYNOPSIS
Z *
Z *	#include <local/dbug.h>
Z *
Z *  SCCS ID
Z *
Z *	@(#)dbug.h	1.11 9/5/87
Z *
Z *  DESCRIPTION
Z *
Z *	Programs which use the dbug package must include this file.
Z *	It contains the appropriate macros to call support routines
Z *	in the dbug runtime library.
Z *
Z *	To disable compilation of the macro expansions define the
Z *	preprocessor symbol "DBUG_OFF".  This will result in null
Z *	macros expansions so that the resulting code will be smaller
Z *	and faster.  (The difference may be smaller than you think
Z *	so this step is recommended only when absolutely necessary).
Z *	In general, tradeoffs between space and efficiency are
Z *	decided in favor of efficiency since space is seldom a
Z *	problem on the new machines).
Z *
Z *	All externally visible symbol names follow the pattern
Z *	"_db_xxx..xx_" to minimize the possibility of a dbug package
Z *	symbol colliding with a user defined symbol.
Z *	
Z *	The DBUG_<N> style macros are obsolete and should not be used
Z *	in new code.  Macros to map them to instances of DBUG_PRINT
Z *	are provided for compatibility with older code.  They may go
Z *	away completely in subsequent releases.
Z *
Z *  AUTHOR
Z *
Z *	Fred Fish
Z *	(Currently employed by Motorola Computer Division, Tempe, Az.)
Z *	hao!noao!mcdsun!fnf
Z *	(602) 438-3614
Z *
Z */
Z
Z
Z/*
Z *	Internally used dbug variables which must be global.
Z */
Z
Z#ifndef DBUG_OFF
Z    extern int _db_on_;			/* TRUE if debug currently enabled */
Z    extern FILE *_db_fp_;		/* Current debug output stream */
Z    extern char *_db_process_;		/* Name of current process */
Z    extern int _db_keyword_ ();		/* Accept/reject keyword */
Z    extern void _db_push_ ();		/* Push state, set up new state */
Z    extern void _db_pop_ ();		/* Pop previous debug state */
Z    extern void _db_enter_ ();		/* New user function entered */
Z    extern void _db_return_ ();		/* User function return */
Z    extern void _db_pargs_ ();		/* Remember args for line */
Z    extern void _db_doprnt_ ();		/* Print debug output */
Z    extern void _db_setjmp_ ();		/* Save debugger environment */
Z    extern void _db_longjmp_ ();	/* Restore debugger environment */
Z# endif
Z
Z
Z/*
Z *	These macros provide a user interface into functions in the
Z *	dbug runtime support library.  They isolate users from changes
Z *	in the MACROS and/or runtime support.
Z *
Z *	The symbols "__LINE__" and "__FILE__" are expanded by the
Z *	preprocessor to the current source file line number and file
Z *	name respectively.
Z *
Z *	WARNING ---  Because the DBUG_ENTER macro allocates space on
Z *	the user function's stack, it must precede any executable
Z *	statements in the user function.
Z *
Z */
Z
Z# ifdef DBUG_OFF
Z#    define DBUG_ENTER(a1)
Z#    define DBUG_RETURN(a1) return(a1)
Z#    define DBUG_VOID_RETURN return
Z#    define DBUG_EXECUTE(keyword,a1)
Z#    define DBUG_PRINT(keyword,arglist)
Z#    define DBUG_2(keyword,format)		/* Obsolete */
Z#    define DBUG_3(keyword,format,a1)		/* Obsolete */
Z#    define DBUG_4(keyword,format,a1,a2)	/* Obsolete */
Z#    define DBUG_5(keyword,format,a1,a2,a3)	/* Obsolete */
Z#    define DBUG_PUSH(a1)
Z#    define DBUG_POP()
Z#    define DBUG_PROCESS(a1)
Z#    define DBUG_FILE (stderr)
Z#    define DBUG_SETJMP setjmp
Z#    define DBUG_LONGJMP longjmp
Z# else
Z#    define DBUG_ENTER(a) \
Z	auto char *_db_func_, *_db_file_; \
Z	int _db_level_; \
Z	_db_enter_ (a,__FILE__,__LINE__,&_db_func_,&_db_file_,&_db_level_)
Z#    define DBUG_LEAVE \
Z	(_db_return_ (__LINE__, &_db_func_, &_db_file_, &_db_level_))
Z#    define DBUG_RETURN(a1) return (DBUG_LEAVE, (a1))
Z/*   define DBUG_RETURN(a1) {DBUG_LEAVE; return(a1);}  Alternate form */
Z#    define DBUG_VOID_RETURN {DBUG_LEAVE; return;}
Z#    define DBUG_EXECUTE(keyword,a1) \
Z	{if (_db_on_) {if (_db_keyword_ (keyword)) { a1 }}}
Z#    define DBUG_PRINT(keyword,arglist) \
Z	{if (_db_on_) {_db_pargs_(__LINE__,keyword); _db_doprnt_ arglist;}}
Z#    define DBUG_2(keyword,format) \
Z	DBUG_PRINT(keyword,(format))		/* Obsolete */
Z#    define DBUG_3(keyword,format,a1) \
Z	DBUG_PRINT(keyword,(format,a1))		/* Obsolete */
Z#    define DBUG_4(keyword,format,a1,a2) \
Z	DBUG_PRINT(keyword,(format,a1,a2))	/* Obsolete */
Z#    define DBUG_5(keyword,format,a1,a2,a3) \
Z	DBUG_PRINT(keyword,(format,a1,a2,a3))	/* Obsolete */
Z#    define DBUG_PUSH(a1) _db_push_ (a1)
Z#    define DBUG_POP() _db_pop_ ()
Z#    define DBUG_PROCESS(a1) (_db_process_ = a1)
Z#    define DBUG_FILE (_db_fp_)
Z#    define DBUG_SETJMP(a1) (_db_setjmp_ (), setjmp (a1))
Z#    define DBUG_LONGJMP(a1,a2) (_db_longjmp_ (), longjmp (a1, a2))
Z# endif
STUNKYFLUFF
set `sum dbug.h`
if test 04698 != $1
then
echo dbug.h: Checksum error. Is: $1, should be: 04698.
fi
#
#
echo Extracting dbug.c:
sed 's/^Z//' >dbug.c <<\STUNKYFLUFF
Z/******************************************************************************
Z *									      *
Z *	                           N O T I C E				      *
Z *									      *
Z *	              Copyright Abandoned, 1987, Fred Fish		      *
Z *									      *
Z *									      *
Z *	This previously copyrighted work has been placed into the  public     *
Z *	domain  by  the  author  and  may be freely used for any purpose,     *
Z *	private or commercial.						      *
Z *									      *
Z *	Because of the number of inquiries I was receiving about the  use     *
Z *	of this product in commercially developed works I have decided to     *
Z *	simply make it public domain to further its unrestricted use.   I     *
Z *	specifically  would  be  most happy to see this material become a     *
Z *	part of the standard Unix distributions by AT&T and the  Berkeley     *
Z *	Computer  Science  Research Group, and a standard part of the GNU     *
Z *	system from the Free Software Foundation.			      *
Z *									      *
Z *	I would appreciate it, as a courtesy, if this notice is  left  in     *
Z *	all copies and derivative works.  Thank you.			      *
Z *									      *
Z *	The author makes no warranty of any kind  with  respect  to  this     *
Z *	product  and  explicitly disclaims any implied warranties of mer-     *
Z *	chantability or fitness for any particular purpose.		      *
Z *									      *
Z ******************************************************************************
Z */
Z
Z
Z/*
Z *  FILE
Z *
Z *	dbug.c   runtime support routines for dbug package
Z *
Z *  SCCS
Z *
Z *	@(#)dbug.c	1.19 9/5/87
Z *
Z *  DESCRIPTION
Z *
Z *	These are the runtime support routines for the dbug package.
Z *	The dbug package has two main components; the user include
Z *	file containing various macro definitions, and the runtime
Z *	support routines which are called from the macro expansions.
Z *
Z *	Externally visible functions in the runtime support module
Z *	use the naming convention pattern "_db_xx...xx_", thus
Z *	they are unlikely to collide with user defined function names.
Z *
Z *  AUTHOR(S)
Z *
Z *	Fred Fish		(base code)
Z *	(Currently at Motorola Computer Division, Tempe, Az.)
Z *	hao!noao!mcdsun!fnf
Z *	(602) 438-3614
Z *
Z *	Binayak Banerjee	(profiling enhancements)
Z *	seismo!bpa!sjuvax!bbanerje
Z */
Z
Z
Z#include <stdio.h>
Z
Z#ifdef AMIGA
Z#define HZ (50)			/* Probably in some header somewhere */
Z#endif
Z
Z/*
Z *	Manifest constants that should not require any changes.
Z */
Z
Z#define FALSE		0	/* Boolean FALSE */
Z#define TRUE		1	/* Boolean TRUE */
Z#define EOS		'\000'	/* End Of String marker */
Z
Z/*
Z *	Manifest constants which may be "tuned" if desired.
Z */
Z
Z#define PRINTBUF	1024	/* Print buffer size */
Z#define INDENT		4	/* Indentation per trace level */
Z#define MAXDEPTH	200	/* Maximum trace depth default */
Z
Z/*
Z *	The following flags are used to determine which
Z *	capabilities the user has enabled with the state
Z *	push macro.
Z */
Z
Z#define TRACE_ON	000001	/* Trace enabled */
Z#define DEBUG_ON	000002	/* Debug enabled */
Z#define FILE_ON 	000004	/* File name print enabled */
Z#define LINE_ON		000010	/* Line number print enabled */
Z#define DEPTH_ON	000020	/* Function nest level print enabled */
Z#define PROCESS_ON	000040	/* Process name print enabled */
Z#define NUMBER_ON	000100	/* Number each line of output */
Z#define PROFILE_ON	000200	/* Print out profiling code */
Z
Z#define TRACING (stack -> flags & TRACE_ON)
Z#define DEBUGGING (stack -> flags & DEBUG_ON)
Z#define PROFILING (stack -> flags & PROFILE_ON)
Z#define STREQ(a,b) (strcmp(a,b) == 0)
Z
Z/*
Z *	Typedefs to make things more obvious.
Z */
Z
Z#define VOID void		/* Can't use typedef for most compilers */
Ztypedef int BOOLEAN;
Z
Z/*
Z *	Make it easy to change storage classes if necessary.
Z */
Z
Z#define LOCAL static		/* Names not needed by outside world */
Z#define IMPORT extern		/* Names defined externally */
Z#define EXPORT			/* Allocated here, available globally */
Z#define AUTO auto		/* Names to be allocated on stack */
Z#define REGISTER register	/* Names to be placed in registers */
Z
Z/*
Z *	The following define is for the variable arguments kluge, see
Z *	the comments in _db_doprnt_().
Z *
Z *	Also note that the longer this list, the less prone to failing
Z *	on long argument lists, but the more stuff that must be moved
Z *	around for each call to the runtime support routines.  The
Z *	length may really be critical if the machine convention is
Z *	to pass arguments in registers.
Z *
Z *	Note that the default define allows up to 16 integral arguments,
Z *	or 8 floating point arguments (doubles), on most machines.
Z *
Z *	Someday this may be replaced with true varargs support, when
Z *	ANSI C has had time to take root.
Z */
Z
Z#define ARGLIST a0,a1,a2,a3,a4,a5,a6,a7,a8,a9,a10,a11,a12,a13,a14,a15
Z
Z/*
Z * The default file for profiling.  Could also add another flag
Z * (G?) which allowed the user to specify this.
Z */
Z
Z#define PROF_FILE	"dbugmon.out"
Z
Z/*
Z *	Variables which are available externally but should only
Z *	be accessed via the macro package facilities.
Z */
Z
ZEXPORT FILE *_db_fp_ = stderr;		/* Output stream, default stderr */
ZEXPORT FILE *_db_pfp_ = (FILE *)0;	/* Profile stream, 'dbugmon.out' */
ZEXPORT char *_db_process_ = "dbug";	/* Pointer to process name; argv[0] */
ZEXPORT BOOLEAN _db_on_ = FALSE;		/* TRUE if debugging currently on */
ZEXPORT BOOLEAN _db_pon_ = FALSE;	/* TRUE if debugging currently on */
Z
Z/*
Z *	Externally supplied functions.
Z */
Z
Z#ifdef unix			/* Only needed for unix */
ZIMPORT VOID perror ();		/* Print system/library error */
ZIMPORT int chown ();		/* Change owner of a file */
ZIMPORT int getgid ();		/* Get real group id */
ZIMPORT int getuid ();		/* Get real user id */
ZIMPORT int access ();		/* Test file for access */
Z#else
Z#if !(AMIGA && LATTICE)
ZLOCAL VOID perror ();		/* Fake system/library error print routine */
Z#endif
Z#endif
Z
Z# if BSD4_3 || sun
ZIMPORT int getrusage ();
Z#endif
Z
ZIMPORT int atoi ();		/* Convert ascii to integer */
ZIMPORT VOID exit ();		/* Terminate execution */
ZIMPORT int fclose ();		/* Close a stream */
ZIMPORT FILE *fopen ();		/* Open a stream */
ZIMPORT int fprintf ();		/* Formatted print on file */
ZIMPORT VOID free ();
ZIMPORT char *malloc ();		/* Allocate memory */
ZIMPORT int strcmp ();		/* Compare strings */
ZIMPORT char *strcpy ();		/* Copy strings around */
ZIMPORT int strlen ();		/* Find length of string */
Z
Z#ifndef fflush			/* This is sometimes a macro */
ZIMPORT int fflush ();		/* Flush output for stream */
Z#endif
Z
Z
Z/*
Z *	The user may specify a list of functions to trace or 
Z *	debug.  These lists are kept in a linear linked list,
Z *	a very simple implementation.
Z */
Z
Zstruct link {
Z    char *string;		/* Pointer to link's contents */
Z    struct link *next_link;	/* Pointer to the next link */
Z};
Z
Z
Z/*
Z *	Debugging states can be pushed or popped off of a
Z *	stack which is implemented as a linked list.  Note
Z *	that the head of the list is the current state and the
Z *	stack is pushed by adding a new state to the head of the
Z *	list or popped by removing the first link.
Z */
Z
Zstruct state {
Z    int flags;				/* Current state flags */
Z    int maxdepth;			/* Current maximum trace depth */
Z    unsigned int delay;			/* Delay after each output line */
Z    int level;				/* Current function nesting level */
Z    FILE *out_file;			/* Current output stream */
Z    FILE *prof_file;			/* Current profiling stream */
Z    struct link *functions;		/* List of functions */
Z    struct link *p_functions;		/* List of profiled functions */
Z    struct link *keywords;		/* List of debug keywords */
Z    struct link *processes;		/* List of process names */
Z    struct state *next_state;		/* Next state in the list */
Z};
Z
ZLOCAL struct state *stack = NULL;	/* Linked list of stacked states */
Z
Z/*
Z *	Local variables not seen by user.
Z */
Z
ZLOCAL int lineno = 0;		/* Current debugger output line number */
ZLOCAL char *func = "?func";	/* Name of current user function */
ZLOCAL char *file = "?file";	/* Name of current user file */
ZLOCAL BOOLEAN init_done = FALSE;/* Set to TRUE when initialization done */
Z
Z#if unix || AMIGA
ZLOCAL int jmplevel;		/* Remember nesting level at setjmp () */
ZLOCAL char *jmpfunc;		/* Remember current function for setjmp */
ZLOCAL char *jmpfile;		/* Remember current file for setjmp */
Z#endif
Z
ZLOCAL struct link *ListParse ();/* Parse a debug command string */
ZLOCAL char *StrDup ();		/* Make a fresh copy of a string */
ZLOCAL VOID OpenFile ();		/* Open debug output stream */
ZLOCAL VOID OpenProfile ();	/* Open profile output stream */
ZLOCAL VOID CloseFile ();	/* Close debug output stream */
ZLOCAL VOID PushState ();	/* Push current debug state */
ZLOCAL VOID ChangeOwner ();	/* Change file owner and group */
ZLOCAL BOOLEAN DoTrace ();	/* Test for tracing enabled */
ZLOCAL BOOLEAN Writable ();	/* Test to see if file is writable */
ZLOCAL unsigned long Clock ();	/* Return current user time (ms) */
ZLOCAL char *DbugMalloc ();	/* Allocate memory for runtime support */
ZLOCAL char *BaseName ();	/* Remove leading pathname components */
ZLOCAL VOID DoPrefix ();		/* Print debugger line prefix */
ZLOCAL VOID FreeList ();		/* Free memory from linked list */
ZLOCAL VOID Indent ();		/* Indent line to specified indent */
Z
Z				/* Supplied in Sys V runtime environ */
ZLOCAL char *strtok ();		/* Break string into tokens */
ZLOCAL char *strrchr ();		/* Find last occurance of char */
Z
Z/*
Z *	The following local variables are used to hold the state information
Z *	between the call to _db_pargs_() and _db_doprnt_(), during
Z *	expansion of the DBUG_PRINT macro.  This is the only macro
Z *	that currently uses these variables.  The DBUG_PRINT macro
Z *	and the new _db_doprnt_() routine replace the older DBUG_N macros
Z *	and their corresponding runtime support routine _db_printf_().
Z *
Z *	These variables are currently used only by _db_pargs_() and
Z *	_db_doprnt_().
Z */
Z
ZLOCAL int u_line = 0;		/* User source code line number */
ZLOCAL char *u_keyword = "?";	/* Keyword for current macro */
Z
Z/*
Z *	Miscellaneous printf format strings.
Z */
Z 
Z#define ERR_MISSING_RETURN "%s: missing DBUG_RETURN or DBUG_VOID_RETURN macro in function \"%s\"\n"
Z#define ERR_OPEN "%s: can't open debug output stream \"%s\": "
Z#define ERR_CLOSE "%s: can't close debug file: "
Z#define ERR_ABORT "%s: debugger aborting because %s\n"
Z#define ERR_CHOWN "%s: can't change owner/group of \"%s\": "
Z#define ERR_PRINTF "%s: obsolete object file for '%s', please recompile!\n"
Z
Z/*
Z *	Macros and defines for testing file accessibility under UNIX.
Z */
Z
Z#ifdef unix
Z#  define A_EXISTS	00		/* Test for file existance */
Z#  define A_EXECUTE	01		/* Test for execute permission */
Z#  define A_WRITE	02		/* Test for write access */
Z#  define A_READ	03		/* Test for read access */
Z#  define EXISTS(pathname) (access (pathname, A_EXISTS) == 0)
Z#  define WRITABLE(pathname) (access (pathname, A_WRITE) == 0)
Z#else
Z#  define EXISTS(pathname) (FALSE)	/* Assume no existance */
Z#endif
Z
Z/*
Z *	Translate some calls among different systems.
Z */
Z
Z#ifdef unix
Z# define Delay sleep
ZIMPORT unsigned int sleep ();	/* Pause for given number of seconds */
Z#endif
Z
Z#ifdef AMIGA
ZIMPORT int Delay ();		/* Pause for given number of ticks */
Z#endif
Z
Z
Z/*
Z *  FUNCTION
Z *
Z *	_db_push_    push current debugger state and set up new one
Z *
Z *  SYNOPSIS
Z *
Z *	VOID _db_push_ (control)
Z *	char *control;
Z *
Z *  DESCRIPTION
Z *
Z *	Given pointer to a debug control string in "control", pushes
Z *	the current debug state, parses the control string, and sets
Z *	up a new debug state.
Z *
Z *	The only attribute of the new state inherited from the previous
Z *	state is the current function nesting level.  This can be
Z *	overridden by using the "r" flag in the control string.
Z *
Z *	The debug control string is a sequence of colon separated fields
Z *	as follows:
Z *
Z *		<field_1>:<field_2>:...:<field_N>
Z *
Z *	Each field consists of a mandatory flag character followed by
Z *	an optional "," and comma separated list of modifiers:
Z *
Z *		flag[,modifier,modifier,...,modifier]
Z *
Z *	The currently recognized flag characters are:
Z *
Z *		d	Enable output from DBUG_<N> macros for
Z *			for the current state.  May be followed
Z *			by a list of keywords which selects output
Z *			only for the DBUG macros with that keyword.
Z *			A null list of keywords implies output for
Z *			all macros.
Z *
Z *		D	Delay after each debugger output line.
Z *			The argument is the number of tenths of seconds
Z *			to delay, subject to machine capabilities.
Z *			I.E.  -#D,20 is delay two seconds.
Z *
Z *		f	Limit debugging and/or tracing, and profiling to the
Z *			list of named functions.  Note that a null list will
Z *			disable all functions.  The appropriate "d" or "t"
Z *			flags must still be given, this flag only limits their
Z *			actions if they are enabled.
Z *
Z *		F	Identify the source file name for each
Z *			line of debug or trace output.
Z *
Z *		g	Enable profiling.  Create a file called 'dbugmon.out'
Z *			containing information that can be used to profile
Z *			the program.  May be followed by a list of keywords
Z *			that select profiling only for the functions in that
Z *			list.  A null list implies that all functions are
Z *			considered.
Z *
Z *		L	Identify the source file line number for
Z *			each line of debug or trace output.
Z *
Z *		n	Print the current function nesting depth for
Z *			each line of debug or trace output.
Z *	
Z *		N	Number each line of dbug output.
Z *
Z *		p	Limit debugger actions to specified processes.
Z *			A process must be identified with the
Z *			DBUG_PROCESS macro and match one in the list
Z *			for debugger actions to occur.
Z *
Z *		P	Print the current process name for each
Z *			line of debug or trace output.
Z *
Z *		r	When pushing a new state, do not inherit
Z *			the previous state's function nesting level.
Z *			Useful when the output is to start at the
Z *			left margin.
Z *
Z *		t	Enable function call/exit trace lines.
Z *			May be followed by a list (containing only
Z *			one modifier) giving a numeric maximum
Z *			trace level, beyond which no output will
Z *			occur for either debugging or tracing
Z *			macros.  The default is a compile time
Z *			option.
Z *
Z *	Some examples of debug control strings which might appear
Z *	on a shell command line (the "-#" is typically used to
Z *	introduce a control string to an application program) are:
Z *
Z *		-#d:t
Z *		-#d:f,main,subr1:F:L:t,20
Z *		-#d,input,output,files:n
Z *
Z *	For convenience, any leading "-#" is stripped off.
Z *
Z */
Z
Z
ZVOID _db_push_ (control)
Zchar *control;
Z{
Z    REGISTER char *scan;
Z    REGISTER struct link *temp;
Z
Z    if (control && *control == '-') {
Z	if (*++control == '#') {
Z	    control++;
Z	}	
Z    }
Z    control = StrDup (control);
Z    PushState ();
Z    scan = strtok (control, ":");
Z    for (; scan != NULL; scan = strtok ((char *)NULL, ":")) {
Z	switch (*scan++) {
Z	    case 'd': 
Z		_db_on_ = TRUE;
Z		stack -> flags |= DEBUG_ON;
Z		if (*scan++ == ',') {
Z		    stack -> keywords = ListParse (scan);
Z		}
Z	    	break;
Z	    case 'D': 
Z		stack -> delay = 0;
Z		if (*scan++ == ',') {
Z		    temp = ListParse (scan);
Z		    stack -> delay = DelayArg (atoi (temp -> string));
Z		    FreeList (temp);
Z		}
Z		break;
Z	    case 'f': 
Z		if (*scan++ == ',') {
Z		    stack -> functions = ListParse (scan);
Z		}
Z		break;
Z	    case 'F': 
Z		stack -> flags |= FILE_ON;
Z		break;
Z	    case 'g': 
Z		_db_pon_ = TRUE;
Z		OpenProfile(PROF_FILE);
Z		stack -> flags |= PROFILE_ON;
Z		if (*scan++ == ',') {
Z		    stack -> p_functions = ListParse (scan);
Z		}
Z		break;
Z	    case 'L': 
Z		stack -> flags |= LINE_ON;
Z		break;
Z	    case 'n': 
Z		stack -> flags |= DEPTH_ON;
Z		break;
Z	    case 'N':
Z		stack -> flags |= NUMBER_ON;
Z		break;
Z	    case 'o': 
Z		if (*scan++ == ',') {
Z		    temp = ListParse (scan);
Z		    OpenFile (temp -> string);
Z		    FreeList (temp);
Z		} else {
Z		    OpenFile ("-");
Z		}
Z		break;
Z	    case 'p':
Z		if (*scan++ == ',') {
Z		    stack -> processes = ListParse (scan);
Z		}
Z		break;
Z	    case 'P': 
Z		stack -> flags |= PROCESS_ON;
Z		break;
Z	    case 'r': 
Z		stack -> level = 0;
Z		break;
Z	    case 't': 
Z		stack -> flags |= TRACE_ON;
Z		if (*scan++ == ',') {
Z		    temp = ListParse (scan);
Z		    stack -> maxdepth = atoi (temp -> string);
Z		    FreeList (temp);
Z		}
Z		break;
Z	}
Z    }
Z    free (control);
Z}
Z
Z
Z
Z/*
Z *  FUNCTION
Z *
Z *	_db_pop_    pop the debug stack
Z *
Z *  DESCRIPTION
Z *
Z *	Pops the debug stack, returning the debug state to its
Z *	condition prior to the most recent _db_push_ invocation.
Z *	Note that the pop will fail if it would remove the last
Z *	valid state from the stack.  This prevents user errors
Z *	in the push/pop sequence from screwing up the debugger.
Z *	Maybe there should be some kind of warning printed if the
Z *	user tries to pop too many states.
Z *
Z */
Z
ZVOID _db_pop_ ()
Z{
Z    REGISTER struct state *discard;
Z
Z    discard = stack;
Z    if (discard != NULL && discard -> next_state != NULL) {
Z	stack = discard -> next_state;
Z	_db_fp_ = stack -> out_file;
Z	_db_pfp_ = stack -> prof_file;
Z	if (discard -> keywords != NULL) {
Z	    FreeList (discard -> keywords);
Z	}
Z	if (discard -> functions != NULL) {
Z	    FreeList (discard -> functions);
Z	}
Z	if (discard -> processes != NULL) {
Z	    FreeList (discard -> processes);
Z	}
Z	if (discard -> p_functions != NULL) {
Z	    FreeList (discard -> p_functions);
Z	}
Z	CloseFile (discard -> out_file);
Z	CloseFile (discard -> prof_file);
Z	free ((char *) discard);
Z    }
Z}
Z
Z
Z/*
Z *  FUNCTION
Z *
Z *	_db_enter_    process entry point to user function
Z *
Z *  SYNOPSIS
Z *
Z *	VOID _db_enter_ (_func_, _file_, _line_, _sfunc_, _sfile_, _slevel_)
Z *	char *_func_;		points to current function name
Z *	char *_file_;		points to current file name
Z *	int _line_;		called from source line number
Z *	char **_sfunc_;		save previous _func_
Z *	char **_sfile_;		save previous _file_
Z *	int *_slevel_;		save previous nesting level
Z *
Z *  DESCRIPTION
Z *
Z *	Called at the beginning of each user function to tell
Z *	the debugger that a new function has been entered.
Z *	Note that the pointers to the previous user function
Z *	name and previous user file name are stored on the
Z *	caller's stack (this is why the ENTER macro must be
Z *	the first "executable" code in a function, since it
Z *	allocates these storage locations).  The previous nesting
Z *	level is also stored on the callers stack for internal
Z *	self consistency checks.
Z *
Z *	Also prints a trace line if tracing is enabled and
Z *	increments the current function nesting depth.
Z *
Z *	Note that this mechanism allows the debugger to know
Z *	what the current user function is at all times, without
Z *	maintaining an internal stack for the function names.
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    if (!init_done) {
Z	_db_push_ ("");
Z    }
Z    *_sfunc_ = func;
Z    *_sfile_ = file;
Z    func = _func_;
Z    file = BaseName (_file_);
Z    stack -> level++;
Z    *_slevel_ = stack -> level;
Z    if (DoProfile ()) {
Z	(VOID) fprintf (_db_pfp_, "%s\tE\t%ld\n",func, Clock());
Z	(VOID) fflush (_db_pfp_);
Z    }
Z    if (DoTrace ()) {
Z	DoPrefix (_line_);
Z	Indent (stack -> level);
Z	(VOID) fprintf (_db_fp_, ">%s\n", func);
Z	(VOID) fflush (_db_fp_);
Z	(VOID) Delay (stack -> delay);
Z    }
Z}
Z
Z
Z/*
Z *  FUNCTION
Z *
Z *	_db_return_    process exit from user function
Z *
Z *  SYNOPSIS
Z *
Z *	VOID _db_return_ (_line_, _sfunc_, _sfile_, _slevel_)
Z *	int _line_;		current source line number
Z *	char **_sfunc_;		where previous _func_ is to be retrieved
Z *	char **_sfile_;		where previous _file_ is to be retrieved
Z *	int *_slevel_;		where previous level was stashed
Z *
Z *  DESCRIPTION
Z *
Z *	Called just before user function executes an explicit or implicit
Z *	return.  Prints a trace line if trace is enabled, decrements
Z *	the current nesting level, and restores the current function and
Z *	file names from the defunct function's stack.
Z *
Z */
Z
ZVOID _db_return_ (_line_, _sfunc_, _sfile_, _slevel_)
Zint _line_;
Zchar **_sfunc_;
Zchar **_sfile_;
Zint *_slevel_;
Z{
Z    if (!init_done) {
Z	_db_push_ ("");
Z    }
Z    if (stack -> level != *_slevel_ && (TRACING || DEBUGGING || PROFILING)) {
Z	(VOID) fprintf (_db_fp_, ERR_MISSING_RETURN, _db_process_, func);
Z    } else if (DoProfile ()) {
Z	(VOID) fprintf (_db_pfp_, "%s\tX\t%ld\n", func, Clock());
Z    } else if (DoTrace ()) {
Z	DoPrefix (_line_);
Z	Indent (stack -> level);
Z	(VOID) fprintf (_db_fp_, "<%s\n", func);
Z    }
Z    (VOID) fflush (_db_fp_);
Z    (VOID) Delay (stack -> delay);
Z    stack -> level = *_slevel_ - 1;
Z    func = *_sfunc_;
Z    file = *_sfile_;
Z}
Z
Z
Z/*
Z *  FUNCTION
Z *
Z *	_db_pargs_    log arguments for subsequent use by _db_doprnt_()
Z *
Z *  SYNOPSIS
Z *
Z *	VOID _db_pargs_ (_line_, keyword)
Z *	int _line_;
Z *	char *keyword;
Z *
Z *  DESCRIPTION
Z *
Z *	The new universal printing macro DBUG_PRINT, which replaces
Z *	all forms of the DBUG_N macros, needs two calls to runtime
Z *	support routines.  The first, this function, remembers arguments
Z *	that are used by the subsequent call to _db_doprnt_().
Z*
Z */
Z
ZVOID _db_pargs_ (_line_, keyword)
Zint _line_;
Zchar *keyword;
Z{
Z    u_line = _line_;
Z    u_keyword = keyword;
Z}
Z
Z
Z/*
Z *  FUNCTION
Z *
Z *	_db_doprnt_    handle print of debug lines
Z *
Z *  SYNOPSIS
Z *
Z *	VOID _db_doprnt_ (format, ARGLIST)
Z *	char *format;
Z *	long ARGLIST;
Z *
Z *  DESCRIPTION
Z *
Z *	When invoked via one of the DBUG macros, tests the current keyword
Z *	set by calling _db_pargs_() to see if that macro has been selected
Z *	for processing via the debugger control string, and if so, handles
Z *	printing of the arguments via the format string.  The line number
Z *	of the DBUG macro in the source is found in u_line.
Z *
Z *	Note that the format string SHOULD NOT include a terminating
Z *	newline, this is supplied automatically.
Z *
Z *  NOTES
Z *
Z *	This runtime support routine replaces the older _db_printf_()
Z *	routine which is temporarily kept around for compatibility.
Z *
Z *	The rather ugly argument declaration is to handle some
Z *	magic with respect to the number of arguments passed
Z *	via the DBUG macros.  The current maximum is 3 arguments
Z *	(not including the keyword and format strings).
Z *
Z *	The new <varargs.h> facility is not yet common enough to
Z *	convert to it quite yet...
Z *
Z */
Z
Z/*VARARGS1*/
ZVOID _db_doprnt_ (format, ARGLIST)
Zchar *format;
Zlong ARGLIST;
Z{
Z    if (_db_keyword_ (u_keyword)) {
Z	DoPrefix (u_line);
Z	if (TRACING) {
Z	    Indent (stack -> level + 1);
Z	} else {
Z	    (VOID) fprintf (_db_fp_, "%s: ", func);
Z	}
Z	(VOID) fprintf (_db_fp_, "%s: ", u_keyword);
Z	(VOID) fprintf (_db_fp_, format, ARGLIST);
Z	(VOID) fprintf (_db_fp_, "\n");
Z	(VOID) fflush (_db_fp_);
Z	(VOID) Delay (stack -> delay);
Z    }
Z}
Z
Z/*
Z *	The following routine is kept around temporarily for compatibility
Z *	with older objects that were compiled with the DBUG_N macro form
Z *	of the print routine.  It will print a warning message on first
Z *	usage.  It will go away in subsequent releases...
Z */
Z
Z/*VARARGS3*/
ZVOID _db_printf_ (_line_, keyword, format, ARGLIST)
Zint _line_;
Zchar *keyword,  *format;
Zlong ARGLIST;
Z{
Z    static BOOLEAN firsttime = TRUE;
Z
Z    if (firsttime) {
Z	(VOID) fprintf (stderr, ERR_PRINTF, _db_process_, file);
Z	firsttime = FALSE;
Z    }
Z    _db_pargs_ (_line_, keyword);
Z    _db_doprnt_ (format, ARGLIST);
Z}
Z
Z
Z/*
Z *  FUNCTION
Z *
Z *	ListParse    parse list of modifiers in debug control string
Z *
Z *  SYNOPSIS
Z *
Z *	LOCAL struct link *ListParse (ctlp)
Z *	char *ctlp;
Z *
Z *  DESCRIPTION
Z *
Z *	Given pointer to a comma separated list of strings in "cltp",
Z *	parses the list, building a list and returning a pointer to it.
Z *	The original comma separated list is destroyed in the process of
Z *	building the linked list, thus it had better be a duplicate
Z *	if it is important.
Z *
Z *	Note that since each link is added at the head of the list,
Z *	the final list will be in "reverse order", which is not
Z *	significant for our usage here.
Z *
Z */
Z
ZLOCAL struct link *ListParse (ctlp)
Zchar *ctlp;
Z{
Z    REGISTER char *start;
Z    REGISTER struct link *new;
Z    REGISTER struct link *head;
Z
Z    head = NULL;
Z    while (*ctlp != EOS) {
Z	start = ctlp;
Z	while (*ctlp != EOS && *ctlp != ',') {
Z	    ctlp++;
Z	}
Z	if (*ctlp == ',') {
Z	    *ctlp++ = EOS;
Z	}
Z	new = (struct link *) DbugMalloc (sizeof (struct link));
Z	new -> string = StrDup (start);
Z	new -> next_link = head;
Z	head = new;
Z    }
Z    return (head);
Z}
Z
Z
Z/*
Z *  FUNCTION
Z *
Z *	InList    test a given string for member of a given list
Z *
Z *  SYNOPSIS
Z *
Z *	LOCAL BOOLEAN InList (linkp, cp)
Z *	struct link *linkp;
Z *	char *cp;
Z *
Z *  DESCRIPTION
Z *
Z *	Tests the string pointed to by "cp" to determine if it is in
Z *	the list pointed to by "linkp".  Linkp points to the first
Z *	link in the list.  If linkp is NULL then the string is treated
Z *	as if it is in the list (I.E all strings are in the null list).
Z *	This may seem rather strange at first but leads to the desired
Z *	operation if no list is given.  The net effect is that all
Z *	strings will be accepted when there is no list, and when there
Z *	is a list, only those strings in the list will be accepted.
Z *
Z */
Z
ZLOCAL BOOLEAN InList (linkp, cp)
Zstruct link *linkp;
Zchar *cp;
Z{
Z    REGISTER struct link *scan;
Z    REGISTER BOOLEAN accept;
Z
Z    if (linkp == NULL) {
Z	accept = TRUE;
Z    } else {
Z	accept = FALSE;
Z	for (scan = linkp; scan != NULL; scan = scan -> next_link) {
Z	    if (STREQ (scan -> string, cp)) {
Z		accept = TRUE;
Z		break;
Z	    }
Z	}
Z    }
Z    return (accept);
Z}
Z
Z
Z/*
Z *  FUNCTION
Z *
Z *	PushState    push current state onto stack and set up new one
Z *
Z *  SYNOPSIS
Z *
Z *	LOCAL VOID PushState ()
Z *
Z *  DESCRIPTION
Z *
Z *	Pushes the current state on the state stack, and initializes
Z *	a new state.  The only parameter inherited from the previous
Z *	state is the function nesting level.  This action can be
Z *	inhibited if desired, via the "r" flag.
Z *
Z *	The state stack is a linked list of states, with the new
Z *	state added at the head.  This allows the stack to grow
Z *	to the limits of memory if necessary.
Z *
Z */
Z
ZLOCAL VOID PushState ()
Z{
Z    REGISTER struct state *new;
Z
Z    new = (struct state *) DbugMalloc (sizeof (struct state));
Z    new -> flags = 0;
Z    new -> delay = 0;
Z    new -> maxdepth = MAXDEPTH;
Z    if (stack != NULL) {
Z	new -> level = stack -> level;
Z    } else {
Z	new -> level = 0;
Z    }
Z    new -> out_file = stderr;
Z    new -> functions = NULL;
Z    new -> p_functions = NULL;
Z    new -> keywords = NULL;
Z    new -> processes = NULL;
Z    new -> next_state = stack;
Z    stack = new;
Z    init_done = TRUE;
Z}
Z
Z
Z/*
Z *  FUNCTION
Z *
Z *	DoTrace    check to see if tracing is current enabled
Z *
Z *  SYNOPSIS
Z *
Z *	LOCAL BOOLEAN DoTrace ()
Z *
Z *  DESCRIPTION
Z *
Z *	Checks to see if tracing is enabled based on whether the
Z *	user has specified tracing, the maximum trace depth has
Z *	not yet been reached, the current function is selected,
Z *	and the current process is selected.  Returns TRUE if
Z *	tracing is enabled, FALSE otherwise.
Z *
Z */
Z
ZLOCAL BOOLEAN DoTrace ()
Z{
Z    REGISTER BOOLEAN trace;
Z
Z    trace = FALSE;
Z    if (TRACING) {
Z	if (stack -> level <= stack -> maxdepth) {
Z	    if (InList (stack -> functions, func)) {
Z		if (InList (stack -> processes, _db_process_)) {
Z		    trace = TRUE;
Z		}
Z	    }
Z	}
Z    }
Z    return (trace);
Z}
Z
Z
Z/*
Z *  FUNCTION
Z *
Z *	DoProfile    check to see if profiling is current enabled
Z *
Z *  SYNOPSIS
Z *
Z *	LOCAL BOOLEAN DoProfile ()
Z *
Z *  DESCRIPTION
Z *
Z *	Checks to see if profiling is enabled based on whether the
Z *	user has specified profiling, the maximum trace depth has
Z *	not yet been reached, the current function is selected,
Z *	and the current process is selected.  Returns TRUE if
Z *	profiling is enabled, FALSE otherwise.
Z *
Z */
Z
ZLOCAL BOOLEAN DoProfile ()
Z{
Z    REGISTER BOOLEAN profile;
Z
Z    profile = FALSE;
Z    if (PROFILING) {
Z	if (stack -> level <= stack -> maxdepth) {
Z	    if (InList (stack -> p_functions, func)) {
Z		if (InList (stack -> processes, _db_process_)) {
Z		    profile = TRUE;
Z		}
Z	    }
Z	}
Z    }
Z    return (profile);
Z}
Z
Z
Z/*
Z *  FUNCTION
Z *
Z *	_db_keyword_    test keyword for member of keyword list
Z *
Z *  SYNOPSIS
Z *
Z *	BOOLEAN _db_keyword_ (keyword)
Z *	char *keyword;
Z *
Z *  DESCRIPTION
Z *
Z *	Test a keyword to determine if it is in the currently active
Z *	keyword list.  As with the function list, a keyword is accepted
Z *	if the list is null, otherwise it must match one of the list
Z *	members.  When debugging is not on, no keywords are accepted.
Z *	After the maximum trace level is exceeded, no keywords are
Z *	accepted (this behavior subject to change).  Additionally,
Z *	the current function and process must be accepted based on
Z *	their respective lists.
Z *
Z *	Returns TRUE if keyword accepted, FALSE otherwise.
Z *
Z */
Z
ZBOOLEAN _db_keyword_ (keyword)
Zchar *keyword;
Z{
Z    REGISTER BOOLEAN accept;
Z
Z    if (!init_done) {
Z	_db_push_ ("");
Z    }
Z    accept = FALSE;
Z    if (DEBUGGING) {
Z	if (stack -> level <= stack -> maxdepth) {
Z	    if (InList (stack -> functions, func)) {
Z		if (InList (stack -> keywords, keyword)) {
Z		    if (InList (stack -> processes, _db_process_)) {
Z			accept = TRUE;
Z		    }
Z		}
Z	    }
Z	}
Z    }
Z    return (accept);
Z}
Z
Z
Z/*
Z *  FUNCTION
Z *
Z *	Indent    indent a line to the given indentation level
Z *
Z *  SYNOPSIS
Z *
Z *	LOCAL VOID Indent (indent)
Z *	int indent;
Z *
Z *  DESCRIPTION
Z *
Z *	Indent a line to the given level.  Note that this is
Z *	a simple minded but portable implementation.
Z *	There are better ways.
Z *
Z *	Also, the indent must be scaled by the compile time option
Z *	of character positions per nesting level.
Z *
Z */
Z
ZLOCAL VOID Indent (indent)
Zint indent;
Z{
Z    REGISTER int count;
Z    AUTO char buffer[PRINTBUF];
Z
Z    indent *= INDENT;
Z    for (count = 0; (count < (indent - INDENT)) && (count < (PRINTBUF - 1)); count++) {
Z	if ((count % INDENT) == 0) {
Z	    buffer[count] = '|';
Z	} else {
Z	    buffer[count] = ' ';
Z	}
Z    }
Z    buffer[count] = EOS;
Z    (VOID) fprintf (_db_fp_, buffer);
Z    (VOID) fflush (_db_fp_);
Z}
Z
Z
Z/*
Z *  FUNCTION
Z *
Z *	FreeList    free all memory associated with a linked list
Z *
Z *  SYNOPSIS
Z *
Z *	LOCAL VOID FreeList (linkp)
Z *	struct link *linkp;
Z *
Z *  DESCRIPTION
Z *
Z *	Given pointer to the head of a linked list, frees all
Z *	memory held by the list and the members of the list.
Z *
Z */
Z
ZLOCAL VOID FreeList (linkp)
Zstruct link *linkp;
Z{
Z    REGISTER struct link *old;
Z
Z    while (linkp != NULL) {
Z	old = linkp;
Z	linkp = linkp -> next_link;
Z	if (old -> string != NULL) {
Z	    free (old -> string);
Z	}
Z	free ((char *) old);
Z    }
Z}
Z
Z
Z/*
Z *  FUNCTION
Z *
Z *	StrDup   make a duplicate of a string in new memory
Z *
Z *  SYNOPSIS
Z *
Z *	LOCAL char *StrDup (string)
Z *	char *string;
Z *
Z *  DESCRIPTION
Z *
Z *	Given pointer to a string, allocates sufficient memory to make
Z *	a duplicate copy, and copies the string to the newly allocated
Z *	memory.  Failure to allocated sufficient memory is immediately
Z *	fatal.
Z *
Z */
Z
Z
ZLOCAL char *StrDup (string)
Zchar *string;
Z{
Z    REGISTER char *new;
Z
Z    new = DbugMalloc (strlen (string) + 1);
Z    (VOID) strcpy (new, string);
Z    return (new);
Z}
Z
Z
Z/*
Z *  FUNCTION
Z *
Z *	DoPrefix    print debugger line prefix prior to indentation
Z *
Z *  SYNOPSIS
Z *
Z *	LOCAL VOID DoPrefix (_line_)
Z *	int _line_;
Z *
Z *  DESCRIPTION
Z *
Z *	Print prefix common to all debugger output lines, prior to
Z *	doing indentation if necessary.  Print such information as
Z *	current process name, current source file name and line number,
Z *	and current function nesting depth.
Z *
Z */
Z  
Z 
ZLOCAL VOID DoPrefix (_line_)
Zint _line_;
Z{
Z    lineno++;
Z    if (stack -> flags & NUMBER_ON) {
Z	(VOID) fprintf (_db_fp_, "%5d: ", lineno);
Z    }
Z    if (stack -> flags & PROCESS_ON) {
Z	(VOID) fprintf (_db_fp_, "%s: ", _db_process_);
Z    }
Z    if (stack -> flags & FILE_ON) {
Z	(VOID) fprintf (_db_fp_, "%14s: ", file);
Z    }
Z    if (stack -> flags & LINE_ON) {
Z	(VOID) fprintf (_db_fp_, "%5d: ", _line_);
Z    }
Z    if (stack -> flags & DEPTH_ON) {
Z	(VOID) fprintf (_db_fp_, "%4d: ", stack -> level);
Z    }
Z    (VOID) fflush (_db_fp_);
Z}
Z
Z
Z/*
Z *  FUNCTION
Z *
Z *	OpenFile    open new output stream for debugger output
Z *
Z *  SYNOPSIS
Z *
Z *	LOCAL VOID OpenFile (name)
Z *	char *name;
Z *
Z *  DESCRIPTION
Z *
Z *	Given name of a new file (or "-" for stdout) opens the file
Z *	and sets the output stream to the new file.
Z *
Z */
Z
ZLOCAL VOID OpenFile (name)
Zchar *name;
Z{
Z    REGISTER FILE *fp;
Z    REGISTER BOOLEAN newfile;
Z
Z    if (name != NULL) {
Z	if (strcmp (name, "-") == 0) {
Z	    _db_fp_ = stdout;
Z	    stack -> out_file = _db_fp_;
Z	} else {
Z	    if (!Writable (name)) {
Z		(VOID) fprintf (_db_fp_, ERR_OPEN, _db_process_, name);
Z		perror ("");
Z		(VOID) fflush (_db_fp_);
Z		(VOID) Delay (stack -> delay);
Z	    } else {
Z		if (EXISTS (name)) {
Z		    newfile = FALSE;
Z		} else {
Z		    newfile = TRUE;
Z		}
Z		fp = fopen (name, "a");
Z		if (fp == NULL) {
Z 		    (VOID) fprintf (_db_fp_, ERR_OPEN, _db_process_, name);
Z		    perror ("");
Z		    (VOID) fflush (_db_fp_);
Z		    (VOID) Delay (stack -> delay);
Z		} else {
Z		    _db_fp_ = fp;
Z		    stack -> out_file = fp;
Z		    if (newfile) {
Z			ChangeOwner (name);
Z		    }
Z		}
Z	    }
Z	}
Z    }
Z}
Z
Z
Z/*
Z *  FUNCTION
Z *
Z *	OpenProfile    open new output stream for profiler output
Z *
Z *  SYNOPSIS
Z *
Z *	LOCAL VOID OpenProfile (name)
Z *	char *name;
Z *
Z *  DESCRIPTION
Z *
Z *	Given name of a new file, opens the file
Z *	and sets the profiler output stream to the new file.
Z *
Z *	It is currently unclear whether the prefered behavior is
Z *	to truncate any existing file, or simply append to it.
Z *	The latter behavior would be desirable for collecting
Z *	accumulated runtime history over a number of separate
Z *	runs.  It might take some changes to the analyzer program
Z *	though, and the notes that Binayak sent with the profiling
Z *	diffs indicated that append was the normal mode, but this
Z *	does not appear to agree with the actual code. I haven't
Z *	investigated at this time [fnf; 24-Jul-87].
Z */
Z
ZLOCAL VOID OpenProfile (name)
Zchar *name;
Z{
Z    REGISTER FILE *fp;
Z    REGISTER BOOLEAN newfile;
Z
Z    if (name != NULL) {
Z	if (!Writable (name)) {
Z	    (VOID) fprintf (_db_fp_, ERR_OPEN, _db_process_, name);
Z	    perror ("");
Z	    (VOID) fflush (_db_fp_);
Z	    (VOID) Delay (stack -> delay);
Z	} else {
Z	    if (EXISTS (name)) {
Z		newfile = FALSE;
Z	    } else {
Z		newfile = TRUE;
Z	    }
Z	    fp = fopen (name, "w");
Z	    if (fp == NULL) {
Z		(VOID) fprintf (_db_fp_, ERR_OPEN, _db_process_, name);
Z		perror ("");
Z		(VOID) fflush (_db_fp_);
Z		(VOID) Delay (stack -> delay);
Z	    } else {
Z		_db_pfp_ = fp;
Z		stack -> prof_file = fp;
Z		if (newfile) {
Z		    ChangeOwner (name);
Z		}
Z	    }
Z	}
Z    }
Z}
Z
Z
Z/*
Z *  FUNCTION
Z *
Z *	CloseFile    close the debug output stream
Z *
Z *  SYNOPSIS
Z *
Z *	LOCAL VOID CloseFile (fp)
Z *	FILE *fp;
Z *
Z *  DESCRIPTION
Z *
Z *	Closes the debug output stream unless it is standard output
Z *	or standard error.
Z *
Z */
Z
ZLOCAL VOID CloseFile (fp)
ZFILE *fp;
Z{
Z    if (fp != stderr && fp != stdout) {
Z	if (fclose (fp) == EOF) {
Z	    (VOID) fprintf (stderr, ERR_CLOSE, _db_process_);
Z	    perror ("");
Z	    (VOID) fflush (stderr);
Z	    (VOID) Delay (stack -> delay);
Z	}
Z    }
Z}
Z
Z
Z/*
Z *  FUNCTION
Z *
Z *	DbugExit    print error message and exit
Z *
Z *  SYNOPSIS
Z *
Z *	LOCAL VOID DbugExit (why)
Z *	char *why;
Z *
Z *  DESCRIPTION
Z *
Z *	Prints error message using current process name, the reason for
Z *	aborting (typically out of memory), and exits with status 1.
Z *	This should probably be changed to use a status code
Z *	defined in the user's debugger include file.
Z *
Z */
Z 
ZLOCAL VOID DbugExit (why)
Zchar *why;
Z{
Z    (VOID) fprintf (stderr, ERR_ABORT, _db_process_, why);
Z    (VOID) fflush (stderr);
Z    (VOID) Delay (stack -> delay);
Z    exit (1);
Z}
Z
Z
Z/*
Z *  FUNCTION
Z *
Z *	DbugMalloc    allocate memory for debugger runtime support
Z *
Z *  SYNOPSIS
Z *
Z *	LOCAL char *DbugMalloc (size)
Z *	int size;
Z *
Z *  DESCRIPTION
Z *
Z *	Allocate more memory for debugger runtime support functions.
Z *	Failure to to allocate the requested number of bytes is
Z *	immediately fatal to the current process.  This may be
Z *	rather unfriendly behavior.  It might be better to simply
Z *	print a warning message, freeze the current debugger state,
Z *	and continue execution.
Z *
Z */
Z 
ZLOCAL char *DbugMalloc (size)
Zint size;
Z{
Z    register char *new;
Z
Z    new = malloc ((unsigned int) size);
Z    if (new == NULL) {
Z	DbugExit ("out of memory");
Z    }
Z    return (new);
Z}
Z
Z
Z/*
Z *	This function may be eliminated when strtok is available
Z *	in the runtime environment (missing from BSD4.1).
Z */
Z
ZLOCAL char *strtok (s1, s2)
Zchar *s1, *s2;
Z{
Z    static char *end = NULL;
Z    REGISTER char *rtnval;
Z
Z    rtnval = NULL;
Z    if (s2 != NULL) {
Z	if (s1 != NULL) {
Z	    end = s1;
Z	    rtnval = strtok ((char *) NULL, s2);
Z	} else if (end != NULL) {
Z	    if (*end != EOS) {
Z		rtnval = end;
Z		while (*end != *s2 && *end != EOS) {end++;}
Z		if (*end != EOS) {
Z		    *end++ = EOS;
Z		}
Z	    }
Z	}
Z    }
Z    return (rtnval);
Z}
Z
Z
Z/*
Z *  FUNCTION
Z *
Z *	BaseName    strip leading pathname components from name
Z *
Z *  SYNOPSIS
Z *
Z *	LOCAL char *BaseName (pathname)
Z *	char *pathname;
Z *
Z *  DESCRIPTION
Z *
Z *	Given pointer to a complete pathname, locates the base file
Z *	name at the end of the pathname and returns a pointer to
Z *	it.
Z *
Z */
Z
ZLOCAL char *BaseName (pathname)
Zchar *pathname;
Z{
Z    register char *base;
Z
Z    base = strrchr (pathname, '/');
Z    if (base++ == NULL) {
Z	base = pathname;
Z    }
Z    return (base);
Z}
Z
Z
Z/*
Z *  FUNCTION
Z *
Z *	Writable    test to see if a pathname is writable/creatable
Z *
Z *  SYNOPSIS
Z *
Z *	LOCAL BOOLEAN Writable (pathname)
Z *	char *pathname;
Z *
Z *  DESCRIPTION
Z *
Z *	Because the debugger might be linked in with a program that
Z *	runs with the set-uid-bit (suid) set, we have to be careful
Z *	about opening a user named file for debug output.  This consists
Z *	of checking the file for write access with the real user id,
Z *	or checking the directory where the file will be created.
Z *
Z *	Returns TRUE if the user would normally be allowed write or
Z *	create access to the named file.  Returns FALSE otherwise.
Z *
Z */
Z
ZLOCAL BOOLEAN Writable (pathname)
Zchar *pathname;
Z{
Z    REGISTER BOOLEAN granted;
Z#ifdef unix
Z    REGISTER char *lastslash;
Z#endif
Z
Z#ifndef unix
Z    granted = TRUE;
Z#else
Z    granted = FALSE;
Z    if (EXISTS (pathname)) {
Z	if (WRITABLE (pathname)) {
Z	    granted = TRUE;
Z	}
Z    } else {
Z	lastslash = strrchr (pathname, '/');
Z	if (lastslash != NULL) {
Z	    *lastslash = EOS;
Z	} else {
Z	    pathname = ".";
Z	}
Z	if (WRITABLE (pathname)) {
Z	    granted = TRUE;
Z	}
Z	if (lastslash != NULL) {
Z	    *lastslash = '/';
Z	}
Z    }
Z#endif
Z    return (granted);
Z}
Z
Z
Z/*
Z *	This function may be eliminated when strrchr is available
Z *	in the runtime environment (missing from BSD4.1).
Z *	Alternately, you can use rindex() on BSD systems.
Z */
Z
ZLOCAL char *strrchr (s, c)
Zchar *s;
Zchar c;
Z{
Z    REGISTER char *scan;
Z
Z    for (scan = s; *scan != EOS; scan++) {;}
Z    while (scan > s && *--scan != c) {;}
Z    if (*scan != c) {
Z	scan = NULL;
Z    }
Z    return (scan);
Z}
Z
Z
Z/*
Z *  FUNCTION
Z *
Z *	ChangeOwner    change owner to real user for suid programs
Z *
Z *  SYNOPSIS
Z *
Z *	LOCAL VOID ChangeOwner (pathname)
Z *
Z *  DESCRIPTION
Z *
Z *	For unix systems, change the owner of the newly created debug
Z *	file to the real owner.  This is strictly for the benefit of
Z *	programs that are running with the set-user-id bit set.
Z *
Z *	Note that at this point, the fact that pathname represents
Z *	a newly created file has already been established.  If the
Z *	program that the debugger is linked to is not running with
Z *	the suid bit set, then this operation is redundant (but
Z *	harmless).
Z *
Z */
Z
ZLOCAL VOID ChangeOwner (pathname)
Zchar *pathname;
Z{
Z#ifdef unix
Z    if (chown (pathname, getuid (), getgid ()) == -1) {
Z	(VOID) fprintf (stderr, ERR_CHOWN, _db_process_, pathname);
Z	perror ("");
Z	(VOID) fflush (stderr);
Z	(VOID) Delay (stack -> delay);
Z    }
Z#endif
Z}
Z
Z
Z/*
Z *  FUNCTION
Z *
Z *	_db_setjmp_    save debugger environment
Z *
Z *  SYNOPSIS
Z *
Z *	VOID _db_setjmp_ ()
Z *
Z *  DESCRIPTION
Z *
Z *	Invoked as part of the user's DBUG_SETJMP macro to save
Z *	the debugger environment in parallel with saving the user's
Z *	environment.
Z *
Z */
Z
ZVOID _db_setjmp_ ()
Z{
Z   jmplevel = stack -> level;
Z   jmpfunc = func;
Z   jmpfile = file;
Z}
Z
Z
Z/*
Z *  FUNCTION
Z *
Z *	_db_longjmp_    restore previously saved debugger environment
Z *
Z *  SYNOPSIS
Z *
Z *	VOID _db_longjmp_ ()
Z *
Z *  DESCRIPTION
Z *
Z *	Invoked as part of the user's DBUG_LONGJMP macro to restore
Z *	the debugger environment in parallel with restoring the user's
Z *	previously saved environment.
Z *
Z */
Z
ZVOID _db_longjmp_ ()
Z{
Z    stack -> level = jmplevel;
Z    if (jmpfunc) {
Z	func = jmpfunc;
Z    }
Z    if (jmpfile) {
Z	file = jmpfile;
Z    }
Z}
Z
Z
Z/*
Z *  FUNCTION
Z *
Z *	DelayArg   convert D flag argument to appropriate value
Z *
Z *  SYNOPSIS
Z *
Z *	LOCAL int DelayArg (value)
Z *	int value;
Z *
Z *  DESCRIPTION
Z *
Z *	Converts delay argument, given in tenths of a second, to the
Z *	appropriate numerical argument used by the system to delay
Z *	that that many tenths of a second.  For example, on the
Z *	AMIGA, there is a system call "Delay()" which takes an
Z *	argument in ticks (50 per second).  On unix, the sleep
Z *	command takes seconds.  Thus a value of "10", for one
Z *	second of delay, gets converted to 50 on the amiga, and 1
Z *	on unix.  Other systems will need to use a timing loop.
Z *
Z */
Z
ZLOCAL int DelayArg (value)
Zint value;
Z{
Z    int delayarg = 0;
Z    
Z#ifdef unix
Z    delayarg = value / 10;		/* Delay is in seconds for sleep () */
Z#endif
Z#ifdef AMIGA
Z    delayarg = (HZ * value) / 10;	/* Delay in ticks for Delay () */
Z#endif
Z    return (delayarg);
Z}
Z
Z
Z/*
Z *	A dummy delay stub for systems that do not support delays.
Z *	With a little work, this can be turned into a timing loop.
Z */
Z
Z#ifndef unix
Z#ifndef AMIGA
ZDelay ()
Z{
Z}
Z#endif
Z#endif
Z
Z
Z/*
Z *  FUNCTION
Z *
Z *	perror    perror simulation for systems that don't have it
Z *
Z *  SYNOPSIS
Z *
Z *	LOCAL VOID perror (s)
Z *	char *s;
Z *
Z *  DESCRIPTION
Z *
Z *	Perror produces a message on the standard error stream which
Z *	provides more information about the library or system error
Z *	just encountered.  The argument string s is printed, followed
Z *	by a ':', a blank, and then a message and a newline.
Z *
Z *	An undocumented feature of the unix perror is that if the string
Z *	's' is a null string (NOT a NULL pointer!), then the ':' and
Z *	blank are not printed.
Z *
Z *	This version just complains about an "unknown system error".
Z *
Z */
Z
Z#if !unix && !(AMIGA && LATTICE)
ZLOCAL VOID perror (s)
Zchar *s;
Z{
Z    if (s && *s != EOS) {
Z	(VOID) fprintf (stderr, "%s: ", s);
Z    }
Z    (VOID) fprintf (stderr, "<unknown system error>\n");
Z}
Z#endif	/* !unix && !(AMIGA && LATTICE) */
Z
Z/*
Z * Here we need the definitions of the clock routine.  Add your
Z * own for whatever system that you have.
Z */
Z
Z#if unix
Z
Z# include <sys/param.h>
Z# if BSD4_3 || sun
Z
Z/*
Z * Definition of the Clock() routine for 4.3 BSD.
Z */
Z
Z#include <sys/time.h>
Z#include <sys/resource.h>
Z
Z/*
Z * Returns the user time in milliseconds used by this process so
Z * far.
Z */
Z
ZLOCAL unsigned long Clock ()
Z{
Z    struct rusage ru;
Z
Z    (VOID) getrusage (RUSAGE_SELF, &ru);
Z    return ((ru.ru_utime.tv_sec * 1000) + (ru.ru_utime.tv_usec / 1000));
Z}
Z
Z#else
Z
ZLOCAL unsigned long Clock ()
Z{
Z    return (0);
Z}
Z
Z# endif
Z
Z#else
Z
Z#if AMIGA
Z
Zstruct DateStamp {		/* Yes, this is a hack, but doing it right */
Z	long ds_Days;		/* is incredibly ugly without splitting this */
Z	long ds_Minute;		/* off into a separate file */
Z	long ds_Tick;
Z};
Z
Zstatic int first_clock = TRUE;
Zstatic struct DateStamp begin;
Zstatic struct DateStamp elapsed;
Z
ZLOCAL unsigned long Clock ()
Z{
Z    register struct DateStamp *now;
Z    register unsigned long millisec = 0;
Z    extern VOID *AllocMem ();
Z
Z    now = (struct DateStamp *) AllocMem ((long) sizeof (struct DateStamp), 0L);
Z    if (now != NULL) {
Z	if (first_clock == TRUE) {
Z	    first_clock = FALSE;
Z	    (VOID) DateStamp (now);
Z	    begin = *now;
Z	}
Z	(VOID) DateStamp (now);
Z	millisec = 24 * 3600 * (1000 / HZ) * (now -> ds_Days - begin.ds_Days);
Z	millisec += 60 * (1000 / HZ) * (now -> ds_Minute - begin.ds_Minute);
Z	millisec += (1000 / HZ) * (now -> ds_Tick - begin.ds_Tick);
Z	(VOID) FreeMem (now, (long) sizeof (struct DateStamp));
Z    }
Z    return (millisec);
Z}
Z
Z#endif	/* AMIGA */
Z#endif	/* unix */
STUNKYFLUFF
set `sum dbug.c`
if test 10401 != $1
then
echo dbug.c: Checksum error. Is: $1, should be: 10401.
fi
echo ALL DONE BUNKY!
exit 0
