embedding with gnu: gnu debugger, 09/99

9
80 SEPTEMBER 1999 Embedded Systems Programming feature BILL GATLIFF Are GNU tools ready for prime-time embedded development? The author points out the strengths and weaknesses and then explains how to use the GNU debugger to debug firmware running on an embedded system. he growth in popularity of the industry’s best-known collec- tion of free software development tools, the GNU toolkit, has reached the embedded marketplace. Well-known embedded vendors like Wind River Systems, Integrated Systems Inc., and others now openly advertise their compatibility with GNU, and the number of individual and corporate consultants claiming expertise in using GNU tools for embedded software develop- ment is growing at a noticeable rate. But are the GNU tools really ready for prime-time embedded develop- ment? I think so, but only under the right circumstances. GNU certainly has its advantages: the tools are cheap (free!), stable, highly portable, and consistent across platforms. However, GNU also has drawbacks: its compo- nents were originally designed for developing desktop applications in a Unix-like environment, they can be a challenge to set up and use for embedded development, and the documentation occasionally lacks detail in areas important to embedded developers. Even with these limitations, a motivated developer who’s willing to invest the time to learn to use GNU will find the transition a rewarding and productive endeavor that lends tremendous stability and flexibility to the Embedding with GNU: GNU Debugger T

Upload: others

Post on 12-Sep-2021

47 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Embedding with GNU: GNU Debugger, 09/99

80 SEPTEMBER 1999 Embedded Systems Programming

fe

at

ur

e

B I L L G A T L I F F

Are GNU tools ready for prime-time embedded development? Theauthor points out the strengths and weaknesses and then explainshow to use the GNU debugger to debug firmware running on anembedded system.

he growth in popularity of the industry’s best-known collec-tion of free software development tools, the GNU toolkit, hasreached the embedded marketplace. Well-known embeddedvendors like Wind River Systems, Integrated Systems Inc., andothers now openly advertise their compatibility with GNU,and the number of individual and corporate consultants

claiming expertise in using GNU tools for embedded software develop-ment is growing at a noticeable rate.

But are the GNU tools really ready for prime-time embedded develop-ment? I think so, but only under the right circumstances. GNU certainlyhas its advantages: the tools are cheap (free!), stable, highly portable, andconsistent across platforms. However, GNU also has drawbacks: its compo-nents were originally designed for developing desktop applications in aUnix-like environment, they can be a challenge to set up and use forembedded development, and the documentation occasionally lacks detailin areas important to embedded developers.

Even with these limitations, a motivated developer who’s willing toinvest the time to learn to use GNU will find the transition a rewarding andproductive endeavor that lends tremendous stability and flexibility to the

Embedding with GNU:

GNU Debugger

T

Page 2: Embedding with GNU: GNU Debugger, 09/99

Embedded Systems Programming SEPTEMBER 1999 81

embedded development experience. Ican say this with confidence because Irecently began using the GNU tools inan embedded project of my own, andthe results have been so inspiring thatGNU tools are now my first choice,even when a commercial alternativeexists.

In this article I’ll explain how touse the GNU debugger, gdb, to debugfirmware running on an embeddedsystem connected to a PC by a serialcable.

What is gdb?The GNU debugger, gdb, is anextremely powerful all-purposedebugger. Its text-based user interfacecan be used to debug programs writ-ten in C, C++, Pascal, Fortran, and sev-eral other languages, including theassembly language for every micro-processor that GNU supports.

Among gdb’s many noteworthyfeatures is its ability to debug pro-grams “remotely,” in a setup wherethe platform running gdb itself (thehost) is connected to the platformrunning the application beingdebugged (the target) via a serialport, network connection, or someother means. This capability is notonly essential when porting GNUtools to a new operating system ormicroprocessor, but it’s also useful fordevelopers who need to debug anembedded system based on a proces-sor that GNU already supports.

The remote debugging capabilityof gdb, when it has been properlyintegrated into an embedded system,allows a developer to step throughcode, set breakpoints, examine mem-ory, and interact with the target inways that rival the capabilities of mostcommercially available debuggingkernels—and even some low-endemulators.

