Anda di halaman 1dari 10

Introduction to the DWARF Debugging Format

Michael J. Eager, Eager Consulting February, 2007

It would be wonderful if we could write programs that were guaranteed to work correctlyandneverneededtobedebugged. Until that halcyon day, the normal pro grammingcycleisgoingtoinvolvewriting aprogram,compilingit,executingit,and then the (somewhat) dreaded scourge of debuggingit.Andthenrepeatuntilthepro gramworksasexpected. Itispossibletodebugprogramsbyin sertingcodethatprintsvaluesofvariousin teresting variables.Indeed, in some situa tions,suchasdebuggingkerneldrivers,this may be the preferred method. There are lowleveldebuggersthatallowyoutostep through the executable program, instruc tionbyinstruction,displayingregistersand memorycontentsinbinary. Butitismucheasiertouseasourcelev el debugger which allows you to step through a program's source, set break points,printvariablevalues,andperhapsa fewotherfunctionssuchasallowingyouto callafunctioninyourprogramwhileinthe debugger. The problem is how to coordi nate two completely different programs, thecompilerandthedebugger,sothatthe programcanbedebugged.

quence of simple operations, registers, memory addresses, and binary values which the processor actually understands. Afterall,theprocessor reallydoesn'tcare whetheryouusedobjectorientedprogram ming,templates,orsmartpointers;itonly understandsaverysimplesetofoperations onalimitednumberofregistersandmem orylocationscontainingbinaryvalues. As a compiler reads and parses the sourceofaprogram,itcollectsavarietyof informationabouttheprogram,suchasthe linenumberswhereavariableorfunction isdeclaredorused.Semanticanalysisex tendsthisinformationtofillindetailssuch asthetypesofvariablesandargumentsof functions.Optimizationsmaymovepartsof the program around, combine similar pieces,expandinlinefunctions,orremove parts which are unneeded. Finally, code generation takes this internal representa tionoftheprogramandgeneratestheactu almachineinstructions.Often,thereisan other passover the machinecode to per formwhatarecalled"peephole"optimiza tionsthatmayfurtherrearrangeormodify thecode,forexample,toeliminatedupli cateinstructions.

difficulttimeconnectingitsmanipulations of lowlevel code to the original source whichgeneratedit. Thesecondchallengeishowtodescribe theexecutableprogramanditsrelationship totheoriginalsourcewithenoughdetailto allowadebuggertoprovidetheprogram merusefulinformation.Atthesametime, thedescriptionhastobeconciseenoughso thatitdoesnottakeupanextremeamount of space or require significant processor timetointerpret.ThisiswheretheDWARF DebuggingFormatcomesin:itisacompact representationoftherelationshipbetween theexecutableprogramandthesourceina waythatisreasonablyefficientforadebug gertoprocess.

The Debugging Process

Allinall,thecompiler'staskistotake thewellcraftedandunderstandablesource Translating from codeandconvertitintoefficientbutessen Source to tiallyunintelligiblemachinelanguage.The betterthecompilerachievesthegoalofcre Executable atingtightandfastcode,themorelikelyit he process of compiling a program isthattheresultwillbedifficulttounder fromhumanreadableformintothebi stand. narythataprocessorexecutesisquitecom During this translation process, the plex,butitessentiallyinvolvessuccessively compiler collects information about the recastingthesourceintosimplerandsim program which will be useful later when plerforms,discardinginformationateach stepuntil,eventually,theresultisthese the program is debugged. There are two challenges in doing this well. The first is thatinthelaterpartsofthisprocess,itmay MichaelEagerisPrincipalConsultantat be difficult for the compiler to relate the EagerConsulting(www.eagercon.com), changesitismakingtotheprogramtothe specializing in development tools for original sourcecodethat the programmer embeddedsystems. Hewasamember wrote.Forexample,thepeepholeoptimizer ofPLSIG'sDWARFstandardizationcom mayremoveaninstructionbecauseitwas mittee and has been Chair of the abletoswitcharoundtheorderofatestin DWARF Standards Committee since codethatwasgeneratedbyaninlinefunc 1999. Michael can be contacted at tionintheinstantiationofaC++template. eager@eagercon.com. Bythetimeitgetsitsmetaphoricalhands EagerConsulting,2006,2007 ontheprogram,theoptimizermayhavea

hen a programmer runs a program under a debugger, there are some common operations which he or she may wanttodo.Themostcommonoftheseare settingabreakpointtostopthedebuggerat aparticularpointinthesource,eitherby specifying the line number or a function name. When this breakpoint is hit, then theprogrammerusuallywouldliketodis playthevaluesoflocalorglobalvariables, ortheargumentstothefunction.Display ingthecallstackletstheprogrammerknow howtheprogramarrivedatthebreakpoint incaseswheretherearemultipleexecution paths.Afterreviewingthisinformation,the programmercanaskthedebuggertocon tinueexecutionoftheprogramundertest. Thereareanumberofadditionalopera tionsthatareusefulindebugging.Forex ample,itmaybehelpfultobeabletostep throughaprogramlinebyline,eitheren tering or stepping over called functions. Settingabreakpointateveryinstanceofa templateor inlinefunction canbe impor tantfordebuggingC++programs.Itcan behelpfultostopjustbeforetheendofa functionsothatthereturnvaluecanbedis played or changed. Sometimes the pro grammermaywanttobypassexecutionof afunction,returningaknownvalueinstead

ofwhatthefunctionwouldhave(possibly Sunextensions. Nonetheless,stabsisstill incorrectly)computed. widelyused. There arealsodata relatedoperations that are useful. For example, displaying thetypeofavariablecanavoidhavingto lookupthetypeinthesourcefiles. Dis playingthevalueofavariableindifferent formats,ordisplayingamemoryorregister inaspecifiedformatishelpful. Therearesomeoperationswhichmight be called advanced debugging functions: for example, being able to debug multi threaded programs or programs stored in writeonlymemory.Onemightwantade bugger (or some other program analysis tool)tokeeptrackofwhethercertainsec tions of code had been executed or not. Somedebuggersallowtheprogrammerto callfunctionsintheprogrambeingtested. In the notsodistant past, debugging pro gramsthathadbeenoptimizedwouldhave beenconsideredanadvancedfeature. Thetaskofadebuggeristoprovidethe programmerwithaviewoftheexecuting programinasnaturalandunderstandable fashionaspossible,whilepermittingawide range of control over its execution. This meansthatthedebuggerhastoessentially reverse much of the compilers carefully craftedtransformations,convertingthepro gramsdataandstatebackintotheterms thattheprogrammeroriginallyusedinthe programssource. COFF stands for Common Object File FormatandoriginatedwithUnixSystemV Release3. Rudimentarydebugging infor mationwasdefinedwiththeCOFFformat, butsinceCOFFincludessupportfornamed sections, a variety of different debugging formatssuchasstabshavebeenusedwith COFF. Themostsignificantproblemwith COFF is that despite the Common in its name,itisntthesameineacharchitecture which uses the format. There are many variationsinCOFF,includingXCOFF(used onIBMRS/6000),ECOFF(used onMIPS and Alpha), and the Windows PECOFF. Documentation of these variants is avail abletovaryingdegreesbutneithertheob jectmoduleformatnor thedebuggingin formationisstandardized.

