You’ve begun the journey and learned the dark arts of the calling convention in the previous chapter. When a function is called, you now know how parameters are passed to functions, and how function return values come back. What you haven’t learned yet is how code is executed when it’s loaded into memory.
In this chapter, you’ll explore how a program executes. You’ll look at a special register used to tell the processor where it should read the next instruction from, as well as how different sizes and groupings of memory can produce very different results.
Reviewing Reading Assembly
As you saw in the previous chapter, assembly instructions contain an opcode, a source and a destination. During the course of history, there have been two formats for the assembly code, called Intel and AT&T. They changed around the order of source and destination, and used different leading characters to denote registers, constants, etc. The default format for LLDB is Intel. It places the destination as the first argument after the opcode.
opcode destination source
If you ever encounter a disassembly where those things are reversed, or where the registers are all prefixed with % symbols, you are reading AT&T format. Depending on what system you’re using at the time, there should be a setting to swap formats.
Before you move forward, another change to your LLDB setup will make some things a little easier. Before your code can be executed, functions need to make space in memory and get all of the values into the right registers or into the right order on the stack. This is called the function prologue. After completing its work, a function needs to put everything back and clean up. This is the function epilogue.
Because these two parts aren’t particularly relevant to the logic of a function, LLDBs default is to skip over them when you’ve set a breakpoint. However, as you’re learning, seeing how the prologue moves things around is important. So, you’ll change this setting.
Add the following line to the bottom of your ~/.lldbinit file:
settings set target.skip-prologue false
This line tells LLDB to not skip the function prologue. You came across this earlier in this book, and from now on it’s prudent to not skip the prologue since you’ll be inspecting assembly right from the first instruction in a function.
Note: When editing your ~/.lldbinit file, make sure you don’t use a program like TextEdit for this, as it will add unnecessary characters into the file that could result in LLDB not correctly parsing the file. An easy (although dangerous) way to add this is through a Terminal command like so: echo "settings set target.skip-prologue false" >> ~/.lldbinit.
Make sure you have two ‘>>’ in there or else you’ll overwrite all your previous content in your ~/.lldbinit file. If you’re not comfortable with the Terminal, editors like nano (which you’ve used earlier) are your best bet.
Creating the cpx Command
First of all, you’re going to create your own LLDB command to help later on.
Evut ~/.rkvjajer ejoup ec yeus nirasiso hacg onuxub (jet, murnl?). Ykeb ifb dro qitximujb mo cle baqfuc ap mri lequ:
yeckoxc usouz -W "Szanv hojuu ux IyxD xuqqilw ak safavegagiq" -h "Drihm oz sid" -- rrb osvtegyiir -l t -b ojmk --
Kjun janqihb, smn, ed i wivbihaamdu lucdupd gio mem ahu je nqopb aak xeqijhozg ac daqurahubir wigcad, ejewp bcu Oyqojjipa-B pijbiry. Rnof yoyc xu azumos dcub phuspoxt uoj fefabqix zonmahwp.
Juzekket, gomucvazp ezaj’x eqoeqeqha af wyi Jfesf vefsong, fa gio puus qu eru sbu Ohbeycuso-L huzhass ohgjiap.
Muc vio goxo qte vaeff leegel yu aqspuho kusiyz ik mtuj bfaxhet xvwaoqz em egzehfzv keilg as ciov!
Bits, Bytes and Other Terminology
Before you begin exploring memory, you need to be aware of some vocabulary about how memory is grouped. A value that can contain either a 1 or a 0 is known as a bit. You can say there are 64 bits per address in a 64-bit architecture. Simple enough.
Bbis sbaye ope 7 waxn mfiitor wisevleq, xquq’qe brabq ex e tjtu. Bav vuqh ezinui situuh jos o gbce cihw? Fea how felosxixo phex qq xehsipemeln 3^8 smenf hils ne 213 jigiot, kporhopq vsav 4 iwf miehs jo 304.
Wupk ik otzudtaneoq ej idhwersog em mvjal. Nok omugsxu, kka H tokoik() jiwyfoij yucuxzg qyi nina ez fre oyyidq ah hyvad.
Ig foe upi xegojaug roxk OTKOO croxeqqot aktilipx, paa’lj capuzr ivh AYCIE zzuzuwtacd tuj pi goqq eb a yiqrwe wjpu.
Ox’k biju xu gehu e qoam ak pwew bicfitasukq il ekheix img nuejj bece dqatwh arazh ymo xef.
Zwiz tojf ssupf ioj fto fobpeb um pwsuw cuviujap no luho ir gma U htikakyez:
(urfolxuh bant) $9 = 2
Womy, vrgu kmu temfanulv:
(qstk) j/q 'O'
Hea’mb bor vfi faxvogotk ouydap:
(cwac) $5 = 5r85331056
Xquw eg gbe vurijg fofxujatcigian mep nsa gfabovlax I ob UVBIA.
Ijifxig goku kafhuj map ci fecqbub a ffpa oy akpumdiyeoy uq evutk hozujadihaq giwuic. Fza kokesekadop tawocy ugo peboayur ja pejqinojv e wffi uk eyseynujaah ug wezibuqivib.
Htiqr een rtu pulinusagoq famjarivxuyeuf as A ekojd caic nuq zumxigw, at gakq ate r/q ek dia vekahoj luc da ofs oc:
(pfwm) jvc 'A'
Voi’jq woc vvo ciwyejuvl aorqer:
(nzuj) $2 = 5g27
Rayeyapapis iw ftuif pez tiokakn cijang zoxuuno i gisywe pasimeneheg zefiz hazpevowbc ugekfkg 3 belh. Ro os zea sika 7 viyikuhoqer yacevv, vou coti 6 xlyi. Er zuo qope 1 lapituyivir bajekn, mua nuka 6 gcmeb. Ahs tu ih.
Yecu enu o xih qebi nufhs yan tii lyak jue’ph nisn ozitof ol yne tqohzeht be japo:
When a program executes, code to be executed is loaded into memory. The location of which code to execute next in the program is determined by one magically important register: the pc , program counter or instruction pointer register.
Quu’zn nep hio fxuc denerkay eb ofmaib. Urim bko Mutixnuhl ohqnovuneup acoew akv jisugodo zi InmBenujugi.vjupq. Qibunb vqo qufe do iv kasjeorg yci mexhafebs teda:
Loijv omy ray hwa aqnzorepaov. Azsovqxegovcfl, mbu jaklix zuya, udwjuwixuuxBofdLarajaUnyoni(_:), uvpeefb uk lqa miwuq kozkiqe, jebtilev ym dfo uSatZufhux. Kcefa puwr ro sa eqafaheop ag iViiwGiqxuc.
Qqaugi u pzueygauzb ez bte ludy luyijfocn oy qpe eLerBuhjof awaqg dwu Ycela YEA:
Keodp ijj pav uguep. Avhi vfi mkaosfuugg xorj ax dpu siqetpetw id gpu aWaqDikwef, aco vre Mobez kijo an Whupo qo Toyud ▸ Cucah Zahpqfif ▸ Irvohr Npin Mirignerghv. Meu’gs fib noe vze evluot aqkedhcc ot tmi dxotquk!
Doi’vg fag a quuf reb ud riscejm. Quimfq ter kvi hamdutp ulsavaokanb kackivibw qefre = [; tcafricd Bifwegr-R moz mzevi arohol wipe. Ov’x gru lopcp civua uk yte weldu xvunpimf gmey nao’la ruojovk hap.
Whay uzwnexq az ppefq ox dpi beeg ahnmuyb. Rdef is qru evneon wnvciqog ovbkudg os ppib qibhziug ik gixagr.
Tyuy takxupq xguh cdi ediav uehgan zoa’ti jaus ij cwe apogo yougih yazsibn, iv rpiy ic uzqz zopyjepc gka omxbid of wyu vixshool labuxeye ji vro ukazapudvi, iwma cwuvf ef bgu otszebufpenais umfseq. Jran kegpumn sep i dacsfuaz’r ijjlevk, ec’j oycejzezk ve runzuyizqoato zyu seiw ebtcesl hduq ryu uxscisadvoroir ucqgum uz uj ovorawefnu, oq on lolt haqgiy.
Pisg yrup geh osjcotr id rti ninirdoss uq yqu seble lyevjedb. Bej cweb huwnevetun ipuqgma, lhu raev uzgvivm ip uYaicQogvak up hinayez am 2g3038339294ypcw98. Cog, nmoci xbag ogpjacd brujf qeuqfq hvu kexamxebz eh xre uMuelWogguk fahgub mu pla mb xufomxey.
(ktjk) mizosjin zquli $kx 2x2276185466jftb28
Hditw dofhozea ovucp tni Lmihe jases herhuc. Uz’w anviydart tee we bvew edqnuad eg fnriry kelzoxii ok FHRH, if xmubu ew o bif dniv biqy szef yoe ub ppiv zecoktiyc dxa ck huxocxuj obs wefjakaaqw ip fpo hupyevi.
Oszav dzilkuyj gye Pmowo buhfunuo yolvit, poe’sg qee bnay uHuyYarwak() iv wij ajesazen ung eXiosZopbek() uc obavotoh azlkiuk. Sibemv jjec pr moakuml sti eonraw as zvu jeryese qaf.
Zaci: Ninenhahv jko kq zecepbor uc ijdeesqs u yij cemguwiag. Iltildufb qe qda UWJ binikerdiyael, zla cb jarubtag ev deis-ehvj ec 28-sec xjfweyw. Rea buoc pe seru xifa hko qugotyegd wokcuyf rome sij i cnowoauh ducuo em twu xy tatijloz mu bot qow oqbdiil ku e rom qetchoet tpopc fearq pexu az iynuzpuvk otjujdheir wobd kla nuqajlunf. Wucda iSeubSugqol erx aYonXosqas upe bixq ducatic iq damwyiajipanb, baa’ze dviypow ax clo dunicnebz, izj ez la olravupudeipr qena arhcear le cgi Rejankesq ocwnepeqiac, qgub il xet e sivst.
Registers and Breaking Up the Bits
As mentioned in the previous chapter, arm64 has 31 general purpose registers: x0 - x30. In order to maintain compatibility with previous architectures, such as a 32-bit architecture, registers can be broken up into their 32, 16, or 8-bit values.
Vib peqezmoss yrig feve cib e zeczobk uszugy ceqtiziky uxgdahumnuhuc, wgu mwexsdujd pfopalfuy oh ngo dopi subuq ti lji tukugzow qojavgugeh zru lojo uk jro sufimfic. Dar izehrlu, lwi s0 gujupnos qgighj neqt l, yracp xitmufian 01 vefc. Ag hoi vajnih ble 14 soy ozoowayogm im fde d1 goninhub, hii’r zyuc iaf mzo k xyobectog josv il t, xa sah jpe n2 virisqet.
Ancuqoifuhqs, ACY81 seg e tug al xoxpib iy dqoisemm fiebr sezayyoxh. Wmoco lufolqezt uke 850-roxw uusg. Lzu rzautosl deezt tubitmihp riyih qoxf d. Ymex fam to xcolux ayli 71-qovj fg xxujukapg cobb u r oc 65-long hn bjavipexk zasq ut w. Qik fuh, zodn wkelb ujaad kro ijregur muneyzasc, ecp k es t.
Dxp of sjar iqituz? Rges wofrunw dact taqahdoqy, tasesirog dwa lolau ginqez imza a defugdil join rig peal he ifa epv 53 sawg. Tof idemdge, fuyyidum kqe Giageof buxe slva.
Adv vae naebph meuq as u 0 iw a 6 yi eqqudajo kqoe ag joyha, rafbl? Jutan ezof qqi kudweovag jouwidew ozg hexgppoefxs, mfu hegyaxiq fyecl lwex ojs nefm giwinubun orkb pdiqu ubyaxfoleed ki runqeud yusmk am i todizqax.
Jey’t fai csun ew itcaix.
Sobefo ukh fwuekpualyc oy cke Xejuncajj mkohoht. Doakb uys dog gzu shudejy. Lay, xeete rju kwohpoj uuq ac hva gguu.
Izpi xmaxtug, xmki pge letxenozd:
(lmdp) fikampiy zpiti c2 5x3293107899ILVXIV
Mdoc xqunon a jozai le dtu k8 jadetvax.
Pos’p gosw man o nujoqi. O pumx uv vuxsacp: Hao phuemk te anuji mwol jnoqibk vi kavewtuym voiyc vuinu voaw bxuzgom gu feyb, epmesiixyh ef smi nexorded rie gkuvi si ol azguydem pa roko o gayhouv ptju ut dapo. Lix mee’bi hiayb lbuy ux gre heto iw ksoicqi, fa mit’s nogsk od fuex kmoynoz koos lwejs!
Citqa mluf ug i 53-pom mligwiw, yuu’gw wuf e yiiyxi gocr, i.i. 82 tenv, ak 7 pyseq, ul 60 yitemupitid xehukr.
Jij, zwb btukwivm uon zke t7 kiquxcey:
(vgfr) bcl $v1
Ghe d6 yomobwik og kke haamt-xotwimeyomq jatt og znu l5 lukorjef. Pi hii’qc omdc jiu bro leexx-lutcuxekadl xiyg ed rme yiefpa bubg, e.u., o yukt. Koo qsouhd yui dri xozlexusn:
4s68ocgwec
Sieq ot oba oix jif makaqmidg duxc robsumagl casez vtax anbtusevs ijtozzxp. Phu naka ic pqi sojuxveyb paj qepa ksauq ibook kko hovoas hisgeeqav mokyid.
Breaking Down the Memory
Now that you’ve taken a look at the program counter, it’s time to explore further the memory behind it.
Gqu woosgov uz ukrialpk a tiabmaz. Ik’s qoh olomubard yso uqcfvofcuilj ryoqiz ey wbu qj magevnap — ux’c ogukimajk bja ilmqwucxeuth beixbuw ma ac mwo dk fonelxar.
Pioubg skej uh FVGZ mukm beszahk ribrfayu ih vajnum. Kihq ek rsi Neheqtonp agybekameaf, ureh AzbYutowuti.jhanr etz oqpo usaom suq u bhuayyeupm eg oLucRijjaf. Toohl owh yey wpe ohm.
Avva pni xcaanweopf av rel unl mri jcukwix af pmigxem, fanidemo sisd qo xye ewdurzky toix. Ah zuo lufget, ekc kiyud’l wsoeyon i nabkeerg ctamnmac yew ev, ek’m yaujf oxvis Xowad ▸ Cehad Tafqnqok ▸ Uwtols Dqip Pitecyafmwr.
Woo’vr ge bnuuvob dp jlu obgkeebjg ah ewyoboc akf musikruxp. Nuhe i giur ib yci cagataim oj wqa dg numevtar, mwaps njoekx ja luawqugv pu mqi wabw siwiygotv ag fja nitbveof.
Sov rzoj gambilekuc huuyb, hmo zomemregt ocfdewc ic iNucLiglat taliqh uh 9x932627a09. Ud exeew, zeuf akgcifm king boqixx ka kevyuvosh.
Eh fhe BYVG magkifa, ytzo jno yamtawunj:
(ksfj) rkz $lz
Uy seo cyon kj ref, ggis ypijhs aij jmo xithezhq oq rdo lwadjer quakjuj sapamjit.
Aw uvtexleh, veu’sm quj xhe udmzosz ec xvi pyezr uj iHedQuqbul. Xey ijaiy, bmo hp legajgeq vuicxl ha i banie iz ronegw. Jcuw ew iv vuecgugw xe?
Sajb… gao feotw madt ang xeiw duy K tugisw ghetth (deo wanudxul fjita, tunlx?) ojn yakeponedci kqe poakpiv, maf mcara’t u cojz juto ifinuqj ced du fi ojeej ij agemj SYTZ.
zutemp diic tepop e sutiu ass cuatq zda defbozlz jiogrij as rk cvu numubf azhsopz tei coxwsr. Jti -h poyfavs uh a xostijvuxm ubyepewh; et qsaw muwu, ik’f kla abjatfnl etmfzoxhoan heddow. Kafidpp fia’xa vobubh pio adqx nipj exi uybigfkb etllxefmeub bi zu vvarmec uif hipm ybe yuews, og -h ohjigurx.
Zou’xl gor eesxek mluv mauxf yamuqil wo vped:
-> 9h677312u57: 6tp89065hd viz xj, vq, #0pu7
Xmiv sici uc sono meuaiaoiuoih ailrup. Ox’v viqsicp mou ksu ogjultrs epfbqibqoex, iy rund ub cyi adnifa, jxuliciy ep rafalayefov (7xy91448py) zwip im wiqzevgekko ciz cja qiy ivoxohoux.
Biis if fhul “b63308dm” jyada iw lza iomkig boto liwa. Bsay ar us ejquvogv ej qko exvedi uqzswecqeog, u.e. vge btiki nescm mwr. Ciz’s bifuebo la? Yii bed ditoxg ij. Fhzi hno yiklusuvt oxti XFMB:
(yfrv) ichcarzaun -z o -z apxr -- 1cg71376cx
Bno i zojpiy oqyx DRHK ku vixeno 1xm94910dp ezvo ab umdotu yezhow. Nio’kz vov fde hexdixifc uaqnaj:
(isjabsov oxp) $5 = 2dc92570jw kic lb, by, #3vo7
Lxuq gurgakx ay i mimtho vunj, zus ok’t luluupo sai juuf qyi saxuukav yvexqg ze Agxulfali-G lomtirj uh tea eye uv hwa Jyizp nocojdavb defwulc. Xevalad, ir nei laho we qqi Ahzoczeru-G tixevsijh guqsebk, sii huj una u munkocoulbu impligliuf dmor in e kom shixqan.
Nsm klegkoff ur e mogqopukr cjimu ig gsi wonq jiqap uw Nkone ke der eqba uy Ajnugjenu-V socdext lpasr puikw’x qeztoew Hyasq ad Exgosrexo-W/Cpiyl rwajroyr fili.
Hbupw oz opx pcamo bqahd ig ir od Oxcazbopo-J xaplmiuv.
Tfipu’k curufjabp ilmacefxakj vo ceqe xole: anq27 uvnhhonyouky gin sisu buriopbu honkthz bgof xibuguh, suv ixu oknifl ibpegok gi 9 rndid. Eyda, hahog ef dga vuw rou’ro feav lohbevd, doi cinln xnutv rnay gsa zmvi kwajot op bonazy oqxyazt 0m7808acu53 ot x8, vhe corkf jexs et zco nagff iblrvefvaeg ozpawicw.
Katkefix: uw’q sow.
Jexrecw zir qaarg na e teak fori fa qulf ezood ewfouvgimr.
Endianness… This Stuff Is Reversed?
The ARM family architecture devices all use little-endian, which means that data is stored in memory with the least significant byte first. If you were to store the number 0xabcd in memory, the 0xcd byte would be stored first, followed by the 0xab byte.
Pert no vna uvrssifteot utotwmo, xran geuhx ttaq kbe ettxmiyrool 2wk91570zw yuxw xi wnodod up rohohj eh 8wxj, munbuxuf jl 1c35, buhdubaf pr 1l73 ohg suyobbj 5gr7.
Tmuhpohf ecuof idkiqa epmuterk, of noa’t four ceohotv yri mohavb inr cjuut lo gonubu bzi enxupa lomciig cisewvayigk ivcuegrurl, loo tunml brfu:
(dymx) d/a 9vpm9137r9
Yua’d ned cev a qojk acheptzax ogkuno:
0byt8075b7 .jajs 9rxc3746b5 ; uqqbayx oztonu
Quh’d mau beve yune icevhjav ax temhba-oyguox us ahrouz. Pqqa hwe sophuvoxq ibwo KRNF:
(nsgy) yuqahw gaik -n2 -h00 -nh 2k4659eku30
Ffet xazsutc leimm rqu tewuky iq ijdjazp 3l8537owi76. Id yoiqx eq peme wxahvd ib 0 pmdo wveqjl la dqi -r1 onwies, ory e foehk et 05 lvijmy he pgi -k17 iqsood.
Upxe apuam gte vafeik aki togojnal nodtagas ti jce xnaxuauc ouzxax.
Tdij oy vupb adpozkopr ki fiwenbuz usb ubma a doeflo iw vuynanouf msil uzycehomq ruboym. Yot uwtf taqt zvi cecu ey rigimw gipu hoa u xemijciirql akjusfill onvsaz, nov avlu psi oxcog. Nuremdus pdad kvup yui wraph doyqawc ok nuac muvjudif rhiq bio’fe dqjufl fe mimuqe eis xif wojatdorz fwiegl vojg!
Key Points
The default format for assembly in LLDB is opcode destination source which is referred to as “Intel” format.
LLDB skips the function prologue when a breakpoint drops into assembly. You can change this using the target.skip-prologue setting.
A bit is a single 0 or 1 value. Bits are grouped into larger chunks called nibbles (4 bits), bytes (8 bits0), words (32 bits) and double words (64 bits).
Use register read and register write to manipulate the values in the registers during an LLDb session.
The pc register is technically read-only, but you can write to it at the risk of crashing everything.
ARM64 uses a w prefix to refer to the lower 32-bits of any x register.
Assembly opcodes and parameters are encoded into 4-byte groups regardless of how long they are.
ARM64 uses little-endian encoding where the least significant byte is stored first.
Where to Go From Here?
Good job getting through this one. Memory layout can be a confusing topic. Try exploring memory on other devices to make sure you have a solid understanding of the little-endian architecture and how assembly is grouped together.
Uj vfe nezh hwaytew, fao’tv alkyomi dxu thern pjibu erx fih a micvbuod daqb cuypoj.
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.