How gdb works, from anembedded perspectiveWhen debugging a remote target, gdbdepends on the functionality providedby a debugging stub, a small piece ofcode in the embedded system thatserves as the intermediary between thehost running gdb and the applicationbeing debugged. This relationship isdepicted graphically in Figure 1.

The debugging stub (the techno-logical equivalent of a ROM monitor)and gdb communicate via the gdbRemote Serial Protocol, an ASCII,message-based protocol containingcommands to read and write memory,query registers, run the program, andso forth. Since most embedded devel-opers write their own stubs so that theycan make the best use of their specifichardware’s features and limitations, aclear understanding of how gdb usesthe Remote Serial Protocol is veryimportant.

To set breakpoints, gdb uses mem-ory reading and writing commands to

nondestructively replace a sourceinstruction with a TRAP or similaropcode.1 This causes control to trans-fer to the debugging stub when thatinstruction is encountered. Thedebugging stub’s job at that point is tocommunicate the event to gdb (viaRemote Serial Protocol messages),and then accept commands from gdbtelling it what to do next.

To illustrate, Listing 1 is a TRAPexception handler for the Hitachi SH-2 microprocessor. When the processorencounters a TRAP instruction placedas a breakpoint by gdb, this functionsends the processor context to a func-tion called gdb_exception(), whichsubsequently communicates it to gdb.Eventually, the target invokesgdb_return_from_exception(), whichrestores the processor context andreturns control to the application.

The Remote Serial Protocol’s stepcommand is a bit more challenging,especially when the target processordoesn’t provide a “trace bit” or similar

I recently began using the GNU tools in an embedded project of my

own, and the results have been so inspiring that GNU tools are now

my first choice, even when a commercial alternative exists.

CO

RB

IS

FIGURE 1 A typical embedded GNU debugger setup

Workstation

Embedded System

Application Code

Serial Cable

DebuggingStub

Page 3: Embedding with GNU: GNU Debugger, 09/99

gnu debugger

functionality.2 In these cases, the onlyalternative is for the stub to disassem-ble the instruction about to be execut-ed so that it can determine where theprogram is going to go next.

Fortunately for me, several sugges-tions on how to implement the stepcommand are supplied with gdb. Forthe Hitachi SH-2, the functiondoSStep() in gdb/sh-stub.c is illustra-tive, as are the similarly-named func-tions in the files gdb/i386-stub.c,gdb/m68k-stub.c, and others.

Other things gdb can doThe debugger can also evaluate arbi-trary C expressions entered at the con-sole, including ones containing func-tion calls on the remote target. So youcan type commands like:

print foo( sci[x]->smr.brg )

and gdb will happily report the results.Of course, gdb can also disassem-

ble code, and it does a good job of sup-plementing magic numbers withequivalent symbol information when-ever possible. For example, the follow-ing output:

jmp 0x401010 <main + 80>

is gdb’s way of saying that the addressshown is equivalent to an offset of 80bytes from the start of the functionmain().

The Remote Serial Protocol mes-sages exchanged between gdb and thedebugging stub running on the targetcan be displayed, as well as logged to afile. These features are extremely use-ful both for debugging a new stub, andfor understanding how gdb uses theRemote Serial Protocol to implementuser requests for data, program mem-ory, function calls, and so forth.

The GNU debugger has a scriptinglanguage that permits automated tar-get setup and testing. The language istarget microprocessor-independent,so scripts can be reused when the tar-get application changes from onemicroprocessor to another.

82 SEPTEMBER 1999 Embedded Systems Programming

LISTING 1 A gdb TRAPA handler for the Hitachi SH2

/* An example TRAPA #32 handler for the Hitachi SH2.

/*

/*Stores current register values on the stack, then calls gdb_exception.

*/