A Brief History of DWARF2


DWARF 1 Unix SVR4 sdb and PLSIG

WARForiginatedwiththeCcompiler and sdb debugger in Unix System V Release4(SVR4)developedbyBellLabsin the mid1980s. The Programming Lan guagesSpecialInterestGroup(PLSIG),part ofUnixInternational(UI),documentedthe DWARFgeneratedbySVR4asDWARF1in 1989. Although the original DWARF had several clear shortcomings, most notably thatitwasnotverycompact,thePLSIGde cidedtostandardizetheSVR4formatwith onlyminimalmodification. Itwaswidely adoptedwithintheembeddedsectorwhere itcontinuestobeusedtoday,especiallyfor PECOFF is the object module format smallprocessors. usedbyMicrosoftWindowsbeginningwith Windows95.ItisbasedontheCOFFfor DWARF 2 PLSIG mat and contains both COFF debugging hePLSIGcontinuedontodevelopand dataandMicrosoftsownproprietaryCode documentextensionstoDWARFtoad VieworCV4debuggingdataformat.Docu dressseveralissues,themostimportantof mentationonthedebuggingformatisboth which was to reduce the amount of data sketchyanddifficulttoobtain. thatweregenerated.Therewerealsoaddi

OMFstandsforObjectModuleFormat andistheobjectfileformatusedinCP/M, DOSandOS/2systems,aswellasasmall number of embedded systems. OMF de fines public name and line number infor mationfordebuggersandcanalsocontain Thechallengeofadebuggingdatafor MicrosoftCV,IBMPM,orAIXformatde mat,likeDWARF,istomakethispossible buggingdata.OMFonlyprovidesthemost andeveneasy. rudimentarysupportfordebuggers.

tionstosupportnewlanguagessuchasthe upandcoming C++ language. DWARF 2 wasreleasedasadraftstandardin1990. Inanexampleofthedominotheoryin action, shortly after PLSIG released the draftstandard,fatalflawswerediscovered in Motorola's 88000 microprocessor. Mo torola pulled the plug on the processor, which in turn resulted in the demise of Open88, a consortium of companies that were developing computers using the 88000.Open88inturnwasasupporterof UnixInternational,sponsorofPLSIG,which resulted in UI being disbanded. When UI folded,allthatremainedofthePLSIGwas amailinglistandavarietyofftpsitesthat hadvariousversionsoftheDWARF2draft standard. A final standard was never re leased. Since Unix International had disap pearedandPLSIGdisbanded,severalorga nizationsindependentlydecidedtoextend DWARF1and2.Someoftheseextensions were specific to a single architecture, but othersmightbeapplicabletoanyarchitec ture.Unfortunately,thedifferentorganiza tionsdidntworktogetherontheseexten sions.Documentationontheextensionsis generallyspottyordifficulttoobtain.Oras a GCC developer might suggest, tongue
2

Debugging Formats

here are several debugging formats: stabs,COFF,PECOFF,OMF,IEEE695, and three versions of DWARF, to name somecommonones. Imnotgoingtode scribetheseinanydetail. Theintenthere is only to mention them to place the DWARFDebuggingFormatincontext. Thename stabs comesfrom symbol ta ble strings,sincethedebuggingdatawere originally saved as strings in Unixs a.out object files symbol table. Stabs encodes the information about a program in text strings. Initially quite simple, stabs has evolvedovertimeintoaquitecomplex,oc casionally cryptic and lessthanconsistent debuggingformat. Stabsis not standard ized nor well documented1. Sun Micro systemshasmadeanumberofextensions tostabs. GCChasmadeotherextensions, while attempting to reverse engineer the
1

IEEE695is a standard object file and debuggingformatdevelopedjointlybyMi crotecResearchandHPinthelate1980s forembeddedenvironments.Itbecamean IEEEstandardin1990.Itisaveryflexible specification,intendedtobeusablewithal most any machine architecture. The de buggingformatisblockstructured,which corresponds to the organization of the sourcebetterthanotherformats.Although itisanIEEEstandard,inmanywaysIEEE 695 is more like the proprietary formats. Although the original standard is readily availablefromIEEE,Microtecmadeanum berofextensionstosupportC++andopti mzedcodewhicharepoorlydocumented. TheIEEEstandardwasneverrevisedtoin corporate any of the Microtec and other changes.

In1992,theauthorwroteanextensivedocumentde scribingthestabsgeneratedbySunMicrosytems'com pilers.Unfortunately,itwasneverwidelydistributed.

ThenameDWARFissomethingofapun,sinceitwas developedalongwiththeELFobjectfileformat. The namemaybeanacronymforDebuggingWithAttribut edRecordFormats,althoughthisisnotmentionedin anyoftheDWARFstandards.

Introduction to the DWARF Debugging Format

Michael J. Eager

firmly in cheek, the extensions were well documented:allyouhavetodoisreadthe compilersourcecode.DWARFwaswellon itswaytofollowingCOFFandbecominga collection of divergent implementations ratherthanbeinganindustrystandard.

a program, you first look in the current scope,theninsuccessiveenclosingscopes untilyoufindthesymbol. Theremaybe multiple definitions of the same name in differentscopes. Compilersverynaturally representaprograminternallyasatree. DWARFfollowsthismodelinthatitis alsoblockstructured.Eachdescriptiveenti tyinDWARF(exceptforthetopmostentry which describes the source file) is con tainedwithinaparententryandmaycon tain children entities. If a node contains multipleentities,theyareallsiblings,relat edtoeachother. TheDWARFdescription ofaprogramisatreestructure,similarto the compilers internal tree, where each node can have children or siblings. The nodes may represent types, variables, or functions.Thisisacompactformatwhere onlytheinformationthatisneededtode scribeanaspectofaprogramisprovided. Theformatisextensibleinauniformfash ion,sothatadebuggercanrecognizeand ignore an extension, even if it might not understanditsmeaning.(Thisismuchbet terthanthesituationwithmostotherde bugging formats wherethe debugger gets fatally confused attempting to read modi fieddata.)DWARFisalsodesignedtobe extensible to describe virtually any proce dural programming language on any ma chinearchitecture,ratherthanbeingbound toonlydescribingonelanguageoronever

