Chapters:
1: Introduction
2: Simple example
3: Invocation
4: Finer Control
5: X-Y Plots
6: Contour Plots
7: Image Plots
8: Examples
9: Gri Commands
10: Programming
11: Environment
12: Emacs Mode
13: History
14: Installation
15: Gri Bugs
16: Test Suite
17: Gri in Press
18: Acknowledgments
19: License
Indices:
Concepts
Commands
Variables

## 15.3: Killing Bugs

- Debugging Software You Will Need:
- Debugging at a Glance:
- Debugging Example:

### 15.3.1: Software that you'll need

This section is intended to help you find and kill bugs yourself, by indicating how the author does this work. Since Gri is open-source, all users are invited to try to kill bugs themselves!

If you know nothing of C or C++, you may as well not read further, since there is little chance of your making progress. On the other hand, experienced programmers won't need any of the advice I give below.

You'll need the Gri source and a C++ compiler. It also helps if you have ``gdb`', the GNU debugger, installed; the instructions below assume that's the case. Also, the instructions assume that you're using the Emacs editor, and running ``gdb`' from within Emacs. Otherwise, you'll want to glance at the documentation on ``gdb`' to see how to use it in standalone mode.

### 15.3.2: Debugging at a glance

The list below is a sketch of what you might try, and in what order.

- Check the bug list to see if other users have found your bug, and also to see if there is a workaround.

- Try a more recent version of gri. If it works, you might wish to archive the version you have at the moment and upgrade.

- If you suspect your bug has something to do with system calls, as in the ``system`' command (see System) or as in piped input files (see Open), you should re-run the script with ``gri -superuser8`' instead of with ``gri`'. This will cause Gri to print out all commands that it is handing over to the operating system; you may see the error that way. (Hint: it may help to interactively cut/paste the commands into your OS shell to see what the action of the command is.)

- If your bug results in early termination, you should run Gri inside a debugger (e.g. GDB, assumed henceforth). When the program terminates, type ``where`' to see where termination occured. Often this will give a clue. In many cases, early termination results from faults in memory allocation. To check memory allocation, you'll need to recompile Gri, linking it against a debugging memory allocator. Many such tools exist; see comments in the ``Makefile`' for a hint at how to use a popular one, called ``Electric Fence.''

- If your bug does not result in early termination, you may find the best scheme is to trim your example down as much as possible, and then run Gri inside the GDB (or other debugger) so that you can monitor program execution. The next section explains this in detail.

### 15.3.3: A debugging Example

Let's take a recent bug as an example. Peter Galbraith found that the gri script

    set color hsb 0.999 1 1
    draw box filled 2 2 3 3 cm
    set color hsb 1.000 1 1
    draw box filled 4 2 5 3 cm

produced odd results in a previous version of Gri; the color patches should have been of nearly the same color, but the first one was red, as expected, and the second was magenta.