asm("

.global _gdb_exception_32

_gdb_exception_32:

/* push the stack pointer and r14 */

mov.l r15, @-r15

mov.l r14, @-r15

/* the sh2 stacks the pc and sr automatically when performing a trap

/* exception, so we have to adjust the stack pointer value we give to gdb to

/* account for this extra data. In other words, gdb wants to see the stack

/* pointer value as it was BEFORE the trap was taken, and not what its value

/* is right now. So, subtract eight (pc and sr are four bytes each) from the

/* sp value we just pushed onto the stack

*/

mov.l @(4,r15), r14

add #8, r14

mov.l r14, @(4,r15)

/* push other register values onto the stack */

mov.l r13, @-r15

mov.l r12, @-r15

mov.l r11, @-r15

mov.l r10, @-r15

mov.l r9, @-r15

mov.l r8, @-r15

mov.l r7, @-r15

mov.l r6, @-r15

mov.l r5, @-r15

mov.l r4, @-r15

mov.l r3, @-r15

mov.l r2, @-r15

mov.l r1, @-r15

mov.l r0, @-r15

sts.l macl, @-r15

sts.l mach, @-r15

stc vbr, r7

stc gbr, r6

sts pr, r5

/* call gdb_exception, pass it exception=32 */

mov.l _gdb_exception_target, r1

jmp @r1

mov #32, r4

.align 2

_gdb_exception_target: .long _gdb_exception

“);

Page 4: Embedding with GNU: GNU Debugger, 09/99

gnu debugger

84 SEPTEMBER 1999 Embedded Systems Programming

LISTING 1, cont’d. A gdb TRAPA handler for the Hitachi SH2

/* An example on how to return control to an application from a debugging

/* stub, for the Hitachi SH2.

/*

/* If this were written in C, the prototype would be:

/* void gdb_return_from_exception( gdb_sh2_registers_T registers );

/*

/* In general, we can simply pop registers off the stack in the same fashion

/* as gdb_exception_nn puts them on. However, usually the return stack pointer

/* isn’t the same as ours, so if we pop r15 before we copy the pc and sr back

/* onto the return stack, we lose them.

*/

asm(“

.global _gdb_return_from_exception

_gdb_return_from_exception:

/* restore some registers */

lds r4, pr

ldc r5, gbr

ldc r6, vbr

lds r7, mach

lds.l @r15+, macl

mov.l @r15+, r0

mov.l @r15+, r1

mov.l @r15+, r2

mov.l @r15+, r3

mov.l @r15+, r4

mov.l @r15+, r5

mov.l @r15+, r6

mov.l @r15+, r7

mov.l @r15+, r8

mov.l @r15+, r9

mov.l @r15+, r10

mov.l @r15+, r11

mov.l @r15+, r12

/* pop pc, sr onto application’s stack, not ours */

mov.l @(8,r15), r14

mov.l @(16,r15), r13

mov.l r13, @-r14

mov.l @(12,r15), r13

mov.l r13, @-r14

/* finish restoring registers */

mov.l @r15+, r13

mov.l @r15+, r14

mov.l @r15, r15

/* adjust application’s stack pointer to account for pc, sr */

add #-8, r15

/* ... and return to the application */

rte

nop

“);

Page 5: Embedding with GNU: GNU Debugger, 09/99

gnu debugger

And finally, gdb provides trace-points, a way to record informationabout a running program with mini-mal interruption of the program tocollect the data. Tracepoints requiresignificant debugging stub support toimplement, so they’ll be the subject ofa future article.

Information on all of these featuresis provided with gdb. You can typehelpat the gdb console, or you can usea GNU utility called “info” to reviewdocumentation contained in the gdbinstallation package. The debuggeralso comes with a preformatted quick-reference card in the filegdb/doc/refcard.ps, and typesetuser’s manuals are available online atseveral sites that mirror gdb sourcecode distributions.

Installing gdbGNU tools like gdb are generally dis-tributed as source code, archived, andcompressed into a single file using thetar and gzip utilities (available fromGNU at www.gnu.org). Once thesource code is in hand, the user typi-cally decompresses, configures, com-piles, links, and installs the programsin a manner most compatible withtheir workstation setup, target envi-ronment, and other factors. Some gra-cious members of the GNU communi-ty provide precompiled binary ver-sions of the most popular tools; theavailability of such releases is usuallyadvertised in Internet newsgroups.

Efforts are underway to produceports of GNU tools for Windows 95,98, and NT hosts. At the present time,however, gdb and other tools neces-sary for embedded development can-not be easily built on Microsoft hosts,although they will run fine when prop-erly cross-compiled on another host.To get the latest information aboutGNU-Microsoft compatibility, checkout the Cygwin Project at http://source-ware.cygnus.com/cygwin/.

The most recent release of gdb isthe file gdb-4.18.tar.gz, which containsboth the gdb source code and someconfiguration scripts that help auto-