sionofalanguageonalimitedrangeofar chitectures. WhileDWARFismostcommonlyasso ciatedwiththeELFobjectfileformat,itis independent of the object file format. It can and has been used with other object fileformats.Allthatisnecessaryisthatthe different data sections that make up the DWARF data be identifiable in the object fileorexecutable.DWARFdoesnotdupli cate information that is contained in the objectfile,suchasidentifyingtheprocessor architectureorwhetherthefileiswrittenin bigendianorlittleendianformat.

DWARF 3 Free Standards Group

espite several online discussions aboutDWARFonthePLSIGemaillist (whichsurvivedunderX/Open(laterOpen Group) sponsorship after UIs demise), therewaslittleimpetustorevise(oreven finalize) the document until the end of 1999. Atthattime,therewasinterestin extending DWARF to have better support fortheHP/IntelIA64architectureaswell asbetterdocumentationoftheABIusedby C++programs.Thesetwoeffortsseparat ed,andtheauthortookoverasChairfor therevivedDWARFCommittee. Followingmorethan18monthsofde velopmentworkandcreationofadraftof the DWARF 3 specification, the standard ization hit what might be called a soft patch.Thecommittee(andthisauthor,in particular) wanted to insure that the DWARFstandardwasreadilyavailableand toavoidthepossibledivergencecausedby multiple sources for the standard. The DWARF Committee became the DWARF WorkgroupoftheFreeStandardsGroupin 2003.Activedevelopmentandclarification oftheDWARF3Standardresumedearlyin 2005withthegoaltoresolveanyopenis suesinthestandard.Apublicreviewdraft wasreleasedtosolicitpubliccommentsin October and the final version of the DWARF 3 Standard was released in Jan uary, 2006. After the Free Standards GroupmergedwithOpenSourceDevelop mentLabs(OSDL)toformtheLinuxFoun dation,theDWARFCommitteereturnedto independent status and created its own websiteatdwarfstd.org.

Debugging Information Entry (DIE)


Tags and Attributes

