MachOObjectFile.cpp 202 KB

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