mate its compilation and installation.This file is available from the CygnusSolutions gdb Web site, http://source-ware.cygnus.com/gdb/.

To install gdb, first decompressgdb-4.18.tar.gz:

tar xzvf gdb-4.18.tar.gz

Next, study gdb-4.18/README andgdb-4.18/gdb/News, as these files con-tain important information on how toinstall gdb, the current state of gdbdevelopment, new features, and soforth.

Per the installation instructions inREADME, configure gdb for your hostmachine and debugging target:

mkdir gdb-build

cd gdb-build

../gdb-4.18/configure

-- target=sh-hitachi-hms

The configure script will study thehost machine’s setup and create theproper local environment in which tobuild gdb. The targetparameter tellsgdb what microprocessor your embed-ded applications will run on. You’llfind a list of supported targets in thefile gdb/ChangeLog.

Finally, tell gdb to compile andinstall itself:

make all install

When you’re done, you’ll end upwith an executable called sh-hitachi-hms-gdb (or whatever prefix you sup-plied in the target parameter duringconfiguration). By default, this file isplaced in /usr/local/bin. To run it,simply type the executable file namefollowed by the name of your applica-tion file:

sh-hitachi-hms-gdb a.out

Source code for a gdbdebugging stubDespite the target-specific nature ofremote software debugging, it is possi-ble to create a highly portable debug-

ging stub that can be reused with min-imal modification on several differentembedded microprocessors.

I have posted my attempt at a“portable” debugging stub on ESP’sWeb site, at www.embedded.com/code.htm. This source code has been com-piled and tested for the Hitachi SH-2,and ports are underway for theHitachi H8, Power PC, and otherprocessors.

The processor-specific code is con-tained in files with processor-specificfile names, like gdb_sh2*.c. Youshould first copy these files to oneswith names related to your micro-processor (such as gdb_m68k*.c), andreplace the contents with code thatworks for your machine.

If you do succeed in porting mycode to another processor, or desireassistance in doing so, please let meknow. In addition to hearing yourfeedback, I would like to make yourmodifications available to the rest ofthe embedded community.

A typical gdb sessionNow that we’ve covered the gdb’sfunctionality in general terms and I’veshown how to install it, let’s observegdb in action. Table 1 is a transcript ofa typical gdb debugging session, dur-ing which gdb initiates communica-tions with a remote target running adebugging stub, downloads a pro-gram, sets a breakpoint, and then runsthe program. The debugging stubinforms gdb when the breakpoint isencountered, and gdb then displaysthe appropriate source line to theuser. The user subsequently displays avariable, steps one instruction, andthen exits gdb.

The left column of the exampleshows a portion of the gdb console,where the user types commands andviews data. The right columns showsome of the GDB Remote SerialProtocol messages exchangedbetween the host machine and theembedded device. I’ve included sup-plemental information in squarebrackets. For a detailed explanation of

86 SEPTEMBER 1999 Embedded Systems Programming

Page 6: Embedding with GNU: GNU Debugger, 09/99

gnu debugger

these messages, see the sidebar, “TheGDB Remote Serial Protocol.”

Note that Table 1 is not what userssee when they use gdb—they see a ter-minal display in English, completewith source code, displayed variables,and the like. Instead, the transcriptshown illustrates what happens behindthe scenes when the user types the list-ed commands.

Ideas on adapting gdb tosolve specific problemsThe modular implementation archi-tecture used by gdb makes it straight-

forward to change aspects of gdb’sbehavior that don’t suit your needs.For example, if your product has onlyone communications port that isalready dedicated to a non-gdb com-munications protocol, then it’s possi-ble to modify gdb so that debuggermessages fit inside of packets that yourproduct already understands.Likewise, if your product lacks a serialport but has some other kind of com-munications interface—like a CANport, for instance—then you couldenhance gdb’s remote communica-tions strategy to work with an off-the-

shelf serial-to-CAN or parallel-to-CANbridge.

You can also modify gdb’s behaviorto make it more compatible with othersoftware in your embedded applica-tion. For example, if you were alreadyusing TRAPA #32 for something non-gdb-related, you could either changethe opcode gdb uses for a breakpoint,or you could have gdb produce a newmessage—one that signaled your tar-get to turn on instruction tracing orenable on-chip breakpoint-generatinghardware, for example.

