/****************************************************************************** * debug.c * Debugging functions. * * Copyright (c)1994-95 David R. Tribble, all rights reserved. * * 1.00 09-17-1994 drt. First cut. * 1.01 09-24-1994 drt. Split .c off from .cpp source. * 1.02 04-20-1995 drt. Added dbg_hexdump(). */ /* Identification */ static const char id[] = "@(#)1.02 04-20-1995 " __FILE__ ; /* Includes */ #include #include #include #include #include #include "debug.h" /* Private variables */ const char * dbg_fname = NULL; /* Public variables */ FILE * dbg_f = NULL; int dbg_flags = 0x0000; /****************************************************************************** * dbg_open * Open file name `fname' with mode `mode' as the debugging output. * * Returns * File pointer if successful, or NULL if not. */ FILE * dbg_open(const char *fname, const char *mode) { /* Check args */ if (fname == NULL) return NULL; if (mode == NULL) mode = "w"; /* Save off file name */ if (dbg_fname != NULL) free((char *)dbg_fname); dbg_fname = strdup(fname); /* Open debugging output file */ dbg_f = fopen(fname, mode); return dbg_f; } /****************************************************************************** * dbg_close * Close the debugging output file. * * Returns * Zero if successful, or -1 if not. */ int dbg_close(void) { int rc; /* Check that debugging output file is open */ if (dbg_f == NULL) return 0; /* Close debugging output file */ fflush(dbg_f); rc = fclose(dbg_f); if (rc != -1) dbg_f = NULL; return rc; } /****************************************************************************** * dbgf * Print formatted args to debugging output. * * Returns * Same value that vfprintf() returns. */ int dbgf(const char *fmt, ...) { va_list ap; int rc; /* Check for debugging output enabled */ if (dbg_f == NULL) return 0; /* Handle flags */ if (dbg_flags & DBG_REOPEN && dbg_fname != NULL) { /* Close debug output file */ fflush(dbg_f); fclose(dbg_f); dbg_f = NULL; /* Reopen debug output file */ dbg_f = fopen(dbg_fname, "a"); if (dbg_f == NULL) return -1; } /* Print formatted args */ va_start(ap, fmt); rc = vfprintf(dbg_f, fmt, ap); fflush(dbg_f); return rc; } /****************************************************************************** * dbg_hexdump * Dump contents of memory area `dat' of `len' bytes in hex and character * form to stream `dbg_fp'. * * Returns * `len'. */ int dbg_hexdump(const void *dat, unsigned len) { const unsigned char * d; int err; int inc; int i, j; /* Check args */ if (dbg_f == NULL) return -1; if (dat == NULL) return -1; if (len == 0) return 0; /* Dump data area */ err = errno; d = (const unsigned char *) dat; inc = (len <= 8) ? 0x08 : 0x10; for (i = 0; i < len; i += inc) { dbgf(" %04X ", i); for (j = 0; j < inc && i+j < len; j++) dbgf(" %.2X", d[i+j]); for (; j < inc; j++) dbgf(" .."); dbgf(" "); for (j = 0; j < inc && i+j < len; j++) dbgf("%c", isprint(d[i+j]) ? d[i+j] : '.'); dbgf("\n"); } errno = err; return len; } /* End debug.c */