MachOObjectFile.cpp 177 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673
  1. //===- MachOObjectFile.cpp - Mach-O object file binding -------------------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This file defines the MachOObjectFile class, which binds the MachOObject
  10. // class to the generic ObjectFile wrapper.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "llvm/ADT/ArrayRef.h"
  14. #include "llvm/ADT/None.h"
  15. #include "llvm/ADT/STLExtras.h"
  16. #include "llvm/ADT/SmallVector.h"
  17. #include "llvm/ADT/StringRef.h"
  18. #include "llvm/ADT/StringSwitch.h"
  19. #include "llvm/ADT/Triple.h"
  20. #include "llvm/ADT/Twine.h"
  21. #include "llvm/BinaryFormat/MachO.h"
  22. #include "llvm/Object/Error.h"
  23. #include "llvm/Object/MachO.h"
  24. #include "llvm/Object/ObjectFile.h"
  25. #include "llvm/Object/SymbolicFile.h"
  26. #include "llvm/Support/DataExtractor.h"
  27. #include "llvm/Support/Debug.h"
  28. #include "llvm/Support/Error.h"
  29. #include "llvm/Support/ErrorHandling.h"
  30. #include "llvm/Support/Format.h"
  31. #include "llvm/Support/Host.h"
  32. #include "llvm/Support/LEB128.h"
  33. #include "llvm/Support/MemoryBuffer.h"
  34. #include "llvm/Support/SwapByteOrder.h"
  35. #include "llvm/Support/raw_ostream.h"
  36. #include <algorithm>
  37. #include <cassert>
  38. #include <cstddef>
  39. #include <cstdint>
  40. #include <cstring>
  41. #include <limits>
  42. #include <list>
  43. #include <memory>
  44. #include <string>
  45. #include <system_error>
  46. using namespace llvm;
  47. using namespace object;
  48. namespace {
  49. struct section_base {
  50. char sectname[16];
  51. char segname[16];
  52. };
  53. } // end anonymous namespace
  54. static Error malformedError(const Twine &Msg) {
  55. return make_error<GenericBinaryError>("truncated or malformed object (" +
  56. Msg + ")",
  57. object_error::parse_failed);
  58. }
  59. // FIXME: Replace all uses of this function with getStructOrErr.
  60. template <typename T>
  61. static T getStruct(const MachOObjectFile &O, const char *P) {
  62. // Don't read before the beginning or past the end of the file
  63. if (P < O.getData().begin() || P + sizeof(T) > O.getData().end())
  64. report_fatal_error("Malformed MachO file.");
  65. T Cmd;
  66. memcpy(&Cmd, P, sizeof(T));
  67. if (O.isLittleEndian() != sys::IsLittleEndianHost)
  68. MachO::swapStruct(Cmd);
  69. return Cmd;
  70. }
  71. template <typename T>
  72. static Expected<T> getStructOrErr(const MachOObjectFile &O, const char *P) {
  73. // Don't read before the beginning or past the end of the file
  74. if (P < O.getData().begin() || P + sizeof(T) > O.getData().end())
  75. return malformedError("Structure read out-of-range");
  76. T Cmd;
  77. memcpy(&Cmd, P, sizeof(T));
  78. if (O.isLittleEndian() != sys::IsLittleEndianHost)
  79. MachO::swapStruct(Cmd);
  80. return Cmd;
  81. }
  82. static const char *
  83. getSectionPtr(const MachOObjectFile &O, MachOObjectFile::LoadCommandInfo L,
  84. unsigned Sec) {
  85. uintptr_t CommandAddr = reinterpret_cast<uintptr_t>(L.Ptr);
  86. bool Is64 = O.is64Bit();
  87. unsigned SegmentLoadSize = Is64 ? sizeof(MachO::segment_command_64) :
  88. sizeof(MachO::segment_command);
  89. unsigned SectionSize = Is64 ? sizeof(MachO::section_64) :
  90. sizeof(MachO::section);
  91. uintptr_t SectionAddr = CommandAddr + SegmentLoadSize + Sec * SectionSize;
  92. return reinterpret_cast<const char*>(SectionAddr);
  93. }
  94. static const char *getPtr(const MachOObjectFile &O, size_t Offset) {
  95. assert(Offset <= O.getData().size());
  96. return O.getData().data() + Offset;
  97. }
  98. static MachO::nlist_base
  99. getSymbolTableEntryBase(const MachOObjectFile &O, DataRefImpl DRI) {
  100. const char *P = reinterpret_cast<const char *>(DRI.p);
  101. return getStruct<MachO::nlist_base>(O, P);
  102. }
  103. static StringRef parseSegmentOrSectionName(const char *P) {
  104. if (P[15] == 0)
  105. // Null terminated.
  106. return P;
  107. // Not null terminated, so this is a 16 char string.
  108. return StringRef(P, 16);
  109. }
  110. static unsigned getCPUType(const MachOObjectFile &O) {
  111. return O.getHeader().cputype;
  112. }
  113. static unsigned getCPUSubType(const MachOObjectFile &O) {
  114. return O.getHeader().cpusubtype;
  115. }
  116. static uint32_t
  117. getPlainRelocationAddress(const MachO::any_relocation_info &RE) {
  118. return RE.r_word0;
  119. }
  120. static unsigned
  121. getScatteredRelocationAddress(const MachO::any_relocation_info &RE) {
  122. return RE.r_word0 & 0xffffff;
  123. }
  124. static bool getPlainRelocationPCRel(const MachOObjectFile &O,
  125. const MachO::any_relocation_info &RE) {
  126. if (O.isLittleEndian())
  127. return (RE.r_word1 >> 24) & 1;
  128. return (RE.r_word1 >> 7) & 1;
  129. }
  130. static bool
  131. getScatteredRelocationPCRel(const MachO::any_relocation_info &RE) {
  132. return (RE.r_word0 >> 30) & 1;
  133. }
  134. static unsigned getPlainRelocationLength(const MachOObjectFile &O,
  135. const MachO::any_relocation_info &RE) {
  136. if (O.isLittleEndian())
  137. return (RE.r_word1 >> 25) & 3;
  138. return (RE.r_word1 >> 5) & 3;
  139. }
  140. static unsigned
  141. getScatteredRelocationLength(const MachO::any_relocation_info &RE) {
  142. return (RE.r_word0 >> 28) & 3;
  143. }
  144. static unsigned getPlainRelocationType(const MachOObjectFile &O,
  145. const MachO::any_relocation_info &RE) {
  146. if (O.isLittleEndian())
  147. return RE.r_word1 >> 28;
  148. return RE.r_word1 & 0xf;
  149. }
  150. static uint32_t getSectionFlags(const MachOObjectFile &O,
  151. DataRefImpl Sec) {
  152. if (O.is64Bit()) {
  153. MachO::section_64 Sect = O.getSection64(Sec);
  154. return Sect.flags;
  155. }
  156. MachO::section Sect = O.getSection(Sec);
  157. return Sect.flags;
  158. }
  159. static Expected<MachOObjectFile::LoadCommandInfo>
  160. getLoadCommandInfo(const MachOObjectFile &Obj, const char *Ptr,
  161. uint32_t LoadCommandIndex) {
  162. if (auto CmdOrErr = getStructOrErr<MachO::load_command>(Obj, Ptr)) {
  163. if (CmdOrErr->cmdsize + Ptr > Obj.getData().end())
  164. return malformedError("load command " + Twine(LoadCommandIndex) +
  165. " extends past end of file");
  166. if (CmdOrErr->cmdsize < 8)
  167. return malformedError("load command " + Twine(LoadCommandIndex) +
  168. " with size less than 8 bytes");
  169. return MachOObjectFile::LoadCommandInfo({Ptr, *CmdOrErr});
  170. } else
  171. return CmdOrErr.takeError();
  172. }
  173. static Expected<MachOObjectFile::LoadCommandInfo>
  174. getFirstLoadCommandInfo(const MachOObjectFile &Obj) {
  175. unsigned HeaderSize = Obj.is64Bit() ? sizeof(MachO::mach_header_64)
  176. : sizeof(MachO::mach_header);
  177. if (sizeof(MachO::load_command) > Obj.getHeader().sizeofcmds)
  178. return malformedError("load command 0 extends past the end all load "
  179. "commands in the file");
  180. return getLoadCommandInfo(Obj, getPtr(Obj, HeaderSize), 0);
  181. }
  182. static Expected<MachOObjectFile::LoadCommandInfo>
  183. getNextLoadCommandInfo(const MachOObjectFile &Obj, uint32_t LoadCommandIndex,
  184. const MachOObjectFile::LoadCommandInfo &L) {
  185. unsigned HeaderSize = Obj.is64Bit() ? sizeof(MachO::mach_header_64)
  186. : sizeof(MachO::mach_header);
  187. if (L.Ptr + L.C.cmdsize + sizeof(MachO::load_command) >
  188. Obj.getData().data() + HeaderSize + Obj.getHeader().sizeofcmds)
  189. return malformedError("load command " + Twine(LoadCommandIndex + 1) +
  190. " extends past the end all load commands in the file");
  191. return getLoadCommandInfo(Obj, L.Ptr + L.C.cmdsize, LoadCommandIndex + 1);
  192. }
  193. template <typename T>
  194. static void parseHeader(const MachOObjectFile &Obj, T &Header,
  195. Error &Err) {
  196. if (sizeof(T) > Obj.getData().size()) {
  197. Err = malformedError("the mach header extends past the end of the "
  198. "file");
  199. return;
  200. }
  201. if (auto HeaderOrErr = getStructOrErr<T>(Obj, getPtr(Obj, 0)))
  202. Header = *HeaderOrErr;
  203. else
  204. Err = HeaderOrErr.takeError();
  205. }
  206. // This is used to check for overlapping of Mach-O elements.
  207. struct MachOElement {
  208. uint64_t Offset;
  209. uint64_t Size;
  210. const char *Name;
  211. };
  212. static Error checkOverlappingElement(std::list<MachOElement> &Elements,
  213. uint64_t Offset, uint64_t Size,
  214. const char *Name) {
  215. if (Size == 0)
  216. return Error::success();
  217. for (auto it=Elements.begin() ; it != Elements.end(); ++it) {
  218. auto E = *it;
  219. if ((Offset >= E.Offset && Offset < E.Offset + E.Size) ||
  220. (Offset + Size > E.Offset && Offset + Size < E.Offset + E.Size) ||
  221. (Offset <= E.Offset && Offset + Size >= E.Offset + E.Size))
  222. return malformedError(Twine(Name) + " at offset " + Twine(Offset) +
  223. " with a size of " + Twine(Size) + ", overlaps " +
  224. E.Name + " at offset " + Twine(E.Offset) + " with "
  225. "a size of " + Twine(E.Size));
  226. auto nt = it;
  227. nt++;
  228. if (nt != Elements.end()) {
  229. auto N = *nt;
  230. if (Offset + Size <= N.Offset) {
  231. Elements.insert(nt, {Offset, Size, Name});
  232. return Error::success();
  233. }
  234. }
  235. }
  236. Elements.push_back({Offset, Size, Name});
  237. return Error::success();
  238. }
  239. // Parses LC_SEGMENT or LC_SEGMENT_64 load command, adds addresses of all
  240. // sections to \param Sections, and optionally sets
  241. // \param IsPageZeroSegment to true.
  242. template <typename Segment, typename Section>
  243. static Error parseSegmentLoadCommand(
  244. const MachOObjectFile &Obj, const MachOObjectFile::LoadCommandInfo &Load,
  245. SmallVectorImpl<const char *> &Sections, bool &IsPageZeroSegment,
  246. uint32_t LoadCommandIndex, const char *CmdName, uint64_t SizeOfHeaders,
  247. std::list<MachOElement> &Elements) {
  248. const unsigned SegmentLoadSize = sizeof(Segment);
  249. if (Load.C.cmdsize < SegmentLoadSize)
  250. return malformedError("load command " + Twine(LoadCommandIndex) +
  251. " " + CmdName + " cmdsize too small");
  252. if (auto SegOrErr = getStructOrErr<Segment>(Obj, Load.Ptr)) {
  253. Segment S = SegOrErr.get();
  254. const unsigned SectionSize = sizeof(Section);
  255. uint64_t FileSize = Obj.getData().size();
  256. if (S.nsects > std::numeric_limits<uint32_t>::max() / SectionSize ||
  257. S.nsects * SectionSize > Load.C.cmdsize - SegmentLoadSize)
  258. return malformedError("load command " + Twine(LoadCommandIndex) +
  259. " inconsistent cmdsize in " + CmdName +
  260. " for the number of sections");
  261. for (unsigned J = 0; J < S.nsects; ++J) {
  262. const char *Sec = getSectionPtr(Obj, Load, J);
  263. Sections.push_back(Sec);
  264. auto SectionOrErr = getStructOrErr<Section>(Obj, Sec);
  265. if (!SectionOrErr)
  266. return SectionOrErr.takeError();
  267. Section s = SectionOrErr.get();
  268. if (Obj.getHeader().filetype != MachO::MH_DYLIB_STUB &&
  269. Obj.getHeader().filetype != MachO::MH_DSYM &&
  270. s.flags != MachO::S_ZEROFILL &&
  271. s.flags != MachO::S_THREAD_LOCAL_ZEROFILL &&
  272. s.offset > FileSize)
  273. return malformedError("offset field of section " + Twine(J) + " in " +
  274. CmdName + " command " + Twine(LoadCommandIndex) +
  275. " extends past the end of the file");
  276. if (Obj.getHeader().filetype != MachO::MH_DYLIB_STUB &&
  277. Obj.getHeader().filetype != MachO::MH_DSYM &&
  278. s.flags != MachO::S_ZEROFILL &&
  279. s.flags != MachO::S_THREAD_LOCAL_ZEROFILL && S.fileoff == 0 &&
  280. s.offset < SizeOfHeaders && s.size != 0)
  281. return malformedError("offset field of section " + Twine(J) + " in " +
  282. CmdName + " command " + Twine(LoadCommandIndex) +
  283. " not past the headers of the file");
  284. uint64_t BigSize = s.offset;
  285. BigSize += s.size;
  286. if (Obj.getHeader().filetype != MachO::MH_DYLIB_STUB &&
  287. Obj.getHeader().filetype != MachO::MH_DSYM &&
  288. s.flags != MachO::S_ZEROFILL &&
  289. s.flags != MachO::S_THREAD_LOCAL_ZEROFILL &&
  290. BigSize > FileSize)
  291. return malformedError("offset field plus size field of section " +
  292. Twine(J) + " in " + CmdName + " command " +
  293. Twine(LoadCommandIndex) +
  294. " extends past the end of the file");
  295. if (Obj.getHeader().filetype != MachO::MH_DYLIB_STUB &&
  296. Obj.getHeader().filetype != MachO::MH_DSYM &&
  297. s.flags != MachO::S_ZEROFILL &&
  298. s.flags != MachO::S_THREAD_LOCAL_ZEROFILL &&
  299. s.size > S.filesize)
  300. return malformedError("size field of section " +
  301. Twine(J) + " in " + CmdName + " command " +
  302. Twine(LoadCommandIndex) +
  303. " greater than the segment");
  304. if (Obj.getHeader().filetype != MachO::MH_DYLIB_STUB &&
  305. Obj.getHeader().filetype != MachO::MH_DSYM && s.size != 0 &&
  306. s.addr < S.vmaddr)
  307. return malformedError("addr field of section " + Twine(J) + " in " +
  308. CmdName + " command " + Twine(LoadCommandIndex) +
  309. " less than the segment's vmaddr");
  310. BigSize = s.addr;
  311. BigSize += s.size;
  312. uint64_t BigEnd = S.vmaddr;
  313. BigEnd += S.vmsize;
  314. if (S.vmsize != 0 && s.size != 0 && BigSize > BigEnd)
  315. return malformedError("addr field plus size of section " + Twine(J) +
  316. " in " + CmdName + " command " +
  317. Twine(LoadCommandIndex) +
  318. " greater than than "
  319. "the segment's vmaddr plus vmsize");
  320. if (Obj.getHeader().filetype != MachO::MH_DYLIB_STUB &&
  321. Obj.getHeader().filetype != MachO::MH_DSYM &&
  322. s.flags != MachO::S_ZEROFILL &&
  323. s.flags != MachO::S_THREAD_LOCAL_ZEROFILL)
  324. if (Error Err = checkOverlappingElement(Elements, s.offset, s.size,
  325. "section contents"))
  326. return Err;
  327. if (s.reloff > FileSize)
  328. return malformedError("reloff field of section " + Twine(J) + " in " +
  329. CmdName + " command " + Twine(LoadCommandIndex) +
  330. " extends past the end of the file");
  331. BigSize = s.nreloc;
  332. BigSize *= sizeof(struct MachO::relocation_info);
  333. BigSize += s.reloff;
  334. if (BigSize > FileSize)
  335. return malformedError("reloff field plus nreloc field times sizeof("
  336. "struct relocation_info) of section " +
  337. Twine(J) + " in " + CmdName + " command " +
  338. Twine(LoadCommandIndex) +
  339. " extends past the end of the file");
  340. if (Error Err = checkOverlappingElement(Elements, s.reloff, s.nreloc *
  341. sizeof(struct
  342. MachO::relocation_info),
  343. "section relocation entries"))
  344. return Err;
  345. }
  346. if (S.fileoff > FileSize)
  347. return malformedError("load command " + Twine(LoadCommandIndex) +
  348. " fileoff field in " + CmdName +
  349. " extends past the end of the file");
  350. uint64_t BigSize = S.fileoff;
  351. BigSize += S.filesize;
  352. if (BigSize > FileSize)
  353. return malformedError("load command " + Twine(LoadCommandIndex) +
  354. " fileoff field plus filesize field in " +
  355. CmdName + " extends past the end of the file");
  356. if (S.vmsize != 0 && S.filesize > S.vmsize)
  357. return malformedError("load command " + Twine(LoadCommandIndex) +
  358. " filesize field in " + CmdName +
  359. " greater than vmsize field");
  360. IsPageZeroSegment |= StringRef("__PAGEZERO").equals(S.segname);
  361. } else
  362. return SegOrErr.takeError();
  363. return Error::success();
  364. }
  365. static Error checkSymtabCommand(const MachOObjectFile &Obj,
  366. const MachOObjectFile::LoadCommandInfo &Load,
  367. uint32_t LoadCommandIndex,
  368. const char **SymtabLoadCmd,
  369. std::list<MachOElement> &Elements) {
  370. if (Load.C.cmdsize < sizeof(MachO::symtab_command))
  371. return malformedError("load command " + Twine(LoadCommandIndex) +
  372. " LC_SYMTAB cmdsize too small");
  373. if (*SymtabLoadCmd != nullptr)
  374. return malformedError("more than one LC_SYMTAB command");
  375. auto SymtabOrErr = getStructOrErr<MachO::symtab_command>(Obj, Load.Ptr);
  376. if (!SymtabOrErr)
  377. return SymtabOrErr.takeError();
  378. MachO::symtab_command Symtab = SymtabOrErr.get();
  379. if (Symtab.cmdsize != sizeof(MachO::symtab_command))
  380. return malformedError("LC_SYMTAB command " + Twine(LoadCommandIndex) +
  381. " has incorrect cmdsize");
  382. uint64_t FileSize = Obj.getData().size();
  383. if (Symtab.symoff > FileSize)
  384. return malformedError("symoff field of LC_SYMTAB command " +
  385. Twine(LoadCommandIndex) + " extends past the end "
  386. "of the file");
  387. uint64_t SymtabSize = Symtab.nsyms;
  388. const char *struct_nlist_name;
  389. if (Obj.is64Bit()) {
  390. SymtabSize *= sizeof(MachO::nlist_64);
  391. struct_nlist_name = "struct nlist_64";
  392. } else {
  393. SymtabSize *= sizeof(MachO::nlist);
  394. struct_nlist_name = "struct nlist";
  395. }
  396. uint64_t BigSize = SymtabSize;
  397. BigSize += Symtab.symoff;
  398. if (BigSize > FileSize)
  399. return malformedError("symoff field plus nsyms field times sizeof(" +
  400. Twine(struct_nlist_name) + ") of LC_SYMTAB command " +
  401. Twine(LoadCommandIndex) + " extends past the end "
  402. "of the file");
  403. if (Error Err = checkOverlappingElement(Elements, Symtab.symoff, SymtabSize,
  404. "symbol table"))
  405. return Err;
  406. if (Symtab.stroff > FileSize)
  407. return malformedError("stroff field of LC_SYMTAB command " +
  408. Twine(LoadCommandIndex) + " extends past the end "
  409. "of the file");
  410. BigSize = Symtab.stroff;
  411. BigSize += Symtab.strsize;
  412. if (BigSize > FileSize)
  413. return malformedError("stroff field plus strsize field of LC_SYMTAB "
  414. "command " + Twine(LoadCommandIndex) + " extends "
  415. "past the end of the file");
  416. if (Error Err = checkOverlappingElement(Elements, Symtab.stroff,
  417. Symtab.strsize, "string table"))
  418. return Err;
  419. *SymtabLoadCmd = Load.Ptr;
  420. return Error::success();
  421. }
  422. static Error checkDysymtabCommand(const MachOObjectFile &Obj,
  423. const MachOObjectFile::LoadCommandInfo &Load,
  424. uint32_t LoadCommandIndex,
  425. const char **DysymtabLoadCmd,
  426. std::list<MachOElement> &Elements) {
  427. if (Load.C.cmdsize < sizeof(MachO::dysymtab_command))
  428. return malformedError("load command " + Twine(LoadCommandIndex) +
  429. " LC_DYSYMTAB cmdsize too small");
  430. if (*DysymtabLoadCmd != nullptr)
  431. return malformedError("more than one LC_DYSYMTAB command");
  432. auto DysymtabOrErr =
  433. getStructOrErr<MachO::dysymtab_command>(Obj, Load.Ptr);
  434. if (!DysymtabOrErr)
  435. return DysymtabOrErr.takeError();
  436. MachO::dysymtab_command Dysymtab = DysymtabOrErr.get();
  437. if (Dysymtab.cmdsize != sizeof(MachO::dysymtab_command))
  438. return malformedError("LC_DYSYMTAB command " + Twine(LoadCommandIndex) +
  439. " has incorrect cmdsize");
  440. uint64_t FileSize = Obj.getData().size();
  441. if (Dysymtab.tocoff > FileSize)
  442. return malformedError("tocoff field of LC_DYSYMTAB command " +
  443. Twine(LoadCommandIndex) + " extends past the end of "
  444. "the file");
  445. uint64_t BigSize = Dysymtab.ntoc;
  446. BigSize *= sizeof(MachO::dylib_table_of_contents);
  447. BigSize += Dysymtab.tocoff;
  448. if (BigSize > FileSize)
  449. return malformedError("tocoff field plus ntoc field times sizeof(struct "
  450. "dylib_table_of_contents) of LC_DYSYMTAB command " +
  451. Twine(LoadCommandIndex) + " extends past the end of "
  452. "the file");
  453. if (Error Err = checkOverlappingElement(Elements, Dysymtab.tocoff,
  454. Dysymtab.ntoc * sizeof(struct
  455. MachO::dylib_table_of_contents),
  456. "table of contents"))
  457. return Err;
  458. if (Dysymtab.modtaboff > FileSize)
  459. return malformedError("modtaboff field of LC_DYSYMTAB command " +
  460. Twine(LoadCommandIndex) + " extends past the end of "
  461. "the file");
  462. BigSize = Dysymtab.nmodtab;
  463. const char *struct_dylib_module_name;
  464. uint64_t sizeof_modtab;
  465. if (Obj.is64Bit()) {
  466. sizeof_modtab = sizeof(MachO::dylib_module_64);
  467. struct_dylib_module_name = "struct dylib_module_64";
  468. } else {
  469. sizeof_modtab = sizeof(MachO::dylib_module);
  470. struct_dylib_module_name = "struct dylib_module";
  471. }
  472. BigSize *= sizeof_modtab;
  473. BigSize += Dysymtab.modtaboff;
  474. if (BigSize > FileSize)
  475. return malformedError("modtaboff field plus nmodtab field times sizeof(" +
  476. Twine(struct_dylib_module_name) + ") of LC_DYSYMTAB "
  477. "command " + Twine(LoadCommandIndex) + " extends "
  478. "past the end of the file");
  479. if (Error Err = checkOverlappingElement(Elements, Dysymtab.modtaboff,
  480. Dysymtab.nmodtab * sizeof_modtab,
  481. "module table"))
  482. return Err;
  483. if (Dysymtab.extrefsymoff > FileSize)
  484. return malformedError("extrefsymoff field of LC_DYSYMTAB command " +
  485. Twine(LoadCommandIndex) + " extends past the end of "
  486. "the file");
  487. BigSize = Dysymtab.nextrefsyms;
  488. BigSize *= sizeof(MachO::dylib_reference);
  489. BigSize += Dysymtab.extrefsymoff;
  490. if (BigSize > FileSize)
  491. return malformedError("extrefsymoff field plus nextrefsyms field times "
  492. "sizeof(struct dylib_reference) of LC_DYSYMTAB "
  493. "command " + Twine(LoadCommandIndex) + " extends "
  494. "past the end of the file");
  495. if (Error Err = checkOverlappingElement(Elements, Dysymtab.extrefsymoff,
  496. Dysymtab.nextrefsyms *
  497. sizeof(MachO::dylib_reference),
  498. "reference table"))
  499. return Err;
  500. if (Dysymtab.indirectsymoff > FileSize)
  501. return malformedError("indirectsymoff field of LC_DYSYMTAB command " +
  502. Twine(LoadCommandIndex) + " extends past the end of "
  503. "the file");
  504. BigSize = Dysymtab.nindirectsyms;
  505. BigSize *= sizeof(uint32_t);
  506. BigSize += Dysymtab.indirectsymoff;
  507. if (BigSize > FileSize)
  508. return malformedError("indirectsymoff field plus nindirectsyms field times "
  509. "sizeof(uint32_t) of LC_DYSYMTAB command " +
  510. Twine(LoadCommandIndex) + " extends past the end of "
  511. "the file");
  512. if (Error Err = checkOverlappingElement(Elements, Dysymtab.indirectsymoff,
  513. Dysymtab.nindirectsyms *
  514. sizeof(uint32_t),
  515. "indirect table"))
  516. return Err;
  517. if (Dysymtab.extreloff > FileSize)
  518. return malformedError("extreloff field of LC_DYSYMTAB command " +
  519. Twine(LoadCommandIndex) + " extends past the end of "
  520. "the file");
  521. BigSize = Dysymtab.nextrel;
  522. BigSize *= sizeof(MachO::relocation_info);
  523. BigSize += Dysymtab.extreloff;
  524. if (BigSize > FileSize)
  525. return malformedError("extreloff field plus nextrel field times sizeof"
  526. "(struct relocation_info) of LC_DYSYMTAB command " +
  527. Twine(LoadCommandIndex) + " extends past the end of "
  528. "the file");
  529. if (Error Err = checkOverlappingElement(Elements, Dysymtab.extreloff,
  530. Dysymtab.nextrel *
  531. sizeof(MachO::relocation_info),
  532. "external relocation table"))
  533. return Err;
  534. if (Dysymtab.locreloff > FileSize)
  535. return malformedError("locreloff field of LC_DYSYMTAB command " +
  536. Twine(LoadCommandIndex) + " extends past the end of "
  537. "the file");
  538. BigSize = Dysymtab.nlocrel;
  539. BigSize *= sizeof(MachO::relocation_info);
  540. BigSize += Dysymtab.locreloff;
  541. if (BigSize > FileSize)
  542. return malformedError("locreloff field plus nlocrel field times sizeof"
  543. "(struct relocation_info) of LC_DYSYMTAB command " +
  544. Twine(LoadCommandIndex) + " extends past the end of "
  545. "the file");
  546. if (Error Err = checkOverlappingElement(Elements, Dysymtab.locreloff,
  547. Dysymtab.nlocrel *
  548. sizeof(MachO::relocation_info),
  549. "local relocation table"))
  550. return Err;
  551. *DysymtabLoadCmd = Load.Ptr;
  552. return Error::success();
  553. }
  554. static Error checkLinkeditDataCommand(const MachOObjectFile &Obj,
  555. const MachOObjectFile::LoadCommandInfo &Load,
  556. uint32_t LoadCommandIndex,
  557. const char **LoadCmd, const char *CmdName,
  558. std::list<MachOElement> &Elements,
  559. const char *ElementName) {
  560. if (Load.C.cmdsize < sizeof(MachO::linkedit_data_command))
  561. return malformedError("load command " + Twine(LoadCommandIndex) + " " +
  562. CmdName + " cmdsize too small");
  563. if (*LoadCmd != nullptr)
  564. return malformedError("more than one " + Twine(CmdName) + " command");
  565. auto LinkDataOrError =
  566. getStructOrErr<MachO::linkedit_data_command>(Obj, Load.Ptr);
  567. if (!LinkDataOrError)
  568. return LinkDataOrError.takeError();
  569. MachO::linkedit_data_command LinkData = LinkDataOrError.get();
  570. if (LinkData.cmdsize != sizeof(MachO::linkedit_data_command))
  571. return malformedError(Twine(CmdName) + " command " +
  572. Twine(LoadCommandIndex) + " has incorrect cmdsize");
  573. uint64_t FileSize = Obj.getData().size();
  574. if (LinkData.dataoff > FileSize)
  575. return malformedError("dataoff field of " + Twine(CmdName) + " command " +
  576. Twine(LoadCommandIndex) + " extends past the end of "
  577. "the file");
  578. uint64_t BigSize = LinkData.dataoff;
  579. BigSize += LinkData.datasize;
  580. if (BigSize > FileSize)
  581. return malformedError("dataoff field plus datasize field of " +
  582. Twine(CmdName) + " command " +
  583. Twine(LoadCommandIndex) + " extends past the end of "
  584. "the file");
  585. if (Error Err = checkOverlappingElement(Elements, LinkData.dataoff,
  586. LinkData.datasize, ElementName))
  587. return Err;
  588. *LoadCmd = Load.Ptr;
  589. return Error::success();
  590. }
  591. static Error checkDyldInfoCommand(const MachOObjectFile &Obj,
  592. const MachOObjectFile::LoadCommandInfo &Load,
  593. uint32_t LoadCommandIndex,
  594. const char **LoadCmd, const char *CmdName,
  595. std::list<MachOElement> &Elements) {
  596. if (Load.C.cmdsize < sizeof(MachO::dyld_info_command))
  597. return malformedError("load command " + Twine(LoadCommandIndex) + " " +
  598. CmdName + " cmdsize too small");
  599. if (*LoadCmd != nullptr)
  600. return malformedError("more than one LC_DYLD_INFO and or LC_DYLD_INFO_ONLY "
  601. "command");
  602. auto DyldInfoOrErr =
  603. getStructOrErr<MachO::dyld_info_command>(Obj, Load.Ptr);
  604. if (!DyldInfoOrErr)
  605. return DyldInfoOrErr.takeError();
  606. MachO::dyld_info_command DyldInfo = DyldInfoOrErr.get();
  607. if (DyldInfo.cmdsize != sizeof(MachO::dyld_info_command))
  608. return malformedError(Twine(CmdName) + " command " +
  609. Twine(LoadCommandIndex) + " has incorrect cmdsize");
  610. uint64_t FileSize = Obj.getData().size();
  611. if (DyldInfo.rebase_off > FileSize)
  612. return malformedError("rebase_off field of " + Twine(CmdName) +
  613. " command " + Twine(LoadCommandIndex) + " extends "
  614. "past the end of the file");
  615. uint64_t BigSize = DyldInfo.rebase_off;
  616. BigSize += DyldInfo.rebase_size;
  617. if (BigSize > FileSize)
  618. return malformedError("rebase_off field plus rebase_size field of " +
  619. Twine(CmdName) + " command " +
  620. Twine(LoadCommandIndex) + " extends past the end of "
  621. "the file");
  622. if (Error Err = checkOverlappingElement(Elements, DyldInfo.rebase_off,
  623. DyldInfo.rebase_size,
  624. "dyld rebase info"))
  625. return Err;
  626. if (DyldInfo.bind_off > FileSize)
  627. return malformedError("bind_off field of " + Twine(CmdName) +
  628. " command " + Twine(LoadCommandIndex) + " extends "
  629. "past the end of the file");
  630. BigSize = DyldInfo.bind_off;
  631. BigSize += DyldInfo.bind_size;
  632. if (BigSize > FileSize)
  633. return malformedError("bind_off field plus bind_size field of " +
  634. Twine(CmdName) + " command " +
  635. Twine(LoadCommandIndex) + " extends past the end of "
  636. "the file");
  637. if (Error Err = checkOverlappingElement(Elements, DyldInfo.bind_off,
  638. DyldInfo.bind_size,
  639. "dyld bind info"))
  640. return Err;
  641. if (DyldInfo.weak_bind_off > FileSize)
  642. return malformedError("weak_bind_off field of " + Twine(CmdName) +
  643. " command " + Twine(LoadCommandIndex) + " extends "
  644. "past the end of the file");
  645. BigSize = DyldInfo.weak_bind_off;
  646. BigSize += DyldInfo.weak_bind_size;
  647. if (BigSize > FileSize)
  648. return malformedError("weak_bind_off field plus weak_bind_size field of " +
  649. Twine(CmdName) + " command " +
  650. Twine(LoadCommandIndex) + " extends past the end of "
  651. "the file");
  652. if (Error Err = checkOverlappingElement(Elements, DyldInfo.weak_bind_off,
  653. DyldInfo.weak_bind_size,
  654. "dyld weak bind info"))
  655. return Err;
  656. if (DyldInfo.lazy_bind_off > FileSize)
  657. return malformedError("lazy_bind_off field of " + Twine(CmdName) +
  658. " command " + Twine(LoadCommandIndex) + " extends "
  659. "past the end of the file");
  660. BigSize = DyldInfo.lazy_bind_off;
  661. BigSize += DyldInfo.lazy_bind_size;
  662. if (BigSize > FileSize)
  663. return malformedError("lazy_bind_off field plus lazy_bind_size field of " +
  664. Twine(CmdName) + " command " +
  665. Twine(LoadCommandIndex) + " extends past the end of "
  666. "the file");
  667. if (Error Err = checkOverlappingElement(Elements, DyldInfo.lazy_bind_off,
  668. DyldInfo.lazy_bind_size,
  669. "dyld lazy bind info"))
  670. return Err;
  671. if (DyldInfo.export_off > FileSize)
  672. return malformedError("export_off field of " + Twine(CmdName) +
  673. " command " + Twine(LoadCommandIndex) + " extends "
  674. "past the end of the file");
  675. BigSize = DyldInfo.export_off;
  676. BigSize += DyldInfo.export_size;
  677. if (BigSize > FileSize)
  678. return malformedError("export_off field plus export_size field of " +
  679. Twine(CmdName) + " command " +
  680. Twine(LoadCommandIndex) + " extends past the end of "
  681. "the file");
  682. if (Error Err = checkOverlappingElement(Elements, DyldInfo.export_off,
  683. DyldInfo.export_size,
  684. "dyld export info"))
  685. return Err;
  686. *LoadCmd = Load.Ptr;
  687. return Error::success();
  688. }
  689. static Error checkDylibCommand(const MachOObjectFile &Obj,
  690. const MachOObjectFile::LoadCommandInfo &Load,
  691. uint32_t LoadCommandIndex, const char *CmdName) {
  692. if (Load.C.cmdsize < sizeof(MachO::dylib_command))
  693. return malformedError("load command " + Twine(LoadCommandIndex) + " " +
  694. CmdName + " cmdsize too small");
  695. auto CommandOrErr = getStructOrErr<MachO::dylib_command>(Obj, Load.Ptr);
  696. if (!CommandOrErr)
  697. return CommandOrErr.takeError();
  698. MachO::dylib_command D = CommandOrErr.get();
  699. if (D.dylib.name < sizeof(MachO::dylib_command))
  700. return malformedError("load command " + Twine(LoadCommandIndex) + " " +
  701. CmdName + " name.offset field too small, not past "
  702. "the end of the dylib_command struct");
  703. if (D.dylib.name >= D.cmdsize)
  704. return malformedError("load command " + Twine(LoadCommandIndex) + " " +
  705. CmdName + " name.offset field extends past the end "
  706. "of the load command");
  707. // Make sure there is a null between the starting offset of the name and
  708. // the end of the load command.
  709. uint32_t i;
  710. const char *P = (const char *)Load.Ptr;
  711. for (i = D.dylib.name; i < D.cmdsize; i++)
  712. if (P[i] == '\0')
  713. break;
  714. if (i >= D.cmdsize)
  715. return malformedError("load command " + Twine(LoadCommandIndex) + " " +
  716. CmdName + " library name extends past the end of the "
  717. "load command");
  718. return Error::success();
  719. }
  720. static Error checkDylibIdCommand(const MachOObjectFile &Obj,
  721. const MachOObjectFile::LoadCommandInfo &Load,
  722. uint32_t LoadCommandIndex,
  723. const char **LoadCmd) {
  724. if (Error Err = checkDylibCommand(Obj, Load, LoadCommandIndex,
  725. "LC_ID_DYLIB"))
  726. return Err;
  727. if (*LoadCmd != nullptr)
  728. return malformedError("more than one LC_ID_DYLIB command");
  729. if (Obj.getHeader().filetype != MachO::MH_DYLIB &&
  730. Obj.getHeader().filetype != MachO::MH_DYLIB_STUB)
  731. return malformedError("LC_ID_DYLIB load command in non-dynamic library "
  732. "file type");
  733. *LoadCmd = Load.Ptr;
  734. return Error::success();
  735. }
  736. static Error checkDyldCommand(const MachOObjectFile &Obj,
  737. const MachOObjectFile::LoadCommandInfo &Load,
  738. uint32_t LoadCommandIndex, const char *CmdName) {
  739. if (Load.C.cmdsize < sizeof(MachO::dylinker_command))
  740. return malformedError("load command " + Twine(LoadCommandIndex) + " " +
  741. CmdName + " cmdsize too small");
  742. auto CommandOrErr = getStructOrErr<MachO::dylinker_command>(Obj, Load.Ptr);
  743. if (!CommandOrErr)
  744. return CommandOrErr.takeError();
  745. MachO::dylinker_command D = CommandOrErr.get();
  746. if (D.name < sizeof(MachO::dylinker_command))
  747. return malformedError("load command " + Twine(LoadCommandIndex) + " " +
  748. CmdName + " name.offset field too small, not past "
  749. "the end of the dylinker_command struct");
  750. if (D.name >= D.cmdsize)
  751. return malformedError("load command " + Twine(LoadCommandIndex) + " " +
  752. CmdName + " name.offset field extends past the end "
  753. "of the load command");
  754. // Make sure there is a null between the starting offset of the name and
  755. // the end of the load command.
  756. uint32_t i;
  757. const char *P = (const char *)Load.Ptr;
  758. for (i = D.name; i < D.cmdsize; i++)
  759. if (P[i] == '\0')
  760. break;
  761. if (i >= D.cmdsize)
  762. return malformedError("load command " + Twine(LoadCommandIndex) + " " +
  763. CmdName + " dyld name extends past the end of the "
  764. "load command");
  765. return Error::success();
  766. }
  767. static Error checkVersCommand(const MachOObjectFile &Obj,
  768. const MachOObjectFile::LoadCommandInfo &Load,
  769. uint32_t LoadCommandIndex,
  770. const char **LoadCmd, const char *CmdName) {
  771. if (Load.C.cmdsize != sizeof(MachO::version_min_command))
  772. return malformedError("load command " + Twine(LoadCommandIndex) + " " +
  773. CmdName + " has incorrect cmdsize");
  774. if (*LoadCmd != nullptr)
  775. return malformedError("more than one LC_VERSION_MIN_MACOSX, "
  776. "LC_VERSION_MIN_IPHONEOS, LC_VERSION_MIN_TVOS or "
  777. "LC_VERSION_MIN_WATCHOS command");
  778. *LoadCmd = Load.Ptr;
  779. return Error::success();
  780. }
  781. static Error checkNoteCommand(const MachOObjectFile &Obj,
  782. const MachOObjectFile::LoadCommandInfo &Load,
  783. uint32_t LoadCommandIndex,
  784. std::list<MachOElement> &Elements) {
  785. if (Load.C.cmdsize != sizeof(MachO::note_command))
  786. return malformedError("load command " + Twine(LoadCommandIndex) +
  787. " LC_NOTE has incorrect cmdsize");
  788. auto NoteCmdOrErr = getStructOrErr<MachO::note_command>(Obj, Load.Ptr);
  789. if (!NoteCmdOrErr)
  790. return NoteCmdOrErr.takeError();
  791. MachO::note_command Nt = NoteCmdOrErr.get();
  792. uint64_t FileSize = Obj.getData().size();
  793. if (Nt.offset > FileSize)
  794. return malformedError("offset field of LC_NOTE command " +
  795. Twine(LoadCommandIndex) + " extends "
  796. "past the end of the file");
  797. uint64_t BigSize = Nt.offset;
  798. BigSize += Nt.size;
  799. if (BigSize > FileSize)
  800. return malformedError("size field plus offset field of LC_NOTE command " +
  801. Twine(LoadCommandIndex) + " extends past the end of "
  802. "the file");
  803. if (Error Err = checkOverlappingElement(Elements, Nt.offset, Nt.size,
  804. "LC_NOTE data"))
  805. return Err;
  806. return Error::success();
  807. }
  808. static Error
  809. parseBuildVersionCommand(const MachOObjectFile &Obj,
  810. const MachOObjectFile::LoadCommandInfo &Load,
  811. SmallVectorImpl<const char*> &BuildTools,
  812. uint32_t LoadCommandIndex) {
  813. auto BVCOrErr =
  814. getStructOrErr<MachO::build_version_command>(Obj, Load.Ptr);
  815. if (!BVCOrErr)
  816. return BVCOrErr.takeError();
  817. MachO::build_version_command BVC = BVCOrErr.get();
  818. if (Load.C.cmdsize !=
  819. sizeof(MachO::build_version_command) +
  820. BVC.ntools * sizeof(MachO::build_tool_version))
  821. return malformedError("load command " + Twine(LoadCommandIndex) +
  822. " LC_BUILD_VERSION_COMMAND has incorrect cmdsize");
  823. auto Start = Load.Ptr + sizeof(MachO::build_version_command);
  824. BuildTools.resize(BVC.ntools);
  825. for (unsigned i = 0; i < BVC.ntools; ++i)
  826. BuildTools[i] = Start + i * sizeof(MachO::build_tool_version);
  827. return Error::success();
  828. }
  829. static Error checkRpathCommand(const MachOObjectFile &Obj,
  830. const MachOObjectFile::LoadCommandInfo &Load,
  831. uint32_t LoadCommandIndex) {
  832. if (Load.C.cmdsize < sizeof(MachO::rpath_command))
  833. return malformedError("load command " + Twine(LoadCommandIndex) +
  834. " LC_RPATH cmdsize too small");
  835. auto ROrErr = getStructOrErr<MachO::rpath_command>(Obj, Load.Ptr);
  836. if (!ROrErr)
  837. return ROrErr.takeError();
  838. MachO::rpath_command R = ROrErr.get();
  839. if (R.path < sizeof(MachO::rpath_command))
  840. return malformedError("load command " + Twine(LoadCommandIndex) +
  841. " LC_RPATH path.offset field too small, not past "
  842. "the end of the rpath_command struct");
  843. if (R.path >= R.cmdsize)
  844. return malformedError("load command " + Twine(LoadCommandIndex) +
  845. " LC_RPATH path.offset field extends past the end "
  846. "of the load command");
  847. // Make sure there is a null between the starting offset of the path and
  848. // the end of the load command.
  849. uint32_t i;
  850. const char *P = (const char *)Load.Ptr;
  851. for (i = R.path; i < R.cmdsize; i++)
  852. if (P[i] == '\0')
  853. break;
  854. if (i >= R.cmdsize)
  855. return malformedError("load command " + Twine(LoadCommandIndex) +
  856. " LC_RPATH library name extends past the end of the "
  857. "load command");
  858. return Error::success();
  859. }
  860. static Error checkEncryptCommand(const MachOObjectFile &Obj,
  861. const MachOObjectFile::LoadCommandInfo &Load,
  862. uint32_t LoadCommandIndex,
  863. uint64_t cryptoff, uint64_t cryptsize,
  864. const char **LoadCmd, const char *CmdName) {
  865. if (*LoadCmd != nullptr)
  866. return malformedError("more than one LC_ENCRYPTION_INFO and or "
  867. "LC_ENCRYPTION_INFO_64 command");
  868. uint64_t FileSize = Obj.getData().size();
  869. if (cryptoff > FileSize)
  870. return malformedError("cryptoff field of " + Twine(CmdName) +
  871. " command " + Twine(LoadCommandIndex) + " extends "
  872. "past the end of the file");
  873. uint64_t BigSize = cryptoff;
  874. BigSize += cryptsize;
  875. if (BigSize > FileSize)
  876. return malformedError("cryptoff field plus cryptsize field of " +
  877. Twine(CmdName) + " command " +
  878. Twine(LoadCommandIndex) + " extends past the end of "
  879. "the file");
  880. *LoadCmd = Load.Ptr;
  881. return Error::success();
  882. }
  883. static Error checkLinkerOptCommand(const MachOObjectFile &Obj,
  884. const MachOObjectFile::LoadCommandInfo &Load,
  885. uint32_t LoadCommandIndex) {
  886. if (Load.C.cmdsize < sizeof(MachO::linker_option_command))
  887. return malformedError("load command " + Twine(LoadCommandIndex) +
  888. " LC_LINKER_OPTION cmdsize too small");
  889. auto LinkOptionOrErr =
  890. getStructOrErr<MachO::linker_option_command>(Obj, Load.Ptr);
  891. if (!LinkOptionOrErr)
  892. return LinkOptionOrErr.takeError();
  893. MachO::linker_option_command L = LinkOptionOrErr.get();
  894. // Make sure the count of strings is correct.
  895. const char *string = (const char *)Load.Ptr +
  896. sizeof(struct MachO::linker_option_command);
  897. uint32_t left = L.cmdsize - sizeof(struct MachO::linker_option_command);
  898. uint32_t i = 0;
  899. while (left > 0) {
  900. while (*string == '\0' && left > 0) {
  901. string++;
  902. left--;
  903. }
  904. if (left > 0) {
  905. i++;
  906. uint32_t NullPos = StringRef(string, left).find('\0');
  907. if (0xffffffff == NullPos)
  908. return malformedError("load command " + Twine(LoadCommandIndex) +
  909. " LC_LINKER_OPTION string #" + Twine(i) +
  910. " is not NULL terminated");
  911. uint32_t len = std::min(NullPos, left) + 1;
  912. string += len;
  913. left -= len;
  914. }
  915. }
  916. if (L.count != i)
  917. return malformedError("load command " + Twine(LoadCommandIndex) +
  918. " LC_LINKER_OPTION string count " + Twine(L.count) +
  919. " does not match number of strings");
  920. return Error::success();
  921. }
  922. static Error checkSubCommand(const MachOObjectFile &Obj,
  923. const MachOObjectFile::LoadCommandInfo &Load,
  924. uint32_t LoadCommandIndex, const char *CmdName,
  925. size_t SizeOfCmd, const char *CmdStructName,
  926. uint32_t PathOffset, const char *PathFieldName) {
  927. if (PathOffset < SizeOfCmd)
  928. return malformedError("load command " + Twine(LoadCommandIndex) + " " +
  929. CmdName + " " + PathFieldName + ".offset field too "
  930. "small, not past the end of the " + CmdStructName);
  931. if (PathOffset >= Load.C.cmdsize)
  932. return malformedError("load command " + Twine(LoadCommandIndex) + " " +
  933. CmdName + " " + PathFieldName + ".offset field "
  934. "extends past the end of the load command");
  935. // Make sure there is a null between the starting offset of the path and
  936. // the end of the load command.
  937. uint32_t i;
  938. const char *P = (const char *)Load.Ptr;
  939. for (i = PathOffset; i < Load.C.cmdsize; i++)
  940. if (P[i] == '\0')
  941. break;
  942. if (i >= Load.C.cmdsize)
  943. return malformedError("load command " + Twine(LoadCommandIndex) + " " +
  944. CmdName + " " + PathFieldName + " name extends past "
  945. "the end of the load command");
  946. return Error::success();
  947. }
  948. static Error checkThreadCommand(const MachOObjectFile &Obj,
  949. const MachOObjectFile::LoadCommandInfo &Load,
  950. uint32_t LoadCommandIndex,
  951. const char *CmdName) {
  952. if (Load.C.cmdsize < sizeof(MachO::thread_command))
  953. return malformedError("load command " + Twine(LoadCommandIndex) +
  954. CmdName + " cmdsize too small");
  955. auto ThreadCommandOrErr =
  956. getStructOrErr<MachO::thread_command>(Obj, Load.Ptr);
  957. if (!ThreadCommandOrErr)
  958. return ThreadCommandOrErr.takeError();
  959. MachO::thread_command T = ThreadCommandOrErr.get();
  960. const char *state = Load.Ptr + sizeof(MachO::thread_command);
  961. const char *end = Load.Ptr + T.cmdsize;
  962. uint32_t nflavor = 0;
  963. uint32_t cputype = getCPUType(Obj);
  964. while (state < end) {
  965. if(state + sizeof(uint32_t) > end)
  966. return malformedError("load command " + Twine(LoadCommandIndex) +
  967. "flavor in " + CmdName + " extends past end of "
  968. "command");
  969. uint32_t flavor;
  970. memcpy(&flavor, state, sizeof(uint32_t));
  971. if (Obj.isLittleEndian() != sys::IsLittleEndianHost)
  972. sys::swapByteOrder(flavor);
  973. state += sizeof(uint32_t);
  974. if(state + sizeof(uint32_t) > end)
  975. return malformedError("load command " + Twine(LoadCommandIndex) +
  976. " count in " + CmdName + " extends past end of "
  977. "command");
  978. uint32_t count;
  979. memcpy(&count, state, sizeof(uint32_t));
  980. if (Obj.isLittleEndian() != sys::IsLittleEndianHost)
  981. sys::swapByteOrder(count);
  982. state += sizeof(uint32_t);
  983. if (cputype == MachO::CPU_TYPE_I386) {
  984. if (flavor == MachO::x86_THREAD_STATE32) {
  985. if (count != MachO::x86_THREAD_STATE32_COUNT)
  986. return malformedError("load command " + Twine(LoadCommandIndex) +
  987. " count not x86_THREAD_STATE32_COUNT for "
  988. "flavor number " + Twine(nflavor) + " which is "
  989. "a x86_THREAD_STATE32 flavor in " + CmdName +
  990. " command");
  991. if (state + sizeof(MachO::x86_thread_state32_t) > end)
  992. return malformedError("load command " + Twine(LoadCommandIndex) +
  993. " x86_THREAD_STATE32 extends past end of "
  994. "command in " + CmdName + " command");
  995. state += sizeof(MachO::x86_thread_state32_t);
  996. } else {
  997. return malformedError("load command " + Twine(LoadCommandIndex) +
  998. " unknown flavor (" + Twine(flavor) + ") for "
  999. "flavor number " + Twine(nflavor) + " in " +
  1000. CmdName + " command");
  1001. }
  1002. } else if (cputype == MachO::CPU_TYPE_X86_64) {
  1003. if (flavor == MachO::x86_THREAD_STATE) {
  1004. if (count != MachO::x86_THREAD_STATE_COUNT)
  1005. return malformedError("load command " + Twine(LoadCommandIndex) +
  1006. " count not x86_THREAD_STATE_COUNT for "
  1007. "flavor number " + Twine(nflavor) + " which is "
  1008. "a x86_THREAD_STATE flavor in " + CmdName +
  1009. " command");
  1010. if (state + sizeof(MachO::x86_thread_state_t) > end)
  1011. return malformedError("load command " + Twine(LoadCommandIndex) +
  1012. " x86_THREAD_STATE extends past end of "
  1013. "command in " + CmdName + " command");
  1014. state += sizeof(MachO::x86_thread_state_t);
  1015. } else if (flavor == MachO::x86_FLOAT_STATE) {
  1016. if (count != MachO::x86_FLOAT_STATE_COUNT)
  1017. return malformedError("load command " + Twine(LoadCommandIndex) +
  1018. " count not x86_FLOAT_STATE_COUNT for "
  1019. "flavor number " + Twine(nflavor) + " which is "
  1020. "a x86_FLOAT_STATE flavor in " + CmdName +
  1021. " command");
  1022. if (state + sizeof(MachO::x86_float_state_t) > end)
  1023. return malformedError("load command " + Twine(LoadCommandIndex) +
  1024. " x86_FLOAT_STATE extends past end of "
  1025. "command in " + CmdName + " command");
  1026. state += sizeof(MachO::x86_float_state_t);
  1027. } else if (flavor == MachO::x86_EXCEPTION_STATE) {
  1028. if (count != MachO::x86_EXCEPTION_STATE_COUNT)
  1029. return malformedError("load command " + Twine(LoadCommandIndex) +
  1030. " count not x86_EXCEPTION_STATE_COUNT for "
  1031. "flavor number " + Twine(nflavor) + " which is "
  1032. "a x86_EXCEPTION_STATE flavor in " + CmdName +
  1033. " command");
  1034. if (state + sizeof(MachO::x86_exception_state_t) > end)
  1035. return malformedError("load command " + Twine(LoadCommandIndex) +
  1036. " x86_EXCEPTION_STATE extends past end of "
  1037. "command in " + CmdName + " command");
  1038. state += sizeof(MachO::x86_exception_state_t);
  1039. } else if (flavor == MachO::x86_THREAD_STATE64) {
  1040. if (count != MachO::x86_THREAD_STATE64_COUNT)
  1041. return malformedError("load command " + Twine(LoadCommandIndex) +
  1042. " count not x86_THREAD_STATE64_COUNT for "
  1043. "flavor number " + Twine(nflavor) + " which is "
  1044. "a x86_THREAD_STATE64 flavor in " + CmdName +
  1045. " command");
  1046. if (state + sizeof(MachO::x86_thread_state64_t) > end)
  1047. return malformedError("load command " + Twine(LoadCommandIndex) +
  1048. " x86_THREAD_STATE64 extends past end of "
  1049. "command in " + CmdName + " command");
  1050. state += sizeof(MachO::x86_thread_state64_t);
  1051. } else if (flavor == MachO::x86_EXCEPTION_STATE64) {
  1052. if (count != MachO::x86_EXCEPTION_STATE64_COUNT)
  1053. return malformedError("load command " + Twine(LoadCommandIndex) +
  1054. " count not x86_EXCEPTION_STATE64_COUNT for "
  1055. "flavor number " + Twine(nflavor) + " which is "
  1056. "a x86_EXCEPTION_STATE64 flavor in " + CmdName +
  1057. " command");
  1058. if (state + sizeof(MachO::x86_exception_state64_t) > end)
  1059. return malformedError("load command " + Twine(LoadCommandIndex) +
  1060. " x86_EXCEPTION_STATE64 extends past end of "
  1061. "command in " + CmdName + " command");
  1062. state += sizeof(MachO::x86_exception_state64_t);
  1063. } else {
  1064. return malformedError("load command " + Twine(LoadCommandIndex) +
  1065. " unknown flavor (" + Twine(flavor) + ") for "
  1066. "flavor number " + Twine(nflavor) + " in " +
  1067. CmdName + " command");
  1068. }
  1069. } else if (cputype == MachO::CPU_TYPE_ARM) {
  1070. if (flavor == MachO::ARM_THREAD_STATE) {
  1071. if (count != MachO::ARM_THREAD_STATE_COUNT)
  1072. return malformedError("load command " + Twine(LoadCommandIndex) +
  1073. " count not ARM_THREAD_STATE_COUNT for "
  1074. "flavor number " + Twine(nflavor) + " which is "
  1075. "a ARM_THREAD_STATE flavor in " + CmdName +
  1076. " command");
  1077. if (state + sizeof(MachO::arm_thread_state32_t) > end)
  1078. return malformedError("load command " + Twine(LoadCommandIndex) +
  1079. " ARM_THREAD_STATE extends past end of "
  1080. "command in " + CmdName + " command");
  1081. state += sizeof(MachO::arm_thread_state32_t);
  1082. } else {
  1083. return malformedError("load command " + Twine(LoadCommandIndex) +
  1084. " unknown flavor (" + Twine(flavor) + ") for "
  1085. "flavor number " + Twine(nflavor) + " in " +
  1086. CmdName + " command");
  1087. }
  1088. } else if (cputype == MachO::CPU_TYPE_ARM64 ||
  1089. cputype == MachO::CPU_TYPE_ARM64_32) {
  1090. if (flavor == MachO::ARM_THREAD_STATE64) {
  1091. if (count != MachO::ARM_THREAD_STATE64_COUNT)
  1092. return malformedError("load command " + Twine(LoadCommandIndex) +
  1093. " count not ARM_THREAD_STATE64_COUNT for "
  1094. "flavor number " + Twine(nflavor) + " which is "
  1095. "a ARM_THREAD_STATE64 flavor in " + CmdName +
  1096. " command");
  1097. if (state + sizeof(MachO::arm_thread_state64_t) > end)
  1098. return malformedError("load command " + Twine(LoadCommandIndex) +
  1099. " ARM_THREAD_STATE64 extends past end of "
  1100. "command in " + CmdName + " command");
  1101. state += sizeof(MachO::arm_thread_state64_t);
  1102. } else {
  1103. return malformedError("load command " + Twine(LoadCommandIndex) +
  1104. " unknown flavor (" + Twine(flavor) + ") for "
  1105. "flavor number " + Twine(nflavor) + " in " +
  1106. CmdName + " command");
  1107. }
  1108. } else if (cputype == MachO::CPU_TYPE_POWERPC) {
  1109. if (flavor == MachO::PPC_THREAD_STATE) {
  1110. if (count != MachO::PPC_THREAD_STATE_COUNT)
  1111. return malformedError("load command " + Twine(LoadCommandIndex) +
  1112. " count not PPC_THREAD_STATE_COUNT for "
  1113. "flavor number " + Twine(nflavor) + " which is "
  1114. "a PPC_THREAD_STATE flavor in " + CmdName +
  1115. " command");
  1116. if (state + sizeof(MachO::ppc_thread_state32_t) > end)
  1117. return malformedError("load command " + Twine(LoadCommandIndex) +
  1118. " PPC_THREAD_STATE extends past end of "
  1119. "command in " + CmdName + " command");
  1120. state += sizeof(MachO::ppc_thread_state32_t);
  1121. } else {
  1122. return malformedError("load command " + Twine(LoadCommandIndex) +
  1123. " unknown flavor (" + Twine(flavor) + ") for "
  1124. "flavor number " + Twine(nflavor) + " in " +
  1125. CmdName + " command");
  1126. }
  1127. } else {
  1128. return malformedError("unknown cputype (" + Twine(cputype) + ") load "
  1129. "command " + Twine(LoadCommandIndex) + " for " +
  1130. CmdName + " command can't be checked");
  1131. }
  1132. nflavor++;
  1133. }
  1134. return Error::success();
  1135. }
  1136. static Error checkTwoLevelHintsCommand(const MachOObjectFile &Obj,
  1137. const MachOObjectFile::LoadCommandInfo
  1138. &Load,
  1139. uint32_t LoadCommandIndex,
  1140. const char **LoadCmd,
  1141. std::list<MachOElement> &Elements) {
  1142. if (Load.C.cmdsize != sizeof(MachO::twolevel_hints_command))
  1143. return malformedError("load command " + Twine(LoadCommandIndex) +
  1144. " LC_TWOLEVEL_HINTS has incorrect cmdsize");
  1145. if (*LoadCmd != nullptr)
  1146. return malformedError("more than one LC_TWOLEVEL_HINTS command");
  1147. auto HintsOrErr = getStructOrErr<MachO::twolevel_hints_command>(Obj, Load.Ptr);
  1148. if(!HintsOrErr)
  1149. return HintsOrErr.takeError();
  1150. MachO::twolevel_hints_command Hints = HintsOrErr.get();
  1151. uint64_t FileSize = Obj.getData().size();
  1152. if (Hints.offset > FileSize)
  1153. return malformedError("offset field of LC_TWOLEVEL_HINTS command " +
  1154. Twine(LoadCommandIndex) + " extends past the end of "
  1155. "the file");
  1156. uint64_t BigSize = Hints.nhints;
  1157. BigSize *= sizeof(MachO::twolevel_hint);
  1158. BigSize += Hints.offset;
  1159. if (BigSize > FileSize)
  1160. return malformedError("offset field plus nhints times sizeof(struct "
  1161. "twolevel_hint) field of LC_TWOLEVEL_HINTS command " +
  1162. Twine(LoadCommandIndex) + " extends past the end of "
  1163. "the file");
  1164. if (Error Err = checkOverlappingElement(Elements, Hints.offset, Hints.nhints *
  1165. sizeof(MachO::twolevel_hint),
  1166. "two level hints"))
  1167. return Err;
  1168. *LoadCmd = Load.Ptr;
  1169. return Error::success();
  1170. }
  1171. // Returns true if the libObject code does not support the load command and its
  1172. // contents. The cmd value it is treated as an unknown load command but with
  1173. // an error message that says the cmd value is obsolete.
  1174. static bool isLoadCommandObsolete(uint32_t cmd) {
  1175. if (cmd == MachO::LC_SYMSEG ||
  1176. cmd == MachO::LC_LOADFVMLIB ||
  1177. cmd == MachO::LC_IDFVMLIB ||
  1178. cmd == MachO::LC_IDENT ||
  1179. cmd == MachO::LC_FVMFILE ||
  1180. cmd == MachO::LC_PREPAGE ||
  1181. cmd == MachO::LC_PREBOUND_DYLIB ||
  1182. cmd == MachO::LC_TWOLEVEL_HINTS ||
  1183. cmd == MachO::LC_PREBIND_CKSUM)
  1184. return true;
  1185. return false;
  1186. }
  1187. Expected<std::unique_ptr<MachOObjectFile>>
  1188. MachOObjectFile::create(MemoryBufferRef Object, bool IsLittleEndian,
  1189. bool Is64Bits, uint32_t UniversalCputype,
  1190. uint32_t UniversalIndex) {
  1191. Error Err = Error::success();
  1192. std::unique_ptr<MachOObjectFile> Obj(
  1193. new MachOObjectFile(std::move(Object), IsLittleEndian,
  1194. Is64Bits, Err, UniversalCputype,
  1195. UniversalIndex));
  1196. if (Err)
  1197. return std::move(Err);
  1198. return std::move(Obj);
  1199. }
  1200. MachOObjectFile::MachOObjectFile(MemoryBufferRef Object, bool IsLittleEndian,
  1201. bool Is64bits, Error &Err,
  1202. uint32_t UniversalCputype,
  1203. uint32_t UniversalIndex)
  1204. : ObjectFile(getMachOType(IsLittleEndian, Is64bits), Object) {
  1205. ErrorAsOutParameter ErrAsOutParam(&Err);
  1206. uint64_t SizeOfHeaders;
  1207. uint32_t cputype;
  1208. if (is64Bit()) {
  1209. parseHeader(*this, Header64, Err);
  1210. SizeOfHeaders = sizeof(MachO::mach_header_64);
  1211. cputype = Header64.cputype;
  1212. } else {
  1213. parseHeader(*this, Header, Err);
  1214. SizeOfHeaders = sizeof(MachO::mach_header);
  1215. cputype = Header.cputype;
  1216. }
  1217. if (Err)
  1218. return;
  1219. SizeOfHeaders += getHeader().sizeofcmds;
  1220. if (getData().data() + SizeOfHeaders > getData().end()) {
  1221. Err = malformedError("load commands extend past the end of the file");
  1222. return;
  1223. }
  1224. if (UniversalCputype != 0 && cputype != UniversalCputype) {
  1225. Err = malformedError("universal header architecture: " +
  1226. Twine(UniversalIndex) + "'s cputype does not match "
  1227. "object file's mach header");
  1228. return;
  1229. }
  1230. std::list<MachOElement> Elements;
  1231. Elements.push_back({0, SizeOfHeaders, "Mach-O headers"});
  1232. uint32_t LoadCommandCount = getHeader().ncmds;
  1233. LoadCommandInfo Load;
  1234. if (LoadCommandCount != 0) {
  1235. if (auto LoadOrErr = getFirstLoadCommandInfo(*this))
  1236. Load = *LoadOrErr;
  1237. else {
  1238. Err = LoadOrErr.takeError();
  1239. return;
  1240. }
  1241. }
  1242. const char *DyldIdLoadCmd = nullptr;
  1243. const char *FuncStartsLoadCmd = nullptr;
  1244. const char *SplitInfoLoadCmd = nullptr;
  1245. const char *CodeSignDrsLoadCmd = nullptr;
  1246. const char *CodeSignLoadCmd = nullptr;
  1247. const char *VersLoadCmd = nullptr;
  1248. const char *SourceLoadCmd = nullptr;
  1249. const char *EntryPointLoadCmd = nullptr;
  1250. const char *EncryptLoadCmd = nullptr;
  1251. const char *RoutinesLoadCmd = nullptr;
  1252. const char *UnixThreadLoadCmd = nullptr;
  1253. const char *TwoLevelHintsLoadCmd = nullptr;
  1254. for (unsigned I = 0; I < LoadCommandCount; ++I) {
  1255. if (is64Bit()) {
  1256. if (Load.C.cmdsize % 8 != 0) {
  1257. // We have a hack here to allow 64-bit Mach-O core files to have
  1258. // LC_THREAD commands that are only a multiple of 4 and not 8 to be
  1259. // allowed since the macOS kernel produces them.
  1260. if (getHeader().filetype != MachO::MH_CORE ||
  1261. Load.C.cmd != MachO::LC_THREAD || Load.C.cmdsize % 4) {
  1262. Err = malformedError("load command " + Twine(I) + " cmdsize not a "
  1263. "multiple of 8");
  1264. return;
  1265. }
  1266. }
  1267. } else {
  1268. if (Load.C.cmdsize % 4 != 0) {
  1269. Err = malformedError("load command " + Twine(I) + " cmdsize not a "
  1270. "multiple of 4");
  1271. return;
  1272. }
  1273. }
  1274. LoadCommands.push_back(Load);
  1275. if (Load.C.cmd == MachO::LC_SYMTAB) {
  1276. if ((Err = checkSymtabCommand(*this, Load, I, &SymtabLoadCmd, Elements)))
  1277. return;
  1278. } else if (Load.C.cmd == MachO::LC_DYSYMTAB) {
  1279. if ((Err = checkDysymtabCommand(*this, Load, I, &DysymtabLoadCmd,
  1280. Elements)))
  1281. return;
  1282. } else if (Load.C.cmd == MachO::LC_DATA_IN_CODE) {
  1283. if ((Err = checkLinkeditDataCommand(*this, Load, I, &DataInCodeLoadCmd,
  1284. "LC_DATA_IN_CODE", Elements,
  1285. "data in code info")))
  1286. return;
  1287. } else if (Load.C.cmd == MachO::LC_LINKER_OPTIMIZATION_HINT) {
  1288. if ((Err = checkLinkeditDataCommand(*this, Load, I, &LinkOptHintsLoadCmd,
  1289. "LC_LINKER_OPTIMIZATION_HINT",
  1290. Elements, "linker optimization "
  1291. "hints")))
  1292. return;
  1293. } else if (Load.C.cmd == MachO::LC_FUNCTION_STARTS) {
  1294. if ((Err = checkLinkeditDataCommand(*this, Load, I, &FuncStartsLoadCmd,
  1295. "LC_FUNCTION_STARTS", Elements,
  1296. "function starts data")))
  1297. return;
  1298. } else if (Load.C.cmd == MachO::LC_SEGMENT_SPLIT_INFO) {
  1299. if ((Err = checkLinkeditDataCommand(*this, Load, I, &SplitInfoLoadCmd,
  1300. "LC_SEGMENT_SPLIT_INFO", Elements,
  1301. "split info data")))
  1302. return;
  1303. } else if (Load.C.cmd == MachO::LC_DYLIB_CODE_SIGN_DRS) {
  1304. if ((Err = checkLinkeditDataCommand(*this, Load, I, &CodeSignDrsLoadCmd,
  1305. "LC_DYLIB_CODE_SIGN_DRS", Elements,
  1306. "code signing RDs data")))
  1307. return;
  1308. } else if (Load.C.cmd == MachO::LC_CODE_SIGNATURE) {
  1309. if ((Err = checkLinkeditDataCommand(*this, Load, I, &CodeSignLoadCmd,
  1310. "LC_CODE_SIGNATURE", Elements,
  1311. "code signature data")))
  1312. return;
  1313. } else if (Load.C.cmd == MachO::LC_DYLD_INFO) {
  1314. if ((Err = checkDyldInfoCommand(*this, Load, I, &DyldInfoLoadCmd,
  1315. "LC_DYLD_INFO", Elements)))
  1316. return;
  1317. } else if (Load.C.cmd == MachO::LC_DYLD_INFO_ONLY) {
  1318. if ((Err = checkDyldInfoCommand(*this, Load, I, &DyldInfoLoadCmd,
  1319. "LC_DYLD_INFO_ONLY", Elements)))
  1320. return;
  1321. } else if (Load.C.cmd == MachO::LC_UUID) {
  1322. if (Load.C.cmdsize != sizeof(MachO::uuid_command)) {
  1323. Err = malformedError("LC_UUID command " + Twine(I) + " has incorrect "
  1324. "cmdsize");
  1325. return;
  1326. }
  1327. if (UuidLoadCmd) {
  1328. Err = malformedError("more than one LC_UUID command");
  1329. return;
  1330. }
  1331. UuidLoadCmd = Load.Ptr;
  1332. } else if (Load.C.cmd == MachO::LC_SEGMENT_64) {
  1333. if ((Err = parseSegmentLoadCommand<MachO::segment_command_64,
  1334. MachO::section_64>(
  1335. *this, Load, Sections, HasPageZeroSegment, I,
  1336. "LC_SEGMENT_64", SizeOfHeaders, Elements)))
  1337. return;
  1338. } else if (Load.C.cmd == MachO::LC_SEGMENT) {
  1339. if ((Err = parseSegmentLoadCommand<MachO::segment_command,
  1340. MachO::section>(
  1341. *this, Load, Sections, HasPageZeroSegment, I,
  1342. "LC_SEGMENT", SizeOfHeaders, Elements)))
  1343. return;
  1344. } else if (Load.C.cmd == MachO::LC_ID_DYLIB) {
  1345. if ((Err = checkDylibIdCommand(*this, Load, I, &DyldIdLoadCmd)))
  1346. return;
  1347. } else if (Load.C.cmd == MachO::LC_LOAD_DYLIB) {
  1348. if ((Err = checkDylibCommand(*this, Load, I, "LC_LOAD_DYLIB")))
  1349. return;
  1350. Libraries.push_back(Load.Ptr);
  1351. } else if (Load.C.cmd == MachO::LC_LOAD_WEAK_DYLIB) {
  1352. if ((Err = checkDylibCommand(*this, Load, I, "LC_LOAD_WEAK_DYLIB")))
  1353. return;
  1354. Libraries.push_back(Load.Ptr);
  1355. } else if (Load.C.cmd == MachO::LC_LAZY_LOAD_DYLIB) {
  1356. if ((Err = checkDylibCommand(*this, Load, I, "LC_LAZY_LOAD_DYLIB")))
  1357. return;
  1358. Libraries.push_back(Load.Ptr);
  1359. } else if (Load.C.cmd == MachO::LC_REEXPORT_DYLIB) {
  1360. if ((Err = checkDylibCommand(*this, Load, I, "LC_REEXPORT_DYLIB")))
  1361. return;
  1362. Libraries.push_back(Load.Ptr);
  1363. } else if (Load.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB) {
  1364. if ((Err = checkDylibCommand(*this, Load, I, "LC_LOAD_UPWARD_DYLIB")))
  1365. return;
  1366. Libraries.push_back(Load.Ptr);
  1367. } else if (Load.C.cmd == MachO::LC_ID_DYLINKER) {
  1368. if ((Err = checkDyldCommand(*this, Load, I, "LC_ID_DYLINKER")))
  1369. return;
  1370. } else if (Load.C.cmd == MachO::LC_LOAD_DYLINKER) {
  1371. if ((Err = checkDyldCommand(*this, Load, I, "LC_LOAD_DYLINKER")))
  1372. return;
  1373. } else if (Load.C.cmd == MachO::LC_DYLD_ENVIRONMENT) {
  1374. if ((Err = checkDyldCommand(*this, Load, I, "LC_DYLD_ENVIRONMENT")))
  1375. return;
  1376. } else if (Load.C.cmd == MachO::LC_VERSION_MIN_MACOSX) {
  1377. if ((Err = checkVersCommand(*this, Load, I, &VersLoadCmd,
  1378. "LC_VERSION_MIN_MACOSX")))
  1379. return;
  1380. } else if (Load.C.cmd == MachO::LC_VERSION_MIN_IPHONEOS) {
  1381. if ((Err = checkVersCommand(*this, Load, I, &VersLoadCmd,
  1382. "LC_VERSION_MIN_IPHONEOS")))
  1383. return;
  1384. } else if (Load.C.cmd == MachO::LC_VERSION_MIN_TVOS) {
  1385. if ((Err = checkVersCommand(*this, Load, I, &VersLoadCmd,
  1386. "LC_VERSION_MIN_TVOS")))
  1387. return;
  1388. } else if (Load.C.cmd == MachO::LC_VERSION_MIN_WATCHOS) {
  1389. if ((Err = checkVersCommand(*this, Load, I, &VersLoadCmd,
  1390. "LC_VERSION_MIN_WATCHOS")))
  1391. return;
  1392. } else if (Load.C.cmd == MachO::LC_NOTE) {
  1393. if ((Err = checkNoteCommand(*this, Load, I, Elements)))
  1394. return;
  1395. } else if (Load.C.cmd == MachO::LC_BUILD_VERSION) {
  1396. if ((Err = parseBuildVersionCommand(*this, Load, BuildTools, I)))
  1397. return;
  1398. } else if (Load.C.cmd == MachO::LC_RPATH) {
  1399. if ((Err = checkRpathCommand(*this, Load, I)))
  1400. return;
  1401. } else if (Load.C.cmd == MachO::LC_SOURCE_VERSION) {
  1402. if (Load.C.cmdsize != sizeof(MachO::source_version_command)) {
  1403. Err = malformedError("LC_SOURCE_VERSION command " + Twine(I) +
  1404. " has incorrect cmdsize");
  1405. return;
  1406. }
  1407. if (SourceLoadCmd) {
  1408. Err = malformedError("more than one LC_SOURCE_VERSION command");
  1409. return;
  1410. }
  1411. SourceLoadCmd = Load.Ptr;
  1412. } else if (Load.C.cmd == MachO::LC_MAIN) {
  1413. if (Load.C.cmdsize != sizeof(MachO::entry_point_command)) {
  1414. Err = malformedError("LC_MAIN command " + Twine(I) +
  1415. " has incorrect cmdsize");
  1416. return;
  1417. }
  1418. if (EntryPointLoadCmd) {
  1419. Err = malformedError("more than one LC_MAIN command");
  1420. return;
  1421. }
  1422. EntryPointLoadCmd = Load.Ptr;
  1423. } else if (Load.C.cmd == MachO::LC_ENCRYPTION_INFO) {
  1424. if (Load.C.cmdsize != sizeof(MachO::encryption_info_command)) {
  1425. Err = malformedError("LC_ENCRYPTION_INFO command " + Twine(I) +
  1426. " has incorrect cmdsize");
  1427. return;
  1428. }
  1429. MachO::encryption_info_command E =
  1430. getStruct<MachO::encryption_info_command>(*this, Load.Ptr);
  1431. if ((Err = checkEncryptCommand(*this, Load, I, E.cryptoff, E.cryptsize,
  1432. &EncryptLoadCmd, "LC_ENCRYPTION_INFO")))
  1433. return;
  1434. } else if (Load.C.cmd == MachO::LC_ENCRYPTION_INFO_64) {
  1435. if (Load.C.cmdsize != sizeof(MachO::encryption_info_command_64)) {
  1436. Err = malformedError("LC_ENCRYPTION_INFO_64 command " + Twine(I) +
  1437. " has incorrect cmdsize");
  1438. return;
  1439. }
  1440. MachO::encryption_info_command_64 E =
  1441. getStruct<MachO::encryption_info_command_64>(*this, Load.Ptr);
  1442. if ((Err = checkEncryptCommand(*this, Load, I, E.cryptoff, E.cryptsize,
  1443. &EncryptLoadCmd, "LC_ENCRYPTION_INFO_64")))
  1444. return;
  1445. } else if (Load.C.cmd == MachO::LC_LINKER_OPTION) {
  1446. if ((Err = checkLinkerOptCommand(*this, Load, I)))
  1447. return;
  1448. } else if (Load.C.cmd == MachO::LC_SUB_FRAMEWORK) {
  1449. if (Load.C.cmdsize < sizeof(MachO::sub_framework_command)) {
  1450. Err = malformedError("load command " + Twine(I) +
  1451. " LC_SUB_FRAMEWORK cmdsize too small");
  1452. return;
  1453. }
  1454. MachO::sub_framework_command S =
  1455. getStruct<MachO::sub_framework_command>(*this, Load.Ptr);
  1456. if ((Err = checkSubCommand(*this, Load, I, "LC_SUB_FRAMEWORK",
  1457. sizeof(MachO::sub_framework_command),
  1458. "sub_framework_command", S.umbrella,
  1459. "umbrella")))
  1460. return;
  1461. } else if (Load.C.cmd == MachO::LC_SUB_UMBRELLA) {
  1462. if (Load.C.cmdsize < sizeof(MachO::sub_umbrella_command)) {
  1463. Err = malformedError("load command " + Twine(I) +
  1464. " LC_SUB_UMBRELLA cmdsize too small");
  1465. return;
  1466. }
  1467. MachO::sub_umbrella_command S =
  1468. getStruct<MachO::sub_umbrella_command>(*this, Load.Ptr);
  1469. if ((Err = checkSubCommand(*this, Load, I, "LC_SUB_UMBRELLA",
  1470. sizeof(MachO::sub_umbrella_command),
  1471. "sub_umbrella_command", S.sub_umbrella,
  1472. "sub_umbrella")))
  1473. return;
  1474. } else if (Load.C.cmd == MachO::LC_SUB_LIBRARY) {
  1475. if (Load.C.cmdsize < sizeof(MachO::sub_library_command)) {
  1476. Err = malformedError("load command " + Twine(I) +
  1477. " LC_SUB_LIBRARY cmdsize too small");
  1478. return;
  1479. }
  1480. MachO::sub_library_command S =
  1481. getStruct<MachO::sub_library_command>(*this, Load.Ptr);
  1482. if ((Err = checkSubCommand(*this, Load, I, "LC_SUB_LIBRARY",
  1483. sizeof(MachO::sub_library_command),
  1484. "sub_library_command", S.sub_library,
  1485. "sub_library")))
  1486. return;
  1487. } else if (Load.C.cmd == MachO::LC_SUB_CLIENT) {
  1488. if (Load.C.cmdsize < sizeof(MachO::sub_client_command)) {
  1489. Err = malformedError("load command " + Twine(I) +
  1490. " LC_SUB_CLIENT cmdsize too small");
  1491. return;
  1492. }
  1493. MachO::sub_client_command S =
  1494. getStruct<MachO::sub_client_command>(*this, Load.Ptr);
  1495. if ((Err = checkSubCommand(*this, Load, I, "LC_SUB_CLIENT",
  1496. sizeof(MachO::sub_client_command),
  1497. "sub_client_command", S.client, "client")))
  1498. return;
  1499. } else if (Load.C.cmd == MachO::LC_ROUTINES) {
  1500. if (Load.C.cmdsize != sizeof(MachO::routines_command)) {
  1501. Err = malformedError("LC_ROUTINES command " + Twine(I) +
  1502. " has incorrect cmdsize");
  1503. return;
  1504. }
  1505. if (RoutinesLoadCmd) {
  1506. Err = malformedError("more than one LC_ROUTINES and or LC_ROUTINES_64 "
  1507. "command");
  1508. return;
  1509. }
  1510. RoutinesLoadCmd = Load.Ptr;
  1511. } else if (Load.C.cmd == MachO::LC_ROUTINES_64) {
  1512. if (Load.C.cmdsize != sizeof(MachO::routines_command_64)) {
  1513. Err = malformedError("LC_ROUTINES_64 command " + Twine(I) +
  1514. " has incorrect cmdsize");
  1515. return;
  1516. }
  1517. if (RoutinesLoadCmd) {
  1518. Err = malformedError("more than one LC_ROUTINES_64 and or LC_ROUTINES "
  1519. "command");
  1520. return;
  1521. }
  1522. RoutinesLoadCmd = Load.Ptr;
  1523. } else if (Load.C.cmd == MachO::LC_UNIXTHREAD) {
  1524. if ((Err = checkThreadCommand(*this, Load, I, "LC_UNIXTHREAD")))
  1525. return;
  1526. if (UnixThreadLoadCmd) {
  1527. Err = malformedError("more than one LC_UNIXTHREAD command");
  1528. return;
  1529. }
  1530. UnixThreadLoadCmd = Load.Ptr;
  1531. } else if (Load.C.cmd == MachO::LC_THREAD) {
  1532. if ((Err = checkThreadCommand(*this, Load, I, "LC_THREAD")))
  1533. return;
  1534. // Note: LC_TWOLEVEL_HINTS is really obsolete and is not supported.
  1535. } else if (Load.C.cmd == MachO::LC_TWOLEVEL_HINTS) {
  1536. if ((Err = checkTwoLevelHintsCommand(*this, Load, I,
  1537. &TwoLevelHintsLoadCmd, Elements)))
  1538. return;
  1539. } else if (Load.C.cmd == MachO::LC_IDENT) {
  1540. // Note: LC_IDENT is ignored.
  1541. continue;
  1542. } else if (isLoadCommandObsolete(Load.C.cmd)) {
  1543. Err = malformedError("load command " + Twine(I) + " for cmd value of: " +
  1544. Twine(Load.C.cmd) + " is obsolete and not "
  1545. "supported");
  1546. return;
  1547. }
  1548. // TODO: generate a error for unknown load commands by default. But still
  1549. // need work out an approach to allow or not allow unknown values like this
  1550. // as an option for some uses like lldb.
  1551. if (I < LoadCommandCount - 1) {
  1552. if (auto LoadOrErr = getNextLoadCommandInfo(*this, I, Load))
  1553. Load = *LoadOrErr;
  1554. else {
  1555. Err = LoadOrErr.takeError();
  1556. return;
  1557. }
  1558. }
  1559. }
  1560. if (!SymtabLoadCmd) {
  1561. if (DysymtabLoadCmd) {
  1562. Err = malformedError("contains LC_DYSYMTAB load command without a "
  1563. "LC_SYMTAB load command");
  1564. return;
  1565. }
  1566. } else if (DysymtabLoadCmd) {
  1567. MachO::symtab_command Symtab =
  1568. getStruct<MachO::symtab_command>(*this, SymtabLoadCmd);
  1569. MachO::dysymtab_command Dysymtab =
  1570. getStruct<MachO::dysymtab_command>(*this, DysymtabLoadCmd);
  1571. if (Dysymtab.nlocalsym != 0 && Dysymtab.ilocalsym > Symtab.nsyms) {
  1572. Err = malformedError("ilocalsym in LC_DYSYMTAB load command "
  1573. "extends past the end of the symbol table");
  1574. return;
  1575. }
  1576. uint64_t BigSize = Dysymtab.ilocalsym;
  1577. BigSize += Dysymtab.nlocalsym;
  1578. if (Dysymtab.nlocalsym != 0 && BigSize > Symtab.nsyms) {
  1579. Err = malformedError("ilocalsym plus nlocalsym in LC_DYSYMTAB load "
  1580. "command extends past the end of the symbol table");
  1581. return;
  1582. }
  1583. if (Dysymtab.nextdefsym != 0 && Dysymtab.iextdefsym > Symtab.nsyms) {
  1584. Err = malformedError("iextdefsym in LC_DYSYMTAB load command "
  1585. "extends past the end of the symbol table");
  1586. return;
  1587. }
  1588. BigSize = Dysymtab.iextdefsym;
  1589. BigSize += Dysymtab.nextdefsym;
  1590. if (Dysymtab.nextdefsym != 0 && BigSize > Symtab.nsyms) {
  1591. Err = malformedError("iextdefsym plus nextdefsym in LC_DYSYMTAB "
  1592. "load command extends past the end of the symbol "
  1593. "table");
  1594. return;
  1595. }
  1596. if (Dysymtab.nundefsym != 0 && Dysymtab.iundefsym > Symtab.nsyms) {
  1597. Err = malformedError("iundefsym in LC_DYSYMTAB load command "
  1598. "extends past the end of the symbol table");
  1599. return;
  1600. }
  1601. BigSize = Dysymtab.iundefsym;
  1602. BigSize += Dysymtab.nundefsym;
  1603. if (Dysymtab.nundefsym != 0 && BigSize > Symtab.nsyms) {
  1604. Err = malformedError("iundefsym plus nundefsym in LC_DYSYMTAB load "
  1605. " command extends past the end of the symbol table");
  1606. return;
  1607. }
  1608. }
  1609. if ((getHeader().filetype == MachO::MH_DYLIB ||
  1610. getHeader().filetype == MachO::MH_DYLIB_STUB) &&
  1611. DyldIdLoadCmd == nullptr) {
  1612. Err = malformedError("no LC_ID_DYLIB load command in dynamic library "
  1613. "filetype");
  1614. return;
  1615. }
  1616. assert(LoadCommands.size() == LoadCommandCount);
  1617. Err = Error::success();
  1618. }
  1619. Error MachOObjectFile::checkSymbolTable() const {
  1620. uint32_t Flags = 0;
  1621. if (is64Bit()) {
  1622. MachO::mach_header_64 H_64 = MachOObjectFile::getHeader64();
  1623. Flags = H_64.flags;
  1624. } else {
  1625. MachO::mach_header H = MachOObjectFile::getHeader();
  1626. Flags = H.flags;
  1627. }
  1628. uint8_t NType = 0;
  1629. uint8_t NSect = 0;
  1630. uint16_t NDesc = 0;
  1631. uint32_t NStrx = 0;
  1632. uint64_t NValue = 0;
  1633. uint32_t SymbolIndex = 0;
  1634. MachO::symtab_command S = getSymtabLoadCommand();
  1635. for (const SymbolRef &Symbol : symbols()) {
  1636. DataRefImpl SymDRI = Symbol.getRawDataRefImpl();
  1637. if (is64Bit()) {
  1638. MachO::nlist_64 STE_64 = getSymbol64TableEntry(SymDRI);
  1639. NType = STE_64.n_type;
  1640. NSect = STE_64.n_sect;
  1641. NDesc = STE_64.n_desc;
  1642. NStrx = STE_64.n_strx;
  1643. NValue = STE_64.n_value;
  1644. } else {
  1645. MachO::nlist STE = getSymbolTableEntry(SymDRI);
  1646. NType = STE.n_type;
  1647. NSect = STE.n_sect;
  1648. NDesc = STE.n_desc;
  1649. NStrx = STE.n_strx;
  1650. NValue = STE.n_value;
  1651. }
  1652. if ((NType & MachO::N_STAB) == 0) {
  1653. if ((NType & MachO::N_TYPE) == MachO::N_SECT) {
  1654. if (NSect == 0 || NSect > Sections.size())
  1655. return malformedError("bad section index: " + Twine((int)NSect) +
  1656. " for symbol at index " + Twine(SymbolIndex));
  1657. }
  1658. if ((NType & MachO::N_TYPE) == MachO::N_INDR) {
  1659. if (NValue >= S.strsize)
  1660. return malformedError("bad n_value: " + Twine((int)NValue) + " past "
  1661. "the end of string table, for N_INDR symbol at "
  1662. "index " + Twine(SymbolIndex));
  1663. }
  1664. if ((Flags & MachO::MH_TWOLEVEL) == MachO::MH_TWOLEVEL &&
  1665. (((NType & MachO::N_TYPE) == MachO::N_UNDF && NValue == 0) ||
  1666. (NType & MachO::N_TYPE) == MachO::N_PBUD)) {
  1667. uint32_t LibraryOrdinal = MachO::GET_LIBRARY_ORDINAL(NDesc);
  1668. if (LibraryOrdinal != 0 &&
  1669. LibraryOrdinal != MachO::EXECUTABLE_ORDINAL &&
  1670. LibraryOrdinal != MachO::DYNAMIC_LOOKUP_ORDINAL &&
  1671. LibraryOrdinal - 1 >= Libraries.size() ) {
  1672. return malformedError("bad library ordinal: " + Twine(LibraryOrdinal) +
  1673. " for symbol at index " + Twine(SymbolIndex));
  1674. }
  1675. }
  1676. }
  1677. if (NStrx >= S.strsize)
  1678. return malformedError("bad string table index: " + Twine((int)NStrx) +
  1679. " past the end of string table, for symbol at "
  1680. "index " + Twine(SymbolIndex));
  1681. SymbolIndex++;
  1682. }
  1683. return Error::success();
  1684. }
  1685. void MachOObjectFile::moveSymbolNext(DataRefImpl &Symb) const {
  1686. unsigned SymbolTableEntrySize = is64Bit() ?
  1687. sizeof(MachO::nlist_64) :
  1688. sizeof(MachO::nlist);
  1689. Symb.p += SymbolTableEntrySize;
  1690. }
  1691. Expected<StringRef> MachOObjectFile::getSymbolName(DataRefImpl Symb) const {
  1692. StringRef StringTable = getStringTableData();
  1693. MachO::nlist_base Entry = getSymbolTableEntryBase(*this, Symb);
  1694. if (Entry.n_strx == 0)
  1695. // A n_strx value of 0 indicates that no name is associated with a
  1696. // particular symbol table entry.
  1697. return StringRef();
  1698. const char *Start = &StringTable.data()[Entry.n_strx];
  1699. if (Start < getData().begin() || Start >= getData().end()) {
  1700. return malformedError("bad string index: " + Twine(Entry.n_strx) +
  1701. " for symbol at index " + Twine(getSymbolIndex(Symb)));
  1702. }
  1703. return StringRef(Start);
  1704. }
  1705. unsigned MachOObjectFile::getSectionType(SectionRef Sec) const {
  1706. DataRefImpl DRI = Sec.getRawDataRefImpl();
  1707. uint32_t Flags = getSectionFlags(*this, DRI);
  1708. return Flags & MachO::SECTION_TYPE;
  1709. }
  1710. uint64_t MachOObjectFile::getNValue(DataRefImpl Sym) const {
  1711. if (is64Bit()) {
  1712. MachO::nlist_64 Entry = getSymbol64TableEntry(Sym);
  1713. return Entry.n_value;
  1714. }
  1715. MachO::nlist Entry = getSymbolTableEntry(Sym);
  1716. return Entry.n_value;
  1717. }
  1718. // getIndirectName() returns the name of the alias'ed symbol who's string table
  1719. // index is in the n_value field.
  1720. std::error_code MachOObjectFile::getIndirectName(DataRefImpl Symb,
  1721. StringRef &Res) const {
  1722. StringRef StringTable = getStringTableData();
  1723. MachO::nlist_base Entry = getSymbolTableEntryBase(*this, Symb);
  1724. if ((Entry.n_type & MachO::N_TYPE) != MachO::N_INDR)
  1725. return object_error::parse_failed;
  1726. uint64_t NValue = getNValue(Symb);
  1727. if (NValue >= StringTable.size())
  1728. return object_error::parse_failed;
  1729. const char *Start = &StringTable.data()[NValue];
  1730. Res = StringRef(Start);
  1731. return std::error_code();
  1732. }
  1733. uint64_t MachOObjectFile::getSymbolValueImpl(DataRefImpl Sym) const {
  1734. return getNValue(Sym);
  1735. }
  1736. Expected<uint64_t> MachOObjectFile::getSymbolAddress(DataRefImpl Sym) const {
  1737. return getSymbolValue(Sym);
  1738. }
  1739. uint32_t MachOObjectFile::getSymbolAlignment(DataRefImpl DRI) const {
  1740. uint32_t Flags = cantFail(getSymbolFlags(DRI));
  1741. if (Flags & SymbolRef::SF_Common) {
  1742. MachO::nlist_base Entry = getSymbolTableEntryBase(*this, DRI);
  1743. return 1 << MachO::GET_COMM_ALIGN(Entry.n_desc);
  1744. }
  1745. return 0;
  1746. }
  1747. uint64_t MachOObjectFile::getCommonSymbolSizeImpl(DataRefImpl DRI) const {
  1748. return getNValue(DRI);
  1749. }
  1750. Expected<SymbolRef::Type>
  1751. MachOObjectFile::getSymbolType(DataRefImpl Symb) const {
  1752. MachO::nlist_base Entry = getSymbolTableEntryBase(*this, Symb);
  1753. uint8_t n_type = Entry.n_type;
  1754. // If this is a STAB debugging symbol, we can do nothing more.
  1755. if (n_type & MachO::N_STAB)
  1756. return SymbolRef::ST_Debug;
  1757. switch (n_type & MachO::N_TYPE) {
  1758. case MachO::N_UNDF :
  1759. return SymbolRef::ST_Unknown;
  1760. case MachO::N_SECT :
  1761. Expected<section_iterator> SecOrError = getSymbolSection(Symb);
  1762. if (!SecOrError)
  1763. return SecOrError.takeError();
  1764. section_iterator Sec = *SecOrError;
  1765. if (Sec->isData() || Sec->isBSS())
  1766. return SymbolRef::ST_Data;
  1767. return SymbolRef::ST_Function;
  1768. }
  1769. return SymbolRef::ST_Other;
  1770. }
  1771. Expected<uint32_t> MachOObjectFile::getSymbolFlags(DataRefImpl DRI) const {
  1772. MachO::nlist_base Entry = getSymbolTableEntryBase(*this, DRI);
  1773. uint8_t MachOType = Entry.n_type;
  1774. uint16_t MachOFlags = Entry.n_desc;
  1775. uint32_t Result = SymbolRef::SF_None;
  1776. if ((MachOType & MachO::N_TYPE) == MachO::N_INDR)
  1777. Result |= SymbolRef::SF_Indirect;
  1778. if (MachOType & MachO::N_STAB)
  1779. Result |= SymbolRef::SF_FormatSpecific;
  1780. if (MachOType & MachO::N_EXT) {
  1781. Result |= SymbolRef::SF_Global;
  1782. if ((MachOType & MachO::N_TYPE) == MachO::N_UNDF) {
  1783. if (getNValue(DRI))
  1784. Result |= SymbolRef::SF_Common;
  1785. else
  1786. Result |= SymbolRef::SF_Undefined;
  1787. }
  1788. if (!(MachOType & MachO::N_PEXT))
  1789. Result |= SymbolRef::SF_Exported;
  1790. }
  1791. if (MachOFlags & (MachO::N_WEAK_REF | MachO::N_WEAK_DEF))
  1792. Result |= SymbolRef::SF_Weak;
  1793. if (MachOFlags & (MachO::N_ARM_THUMB_DEF))
  1794. Result |= SymbolRef::SF_Thumb;
  1795. if ((MachOType & MachO::N_TYPE) == MachO::N_ABS)
  1796. Result |= SymbolRef::SF_Absolute;
  1797. return Result;
  1798. }
  1799. Expected<section_iterator>
  1800. MachOObjectFile::getSymbolSection(DataRefImpl Symb) const {
  1801. MachO::nlist_base Entry = getSymbolTableEntryBase(*this, Symb);
  1802. uint8_t index = Entry.n_sect;
  1803. if (index == 0)
  1804. return section_end();
  1805. DataRefImpl DRI;
  1806. DRI.d.a = index - 1;
  1807. if (DRI.d.a >= Sections.size()){
  1808. return malformedError("bad section index: " + Twine((int)index) +
  1809. " for symbol at index " + Twine(getSymbolIndex(Symb)));
  1810. }
  1811. return section_iterator(SectionRef(DRI, this));
  1812. }
  1813. unsigned MachOObjectFile::getSymbolSectionID(SymbolRef Sym) const {
  1814. MachO::nlist_base Entry =
  1815. getSymbolTableEntryBase(*this, Sym.getRawDataRefImpl());
  1816. return Entry.n_sect - 1;
  1817. }
  1818. void MachOObjectFile::moveSectionNext(DataRefImpl &Sec) const {
  1819. Sec.d.a++;
  1820. }
  1821. Expected<StringRef> MachOObjectFile::getSectionName(DataRefImpl Sec) const {
  1822. ArrayRef<char> Raw = getSectionRawName(Sec);
  1823. return parseSegmentOrSectionName(Raw.data());
  1824. }
  1825. uint64_t MachOObjectFile::getSectionAddress(DataRefImpl Sec) const {
  1826. if (is64Bit())
  1827. return getSection64(Sec).addr;
  1828. return getSection(Sec).addr;
  1829. }
  1830. uint64_t MachOObjectFile::getSectionIndex(DataRefImpl Sec) const {
  1831. return Sec.d.a;
  1832. }
  1833. uint64_t MachOObjectFile::getSectionSize(DataRefImpl Sec) const {
  1834. // In the case if a malformed Mach-O file where the section offset is past
  1835. // the end of the file or some part of the section size is past the end of
  1836. // the file return a size of zero or a size that covers the rest of the file
  1837. // but does not extend past the end of the file.
  1838. uint32_t SectOffset, SectType;
  1839. uint64_t SectSize;
  1840. if (is64Bit()) {
  1841. MachO::section_64 Sect = getSection64(Sec);
  1842. SectOffset = Sect.offset;
  1843. SectSize = Sect.size;
  1844. SectType = Sect.flags & MachO::SECTION_TYPE;
  1845. } else {
  1846. MachO::section Sect = getSection(Sec);
  1847. SectOffset = Sect.offset;
  1848. SectSize = Sect.size;
  1849. SectType = Sect.flags & MachO::SECTION_TYPE;
  1850. }
  1851. if (SectType == MachO::S_ZEROFILL || SectType == MachO::S_GB_ZEROFILL)
  1852. return SectSize;
  1853. uint64_t FileSize = getData().size();
  1854. if (SectOffset > FileSize)
  1855. return 0;
  1856. if (FileSize - SectOffset < SectSize)
  1857. return FileSize - SectOffset;
  1858. return SectSize;
  1859. }
  1860. ArrayRef<uint8_t> MachOObjectFile::getSectionContents(uint32_t Offset,
  1861. uint64_t Size) const {
  1862. return arrayRefFromStringRef(getData().substr(Offset, Size));
  1863. }
  1864. Expected<ArrayRef<uint8_t>>
  1865. MachOObjectFile::getSectionContents(DataRefImpl Sec) const {
  1866. uint32_t Offset;
  1867. uint64_t Size;
  1868. if (is64Bit()) {
  1869. MachO::section_64 Sect = getSection64(Sec);
  1870. Offset = Sect.offset;
  1871. Size = Sect.size;
  1872. } else {
  1873. MachO::section Sect = getSection(Sec);
  1874. Offset = Sect.offset;
  1875. Size = Sect.size;
  1876. }
  1877. return getSectionContents(Offset, Size);
  1878. }
  1879. uint64_t MachOObjectFile::getSectionAlignment(DataRefImpl Sec) const {
  1880. uint32_t Align;
  1881. if (is64Bit()) {
  1882. MachO::section_64 Sect = getSection64(Sec);
  1883. Align = Sect.align;
  1884. } else {
  1885. MachO::section Sect = getSection(Sec);
  1886. Align = Sect.align;
  1887. }
  1888. return uint64_t(1) << Align;
  1889. }
  1890. Expected<SectionRef> MachOObjectFile::getSection(unsigned SectionIndex) const {
  1891. if (SectionIndex < 1 || SectionIndex > Sections.size())
  1892. return malformedError("bad section index: " + Twine((int)SectionIndex));
  1893. DataRefImpl DRI;
  1894. DRI.d.a = SectionIndex - 1;
  1895. return SectionRef(DRI, this);
  1896. }
  1897. Expected<SectionRef> MachOObjectFile::getSection(StringRef SectionName) const {
  1898. for (const SectionRef &Section : sections()) {
  1899. auto NameOrErr = Section.getName();
  1900. if (!NameOrErr)
  1901. return NameOrErr.takeError();
  1902. if (*NameOrErr == SectionName)
  1903. return Section;
  1904. }
  1905. return errorCodeToError(object_error::parse_failed);
  1906. }
  1907. bool MachOObjectFile::isSectionCompressed(DataRefImpl Sec) const {
  1908. return false;
  1909. }
  1910. bool MachOObjectFile::isSectionText(DataRefImpl Sec) const {
  1911. uint32_t Flags = getSectionFlags(*this, Sec);
  1912. return Flags & MachO::S_ATTR_PURE_INSTRUCTIONS;
  1913. }
  1914. bool MachOObjectFile::isSectionData(DataRefImpl Sec) const {
  1915. uint32_t Flags = getSectionFlags(*this, Sec);
  1916. unsigned SectionType = Flags & MachO::SECTION_TYPE;
  1917. return !(Flags & MachO::S_ATTR_PURE_INSTRUCTIONS) &&
  1918. !(SectionType == MachO::S_ZEROFILL ||
  1919. SectionType == MachO::S_GB_ZEROFILL);
  1920. }
  1921. bool MachOObjectFile::isSectionBSS(DataRefImpl Sec) const {
  1922. uint32_t Flags = getSectionFlags(*this, Sec);
  1923. unsigned SectionType = Flags & MachO::SECTION_TYPE;
  1924. return !(Flags & MachO::S_ATTR_PURE_INSTRUCTIONS) &&
  1925. (SectionType == MachO::S_ZEROFILL ||
  1926. SectionType == MachO::S_GB_ZEROFILL);
  1927. }
  1928. bool MachOObjectFile::isDebugSection(StringRef SectionName) const {
  1929. return SectionName.startswith("__debug") ||
  1930. SectionName.startswith("__zdebug") ||
  1931. SectionName.startswith("__apple") || SectionName == "__gdb_index" ||
  1932. SectionName == "__swift_ast";
  1933. }
  1934. unsigned MachOObjectFile::getSectionID(SectionRef Sec) const {
  1935. return Sec.getRawDataRefImpl().d.a;
  1936. }
  1937. bool MachOObjectFile::isSectionVirtual(DataRefImpl Sec) const {
  1938. uint32_t Flags = getSectionFlags(*this, Sec);
  1939. unsigned SectionType = Flags & MachO::SECTION_TYPE;
  1940. return SectionType == MachO::S_ZEROFILL ||
  1941. SectionType == MachO::S_GB_ZEROFILL;
  1942. }
  1943. bool MachOObjectFile::isSectionBitcode(DataRefImpl Sec) const {
  1944. StringRef SegmentName = getSectionFinalSegmentName(Sec);
  1945. if (Expected<StringRef> NameOrErr = getSectionName(Sec))
  1946. return (SegmentName == "__LLVM" && *NameOrErr == "__bitcode");
  1947. return false;
  1948. }
  1949. bool MachOObjectFile::isSectionStripped(DataRefImpl Sec) const {
  1950. if (is64Bit())
  1951. return getSection64(Sec).offset == 0;
  1952. return getSection(Sec).offset == 0;
  1953. }
  1954. relocation_iterator MachOObjectFile::section_rel_begin(DataRefImpl Sec) const {
  1955. DataRefImpl Ret;
  1956. Ret.d.a = Sec.d.a;
  1957. Ret.d.b = 0;
  1958. return relocation_iterator(RelocationRef(Ret, this));
  1959. }
  1960. relocation_iterator
  1961. MachOObjectFile::section_rel_end(DataRefImpl Sec) const {
  1962. uint32_t Num;
  1963. if (is64Bit()) {
  1964. MachO::section_64 Sect = getSection64(Sec);
  1965. Num = Sect.nreloc;
  1966. } else {
  1967. MachO::section Sect = getSection(Sec);
  1968. Num = Sect.nreloc;
  1969. }
  1970. DataRefImpl Ret;
  1971. Ret.d.a = Sec.d.a;
  1972. Ret.d.b = Num;
  1973. return relocation_iterator(RelocationRef(Ret, this));
  1974. }
  1975. relocation_iterator MachOObjectFile::extrel_begin() const {
  1976. DataRefImpl Ret;
  1977. // for DYSYMTAB symbols, Ret.d.a == 0 for external relocations
  1978. Ret.d.a = 0; // Would normally be a section index.
  1979. Ret.d.b = 0; // Index into the external relocations
  1980. return relocation_iterator(RelocationRef(Ret, this));
  1981. }
  1982. relocation_iterator MachOObjectFile::extrel_end() const {
  1983. MachO::dysymtab_command DysymtabLoadCmd = getDysymtabLoadCommand();
  1984. DataRefImpl Ret;
  1985. // for DYSYMTAB symbols, Ret.d.a == 0 for external relocations
  1986. Ret.d.a = 0; // Would normally be a section index.
  1987. Ret.d.b = DysymtabLoadCmd.nextrel; // Index into the external relocations
  1988. return relocation_iterator(RelocationRef(Ret, this));
  1989. }
  1990. relocation_iterator MachOObjectFile::locrel_begin() const {
  1991. DataRefImpl Ret;
  1992. // for DYSYMTAB symbols, Ret.d.a == 1 for local relocations
  1993. Ret.d.a = 1; // Would normally be a section index.
  1994. Ret.d.b = 0; // Index into the local relocations
  1995. return relocation_iterator(RelocationRef(Ret, this));
  1996. }
  1997. relocation_iterator MachOObjectFile::locrel_end() const {
  1998. MachO::dysymtab_command DysymtabLoadCmd = getDysymtabLoadCommand();
  1999. DataRefImpl Ret;
  2000. // for DYSYMTAB symbols, Ret.d.a == 1 for local relocations
  2001. Ret.d.a = 1; // Would normally be a section index.
  2002. Ret.d.b = DysymtabLoadCmd.nlocrel; // Index into the local relocations
  2003. return relocation_iterator(RelocationRef(Ret, this));
  2004. }
  2005. void MachOObjectFile::moveRelocationNext(DataRefImpl &Rel) const {
  2006. ++Rel.d.b;
  2007. }
  2008. uint64_t MachOObjectFile::getRelocationOffset(DataRefImpl Rel) const {
  2009. assert((getHeader().filetype == MachO::MH_OBJECT ||
  2010. getHeader().filetype == MachO::MH_KEXT_BUNDLE) &&
  2011. "Only implemented for MH_OBJECT && MH_KEXT_BUNDLE");
  2012. MachO::any_relocation_info RE = getRelocation(Rel);
  2013. return getAnyRelocationAddress(RE);
  2014. }
  2015. symbol_iterator
  2016. MachOObjectFile::getRelocationSymbol(DataRefImpl Rel) const {
  2017. MachO::any_relocation_info RE = getRelocation(Rel);
  2018. if (isRelocationScattered(RE))
  2019. return symbol_end();
  2020. uint32_t SymbolIdx = getPlainRelocationSymbolNum(RE);
  2021. bool isExtern = getPlainRelocationExternal(RE);
  2022. if (!isExtern)
  2023. return symbol_end();
  2024. MachO::symtab_command S = getSymtabLoadCommand();
  2025. unsigned SymbolTableEntrySize = is64Bit() ?
  2026. sizeof(MachO::nlist_64) :
  2027. sizeof(MachO::nlist);
  2028. uint64_t Offset = S.symoff + SymbolIdx * SymbolTableEntrySize;
  2029. DataRefImpl Sym;
  2030. Sym.p = reinterpret_cast<uintptr_t>(getPtr(*this, Offset));
  2031. return symbol_iterator(SymbolRef(Sym, this));
  2032. }
  2033. section_iterator
  2034. MachOObjectFile::getRelocationSection(DataRefImpl Rel) const {
  2035. return section_iterator(getAnyRelocationSection(getRelocation(Rel)));
  2036. }
  2037. uint64_t MachOObjectFile::getRelocationType(DataRefImpl Rel) const {
  2038. MachO::any_relocation_info RE = getRelocation(Rel);
  2039. return getAnyRelocationType(RE);
  2040. }
  2041. void MachOObjectFile::getRelocationTypeName(
  2042. DataRefImpl Rel, SmallVectorImpl<char> &Result) const {
  2043. StringRef res;
  2044. uint64_t RType = getRelocationType(Rel);
  2045. unsigned Arch = this->getArch();
  2046. switch (Arch) {
  2047. case Triple::x86: {
  2048. static const char *const Table[] = {
  2049. "GENERIC_RELOC_VANILLA",
  2050. "GENERIC_RELOC_PAIR",
  2051. "GENERIC_RELOC_SECTDIFF",
  2052. "GENERIC_RELOC_PB_LA_PTR",
  2053. "GENERIC_RELOC_LOCAL_SECTDIFF",
  2054. "GENERIC_RELOC_TLV" };
  2055. if (RType > 5)
  2056. res = "Unknown";
  2057. else
  2058. res = Table[RType];
  2059. break;
  2060. }
  2061. case Triple::x86_64: {
  2062. static const char *const Table[] = {
  2063. "X86_64_RELOC_UNSIGNED",
  2064. "X86_64_RELOC_SIGNED",
  2065. "X86_64_RELOC_BRANCH",
  2066. "X86_64_RELOC_GOT_LOAD",
  2067. "X86_64_RELOC_GOT",
  2068. "X86_64_RELOC_SUBTRACTOR",
  2069. "X86_64_RELOC_SIGNED_1",
  2070. "X86_64_RELOC_SIGNED_2",
  2071. "X86_64_RELOC_SIGNED_4",
  2072. "X86_64_RELOC_TLV" };
  2073. if (RType > 9)
  2074. res = "Unknown";
  2075. else
  2076. res = Table[RType];
  2077. break;
  2078. }
  2079. case Triple::arm: {
  2080. static const char *const Table[] = {
  2081. "ARM_RELOC_VANILLA",
  2082. "ARM_RELOC_PAIR",
  2083. "ARM_RELOC_SECTDIFF",
  2084. "ARM_RELOC_LOCAL_SECTDIFF",
  2085. "ARM_RELOC_PB_LA_PTR",
  2086. "ARM_RELOC_BR24",
  2087. "ARM_THUMB_RELOC_BR22",
  2088. "ARM_THUMB_32BIT_BRANCH",
  2089. "ARM_RELOC_HALF",
  2090. "ARM_RELOC_HALF_SECTDIFF" };
  2091. if (RType > 9)
  2092. res = "Unknown";
  2093. else
  2094. res = Table[RType];
  2095. break;
  2096. }
  2097. case Triple::aarch64:
  2098. case Triple::aarch64_32: {
  2099. static const char *const Table[] = {
  2100. "ARM64_RELOC_UNSIGNED", "ARM64_RELOC_SUBTRACTOR",
  2101. "ARM64_RELOC_BRANCH26", "ARM64_RELOC_PAGE21",
  2102. "ARM64_RELOC_PAGEOFF12", "ARM64_RELOC_GOT_LOAD_PAGE21",
  2103. "ARM64_RELOC_GOT_LOAD_PAGEOFF12", "ARM64_RELOC_POINTER_TO_GOT",
  2104. "ARM64_RELOC_TLVP_LOAD_PAGE21", "ARM64_RELOC_TLVP_LOAD_PAGEOFF12",
  2105. "ARM64_RELOC_ADDEND"
  2106. };
  2107. if (RType >= array_lengthof(Table))
  2108. res = "Unknown";
  2109. else
  2110. res = Table[RType];
  2111. break;
  2112. }
  2113. case Triple::ppc: {
  2114. static const char *const Table[] = {
  2115. "PPC_RELOC_VANILLA",
  2116. "PPC_RELOC_PAIR",
  2117. "PPC_RELOC_BR14",
  2118. "PPC_RELOC_BR24",
  2119. "PPC_RELOC_HI16",
  2120. "PPC_RELOC_LO16",
  2121. "PPC_RELOC_HA16",
  2122. "PPC_RELOC_LO14",
  2123. "PPC_RELOC_SECTDIFF",
  2124. "PPC_RELOC_PB_LA_PTR",
  2125. "PPC_RELOC_HI16_SECTDIFF",
  2126. "PPC_RELOC_LO16_SECTDIFF",
  2127. "PPC_RELOC_HA16_SECTDIFF",
  2128. "PPC_RELOC_JBSR",
  2129. "PPC_RELOC_LO14_SECTDIFF",
  2130. "PPC_RELOC_LOCAL_SECTDIFF" };
  2131. if (RType > 15)
  2132. res = "Unknown";
  2133. else
  2134. res = Table[RType];
  2135. break;
  2136. }
  2137. case Triple::UnknownArch:
  2138. res = "Unknown";
  2139. break;
  2140. }
  2141. Result.append(res.begin(), res.end());
  2142. }
  2143. uint8_t MachOObjectFile::getRelocationLength(DataRefImpl Rel) const {
  2144. MachO::any_relocation_info RE = getRelocation(Rel);
  2145. return getAnyRelocationLength(RE);
  2146. }
  2147. //
  2148. // guessLibraryShortName() is passed a name of a dynamic library and returns a
  2149. // guess on what the short name is. Then name is returned as a substring of the
  2150. // StringRef Name passed in. The name of the dynamic library is recognized as
  2151. // a framework if it has one of the two following forms:
  2152. // Foo.framework/Versions/A/Foo
  2153. // Foo.framework/Foo
  2154. // Where A and Foo can be any string. And may contain a trailing suffix
  2155. // starting with an underbar. If the Name is recognized as a framework then
  2156. // isFramework is set to true else it is set to false. If the Name has a
  2157. // suffix then Suffix is set to the substring in Name that contains the suffix
  2158. // else it is set to a NULL StringRef.
  2159. //
  2160. // The Name of the dynamic library is recognized as a library name if it has
  2161. // one of the two following forms:
  2162. // libFoo.A.dylib
  2163. // libFoo.dylib
  2164. //
  2165. // The library may have a suffix trailing the name Foo of the form:
  2166. // libFoo_profile.A.dylib
  2167. // libFoo_profile.dylib
  2168. // These dyld image suffixes are separated from the short name by a '_'
  2169. // character. Because the '_' character is commonly used to separate words in
  2170. // filenames guessLibraryShortName() cannot reliably separate a dylib's short
  2171. // name from an arbitrary image suffix; imagine if both the short name and the
  2172. // suffix contains an '_' character! To better deal with this ambiguity,
  2173. // guessLibraryShortName() will recognize only "_debug" and "_profile" as valid
  2174. // Suffix values. Calling code needs to be tolerant of guessLibraryShortName()
  2175. // guessing incorrectly.
  2176. //
  2177. // The Name of the dynamic library is also recognized as a library name if it
  2178. // has the following form:
  2179. // Foo.qtx
  2180. //
  2181. // If the Name of the dynamic library is none of the forms above then a NULL
  2182. // StringRef is returned.
  2183. StringRef MachOObjectFile::guessLibraryShortName(StringRef Name,
  2184. bool &isFramework,
  2185. StringRef &Suffix) {
  2186. StringRef Foo, F, DotFramework, V, Dylib, Lib, Dot, Qtx;
  2187. size_t a, b, c, d, Idx;
  2188. isFramework = false;
  2189. Suffix = StringRef();
  2190. // Pull off the last component and make Foo point to it
  2191. a = Name.rfind('/');
  2192. if (a == Name.npos || a == 0)
  2193. goto guess_library;
  2194. Foo = Name.slice(a+1, Name.npos);
  2195. // Look for a suffix starting with a '_'
  2196. Idx = Foo.rfind('_');
  2197. if (Idx != Foo.npos && Foo.size() >= 2) {
  2198. Suffix = Foo.slice(Idx, Foo.npos);
  2199. if (Suffix != "_debug" && Suffix != "_profile")
  2200. Suffix = StringRef();
  2201. else
  2202. Foo = Foo.slice(0, Idx);
  2203. }
  2204. // First look for the form Foo.framework/Foo
  2205. b = Name.rfind('/', a);
  2206. if (b == Name.npos)
  2207. Idx = 0;
  2208. else
  2209. Idx = b+1;
  2210. F = Name.slice(Idx, Idx + Foo.size());
  2211. DotFramework = Name.slice(Idx + Foo.size(),
  2212. Idx + Foo.size() + sizeof(".framework/")-1);
  2213. if (F == Foo && DotFramework == ".framework/") {
  2214. isFramework = true;
  2215. return Foo;
  2216. }
  2217. // Next look for the form Foo.framework/Versions/A/Foo
  2218. if (b == Name.npos)
  2219. goto guess_library;
  2220. c = Name.rfind('/', b);
  2221. if (c == Name.npos || c == 0)
  2222. goto guess_library;
  2223. V = Name.slice(c+1, Name.npos);
  2224. if (!V.startswith("Versions/"))
  2225. goto guess_library;
  2226. d = Name.rfind('/', c);
  2227. if (d == Name.npos)
  2228. Idx = 0;
  2229. else
  2230. Idx = d+1;
  2231. F = Name.slice(Idx, Idx + Foo.size());
  2232. DotFramework = Name.slice(Idx + Foo.size(),
  2233. Idx + Foo.size() + sizeof(".framework/")-1);
  2234. if (F == Foo && DotFramework == ".framework/") {
  2235. isFramework = true;
  2236. return Foo;
  2237. }
  2238. guess_library:
  2239. // pull off the suffix after the "." and make a point to it
  2240. a = Name.rfind('.');
  2241. if (a == Name.npos || a == 0)
  2242. return StringRef();
  2243. Dylib = Name.slice(a, Name.npos);
  2244. if (Dylib != ".dylib")
  2245. goto guess_qtx;
  2246. // First pull off the version letter for the form Foo.A.dylib if any.
  2247. if (a >= 3) {
  2248. Dot = Name.slice(a-2, a-1);
  2249. if (Dot == ".")
  2250. a = a - 2;
  2251. }
  2252. b = Name.rfind('/', a);
  2253. if (b == Name.npos)
  2254. b = 0;
  2255. else
  2256. b = b+1;
  2257. // ignore any suffix after an underbar like Foo_profile.A.dylib
  2258. Idx = Name.rfind('_');
  2259. if (Idx != Name.npos && Idx != b) {
  2260. Lib = Name.slice(b, Idx);
  2261. Suffix = Name.slice(Idx, a);
  2262. if (Suffix != "_debug" && Suffix != "_profile") {
  2263. Suffix = StringRef();
  2264. Lib = Name.slice(b, a);
  2265. }
  2266. }
  2267. else
  2268. Lib = Name.slice(b, a);
  2269. // There are incorrect library names of the form:
  2270. // libATS.A_profile.dylib so check for these.
  2271. if (Lib.size() >= 3) {
  2272. Dot = Lib.slice(Lib.size()-2, Lib.size()-1);
  2273. if (Dot == ".")
  2274. Lib = Lib.slice(0, Lib.size()-2);
  2275. }
  2276. return Lib;
  2277. guess_qtx:
  2278. Qtx = Name.slice(a, Name.npos);
  2279. if (Qtx != ".qtx")
  2280. return StringRef();
  2281. b = Name.rfind('/', a);
  2282. if (b == Name.npos)
  2283. Lib = Name.slice(0, a);
  2284. else
  2285. Lib = Name.slice(b+1, a);
  2286. // There are library names of the form: QT.A.qtx so check for these.
  2287. if (Lib.size() >= 3) {
  2288. Dot = Lib.slice(Lib.size()-2, Lib.size()-1);
  2289. if (Dot == ".")
  2290. Lib = Lib.slice(0, Lib.size()-2);
  2291. }
  2292. return Lib;
  2293. }
  2294. // getLibraryShortNameByIndex() is used to get the short name of the library
  2295. // for an undefined symbol in a linked Mach-O binary that was linked with the
  2296. // normal two-level namespace default (that is MH_TWOLEVEL in the header).
  2297. // It is passed the index (0 - based) of the library as translated from
  2298. // GET_LIBRARY_ORDINAL (1 - based).
  2299. std::error_code MachOObjectFile::getLibraryShortNameByIndex(unsigned Index,
  2300. StringRef &Res) const {
  2301. if (Index >= Libraries.size())
  2302. return object_error::parse_failed;
  2303. // If the cache of LibrariesShortNames is not built up do that first for
  2304. // all the Libraries.
  2305. if (LibrariesShortNames.size() == 0) {
  2306. for (unsigned i = 0; i < Libraries.size(); i++) {
  2307. auto CommandOrErr =
  2308. getStructOrErr<MachO::dylib_command>(*this, Libraries[i]);
  2309. if (!CommandOrErr)
  2310. return object_error::parse_failed;
  2311. MachO::dylib_command D = CommandOrErr.get();
  2312. if (D.dylib.name >= D.cmdsize)
  2313. return object_error::parse_failed;
  2314. const char *P = (const char *)(Libraries[i]) + D.dylib.name;
  2315. StringRef Name = StringRef(P);
  2316. if (D.dylib.name+Name.size() >= D.cmdsize)
  2317. return object_error::parse_failed;
  2318. StringRef Suffix;
  2319. bool isFramework;
  2320. StringRef shortName = guessLibraryShortName(Name, isFramework, Suffix);
  2321. if (shortName.empty())
  2322. LibrariesShortNames.push_back(Name);
  2323. else
  2324. LibrariesShortNames.push_back(shortName);
  2325. }
  2326. }
  2327. Res = LibrariesShortNames[Index];
  2328. return std::error_code();
  2329. }
  2330. uint32_t MachOObjectFile::getLibraryCount() const {
  2331. return Libraries.size();
  2332. }
  2333. section_iterator
  2334. MachOObjectFile::getRelocationRelocatedSection(relocation_iterator Rel) const {
  2335. DataRefImpl Sec;
  2336. Sec.d.a = Rel->getRawDataRefImpl().d.a;
  2337. return section_iterator(SectionRef(Sec, this));
  2338. }
  2339. basic_symbol_iterator MachOObjectFile::symbol_begin() const {
  2340. DataRefImpl DRI;
  2341. MachO::symtab_command Symtab = getSymtabLoadCommand();
  2342. if (!SymtabLoadCmd || Symtab.nsyms == 0)
  2343. return basic_symbol_iterator(SymbolRef(DRI, this));
  2344. return getSymbolByIndex(0);
  2345. }
  2346. basic_symbol_iterator MachOObjectFile::symbol_end() const {
  2347. DataRefImpl DRI;
  2348. MachO::symtab_command Symtab = getSymtabLoadCommand();
  2349. if (!SymtabLoadCmd || Symtab.nsyms == 0)
  2350. return basic_symbol_iterator(SymbolRef(DRI, this));
  2351. unsigned SymbolTableEntrySize = is64Bit() ?
  2352. sizeof(MachO::nlist_64) :
  2353. sizeof(MachO::nlist);
  2354. unsigned Offset = Symtab.symoff +
  2355. Symtab.nsyms * SymbolTableEntrySize;
  2356. DRI.p = reinterpret_cast<uintptr_t>(getPtr(*this, Offset));
  2357. return basic_symbol_iterator(SymbolRef(DRI, this));
  2358. }
  2359. symbol_iterator MachOObjectFile::getSymbolByIndex(unsigned Index) const {
  2360. MachO::symtab_command Symtab = getSymtabLoadCommand();
  2361. if (!SymtabLoadCmd || Index >= Symtab.nsyms)
  2362. report_fatal_error("Requested symbol index is out of range.");
  2363. unsigned SymbolTableEntrySize =
  2364. is64Bit() ? sizeof(MachO::nlist_64) : sizeof(MachO::nlist);
  2365. DataRefImpl DRI;
  2366. DRI.p = reinterpret_cast<uintptr_t>(getPtr(*this, Symtab.symoff));
  2367. DRI.p += Index * SymbolTableEntrySize;
  2368. return basic_symbol_iterator(SymbolRef(DRI, this));
  2369. }
  2370. uint64_t MachOObjectFile::getSymbolIndex(DataRefImpl Symb) const {
  2371. MachO::symtab_command Symtab = getSymtabLoadCommand();
  2372. if (!SymtabLoadCmd)
  2373. report_fatal_error("getSymbolIndex() called with no symbol table symbol");
  2374. unsigned SymbolTableEntrySize =
  2375. is64Bit() ? sizeof(MachO::nlist_64) : sizeof(MachO::nlist);
  2376. DataRefImpl DRIstart;
  2377. DRIstart.p = reinterpret_cast<uintptr_t>(getPtr(*this, Symtab.symoff));
  2378. uint64_t Index = (Symb.p - DRIstart.p) / SymbolTableEntrySize;
  2379. return Index;
  2380. }
  2381. section_iterator MachOObjectFile::section_begin() const {
  2382. DataRefImpl DRI;
  2383. return section_iterator(SectionRef(DRI, this));
  2384. }
  2385. section_iterator MachOObjectFile::section_end() const {
  2386. DataRefImpl DRI;
  2387. DRI.d.a = Sections.size();
  2388. return section_iterator(SectionRef(DRI, this));
  2389. }
  2390. uint8_t MachOObjectFile::getBytesInAddress() const {
  2391. return is64Bit() ? 8 : 4;
  2392. }
  2393. StringRef MachOObjectFile::getFileFormatName() const {
  2394. unsigned CPUType = getCPUType(*this);
  2395. if (!is64Bit()) {
  2396. switch (CPUType) {
  2397. case MachO::CPU_TYPE_I386:
  2398. return "Mach-O 32-bit i386";
  2399. case MachO::CPU_TYPE_ARM:
  2400. return "Mach-O arm";
  2401. case MachO::CPU_TYPE_ARM64_32:
  2402. return "Mach-O arm64 (ILP32)";
  2403. case MachO::CPU_TYPE_POWERPC:
  2404. return "Mach-O 32-bit ppc";
  2405. default:
  2406. return "Mach-O 32-bit unknown";
  2407. }
  2408. }
  2409. switch (CPUType) {
  2410. case MachO::CPU_TYPE_X86_64:
  2411. return "Mach-O 64-bit x86-64";
  2412. case MachO::CPU_TYPE_ARM64:
  2413. return "Mach-O arm64";
  2414. case MachO::CPU_TYPE_POWERPC64:
  2415. return "Mach-O 64-bit ppc64";
  2416. default:
  2417. return "Mach-O 64-bit unknown";
  2418. }
  2419. }
  2420. Triple::ArchType MachOObjectFile::getArch(uint32_t CPUType, uint32_t CPUSubType) {
  2421. switch (CPUType) {
  2422. case MachO::CPU_TYPE_I386:
  2423. return Triple::x86;
  2424. case MachO::CPU_TYPE_X86_64:
  2425. return Triple::x86_64;
  2426. case MachO::CPU_TYPE_ARM:
  2427. return Triple::arm;
  2428. case MachO::CPU_TYPE_ARM64:
  2429. return Triple::aarch64;
  2430. case MachO::CPU_TYPE_ARM64_32:
  2431. return Triple::aarch64_32;
  2432. case MachO::CPU_TYPE_POWERPC:
  2433. return Triple::ppc;
  2434. case MachO::CPU_TYPE_POWERPC64:
  2435. return Triple::ppc64;
  2436. default:
  2437. return Triple::UnknownArch;
  2438. }
  2439. }
  2440. Triple MachOObjectFile::getArchTriple(uint32_t CPUType, uint32_t CPUSubType,
  2441. const char **McpuDefault,
  2442. const char **ArchFlag) {
  2443. if (McpuDefault)
  2444. *McpuDefault = nullptr;
  2445. if (ArchFlag)
  2446. *ArchFlag = nullptr;
  2447. switch (CPUType) {
  2448. case MachO::CPU_TYPE_I386:
  2449. switch (CPUSubType & ~MachO::CPU_SUBTYPE_MASK) {
  2450. case MachO::CPU_SUBTYPE_I386_ALL:
  2451. if (ArchFlag)
  2452. *ArchFlag = "i386";
  2453. return Triple("i386-apple-darwin");
  2454. default:
  2455. return Triple();
  2456. }
  2457. case MachO::CPU_TYPE_X86_64:
  2458. switch (CPUSubType & ~MachO::CPU_SUBTYPE_MASK) {
  2459. case MachO::CPU_SUBTYPE_X86_64_ALL:
  2460. if (ArchFlag)
  2461. *ArchFlag = "x86_64";
  2462. return Triple("x86_64-apple-darwin");
  2463. case MachO::CPU_SUBTYPE_X86_64_H:
  2464. if (ArchFlag)
  2465. *ArchFlag = "x86_64h";
  2466. return Triple("x86_64h-apple-darwin");
  2467. default:
  2468. return Triple();
  2469. }
  2470. case MachO::CPU_TYPE_ARM:
  2471. switch (CPUSubType & ~MachO::CPU_SUBTYPE_MASK) {
  2472. case MachO::CPU_SUBTYPE_ARM_V4T:
  2473. if (ArchFlag)
  2474. *ArchFlag = "armv4t";
  2475. return Triple("armv4t-apple-darwin");
  2476. case MachO::CPU_SUBTYPE_ARM_V5TEJ:
  2477. if (ArchFlag)
  2478. *ArchFlag = "armv5e";
  2479. return Triple("armv5e-apple-darwin");
  2480. case MachO::CPU_SUBTYPE_ARM_XSCALE:
  2481. if (ArchFlag)
  2482. *ArchFlag = "xscale";
  2483. return Triple("xscale-apple-darwin");
  2484. case MachO::CPU_SUBTYPE_ARM_V6:
  2485. if (ArchFlag)
  2486. *ArchFlag = "armv6";
  2487. return Triple("armv6-apple-darwin");
  2488. case MachO::CPU_SUBTYPE_ARM_V6M:
  2489. if (McpuDefault)
  2490. *McpuDefault = "cortex-m0";
  2491. if (ArchFlag)
  2492. *ArchFlag = "armv6m";
  2493. return Triple("armv6m-apple-darwin");
  2494. case MachO::CPU_SUBTYPE_ARM_V7:
  2495. if (ArchFlag)
  2496. *ArchFlag = "armv7";
  2497. return Triple("armv7-apple-darwin");
  2498. case MachO::CPU_SUBTYPE_ARM_V7EM:
  2499. if (McpuDefault)
  2500. *McpuDefault = "cortex-m4";
  2501. if (ArchFlag)
  2502. *ArchFlag = "armv7em";
  2503. return Triple("thumbv7em-apple-darwin");
  2504. case MachO::CPU_SUBTYPE_ARM_V7K:
  2505. if (McpuDefault)
  2506. *McpuDefault = "cortex-a7";
  2507. if (ArchFlag)
  2508. *ArchFlag = "armv7k";
  2509. return Triple("armv7k-apple-darwin");
  2510. case MachO::CPU_SUBTYPE_ARM_V7M:
  2511. if (McpuDefault)
  2512. *McpuDefault = "cortex-m3";
  2513. if (ArchFlag)
  2514. *ArchFlag = "armv7m";
  2515. return Triple("thumbv7m-apple-darwin");
  2516. case MachO::CPU_SUBTYPE_ARM_V7S:
  2517. if (McpuDefault)
  2518. *McpuDefault = "cortex-a7";
  2519. if (ArchFlag)
  2520. *ArchFlag = "armv7s";
  2521. return Triple("armv7s-apple-darwin");
  2522. default:
  2523. return Triple();
  2524. }
  2525. case MachO::CPU_TYPE_ARM64:
  2526. switch (CPUSubType & ~MachO::CPU_SUBTYPE_MASK) {
  2527. case MachO::CPU_SUBTYPE_ARM64_ALL:
  2528. if (McpuDefault)
  2529. *McpuDefault = "cyclone";
  2530. if (ArchFlag)
  2531. *ArchFlag = "arm64";
  2532. return Triple("arm64-apple-darwin");
  2533. case MachO::CPU_SUBTYPE_ARM64E:
  2534. if (McpuDefault)
  2535. *McpuDefault = "apple-a12";
  2536. if (ArchFlag)
  2537. *ArchFlag = "arm64e";
  2538. return Triple("arm64e-apple-darwin");
  2539. default:
  2540. return Triple();
  2541. }
  2542. case MachO::CPU_TYPE_ARM64_32:
  2543. switch (CPUSubType & ~MachO::CPU_SUBTYPE_MASK) {
  2544. case MachO::CPU_SUBTYPE_ARM64_32_V8:
  2545. if (McpuDefault)
  2546. *McpuDefault = "cyclone";
  2547. if (ArchFlag)
  2548. *ArchFlag = "arm64_32";
  2549. return Triple("arm64_32-apple-darwin");
  2550. default:
  2551. return Triple();
  2552. }
  2553. case MachO::CPU_TYPE_POWERPC:
  2554. switch (CPUSubType & ~MachO::CPU_SUBTYPE_MASK) {
  2555. case MachO::CPU_SUBTYPE_POWERPC_ALL:
  2556. if (ArchFlag)
  2557. *ArchFlag = "ppc";
  2558. return Triple("ppc-apple-darwin");
  2559. default:
  2560. return Triple();
  2561. }
  2562. case MachO::CPU_TYPE_POWERPC64:
  2563. switch (CPUSubType & ~MachO::CPU_SUBTYPE_MASK) {
  2564. case MachO::CPU_SUBTYPE_POWERPC_ALL:
  2565. if (ArchFlag)
  2566. *ArchFlag = "ppc64";
  2567. return Triple("ppc64-apple-darwin");
  2568. default:
  2569. return Triple();
  2570. }
  2571. default:
  2572. return Triple();
  2573. }
  2574. }
  2575. Triple MachOObjectFile::getHostArch() {
  2576. return Triple(sys::getDefaultTargetTriple());
  2577. }
  2578. bool MachOObjectFile::isValidArch(StringRef ArchFlag) {
  2579. auto validArchs = getValidArchs();
  2580. return llvm::is_contained(validArchs, ArchFlag);
  2581. }
  2582. ArrayRef<StringRef> MachOObjectFile::getValidArchs() {
  2583. static const std::array<StringRef, 18> ValidArchs = {{
  2584. "i386",
  2585. "x86_64",
  2586. "x86_64h",
  2587. "armv4t",
  2588. "arm",
  2589. "armv5e",
  2590. "armv6",
  2591. "armv6m",
  2592. "armv7",
  2593. "armv7em",
  2594. "armv7k",
  2595. "armv7m",
  2596. "armv7s",
  2597. "arm64",
  2598. "arm64e",
  2599. "arm64_32",
  2600. "ppc",
  2601. "ppc64",
  2602. }};
  2603. return ValidArchs;
  2604. }
  2605. Triple::ArchType MachOObjectFile::getArch() const {
  2606. return getArch(getCPUType(*this), getCPUSubType(*this));
  2607. }
  2608. Triple MachOObjectFile::getArchTriple(const char **McpuDefault) const {
  2609. return getArchTriple(Header.cputype, Header.cpusubtype, McpuDefault);
  2610. }
  2611. relocation_iterator MachOObjectFile::section_rel_begin(unsigned Index) const {
  2612. DataRefImpl DRI;
  2613. DRI.d.a = Index;
  2614. return section_rel_begin(DRI);
  2615. }
  2616. relocation_iterator MachOObjectFile::section_rel_end(unsigned Index) const {
  2617. DataRefImpl DRI;
  2618. DRI.d.a = Index;
  2619. return section_rel_end(DRI);
  2620. }
  2621. dice_iterator MachOObjectFile::begin_dices() const {
  2622. DataRefImpl DRI;
  2623. if (!DataInCodeLoadCmd)
  2624. return dice_iterator(DiceRef(DRI, this));
  2625. MachO::linkedit_data_command DicLC = getDataInCodeLoadCommand();
  2626. DRI.p = reinterpret_cast<uintptr_t>(getPtr(*this, DicLC.dataoff));
  2627. return dice_iterator(DiceRef(DRI, this));
  2628. }
  2629. dice_iterator MachOObjectFile::end_dices() const {
  2630. DataRefImpl DRI;
  2631. if (!DataInCodeLoadCmd)
  2632. return dice_iterator(DiceRef(DRI, this));
  2633. MachO::linkedit_data_command DicLC = getDataInCodeLoadCommand();
  2634. unsigned Offset = DicLC.dataoff + DicLC.datasize;
  2635. DRI.p = reinterpret_cast<uintptr_t>(getPtr(*this, Offset));
  2636. return dice_iterator(DiceRef(DRI, this));
  2637. }
  2638. ExportEntry::ExportEntry(Error *E, const MachOObjectFile *O,
  2639. ArrayRef<uint8_t> T) : E(E), O(O), Trie(T) {}
  2640. void ExportEntry::moveToFirst() {
  2641. ErrorAsOutParameter ErrAsOutParam(E);
  2642. pushNode(0);
  2643. if (*E)
  2644. return;
  2645. pushDownUntilBottom();
  2646. }
  2647. void ExportEntry::moveToEnd() {
  2648. Stack.clear();
  2649. Done = true;
  2650. }
  2651. bool ExportEntry::operator==(const ExportEntry &Other) const {
  2652. // Common case, one at end, other iterating from begin.
  2653. if (Done || Other.Done)
  2654. return (Done == Other.Done);
  2655. // Not equal if different stack sizes.
  2656. if (Stack.size() != Other.Stack.size())
  2657. return false;
  2658. // Not equal if different cumulative strings.
  2659. if (!CumulativeString.equals(Other.CumulativeString))
  2660. return false;
  2661. // Equal if all nodes in both stacks match.
  2662. for (unsigned i=0; i < Stack.size(); ++i) {
  2663. if (Stack[i].Start != Other.Stack[i].Start)
  2664. return false;
  2665. }
  2666. return true;
  2667. }
  2668. uint64_t ExportEntry::readULEB128(const uint8_t *&Ptr, const char **error) {
  2669. unsigned Count;
  2670. uint64_t Result = decodeULEB128(Ptr, &Count, Trie.end(), error);
  2671. Ptr += Count;
  2672. if (Ptr > Trie.end())
  2673. Ptr = Trie.end();
  2674. return Result;
  2675. }
  2676. StringRef ExportEntry::name() const {
  2677. return CumulativeString;
  2678. }
  2679. uint64_t ExportEntry::flags() const {
  2680. return Stack.back().Flags;
  2681. }
  2682. uint64_t ExportEntry::address() const {
  2683. return Stack.back().Address;
  2684. }
  2685. uint64_t ExportEntry::other() const {
  2686. return Stack.back().Other;
  2687. }
  2688. StringRef ExportEntry::otherName() const {
  2689. const char* ImportName = Stack.back().ImportName;
  2690. if (ImportName)
  2691. return StringRef(ImportName);
  2692. return StringRef();
  2693. }
  2694. uint32_t ExportEntry::nodeOffset() const {
  2695. return Stack.back().Start - Trie.begin();
  2696. }
  2697. ExportEntry::NodeState::NodeState(const uint8_t *Ptr)
  2698. : Start(Ptr), Current(Ptr) {}
  2699. void ExportEntry::pushNode(uint64_t offset) {
  2700. ErrorAsOutParameter ErrAsOutParam(E);
  2701. const uint8_t *Ptr = Trie.begin() + offset;
  2702. NodeState State(Ptr);
  2703. const char *error;
  2704. uint64_t ExportInfoSize = readULEB128(State.Current, &error);
  2705. if (error) {
  2706. *E = malformedError("export info size " + Twine(error) +
  2707. " in export trie data at node: 0x" +
  2708. Twine::utohexstr(offset));
  2709. moveToEnd();
  2710. return;
  2711. }
  2712. State.IsExportNode = (ExportInfoSize != 0);
  2713. const uint8_t* Children = State.Current + ExportInfoSize;
  2714. if (Children > Trie.end()) {
  2715. *E = malformedError(
  2716. "export info size: 0x" + Twine::utohexstr(ExportInfoSize) +
  2717. " in export trie data at node: 0x" + Twine::utohexstr(offset) +
  2718. " too big and extends past end of trie data");
  2719. moveToEnd();
  2720. return;
  2721. }
  2722. if (State.IsExportNode) {
  2723. const uint8_t *ExportStart = State.Current;
  2724. State.Flags = readULEB128(State.Current, &error);
  2725. if (error) {
  2726. *E = malformedError("flags " + Twine(error) +
  2727. " in export trie data at node: 0x" +
  2728. Twine::utohexstr(offset));
  2729. moveToEnd();
  2730. return;
  2731. }
  2732. uint64_t Kind = State.Flags & MachO::EXPORT_SYMBOL_FLAGS_KIND_MASK;
  2733. if (State.Flags != 0 &&
  2734. (Kind != MachO::EXPORT_SYMBOL_FLAGS_KIND_REGULAR &&
  2735. Kind != MachO::EXPORT_SYMBOL_FLAGS_KIND_ABSOLUTE &&
  2736. Kind != MachO::EXPORT_SYMBOL_FLAGS_KIND_THREAD_LOCAL)) {
  2737. *E = malformedError(
  2738. "unsupported exported symbol kind: " + Twine((int)Kind) +
  2739. " in flags: 0x" + Twine::utohexstr(State.Flags) +
  2740. " in export trie data at node: 0x" + Twine::utohexstr(offset));
  2741. moveToEnd();
  2742. return;
  2743. }
  2744. if (State.Flags & MachO::EXPORT_SYMBOL_FLAGS_REEXPORT) {
  2745. State.Address = 0;
  2746. State.Other = readULEB128(State.Current, &error); // dylib ordinal
  2747. if (error) {
  2748. *E = malformedError("dylib ordinal of re-export " + Twine(error) +
  2749. " in export trie data at node: 0x" +
  2750. Twine::utohexstr(offset));
  2751. moveToEnd();
  2752. return;
  2753. }
  2754. if (O != nullptr) {
  2755. if (State.Other > O->getLibraryCount()) {
  2756. *E = malformedError(
  2757. "bad library ordinal: " + Twine((int)State.Other) + " (max " +
  2758. Twine((int)O->getLibraryCount()) +
  2759. ") in export trie data at node: 0x" + Twine::utohexstr(offset));
  2760. moveToEnd();
  2761. return;
  2762. }
  2763. }
  2764. State.ImportName = reinterpret_cast<const char*>(State.Current);
  2765. if (*State.ImportName == '\0') {
  2766. State.Current++;
  2767. } else {
  2768. const uint8_t *End = State.Current + 1;
  2769. if (End >= Trie.end()) {
  2770. *E = malformedError("import name of re-export in export trie data at "
  2771. "node: 0x" +
  2772. Twine::utohexstr(offset) +
  2773. " starts past end of trie data");
  2774. moveToEnd();
  2775. return;
  2776. }
  2777. while(*End != '\0' && End < Trie.end())
  2778. End++;
  2779. if (*End != '\0') {
  2780. *E = malformedError("import name of re-export in export trie data at "
  2781. "node: 0x" +
  2782. Twine::utohexstr(offset) +
  2783. " extends past end of trie data");
  2784. moveToEnd();
  2785. return;
  2786. }
  2787. State.Current = End + 1;
  2788. }
  2789. } else {
  2790. State.Address = readULEB128(State.Current, &error);
  2791. if (error) {
  2792. *E = malformedError("address " + Twine(error) +
  2793. " in export trie data at node: 0x" +
  2794. Twine::utohexstr(offset));
  2795. moveToEnd();
  2796. return;
  2797. }
  2798. if (State.Flags & MachO::EXPORT_SYMBOL_FLAGS_STUB_AND_RESOLVER) {
  2799. State.Other = readULEB128(State.Current, &error);
  2800. if (error) {
  2801. *E = malformedError("resolver of stub and resolver " + Twine(error) +
  2802. " in export trie data at node: 0x" +
  2803. Twine::utohexstr(offset));
  2804. moveToEnd();
  2805. return;
  2806. }
  2807. }
  2808. }
  2809. if(ExportStart + ExportInfoSize != State.Current) {
  2810. *E = malformedError(
  2811. "inconsistant export info size: 0x" +
  2812. Twine::utohexstr(ExportInfoSize) + " where actual size was: 0x" +
  2813. Twine::utohexstr(State.Current - ExportStart) +
  2814. " in export trie data at node: 0x" + Twine::utohexstr(offset));
  2815. moveToEnd();
  2816. return;
  2817. }
  2818. }
  2819. State.ChildCount = *Children;
  2820. if (State.ChildCount != 0 && Children + 1 >= Trie.end()) {
  2821. *E = malformedError("byte for count of childern in export trie data at "
  2822. "node: 0x" +
  2823. Twine::utohexstr(offset) +
  2824. " extends past end of trie data");
  2825. moveToEnd();
  2826. return;
  2827. }
  2828. State.Current = Children + 1;
  2829. State.NextChildIndex = 0;
  2830. State.ParentStringLength = CumulativeString.size();
  2831. Stack.push_back(State);
  2832. }
  2833. void ExportEntry::pushDownUntilBottom() {
  2834. ErrorAsOutParameter ErrAsOutParam(E);
  2835. const char *error;
  2836. while (Stack.back().NextChildIndex < Stack.back().ChildCount) {
  2837. NodeState &Top = Stack.back();
  2838. CumulativeString.resize(Top.ParentStringLength);
  2839. for (;*Top.Current != 0 && Top.Current < Trie.end(); Top.Current++) {
  2840. char C = *Top.Current;
  2841. CumulativeString.push_back(C);
  2842. }
  2843. if (Top.Current >= Trie.end()) {
  2844. *E = malformedError("edge sub-string in export trie data at node: 0x" +
  2845. Twine::utohexstr(Top.Start - Trie.begin()) +
  2846. " for child #" + Twine((int)Top.NextChildIndex) +
  2847. " extends past end of trie data");
  2848. moveToEnd();
  2849. return;
  2850. }
  2851. Top.Current += 1;
  2852. uint64_t childNodeIndex = readULEB128(Top.Current, &error);
  2853. if (error) {
  2854. *E = malformedError("child node offset " + Twine(error) +
  2855. " in export trie data at node: 0x" +
  2856. Twine::utohexstr(Top.Start - Trie.begin()));
  2857. moveToEnd();
  2858. return;
  2859. }
  2860. for (const NodeState &node : nodes()) {
  2861. if (node.Start == Trie.begin() + childNodeIndex){
  2862. *E = malformedError("loop in childern in export trie data at node: 0x" +
  2863. Twine::utohexstr(Top.Start - Trie.begin()) +
  2864. " back to node: 0x" +
  2865. Twine::utohexstr(childNodeIndex));
  2866. moveToEnd();
  2867. return;
  2868. }
  2869. }
  2870. Top.NextChildIndex += 1;
  2871. pushNode(childNodeIndex);
  2872. if (*E)
  2873. return;
  2874. }
  2875. if (!Stack.back().IsExportNode) {
  2876. *E = malformedError("node is not an export node in export trie data at "
  2877. "node: 0x" +
  2878. Twine::utohexstr(Stack.back().Start - Trie.begin()));
  2879. moveToEnd();
  2880. return;
  2881. }
  2882. }
  2883. // We have a trie data structure and need a way to walk it that is compatible
  2884. // with the C++ iterator model. The solution is a non-recursive depth first
  2885. // traversal where the iterator contains a stack of parent nodes along with a
  2886. // string that is the accumulation of all edge strings along the parent chain
  2887. // to this point.
  2888. //
  2889. // There is one "export" node for each exported symbol. But because some
  2890. // symbols may be a prefix of another symbol (e.g. _dup and _dup2), an export
  2891. // node may have child nodes too.
  2892. //
  2893. // The algorithm for moveNext() is to keep moving down the leftmost unvisited
  2894. // child until hitting a node with no children (which is an export node or
  2895. // else the trie is malformed). On the way down, each node is pushed on the
  2896. // stack ivar. If there is no more ways down, it pops up one and tries to go
  2897. // down a sibling path until a childless node is reached.
  2898. void ExportEntry::moveNext() {
  2899. assert(!Stack.empty() && "ExportEntry::moveNext() with empty node stack");
  2900. if (!Stack.back().IsExportNode) {
  2901. *E = malformedError("node is not an export node in export trie data at "
  2902. "node: 0x" +
  2903. Twine::utohexstr(Stack.back().Start - Trie.begin()));
  2904. moveToEnd();
  2905. return;
  2906. }
  2907. Stack.pop_back();
  2908. while (!Stack.empty()) {
  2909. NodeState &Top = Stack.back();
  2910. if (Top.NextChildIndex < Top.ChildCount) {
  2911. pushDownUntilBottom();
  2912. // Now at the next export node.
  2913. return;
  2914. } else {
  2915. if (Top.IsExportNode) {
  2916. // This node has no children but is itself an export node.
  2917. CumulativeString.resize(Top.ParentStringLength);
  2918. return;
  2919. }
  2920. Stack.pop_back();
  2921. }
  2922. }
  2923. Done = true;
  2924. }
  2925. iterator_range<export_iterator>
  2926. MachOObjectFile::exports(Error &E, ArrayRef<uint8_t> Trie,
  2927. const MachOObjectFile *O) {
  2928. ExportEntry Start(&E, O, Trie);
  2929. if (Trie.empty())
  2930. Start.moveToEnd();
  2931. else
  2932. Start.moveToFirst();
  2933. ExportEntry Finish(&E, O, Trie);
  2934. Finish.moveToEnd();
  2935. return make_range(export_iterator(Start), export_iterator(Finish));
  2936. }
  2937. iterator_range<export_iterator> MachOObjectFile::exports(Error &Err) const {
  2938. return exports(Err, getDyldInfoExportsTrie(), this);
  2939. }
  2940. MachORebaseEntry::MachORebaseEntry(Error *E, const MachOObjectFile *O,
  2941. ArrayRef<uint8_t> Bytes, bool is64Bit)
  2942. : E(E), O(O), Opcodes(Bytes), Ptr(Bytes.begin()),
  2943. PointerSize(is64Bit ? 8 : 4) {}
  2944. void MachORebaseEntry::moveToFirst() {
  2945. Ptr = Opcodes.begin();
  2946. moveNext();
  2947. }
  2948. void MachORebaseEntry::moveToEnd() {
  2949. Ptr = Opcodes.end();
  2950. RemainingLoopCount = 0;
  2951. Done = true;
  2952. }
  2953. void MachORebaseEntry::moveNext() {
  2954. ErrorAsOutParameter ErrAsOutParam(E);
  2955. // If in the middle of some loop, move to next rebasing in loop.
  2956. SegmentOffset += AdvanceAmount;
  2957. if (RemainingLoopCount) {
  2958. --RemainingLoopCount;
  2959. return;
  2960. }
  2961. // REBASE_OPCODE_DONE is only used for padding if we are not aligned to
  2962. // pointer size. Therefore it is possible to reach the end without ever having
  2963. // seen REBASE_OPCODE_DONE.
  2964. if (Ptr == Opcodes.end()) {
  2965. Done = true;
  2966. return;
  2967. }
  2968. bool More = true;
  2969. while (More) {
  2970. // Parse next opcode and set up next loop.
  2971. const uint8_t *OpcodeStart = Ptr;
  2972. uint8_t Byte = *Ptr++;
  2973. uint8_t ImmValue = Byte & MachO::REBASE_IMMEDIATE_MASK;
  2974. uint8_t Opcode = Byte & MachO::REBASE_OPCODE_MASK;
  2975. uint32_t Count, Skip;
  2976. const char *error = nullptr;
  2977. switch (Opcode) {
  2978. case MachO::REBASE_OPCODE_DONE:
  2979. More = false;
  2980. Done = true;
  2981. moveToEnd();
  2982. DEBUG_WITH_TYPE("mach-o-rebase", dbgs() << "REBASE_OPCODE_DONE\n");
  2983. break;
  2984. case MachO::REBASE_OPCODE_SET_TYPE_IMM:
  2985. RebaseType = ImmValue;
  2986. if (RebaseType > MachO::REBASE_TYPE_TEXT_PCREL32) {
  2987. *E = malformedError("for REBASE_OPCODE_SET_TYPE_IMM bad bind type: " +
  2988. Twine((int)RebaseType) + " for opcode at: 0x" +
  2989. Twine::utohexstr(OpcodeStart - Opcodes.begin()));
  2990. moveToEnd();
  2991. return;
  2992. }
  2993. DEBUG_WITH_TYPE(
  2994. "mach-o-rebase",
  2995. dbgs() << "REBASE_OPCODE_SET_TYPE_IMM: "
  2996. << "RebaseType=" << (int) RebaseType << "\n");
  2997. break;
  2998. case MachO::REBASE_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB:
  2999. SegmentIndex = ImmValue;
  3000. SegmentOffset = readULEB128(&error);
  3001. if (error) {
  3002. *E = malformedError("for REBASE_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB " +
  3003. Twine(error) + " for opcode at: 0x" +
  3004. Twine::utohexstr(OpcodeStart - Opcodes.begin()));
  3005. moveToEnd();
  3006. return;
  3007. }
  3008. error = O->RebaseEntryCheckSegAndOffsets(SegmentIndex, SegmentOffset,
  3009. PointerSize);
  3010. if (error) {
  3011. *E = malformedError("for REBASE_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB " +
  3012. Twine(error) + " for opcode at: 0x" +
  3013. Twine::utohexstr(OpcodeStart - Opcodes.begin()));
  3014. moveToEnd();
  3015. return;
  3016. }
  3017. DEBUG_WITH_TYPE(
  3018. "mach-o-rebase",
  3019. dbgs() << "REBASE_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB: "
  3020. << "SegmentIndex=" << SegmentIndex << ", "
  3021. << format("SegmentOffset=0x%06X", SegmentOffset)
  3022. << "\n");
  3023. break;
  3024. case MachO::REBASE_OPCODE_ADD_ADDR_ULEB:
  3025. SegmentOffset += readULEB128(&error);
  3026. if (error) {
  3027. *E = malformedError("for REBASE_OPCODE_ADD_ADDR_ULEB " + Twine(error) +
  3028. " for opcode at: 0x" +
  3029. Twine::utohexstr(OpcodeStart - Opcodes.begin()));
  3030. moveToEnd();
  3031. return;
  3032. }
  3033. error = O->RebaseEntryCheckSegAndOffsets(SegmentIndex, SegmentOffset,
  3034. PointerSize);
  3035. if (error) {
  3036. *E = malformedError("for REBASE_OPCODE_ADD_ADDR_ULEB " + Twine(error) +
  3037. " for opcode at: 0x" +
  3038. Twine::utohexstr(OpcodeStart - Opcodes.begin()));
  3039. moveToEnd();
  3040. return;
  3041. }
  3042. DEBUG_WITH_TYPE("mach-o-rebase",
  3043. dbgs() << "REBASE_OPCODE_ADD_ADDR_ULEB: "
  3044. << format("SegmentOffset=0x%06X",
  3045. SegmentOffset) << "\n");
  3046. break;
  3047. case MachO::REBASE_OPCODE_ADD_ADDR_IMM_SCALED:
  3048. SegmentOffset += ImmValue * PointerSize;
  3049. error = O->RebaseEntryCheckSegAndOffsets(SegmentIndex, SegmentOffset,
  3050. PointerSize);
  3051. if (error) {
  3052. *E = malformedError("for REBASE_OPCODE_ADD_ADDR_IMM_SCALED " +
  3053. Twine(error) + " for opcode at: 0x" +
  3054. Twine::utohexstr(OpcodeStart - Opcodes.begin()));
  3055. moveToEnd();
  3056. return;
  3057. }
  3058. DEBUG_WITH_TYPE("mach-o-rebase",
  3059. dbgs() << "REBASE_OPCODE_ADD_ADDR_IMM_SCALED: "
  3060. << format("SegmentOffset=0x%06X",
  3061. SegmentOffset) << "\n");
  3062. break;
  3063. case MachO::REBASE_OPCODE_DO_REBASE_IMM_TIMES:
  3064. AdvanceAmount = PointerSize;
  3065. Skip = 0;
  3066. Count = ImmValue;
  3067. if (ImmValue != 0)
  3068. RemainingLoopCount = ImmValue - 1;
  3069. else
  3070. RemainingLoopCount = 0;
  3071. error = O->RebaseEntryCheckSegAndOffsets(SegmentIndex, SegmentOffset,
  3072. PointerSize, Count, Skip);
  3073. if (error) {
  3074. *E = malformedError("for REBASE_OPCODE_DO_REBASE_IMM_TIMES " +
  3075. Twine(error) + " for opcode at: 0x" +
  3076. Twine::utohexstr(OpcodeStart - Opcodes.begin()));
  3077. moveToEnd();
  3078. return;
  3079. }
  3080. DEBUG_WITH_TYPE(
  3081. "mach-o-rebase",
  3082. dbgs() << "REBASE_OPCODE_DO_REBASE_IMM_TIMES: "
  3083. << format("SegmentOffset=0x%06X", SegmentOffset)
  3084. << ", AdvanceAmount=" << AdvanceAmount
  3085. << ", RemainingLoopCount=" << RemainingLoopCount
  3086. << "\n");
  3087. return;
  3088. case MachO::REBASE_OPCODE_DO_REBASE_ULEB_TIMES:
  3089. AdvanceAmount = PointerSize;
  3090. Skip = 0;
  3091. Count = readULEB128(&error);
  3092. if (error) {
  3093. *E = malformedError("for REBASE_OPCODE_DO_REBASE_ULEB_TIMES " +
  3094. Twine(error) + " for opcode at: 0x" +
  3095. Twine::utohexstr(OpcodeStart - Opcodes.begin()));
  3096. moveToEnd();
  3097. return;
  3098. }
  3099. if (Count != 0)
  3100. RemainingLoopCount = Count - 1;
  3101. else
  3102. RemainingLoopCount = 0;
  3103. error = O->RebaseEntryCheckSegAndOffsets(SegmentIndex, SegmentOffset,
  3104. PointerSize, Count, Skip);
  3105. if (error) {
  3106. *E = malformedError("for REBASE_OPCODE_DO_REBASE_ULEB_TIMES " +
  3107. Twine(error) + " for opcode at: 0x" +
  3108. Twine::utohexstr(OpcodeStart - Opcodes.begin()));
  3109. moveToEnd();
  3110. return;
  3111. }
  3112. DEBUG_WITH_TYPE(
  3113. "mach-o-rebase",
  3114. dbgs() << "REBASE_OPCODE_DO_REBASE_ULEB_TIMES: "
  3115. << format("SegmentOffset=0x%06X", SegmentOffset)
  3116. << ", AdvanceAmount=" << AdvanceAmount
  3117. << ", RemainingLoopCount=" << RemainingLoopCount
  3118. << "\n");
  3119. return;
  3120. case MachO::REBASE_OPCODE_DO_REBASE_ADD_ADDR_ULEB:
  3121. Skip = readULEB128(&error);
  3122. if (error) {
  3123. *E = malformedError("for REBASE_OPCODE_DO_REBASE_ADD_ADDR_ULEB " +
  3124. Twine(error) + " for opcode at: 0x" +
  3125. Twine::utohexstr(OpcodeStart - Opcodes.begin()));
  3126. moveToEnd();
  3127. return;
  3128. }
  3129. AdvanceAmount = Skip + PointerSize;
  3130. Count = 1;
  3131. RemainingLoopCount = 0;
  3132. error = O->RebaseEntryCheckSegAndOffsets(SegmentIndex, SegmentOffset,
  3133. PointerSize, Count, Skip);
  3134. if (error) {
  3135. *E = malformedError("for REBASE_OPCODE_DO_REBASE_ADD_ADDR_ULEB " +
  3136. Twine(error) + " for opcode at: 0x" +
  3137. Twine::utohexstr(OpcodeStart - Opcodes.begin()));
  3138. moveToEnd();
  3139. return;
  3140. }
  3141. DEBUG_WITH_TYPE(
  3142. "mach-o-rebase",
  3143. dbgs() << "REBASE_OPCODE_DO_REBASE_ADD_ADDR_ULEB: "
  3144. << format("SegmentOffset=0x%06X", SegmentOffset)
  3145. << ", AdvanceAmount=" << AdvanceAmount
  3146. << ", RemainingLoopCount=" << RemainingLoopCount
  3147. << "\n");
  3148. return;
  3149. case MachO::REBASE_OPCODE_DO_REBASE_ULEB_TIMES_SKIPPING_ULEB:
  3150. Count = readULEB128(&error);
  3151. if (error) {
  3152. *E = malformedError("for REBASE_OPCODE_DO_REBASE_ULEB_TIMES_SKIPPING_"
  3153. "ULEB " +
  3154. Twine(error) + " for opcode at: 0x" +
  3155. Twine::utohexstr(OpcodeStart - Opcodes.begin()));
  3156. moveToEnd();
  3157. return;
  3158. }
  3159. if (Count != 0)
  3160. RemainingLoopCount = Count - 1;
  3161. else
  3162. RemainingLoopCount = 0;
  3163. Skip = readULEB128(&error);
  3164. if (error) {
  3165. *E = malformedError("for REBASE_OPCODE_DO_REBASE_ULEB_TIMES_SKIPPING_"
  3166. "ULEB " +
  3167. Twine(error) + " for opcode at: 0x" +
  3168. Twine::utohexstr(OpcodeStart - Opcodes.begin()));
  3169. moveToEnd();
  3170. return;
  3171. }
  3172. AdvanceAmount = Skip + PointerSize;
  3173. error = O->RebaseEntryCheckSegAndOffsets(SegmentIndex, SegmentOffset,
  3174. PointerSize, Count, Skip);
  3175. if (error) {
  3176. *E = malformedError("for REBASE_OPCODE_DO_REBASE_ULEB_TIMES_SKIPPING_"
  3177. "ULEB " +
  3178. Twine(error) + " for opcode at: 0x" +
  3179. Twine::utohexstr(OpcodeStart - Opcodes.begin()));
  3180. moveToEnd();
  3181. return;
  3182. }
  3183. DEBUG_WITH_TYPE(
  3184. "mach-o-rebase",
  3185. dbgs() << "REBASE_OPCODE_DO_REBASE_ULEB_TIMES_SKIPPING_ULEB: "
  3186. << format("SegmentOffset=0x%06X", SegmentOffset)
  3187. << ", AdvanceAmount=" << AdvanceAmount
  3188. << ", RemainingLoopCount=" << RemainingLoopCount
  3189. << "\n");
  3190. return;
  3191. default:
  3192. *E = malformedError("bad rebase info (bad opcode value 0x" +
  3193. Twine::utohexstr(Opcode) + " for opcode at: 0x" +
  3194. Twine::utohexstr(OpcodeStart - Opcodes.begin()));
  3195. moveToEnd();
  3196. return;
  3197. }
  3198. }
  3199. }
  3200. uint64_t MachORebaseEntry::readULEB128(const char **error) {
  3201. unsigned Count;
  3202. uint64_t Result = decodeULEB128(Ptr, &Count, Opcodes.end(), error);
  3203. Ptr += Count;
  3204. if (Ptr > Opcodes.end())
  3205. Ptr = Opcodes.end();
  3206. return Result;
  3207. }
  3208. int32_t MachORebaseEntry::segmentIndex() const { return SegmentIndex; }
  3209. uint64_t MachORebaseEntry::segmentOffset() const { return SegmentOffset; }
  3210. StringRef MachORebaseEntry::typeName() const {
  3211. switch (RebaseType) {
  3212. case MachO::REBASE_TYPE_POINTER:
  3213. return "pointer";
  3214. case MachO::REBASE_TYPE_TEXT_ABSOLUTE32:
  3215. return "text abs32";
  3216. case MachO::REBASE_TYPE_TEXT_PCREL32:
  3217. return "text rel32";
  3218. }
  3219. return "unknown";
  3220. }
  3221. // For use with the SegIndex of a checked Mach-O Rebase entry
  3222. // to get the segment name.
  3223. StringRef MachORebaseEntry::segmentName() const {
  3224. return O->BindRebaseSegmentName(SegmentIndex);
  3225. }
  3226. // For use with a SegIndex,SegOffset pair from a checked Mach-O Rebase entry
  3227. // to get the section name.
  3228. StringRef MachORebaseEntry::sectionName() const {
  3229. return O->BindRebaseSectionName(SegmentIndex, SegmentOffset);
  3230. }
  3231. // For use with a SegIndex,SegOffset pair from a checked Mach-O Rebase entry
  3232. // to get the address.
  3233. uint64_t MachORebaseEntry::address() const {
  3234. return O->BindRebaseAddress(SegmentIndex, SegmentOffset);
  3235. }
  3236. bool MachORebaseEntry::operator==(const MachORebaseEntry &Other) const {
  3237. #ifdef EXPENSIVE_CHECKS
  3238. assert(Opcodes == Other.Opcodes && "compare iterators of different files");
  3239. #else
  3240. assert(Opcodes.data() == Other.Opcodes.data() && "compare iterators of different files");
  3241. #endif
  3242. return (Ptr == Other.Ptr) &&
  3243. (RemainingLoopCount == Other.RemainingLoopCount) &&
  3244. (Done == Other.Done);
  3245. }
  3246. iterator_range<rebase_iterator>
  3247. MachOObjectFile::rebaseTable(Error &Err, MachOObjectFile *O,
  3248. ArrayRef<uint8_t> Opcodes, bool is64) {
  3249. if (O->BindRebaseSectionTable == nullptr)
  3250. O->BindRebaseSectionTable = std::make_unique<BindRebaseSegInfo>(O);
  3251. MachORebaseEntry Start(&Err, O, Opcodes, is64);
  3252. Start.moveToFirst();
  3253. MachORebaseEntry Finish(&Err, O, Opcodes, is64);
  3254. Finish.moveToEnd();
  3255. return make_range(rebase_iterator(Start), rebase_iterator(Finish));
  3256. }
  3257. iterator_range<rebase_iterator> MachOObjectFile::rebaseTable(Error &Err) {
  3258. return rebaseTable(Err, this, getDyldInfoRebaseOpcodes(), is64Bit());
  3259. }
  3260. MachOBindEntry::MachOBindEntry(Error *E, const MachOObjectFile *O,
  3261. ArrayRef<uint8_t> Bytes, bool is64Bit, Kind BK)
  3262. : E(E), O(O), Opcodes(Bytes), Ptr(Bytes.begin()),
  3263. PointerSize(is64Bit ? 8 : 4), TableKind(BK) {}
  3264. void MachOBindEntry::moveToFirst() {
  3265. Ptr = Opcodes.begin();
  3266. moveNext();
  3267. }
  3268. void MachOBindEntry::moveToEnd() {
  3269. Ptr = Opcodes.end();
  3270. RemainingLoopCount = 0;
  3271. Done = true;
  3272. }
  3273. void MachOBindEntry::moveNext() {
  3274. ErrorAsOutParameter ErrAsOutParam(E);
  3275. // If in the middle of some loop, move to next binding in loop.
  3276. SegmentOffset += AdvanceAmount;
  3277. if (RemainingLoopCount) {
  3278. --RemainingLoopCount;
  3279. return;
  3280. }
  3281. // BIND_OPCODE_DONE is only used for padding if we are not aligned to
  3282. // pointer size. Therefore it is possible to reach the end without ever having
  3283. // seen BIND_OPCODE_DONE.
  3284. if (Ptr == Opcodes.end()) {
  3285. Done = true;
  3286. return;
  3287. }
  3288. bool More = true;
  3289. while (More) {
  3290. // Parse next opcode and set up next loop.
  3291. const uint8_t *OpcodeStart = Ptr;
  3292. uint8_t Byte = *Ptr++;
  3293. uint8_t ImmValue = Byte & MachO::BIND_IMMEDIATE_MASK;
  3294. uint8_t Opcode = Byte & MachO::BIND_OPCODE_MASK;
  3295. int8_t SignExtended;
  3296. const uint8_t *SymStart;
  3297. uint32_t Count, Skip;
  3298. const char *error = nullptr;
  3299. switch (Opcode) {
  3300. case MachO::BIND_OPCODE_DONE:
  3301. if (TableKind == Kind::Lazy) {
  3302. // Lazying bindings have a DONE opcode between entries. Need to ignore
  3303. // it to advance to next entry. But need not if this is last entry.
  3304. bool NotLastEntry = false;
  3305. for (const uint8_t *P = Ptr; P < Opcodes.end(); ++P) {
  3306. if (*P) {
  3307. NotLastEntry = true;
  3308. }
  3309. }
  3310. if (NotLastEntry)
  3311. break;
  3312. }
  3313. More = false;
  3314. moveToEnd();
  3315. DEBUG_WITH_TYPE("mach-o-bind", dbgs() << "BIND_OPCODE_DONE\n");
  3316. break;
  3317. case MachO::BIND_OPCODE_SET_DYLIB_ORDINAL_IMM:
  3318. if (TableKind == Kind::Weak) {
  3319. *E = malformedError("BIND_OPCODE_SET_DYLIB_ORDINAL_IMM not allowed in "
  3320. "weak bind table for opcode at: 0x" +
  3321. Twine::utohexstr(OpcodeStart - Opcodes.begin()));
  3322. moveToEnd();
  3323. return;
  3324. }
  3325. Ordinal = ImmValue;
  3326. LibraryOrdinalSet = true;
  3327. if (ImmValue > O->getLibraryCount()) {
  3328. *E = malformedError("for BIND_OPCODE_SET_DYLIB_ORDINAL_ULEB bad "
  3329. "library ordinal: " +
  3330. Twine((int)ImmValue) + " (max " +
  3331. Twine((int)O->getLibraryCount()) +
  3332. ") for opcode at: 0x" +
  3333. Twine::utohexstr(OpcodeStart - Opcodes.begin()));
  3334. moveToEnd();
  3335. return;
  3336. }
  3337. DEBUG_WITH_TYPE(
  3338. "mach-o-bind",
  3339. dbgs() << "BIND_OPCODE_SET_DYLIB_ORDINAL_IMM: "
  3340. << "Ordinal=" << Ordinal << "\n");
  3341. break;
  3342. case MachO::BIND_OPCODE_SET_DYLIB_ORDINAL_ULEB:
  3343. if (TableKind == Kind::Weak) {
  3344. *E = malformedError("BIND_OPCODE_SET_DYLIB_ORDINAL_ULEB not allowed in "
  3345. "weak bind table for opcode at: 0x" +
  3346. Twine::utohexstr(OpcodeStart - Opcodes.begin()));
  3347. moveToEnd();
  3348. return;
  3349. }
  3350. Ordinal = readULEB128(&error);
  3351. LibraryOrdinalSet = true;
  3352. if (error) {
  3353. *E = malformedError("for BIND_OPCODE_SET_DYLIB_ORDINAL_ULEB " +
  3354. Twine(error) + " for opcode at: 0x" +
  3355. Twine::utohexstr(OpcodeStart - Opcodes.begin()));
  3356. moveToEnd();
  3357. return;
  3358. }
  3359. if (Ordinal > (int)O->getLibraryCount()) {
  3360. *E = malformedError("for BIND_OPCODE_SET_DYLIB_ORDINAL_ULEB bad "
  3361. "library ordinal: " +
  3362. Twine((int)Ordinal) + " (max " +
  3363. Twine((int)O->getLibraryCount()) +
  3364. ") for opcode at: 0x" +
  3365. Twine::utohexstr(OpcodeStart - Opcodes.begin()));
  3366. moveToEnd();
  3367. return;
  3368. }
  3369. DEBUG_WITH_TYPE(
  3370. "mach-o-bind",
  3371. dbgs() << "BIND_OPCODE_SET_DYLIB_ORDINAL_ULEB: "
  3372. << "Ordinal=" << Ordinal << "\n");
  3373. break;
  3374. case MachO::BIND_OPCODE_SET_DYLIB_SPECIAL_IMM:
  3375. if (TableKind == Kind::Weak) {
  3376. *E = malformedError("BIND_OPCODE_SET_DYLIB_SPECIAL_IMM not allowed in "
  3377. "weak bind table for opcode at: 0x" +
  3378. Twine::utohexstr(OpcodeStart - Opcodes.begin()));
  3379. moveToEnd();
  3380. return;
  3381. }
  3382. if (ImmValue) {
  3383. SignExtended = MachO::BIND_OPCODE_MASK | ImmValue;
  3384. Ordinal = SignExtended;
  3385. if (Ordinal < MachO::BIND_SPECIAL_DYLIB_FLAT_LOOKUP) {
  3386. *E = malformedError("for BIND_OPCODE_SET_DYLIB_SPECIAL_IMM unknown "
  3387. "special ordinal: " +
  3388. Twine((int)Ordinal) + " for opcode at: 0x" +
  3389. Twine::utohexstr(OpcodeStart - Opcodes.begin()));
  3390. moveToEnd();
  3391. return;
  3392. }
  3393. } else
  3394. Ordinal = 0;
  3395. LibraryOrdinalSet = true;
  3396. DEBUG_WITH_TYPE(
  3397. "mach-o-bind",
  3398. dbgs() << "BIND_OPCODE_SET_DYLIB_SPECIAL_IMM: "
  3399. << "Ordinal=" << Ordinal << "\n");
  3400. break;
  3401. case MachO::BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM:
  3402. Flags = ImmValue;
  3403. SymStart = Ptr;
  3404. while (*Ptr && (Ptr < Opcodes.end())) {
  3405. ++Ptr;
  3406. }
  3407. if (Ptr == Opcodes.end()) {
  3408. *E = malformedError(
  3409. "for BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM "
  3410. "symbol name extends past opcodes for opcode at: 0x" +
  3411. Twine::utohexstr(OpcodeStart - Opcodes.begin()));
  3412. moveToEnd();
  3413. return;
  3414. }
  3415. SymbolName = StringRef(reinterpret_cast<const char*>(SymStart),
  3416. Ptr-SymStart);
  3417. ++Ptr;
  3418. DEBUG_WITH_TYPE(
  3419. "mach-o-bind",
  3420. dbgs() << "BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM: "
  3421. << "SymbolName=" << SymbolName << "\n");
  3422. if (TableKind == Kind::Weak) {
  3423. if (ImmValue & MachO::BIND_SYMBOL_FLAGS_NON_WEAK_DEFINITION)
  3424. return;
  3425. }
  3426. break;
  3427. case MachO::BIND_OPCODE_SET_TYPE_IMM:
  3428. BindType = ImmValue;
  3429. if (ImmValue > MachO::BIND_TYPE_TEXT_PCREL32) {
  3430. *E = malformedError("for BIND_OPCODE_SET_TYPE_IMM bad bind type: " +
  3431. Twine((int)ImmValue) + " for opcode at: 0x" +
  3432. Twine::utohexstr(OpcodeStart - Opcodes.begin()));
  3433. moveToEnd();
  3434. return;
  3435. }
  3436. DEBUG_WITH_TYPE(
  3437. "mach-o-bind",
  3438. dbgs() << "BIND_OPCODE_SET_TYPE_IMM: "
  3439. << "BindType=" << (int)BindType << "\n");
  3440. break;
  3441. case MachO::BIND_OPCODE_SET_ADDEND_SLEB:
  3442. Addend = readSLEB128(&error);
  3443. if (error) {
  3444. *E = malformedError("for BIND_OPCODE_SET_ADDEND_SLEB " + Twine(error) +
  3445. " for opcode at: 0x" +
  3446. Twine::utohexstr(OpcodeStart - Opcodes.begin()));
  3447. moveToEnd();
  3448. return;
  3449. }
  3450. DEBUG_WITH_TYPE(
  3451. "mach-o-bind",
  3452. dbgs() << "BIND_OPCODE_SET_ADDEND_SLEB: "
  3453. << "Addend=" << Addend << "\n");
  3454. break;
  3455. case MachO::BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB:
  3456. SegmentIndex = ImmValue;
  3457. SegmentOffset = readULEB128(&error);
  3458. if (error) {
  3459. *E = malformedError("for BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB " +
  3460. Twine(error) + " for opcode at: 0x" +
  3461. Twine::utohexstr(OpcodeStart - Opcodes.begin()));
  3462. moveToEnd();
  3463. return;
  3464. }
  3465. error = O->BindEntryCheckSegAndOffsets(SegmentIndex, SegmentOffset,
  3466. PointerSize);
  3467. if (error) {
  3468. *E = malformedError("for BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB " +
  3469. Twine(error) + " for opcode at: 0x" +
  3470. Twine::utohexstr(OpcodeStart - Opcodes.begin()));
  3471. moveToEnd();
  3472. return;
  3473. }
  3474. DEBUG_WITH_TYPE(
  3475. "mach-o-bind",
  3476. dbgs() << "BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB: "
  3477. << "SegmentIndex=" << SegmentIndex << ", "
  3478. << format("SegmentOffset=0x%06X", SegmentOffset)
  3479. << "\n");
  3480. break;
  3481. case MachO::BIND_OPCODE_ADD_ADDR_ULEB:
  3482. SegmentOffset += readULEB128(&error);
  3483. if (error) {
  3484. *E = malformedError("for BIND_OPCODE_ADD_ADDR_ULEB " + Twine(error) +
  3485. " for opcode at: 0x" +
  3486. Twine::utohexstr(OpcodeStart - Opcodes.begin()));
  3487. moveToEnd();
  3488. return;
  3489. }
  3490. error = O->BindEntryCheckSegAndOffsets(SegmentIndex, SegmentOffset,
  3491. PointerSize);
  3492. if (error) {
  3493. *E = malformedError("for BIND_OPCODE_ADD_ADDR_ULEB " + Twine(error) +
  3494. " for opcode at: 0x" +
  3495. Twine::utohexstr(OpcodeStart - Opcodes.begin()));
  3496. moveToEnd();
  3497. return;
  3498. }
  3499. DEBUG_WITH_TYPE("mach-o-bind",
  3500. dbgs() << "BIND_OPCODE_ADD_ADDR_ULEB: "
  3501. << format("SegmentOffset=0x%06X",
  3502. SegmentOffset) << "\n");
  3503. break;
  3504. case MachO::BIND_OPCODE_DO_BIND:
  3505. AdvanceAmount = PointerSize;
  3506. RemainingLoopCount = 0;
  3507. error = O->BindEntryCheckSegAndOffsets(SegmentIndex, SegmentOffset,
  3508. PointerSize);
  3509. if (error) {
  3510. *E = malformedError("for BIND_OPCODE_DO_BIND " + Twine(error) +
  3511. " for opcode at: 0x" +
  3512. Twine::utohexstr(OpcodeStart - Opcodes.begin()));
  3513. moveToEnd();
  3514. return;
  3515. }
  3516. if (SymbolName == StringRef()) {
  3517. *E = malformedError(
  3518. "for BIND_OPCODE_DO_BIND missing preceding "
  3519. "BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM for opcode at: 0x" +
  3520. Twine::utohexstr(OpcodeStart - Opcodes.begin()));
  3521. moveToEnd();
  3522. return;
  3523. }
  3524. if (!LibraryOrdinalSet && TableKind != Kind::Weak) {
  3525. *E =
  3526. malformedError("for BIND_OPCODE_DO_BIND missing preceding "
  3527. "BIND_OPCODE_SET_DYLIB_ORDINAL_* for opcode at: 0x" +
  3528. Twine::utohexstr(OpcodeStart - Opcodes.begin()));
  3529. moveToEnd();
  3530. return;
  3531. }
  3532. DEBUG_WITH_TYPE("mach-o-bind",
  3533. dbgs() << "BIND_OPCODE_DO_BIND: "
  3534. << format("SegmentOffset=0x%06X",
  3535. SegmentOffset) << "\n");
  3536. return;
  3537. case MachO::BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB:
  3538. if (TableKind == Kind::Lazy) {
  3539. *E = malformedError("BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB not allowed in "
  3540. "lazy bind table for opcode at: 0x" +
  3541. Twine::utohexstr(OpcodeStart - Opcodes.begin()));
  3542. moveToEnd();
  3543. return;
  3544. }
  3545. error = O->BindEntryCheckSegAndOffsets(SegmentIndex, SegmentOffset,
  3546. PointerSize);
  3547. if (error) {
  3548. *E = malformedError("for BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB " +
  3549. Twine(error) + " for opcode at: 0x" +
  3550. Twine::utohexstr(OpcodeStart - Opcodes.begin()));
  3551. moveToEnd();
  3552. return;
  3553. }
  3554. if (SymbolName == StringRef()) {
  3555. *E = malformedError(
  3556. "for BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB missing "
  3557. "preceding BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM for opcode "
  3558. "at: 0x" +
  3559. Twine::utohexstr(OpcodeStart - Opcodes.begin()));
  3560. moveToEnd();
  3561. return;
  3562. }
  3563. if (!LibraryOrdinalSet && TableKind != Kind::Weak) {
  3564. *E = malformedError(
  3565. "for BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB missing "
  3566. "preceding BIND_OPCODE_SET_DYLIB_ORDINAL_* for opcode at: 0x" +
  3567. Twine::utohexstr(OpcodeStart - Opcodes.begin()));
  3568. moveToEnd();
  3569. return;
  3570. }
  3571. AdvanceAmount = readULEB128(&error) + PointerSize;
  3572. if (error) {
  3573. *E = malformedError("for BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB " +
  3574. Twine(error) + " for opcode at: 0x" +
  3575. Twine::utohexstr(OpcodeStart - Opcodes.begin()));
  3576. moveToEnd();
  3577. return;
  3578. }
  3579. // Note, this is not really an error until the next bind but make no sense
  3580. // for a BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB to not be followed by another
  3581. // bind operation.
  3582. error = O->BindEntryCheckSegAndOffsets(SegmentIndex, SegmentOffset +
  3583. AdvanceAmount, PointerSize);
  3584. if (error) {
  3585. *E = malformedError("for BIND_OPCODE_ADD_ADDR_ULEB (after adding "
  3586. "ULEB) " +
  3587. Twine(error) + " for opcode at: 0x" +
  3588. Twine::utohexstr(OpcodeStart - Opcodes.begin()));
  3589. moveToEnd();
  3590. return;
  3591. }
  3592. RemainingLoopCount = 0;
  3593. DEBUG_WITH_TYPE(
  3594. "mach-o-bind",
  3595. dbgs() << "BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB: "
  3596. << format("SegmentOffset=0x%06X", SegmentOffset)
  3597. << ", AdvanceAmount=" << AdvanceAmount
  3598. << ", RemainingLoopCount=" << RemainingLoopCount
  3599. << "\n");
  3600. return;
  3601. case MachO::BIND_OPCODE_DO_BIND_ADD_ADDR_IMM_SCALED:
  3602. if (TableKind == Kind::Lazy) {
  3603. *E = malformedError("BIND_OPCODE_DO_BIND_ADD_ADDR_IMM_SCALED not "
  3604. "allowed in lazy bind table for opcode at: 0x" +
  3605. Twine::utohexstr(OpcodeStart - Opcodes.begin()));
  3606. moveToEnd();
  3607. return;
  3608. }
  3609. if (SymbolName == StringRef()) {
  3610. *E = malformedError(
  3611. "for BIND_OPCODE_DO_BIND_ADD_ADDR_IMM_SCALED "
  3612. "missing preceding BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM for "
  3613. "opcode at: 0x" +
  3614. Twine::utohexstr(OpcodeStart - Opcodes.begin()));
  3615. moveToEnd();
  3616. return;
  3617. }
  3618. if (!LibraryOrdinalSet && TableKind != Kind::Weak) {
  3619. *E = malformedError(
  3620. "for BIND_OPCODE_DO_BIND_ADD_ADDR_IMM_SCALED "
  3621. "missing preceding BIND_OPCODE_SET_DYLIB_ORDINAL_* for opcode "
  3622. "at: 0x" +
  3623. Twine::utohexstr(OpcodeStart - Opcodes.begin()));
  3624. moveToEnd();
  3625. return;
  3626. }
  3627. AdvanceAmount = ImmValue * PointerSize + PointerSize;
  3628. RemainingLoopCount = 0;
  3629. error = O->BindEntryCheckSegAndOffsets(SegmentIndex, SegmentOffset +
  3630. AdvanceAmount, PointerSize);
  3631. if (error) {
  3632. *E = malformedError("for BIND_OPCODE_DO_BIND_ADD_ADDR_IMM_SCALED " +
  3633. Twine(error) + " for opcode at: 0x" +
  3634. Twine::utohexstr(OpcodeStart - Opcodes.begin()));
  3635. moveToEnd();
  3636. return;
  3637. }
  3638. DEBUG_WITH_TYPE("mach-o-bind",
  3639. dbgs()
  3640. << "BIND_OPCODE_DO_BIND_ADD_ADDR_IMM_SCALED: "
  3641. << format("SegmentOffset=0x%06X", SegmentOffset) << "\n");
  3642. return;
  3643. case MachO::BIND_OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB:
  3644. if (TableKind == Kind::Lazy) {
  3645. *E = malformedError("BIND_OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB not "
  3646. "allowed in lazy bind table for opcode at: 0x" +
  3647. Twine::utohexstr(OpcodeStart - Opcodes.begin()));
  3648. moveToEnd();
  3649. return;
  3650. }
  3651. Count = readULEB128(&error);
  3652. if (Count != 0)
  3653. RemainingLoopCount = Count - 1;
  3654. else
  3655. RemainingLoopCount = 0;
  3656. if (error) {
  3657. *E = malformedError("for BIND_OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB "
  3658. " (count value) " +
  3659. Twine(error) + " for opcode at: 0x" +
  3660. Twine::utohexstr(OpcodeStart - Opcodes.begin()));
  3661. moveToEnd();
  3662. return;
  3663. }
  3664. Skip = readULEB128(&error);
  3665. AdvanceAmount = Skip + PointerSize;
  3666. if (error) {
  3667. *E = malformedError("for BIND_OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB "
  3668. " (skip value) " +
  3669. Twine(error) + " for opcode at: 0x" +
  3670. Twine::utohexstr(OpcodeStart - Opcodes.begin()));
  3671. moveToEnd();
  3672. return;
  3673. }
  3674. if (SymbolName == StringRef()) {
  3675. *E = malformedError(
  3676. "for BIND_OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB "
  3677. "missing preceding BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM for "
  3678. "opcode at: 0x" +
  3679. Twine::utohexstr(OpcodeStart - Opcodes.begin()));
  3680. moveToEnd();
  3681. return;
  3682. }
  3683. if (!LibraryOrdinalSet && TableKind != Kind::Weak) {
  3684. *E = malformedError(
  3685. "for BIND_OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB "
  3686. "missing preceding BIND_OPCODE_SET_DYLIB_ORDINAL_* for opcode "
  3687. "at: 0x" +
  3688. Twine::utohexstr(OpcodeStart - Opcodes.begin()));
  3689. moveToEnd();
  3690. return;
  3691. }
  3692. error = O->BindEntryCheckSegAndOffsets(SegmentIndex, SegmentOffset,
  3693. PointerSize, Count, Skip);
  3694. if (error) {
  3695. *E =
  3696. malformedError("for BIND_OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB " +
  3697. Twine(error) + " for opcode at: 0x" +
  3698. Twine::utohexstr(OpcodeStart - Opcodes.begin()));
  3699. moveToEnd();
  3700. return;
  3701. }
  3702. DEBUG_WITH_TYPE(
  3703. "mach-o-bind",
  3704. dbgs() << "BIND_OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB: "
  3705. << format("SegmentOffset=0x%06X", SegmentOffset)
  3706. << ", AdvanceAmount=" << AdvanceAmount
  3707. << ", RemainingLoopCount=" << RemainingLoopCount
  3708. << "\n");
  3709. return;
  3710. default:
  3711. *E = malformedError("bad bind info (bad opcode value 0x" +
  3712. Twine::utohexstr(Opcode) + " for opcode at: 0x" +
  3713. Twine::utohexstr(OpcodeStart - Opcodes.begin()));
  3714. moveToEnd();
  3715. return;
  3716. }
  3717. }
  3718. }
  3719. uint64_t MachOBindEntry::readULEB128(const char **error) {
  3720. unsigned Count;
  3721. uint64_t Result = decodeULEB128(Ptr, &Count, Opcodes.end(), error);
  3722. Ptr += Count;
  3723. if (Ptr > Opcodes.end())
  3724. Ptr = Opcodes.end();
  3725. return Result;
  3726. }
  3727. int64_t MachOBindEntry::readSLEB128(const char **error) {
  3728. unsigned Count;
  3729. int64_t Result = decodeSLEB128(Ptr, &Count, Opcodes.end(), error);
  3730. Ptr += Count;
  3731. if (Ptr > Opcodes.end())
  3732. Ptr = Opcodes.end();
  3733. return Result;
  3734. }
  3735. int32_t MachOBindEntry::segmentIndex() const { return SegmentIndex; }
  3736. uint64_t MachOBindEntry::segmentOffset() const { return SegmentOffset; }
  3737. StringRef MachOBindEntry::typeName() const {
  3738. switch (BindType) {
  3739. case MachO::BIND_TYPE_POINTER:
  3740. return "pointer";
  3741. case MachO::BIND_TYPE_TEXT_ABSOLUTE32:
  3742. return "text abs32";
  3743. case MachO::BIND_TYPE_TEXT_PCREL32:
  3744. return "text rel32";
  3745. }
  3746. return "unknown";
  3747. }
  3748. StringRef MachOBindEntry::symbolName() const { return SymbolName; }
  3749. int64_t MachOBindEntry::addend() const { return Addend; }
  3750. uint32_t MachOBindEntry::flags() const { return Flags; }
  3751. int MachOBindEntry::ordinal() const { return Ordinal; }
  3752. // For use with the SegIndex of a checked Mach-O Bind entry
  3753. // to get the segment name.
  3754. StringRef MachOBindEntry::segmentName() const {
  3755. return O->BindRebaseSegmentName(SegmentIndex);
  3756. }
  3757. // For use with a SegIndex,SegOffset pair from a checked Mach-O Bind entry
  3758. // to get the section name.
  3759. StringRef MachOBindEntry::sectionName() const {
  3760. return O->BindRebaseSectionName(SegmentIndex, SegmentOffset);
  3761. }
  3762. // For use with a SegIndex,SegOffset pair from a checked Mach-O Bind entry
  3763. // to get the address.
  3764. uint64_t MachOBindEntry::address() const {
  3765. return O->BindRebaseAddress(SegmentIndex, SegmentOffset);
  3766. }
  3767. bool MachOBindEntry::operator==(const MachOBindEntry &Other) const {
  3768. #ifdef EXPENSIVE_CHECKS
  3769. assert(Opcodes == Other.Opcodes && "compare iterators of different files");
  3770. #else
  3771. assert(Opcodes.data() == Other.Opcodes.data() && "compare iterators of different files");
  3772. #endif
  3773. return (Ptr == Other.Ptr) &&
  3774. (RemainingLoopCount == Other.RemainingLoopCount) &&
  3775. (Done == Other.Done);
  3776. }
  3777. // Build table of sections so SegIndex/SegOffset pairs can be translated.
  3778. BindRebaseSegInfo::BindRebaseSegInfo(const object::MachOObjectFile *Obj) {
  3779. uint32_t CurSegIndex = Obj->hasPageZeroSegment() ? 1 : 0;
  3780. StringRef CurSegName;
  3781. uint64_t CurSegAddress;
  3782. for (const SectionRef &Section : Obj->sections()) {
  3783. SectionInfo Info;
  3784. Expected<StringRef> NameOrErr = Section.getName();
  3785. if (!NameOrErr)
  3786. consumeError(NameOrErr.takeError());
  3787. else
  3788. Info.SectionName = *NameOrErr;
  3789. Info.Address = Section.getAddress();
  3790. Info.Size = Section.getSize();
  3791. Info.SegmentName =
  3792. Obj->getSectionFinalSegmentName(Section.getRawDataRefImpl());
  3793. if (!Info.SegmentName.equals(CurSegName)) {
  3794. ++CurSegIndex;
  3795. CurSegName = Info.SegmentName;
  3796. CurSegAddress = Info.Address;
  3797. }
  3798. Info.SegmentIndex = CurSegIndex - 1;
  3799. Info.OffsetInSegment = Info.Address - CurSegAddress;
  3800. Info.SegmentStartAddress = CurSegAddress;
  3801. Sections.push_back(Info);
  3802. }
  3803. MaxSegIndex = CurSegIndex;
  3804. }
  3805. // For use with a SegIndex, SegOffset, and PointerSize triple in
  3806. // MachOBindEntry::moveNext() to validate a MachOBindEntry or MachORebaseEntry.
  3807. //
  3808. // Given a SegIndex, SegOffset, and PointerSize, verify a valid section exists
  3809. // that fully contains a pointer at that location. Multiple fixups in a bind
  3810. // (such as with the BIND_OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB opcode) can
  3811. // be tested via the Count and Skip parameters.
  3812. const char * BindRebaseSegInfo::checkSegAndOffsets(int32_t SegIndex,
  3813. uint64_t SegOffset,
  3814. uint8_t PointerSize,
  3815. uint32_t Count,
  3816. uint32_t Skip) {
  3817. if (SegIndex == -1)
  3818. return "missing preceding *_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB";
  3819. if (SegIndex >= MaxSegIndex)
  3820. return "bad segIndex (too large)";
  3821. for (uint32_t i = 0; i < Count; ++i) {
  3822. uint32_t Start = SegOffset + i * (PointerSize + Skip);
  3823. uint32_t End = Start + PointerSize;
  3824. bool Found = false;
  3825. for (const SectionInfo &SI : Sections) {
  3826. if (SI.SegmentIndex != SegIndex)
  3827. continue;
  3828. if ((SI.OffsetInSegment<=Start) && (Start<(SI.OffsetInSegment+SI.Size))) {
  3829. if (End <= SI.OffsetInSegment + SI.Size) {
  3830. Found = true;
  3831. break;
  3832. }
  3833. else
  3834. return "bad offset, extends beyond section boundary";
  3835. }
  3836. }
  3837. if (!Found)
  3838. return "bad offset, not in section";
  3839. }
  3840. return nullptr;
  3841. }
  3842. // For use with the SegIndex of a checked Mach-O Bind or Rebase entry
  3843. // to get the segment name.
  3844. StringRef BindRebaseSegInfo::segmentName(int32_t SegIndex) {
  3845. for (const SectionInfo &SI : Sections) {
  3846. if (SI.SegmentIndex == SegIndex)
  3847. return SI.SegmentName;
  3848. }
  3849. llvm_unreachable("invalid SegIndex");
  3850. }
  3851. // For use with a SegIndex,SegOffset pair from a checked Mach-O Bind or Rebase
  3852. // to get the SectionInfo.
  3853. const BindRebaseSegInfo::SectionInfo &BindRebaseSegInfo::findSection(
  3854. int32_t SegIndex, uint64_t SegOffset) {
  3855. for (const SectionInfo &SI : Sections) {
  3856. if (SI.SegmentIndex != SegIndex)
  3857. continue;
  3858. if (SI.OffsetInSegment > SegOffset)
  3859. continue;
  3860. if (SegOffset >= (SI.OffsetInSegment + SI.Size))
  3861. continue;
  3862. return SI;
  3863. }
  3864. llvm_unreachable("SegIndex and SegOffset not in any section");
  3865. }
  3866. // For use with a SegIndex,SegOffset pair from a checked Mach-O Bind or Rebase
  3867. // entry to get the section name.
  3868. StringRef BindRebaseSegInfo::sectionName(int32_t SegIndex,
  3869. uint64_t SegOffset) {
  3870. return findSection(SegIndex, SegOffset).SectionName;
  3871. }
  3872. // For use with a SegIndex,SegOffset pair from a checked Mach-O Bind or Rebase
  3873. // entry to get the address.
  3874. uint64_t BindRebaseSegInfo::address(uint32_t SegIndex, uint64_t OffsetInSeg) {
  3875. const SectionInfo &SI = findSection(SegIndex, OffsetInSeg);
  3876. return SI.SegmentStartAddress + OffsetInSeg;
  3877. }
  3878. iterator_range<bind_iterator>
  3879. MachOObjectFile::bindTable(Error &Err, MachOObjectFile *O,
  3880. ArrayRef<uint8_t> Opcodes, bool is64,
  3881. MachOBindEntry::Kind BKind) {
  3882. if (O->BindRebaseSectionTable == nullptr)
  3883. O->BindRebaseSectionTable = std::make_unique<BindRebaseSegInfo>(O);
  3884. MachOBindEntry Start(&Err, O, Opcodes, is64, BKind);
  3885. Start.moveToFirst();
  3886. MachOBindEntry Finish(&Err, O, Opcodes, is64, BKind);
  3887. Finish.moveToEnd();
  3888. return make_range(bind_iterator(Start), bind_iterator(Finish));
  3889. }
  3890. iterator_range<bind_iterator> MachOObjectFile::bindTable(Error &Err) {
  3891. return bindTable(Err, this, getDyldInfoBindOpcodes(), is64Bit(),
  3892. MachOBindEntry::Kind::Regular);
  3893. }
  3894. iterator_range<bind_iterator> MachOObjectFile::lazyBindTable(Error &Err) {
  3895. return bindTable(Err, this, getDyldInfoLazyBindOpcodes(), is64Bit(),
  3896. MachOBindEntry::Kind::Lazy);
  3897. }
  3898. iterator_range<bind_iterator> MachOObjectFile::weakBindTable(Error &Err) {
  3899. return bindTable(Err, this, getDyldInfoWeakBindOpcodes(), is64Bit(),
  3900. MachOBindEntry::Kind::Weak);
  3901. }
  3902. MachOObjectFile::load_command_iterator
  3903. MachOObjectFile::begin_load_commands() const {
  3904. return LoadCommands.begin();
  3905. }
  3906. MachOObjectFile::load_command_iterator
  3907. MachOObjectFile::end_load_commands() const {
  3908. return LoadCommands.end();
  3909. }
  3910. iterator_range<MachOObjectFile::load_command_iterator>
  3911. MachOObjectFile::load_commands() const {
  3912. return make_range(begin_load_commands(), end_load_commands());
  3913. }
  3914. StringRef
  3915. MachOObjectFile::getSectionFinalSegmentName(DataRefImpl Sec) const {
  3916. ArrayRef<char> Raw = getSectionRawFinalSegmentName(Sec);
  3917. return parseSegmentOrSectionName(Raw.data());
  3918. }
  3919. ArrayRef<char>
  3920. MachOObjectFile::getSectionRawName(DataRefImpl Sec) const {
  3921. assert(Sec.d.a < Sections.size() && "Should have detected this earlier");
  3922. const section_base *Base =
  3923. reinterpret_cast<const section_base *>(Sections[Sec.d.a]);
  3924. return makeArrayRef(Base->sectname);
  3925. }
  3926. ArrayRef<char>
  3927. MachOObjectFile::getSectionRawFinalSegmentName(DataRefImpl Sec) const {
  3928. assert(Sec.d.a < Sections.size() && "Should have detected this earlier");
  3929. const section_base *Base =
  3930. reinterpret_cast<const section_base *>(Sections[Sec.d.a]);
  3931. return makeArrayRef(Base->segname);
  3932. }
  3933. bool
  3934. MachOObjectFile::isRelocationScattered(const MachO::any_relocation_info &RE)
  3935. const {
  3936. if (getCPUType(*this) == MachO::CPU_TYPE_X86_64)
  3937. return false;
  3938. return getPlainRelocationAddress(RE) & MachO::R_SCATTERED;
  3939. }
  3940. unsigned MachOObjectFile::getPlainRelocationSymbolNum(
  3941. const MachO::any_relocation_info &RE) const {
  3942. if (isLittleEndian())
  3943. return RE.r_word1 & 0xffffff;
  3944. return RE.r_word1 >> 8;
  3945. }
  3946. bool MachOObjectFile::getPlainRelocationExternal(
  3947. const MachO::any_relocation_info &RE) const {
  3948. if (isLittleEndian())
  3949. return (RE.r_word1 >> 27) & 1;
  3950. return (RE.r_word1 >> 4) & 1;
  3951. }
  3952. bool MachOObjectFile::getScatteredRelocationScattered(
  3953. const MachO::any_relocation_info &RE) const {
  3954. return RE.r_word0 >> 31;
  3955. }
  3956. uint32_t MachOObjectFile::getScatteredRelocationValue(
  3957. const MachO::any_relocation_info &RE) const {
  3958. return RE.r_word1;
  3959. }
  3960. uint32_t MachOObjectFile::getScatteredRelocationType(
  3961. const MachO::any_relocation_info &RE) const {
  3962. return (RE.r_word0 >> 24) & 0xf;
  3963. }
  3964. unsigned MachOObjectFile::getAnyRelocationAddress(
  3965. const MachO::any_relocation_info &RE) const {
  3966. if (isRelocationScattered(RE))
  3967. return getScatteredRelocationAddress(RE);
  3968. return getPlainRelocationAddress(RE);
  3969. }
  3970. unsigned MachOObjectFile::getAnyRelocationPCRel(
  3971. const MachO::any_relocation_info &RE) const {
  3972. if (isRelocationScattered(RE))
  3973. return getScatteredRelocationPCRel(RE);
  3974. return getPlainRelocationPCRel(*this, RE);
  3975. }
  3976. unsigned MachOObjectFile::getAnyRelocationLength(
  3977. const MachO::any_relocation_info &RE) const {
  3978. if (isRelocationScattered(RE))
  3979. return getScatteredRelocationLength(RE);
  3980. return getPlainRelocationLength(*this, RE);
  3981. }
  3982. unsigned
  3983. MachOObjectFile::getAnyRelocationType(
  3984. const MachO::any_relocation_info &RE) const {
  3985. if (isRelocationScattered(RE))
  3986. return getScatteredRelocationType(RE);
  3987. return getPlainRelocationType(*this, RE);
  3988. }
  3989. SectionRef
  3990. MachOObjectFile::getAnyRelocationSection(
  3991. const MachO::any_relocation_info &RE) const {
  3992. if (isRelocationScattered(RE) || getPlainRelocationExternal(RE))
  3993. return *section_end();
  3994. unsigned SecNum = getPlainRelocationSymbolNum(RE);
  3995. if (SecNum == MachO::R_ABS || SecNum > Sections.size())
  3996. return *section_end();
  3997. DataRefImpl DRI;
  3998. DRI.d.a = SecNum - 1;
  3999. return SectionRef(DRI, this);
  4000. }
  4001. MachO::section MachOObjectFile::getSection(DataRefImpl DRI) const {
  4002. assert(DRI.d.a < Sections.size() && "Should have detected this earlier");
  4003. return getStruct<MachO::section>(*this, Sections[DRI.d.a]);
  4004. }
  4005. MachO::section_64 MachOObjectFile::getSection64(DataRefImpl DRI) const {
  4006. assert(DRI.d.a < Sections.size() && "Should have detected this earlier");
  4007. return getStruct<MachO::section_64>(*this, Sections[DRI.d.a]);
  4008. }
  4009. MachO::section MachOObjectFile::getSection(const LoadCommandInfo &L,
  4010. unsigned Index) const {
  4011. const char *Sec = getSectionPtr(*this, L, Index);
  4012. return getStruct<MachO::section>(*this, Sec);
  4013. }
  4014. MachO::section_64 MachOObjectFile::getSection64(const LoadCommandInfo &L,
  4015. unsigned Index) const {
  4016. const char *Sec = getSectionPtr(*this, L, Index);
  4017. return getStruct<MachO::section_64>(*this, Sec);
  4018. }
  4019. MachO::nlist
  4020. MachOObjectFile::getSymbolTableEntry(DataRefImpl DRI) const {
  4021. const char *P = reinterpret_cast<const char *>(DRI.p);
  4022. return getStruct<MachO::nlist>(*this, P);
  4023. }
  4024. MachO::nlist_64
  4025. MachOObjectFile::getSymbol64TableEntry(DataRefImpl DRI) const {
  4026. const char *P = reinterpret_cast<const char *>(DRI.p);
  4027. return getStruct<MachO::nlist_64>(*this, P);
  4028. }
  4029. MachO::linkedit_data_command
  4030. MachOObjectFile::getLinkeditDataLoadCommand(const LoadCommandInfo &L) const {
  4031. return getStruct<MachO::linkedit_data_command>(*this, L.Ptr);
  4032. }
  4033. MachO::segment_command
  4034. MachOObjectFile::getSegmentLoadCommand(const LoadCommandInfo &L) const {
  4035. return getStruct<MachO::segment_command>(*this, L.Ptr);
  4036. }
  4037. MachO::segment_command_64
  4038. MachOObjectFile::getSegment64LoadCommand(const LoadCommandInfo &L) const {
  4039. return getStruct<MachO::segment_command_64>(*this, L.Ptr);
  4040. }
  4041. MachO::linker_option_command
  4042. MachOObjectFile::getLinkerOptionLoadCommand(const LoadCommandInfo &L) const {
  4043. return getStruct<MachO::linker_option_command>(*this, L.Ptr);
  4044. }
  4045. MachO::version_min_command
  4046. MachOObjectFile::getVersionMinLoadCommand(const LoadCommandInfo &L) const {
  4047. return getStruct<MachO::version_min_command>(*this, L.Ptr);
  4048. }
  4049. MachO::note_command
  4050. MachOObjectFile::getNoteLoadCommand(const LoadCommandInfo &L) const {
  4051. return getStruct<MachO::note_command>(*this, L.Ptr);
  4052. }
  4053. MachO::build_version_command
  4054. MachOObjectFile::getBuildVersionLoadCommand(const LoadCommandInfo &L) const {
  4055. return getStruct<MachO::build_version_command>(*this, L.Ptr);
  4056. }
  4057. MachO::build_tool_version
  4058. MachOObjectFile::getBuildToolVersion(unsigned index) const {
  4059. return getStruct<MachO::build_tool_version>(*this, BuildTools[index]);
  4060. }
  4061. MachO::dylib_command
  4062. MachOObjectFile::getDylibIDLoadCommand(const LoadCommandInfo &L) const {
  4063. return getStruct<MachO::dylib_command>(*this, L.Ptr);
  4064. }
  4065. MachO::dyld_info_command
  4066. MachOObjectFile::getDyldInfoLoadCommand(const LoadCommandInfo &L) const {
  4067. return getStruct<MachO::dyld_info_command>(*this, L.Ptr);
  4068. }
  4069. MachO::dylinker_command
  4070. MachOObjectFile::getDylinkerCommand(const LoadCommandInfo &L) const {
  4071. return getStruct<MachO::dylinker_command>(*this, L.Ptr);
  4072. }
  4073. MachO::uuid_command
  4074. MachOObjectFile::getUuidCommand(const LoadCommandInfo &L) const {
  4075. return getStruct<MachO::uuid_command>(*this, L.Ptr);
  4076. }
  4077. MachO::rpath_command
  4078. MachOObjectFile::getRpathCommand(const LoadCommandInfo &L) const {
  4079. return getStruct<MachO::rpath_command>(*this, L.Ptr);
  4080. }
  4081. MachO::source_version_command
  4082. MachOObjectFile::getSourceVersionCommand(const LoadCommandInfo &L) const {
  4083. return getStruct<MachO::source_version_command>(*this, L.Ptr);
  4084. }
  4085. MachO::entry_point_command
  4086. MachOObjectFile::getEntryPointCommand(const LoadCommandInfo &L) const {
  4087. return getStruct<MachO::entry_point_command>(*this, L.Ptr);
  4088. }
  4089. MachO::encryption_info_command
  4090. MachOObjectFile::getEncryptionInfoCommand(const LoadCommandInfo &L) const {
  4091. return getStruct<MachO::encryption_info_command>(*this, L.Ptr);
  4092. }
  4093. MachO::encryption_info_command_64
  4094. MachOObjectFile::getEncryptionInfoCommand64(const LoadCommandInfo &L) const {
  4095. return getStruct<MachO::encryption_info_command_64>(*this, L.Ptr);
  4096. }
  4097. MachO::sub_framework_command
  4098. MachOObjectFile::getSubFrameworkCommand(const LoadCommandInfo &L) const {
  4099. return getStruct<MachO::sub_framework_command>(*this, L.Ptr);
  4100. }
  4101. MachO::sub_umbrella_command
  4102. MachOObjectFile::getSubUmbrellaCommand(const LoadCommandInfo &L) const {
  4103. return getStruct<MachO::sub_umbrella_command>(*this, L.Ptr);
  4104. }
  4105. MachO::sub_library_command
  4106. MachOObjectFile::getSubLibraryCommand(const LoadCommandInfo &L) const {
  4107. return getStruct<MachO::sub_library_command>(*this, L.Ptr);
  4108. }
  4109. MachO::sub_client_command
  4110. MachOObjectFile::getSubClientCommand(const LoadCommandInfo &L) const {
  4111. return getStruct<MachO::sub_client_command>(*this, L.Ptr);
  4112. }
  4113. MachO::routines_command
  4114. MachOObjectFile::getRoutinesCommand(const LoadCommandInfo &L) const {
  4115. return getStruct<MachO::routines_command>(*this, L.Ptr);
  4116. }
  4117. MachO::routines_command_64
  4118. MachOObjectFile::getRoutinesCommand64(const LoadCommandInfo &L) const {
  4119. return getStruct<MachO::routines_command_64>(*this, L.Ptr);
  4120. }
  4121. MachO::thread_command
  4122. MachOObjectFile::getThreadCommand(const LoadCommandInfo &L) const {
  4123. return getStruct<MachO::thread_command>(*this, L.Ptr);
  4124. }
  4125. MachO::any_relocation_info
  4126. MachOObjectFile::getRelocation(DataRefImpl Rel) const {
  4127. uint32_t Offset;
  4128. if (getHeader().filetype == MachO::MH_OBJECT) {
  4129. DataRefImpl Sec;
  4130. Sec.d.a = Rel.d.a;
  4131. if (is64Bit()) {
  4132. MachO::section_64 Sect = getSection64(Sec);
  4133. Offset = Sect.reloff;
  4134. } else {
  4135. MachO::section Sect = getSection(Sec);
  4136. Offset = Sect.reloff;
  4137. }
  4138. } else {
  4139. MachO::dysymtab_command DysymtabLoadCmd = getDysymtabLoadCommand();
  4140. if (Rel.d.a == 0)
  4141. Offset = DysymtabLoadCmd.extreloff; // Offset to the external relocations
  4142. else
  4143. Offset = DysymtabLoadCmd.locreloff; // Offset to the local relocations
  4144. }
  4145. auto P = reinterpret_cast<const MachO::any_relocation_info *>(
  4146. getPtr(*this, Offset)) + Rel.d.b;
  4147. return getStruct<MachO::any_relocation_info>(
  4148. *this, reinterpret_cast<const char *>(P));
  4149. }
  4150. MachO::data_in_code_entry
  4151. MachOObjectFile::getDice(DataRefImpl Rel) const {
  4152. const char *P = reinterpret_cast<const char *>(Rel.p);
  4153. return getStruct<MachO::data_in_code_entry>(*this, P);
  4154. }
  4155. const MachO::mach_header &MachOObjectFile::getHeader() const {
  4156. return Header;
  4157. }
  4158. const MachO::mach_header_64 &MachOObjectFile::getHeader64() const {
  4159. assert(is64Bit());
  4160. return Header64;
  4161. }
  4162. uint32_t MachOObjectFile::getIndirectSymbolTableEntry(
  4163. const MachO::dysymtab_command &DLC,
  4164. unsigned Index) const {
  4165. uint64_t Offset = DLC.indirectsymoff + Index * sizeof(uint32_t);
  4166. return getStruct<uint32_t>(*this, getPtr(*this, Offset));
  4167. }
  4168. MachO::data_in_code_entry
  4169. MachOObjectFile::getDataInCodeTableEntry(uint32_t DataOffset,
  4170. unsigned Index) const {
  4171. uint64_t Offset = DataOffset + Index * sizeof(MachO::data_in_code_entry);
  4172. return getStruct<MachO::data_in_code_entry>(*this, getPtr(*this, Offset));
  4173. }
  4174. MachO::symtab_command MachOObjectFile::getSymtabLoadCommand() const {
  4175. if (SymtabLoadCmd)
  4176. return getStruct<MachO::symtab_command>(*this, SymtabLoadCmd);
  4177. // If there is no SymtabLoadCmd return a load command with zero'ed fields.
  4178. MachO::symtab_command Cmd;
  4179. Cmd.cmd = MachO::LC_SYMTAB;
  4180. Cmd.cmdsize = sizeof(MachO::symtab_command);
  4181. Cmd.symoff = 0;
  4182. Cmd.nsyms = 0;
  4183. Cmd.stroff = 0;
  4184. Cmd.strsize = 0;
  4185. return Cmd;
  4186. }
  4187. MachO::dysymtab_command MachOObjectFile::getDysymtabLoadCommand() const {
  4188. if (DysymtabLoadCmd)
  4189. return getStruct<MachO::dysymtab_command>(*this, DysymtabLoadCmd);
  4190. // If there is no DysymtabLoadCmd return a load command with zero'ed fields.
  4191. MachO::dysymtab_command Cmd;
  4192. Cmd.cmd = MachO::LC_DYSYMTAB;
  4193. Cmd.cmdsize = sizeof(MachO::dysymtab_command);
  4194. Cmd.ilocalsym = 0;
  4195. Cmd.nlocalsym = 0;
  4196. Cmd.iextdefsym = 0;
  4197. Cmd.nextdefsym = 0;
  4198. Cmd.iundefsym = 0;
  4199. Cmd.nundefsym = 0;
  4200. Cmd.tocoff = 0;
  4201. Cmd.ntoc = 0;
  4202. Cmd.modtaboff = 0;
  4203. Cmd.nmodtab = 0;
  4204. Cmd.extrefsymoff = 0;
  4205. Cmd.nextrefsyms = 0;
  4206. Cmd.indirectsymoff = 0;
  4207. Cmd.nindirectsyms = 0;
  4208. Cmd.extreloff = 0;
  4209. Cmd.nextrel = 0;
  4210. Cmd.locreloff = 0;
  4211. Cmd.nlocrel = 0;
  4212. return Cmd;
  4213. }
  4214. MachO::linkedit_data_command
  4215. MachOObjectFile::getDataInCodeLoadCommand() const {
  4216. if (DataInCodeLoadCmd)
  4217. return getStruct<MachO::linkedit_data_command>(*this, DataInCodeLoadCmd);
  4218. // If there is no DataInCodeLoadCmd return a load command with zero'ed fields.
  4219. MachO::linkedit_data_command Cmd;
  4220. Cmd.cmd = MachO::LC_DATA_IN_CODE;
  4221. Cmd.cmdsize = sizeof(MachO::linkedit_data_command);
  4222. Cmd.dataoff = 0;
  4223. Cmd.datasize = 0;
  4224. return Cmd;
  4225. }
  4226. MachO::linkedit_data_command
  4227. MachOObjectFile::getLinkOptHintsLoadCommand() const {
  4228. if (LinkOptHintsLoadCmd)
  4229. return getStruct<MachO::linkedit_data_command>(*this, LinkOptHintsLoadCmd);
  4230. // If there is no LinkOptHintsLoadCmd return a load command with zero'ed
  4231. // fields.
  4232. MachO::linkedit_data_command Cmd;
  4233. Cmd.cmd = MachO::LC_LINKER_OPTIMIZATION_HINT;
  4234. Cmd.cmdsize = sizeof(MachO::linkedit_data_command);
  4235. Cmd.dataoff = 0;
  4236. Cmd.datasize = 0;
  4237. return Cmd;
  4238. }
  4239. ArrayRef<uint8_t> MachOObjectFile::getDyldInfoRebaseOpcodes() const {
  4240. if (!DyldInfoLoadCmd)
  4241. return None;
  4242. auto DyldInfoOrErr =
  4243. getStructOrErr<MachO::dyld_info_command>(*this, DyldInfoLoadCmd);
  4244. if (!DyldInfoOrErr)
  4245. return None;
  4246. MachO::dyld_info_command DyldInfo = DyldInfoOrErr.get();
  4247. const uint8_t *Ptr =
  4248. reinterpret_cast<const uint8_t *>(getPtr(*this, DyldInfo.rebase_off));
  4249. return makeArrayRef(Ptr, DyldInfo.rebase_size);
  4250. }
  4251. ArrayRef<uint8_t> MachOObjectFile::getDyldInfoBindOpcodes() const {
  4252. if (!DyldInfoLoadCmd)
  4253. return None;
  4254. auto DyldInfoOrErr =
  4255. getStructOrErr<MachO::dyld_info_command>(*this, DyldInfoLoadCmd);
  4256. if (!DyldInfoOrErr)
  4257. return None;
  4258. MachO::dyld_info_command DyldInfo = DyldInfoOrErr.get();
  4259. const uint8_t *Ptr =
  4260. reinterpret_cast<const uint8_t *>(getPtr(*this, DyldInfo.bind_off));
  4261. return makeArrayRef(Ptr, DyldInfo.bind_size);
  4262. }
  4263. ArrayRef<uint8_t> MachOObjectFile::getDyldInfoWeakBindOpcodes() const {
  4264. if (!DyldInfoLoadCmd)
  4265. return None;
  4266. auto DyldInfoOrErr =
  4267. getStructOrErr<MachO::dyld_info_command>(*this, DyldInfoLoadCmd);
  4268. if (!DyldInfoOrErr)
  4269. return None;
  4270. MachO::dyld_info_command DyldInfo = DyldInfoOrErr.get();
  4271. const uint8_t *Ptr =
  4272. reinterpret_cast<const uint8_t *>(getPtr(*this, DyldInfo.weak_bind_off));
  4273. return makeArrayRef(Ptr, DyldInfo.weak_bind_size);
  4274. }
  4275. ArrayRef<uint8_t> MachOObjectFile::getDyldInfoLazyBindOpcodes() const {
  4276. if (!DyldInfoLoadCmd)
  4277. return None;
  4278. auto DyldInfoOrErr =
  4279. getStructOrErr<MachO::dyld_info_command>(*this, DyldInfoLoadCmd);
  4280. if (!DyldInfoOrErr)
  4281. return None;
  4282. MachO::dyld_info_command DyldInfo = DyldInfoOrErr.get();
  4283. const uint8_t *Ptr =
  4284. reinterpret_cast<const uint8_t *>(getPtr(*this, DyldInfo.lazy_bind_off));
  4285. return makeArrayRef(Ptr, DyldInfo.lazy_bind_size);
  4286. }
  4287. ArrayRef<uint8_t> MachOObjectFile::getDyldInfoExportsTrie() const {
  4288. if (!DyldInfoLoadCmd)
  4289. return None;
  4290. auto DyldInfoOrErr =
  4291. getStructOrErr<MachO::dyld_info_command>(*this, DyldInfoLoadCmd);
  4292. if (!DyldInfoOrErr)
  4293. return None;
  4294. MachO::dyld_info_command DyldInfo = DyldInfoOrErr.get();
  4295. const uint8_t *Ptr =
  4296. reinterpret_cast<const uint8_t *>(getPtr(*this, DyldInfo.export_off));
  4297. return makeArrayRef(Ptr, DyldInfo.export_size);
  4298. }
  4299. ArrayRef<uint8_t> MachOObjectFile::getUuid() const {
  4300. if (!UuidLoadCmd)
  4301. return None;
  4302. // Returning a pointer is fine as uuid doesn't need endian swapping.
  4303. const char *Ptr = UuidLoadCmd + offsetof(MachO::uuid_command, uuid);
  4304. return makeArrayRef(reinterpret_cast<const uint8_t *>(Ptr), 16);
  4305. }
  4306. StringRef MachOObjectFile::getStringTableData() const {
  4307. MachO::symtab_command S = getSymtabLoadCommand();
  4308. return getData().substr(S.stroff, S.strsize);
  4309. }
  4310. bool MachOObjectFile::is64Bit() const {
  4311. return getType() == getMachOType(false, true) ||
  4312. getType() == getMachOType(true, true);
  4313. }
  4314. void MachOObjectFile::ReadULEB128s(uint64_t Index,
  4315. SmallVectorImpl<uint64_t> &Out) const {
  4316. DataExtractor extractor(ObjectFile::getData(), true, 0);
  4317. uint64_t offset = Index;
  4318. uint64_t data = 0;
  4319. while (uint64_t delta = extractor.getULEB128(&offset)) {
  4320. data += delta;
  4321. Out.push_back(data);
  4322. }
  4323. }
  4324. bool MachOObjectFile::isRelocatableObject() const {
  4325. return getHeader().filetype == MachO::MH_OBJECT;
  4326. }
  4327. Expected<std::unique_ptr<MachOObjectFile>>
  4328. ObjectFile::createMachOObjectFile(MemoryBufferRef Buffer,
  4329. uint32_t UniversalCputype,
  4330. uint32_t UniversalIndex) {
  4331. StringRef Magic = Buffer.getBuffer().slice(0, 4);
  4332. if (Magic == "\xFE\xED\xFA\xCE")
  4333. return MachOObjectFile::create(Buffer, false, false,
  4334. UniversalCputype, UniversalIndex);
  4335. if (Magic == "\xCE\xFA\xED\xFE")
  4336. return MachOObjectFile::create(Buffer, true, false,
  4337. UniversalCputype, UniversalIndex);
  4338. if (Magic == "\xFE\xED\xFA\xCF")
  4339. return MachOObjectFile::create(Buffer, false, true,
  4340. UniversalCputype, UniversalIndex);
  4341. if (Magic == "\xCF\xFA\xED\xFE")
  4342. return MachOObjectFile::create(Buffer, true, true,
  4343. UniversalCputype, UniversalIndex);
  4344. return make_error<GenericBinaryError>("Unrecognized MachO magic number",
  4345. object_error::invalid_file_type);
  4346. }
  4347. StringRef MachOObjectFile::mapDebugSectionName(StringRef Name) const {
  4348. return StringSwitch<StringRef>(Name)
  4349. .Case("debug_str_offs", "debug_str_offsets")
  4350. .Default(Name);
  4351. }