The file gdb/remote.c containsgdb’s implementation of the RemoteSerial Protocol, and is a good startingpoint for studying how gdb’s modularimplementation permits you to quick-ly adapt it to meet the needs of a spe-cific debugging target. Other files, likegdb/remote-hms.c and gdb/remote-e7000.c, use this modular frameworkto provide support for debuggers andemulators supplied by Hitachi,Motorola, and other vendors.

For the most up-to-date informa-tion on how gdb works, how toenhance gdb, and how to get yourimprovements into future gdb releas-es, type info gdb-internals afterinstalling gdb.

Graphical gdb interfacesOnce you get the plain-vanilla gdbworking on your embedded target,you may find that although its textconsole is fast, intuitive, and easy touse, it’s also a bit, well, uninspiring.You are not alone, and fortunately sev-eral free graphical add-ons are avail-able to help jazz up your debuggingexperience. These enhancements alluse a running instance of gdb itself asthe low-level debugger, so if gdb talksproperly to your target, then theseinterfaces will too.

The following is not a comprehen-sive list of all available graphical gdbfront ends, by any means—I’ve onlyincluded tools that I have firsthandexperience with. Be sure to askaround in the gdb newsgroups and onthe gdb homepage if you find that the

88 SEPTEMBER 1999 Embedded Systems Programming

TABLE 1 Transcript of a typical gdb session

What the user enters What happens on the serial portgdb sends... target responds with...

host>gdb myprogramgdb> target remote +$Hc-1#09 +$OK#9a/dev/ttyS0 +$qOffsets#4b +$Text=0;Data=0;Bss=0#04

+$?#3f +$S05#b8+$g#67 +$00001a00ffff81b200000020...

gdb> load $M401054,10:004020240040 +$OK#9a20240040202400402024#72... [lots more M messages]

gdb> breakpoint main [nothing— gdb physically sets the breakpoint immediately before the continue command is sent]

gdb> continue +$M4015cc,2:c320#6d +$OK#9a+$c#63 + [gdb places a breakpoint [program runs until it reaches opcode at main()] main()]

$T050:00401400;1:00404850;2:00000001;3:00000030;4:ffffffff;5:00000000;6:00000010;7:00000010;8:0040161c;9:00002070;a:00404068;b:004015bc;c:ffffffff;d:ffffffef;e:00404840;f:00404840;10:004015cc;11:004015cc;12:d04001e2;13:00401000;14:00000000;15:00ffffff;16:000000f0;#d1[target stopped at main(),address 0x4015cc]

gdb> display foo +$m4015bc,2#5a +$2f86#06 [foo is at address 0x4015bc;its value is 0x2f86]

gdb> stepi $s#73 + [target executes one instruction]$T050:00401400;1:00404840;2:00000001;3:00000030;4:ffffffff;5:00000000;6:00000010;7:00000010;8:0040161c;9:00002070;a:00404068;b:004015bc;c:ffffffff;d:ffffffef;e:00404840;f:00404840;10:004015ce;11:004015cc;12:d04001e2;13:00401000;14:00000000;15:00ffffff;16:000000f0;#d2[PC is now 0x4015ce]

gdb> quit $k#6b +

Page 7: Embedding with GNU: GNU Debugger, 09/99

gnu debugger

tools I’ve listed don’t suit yourneeds.

DDD: Data DisplayDebuggerThe Data Display Debugger(www.cs.tu-bs.de/softech/ddd/) byAndreas Zeller (SoftwareTechnology Department,Technical University ofBraunschweig) is a mature,high-quality X-Windows-basedgraphical gdb interface.Besides the usual features youwould expect from any graphi-cal debugger, DDD provides aneasy-to-navigate graphical datadisplay that allows sophisticateddata structure visualization withjust a few mouse clicks.

This application is well doc-umented and easy to install. Itsgraphics-intensive interfaceextracts a slight penalty in run-time performance, but any hostprocessor that can reasonablyrun other graphical GNU toolswill probably work fine.