hebasicdescriptiveentityinDWARFis the Debugging Information Entry (DIE). A DIE has a tag, which specifies what the DIE describes and a list of at tributeswhichfillindetailsandfurtherde scribestheentity.ADIE(exceptforthetop most)iscontainedinorownedbyaparent DIEandmayhavesiblingDIEsorchildren DIEs. Attributes may contain a variety of values: constants (such as a function name),variables(suchasthestartaddress

hello.c: 1: int main() 2: { 3: printf("Hello World!\n"); 4: return 0; 5: }

DIE Compilation Unit


Dir = /home/dwarf/exam ples Name = hello.c LowPC = 0x0 HighPC = 0x2b Producer = GCC

DWARF Overview

ost modernprogramminglanguages are block structured: each entity (a classdefinitionorafunction,forexample) is contained within another entity. Each fileina C program may contain multiple data definitions, multiple variable defini tions,andmultiplefunctions.Withineach Cfunctiontheremaybeseveraldatadefini tionsfollowedbyexecutablestatements.A statementmayacompoundstatementthat inturncancontaindatadefinitionsandex ecutable statements. This creates lexical scopes,wherenamesareknownonlywith inthescopeinwhichtheyaredefined.To findthedefinitionofaparticularsymbolin Introduction to the DWARF Debugging Format

DIE Subprogram

Name = main File = hello.c Line = 2 Type = int LowPC = 0x0 HighPC = 0x2b External = yes

DIE Base Type

Name = int ByteSize = 4 Encoding = signed integer

Figure1.GraphicalrepresentationofDWARFdata 3 Michael J. Eager

for a function), or references to another tionforthesetypes,Conlyspecifiessome ueis16bitswideandanoffsetfromthe DIE(suchasforthetypeofafunctionsre general characteristics, allowing the com highorderbitofzero.(Thisisareallifeex turnvalue). plier to pick the actual specifications that ample taken from an implementation of best fit the target processor. Some lan Pascalthatpassed16bitintegersinthetop Figure 1 shows C's classic hello.c guages,likePascal,allownewbasetypesto halfofawordonthestack.) programwithasimplifiedgraphicalrepre be defined, for example, an integer type TheDWARFbasetypesallowanumber whichcanholdintegervaluesbe ofdifferentencodingstobedescribed,in tween0and100.Pascaldoesn't cluding address, character, fixed point, DW_TAG_base_type specifyhowthisshouldbeimple floatingpoint,andpackeddecimal,inaddi DW_AT_name = int mented.Onecompilermightim DW_AT_byte_size = 4 tiontobinaryintegers.Thereisstillalittle plementthisasasinglebyte,an DW_AT_encoding = signed ambiguityremaining:forexample,theac othermightusea16bitinteger, tualencodingforafloatingpointnumberis athirdmightimplementallinte Figure2a.intbasetypeon32bitprocessor. notspecified;thisisdeterminedbytheen gertypesas32bitvaluesnomat codingthatthehardwareactuallysupports. terhowtheyaredefined. Inaprocessorwhichsupportsboth32bit With DWARF Version 1 and and 64bit floating point values following DW_TAG_base_type other debugging formats, the theIEEE754standard,theencodingsrep DW_AT_name = int compiler and debugger are sup resentedbyfloataredifferentdepending DW_AT_byte_size = 2 posedtoshareacommonunder onthesizeofthevalue. DW_AT_encoding = signed standingaboutwhetheran int is Figure2b.intbasetypeon16bitprocessor 16,32,oreven64bits.Thisbe comes awkward when the same hardware can support sentation of its DWARF description. The topmost DIE represents the compilation different size integers or when DW_TAG_base_type unit.Ithastwochildren,thefirstisthe different compilers make differ DW_AT_name = word entimplementationdecisionsfor DIE describing main and the second de DW_AT_byte_size = 4 thesametargetprocessor.These scribingthebasetypeintwhichisthetype DW_AT_bit_size = 16 of thevaluereturnedby main. Thesub assumptions,oftenundocument DW_AT_bit_offset = 0 DW_AT_encoding = signed programDIEisachildofthecompilation ed,makeitdifficulttohavecom unitDIE,whilethebasetypeDIEisrefer patibilitybetweendifferentcom Figure3.16bitwordtypestoredinthetop16 encedbytheTypeattributeinthesubpro pilersordebuggers,orevenbe tween different versions of the bitsofa32bitword. gramDIE.WealsotalkaboutaDIEown sametools. ingorcontainingthechildrenDIEs.

Types of DIEs

IEscanbesplitintotwogeneraltypes. Those that describe data including datatypesandthosethatdescribefunctions andotherexecutablecode.

Describing Data and Types

ostprogramminglanguageshaveso phisticated descriptions of data. Thereareanumberofbuiltindatatypes, pointers,variousdatastructures,andusual lywaysofcreatingnewdatatypes.Since DWARFisintendedtobeusedwithavari etyoflanguages,itabstractsoutthebasics andprovidesarepresentationthatcanbe usedforallsupportedlanguage.Theprima rytypes,builtdirectlyonthehardware,are the basetypes. Otherdatatypesarecon structed as collections or compositions of thesebasetypes.

Base Types

very programming language defines severalbasicscalardatatypes.Forex ample,bothCandJavadefineintanddou ble.WhileJavaprovidesacompletedefini

DWARF base types provide <1>: DW_TAG_base_type the lowest level mapping be DW_AT_name = int tweenthesimpledatatypesand DW_AT_byte_size = 4 how they are implemented on DW_AT_encoding = signed the target machine's hardware. Thismakesthedefinitionof int <2>: DW_TAG_variable DW_AT_name = x explicitforbothJavaandCand DW_AT_type = <1> allowsdifferentdefinitionstobe used, possibly even within the Figure4.DWARFdescriptionofint x. sameprogram.Figure2ashows theDIEwhichdescribesintona typical32bitprocessor.Theat tributesspecifythename(int),anencoding Type Composition (signed binary integer), and the size in namedvariableisdescribedbyaDIE bytes(4).Figure2bshowsasimilardefini whichhasavarietyofattributes,one tionofintona16bitprocessor.(InFigure ofwhichisareferencetoatypedefinition. 2,weusethetagandattributenamesde Figure 4 describes an integer variable finedintheDWARFstandard,ratherthan named x.(Forthemomentwewillignore themoreinformalnamesusedabove.The the other information that is usually con names of tags are all prefixed with tainedinaDIEdescribingavariable.) DW_TAG and the names of attributes are Thebasetypefor int describesitasa prefixedwithDW_AT.) signedbinaryintegeroccupyingfourbytes. The base types allow the compiler to The DW_TAG_variable DIE for x gives its describe almost any mapping between a nameandatypeattribute,whichrefersto programming language scalar type and thebasetypeDIE.Forclarity,theDIEsare howitisactuallyimplementedonthepro labeledsequentiallyinthethisandfollow cessor.Figure3describesa16bitinteger ingexamples;intheactualDWARFdata,a valuethatisstoredintheupper16bitsofa reference to a DIE is the offset from the fourbyteword.Inthisbasetype,thereisa startofthecompilationunitwheretheDIE bitsizeattributethatspecifiesthattheval canbefound. Referencescanbetoprevi

Introduction to the DWARF Debugging Format

Michael J. Eager

ously defined DIEs, as in Figure 4, or to Array DIEs which are defined later. Once we rray types are described by a DIE havecreatedabasetypeDIEfor int,any which defines whether the data is variableinthesamecompilationcanrefer 3 storedin columnmajororder(asinFortan) encethesameDIE . or in rowmajor order(asinCor C++). DWARFusesthebasetypestoconstruct Theindexforthearrayisrepresentedbya otherdatatypedefinitionsbycomposition. subrangetype thatgivesthelowerandup Anewtypeiscreatedasamodificationof perboundsofeachdimension.Thisallows anothertype.Forexample,Figure5shows DWARF to describe both C style arrays, apointertoanintonourtypical32bitma which alwayshave zero as thelowestin chine.ThisDIEdefinesapointertype,spec dex, as well as arrays in Pascal or Ada, ifiesthatitssizeisfourbytes,andinturn whichcanhaveanyvalueforthelowand referencestheintbasetype.OtherDIEsde highbounds. scribethe const or volatile attributes,C++ reference type, or C restrict types. These type DIEs can be chained together to de Structures, Classes,

vate,orprotected.Thesearedescribedwith theaccessibilityattribute. C and C++ allow bit fields as class members that are not simple variables. Thesearedescribedwithbitoffsetfromthe startoftheclassinstancetotheleftmost bitofthebitfieldanda bitsize thatsays howmanybitsthememberoccupies.

Variables

<1>: DW_TAG_variable DW_AT_name = px DW_AT_type = <2> <2>: DW_TAG_pointer_type DW_AT_byte_size = 4 DW_AT_type = <3> <3>: DW_TAG_base_type DW_AT_name = word DW_AT_byte_size = 4 DW_AT_encoding = signed

Unions, and Interfaces

ariables are generally pretty simple. Theyhaveanamewhichrepresentsa chunk of memory (or register) that can containsomekindofavalue.Thekindof valuesthatthevariablecancontain,aswell as restrictions on how it can be modified (e.g.,whetheritis const)aredescribedby thetypeofthevariable. What distinguishes variables is where the variable is stored and its scope. The scopeofavariabledefineswherethevari ableknownwithintheprogramandis,to some degree, determined by where the variable is declared. In C, variables de claredwithinafunctionorblockhavefunc tionorblockscope.Thosedeclaredoutside afunctionhaveeitherglobalorfilescope. This allows different variables with the samenametobedefinedindifferentfiles withoutconflicting.Italsoallowsdifferent functionsorcompilationstoreferencethe same variable. DWARF documents where the variable is declared in the source file witha(file,line,column)triplet. DWARFsplitsvariablesintothreecate gories:constants,functionparameters,and variables. A constant is used to describe languagesthathavetruenamedconstants aspartofthelanguage,suchasAdaparam eters.(Cdoesnothaveconstantsaspartof thelanguage.Declaringavariableconstjust says that you cannot modify the variable withoutusinganexplicitcast.)Aformalpa rameterrepresentsvaluespassedtoafunc tion.We'llcomebacktothatabitlater.

Figure5.DWARFdescriptionofint *px.

<1>: DW_TAG_variable DW_AT_name = argv DW_AT_type = <2> <2>: DW_TAG_pointer_type DW_AT_byte_size = 4 DW_AT_type = <3>

Most languages allow the programmer to group data to gether into structures (called struct in C and C++, class in C++,andrecordinPascal).Each ofthecomponentsofthestruc turegenerallyhasauniquename and may have a different type, andeachoccupiesitsownspace. CandC++havethe union and Pascalhasthevariantrecordthat aresimilartoastructureexcept that the component occupy the same memory locations. The Javainterfacehasasubsetofthe propertiesofaC++ class,since itmayonlyhaveabstractmeth odsandconstantdatamembers.

Although each language has itsownterminology(C++calls thecomponentsofaclass mem <3>: DW_TAG_pointer_type bers while Pascal calls them DW_AT_byte_size = 4 fields) the underlying organiza DW_AT_type = <4> tioncanbedescribedinDWARF. Truetoitsheritage,DWARFuses <4>: DW_TAG_const_type theC/C++terminologyandhas DW_AT_type = <5> DIEs which describe struct, <5>: DW_TAG_base_type union, class, and interface. We'll DW_AT_name = char Some languages, like C or C++ (but describe the class DIE here, but DW_AT_byte_size = 1 notPascal),allowavariabletobedeclared the others have essentially the DW_AT_encoding = unsigned withoutdefiningit.Thisimpliesthatthere sameorganization. shouldbearealdefinitionofthevariable Figure6.DWARFdescriptionof TheDIEforaclassisthepar somewhereelse,hopefullysomewherethat const char **argv. ent of the DIEs which describe thecompilerordebuggercanfind.ADIE each of the class's members. describingavariabledeclarationprovidesa Eachclasshasanameandpossi descriptionofthevariablewithoutactually scribe more complex data types, such as bly other attributes. If the size of an in tellingthedebuggerwhereitis. const char **argv which is de stance is known at compile time, then it scribedinFigure6. Mostvariableshavealocationattribute willhaveabytesizeattribute.Eachofthese descriptions looks very much like the de thatdescribeswherethevariableisstored. scription of a simple variable, although Inthesimplestofcases,avariableisstored 4 there may be some additional attributes. in memory and has a fixed address . But 3 Forexample,C++allowstheprogrammer Somecompilersdefineacommonsetoftypedefini 4 tionsatthestartofeverycompilationunit.Othersonly tospecifywhetheramemberispublic,pri Well,maybenotafixedaddress,butonethatisafixed
generatethedefinitionsforthetypeswhichareactually referencedintheprogram.Eitherisvalid. offsetfromwheretheexecutableisloaded.Theloader relocatesreferencestoaddresseswithinanexecutable

Introduction to the DWARF Debugging Format

Michael J. Eager

many variables, such as those declared withinaCfunction,aredynamicallyallo cated and locating them requires some (usuallysimple)computation.Forexample, a local variable may be allocated on the stack,andlocatingitmaybeassimpleas addingafixedoffsettoaframepointer.In othercases,thevariablemaybestoredina register.Othervariablesmayrequiresome whatmorecomplicatedcomputationstolo catethedata.Avariablethatisamember ofaC++classmayrequiremorecomplex computationstodeterminethelocationof thebaseclasswithinaderivedclass.

Describing Executable Code


Functions and Subprograms

WARFtreatsfunctionsthatreturnval ues and subroutines that do not as variationsofthesamething.Driftingslight ly away from its roots in C terminology, DWARFdescribesbothwithaSubprogram DIE.ThisDIEhasaname,asourcelocation triplet, and an attribute which indicates whetherthesubprogramisexternal,thatis, visibleoutsidethecurrentcompilation. A Subprogram DIE has attributes that give the low and high memory addresses thatthesubprogramoccupies,ifitiscon tiguous,oralistofmemoryrangesifthe functiondoesnotoccupyacontiguousset ofmemoryaddresses.ThelowPCaddress is assumed to be the entry point for the routine unless another one is explicitly specified.

A function may define variables that maybelocalorglobal.TheDIEsforthese variablesfollowtheparameterDIEs.Many languages allow nesting of lexical blocks. ThesearerepresentedbylexicalblockDIEs which in turn, may own variable DIEs or nestedlexicalblockDIEs. Here is a somewhat longer example. Figure 8a shows the source for strndup.c, a function in gcc that dupli catesastring. Figure8bliststheDWARF generatedforthisfile.Asinpreviousexam ples,thesourcelineinformationandthelo cationattributesarenotshown.

Location Expressions

WARFprovidesaverygeneralscheme todescribehowtolocatethedatarep resentedbyavariable.ADWARFlocation expression contains a sequence of opera tionswhichtelladebuggerhowtolocate the data. Figure 7 shows DIEs for three variablesnameda,b,andc.Variableahas afixedlocationinmemory,variablebisin register 0, and variable c is at offset 12 within the current function's stack frame. Although a was declared first,the DIE to describeitisgeneratedlater,afterallfunc tions.Theactuallocationofawillbefilled inbythelinker. The DWARF location expression can containasequenceofoperatorsandvalues that are evaluated by a simple stack ma chine. This can be an arbitrarily complex computation, with a wide range of arith meticoperations,testsandbrancheswithin theexpression,callstoevaluateotherloca tion expressions,and accesses to the pro cessor's memory or registers. There are even operations used to describe data whichissplitupandstoredindifferentlo cations, such as a structure where some data are stored in memory and some are storedinregisters. Althoughthisgreatflexibilityisseldom used in practice, the location expression should allow the location of a variable's datatobedescribednomatterhowcom plexthelanguagedefinitionorhowclever thecompiler'soptimizations.

InFigure8b,DIE<2>showsthedefi nitionof size_t whichisa typdef of unsigned int. Thisallowsadebuggerto displaythetypeofformalargumentnasa size_t, while displaying its value as an unsignedinteger. DIE<5>describesthe functionstrndup.Thishasapointertoits sibling, DIE <10>; all of the following DIEsarechildrenoftheSubprogramDIE. Thevaluethatafunctionreturnsisgiv Thefunctionreturnsapointertochar,de en by the type attribute. Subroutines that scribedinDIE<10>. DIE<5>alsode donotreturnvalues(likeCvoidfunctions) scribesthesubroutineas external and pro donothavethisattribute.DWARFdoesn't totypedandgivesthelowandhighPCval describethecallingconventionsforafunc uesfortheroutine.Theformalparameters tion;thatisdefinedintheApplicationBina and local variables of the routine are de ryInterface(ABI)fortheparticulararchi scribedinDIEs<6>to<9>. tecture.Theremaybeattributesthathelpa debugger to locate the subpro gram'sdataortofindthecurrent subprogram's caller. The return fig7.c: addressattributeisalocationex 1: int a; pressionthatspecifieswherethe 2: void foo() address of the caller is stored. 3: { The framebase attributeisalo 4: register int b; 5: int c; cationexpressionthatcomputes 6: } the address of the stack frame forthefunction.Theseareuseful <1>: DW_TAG_subprogram sincesomeofthemostcommon DW_AT_name = foo optimizations that a compiler <2>: DW_TAG_variable DW_AT_name = b might do are to eliminate in DW_AT_type = <4> structionsthatexplicitlysavethe DW_AT_location = returnaddressorframepointer. The subprogram DIE owns DIEs that describe the subpro gram.Theparametersthatmay bepassedtoafunctionarerep resentedbyvariableDIEswhich have the variable parameter at tribute. If the parameter is op tional or has a default value, these are represented by at tributes.TheDIEsfortheparam eters are in the same order as the argument list for the func tion,buttheremaybeadditional DIEs interspersed, for example, todefinetypesusedbythepa rameters.
<3>: (DW_OP_reg0) DW_TAG_variable DW_AT_name = c DW_AT_type = <4> DW_AT_location = (DW_OP_fbreg: -12) DW_TAG_base_type DW_AT_name = int DW_AT_byte_size = 4 DW_AT_encoding = signed DW_TAG_variable DW_AT_name = a DW_AT_type = <4> DW_AT_external = 1 DW_AT_location = (DW_OP_addr: 0)

<4>:

<5>:

sothatatruntimethelocationattributecontainsthe actualmemoryaddress.Inanobjectfile,thelocationat tributeistheoffset,alongwithanappropriatereloca tiontableentry.

Figure7.DWARFdescriptionofvariables a,b,andc.

Introduction to the DWARF Debugging Format

Michael J. Eager

strndup.c: 1: #include "ansidecl.h" 2: #include <stddef.h> 3: 4: extern size_t strlen (const char*); 5: extern PTR malloc (size_t); 6: extern PTR memcpy (PTR, const PTR, size_t); 7: 8: char * 9: strndup (const char *s, size_t n) 10: { 11: char *result; 12: size_t len = strlen (s); 13: 14: if (n < len) 15: len = n; 16: 17: result = (char *) malloc (len + 1); 18: if (!result) 19: return 0; 20: 21: result[len] = '\0'; 22: return (char *) memcpy (result, s, len); 23: }

about the compila tion,includingthedi rectory and name of the source file, the programming lan guage used, a string which identifies the producer of the DWARFdata,andoff sets into the DWARF data sections to help locate the line num ber and macro infor mation. If the compilation unit is contiguous (i.e.,itisloadedinto memoryinonepiece) thentherearevalues for the low and high memoryaddressesfor theunit.Thismakesit easierforadebugger

areinthesameorderinwhichtheyappear inthesourcefile.

Data encoding

onceptually,theDWARFdatathatde scribesaprogramisatree.EachDIE mayhaveasiblingandseveralDIEsthatit contains. Each of the DIEs has a type (calleditsTAG)andanumberofattributes. Eachattributesisrepresentedbyaattribute typeandavalue.Unfortunately,thisisnot a very dense encoding. Without compres sion,theDWARFdataisunwieldy. DWARFVersions2and3offerseveral waystoreducethesizeofthedatawhich needstobesavedwiththeobjectfile.The firstisto"flatten"thetreebysavingitin prefixorder.EachtypeofDIEisdefinedto eitherhavechildrenornot.IftheDIEcan nothave children,thenextDIEisitssib ling.IftheDIEcanhavechildren,thenthe next DIE is its first child. The remaining childrenarerepresentedasthesiblingsof thisfirstchild.Thisway,linkstothesibling or child DIEs can be eliminated. If the compilerwriterthinksthatitmightbeuse fultobeabletojumpfromoneDIEtoits siblingwithoutsteppingthrougheachofits childrenDIEs(forexample,tojumptothe nextfunctioninacompilation)thena sib lingattributecanbeaddedtotheDIE. Asecondschemetocompressthedata is to use abbreviations. Although DWARF allows great flexibility in which DIEs and attributesitmaygenerate,mostcompilers onlygeneratealimitedsetofDIEs,allof whichhavethesamesetofattributes.In steadofstoringthevalueoftheTAGofthe DIEandtheattributevaluepairs,onlyan indexintoatableofabbreviationsisstored, followed by the attribute codes. Each ab breviationgivesthetagvalue,aflagindi catingwhethertheDIEhaschildren,anda listofattributeswiththetypeofvalueitex pects.Figure9showstheabbreviationfor the formal parameter DIE used in Figure 8b.DIE<6>inFigure8isactuallyencod edasshown5.Thisisasignificantreduction in the amount of data that needs to be savedatsomeexpenseinaddedcomplexi ty. Less commonly used are features of DWARF Version 3 which allow references fromone compilation unitto the DWARF datastoredinanothercompilationunitor inasharedlibrary.Manycompilersgener ate the same abbreviation table or base typesforeverycompilation,independentof whetherthecompilationactuallyusesallof the abbreviations or types. These can be
5

Figure8a.Sourceforstrndup.c.

<1>: DW_TAG_base_type DW_AT_name = int DW_AT_byte_size = 4 DW_AT_encoding = signed <2>: DW_TAG_typedef DW_AT_name = size_t DW_AT_type = <3> <3>: DW_TAG_base_type DW_AT_name = unsigned int DW_AT_byte_size = 4 DW_AT_encoding = unsigned <4>: DW_TAG_base_type DW_AT_name = long int DW_AT_byte_size = 4 DW_AT_encoding = signed <5>: DW_TAG_subprogram DW_AT_sibling = <10> DW_AT_external = 1 DW_AT_name = strndup DW_AT_prototyped = 1 DW_AT_type = <10> DW_AT_low_pc = 0 DW_AT_high_pc = 0x7b <6>: DW_TAG_formal_parameter DW_AT_name = s DW_AT_type = <12> DW_AT_location = (DW_OP_fbreg: 0)

<7>: DW_TAG_formal_parameter DW_AT_name = n DW_AT_type = <2> DW_AT_location = (DW_OP_fbreg: 4) <8>: DW_TAG_variable DW_AT_name = result DW_AT_type = <10> DW_AT_location = (DW_OP_fbreg: -28) <9>: DW_TAG_variable DW_AT_name = len DW_AT_type = <2> DW_AT_location = (DW_OP_fbreg: -24) <10>: DW_TAG_pointer_type DW_AT_byte_size = 4 DW_AT_type = <11> <11>: DW_TAG_base_type DW_AT_name = char DW_AT_byte_size = 1 DW_AT_encoding = signed char <12>: DW_TAG_pointer_type DW_AT_byte_size = 4 DW_AT_type = <13> <13>: DW_TAG_const_type DW_AT_type = <11>

Figure8b.DWARFdescriptionforstrndup.c.

Compilation Unit

ost interesting programs consists of morethanasinglefile.Eachsource filethatmakesupaprogramiscompiled independently and then linked together withsystemlibrariestomakeupthepro gram. DWARF calls each separately com TheCompilationUnitDIEistheparent piledsourcefileacompilationunit. ofalloftheDIEsthatdescribethecompila tionunit.Generally,thefirstDIEswillde TheDWARFdataforeachcompilation scribedatatypes,followedbyglobaldata, unit starts with a Compilation Unit DIE. thenthefunctionsthatmakeupthesource This DIE contains general information file. The DIEs for variables and functions Introduction to the DWARF Debugging Format 7

toidentifywhichcompilationunitcreated thecodeataparticularmemoryaddress.If thecompilationunitisnotcontiguous,then a list of the memory addresses that the codeoccupiesisprovidedbythecompiler andlinker.

Theencodedentryalsoincludesthefileandlinevalues whicharenotshowninFig.8b.

Michael J. Eager

Abbrev 5:

DW_TAG_formal_parameter [no children] DW_AT_name DW_FORM_string DW_AT_decl_file DW_FORM_data1 DW_AT_decl_line DW_FORM_data1 DW_AT_type DW_FORM_ref4 DW_AT_location DW_FORM_block1

ost debuggers have a very difficult timedisplayinganddebuggingcode Figure9.Abbreviationentryandencodedform. whichhasmacros.Theuserseestheorigi nalsourcefile,withthemacros,whilethe code corresponds to whatever the macros savedinasharedlibraryandreferencedby pressesthisdatabyencodingitassequence generated. each compilation unit, rather than being of instructions called a line number pro DWARFincludesthedescriptionofthe duplicatedineach. gram6.Theseinstructionsareinterpretedby asimplefinitestatemachinetorecreatethe macros defined in the program. This is quiterudimentaryinformation,butcanbe completelinenumbertable. Other DWARF Data used by a debugger to display the values The finite state machine is initialized foramacroorpossiblytranslatethemacro withasetofdefaultvalues.Eachrowinthe intothecorrespondingsourcelanguage. Line Number Table line number heDWARFlinetablecontainsthemap tableisgener pingbetweenthesourcelines(forthe ated by exe executable parts of a program) and the cuting one or memorythatcontainsthecodethatcorre more of the spondstothesource.Inthesimplestform, opcodesofthe Address File Line Col Stmt Block End Prolog Epilog ISA thiscanbelookedatasamatrixwithone line number column containing the memory addresses program. The 0x0 0 42 0 yes no no no no 0 andanothercolumncontainingthesource opcodes are 0x9 0 44 0 yes no no no no 0 triplet(file,line,andcolumn).Ifyouwant generally 0x1a 0 44 0 yes no no no no 0 tosetabreakpointataparticularline,the quite simple: 0x24 0 46 0 yes no no no no 0 table gives you the memory address to for example, 0x2c 0 47 0 yes no no no no 0 storethebreakpointinstruction.Converse addavalueto 0x32 0 49 0 yes no no no no 0 ly,ifyourprogramhasafault(say,usinga eitherthema 0x41 0 50 0 yes no no no no 0 badpointer)atsomelocationinmemory, chine address 0x47 0 51 0 yes no no no no 0 youcanlookforthesourcelinethatisclos or to the line 0x50 0 53 0 yes no no no no 0 esttothememoryaddress. 0x59 0 54 0 yes no no no no 0 number, set 0x6a 0 54 0 yes no no no no 0 DWARF has extended this with added the column 0x73 0 55 0 yes no no no no 0 columns to convey additional information number, or 0x7b 0 56 0 yes no yes no no 0 set a flag aboutaprogram.Asacompileroptimizes File0: strndup.c the program, it may move instructions which indi File1:stddef.h aroundorremovethem.Thecodeforagiv cates that the memory ad ensourcestatementmaynotbestoredasa Figure10.LineNumberTableforstrndup.c. sequenceofmachineinstructions,butmay dress repre be scattered and interleaved with the in sentsthestart structions for other nearby source state of an source ments.Itmaybeusefultoidentifytheend statement,the Call Frame Information ofthecodewhichrepresentstheprologof endofthefunctionprolog,orthestartof very processor has a certain way of afunctionorthebeginningoftheepilog,so thefunctionepilog.Asetofspecialopcodes calling functions and passing argu combinethemostcommonoperations(in thatthedebuggercanstopafterallofthe ments, usually defined in the ABI. In the crementingthememoryaddressandeither argumentstoafunctionhavebeenloaded or beforethefunctionreturns.Somepro incrementing or decrementing the source simplest case, this is the same for each function and the debugger knows exactly cessorscanexecutemorethanoneinstruc linenumber)intoasingleopcode. how to find the argumentvaluesand the tionset,sothereisanothercolumnthatin Finally,ifarowofthelinenumberta dicateswhichsetisstoredatthespecified blehasthesamesourcetripletastheprevi returnaddressforthefunction. machinelocation. Forsomeprocessors,theremaybedif ousrow,thennoinstructionsaregenerated Asyoumightimagine,ifthistablewere 6 Callingthisalinenumberprogramissomethingofa ferentcallingsequencesdependingonhow storedwithonerowforeachmachinein misnomer.Theprogramdescribesmuchmorethanjust thefunctioniswritten,forexample,ifthere struction,itwouldbehuge.DWARFcom linenumbers,suchasinstructionset,beginningofbasic are more than a certain number of argu ments. There may be different calling se blocks,endoffunctionprolog,etc.

abbreviation 5 s file 1 line 41 type DIE offset location (fbreg + 0) terminating NUL

for this row in the line number program. Figure10liststhelinenumberprogramfor strndup.c.Noticethatonlythemachine addressesthatrepresentthebeginningin struction of a statement are stored. The compilerdidnotidentifythebasicblocksin thiscode,theendoftheprologorthestart oftheepilogtothefunction. Thistableis encodedinjust31bytesinthelinenumber program.

Macro Information

05 7300 01 29 0000010c 9100 00

Introduction to the DWARF Debugging Format

Michael J. Eager

quences depending on operating systems. Compilers will try to optimize the calling sequence to make code both smaller and faster.Onecommonoptimizationiswhen thereisasimplefunctionwhichdoesn'tcall anyothers(aleaffunction)touseitscaller stackframeinsteadofcreatingitsown.An other optimization may be to eliminate a register which points to the current call frame. Some registers may be preserved acrossthecallwhileothersarenot.Whileit maybepossibleforthedebuggertopuzzle outallthepossiblepermutationsincalling sequence or optimizations, it is both te dious and errorprone. A small change in theoptimizationsandthedebuggermayno longerbeabletowalkthestacktothecall ingfunction. The DWARF Call Frame Information (CFI) provides the debugger with enough informationabouthowafunctioniscalled sothatitcanlocateeachofthearguments to the function, locate the current call frame, and locate the call frame for the callingfunction.Thisinformationisusedby thedebuggerto"unwindthestack,"locat ing the previous function, the location wherethefunctionwascalled,andtheval uespassed. Like the linenumber table,the CFI is encodedasasequenceofinstructionsthat areinterpretedtogenerateatable.Thereis onerowinthistableforeachaddressthat contains code. The first column contains themachineaddresswhilethesubsequent columnscontainthevaluesofthemachine registers when the instruction at that ad dressisexecuted.Likethelinenumberta ble, if this table were actually created it wouldbehuge.Luckily,verylittlechanges between two machine instructions, so the CFIencodingisquitecompact.

ELF sections

Summary

hileDWARFisdefinedinawaythat allowsittobeusedwithanyobject fileformat,it'smostoftenusedwithELF. EachofthedifferentkindsofDWARFdata arestoredintheirownsection.Thenames ofthesesectionsallstartwith".debug_". Forimprovedefficiency,mostreferencesto DWARFdatauseanoffsetfromthestartof thedatafor thecurrentcompilation.This avoidstheneedtorelocatethedebugging data,whichspeedsupprogramloadingand debugging. TheELFsectionsandtheircontentsare
.debug_abbrev .debug_aranges Abbreviationsusedinthe .debug_infosection Amappingbetween memoryaddressand compilation CallFrameInformation ThecoreDWARFdata containingDIEs LineNumberProgram Macrodescriptions Alookuptableforglobal objectsandfunctions

othereyouhaveitDWARFinanut shell.Well,notquiteanutshell.Theba sicconceptsfortheDWARFdebuginforma tionarestraightforward.Aprogramisde scribed as a tree with nodes representing thevariousfunctions,dataandtypesinthe source in a compact language and ma chineindependent fashion. The line table provides the mapping between the exe cutable instructions and the source that generatedthem.TheCFIdescribeshowto unwindthestack. There is quite a bit of subtlety in DWARFaswell,giventhatitneedstoex pressthemanydifferentnuancesforawide rangeof programminglanguagesand dif ferentmachinearchitectures.Futuredirec tions for DWARF are to improve the de scriptionofoptimizedcodesothatdebug gerscanbetternavigatethecodewhichad vancedcompileroptimizationsgenerate. Thecomplete DWARF Version 3Stan dardisavailablefordownloadwithoutcost attheDWARFwebsite(dwarf.freestandard s.org).Thereisalsoamailinglistforques tions and discussion about DWARF. In structionsonregisteringforthemailinglist arealsoonthewebsite.

.debug_frame .debug_info .debug_line .debug_loc .debug_macinfo

.debug_pubnames Alookuptableforglobal objectsandfunctions .debug_pubtypes Alookuptableforglobal types .debug_ranges .debug_str Addressranges referencedbyDIEs Stringtableusedby .debug_info

Acknowledgements
IwanttothankChrisQuenelleofSun MicrosystemsandRonBrender,formerlyof HP, for their comments and advice about thispaper.ThanksalsotoSusanHeimlich forhermanyeditorialcomments.

Introduction to the DWARF Debugging Format

Michael J. Eager

Generating DWARF with GCC


ItsverysimpletogenerateDWARFwithgcc.Simplyspecifythegoptiontogenerate debugginginformation.TheELFsectionscanbedisplayedusingobjumpwiththeh option.

$ gcc g c strndup.c $ objdump h strndup.o


strndup.o: Sections: Idx Name 0 .text 1 2 3 4 5 6 7 8 9 10 11 file format elf32-i386

Size VMA LMA File off Algn 0000007b 00000000 00000000 00000034 2**2 CONTENTS, ALLOC, LOAD, RELOC, READONLY, CODE .data 00000000 00000000 00000000 000000b0 2**2 CONTENTS, ALLOC, LOAD, DATA .bss 00000000 00000000 00000000 000000b0 2**2 ALLOC .debug_abbrev 00000073 00000000 00000000 000000b0 2**0 CONTENTS, READONLY, DEBUGGING .debug_info 00000118 00000000 00000000 00000123 2**0 CONTENTS, RELOC, READONLY, DEBUGGING .debug_line 00000080 00000000 00000000 0000023b 2**0 CONTENTS, RELOC, READONLY, DEBUGGING .debug_frame 00000034 00000000 00000000 000002bc 2**2 CONTENTS, RELOC, READONLY, DEBUGGING .debug_loc 0000002c 00000000 00000000 000002f0 2**0 CONTENTS, READONLY, DEBUGGING .debug_pubnames 0000001e 00000000 00000000 0000031c 2**0 CONTENTS, RELOC, READONLY, DEBUGGING .debug_aranges 00000020 00000000 00000000 0000033a 2**0 CONTENTS, RELOC, READONLY, DEBUGGING .comment 0000002a 00000000 00000000 0000035a 2**0 CONTENTS, READONLY .note.GNU-stack 00000000 00000000 00000000 00000384 2**0 CONTENTS, READONLY

Printing DWARF using Readelf


ReadelfcandisplayanddecodetheDWARFdatainanobjectorexecutablefile.The optionsare
-w -w[liaprmfFso] l i a p r m f F s o display all DWARF sections display specific sections line table debug info abbreviation table public names ranges macro table debug frame (encoded) debug frame (decoded) string table location lists

TheDWARFlistingforallbutthesmallestprogramsisquitevoluminous,soitwould beagoodideatodirectreadelfsoutputtoafileandthenbrowsethefilewith lessor aneditorsuchasvi.

Introduction to the DWARF Debugging Format

10

Michael J. Eager