mysql Appendix C (The debugging library)

Documentation Version: 0.80
mysql Version: 3.20.16

The Debugging Library

The debugging library used by mysql was originally written by Fred Fish. This stuff will be very useful if you plan on debugging and/or adding functionality to the mysql database system.

 Here's the header from the source file dbug.c, along with all the function header comments.

 *                                                                            *
 *                                 N O T I C E                                *
 *                                                                            *
 *                    Copyright Abandoned, 1987, Fred Fish                    *
 *                                                                            *
 *                                                                            *
 *      This previously copyrighted work has been placed into the  public     *
 *      domain  by  the  author  and  may be freely used for any purpose,     *
 *      private or commercial.                                                *
 *                                                                            *
 *      Because of the number of inquiries I was receiving about the  use     *
 *      of this product in commercially developed works I have decided to     *
 *      simply make it public domain to further its unrestricted use.   I     *
 *      specifically  would  be  most happy to see this material become a     *
 *      part of the standard Unix distributions by AT&T and the  Berkeley     *
 *      Computer  Science  Research Group, and a standard part of the GNU     *
 *      system from the Free Software Foundation.                             *
 *                                                                            *
 *      I would appreciate it, as a courtesy, if this notice is  left  in     *
 *      all copies and derivative works.  Thank you.                          *
 *                                                                            *
 *      The author makes no warranty of any kind  with  respect  to  this     *
 *      product  and  explicitly disclaims any implied warranties of mer-     *
 *      chantability or fitness for any particular purpose.                   *
 *                                                                            *

 *  FILE
 *      dbug.c   runtime support routines for dbug package
 *  SCCS
 *      @(#)dbug.c      1.25    7/25/89
 *      These are the runtime support routines for the dbug package.
 *      The dbug package has two main components; the user include
 *      file containing various macro definitions, and the runtime
 *      support routines which are called from the macro expansions.
 *      Externally visible functions in the runtime support module
 *      use the naming convention pattern "_db_xx...xx_", thus
 *      they are unlikely to collide with user defined function names.
 *      Fred Fish               (base code)
 *      Enhanced Software Technologies, Tempe, AZ
 *      asuvax!mcdphx!estinc!fnf
 *      Binayak Banerjee        (profiling enhancements)
 *      seismo!bpa!sjuvax!bbanerje
 *      Michael Widenius:
 *      DBUG_DUMP               - To dump a piece of memory.
 *      PUSH_FLAG "O"   - To be used instead of "o" if we don't
 *                        want flushing (for slow systems)
 *      Check of malloc on entry/exit (option "S")



Push current debugger state and set up new one.


       VOID _db_push_ (control)
       char *control;

 Given pointer to a debug control string in "control", pushes the current debug state, parses the control string, and sets up a new debug state.

 The only attribute of the new state inherited from the previous state is the current function nesting level. This can be overridden by using the "r" flag in the control string.

 The debug control string is a sequence of colon separated fields as follows:


 Each field consists of a mandatory flag character followed by an optional "," and comma separated list of modifiers:


 The currently recognized flag characters are:

Some examples of debug control strings which might appear on a shell command line (the "-#" is typically used to introduce a control string to an application program) are:
For convenience, any leading "-#" is stripped off.



 Pops the debug stack, returning the debug state to its condition prior to the most recent _db_push_ invocation. Note that the pop will fail if it would remove the last valid state from the stack. This prevents user errors in the push/pop sequence from screwing up the debugger. Maybe there should be some kind of warning printed if the user tries to pop too many states.



       VOID _db_enter_ (_func_, _file_, _line_,
                        _sfunc_, _sfile_, _slevel_, _sframep_)
       char *_func_;           points to current function name
       char *_file_;           points to current file name
       int _line_;             called from source line number
       char **_sfunc_;         save previous _func_
       char **_sfile_;         save previous _file_
       int *_slevel_;          save previous nesting level
       char ***_sframep_;      save previous frame pointer

 Called at the beginning of each user function to tell the debugger that a new function has been entered. Note that the pointers to the previous user function name and previous user file name are stored on the caller's stack (this is why the ENTER macro must be the first "executable" code in a function, since it allocates these storage locations). The previous nesting level is also stored on the callers stack for internal self consistency checks.

 Also prints a trace line if tracing is enabled and increments the current function nesting depth.

 Note that this mechanism allows the debugger to know what the current user function is at all times, without maintaining an internal stack for the function names.



       VOID _db_return_ (_line_, _sfunc_, _sfile_, _slevel_)
       int _line_;             current source line number
       char **_sfunc_;         where previous _func_ is to be retrieved
       char **_sfile_;         where previous _file_ is to be retrieved
       int *_slevel_;          where previous level was stashed

 Called just before user function executes an explicit or implicit return. Prints a trace line if trace is enabled, decrements the current nesting level, and restores the current function and file names from the defunct function's stack.


Log arguments for subsequent use by _db_doprnt_().


       VOID _db_pargs_ (_line_, keyword)
       int _line_;
       char *keyword;

 The new universal printing macro DBUG_PRINT, which replaces all forms of the DBUG_N macros, needs two calls to runtime support routines. The first, this function, remembers arguments that are used by the subsequent call to _db_doprnt_().


Handle print of debug lines.


       VOID _db_doprnt_ (format, va_alist)
       char *format;

 When invoked via one of the DBUG macros, tests the current keyword set by calling _db_pargs_() to see if that macro has been selected for processing via the debugger control string, and if so, handles printing of the arguments via the format string. The line number of the DBUG macro in the source is found in u_line.

 Note that the format string SHOULD NOT include a terminating newline, this is supplied automatically.


Dump a string until '\0' is found.


       void _db_dump_ (_line_,keyword,memory,length)
       int _line_;               current source line number
       char *keyword;
       char *memory;             Memory to print
       int length;               Bytes to print

 Dump N characters in a binary array. Is used to examine corrupted memory or arrays.


Parse list of modifiers in debug control string.


       static struct link *ListParse (ctlp)
       char *ctlp;

 Given pointer to a comma separated list of strings in "ctlp", parses the list, building a list and returning a pointer to it. The original comma separated list is destroyed in the process of building the linked list, thus it had better be a duplicate if it is important.

 Note that since each link is added at the head of the list, the final list will be in "reverse order", which is not significant for our usage here.


Test a given string for member of a given list.


       static BOOLEAN InList (linkp, cp)
       struct link *linkp;
       char *cp;

 Tests the string pointed to by "cp" to determine if it is in the list pointed to by "linkp". Linkp points to the first link in the list. If linkp is NULL then the string is treated as if it is in the list (I.E all strings are in the null list). This may seem rather strange at first but leads to the desired operation if no list is given. The net effect is that all strings will be accepted when there is no list, and when there is a list, only those strings in the list will be accepted.


Push current state onto stack and set up new one.


       static VOID PushState ()

 Pushes the current state on the state stack, and initializes a new state. The only parameter inherited from the previous state is the function nesting level. This action can be inhibited if desired, via the "r" flag.

 The state stack is a linked list of states, with the new state added at the head. This allows the stack to grow to the limits of memory if necessary.


Check to see if tracing is current enabled.


       static BOOLEAN DoTrace (stack)


 Checks to see if tracing is enabled based on whether the user has specified tracing, the maximum trace depth has not yet been reached, the current function is selected, and the current process is selected. Returns TRUE if tracing is enabled, FALSE otherwise.


Check to see if profiling is current enabled.


        static BOOLEAN DoProfile ()

 Checks to see if profiling is enabled based on whether the user has specified profiling, the maximum trace depth has not yet been reached, the current function is selected, and the current process is selected. Returns TRUE if profiling is enabled, FALSE otherwise.


Test keyword for member of keyword list.


       BOOLEAN _db_keyword_ (keyword)
       char *keyword;

 Test a keyword to determine if it is in the currently active keyword list. As with the function list, a keyword is accepted if the list is null, otherwise it must match one of the list members. When debugging is not on, no keywords are accepted. After the maximum trace level is exceeded, no keywords are accepted (this behavior subject to change). Additionally, the current function and process must be accepted based on their respective lists.

 Returns TRUE if keyword accepted, FALSE otherwise.


Indent a line to the given indentation level.


       static VOID Indent (indent)
       int indent;

 Indent a line to the given level. Note that this is a simple minded but portable implementation. There are better ways.

 Also, the indent must be scaled by the compile time option of character positions per nesting level.


Free all memory associated with a linked list.


        static VOID FreeList (linkp)
        struct link *linkp;

 Given pointer to the head of a linked list, frees all memory held by the list and the members of the list.


Make a duplicate of a string in new memory.


        static char *StrDup (string)
        char *string;

 Given pointer to a string, allocates sufficient memory to make a duplicate copy, and copies the string to the newly allocated memory. Failure to allocated sufficient memory is immediately fatal.


Print debugger line prefix prior to indentation.


        static VOID DoPrefix (_line_)
        int _line_;

 Print prefix common to all debugger output lines, prior to doing indentation if necessary. Print such information as current process name, current source file name and line number, and current function nesting depth.


Open new output stream for debugger output.


        static VOID OpenFile (name)
        char *name;

 Given name of a new file (or "-" for stdout) opens the file and sets the output stream to the new file.


Open new output stream for profiler output.


        static FILE *OpenProfile (name)
        char *name;

 Given name of a new file, opens the file and sets the profiler output stream to the new file.

 It is currently unclear whether the preferred behavior is to truncate any existing file, or simply append to it. The latter behavior would be desirable for collecting accumulated runtime history over a number of separate runs. It might take some changes to the analyzer program though, and the notes that Binayak sent with the profiling diffs indicated that append was the normal mode, but this does not appear to agree with the actual code. I haven't investigated at this time [fnf; 24-Jul-87].


Close the debug output stream.


        static VOID CloseFile (fp)
        FILE *fp;

 Closes the debug output stream unless it is standard output or standard error.


Print error message and exit.


        static VOID DbugExit (why)
        char *why;

 Prints error message using current process name, the reason for aborting (typically out of memory), and exits with status 1. This should probably be changed to use a status code defined in the user's debugger include file.


Allocate memory for debugger runtime support.


        static long *DbugMalloc (size)
        int size;

 Allocate more memory for debugger runtime support functions. Failure to to allocate the requested number of bytes is immediately fatal to the current process. This may be rather unfriendly behavior. It might be better to simply print a warning message, freeze the current debugger state, and continue execution.



   static char *static_strtok (s1, separator)

 As strtok but two separators in a row are changed to one separator (to allow directory-paths in DOS).


Strip leading pathname components from name.


        static char *BaseName (pathname)
        char *pathname;

 Given pointer to a complete pathname, locates the base file name at the end of the pathname and returns a pointer to it.


Test to see if a pathname is writable/create-able.


        static BOOLEAN Writable (pathname)
        char *pathname;

 Because the debugger might be linked in with a program that runs with the set-uid-bit (suid) set, we have to be careful about opening a user named file for debug output. This consists of checking the file for write access with the real user id, or checking the directory where the file will be created.

 Returns TRUE if the user would normally be allowed write or create access to the named file. Returns FALSE otherwise.


Change owner to real user for suid programs.


        static VOID ChangeOwner (pathname)

 For Unix systems, change the owner of the newly created debug file to the real owner. This is strictly for the benefit of programs that are running with the set-user-id bit set.

 Note that at this point, the fact that pathname represents a newly created file has already been established. If the program that the debugger is linked to is not running with the suid bit set, then this operation is redundant (but harmless).


Save debugger environment.


        VOID _db_setjmp_ ()

 Invoked as part of the user's DBUG_SETJMP macro to save the debugger environment in parallel with saving the user's environment.


Restore previously saved debugger environment.


        VOID _db_longjmp_ ()

 Invoked as part of the user's DBUG_LONGJMP macro to restore the debugger environment in parallel with restoring the user's previously saved environment.


Convert D flag argument to appropriate value.


        static int DelayArg (value)
        int value;

 Converts delay argument, given in tenths of a second, to the appropriate numerical argument used by the system to delay that that many tenths of a second. For example, on the Amiga, there is a system call "Delay()" which takes an argument in ticks (50 per second). On Unix, the sleep command takes seconds. Thus a value of "10", for one second of delay, gets converted to 50 on the Amiga, and 1 on Unix. Other systems will need to use a timing loop.


A perror simulation for systems that don't have it.


        static VOID perror (s)
        char *s;

 Perror produces a message on the standard error stream which provides more information about the library or system error just encountered. The argument string s is printed, followed by a ':', a blank, and then a message and a newline.

 An undocumented feature of the Unix perror is that if the string 's' is a null string (NOT a NULL pointer!), then the ':' and blank are not printed.

 This version just complains about an "unknown system error".