Code MedicCode Medic (www.cco.caltech.edu/~glenn/medic/) is an ele-gant, X-Windows-based graphi-cal interface to gdb’s mostimportant features. The inter-face was written by Glenn Bach(of the Physics, Mathematics,and Astronomy Division,California Institute ofTechnology), and is also part ofa suite of integrated softwaredevelopment tools known asCode Crusader.

Code Medic provides drag-and-drop data management,context-sensitive highlighting,and a sophisticated display tai-lored for complicated datastructure visualization.Furthermore, Code Medic uses a mes-sage-based interface to gdb, whichimproves performance significantlyover DDD in both remote and self-hosted debugging setups.

InsightInsight (http://sourceware.cygnus.com/gdb/) is Cygnus Solution’s own (andformerly proprietary) graphicalenhancement to gdb. In contrast to

DDD and Code Medic, Insight’sgraphics come by way of Tcl/Tkinstead of X-Windows, whichmeans it runs easily on Windowsplatforms. Furthermore, Insightis compiled into gdb (ratherthan it running gdb as a sub-process, the way CodeMedic andDDD do), which improves itsperformance and makes its com-munications with gdb moreinteractive. It also provides func-tionality to graphically configureremote connections, which theother front ends can only do byway of gdb command scripts.

But is gdb right foryou?I hope that by now you’re con-vinced that gdb is a powerfuland capable tool for embeddedsoftware debugging. If that wereall that mattered, then I believethat gdb would be the most pop-ular embedded debugger avail-able today.

Unfortunately, tool selectionis a trade-off among many fac-tors—price, performance, com-patibility, and support, to namea few—and when everything isconsidered, gdb has both itsstrengths and weaknesses (asdoes any tool available today atany price, free or otherwise).

As I’ve already mentioned,gdb’s strengths (besides its cost)lie in its feature list, its uniformapplicability across many hostplatforms and debug targets,and the degree to which itsbehavior can be tailored tomeet the specific demands of anembedded debugging target.

In particular, gdb’s consisten-cy across hosts and targets pre-sents the opportunity for con-

siderable reuse of automatedconfiguration, compilation and unittesting scripts, which is a value thatshould not be underestimated. This initself may reward the pain of switchingto GNU, particularly if proliferation of

90 SEPTEMBER 1999 Embedded Systems Programming

FIGURE 2 Data Display Debugger

FIGURE 3 Code Medic

FIGURE 4 Insight

Page 8: Embedding with GNU: GNU Debugger, 09/99

gnu debugger

your products across a variety of targetprocessors is likely.

Although the GNU tools are gener-ally well documented, the information

occasionally lacks details that areimportant to embedded developers.For example, procedures to properlyestablish the C run-time environ-

ment—initialize global variables, zeroout memory, and so forth—are onlysupplied as working code and as anoccasional side note in the descrip-tions of a few linker commands; thereis currently no single document thatcompletely describes in detail aprocess that is critically important forC/C++-based embedded systems. (I’mcertain that the GNU effort would wel-come the creation of a tutorial on thissubject.)

Finally, gdb works best when feddebugging information produced bythe GNU compiler and linker, whichpresents compatibility problems fornon-GNU legacy projects, or workinvolving third-party libraries thataren’t available in a GNU-compatibleformat.

What about support?One perceived drawback that’s actual-ly an advantage for GNU is the lack ofavailable support from a central, con-trolling organization. Instead, peoplehighly skilled in the use and develop-ment of the GNU tools (including theauthors of the tools themselves) areavailable 24 hours a day via a variety ofInternet news groups (gnu.gdb.bug isone) and mail servers (www.sourceware.cygnus.com/gdb, for example). In situa-tions where I’ve requested help I usu-ally received an answer in four hoursor less—an impressive statistic for eventhe most expensive product supportdesks.

On the other hand, if you trulyneed the level of support that onlymoney can buy, or you need extensivemodifications to one or more GNUtools in support of a very specializedsituation, then there are companiesand individuals around that can pro-vide those kinds of services. The bestway to find them is to subscribe to andread the Internet news groups andmail specific to the GNU tools youneed help with.

A rewarding experienceThe ability of gdb to adapt to the spe-cific needs of a debugging target

92 SEPTEMBER 1999 Embedded Systems Programming

The GDB Remote Serial ProtocolThe GDB Remote Serial Protocol (RSP) is the lingua franca between gdb and a remote

target. It defines messages for reading and writing data, controlling the application

being debugged, and reporting application status. The host side is implemented in

gdb’s remote.c source file.

The following are short descriptions of the RSP’s most important commands. A

complete summary of each command is available on the ESP Web site, www.embed-

ded.com/code.htm.

Data exchanged between gdb and a remote target with the GDB Remote Serial

Protocol uses plain ASCII characters. Messages begin with a dollar sign ($) and end

with a gridlet (#) and eight-bit checksum. In other words, each message looks like this:

$ <data> # CKSUM_MSN CKSUM_LSN

where <data> is typically a string of ASCII hex [0-9,a-f,A-F] characters.

CKSUM_MSNand CKSUM_LSNare ASCII hex representations of an eight-bit checksum

of <data>. Only the hex digits 0 to 9 and a to f are allowed.

When a message is sent, the receiver responds with either:

+ if the received checksum was correct, and the receiver is ready for the next packet

- the received checksum was incorrect, and the message needs to be retransmitted

A target can respond to a message from gdb with either data or an OK (depending

on the message), or a target-defined error code. When gdb receives an error code, it

reports the number to the user via the gdb console.

Definitions for <data>are shown below.

TABLE A Register-related commands

Command name <data>definition Descriptionread registers g Return the values of all registerswrite registers GXX..XX Set registers to XX..XXwrite register nn Pnn=XX..XX Set the value of register NN

TABLE B Memory-related commands

Command name <data> definition Descriptionread memory mAA..AA,LL..LL Read values from memorywrite memory MAA..AA,LL..LL:XX..XX Write values to memory

TABLE C Target infromation commands

Command name <data> definition Descriptionquery section offsets qOffsets Return section offset information

Page 9: Embedding with GNU: GNU Debugger, 09/99

gnu debugger

(memory usage, communicationsmedia, and so forth) often makes itthe only choice available for on-targetdebugging, particularly given thegrowing popularity of single-chip,highly-integrated, and IP-basedembedded products. The complexityof today’s embedded devices isincreasing at an alarming rate, and asthe technology choices available fornew designs continue to diverge, find-ing a commercial development toolvendor with a product that fits yourneeds becomes less likely every day.

A switch to GNU might be in yourbest long-term interests, even if you’reusing conventional technology in yourembedded designs, because GNUapplications are becoming increasing-ly popular as educational tools. So arecent engineering graduate wouldprobably be more familiar with themthan with any specific equivalent com-mercial products.

And finally, GNU’s support of avariety of popular embedded proces-sors means that you reduce the risk ofneeding to find a new tool vendorbecause your current one doesn’t sup-port the processor you’d like to use inyour next design.

With all these advantages, I have no

doubt that a motivated developer whois willing to master the GNU tools willfind their product development amore stable, flexible, and rewardingexperience. esp

Source code for gdb is available athttp://sourceware.cygnus.com/gdb/.This site also includes links to gdb-specificmailing lists, graphical front ends, andsources for precompiled gdb binaries.

Bill Gatliff is a freelance embedded develop-er and senior design engineer withKomatsu Mining Systems, Inc. in Peoria,IL, and is a semi-regular presenter at theEmbedded Systems Conferences. He can bereached at [email protected].

References1. An assumption here is that the applica-

tion being debugged is located in RAM.

With a smart enough debugging stub,

proper hardware support, and/or com-

piled-in breakpoints, however, this need

not be true.

2. For example, Motorola 683xx processors

contain the ability to trap on instruction

execution and/or changes in program

flow; this feature is controlled by the

"trace enable" bits, T1 and T0, in the

processor's status register.

94 SEPTEMBER 1999 Embedded Systems Programming

TABLE D Program control commands

Command name <data> definition Descriptionset thread Hc Set current program threadstep sAA..AA Execute one assembly instructioncontinue cAA..AA Resume application executionlast signal ? Report last signal kill k Terminate application

TABLE E Target status messages (responses from the target)

Message name <data> definition Descriptionlast signal response Snn Minimal reply to the last signal

commandexpedited response Tnnr...:v...r...:v...; The last signal reported, plus key

register valuesconsole output Ovvvvvvvv... Sends text from the target to

gdb’s console