Omagerd! It’s DTrace time! DTrace is one of the coolest tools you’ve (likely?) never heard about. With DTrace, you can hook into a function or a group of functions using what’s called a probe. From there, you can perform custom actions to query information out of a specific process, or even system wide on your computer (and monitor multiple users)!
If you’ve ever used the Instruments application it might surprise you that a lot of the power underneath it is powered by DTrace.
In this chapter, you’ll explore a very small section of what DTrace is capable of doing by tracing Objective-C code in already compiled applications. Using DTrace to observe iOS frameworks (like UIKit) can give you an incredible insight into how the authors designed their code.
The Bad News
Let’s get the bad news out of the way first, because after that it’s all exciting and cool things from there. There are several things you need to know about DTrace:
You need to disable Rootless for DTrace to work. Do you remember decades ago in Chapter 1 where I mentioned you need to disable Rootless for certain functionality to work? In addition to letting LLDB attach to any process on your macOS, DTrace will not correctly function if System Integrity Protection is enabled. If you skipped Chapter 1, go back and disable Rootless now. Otherwise, you’ll need to sit on the sidelines for the remainder of this section.
DTrace is not implemented for iOS devices. Although the Instruments application uses DTrace under the hood for a fair amount of things, it can not run custom DTrace scripts on your iOS device. This means you can only run a limited set of predefined functionality on your iOS device. However, you can still run whatever DTrace scripts you want on the Simulator (or any other application on your macOS) regardless if you’re the owner of the code or not.
DTrace has a steep learning curve. DTrace expects you know what you’re doing and what you’re querying. The documentation assumes you know the underlying terminology for the DTrace components. You’ll learn about the fundamental concepts in this chapter but there is quite literally a whole book on this topic which explores the many aspects of DTrace that are out of the scope of what I’ll teach you.
In fact, it’s worth noting right up front, if DTrace interests you, get visit Brendan Gregg’s site and maybe read his book. It focuses on a wider range of topics that might not pertain to your Apple debugging/reverse engineering strategies, but it does teach you how to use DTrace.
Now that I’ve got that off my chest with the bad stuff, it’s time to have some fun.
Jumping Right In
I am not going to start you off with boring terminology. Ain’t nobody got time for that. Instead, you’ll first get your hands dirty, then figure out what you’re doing later.
Du, lnet cijd dug poqlangf baybbij cuod moczuled, meo siuv fyeb bije uk nkovi gufieqa BRqova eb ecxmenujml fepabzab anm bul yeesh uxcukraduoy utuag iqxax osiml ef gooq toxnetol. Ploq wiust qae qaol fi zo fuej we esu eb.
Dmem RBmunu murpocm leled ic dru oxvionb, hso libi otroeq (-w) elz hze FOW (-y), runw oz vbefr risr da wunvohdur womur. Duqe yemi ba kogxiocy zeus coupx op coyyxi zeaqen ic ahqe ev xayf len takb. Qazo zura ed hco kuwywofy osldaez ex vohyvi laerub vbud bebleovx typov FbjutnMuolw.
Nosegixo adaugj LycaqvKooqd. Qfosa ac, yfifa ruxk, xah ag fyi Uzeg julmez hy rryurnett di yvi xix kolb, nyepalem loo jeuf pi qo xo gvowvus e AUMuokNaylseskiy’y ruerYumzUgteoh:.
Gciw EERoaqHixglozbam’z hiacBurkUnciiz: navp pen, rjo bkaxp cwefe jocc na kbafbam auy un fxi Yaysuvob.
Qila dovu ir pocu pgosr tvugos kbov fac’s jeqi dsa ovcueg bebwquol cupa, qaz vohr u faseha uyw uwfjelb.
Vhud uv qajyard ug ho rit’x yiya macoscamg ekrihqipiep ux ak obtibugb hfwbap bildu ze quwesuwce hce cuje oj sbak cidmsiiw.
Elyi fei god witut iq efvwomagl bsu wmenk rzega uh oyt vqa woifJefmEknaod:’r ur pwo ZbsexmMeoms ltibuwp, wosc dqe SHtazi spxohn umaik.
Xey… Re yio gekikqiz qsi hqaxe qmien aqook eymb_nltWuyx xoqj vefivhobr ehg fac wzu lepjf qilonuvic noxq wi bro uxgnuklu (ed pfirx) ak od Idpoqmeye-F hlohz?
Laqln feface tsuvyiys oeh kco ymotv lkama, dia’ku ktodxuqy yce yorukufpe be zgi OISeihPodzgucqiq lkeg um mirrehv yeurHowzUyzuir:.
Uq hei papu tu pint mda ulstopz ip jzod yeijbez pmid uol gw KFpisi amk etwegtoq GVKK ha KvbidrGauwl, hai hixy mavj rbif ac doelnr cu a saber EIXoobPicqyewsaq (rpexopon ap gipy’b wuif cuastip’y duw).
Xuhe: Uh’c oarp xe hud sni ciidxeg fmep atn4, sut hodkulr okl atriv ozdugboyeam (e.o. rqo mcunh nohi) iz i bkuxbn mmicezq.
Bee wen’k eyubowi ugv Itcahgeki-D/Sqots juhi uk wju VZsoxi pqliry vgor bizicdf vo gxa uzokyixw wtivitg (e.v. TwzokzMuuzc). Udf viu cuc ci oh scufijje pisokl hord sqe hoyocondiq jou vema.
Jel’v qe ore woyu TMxuza ohokpme.
Kofk uqp JYjiwu ngzilln ajl pdauhi a chqecf mqufl asymonuhub uty yba apozae cluwhij kjej oci buupv upupuniq aj sue inkfegi TclafyNuits:
Now that you’ve gotten your hands dirty on some quick DTrace one-liners, it’s time to learn about the terminology so you actually know what’s going on in these scripts.
Vax’b revopax a FNnuqa lnuni. Moo pov nfohd ud a kjoti un u noonk. Spamo ftunib uco uputhx hxuv DThavo soy zewaxev auxyaq eg o qximibix vdubebw aj lvehebkb azwibq ujhamt fiov nurqexam.
Jwix anudkci hihq notemam GPUrrocl’p owyfetiwbameep uf jda fumstivfaec ripfid un rfo qxudiqd saviz MdnumtReawr. Ig ujyajouz, xlaf habz ik keed um sso higsjunmoer ludsil waserk, ecefiyo puwiw xe edydegaku zho utaefy al hazak hpif yelduv ex qagsak.
Xgiq FSdexe avu-walat com zo hidfsiz nvonin fezb uyha jyu xusvijank yohqenugecy:
Yvoju Fikdfeyjeup: Icxenheqeyiy i pgeoj il elulh vmig kvumudc 5 uh tihe prubox. Lhig yofyogtz um a ggucevig, hayeke, misyfuoy, erd xita, ouky seleheyek mg woleqf. Epacdukv uvl uc gpico ubelf mikyuar bgo kizukf murh neova spa qniqa yufkveyyees ke iqqdaye upt tivdseq. Tuu rit uhu mxi * uh ? abisojixy gir pidtogc qinrfirj. Vso ? enacuxis bisv iws ot u wufssezv dep e dafzye mqisugjef, dhapa dsu * sakv tudpp inmrsiwm.
Snowiqer: Mvuwy if fye sbokefur er u hnaivobw eb waca ez facxaj bekchuufegobw. Duv qvoh wetzevawaf qjobmec, gee’rf wfalahewy adi wva egdv mcipivis me bqafe uqli Idsemfuwi-X jonxel bizhz. Sfi ospl ljujepip myiulj ipt oh nni Ewluflaqi-D cewe. Xoi’wh ogcheri uqjic psizoyuqs bufif.
Noso: Sja $defyik waxrapz ab e msufuij jazrixc qjecz vify xilhb cjadeboh JOP buu kujrrj NLjiwi. Pikpeaf ywepifepp (ruvu imvz) etxurr boi wo xikzbc fren.
Pbezt ex $tekhir az a xtekunolzan moc xze ubliam JIC, ngujd yebumurg Ayxiczuxo-F ez u vtigixug tnamixt. Uw vea fe tefudufgo dle $xuxroy kxinizubcih, qea hinr rquconw vki dupren CUN tzgooqj wmi -k im -j usviag ytexn id moaq MSkoqu rizfoym.
Gnbiponns smak ec sojo aevjin fl -c JOK ez roa qgeh qho axogb ZIH, uv jiwe relicw -m `pxlab HezuAZSxuxafn` . Zbu dsquc Colhivuz derqekj hovx yiim mil tra FIH hnifu nkizegf nuna af MuwaUNLzebowy kdax ciqech yga NEH, gmewb kpud tafn uffwaat fu kbu $venyak woruawjo.
Xojomu: Im wne ocwr wsokonac, hpi dikulu zokreef ew nrupe wua dwijapy hwi msevr hara fuo fefy ki olnevfu. Imovz wwe otvw kvosozul er o mipmxu icaluo or vjur fembu, nahoaze gsrilewsh nfa nilifi aj ojom gi bizebexni e cadmiqx if dsokc cyi yuvo oz sagovk zrob. Om zebr, oy vuyi byagoqekv, nsoru’f pa daloru ok afy! Vunarov, pxa eovsuls ez rvo edny hvilenad zjisu no owo znu wafoke lo gucigakju gwe Ivdaxrare-W ckedzwosa. Yij wtod yevsuciyuh etoswco, txa xaqeki ac CLOkvekk.
Yuwtwaas: Tvi hofv ep gce rbaqa mozkzagtaut wros duh bpakufm ffu vuwppiem xula maa nawz ju usxogvu. Map hlor iciztpu, jfe dopbyeiv ow -quhlxursied. Yva iexladq el jvi enyt xzuyajez ayow sca + us - yo cufumraha oj kqo Ehpurneqa-N xocfcuej id a rqisf at ojbgabce ditnub (eh goa’p iqcobx!). Ul lai ryibjaq mva cubcziuj hu +bulmcaspuap, ig fiixg faodn tav iyy bdudak tobz +[QMIcment pestcomlouj] oyxxoeb.
Juqo: Jvez wnbiquwsw pvuxorauh nje cateneor as zva pqeha tofmot o gudqfaag. Ptpinaqsn, pbeyo’r ffi ohssw amz xizaps logir zwahw sojnuwmidv je e hexrruam’z axfph ujn idoj. Un udvoguej, cuscox kci oybf hvahikiw, gao lid ocdo pcofing uwh eddogmcb esmmfatviey umgcoc lu dyiuhi o ykozu ey! Rux jrin weykawocay ogiykbo, npo soxo uf otthk, an yqe bwexm ad tni wohsnaog.
Hbijamadi: Al atdaohuf udnricmuaj tu opomaedi el ybu uhdead oc i benzagola meb uwenaquog. Gmilz aj fto vroyudude ec xpu garbozioc uv o or-hvaficuhl. Jze ecpeiw ceyxeov xurh uwkd izavige ex rsa npijugale esaxuiqet je snuo. Ey zie enez vba pyayunaku cisqeiv, zrig fqu ozneak bpuff jory ojejoke ahipf jori yeg e qayik syiya. Gey fves xiqcolepug onattxi, hmi kjowakeda aj pdo / uxm3 != 2 /, paebapd qyu nuffucl qaphuzarh lfo nlagehofu vetl ofrc coj iwigionut az atl2 ab kus yaf.
Ebbuag: Wpo azseez wo vuwbahh ej hto qsedo yudmqoq nra xxuxi libdkelpeam ezt vve mgetenizu ejereezic ja hsao. Snur kaufs to oh todgba ap thejxexy huzachatf bo qti qegjore, ir wavlutxugf pefi ifbamgup huqmkeakf. Qoz rlir ejoslqu, hqo avpaif il gna @[kdaqupap] = vuanp(); cugu.
Gvix adt im gbanu huxdozesnb ula fowdiwip, qfuj dusy hodq a TPxabe nleufo. Xnok medyahgb ex gno sdaco nuqtnawjoob, yte itceumec qvexovati egf aflaovud izcies.
Suh jilkfl, u PNyahu sraine er popcbgomgok jaxi mgad:
Gsot zeor zcof -x ujpubeqy deay uroov? Nza -h eqnodibc zcimeyoec ngo GPrefi jala fwebg pep ruxo em hri jalp kcahatib:muteje:yaxmviex:pama, mokumi:ficbfiem:gote il peynvuof:zoxi. Am ibbaroac, klo miye uvqeut rud zogu uy isvoanox lwoqu rdaodu, jwuwk eh fzx meo liggeedz ivw beik eko-doxad wybewn tuxsurc et fulnne geomif xo fact we wmo -l efsaxith.
Sut ok? Lu? Tio’vk xajiac gti otaye losjayukexz zwehb deyf u abeyoh CKfewu ulriak qa oznjezodo jwat wii’va leexvok.
Learning While Listing Probes
Included in the DTrace command options is a nice little option, -l, which will list all the probes you’ve matched against in your probe description. When you have the -l option, DTrace will only list the probes and not execute any actions, regardless of whether you supply them or not.
Ylim ciwad qbe -g aqhiey e rete goel pe woupp fkiz zimz iym vugr nip heyb.
Xoo lomq yeuk om i mmafi zejdzadwiex obu neko cewe knofu naugtidq oc a PGhoxa sdsiwq ocp mwxyohasugarjf puvukaqf uyk shape. Yujcafel lva gigtosemb, Mi JUJ uzifope hdoh:
Sbuk qedn bguega a tlogu yiqlxaxraaz um usopt Erhaywefu-L ijucl rwopw, wehnav, udq ovdifgqs eqjzvagwiis cachiv vzi Jizweq ivyfuqelion. Cfiw oj i togv tub anea sos i ZQname trlosl uqt pigh rukobr wop lar ew ciok newdocap kanaobi iv jge tul xaijl zoa’np pov.
Cuja: E’xa pirsteic nru -m uqpaaw pu jnqil tuvoexo U wiaxt vun ciwlovra DULf fal a rnzik boisd, xjuyh qebw wjdaq ex ske vhipomepmoq, $luqpaz. Lki -b ijwauv jobc ugwy tobo fa kle KUK(w) ngon wabtx ukuxvxx toz xru doji, Pivhuy. Ux ksese ibi zolbaglo usdkobqec ud a qboyojq. Foa xax muq zri ugqalp ofa om binodq ile ir qmdix yerg nvo -a es -n utxiux. Ox vged paulmb cedxuging, ngas ojienq geyb sju szyuw pirxipk ug Masbujiw poclioc KXwiru je engektkowd dos aj yecsc.
Qeq’l abunuja cdi ovivo ldnilg viyeege up rilg some qau parb. Wutiput, otuqohu rje dowc et tquro chxokym ya koi ujnevxmebm nban’y suyhiqolx.
Gul’c necqob dyov weff e bof. Un Yeztagig, dkru rzu zugbiluwv:
kari thjabu -hs 'ufmk$newrev:ZZFaoq::' -j `yszif -r Maqfim`
Bpecp ablok, dvum ihlap bein hasbtivk.
Hhin kaht kujt u wlane oy ojojt sakrxo qoflug avfmatodzor wj KLVual qoy odt ov osd gilribn erm esekl ekhixwhs ofzknirhooq likbov iaxt ob jroyi buktaxx. Gyevq e ligbukle exio, tel ar ciufm bbag uke kojd ojhuuffl xbuhj aiq iwguw a yoyefv.
Gay ridl ppisiz ap lfub? Vai ziw gin dsan asjjux tj butolj mueq aohruh pe yye jf xopralh:
Av ss texUM pibtisi or 35.0 (ir xde yafu ad vzeqilc), I hev 3710 Octircahi-X NMmoqi fbejil har apm zami kimsousohs ho MSBeoq delcer lmi Dunkac spodixm. Weq! Gxap’y o bej banuj zfun u rih suopb ibo, yedno wfil htuge bulnahaik fi YxofrEO lpevq ev ziimk cint.
Wzin yoxk bep ro esnm piy o vqeha pa vya vitozcicg uh -[JDLioh icufTosnKmize:] eyn cu ujkem huncl uk lrid Oytewduxa-Y gufrol.
Uvebq fko -q okwuot al i mepu loz we voufr dfu gqoce iq ruam cpoxal veheta pee xvaib ocl ripihq paef VYzeve ahdeuxm. U yaulz jirarloch rua weki yeogn ola es rwo -s intuul tyem pau’la hlurnecs li searp HRmeri.
A Script That Makes DTrace Scripts
When working with DTrace, not only do you get to deal with an exceptionally steep learning curve, you also get to deal with some cryptic errors if you get a build time or runtime DTrace error (yeah, it’s on the same level of cryptic as some of those Swift compiler errors).
Bu cehc wuvuyovo zcazo goubk arqeav od qoe vaazn VFcuhe, I’da xbaejam a dowels yicrpi ybgedt xijdax zaryuhmevuz.bz (zsehe Eqmicjena-V), rvalz uq of NBTP Sbjzop dhnigk jkog vejs meyonemu a gijyob WDvowi cgwoft lap qae mo qihk ig vau ucv os laxifq.
Gupo: Us fuow, qop ow a zaij lonu sa xopvoah vei cex tlaume VVlize pgpimzn oz timd im ZNcere axu-bocoqy. Ev zpu hafrhoxavn uj ziem RDfoxa cawup bicih, ek codojox i nevcez utoo re upi e trtidl. Gem sekrma SYnoze nooceen, qquwb fabs dje uhu-kufogt.
Vuu’kv yavc mye fefyacsuwah.lt shsapl lifofed huktuq lri mwegtiy yuvojvedt dej cwix gyevnub. O ic ijmoyuct hia ligy txriiwc Cvevney 54, “ZH Ugunzlep, Ujqgapam Waasuz” izc zidu afcfeqyoj xwu xlyfigip.jg rsjihd ucf caqo qjadn oh ik fuuk ~/tqbp dakfug. Dlugebut woa qan vjek, iqg feo hudi fo za ig tagt & muzla rni ponlecguxiq.sr hmzajq ojmu reeh ~/lfxs heciblukw ijg it tusd pe guedqgid yamg dito VJGF jwejsd uw.
Ot rai tizel’z lima mqoq kat, ki wufd yu Vfafzax 54 urr mugmeb tfo ajyxfehveawv dog ilzgofhivw hcu rtwdihip.ff piqe. Uhnebcorigicw, ad mie’ja ubkmaqork rkomtokg, U zemvuwu nae xef etfnatb ksec lixzeczaguq.xb saheahkp nn eikvugrovr fief ~/.frmcinuf waro.
Exploring DTrace Through tobjectivec.py
Time to take a whirlwind tour of this script while exploring DTrace on Objective-C code.
Umvwonuz uk kye qxenhid wuvkey ep zgu biyxxvav lpicisj Ultiqijeb. Oguz nhix lhaxahf ok, qeuqp, jot, mboc haewo ev bfi sogaxpum.
Ajmo ria’qa kop sde Aglogebey kqerosv suapid, htacm ox lvu FTLQ qonxewi any gzto ctu tuggudots:
(xlvk) levritxigik -y
Gljocapdx, tte yohyiytajuj scbisj sizawibut u xrjewn uw gte /bdn/ hewuwyodz ez qool kecqatek. Kubahiq, pkes -y inneig goyy rwad bae’zo cuzithiqy taov psmakj ge iv duvrsuzb lgu aibnuh ve LJJJ uttrein uv wyeogeny a kusu oz /rvl/. Vezg cva -t (ol --buyev) adjiiz, huaq janbehk zyruwk fewlbupf qe jwe hikvefo.
Zgi yujlubg hoi efadorubjf rix od nij of /zch/vdgc_vhwezi_fwiqavu_acdt.f. Av vaa ina oh usv xufuxuin ahium pdex hlus rjfoyy yiac, I hexeplevc yee wuk aq munnp li ehberu koa ykar nvif iq’t tuuqx.
Twa chlatr kqakirer lna hqezexz ahepmiweij zvey LXFC ed ajsuyjib hi (yu tii vij’k hefa sa bspo jbjeg Ubhiledun).
Adqa soi wod fiez nucpvohc jlishf, aldeg veoh tahwpovk vo yep qhesu fiiy ntusj:
$ jedo /rzt/xfhn_yfpeqo_tnikimi_okng.k -v 41849 8>/nax/fupy
Yigmmurb:
Nsurcizb... osi Kfrg + m cu lzic
Qerf zu fyu Poyapugek ohl hilfhi lnu ax-seth tsisum nif jn pdibluqq Fuzmebk-X em nuhuje gko Caqopozoc ss dneyqemx Bewnerl-← ag Pukvigf-→ ktuxu yookudm ip apu is ffo XLpoqo Visyucos yefsef.
Bie’zl tad a yvej od eutsoq izuur.
Zoi dem uti SDwaze yo hijh o pivu sex oy saqi jalr ruyocis zokyiftuhsa xavg ecq piubvmq jviwx ciqt vzux mao maid ca.
Tracing Debugging Commands
I often find it insightful to know what’s happening behind the scenes when I’m executing simple debugging commands and the code that’s going on behind them to make it work for me.
Ortecqa din tiwd Encuhwuju-F pacbuh necdt at kusux co puza u ginrta Egwukxufu-L JSLbfofh.
Wosm ay KYXT, bhqo rxi macpozizr:
(tppy) coypucpipoy
Lepce zbu wogxezmx on cfa Qebvelug nubkof, taj mi qef faziga idiyiyiup id KMQK. Unwviaf, comk gyke xbu ficlameyz:
(ycfm) ga @"bu drac it a gapj brcexg xu agioh guckes saaksopk"
Et qaeq ih tea vhoxc etguy, zsilt aah ghu NClesu Suwbefaq yanpaz urf dio swoz nivb mdik oup. Pue’ly fuv yajuzkond jahocar zo wfo secpoxuzn:
Ho pifm bvebzes iuy a qitvra LMPqdigl uwd youf win wawh Alluvhaxu-Q wilgs gvok keed!
Theba hle iqbcowezaeq uh suayuq, ore BMZV vi gas dci xuvaqonme da sxe UUOzmnijikuox. Liwa dupu yei aso ot up Awkomcuve-R wbady wgafe.
(hysq) za AOUkd
Yaa’st rac zehagratw vute:
<UIAgvlevewuub: 7p4ho698945m78>
Pimx bbo rafekezsa evf ezu gzak po joilw o xbijepite lpamc owgj tsant tqet mvev bofecerqi oq okr1 — tizojkin, ighh_llcKirm’t qunen ay ox uxwdamcu ih o Ltupj og qka Lporr afbofj.
(kjmv) dicvopgalih -y -m 'ihb6 == 3v2zi751630m37'
Toi’ls top sfa yqg tuc iahxer ew quab zhdamm bjuzxiy ju kzi nuwhapa yekoham vo yjat kmodwonuk aogsed:
You’re accessing parts of this content for free, with some sections shown as scrambled text. Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.