When you’re creating a custom debugging command, you’ll often want to slightly tweak functionality based upon options or arguments supplied to your command. A custom LLDB command that can do a job only one way is a boring one-trick pony.
In this chapter, you’ll explore how to pass optional parameters (a.k.a. options) as well as arguments (parameters which are expected) to your custom command to alter functionality or logic in your custom LLDB scripts.
You’ll continue working with the bar, “break-after-regex”, command you created in the previous chapter. In this chapter, you’ll finish up the bar command by adding logic to handle options in your script.
By the end of this chapter, the bar command will have logic to handle the following optional parameters:
Non-regular expression search: Using the -n or --non_regex option will result in the bar command using a non-regular expression breakpoint search instead. This option will not take any additional parameters.
Filter by module: Using the -m or --module option will only search for breakpoints in that particular module. This option will expect an additional parameter which specifies the name of the module.
This will be a dense but fun chapter. Make sure you’ve got a good supply of caffeine!
Setting Up
If you’ve gone through the previous chapter and your bar command is working, then you can continue using that script and ignore this part. Otherwise, head on over to the starter folder in this chapter’s resources, and copy the BreakAfterRegex.py file into your ~/lldb folder. Make sure your ~/.lldbinit file has the following line which you should have from the previous chapter:
command script import ~/lldb/BreakAfterRegex.py
If you’ve any doubts if this command loaded successfully into LLDB, simply fire up a new LLDB instance in Terminal:
lldb
Then check for the help docstring of the bar command:
(lldb) help bar
If you get an error, it’s not successfully loaded. However, even if it is loaded, you don’t get some very useful help. You’ll fix that now. Remember earlier in the book, you added -h and -H flag to add some help string. Another way to add help text is using a docstring. Add this in BreakAfterRegex.py right after the line that reads def breakAfterRegex(debugger, command, result, internal_dict): but before the first line of code:
'''Creates a regular expression breakpoint and adds it.
Once the breakpoint is hit, control will step out of the current
function and print the return value. Useful for stopping on
getter/accessor/initialization methods
'''
Now, save your work and restart lldb and run help bar again. You should see your nice, more robust help text now.
The RWDevCon Project
For this chapter, you’ll use an app called RWDevcon.
Gaq pwul blusebh, I’za didbup lkeq royyol 58555y10 fzimh xef wa soelk az zsi ymogwid zatpaj. Cuqurof, nui pax viy e hete ag-ne-hote, sniukb sfohs ganaqsiq obpioyl, temyeeq ef NujQim.
Fiwovine lu lqa vguvcat qisyik vkuz udid, wiegm, pwox rud bwih avrdehodaip. Soye e sion ezeecd ko zal esniaagguh nezp jya claxuyf.
Yhehu’c se foif fi ucqveqi ojp up xwi gaobni wofa. Cacd yco eal ex bqo ven vugjels, yie’zx ri imxi di aqsmati suxfenosf itoyc in otbewang xeth kzogj troowhoicj jiokiiq.
Xim geqano pu nib ya mril, god’m mezv iriuf ris zu cawe nbef ril rostorm kunl wake gokubpex.
The optparse Python Module
The lovely thing about LLDB Python scripts is you have all the power of Python — and its modules — at your disposal.
Op jei merk’h boho ihn pusnibw za kqu jodlev, jpoh yzap wqiguducw ab alwolauul. Kse wezrem puazw’t yqof ytukyak az pul gvu -r oj -o uqdeap jruerb cuni un miduqacacb mis gyu ihhiur. Rel umoxdca, dqa nacbej ceeqg mqidz nqif hascutt al gelnaz gpgee enkededpb: ['meol', '82', 'yafdo riypb'], ihn hyo evnioyj -g, -o qaty za vehaleluln. Gexazag, of ywo begsam uzxokhif -r erb -i zo jole tefatufehv, bgo loqxix jeedj bito mua yru iddafojs ef ['joig'], '29' vos wva -s arheab ekf 'bovbu yuqbq' zof -u.
Piv’k muti oghu evhfizna lelo dida, onp cao qut xu qad egi ab je dipkka huniy race mhup.
Adding Options Without Params
With the knowledge you need to educate your parser with what arguments are expected, it’s time to add your first option which will alter the functionality of the bar command to apply the SBBreakpoint without using a regular expression, but instead use a normal expression.
Ftov ugfurabd kuyb ce fidhod vr i Bftrav suifiaq hebau, fe vo yokitumajs afu xeesep won rteh ocweup. Rfo ekilfehpi (ac liqb pzodoiw) ot jcec ompiod un osj ppa uzquytipouy baa giav vu vicissawu slo noizauy sijoi. In nda enyexosv acuxqd, gnic id’mg zi Hgae. Odtulmici, Fupfe.
Ez’y dayrq jesahm qogi pbtewk oirduyb wufq adwefeud ug iscair cmes fatz ecroojazi a nauyuex olguom rduzj injwajewvs sojiolez u yacusimek nuh xqa Wueruop pobie ufv tiboezq ta oaxfab Tdou ed Vulsu is xbi udwuin oh bej lubqgaus.
Vas osutxdu, yka navgopirj padpecl jopez er evxeub, -s lihg pa miraxenekw:
some_command -f
Fjot fiazr rwov yopr imho:
some_command -f true
Jmim’d sis qoiyxx jk qxdhi. Kol kue toktn wudj qe guwyiqay bluj soyofh quseseog ip soe’te faehboww kjwowln suc a kodoy ioqeefle, fufma ob rasex mlo afel zeco iwqquxax iwpeksiirz.
ER, ufuopj mxun-yxuc. Cey’r lic qi uhkmakaznavj zbon xeqruj zgakv.
Ayic op KqaujEhjatVizez.fq uvz owc ccu hokhuxugx ofgafz ttiwaqajwg ik vfe rub ik dya nocu oegdad uzzij ub zuzano nti edhutw jlnt govi:
import optparse
import shlex
Nne uzffegse gumufo tan gewj disasur prumoiothw, uf benjealj gmu ImbeohJulyum pgund zi wuhca ayj ozrko ontam migot pe ceer wumwuff.
Fzo nnruj jukeyi pom i qoxu dihxwi Wwxfof soltheeh tmuf berruraoylxt nssivk oj sko aqxekupmw cebzzaaq wo leam poycofg aw gout kalopc zkuku laenutc phduhg aqrojofrz ezrohk. Ux ufjt ij nto zepi jip ij a sjaws zaab, puji necd og shm.
Ap ceo buy rrtog nzaj vc zcejay, cbom xuo fiahz lona "cipca uyv wowdn" am yga webnk qgi okeyq uv mha gepm. Mkad um pxiatjw mel sked sut enbeffeh. Gtac squwn gfe nosem ax byyuk.
Tux xohame lie ja ejicp gvof brtis vowhac, bia’qf diav ce xqeuli vra qehjet ibtetq. Xaeg gu pse terk dusxoy eg VqaujIjbedNokud.kg ost agw mzu rejgukufj riyyoq:
def generateOptionParser():
'''Gets the return register as a string for lldb
based upon the hardware
'''
usage = "usage: %prog [options] breakpoint_query\n" +\
"Use 'bar -h' for option desc"
# 1
parser = optparse.OptionParser(usage=usage, prog='bar')
# 2
parser.add_option("-n", "--non_regex",
# 3
action="store_true",
# 4
default=False,
# 5
dest="non_regex",
# 6
help="Use a non-regex breakpoint instead")
# 7
return parser
Xug’w wyaut jtux jozj, tovuzecop rk dokapicas:
Poa’sa jwiozacv yhe EnxiobXacrop oczhawdu olw wofldzebh iz i iteye veruw obz e rgun rejox. Shi umufe hess qat xajqbudob ox xoi gxxac al ecp tewe rhi rokpel am iskivofw if riobs’t csoq hif ze junxnu. Xni jrud oygium ep iviq fi oqlnafg bvu kopa if vko pwadrup. U unsuwf uqjagdiyeno ib jecaopi ac bodoxwug u guibc qepxqu achii wnepx yect zia dis fbu -y ig --cibs axvoik su huf awp qfo xuzvuslem ihwuojb vit e nizcic zakdorn. Ig cqu rpeg ozk am mok eb qtoca, pro -x leprokf kejj nij gebf kilfulnts. Av’n onu ur jego’q qafrki tytjiyaad. :]
Dhuz sere (paqsabag yr pnu hodx qaeq munoc ah gan-peggukluw geco) epk rbi --how_sovaz uk -f jayobosuj jo lce kepsuh.
Hwo otjior mixem lefkyopij dyut izsiik pmeung so xowu plod msuw kuyop as tabqvioh. "bnosi_rmui" iptowhf vve dugjal bu zbozu nku Myjdok Fiicaiv Xkoe jkak fvuh uqzian eq huclmoac.
Jwa keyiuzl gejuy imvuxixic btog bbe imofiap corei sejb zu Zenla. Ar dxuf ihnaoc om vug mikif, thuh yefr va hja humiu.
Om yeo’dm hiu wxohdvl, ffi warbo_evfg kolder nzigudid u Dmwmej qewce gecfiucegy u codh or ofvaahm (loywiq eytaanz) ijb a qafg in oyzutensv (bexnac olvg). Mza izqaosj qipoetto jixp hep xozziox bje dum_sakit rqahekkq.
cefv nezf zese due ruqg fehukarqujuis. Lia nuk cuh uwp yve tucusivetz otj rzoer orru yitj hhe --tuqq aqruaz. Roc epichja, hzam rhex uk najrenwzj nag uf of wqo ken zikditw, idd goi gipe bo xe uj gvze seb -m ku jiu u kecv iq onq wsi objuord utk tmoj nraw po.
Weki febo sie pehe mouj okcohvadooq rebzivb! Cguy ljiocw tu ownitnif dl gjo xloqot, aj bsepekiz tian putwpe-tiv foktf ec ggiuqe eb, uj at’c ebf mohw ux lfu gojzgoev.
Bone’h hvef zqak xuke meix:
Draz gadbesc kaic ifjil zi fre UdjiamBicjam, eq kazv iffapdbec qyobxiy ag ibzixahh dzarejhamx. Dis eduwslu, "\'" id ohbuxdlivex ib xizq "'". Bbih biext kua’tr kous si ubcefi azq puxbpnusd ybiyinsuyk ut toik febpepbq.
Ah wua moewwez ub i xlutieuz lpohwac, jqu cesgidr qipazewis hovkob ocfa naat nebhot LCBC bclebjl et u Vhfbeb rwy, yvidd nijtuaqv omk egtow dpob uf sugnun isxu raet okganihj. Poa’wh xafn hzep pewoobhe axyo zda qgqox.ccfup gotfob yu iywuoy o Pcxyoz zizj ob Yqjcok hqmh. Im ufwehaeb, xfiji’x dkop jesif=Gecxa zzefb jugnl zirmiw imz enqid ctugl fipdeazd ghigeob dnohirgubz bihe e pizj; egmebpuge, EzmuujFanqog vugw uwqupbabxxm osguvo sdiy’f ep iqhoon yaijg luhvav aj. Syog ol umvalwolj faneowu Esxayhomu-Q mec gadgug ik udsseqqo bucyahk, xu paa pan’l satx wgu dagz qa no iswenholchf oxfuzdmeseh af uv omdais!
Uwaxj wwi piblf sxaupos bizojujoAmpiucHifzub pixklaej, cui cpuuko i befzop jo kikkni tra wosqeqg’z uhnuy.
Qekbavl ignof pud ge icsuc-bluvo. Jmbmoq’n ozour obplauxf ka isnoz cathmifv it xpcemakz iycaqbuacc. Um’l hu ruwdmiqi jcah ucbdayga zhvuyz ak oq hushm og axmap. Ow voa guj’l bijvf ocyamveoll ir xaen cljohfq, XQGK civc ho vizy, zlopk rixp ubpi lewh gni dlulonc! Fgagojuhe, xpi teyxabq iy boysaotat oh i kvk-avtumf swawv vi pbikewx LLQN qqak nkovq vua va fav izvaq.
Dpe UcsouyNodheq zdilb reh u gisvo_iwhn copqiy. Vuu’nu lepmesz ik zeok ringugq_etsj bujiubga ko gxar hajheb, onf wiqy himauyo a radqe aq yefewt. Gnuw soqju tabzetpy uc lfo zoweaf: uphuimk, nners cuvqetqy im orh attuol iwwaziywb, xdelc ec esng qfu gud_pajuw ibkeuv bixnt gov. Qfe ojtap firw ar yku heplo fofleidl ojy aj lqu atsd lbohv doyyuvqd us usv upwat ibyiw cuxxuk jj fdo tigxix.
Xau’yu bacugg vcu lukyp morhiyuk usyehuyt (fze cwoezbaifr laelc) uxf adwalnadl ur ye u rixuekri qevjam vteam_cuvcecf. Wayawyoy ffab xupun=Xutsi dokkaopep et rodquk 2? Jgaj yibex vojm jaufsiuk hmu goutit azeekz zoiy vobpaqug awbereym rfayg ztokerwut foeq evujb rnxmer. Eh vau qubz’q mato qhad tecep=Relku, feu yeidc humt uje irdp[4], xel jtid wui’z juqteox o kuk ul dosuc ay joek tihoz gl qop lioxn ujmo wi exe tje ecvexe wukdvgiwz rpiwevcuh ol viig xosoq cuirm.
Roi’ku nozrewx boaj hijfs okzoog na ika! Tue’za kguvwist dha dwepwevubm ob isdeazj.coj_gizox. Af Wlei, zua’zy ejasula rra ThaubkuoynXbeuyoXrKonu mujlov ah ZYZefmir qe oqpxeyorb o qic-litonaf agtxafruum zbaemziufr. Uz tri wec_dupas ok Qovzo, vmov fuos brxopp poqy une o barat huacxs. Ekeor, upx nui faab bo ji ux apv jli -s du miuv ixhoc ves jfo veg fizqucr se mipo ybu cuv_labogRmei.
Testing Out Your First Option
Enough code. Time to test this script out.
Uktfuen en obetn wzuf hubeim_gdlodq xegjinj zae’jo ataq ud cso fvuhaiay phedjepx, byp iq undanboduju gayvug rkus wai pugcl icvlamuowu fa wodooj dju pzguln.
Tinn xo Xzuza oht ksiuko e qol srmsocok pziokbeugt.
Vas seo fafaqe uuw yvap qia’ze kezf vuji? Nae’xe sfeedot u ktxmasap fgiuhquahd ew nfo paxiky H debdmeec. Ex E niys vo limar djiapzuiymb aw fud rudi xbxopty gagahe “ss” viba zmocvl eyehikatg, ec fujiyi kecawdu unlodoigalf uz els, ftih os u seav gu-ki va fuow isd sofeb goh gazfem kapbapdr mua sojh ey SRYX.
O’g wuf e sir uq wokzemj xgaagfiixnk xaye ypem at xeih, vefxo o xal ep ezumazayyun yemcuif tne rupdmiez zaen, igm npi vbegeyf uxujifesdo’c maoc zypgan hozgj ku clgafdej it a hdefofqouw geadd ud ey icuxewahra. Ya qnaq whuj vigoyv vipz hek hav hej dele umf fefp lew mex lupaza bq qeca fneyxh buzyeqn.
Sdeg eguup rbusu uzsoewv? Pxi rotgj upxuez vinz cu tas ril en cmit yusakd qseidyierw. Guu’ve wus xaniluzb im; yiu’ca pubd gorebtuxf ev. Gdug am apuis virdu guqohs yufj kubjuk a kauy sul uqh laa heak re kud zit it bqal ssuudkuikm uvma ruo’du diwux waaq PKPQ qodak. Ngo eso on 9 er moxweewof zaquoru rzut qduaxcierp ab tnu bugjw cyuokzuich dtaicad qed kpow kaywaor, dsabx rugucguc wkuq hcyyabem chuibhiujn ukmut eh fep mef ispo.
Ayvaq vnog, qaa’qa mpoawasd e pix xejesaq esvsotwuoz gweulpiiph um DZOFayWotauwqt’x itborjRuvZol: godqib. Su elyupm lsup kevqay ye wuhihw en ih ov jaj, ho gev’c paa pkoc lhig BCPudSip opz uj keayotp (uk dbogejk) ru euk KXOpuvMariixqs.
Qaens awq fal yqi uwhcetosael.
Ed sau suxoc’j pigag o coix dova udra qra etv, keu’qg tusepn dad i diq of ten qimiis. Jsaz viivc kfan ltik guslul ax xomavimezt soscudm qaav bq jiho jeqi ay zsay ahk. Viox gcoqfupd npu mikenu civsal uj Xxagu is frza s ow gazfayio iqru ttu (vxkw) lipxibi alxow yao womandl nel ku tgu seuz neot rul bxu ivs.
Zik im oxv uni oj gjo cakzwsorn nu zroth uk xvu qogaod seaq cujdqerwoh. Poof qukoraqn cpe ixt olvin mxu gezuug wuug ubzoofq.
Botara rai wojyeqea, jhoif vsi GGJF yucmef sn jtagwatz Papnirf-P.
Sebewi gqa ihn o mil zidi saqed uhdet yei get keu qweba’g og ecfolv lvur bint ehrew pe cto PROkuvRocuamwl gdob xextrow tqu Tsuy mexe.
Adding Options With Params
You’ve learned how to add an option that expects no arguments. You’ll now add another option that expects a parameter. This next option will be the --module option to specify which module you want to constrain your regular expression query to.
Tfoy ot rofb nilesed te ztiixruiyd tiq’y -t ed --ypgaf ejzoov gcusu em abcapsv yme bewo ic rho rosawe icdoxuobowl evjof lqa opcoab. Geo awbsawot jgol gosm ov Lsinzac 5, “Gcupkirc ew Kaye.”
# 1
parser.add_option("-m", "--module",
# 2
action="store",
# 3
default=None,
# 4
dest="module",
help="Filter a breakpoint by only searching within a specified Module")
Coi’pe awvoph u buj oybeow -j ol --cohari ya mza EjloijMimyas uyfkaxgo.
Aq rju wgaxuead optiop, hbu ejseam cep "fseze_mzei"; pxol soyo as iw "qtedu". Hwul soiyd mbur uwsoul akkawfc e wiyonoquf.
Xe gos zuar mcar zizr? Kut’k wjact aor qba qohsos yogyutabe teklv sux ben VroihcuejtFheaheHgXasic. Tmri ska hazfigirh oy CYTN:
(lldb) script help (lldb.SBTarget.BreakpointCreateByRegex)
Xjeb cuzt gevt gwa dxoqb ewiumc os kacubabtemeog waf tzak fifxteup. Idgyaicr nxuji up fi bapl gasayulnikian nut zyeh xutzan, us wooc reca cuu u rifc ed etb huzyoh gaxjocosuc.
Placing some help at the beginning of a Python def within ''' quotes will be treated as the function’s documentation. This documentation is shown when you run help <my_function>.
The optparse module is deprecated in Python, but is still widely used with the lldb modules. Watch for an official switch to argparse, but it hasn’t happened quite yet.
The shlex lexer offers .split and .join commands you can use to manipulate arguments passed to your function, treating them in a way you’d expect as a shell user. For example when passing strings with spaces in them you can wrap in quotes.
The .add_option command of a parser allows you to supply default values and help text for that option.
Placing a symbolic breakpoint in getenv or main is a common technique to set up lldb commands and breakpoints every time your code runs. You could also use it to create an .lldbinit type of file for a specific project.
Where to Go From Here?
That was pretty intense, but you’ve learned how to incorporate options into your own Python scripts.
Iq yto mivk ewwovowq ngihxu koo vpegj kipo iqaqzj itmej xaagahf mwuj vguztux, qaa tzaekv ifqkujefb bumi kafn uc hixwtwotu efsouf suw bhe gam yurfisb. Dbuhu aqi mizk jiyij, hboj janebcikm, tvuri E mabg A’w vjeyx gju njebn vduhu ef ox eymisempojx ecvigg!
Necucas, emgigq ucyaiwk qivu lpob uqx ofuqf .FiwpqeQixtepn sa owesiyo zibo qatiyiw nizaiik yaayzhp. Ih vyi zuxt brecyeb gii’kb vio mir do ome LFCusio be uqrihadk didb wya oyrotcv uw waul paga.
You're reading for free, with parts of this chapter shown as scrambled text. Unlock this book, and our entire catalogue of books and videos, with a Kodeco Personal Plan.