TillStraumann 3/14/2005;lastmodified7/29/2008 Contents 1IntroductionandFeatures 1.1Architecture...........1.2Multithreading..........1.3CexpSupport...........1.4SupportedTargets........1.5SupportedConnectionMethods1.6GDBPatches...........2Building 3DebuggingSession 3.1Prerequisites...............3.2StartingtheDebuggingAgent.....3.3ConnectingtotheTarget........ 3.3.1SharingtheConsoleSerialLine3.4SwitchingThreadContext.......3.5ExecutingSubroutinesontheTarget.3.6DDDNote.................4RTEMSSpecificGDBCommands5ExampleSession .................................................................................... ................................................................................................ 112223335566778999 1IntroductionandFeatures Thisdocumentcoversversion1.5ofthetargetagent. 1.1Architecture ThisgdbstubisanimplementationoftheremoteendoftheGDBremoteprotocolforaRTEMStarget.Unlikeotherstubsavailablefor 1 RTEMS(e.g.,them68kimplementation),thisversiondoesNOTrunat‘exception’levelbutisintendedtobelessintrusive.It’sprimaryuseisdebuggingofuser-level/applicationcoderatherthanthekernelit-self(kerneldebuggingisstillpossibletoacertainextentbutthestubessentiallyneedsafunctionalandinitializedsystemtooperate). Thestubrunsasa‘daemontask’executingdebuggingcommandsasdemandedbythehostgdb.Unlikea‘low-levelstub’whichinter-rupts/stopsthetargetsystemasawholewhiletalkingtogdb,thisimplementationonlyaffectstheexecutionofoneormultiple‘targetthreads’leavingothertasksalone. Asaconsequence,itispossibletouseTCP/IPasacommunicationprotocol(nobreakpointsinnetworkingmustbeset,though!). 1.2Multithreading Gdbsemanticsexpectthetargetsystemtobe‘interrupted’or‘stopped’whilelisteningtogdbcommands.Thisimplementation,OTOH,at-temptstobeaslittleintrusiveaspossible.Forthispurpose,alistof‘stopped’tasksismaintainedinternally.Tasksareinterruptedonlyasaresultofhittingabreakpoint,incurringanexceptionoranexplicitrequestbythedebugger.Interruptedtaskscanbeinspectedasusual(stackframe,registercontentsetc.)andcanbe‘continued/resumed’.Only‘stopped’taskscanbeinspected-theotherscontinueexecutingnormally. Thestubalsocreatesaspecialhelpertaskcontextwhichisalwaysinterruptedwhenthetargetisstopped,henceitispossibletodonon-taskrelatedwork(inspect/changememory,disassemble,...)withouthavingtostopanapplicationtask. 1.3CexpSupport Apatchto‘gdb’isprovidedextendingtheremoteprotocolinordertosupportloadablemodules.Gdbcaninquirethelistofcurrentlyloadedmodulesandtheirsectionaddressesaswellasload/unloadadditionalmodulesonthefly. 1.4SupportedTargets Whilemanypartsofthestubareintendedtobeportableandtarget-architectureindependent,thereareafewpiecesofcodewhichareBSP/CPUdependent.Currently,low-levelsupporthasbeenimple-mentedforthei386/pc386,m68k/coldfireandpowerpc/shared(andderived-shouldprobablyworkonany‘new-exceptionprocessing’ppcBSP)BSPs. 2 Addingsupportforanewtargetshouldnotbeextremelyhard.Itmainlyconsistsofwritingtworoutinesforpacking/unpackingregistervaluesintoanarrayformattedasexpectedbygdb.Also,alow-levelexceptionhandlerneedstobewritten(mostlyformappingexceptioncodestosignalnumbers).E.g.,thei386/pc386specificfileconsistsof400linesofquitestraightforwardcode. 1.5SupportedConnectionMethods Oneofthestrengthsofthegdbremoteprotocolisitssimplicitywhichmakesitpossibletousemanycharacter-streambasedI/Omethodsforexchangingmessages.Currently,thestubsupportsTCP/IP,serialportcommunicationviaRTEMS’termiosdriverandplain“dumb”characterdevicesaslongastheycanbeaccessedviathefile-system(/dev/xzy). 1.6GDBPatches Oneimportantdesigngoalwasnothavingtopatchgdbitself.Unfor-tunately,itwasnotcompletelypossibletomeetthisgoal.However,thenecessarypatchesarebelievedtobeassmallandasmodularaspossible. •Asmallpatchisneededtofixabug[hasbeensubmittedasGDBbug#2029butto-date,Idon’tknowifithasbeenmerged]inthepowerpcstackunwinding.•Asmallpatchisneededtomakeitpossibletoobtainthelistoftasksrunningonthetargetwithoutinterruptingandstoppingthemall(whichwouldresultinviolatingdesigngoal#1:onlyin-terrupttasksonrequest[explicitorbreakpoint]).•Anadditionalpatchaddsanewgdbtarget(“rtems-remote”)withprotocolextentionstosupportloadablemodules(CEXP).NotethatthestubworksfinewithoutCEXP,however.Allofthesepatchesareusuallyavailablewiththesource-codeofthestubasa“.diff”-fileoftheformatgdb- 2Building •Changedirectorytothegdbsourcetopdir,createabuildsub-directory(nameofyourchoice),chdirthereandconfigure(be-sides‘powerpc’,the‘i386’and’m68k’CPUsaresupportedandthecross-debuggermaybeconfiguredaccordingly)1: 1Older Fortheprerequisitesconsulttable1 versionsofthegdbpatch(pre6.8)requiredthetargettobe 3 host: target: •downloadandunpackgdb-6.8(oranylaterversionforwhichapatchhasbeendeveloped–checkthegdb- •patchesdistributedwithrtems-gdb-stub•(optional)libbspExt>=version1.3•(optional)CEXP>=version1.5.beta Table1:Prerequisites >>>mkdirbuildcdbuild ../configure--target=powerpc-rtems Compilebytypingmake(gnumake)andinstallmanually:>> make install-sgdb/gdb Ifyouwanttoinstalleverythingincludingdocumentationyoumightneedmoreelaborateconfigureoptionstogettheinstalllocationsandtheexecutablenameright. •ThetargetagentispartofthessrlAppspackageandshouldbebuildautomaticallyaspartofthatpackage.Ifyoudon’twanttouselibbspExt(onpowerpc)orCexpyouhavetoredefinetherespectiveUSExxxvariablesintheMakefile.Notethatifyoudousethosepackagesthenyoumustmakesurethatyourapplicationexecutestherespectiveinitializationrou-tines(bspExtInit()andcexpInit(),respectively;consulttheheaderfilesforanyargumentsand/orreturnvalue). Ifyoutrytobuildrtems-gdb-stubindependentlyfromssrlApps,anadditionalstepisrequiredbecausetheagentneedsaprivateheaderfile,cexpmodP.h,fromCexp(onlyifCexpsupportistobeused)thatisnotinstalledwiththeCexppackage:EdittheMake-fileandpointtheCEXPSOURCEPATHvariabletothecorrectloca-tion. •AswithanyRTEMSapplication,youmustnotforgettolinkallrequiredRTEMSmanagers–otherwiseyouincurwhatseemtobeobscureerrors.Ifyouhaveplentyofmemorythensimplyin-cludingallmanagersbysettingMANAGERS=allinyourMakefileismostcomfortable. 4 3 3.1 DebuggingSession Prerequisites Compilation Codetobedebuggedmustbecompiledwiththe‘-g’option.(preferrablyeverything)2. OptimizationCaveat:ItispossibletouseGDBwithoptimizedcode(Idoitallthetime)butthismaychangetheflowofexecution,inlinesubroutinecallsandmaycausevariablesto‘disappear’etc.Front-End YouwanttouseaGUIfrontendtogetherwithcross-gdb,e.g.,ddd--debugger Note:youneedtosetPATHpriortostartingddd/gdb,seebelow.RTMF GDBisaquitepowerfulprogram–makesureyouknowhowtouseit!The‘rtems-remote’targetonlyadds2newcommands.Everythingelseisoff-theshelfGDB.Notethatnotallavailablecommandsnecessarilymakesenseonthisspecifictarget.PathSettings Cross-debugginginvolvesboth,ahostcomputerandthetargetsystemexecutingtheactualcode.Thehostcomputerneedsaccesstothesameversionoftheobjectfilesthatthetargetcomputerisexecuting. Uponconnectiontothetarget,thehostcomputerobtainsalistofcurrentlyloadedobjectfilesfromthetarget.InorderforthehostGDBbeingabletolocatethenecessaryobjectfiles,thePATHenvi-ronmentvariablemustpointtothedirectoriescontainingtheseob-jects.NotethatGDBdoesn’tdefineadedicatedpathvariablefor‘cross-architectureobjects’butrequirestheusertosettheordinaryPATHthatisalsosearchedforhostexecutables!NotethatPATHisanenvironmentvariableandcannotbechangedfromwithinaGDBsession(GDB’senvironandpathcommandsonlyaffectthePATHasseenbyanativedebuggeeanddon’thaveanyeffectinacross-gdbsession). GDBalsofeaturesaloadcommandtoinstructthetargetcomputertoload/linkobjectmodules.Sincethetargetcomputerusuallyseesa recently,‘-g’wasimplicitelysetwhenbuildingRTEMSproper.Unfortu-nately,this(lateNov.’05)nolongerseemstobethecase.Ifoundthatpassing‘RTEMSCFLAGS=-g’onthecommandlinetotheconfigurescriptwhenbuildingRTEMSdidthejob.Idon’tknowifthisistherecommendedway,though.YMMV. 2Until 5 directorytreethatisdifferentfromthehost,anypathinformationisdiscardedfromtheloadargument–instead,thetarget’sPATHenviron-mentvariablemustcontainthedirectorywherethetargetcanlocatetheobjectthatistobeloaded. 3.2StartingtheDebuggingAgent Onthetarget,thedebuggingagentmustberunning.Itneedstobelinkedintothesystemandisstartedbycalling intrtems_gdb_start(intagent_prio,char*dev_name);Passingapriorityof0letsthedaemonpickitsdefaultschedulingpriority.Thesecondargumentdefinestheconnectionmethodtobeused.ANULLpointerletsthedaemonlistenonTCPport2159(reg-isteredportnumberforthegdbremoteprotocol)foranincomingcon-nection,ifastringispassed,itmustbethepathtoacharacterdevice,e.g.,/dev/ttyS1. Theagentcanbestopped(rtems_gdb_stop())andrestartedwithadifferentpriorityand/orcommunicationmethod. Note:rtems4.6.2requiresapatchforthistoworksafelysincetheoperationinvolvesonetaskclosingasocketonwhichanothertaskisblocking. 3.3ConnectingtotheTarget gdbcanuseeitherserial-port,TCPorUDPconnections.Notethateitherusescertainresourcesonthetarget(e.g.,thetermiosdriverortheTCP/IPstack,respectively)andadebuggingsessionmaydeadlockthesystemifthedebuggingagentneedsaresourcethatislockedwhenthedebuggeerunsintoabreakpoint. Thesyntaxforconnectingtoatargetis(TCP)(gdb)targetrtems-remote or(serial)–notethattheagent’sserialportrunsat1152008N1–useGDB’sremotebaudcommand: (gdb)targetrtems-remote UDPconnectionscanalsobeusedbutgdbwarnsagainstthembe-inglessreliable.ThereisusuallynopointusingUDPifTCPisavailable.Oneimportantexceptionwouldbeifthetargetfeaturesa“standalone”UDPcommunicationchannel(e.g.,asimpleethernet/IP/UDPpacketdriver/stack;suchadriver/stackcouldbeusedtodebugTCP/IPitself)orhasreducednetworkingcapabilities. (gdb)targetrtems-remoteudp: 6 Notethatrtems-remoteisanextensionofthestandardGDB‘re-mote’target–itaddssupportforCexpmodules(names,sectionad-dressesetc.). Onceconnectedtothetarget,thedebuggerisattachedtoadummythreadcontext.Alluserandsystemthreadsareexecutingnormallyatthispoint. Usethedetachcommandtoclosetheconnectiontothetargetatanytime.Allstoppedthreadswillberesumed.3.3.1 SharingtheConsoleSerialLine Ifaprioritylessthanzeroispassedtortems_gdb_start()theagentisexecutedinthecontextofthethecaller,i.e.,noseparatetaskiscreated.Thus,theagentmayberunfromashell(e.g.,“Cexp”)andtakeovertheconsolelineforthedurationofthesession,i.e.,untilthedetachcommandisissuedfromGDB.Inthis“foreground”modeofoperation,theagentterminatesafterathesessionisendedreturningcontroltothecallerofrtems_gdb_start().Asamplesessionexample:Cexp>rtems_gdb_start(-1,0)GDBDaemonstarting .y (gdb)targetrtems-remote(gdb) Cexp> 3.4SwitchingThreadContext Inordertoinspectathread’sstack,registersetc.itmustbestopped.Athreadisstoppedeitherbecauseitrunsintoabreakpointorifthedebuggerisexplicitelyattachedtoit(threadcommand).Ifyouwanttoattachtoaspecificthreadyouneedtoknowits‘id’(i.e.,GDB’sidwhichisorthogonaltotheRTEMStaskid–useinfothreadstoobtainatasklist). Oncestopped,athreadremainssuspendeduntilyouissuethecontinuecommandordetach(terminatethesession).Eitherofthoseoperationsletsallstoppedthreadsresume. Youcanhit targetrtems-remotexx:2159//connect,attachto’helper’ 7 Atthispoint,thehelperisstopped-youcaninspectitsregistersetc.everyoneelsecontinuesnormallyinfothreadst14 //switchtothreadID14 Thread14isstopped.Thehelperremainsstopped.InspectT14’sreg-isters+stackt12t14cont //switchtothreadID12//switchbacktothreadID14//resumeeverything//interrupt helper,T14andT12arestopped;inspectT12’sregisters+stackhelper,T14andT12remainstopped;inspectT14’sregisters+stackhelper,T14andT12areresumed interrupt,stophelperandattachtoit-samestateasafterconnectionwasestablished. 3.5ExecutingSubroutinesontheTarget Whenevaluatingexpressionsatthe(gdb)commandline(e.g.,withinacallorprintcommand)gdbmayneedtoexecuteasubroutineonthetarget.Forexample, (gdb)printprintf(\"Hello\\n\") invokestheprintfroutineonthetarget,retrievesthereturnvalueandprintsittothegdbconsole. Thisisactuallyaprettycomplexoperationwhichinvolvescreatingadummystackframeandappropriateargumentsetc.onthetarget.Sometargets’exceptionhandlersmaynotexpectmodificationsofthestackandmightcrashasaresultofanattempttocallaroutineonthetarget. Also,itshouldbenotedthattheroutineisalwaysexecutedinthecontextofthe“currenttask”.Hence,the“currenttask” •musthavesufficientstackspace. •mustprovideanappropriateexecutionenvironment.E.g.,ifthecurrenttaskisan“integer-only”taskthenanattempttoinvokemathroutinesmayfail(crash).•mustnothavebeensuspendedduetoanexceptioncondition(i.e.,itmustnotbea“dead”or“killed”thread).The‘helper’taskprovidesasuitableenvironmentforthepurposeofexecutingsubroutinesonthetarget. 8 3.6DDDNote Afterreloadinganyobjectonthetarget(usingthertemsloadorrtemssync-objscommands)thesourcecodedisplayedbyDDDmaynotbecurrent(sincethecommandswereperformedattheGDBlevel,unnoticedbyddd).Useddd’sReloadSourcemenuentryfromtheSourcepull-downmenuortheequivalentacceleratorkeycombination 4RTEMSSpecificGDBCommands •usertemsloadinsteadofload. •usetargetrtems-remoteinsteadoftargetremote.Withstat-icallylinkedapplicationstheplainremotetargetisenough–theenhancedtargetversionrtems-remotehasaddedsupportforloadablemodules:itqueriesthetargetforalistofloadedobjectsandtheirsectionaddresses. •rtemssync-objs(re)-synchronizegdb’sfileandsectioninforma-tionwithwhat’scurrentonthetarget.Usethiscommandifyouadded,removedorre-loadedmodulesfromtheCexp>promptin-steadofusingrtemsloadfrominsideGDB.•infothreadssemanticshaveslightlychanged.OnlyalistofthreadIDs/namesisretrievedbutnottheirstackframeorIPad-dress(impossiblewithoutstoppingallthreads). NotethatevenifyoudonotuseCexporthertems-remotetargetyoustillmustuseapatchedgdbincombinationwiththisstub.One(smallbutimportant)changethepatchachievesisavoidingtoattachtoallofthetasksrunningonthetarget(andthusstopthem)whichwouldbringthesessiontoagrindinghalt. < Moredetails;morecommands;moreimplementationspecifica< 5ExampleSession Assumeyoucompiledamoduleinyourhomedirectorycross-gcc-g-cblah.c-o/home/john/blah.o YoucopytheobjecttoaTFTPserverwhereitcanbe‘seen’bythetarget.cpblah.o/tftpboot 9 Priortostartingadebuggingsession,thePATHonthehostissetup:setenvPATH$PATH\":/home/john\" Onthetarget,(e.g.,viastartupscriptorfromtheCexp>prompt)thePATHisalsosetup: Cexp>setenv(\"PATH\dirs>:\StartaGDBsessiononthehostpowerpc-rtems-gdbConnecttothetarget (gdb)targetrtems-remote //gdbobtainsobjectfilelistandsearches //PATHfor’blah.o’Recompile‘blah.c’ cross-gcc-g-cblah.c-o/home/john/blah.ocpblah.o/tftpboot ReloadmodulefromGDBprompt(gdb)rtemsloadblah.o 10 因篇幅问题不能全部显示,请点此查看更多更全内容