The list below shows how I found Peter's bug. Experienced C or C++ programmers will find all of this very familiar, and will really only need to read item 6 of the list below, since that's the only action that is really specific to Gri. (Note: for display purposes, I've broken some of the lines in the files into two lines in this list.)

1. Copy the above script (called ``test.gri`') into the Gri source directory, and the script into an Emacs buffer. Note: all the following steps are done within Emacs, and the items in parentheses are the Emacs keys to get the indicated actions.

2. If you're working from a pre-compiled version, you'll need to get the source first and do a compile yourself (see Uncompiled Unix). Then do a ``make tags`' command (type this to the unix shell) to create a so-called "tag" table.

3. Run Gri in this emacs buffer (``C-cC-r`') noting from the postscript window that pops up that the colors are, indeed, mixed up.

4. Load up the ``gdb`' debugger by typing ``M-x gdb gri`'. This will open a new Emacs buffer in which you may type commands. We'll be switching back and forth between this buffer and various source files.

5. Reasoning that the error probably occurs at ``set color`' or ``draw box`', try replacing the latter by a command such as ``draw label "hi" at 3 3 cm"`'. The color is still wrong, indicating that it is the ``set color`' command that has the problem.

6. Next, we must find where the C++ code corresponding to the ``set color`' command resides. As it turns out, all ``set`' commands are defined in the source file ``set.cc`', and this command is defined in a subroutine called ``set_colorCmd()`'. But the author knows this -- how would you? The answer is to look in the ``gri.cmd`' file, for the ``set color`' command. (Search for the string ```set color` '.) Then read down to see the body of the command, enclosed in braces; you'll see

       {
           extern "C" bool set_colorCmd(void);
       }

   which indicates that the subroutine name is ``set_colorCmd()`'.

7. Next we need to edit this subroutine to see what it is doing. There are several ways to find it (e.g. ``grep`' through the source files), but the easiest is to use the "tags" feature of Emacs, by typing ``M-. set_colorCmd`'. This will bring you to the indicated subroutine.

8. Have a look through this subroutine to see what it is doing. It looks very much like many other Gri subroutines. A check is done on the number of words provided to the command, in the

       	switch (_nword) {

   line. (That's line ``set.cc:484`' at the moment -- but it may be different by the time you read this file, if I've changed it!) We are calling it with 6 words (``set color hsb 1.000 1 1`'), so move down to the line

       	case 6:

   and you'll see that there is an ``if`' statement seeing whether this word is ``rgb`' or ``hsv`'. These statements are checking ``_word[2]`', which is the third word of the command. (In Gri, as in C, words start at zero. Thus, for this command, ``_word[0]`' is ``set`', ``_word[1]`' is ``color`', and ``_word[2]`' is expected to be either ``rgb`' or ``hsb`'. We are having problems with the ``hsb`' style, so we'll move down to that code. The code that's being executed is as follows.

       } else if (!strcmp(_word[2], "hsb")) {
               // `set color hsb .hue. .saturation. .brightness.'
               double          hue, saturation, brightness;
               Require(getdnum(_word[3], &hue),
                       READ_WORD_ERROR(".hue."));
               Require(getdnum(_word[4], &saturation),
                       READ_WORD_ERROR(".saturation."));
               Require(getdnum(_word[5], &brightness),
                       READ_WORD_ERROR(".brightness."));
               // Clip if necessary
               CHECK_HSB_RANGE(hue);
               CHECK_HSB_RANGE(saturation);
               CHECK_HSB_RANGE(brightness);
               gr_hsv2rgb(hue, saturation, brightness,
                       &red, &green, &blue);
               PUT_VAR("..red..", red);
               PUT_VAR("..green..", green);
               PUT_VAR("..blue..", blue);
               c.setHSV(hue, saturation, brightness);
               _griState.set_color_line(c);
               if (_griState.separate_text_color() == false)
                       _griState.set_color_text(c);
               return true;

   The ``Require`' lines are ensuring that we could decode the values of the variables ``hue`', etc, from the commandline. Then we clip the range of these values. Then we convert from ``hsb`' color format to ``rgb`' color format, save the values of the colors in Gri variables with ``PUT_VAR`', and then set the color with ``c.setHSV`'. Finally we save this color in the Gri "state" with ``_griState.set_color_line(c)`'.

   As it turns out, Gri outputs all colors to the PostScript file in RGB format, so the we may well suspect that the problem is in the ``gr_hsv2rgb()`' line.

9. We have an idea where to look now, so let's go to the line just after it, in the editor, and insert a "breakpoint" there by typing ``C-x SPC`'. Then move to the ``gdb`' buffer and re-run Gri by typing

       run -directory . test.gri

   to run Gri on our script. Then, magic happens! Gri stops at the indicated breakpoint, and Emacs will display both the ``gdb`' buffer and the ``set.cc`' buffer. The latter has a margin indication telling what line were are on. You may now type ``gdb`' commands in the ``gdb`' buffer. In particular, type

       p hue

   to print the hue. Then type

       p red

   to see the red value. Then type

       c

   to continue running Gri. It will pause again. Check the hue and red values again, as above. If you like, play around with hue value in the Gri script ``test.gri`' and run gri again (type ``r`' in ``gdb`'). This seems to indicate that the conversion is working strangely.

10. To see how the conversion is done, clear the breakpoints by typing ``delete`' in the ``gdb`' buffer, then insert a breakpoint before ``gr_hsv2rgb`' is called. Then, run Gri again (``r`' in the ``gdb`' buffer). When it stops just before this subroutine, type ``s`' to "step into" the subroutine. Then you'll see a conversion code from the (wonderful) textbook of Foley and Van Dam. You'll see

        void
        gr_hsv2rgb(double h, double s, double v,
                   double *r, double *g, double *b)
        {
        	h = 6.0 * pin0_1(h);
        	s = pin0_1(s);
        	v = pin0_1(v);
        	int i = (int) floor(h);
        	if (i > 5)
        		i = 5; // Prevent problem if hue is exactly 1
        	double f = h - i;
        	double p = v * (1.0 - s);
                ...

    in the present version of Gri, but in the previous (buggy) version, the ``if`' statement was missing. Without this ``if`' statement, Gri produced wrong colors. With the statement, the colors are correct.

And so ends the example. You may wish to read the Foley and Van Dam textbook to see just what I'm doing in ``gr_hsv2rgb`', but suffice it to say that the problem in the (older) version of Gri was that ``i`' could take the value 6 if the hue was exactly equal to 1, and that was erroneous.

In reading the code, you may notice that it is formatted in a uniform way: the Kernighan and Ritchie scheme (from their classic C textbook), with 8-character indents. I get this by putting the following lines in the ``~/.emacs`' file, which is used to customize the Emacs editor:

    (defun my-c-mode-common-hook ()
      (c-set-style "K&R")
      (setq c-basic-offset 8)
      )
    (add-hook 'c-mode-common-hook 'my-c-mode-common-hook)

If you submit patches, please use the same format as I've done, so that I can more easily see the changes you've made.