objc-runtime-new.mm 251 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919
  1. /*
  2. * Copyright (c) 2005-2009 Apple Inc. All Rights Reserved.
  3. *
  4. * @APPLE_LICENSE_HEADER_START@
  5. *
  6. * This file contains Original Code and/or Modifications of Original Code
  7. * as defined in and that are subject to the Apple Public Source License
  8. * Version 2.0 (the 'License'). You may not use this file except in
  9. * compliance with the License. Please obtain a copy of the License at
  10. * http://www.opensource.apple.com/apsl/ and read it before using this
  11. * file.
  12. *
  13. * The Original Code and all software distributed under the License are
  14. * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
  15. * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
  16. * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
  17. * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
  18. * Please see the License for the specific language governing rights and
  19. * limitations under the License.
  20. *
  21. * @APPLE_LICENSE_HEADER_END@
  22. */
  23. /***********************************************************************
  24. * objc-runtime-new.m
  25. * Support for new-ABI classes and images.
  26. **********************************************************************/
  27. #if __OBJC2__
  28. #include "DenseMapExtras.h"
  29. #include "objc-private.h"
  30. #include "objc-runtime-new.h"
  31. #include "objc-file.h"
  32. #include "objc-cache.h"
  33. #include <Block.h>
  34. #include <objc/message.h>
  35. #include <mach/shared_region.h>
  36. #define newprotocol(p) ((protocol_t *)p)
  37. static void disableTaggedPointers();
  38. static void detach_class(Class cls, bool isMeta);
  39. static void free_class(Class cls);
  40. static IMP addMethod(Class cls, SEL name, IMP imp, const char *types, bool replace);
  41. static void adjustCustomFlagsForMethodChange(Class cls, method_t *meth);
  42. static method_t *search_method_list(const method_list_t *mlist, SEL sel);
  43. static bool method_lists_contains_any(method_list_t **mlists, method_list_t **end,
  44. SEL sels[], size_t selcount);
  45. static void flushCaches(Class cls);
  46. static void initializeTaggedPointerObfuscator(void);
  47. #if SUPPORT_FIXUP
  48. static void fixupMessageRef(message_ref_t *msg);
  49. #endif
  50. static Class realizeClassMaybeSwiftAndUnlock(Class cls, mutex_t& lock);
  51. static Class readClass(Class cls, bool headerIsBundle, bool headerIsPreoptimized);
  52. struct locstamped_category_t {
  53. category_t *cat;
  54. struct header_info *hi;
  55. };
  56. enum {
  57. ATTACH_CLASS = 1 << 0,
  58. ATTACH_METACLASS = 1 << 1,
  59. ATTACH_CLASS_AND_METACLASS = 1 << 2,
  60. ATTACH_EXISTING = 1 << 3,
  61. };
  62. static void attachCategories(Class cls, const struct locstamped_category_t *cats_list, uint32_t cats_count, int flags);
  63. /***********************************************************************
  64. * Lock management
  65. **********************************************************************/
  66. mutex_t runtimeLock;
  67. mutex_t selLock;
  68. #if CONFIG_USE_CACHE_LOCK
  69. mutex_t cacheUpdateLock;
  70. #endif
  71. recursive_mutex_t loadMethodLock;
  72. /***********************************************************************
  73. * Class structure decoding
  74. **********************************************************************/
  75. const uintptr_t objc_debug_class_rw_data_mask = FAST_DATA_MASK;
  76. /***********************************************************************
  77. * Non-pointer isa decoding
  78. **********************************************************************/
  79. #if SUPPORT_INDEXED_ISA
  80. // Indexed non-pointer isa.
  81. // These are used to mask the ISA and see if its got an index or not.
  82. const uintptr_t objc_debug_indexed_isa_magic_mask = ISA_INDEX_MAGIC_MASK;
  83. const uintptr_t objc_debug_indexed_isa_magic_value = ISA_INDEX_MAGIC_VALUE;
  84. // die if masks overlap
  85. STATIC_ASSERT((ISA_INDEX_MASK & ISA_INDEX_MAGIC_MASK) == 0);
  86. // die if magic is wrong
  87. STATIC_ASSERT((~ISA_INDEX_MAGIC_MASK & ISA_INDEX_MAGIC_VALUE) == 0);
  88. // Then these are used to extract the index from the ISA.
  89. const uintptr_t objc_debug_indexed_isa_index_mask = ISA_INDEX_MASK;
  90. const uintptr_t objc_debug_indexed_isa_index_shift = ISA_INDEX_SHIFT;
  91. asm("\n .globl _objc_absolute_indexed_isa_magic_mask" \
  92. "\n _objc_absolute_indexed_isa_magic_mask = " STRINGIFY2(ISA_INDEX_MAGIC_MASK));
  93. asm("\n .globl _objc_absolute_indexed_isa_magic_value" \
  94. "\n _objc_absolute_indexed_isa_magic_value = " STRINGIFY2(ISA_INDEX_MAGIC_VALUE));
  95. asm("\n .globl _objc_absolute_indexed_isa_index_mask" \
  96. "\n _objc_absolute_indexed_isa_index_mask = " STRINGIFY2(ISA_INDEX_MASK));
  97. asm("\n .globl _objc_absolute_indexed_isa_index_shift" \
  98. "\n _objc_absolute_indexed_isa_index_shift = " STRINGIFY2(ISA_INDEX_SHIFT));
  99. // And then we can use that index to get the class from this array. Note
  100. // the size is provided so that clients can ensure the index they get is in
  101. // bounds and not read off the end of the array.
  102. // Defined in the objc-msg-*.s files
  103. // const Class objc_indexed_classes[]
  104. // When we don't have enough bits to store a class*, we can instead store an
  105. // index in to this array. Classes are added here when they are realized.
  106. // Note, an index of 0 is illegal.
  107. uintptr_t objc_indexed_classes_count = 0;
  108. // SUPPORT_INDEXED_ISA
  109. #else
  110. // not SUPPORT_INDEXED_ISA
  111. // These variables exist but are all set to 0 so that they are ignored.
  112. const uintptr_t objc_debug_indexed_isa_magic_mask = 0;
  113. const uintptr_t objc_debug_indexed_isa_magic_value = 0;
  114. const uintptr_t objc_debug_indexed_isa_index_mask = 0;
  115. const uintptr_t objc_debug_indexed_isa_index_shift = 0;
  116. Class objc_indexed_classes[1] = { nil };
  117. uintptr_t objc_indexed_classes_count = 0;
  118. // not SUPPORT_INDEXED_ISA
  119. #endif
  120. #if SUPPORT_PACKED_ISA
  121. // Packed non-pointer isa.
  122. asm("\n .globl _objc_absolute_packed_isa_class_mask" \
  123. "\n _objc_absolute_packed_isa_class_mask = " STRINGIFY2(ISA_MASK));
  124. const uintptr_t objc_debug_isa_class_mask = ISA_MASK;
  125. const uintptr_t objc_debug_isa_magic_mask = ISA_MAGIC_MASK;
  126. const uintptr_t objc_debug_isa_magic_value = ISA_MAGIC_VALUE;
  127. // die if masks overlap
  128. STATIC_ASSERT((ISA_MASK & ISA_MAGIC_MASK) == 0);
  129. // die if magic is wrong
  130. STATIC_ASSERT((~ISA_MAGIC_MASK & ISA_MAGIC_VALUE) == 0);
  131. // die if virtual address space bound goes up
  132. STATIC_ASSERT((~ISA_MASK & MACH_VM_MAX_ADDRESS) == 0 ||
  133. ISA_MASK + sizeof(void*) == MACH_VM_MAX_ADDRESS);
  134. // SUPPORT_PACKED_ISA
  135. #else
  136. // not SUPPORT_PACKED_ISA
  137. // These variables exist but enforce pointer alignment only.
  138. const uintptr_t objc_debug_isa_class_mask = (~WORD_MASK);
  139. const uintptr_t objc_debug_isa_magic_mask = WORD_MASK;
  140. const uintptr_t objc_debug_isa_magic_value = 0;
  141. // not SUPPORT_PACKED_ISA
  142. #endif
  143. /***********************************************************************
  144. * Swift marker bits
  145. **********************************************************************/
  146. const uintptr_t objc_debug_swift_stable_abi_bit = FAST_IS_SWIFT_STABLE;
  147. /***********************************************************************
  148. * allocatedClasses
  149. * A table of all classes (and metaclasses) which have been allocated
  150. * with objc_allocateClassPair.
  151. **********************************************************************/
  152. namespace objc {
  153. static ExplicitInitDenseSet<Class> allocatedClasses;
  154. }
  155. /***********************************************************************
  156. * _firstRealizedClass
  157. * The root of all realized classes
  158. **********************************************************************/
  159. static Class _firstRealizedClass = nil;
  160. /*
  161. Low two bits of mlist->entsize is used as the fixed-up marker.
  162. PREOPTIMIZED VERSION:
  163. Method lists from shared cache are 1 (uniqued) or 3 (uniqued and sorted).
  164. (Protocol method lists are not sorted because of their extra parallel data)
  165. Runtime fixed-up method lists get 3.
  166. UN-PREOPTIMIZED VERSION:
  167. Method lists from shared cache are 1 (uniqued) or 3 (uniqued and sorted)
  168. Shared cache's sorting and uniquing are not trusted, but do affect the
  169. location of the selector name string.
  170. Runtime fixed-up method lists get 2.
  171. High two bits of protocol->flags is used as the fixed-up marker.
  172. PREOPTIMIZED VERSION:
  173. Protocols from shared cache are 1<<30.
  174. Runtime fixed-up protocols get 1<<30.
  175. UN-PREOPTIMIZED VERSION:
  176. Protocols from shared cache are 1<<30.
  177. Shared cache's fixups are not trusted.
  178. Runtime fixed-up protocols get 3<<30.
  179. */
  180. static uint32_t fixed_up_method_list = 3;
  181. static uint32_t uniqued_method_list = 1;
  182. static uint32_t fixed_up_protocol = PROTOCOL_FIXED_UP_1;
  183. static uint32_t canonical_protocol = PROTOCOL_IS_CANONICAL;
  184. void
  185. disableSharedCacheOptimizations(void)
  186. {
  187. fixed_up_method_list = 2;
  188. // It is safe to set uniqued method lists to 0 as we'll never call it unless
  189. // the method list was already in need of being fixed up
  190. uniqued_method_list = 0;
  191. fixed_up_protocol = PROTOCOL_FIXED_UP_1 | PROTOCOL_FIXED_UP_2;
  192. // Its safe to just set canonical protocol to 0 as we'll never call
  193. // clearIsCanonical() unless isCanonical() returned true, which can't happen
  194. // with a 0 mask
  195. canonical_protocol = 0;
  196. }
  197. bool method_list_t::isUniqued() const {
  198. return (flags() & uniqued_method_list) != 0;
  199. }
  200. bool method_list_t::isFixedUp() const {
  201. return flags() == fixed_up_method_list;
  202. }
  203. void method_list_t::setFixedUp() {
  204. runtimeLock.assertLocked();
  205. ASSERT(!isFixedUp());
  206. entsizeAndFlags = entsize() | fixed_up_method_list;
  207. }
  208. bool protocol_t::isFixedUp() const {
  209. return (flags & PROTOCOL_FIXED_UP_MASK) == fixed_up_protocol;
  210. }
  211. void protocol_t::setFixedUp() {
  212. runtimeLock.assertLocked();
  213. ASSERT(!isFixedUp());
  214. flags = (flags & ~PROTOCOL_FIXED_UP_MASK) | fixed_up_protocol;
  215. }
  216. bool protocol_t::isCanonical() const {
  217. return (flags & canonical_protocol) != 0;
  218. }
  219. void protocol_t::clearIsCanonical() {
  220. runtimeLock.assertLocked();
  221. ASSERT(isCanonical());
  222. flags = flags & ~canonical_protocol;
  223. }
  224. method_list_t **method_array_t::endCategoryMethodLists(Class cls)
  225. {
  226. method_list_t **mlists = beginLists();
  227. method_list_t **mlistsEnd = endLists();
  228. if (mlists == mlistsEnd || !cls->data()->ro->baseMethods())
  229. {
  230. // No methods, or no base methods.
  231. // Everything here is a category method.
  232. return mlistsEnd;
  233. }
  234. // Have base methods. Category methods are
  235. // everything except the last method list.
  236. return mlistsEnd - 1;
  237. }
  238. static const char *sel_cname(SEL sel)
  239. {
  240. return (const char *)(void *)sel;
  241. }
  242. static size_t protocol_list_size(const protocol_list_t *plist)
  243. {
  244. return sizeof(protocol_list_t) + plist->count * sizeof(protocol_t *);
  245. }
  246. static void try_free(const void *p)
  247. {
  248. if (p && malloc_size(p)) free((void *)p);
  249. }
  250. using ClassCopyFixupHandler = void (*)(Class _Nonnull oldClass,
  251. Class _Nonnull newClass);
  252. // Normally there's only one handler registered.
  253. static GlobalSmallVector<ClassCopyFixupHandler, 1> classCopyFixupHandlers;
  254. void _objc_setClassCopyFixupHandler(void (* _Nonnull newFixupHandler)
  255. (Class _Nonnull oldClass, Class _Nonnull newClass)) {
  256. mutex_locker_t lock(runtimeLock);
  257. classCopyFixupHandlers.append(newFixupHandler);
  258. }
  259. static Class
  260. alloc_class_for_subclass(Class supercls, size_t extraBytes)
  261. {
  262. if (!supercls || !supercls->isAnySwift()) {
  263. return _calloc_class(sizeof(objc_class) + extraBytes);
  264. }
  265. // Superclass is a Swift class. New subclass must duplicate its extra bits.
  266. // Allocate the new class, with space for super's prefix and suffix
  267. // and self's extraBytes.
  268. swift_class_t *swiftSupercls = (swift_class_t *)supercls;
  269. size_t superSize = swiftSupercls->classSize;
  270. void *superBits = swiftSupercls->baseAddress();
  271. void *bits = malloc(superSize + extraBytes);
  272. // Copy all of the superclass's data to the new class.
  273. memcpy(bits, superBits, superSize);
  274. // Erase the objc data and the Swift description in the new class.
  275. swift_class_t *swcls = (swift_class_t *)
  276. ((uint8_t *)bits + swiftSupercls->classAddressOffset);
  277. bzero(swcls, sizeof(objc_class));
  278. swcls->description = nil;
  279. for (auto handler : classCopyFixupHandlers) {
  280. handler(supercls, (Class)swcls);
  281. }
  282. // Mark this class as Swift-enhanced.
  283. if (supercls->isSwiftStable()) {
  284. swcls->bits.setIsSwiftStable();
  285. }
  286. if (supercls->isSwiftLegacy()) {
  287. swcls->bits.setIsSwiftLegacy();
  288. }
  289. return (Class)swcls;
  290. }
  291. /***********************************************************************
  292. * object_getIndexedIvars.
  293. **********************************************************************/
  294. void *object_getIndexedIvars(id obj)
  295. {
  296. uint8_t *base = (uint8_t *)obj;
  297. if (!obj) return nil;
  298. if (obj->isTaggedPointer()) return nil;
  299. if (!obj->isClass()) return base + obj->ISA()->alignedInstanceSize();
  300. Class cls = (Class)obj;
  301. if (!cls->isAnySwift()) return base + sizeof(objc_class);
  302. swift_class_t *swcls = (swift_class_t *)cls;
  303. return base - swcls->classAddressOffset + word_align(swcls->classSize);
  304. }
  305. /***********************************************************************
  306. * make_ro_writeable
  307. * Reallocates rw->ro if necessary to make it writeable.
  308. * Locking: runtimeLock must be held by the caller.
  309. **********************************************************************/
  310. static class_ro_t *make_ro_writeable(class_rw_t *rw)
  311. {
  312. runtimeLock.assertLocked();
  313. if (rw->flags & RW_COPIED_RO) {
  314. // already writeable, do nothing
  315. } else {
  316. rw->ro = rw->ro->duplicate();
  317. rw->flags |= RW_COPIED_RO;
  318. }
  319. return (class_ro_t *)rw->ro;
  320. }
  321. /***********************************************************************
  322. * dataSegmentsContain
  323. * Returns true if the given address lies within a data segment in any
  324. * loaded image.
  325. **********************************************************************/
  326. NEVER_INLINE
  327. static bool
  328. dataSegmentsContain(Class cls)
  329. {
  330. uint32_t index;
  331. if (objc::dataSegmentsRanges.find((uintptr_t)cls, index)) {
  332. // if the class is realized (hence has a class_rw_t),
  333. // memorize where we found the range
  334. if (cls->isRealized()) {
  335. cls->data()->witness = (uint16_t)index;
  336. }
  337. return true;
  338. }
  339. return false;
  340. }
  341. /***********************************************************************
  342. * isKnownClass
  343. * Return true if the class is known to the runtime (located within the
  344. * shared cache, within the data segment of a loaded image, or has been
  345. * allocated with obj_allocateClassPair).
  346. *
  347. * The result of this operation is cached on the class in a "witness"
  348. * value that is cheaply checked in the fastpath.
  349. **********************************************************************/
  350. ALWAYS_INLINE
  351. static bool
  352. isKnownClass(Class cls)
  353. {
  354. if (fastpath(objc::dataSegmentsRanges.contains(cls->data()->witness, (uintptr_t)cls))) {
  355. return true;
  356. }
  357. auto &set = objc::allocatedClasses.get();
  358. return set.find(cls) != set.end() || dataSegmentsContain(cls);
  359. }
  360. /***********************************************************************
  361. * addClassTableEntry
  362. * Add a class to the table of all classes. If addMeta is true,
  363. * automatically adds the metaclass of the class as well.
  364. * Locking: runtimeLock must be held by the caller.
  365. **********************************************************************/
  366. static void
  367. addClassTableEntry(Class cls, bool addMeta = true)
  368. {
  369. runtimeLock.assertLocked();
  370. // This class is allowed to be a known class via the shared cache or via
  371. // data segments, but it is not allowed to be in the dynamic table already.
  372. auto &set = objc::allocatedClasses.get();
  373. ASSERT(set.find(cls) == set.end());
  374. if (!isKnownClass(cls))
  375. set.insert(cls);
  376. if (addMeta)
  377. addClassTableEntry(cls->ISA(), false);
  378. }
  379. /***********************************************************************
  380. * checkIsKnownClass
  381. * Checks the given class against the list of all known classes. Dies
  382. * with a fatal error if the class is not known.
  383. * Locking: runtimeLock must be held by the caller.
  384. **********************************************************************/
  385. ALWAYS_INLINE
  386. static void
  387. checkIsKnownClass(Class cls)
  388. {
  389. if (slowpath(!isKnownClass(cls))) {
  390. _objc_fatal("Attempt to use unknown class %p.", cls);
  391. }
  392. }
  393. /***********************************************************************
  394. * classNSObject
  395. * Returns class NSObject.
  396. * Locking: none
  397. **********************************************************************/
  398. static Class classNSObject(void)
  399. {
  400. extern objc_class OBJC_CLASS_$_NSObject;
  401. return (Class)&OBJC_CLASS_$_NSObject;
  402. }
  403. static Class metaclassNSObject(void)
  404. {
  405. extern objc_class OBJC_METACLASS_$_NSObject;
  406. return (Class)&OBJC_METACLASS_$_NSObject;
  407. }
  408. /***********************************************************************
  409. * printReplacements
  410. * Implementation of PrintReplacedMethods / OBJC_PRINT_REPLACED_METHODS.
  411. * Warn about methods from cats that override other methods in cats or cls.
  412. * Assumes no methods from cats have been added to cls yet.
  413. **********************************************************************/
  414. __attribute__((cold, noinline))
  415. static void
  416. printReplacements(Class cls, const locstamped_category_t *cats_list, uint32_t cats_count)
  417. {
  418. uint32_t c;
  419. bool isMeta = cls->isMetaClass();
  420. // Newest categories are LAST in cats
  421. // Later categories override earlier ones.
  422. for (c = 0; c < cats_count; c++) {
  423. category_t *cat = cats_list[c].cat;
  424. method_list_t *mlist = cat->methodsForMeta(isMeta);
  425. if (!mlist) continue;
  426. for (const auto& meth : *mlist) {
  427. SEL s = sel_registerName(sel_cname(meth.name));
  428. // Search for replaced methods in method lookup order.
  429. // Complain about the first duplicate only.
  430. // Look for method in earlier categories
  431. for (uint32_t c2 = 0; c2 < c; c2++) {
  432. category_t *cat2 = cats_list[c2].cat;
  433. const method_list_t *mlist2 = cat2->methodsForMeta(isMeta);
  434. if (!mlist2) continue;
  435. for (const auto& meth2 : *mlist2) {
  436. SEL s2 = sel_registerName(sel_cname(meth2.name));
  437. if (s == s2) {
  438. logReplacedMethod(cls->nameForLogging(), s,
  439. cls->isMetaClass(), cat->name,
  440. meth2.imp, meth.imp);
  441. goto complained;
  442. }
  443. }
  444. }
  445. // Look for method in cls
  446. for (const auto& meth2 : cls->data()->methods) {
  447. SEL s2 = sel_registerName(sel_cname(meth2.name));
  448. if (s == s2) {
  449. logReplacedMethod(cls->nameForLogging(), s,
  450. cls->isMetaClass(), cat->name,
  451. meth2.imp, meth.imp);
  452. goto complained;
  453. }
  454. }
  455. complained:
  456. ;
  457. }
  458. }
  459. }
  460. /***********************************************************************
  461. * unreasonableClassCount
  462. * Provides an upper bound for any iteration of classes,
  463. * to prevent spins when runtime metadata is corrupted.
  464. **********************************************************************/
  465. static unsigned unreasonableClassCount()
  466. {
  467. runtimeLock.assertLocked();
  468. int base = NXCountMapTable(gdb_objc_realized_classes) +
  469. getPreoptimizedClassUnreasonableCount();
  470. // Provide lots of slack here. Some iterations touch metaclasses too.
  471. // Some iterations backtrack (like realized class iteration).
  472. // We don't need an efficient bound, merely one that prevents spins.
  473. return (base + 1) * 16;
  474. }
  475. /***********************************************************************
  476. * Class enumerators
  477. * The passed in block returns `false` if subclasses can be skipped
  478. * Locking: runtimeLock must be held by the caller.
  479. **********************************************************************/
  480. static inline void
  481. foreach_realized_class_and_subclass_2(Class top, unsigned &count,
  482. bool skip_metaclass,
  483. bool (^code)(Class) __attribute((noescape)))
  484. {
  485. Class cls = top;
  486. runtimeLock.assertLocked();
  487. ASSERT(top);
  488. while (1) {
  489. if (--count == 0) {
  490. _objc_fatal("Memory corruption in class list.");
  491. }
  492. bool skip_subclasses;
  493. if (skip_metaclass && cls->isMetaClass()) {
  494. skip_subclasses = true;
  495. } else {
  496. skip_subclasses = !code(cls);
  497. }
  498. if (!skip_subclasses && cls->data()->firstSubclass) {
  499. cls = cls->data()->firstSubclass;
  500. } else {
  501. while (!cls->data()->nextSiblingClass && cls != top) {
  502. cls = cls->superclass;
  503. if (--count == 0) {
  504. _objc_fatal("Memory corruption in class list.");
  505. }
  506. }
  507. if (cls == top) break;
  508. cls = cls->data()->nextSiblingClass;
  509. }
  510. }
  511. }
  512. // Enumerates a class and all of its realized subclasses.
  513. static void
  514. foreach_realized_class_and_subclass(Class top, bool (^code)(Class) __attribute((noescape)))
  515. {
  516. unsigned int count = unreasonableClassCount();
  517. foreach_realized_class_and_subclass_2(top, count, false, code);
  518. }
  519. // Enumerates all realized classes and metaclasses.
  520. static void
  521. foreach_realized_class_and_metaclass(bool (^code)(Class) __attribute((noescape)))
  522. {
  523. unsigned int count = unreasonableClassCount();
  524. for (Class top = _firstRealizedClass;
  525. top != nil;
  526. top = top->data()->nextSiblingClass)
  527. {
  528. foreach_realized_class_and_subclass_2(top, count, false, code);
  529. }
  530. }
  531. // Enumerates all realized classes (ignoring metaclasses).
  532. static void
  533. foreach_realized_class(bool (^code)(Class) __attribute((noescape)))
  534. {
  535. unsigned int count = unreasonableClassCount();
  536. for (Class top = _firstRealizedClass;
  537. top != nil;
  538. top = top->data()->nextSiblingClass)
  539. {
  540. foreach_realized_class_and_subclass_2(top, count, true, code);
  541. }
  542. }
  543. /***********************************************************************
  544. * Method Scanners / Optimization tracking
  545. * Implementation of scanning for various implementations of methods.
  546. **********************************************************************/
  547. namespace objc {
  548. enum SelectorBundle {
  549. AWZ,
  550. RR,
  551. Core,
  552. };
  553. namespace scanner {
  554. // The current state of NSObject swizzling for every scanner
  555. //
  556. // It allows for cheap checks of global swizzles, and also lets
  557. // things like IMP Swizzling before NSObject has been initialized
  558. // to be remembered, as setInitialized() would miss these.
  559. //
  560. // Every pair of bits describes a SelectorBundle.
  561. // even bits: is NSObject class swizzled for this bundle
  562. // odd bits: is NSObject meta class swizzled for this bundle
  563. static uintptr_t NSObjectSwizzledMask;
  564. static ALWAYS_INLINE uintptr_t
  565. swizzlingBit(SelectorBundle bundle, bool isMeta)
  566. {
  567. return 1UL << (2 * bundle + isMeta);
  568. }
  569. static void __attribute__((cold, noinline))
  570. printCustom(Class cls, SelectorBundle bundle, bool inherited)
  571. {
  572. static char const * const SelectorBundleName[] = {
  573. [AWZ] = "CUSTOM AWZ",
  574. [RR] = "CUSTOM RR",
  575. [Core] = "CUSTOM Core",
  576. };
  577. _objc_inform("%s: %s%s%s", SelectorBundleName[bundle],
  578. cls->nameForLogging(),
  579. cls->isMetaClass() ? " (meta)" : "",
  580. inherited ? " (inherited)" : "");
  581. }
  582. enum class Scope { Instances, Classes, Both };
  583. template <typename Traits, SelectorBundle Bundle, bool &ShouldPrint, Scope Domain = Scope::Both>
  584. class Mixin {
  585. // work around compiler being broken with templates using Class/objc_class,
  586. // probably some weird confusion with Class being builtin
  587. ALWAYS_INLINE static objc_class *as_objc_class(Class cls) {
  588. return (objc_class *)cls;
  589. }
  590. static void
  591. setCustomRecursively(Class cls, bool inherited = false)
  592. {
  593. foreach_realized_class_and_subclass(cls, [=](Class c){
  594. if (c != cls && !as_objc_class(c)->isInitialized()) {
  595. // Subclass not yet initialized. Wait for setInitialized() to do it
  596. return false;
  597. }
  598. if (Traits::isCustom(c)) {
  599. return false;
  600. }
  601. Traits::setCustom(c);
  602. if (ShouldPrint) {
  603. printCustom(cls, Bundle, inherited || c != cls);
  604. }
  605. return true;
  606. });
  607. }
  608. static bool
  609. isNSObjectSwizzled(bool isMeta)
  610. {
  611. return NSObjectSwizzledMask & swizzlingBit(Bundle, isMeta);
  612. }
  613. static void
  614. setNSObjectSwizzled(Class NSOClass, bool isMeta)
  615. {
  616. NSObjectSwizzledMask |= swizzlingBit(Bundle, isMeta);
  617. if (as_objc_class(NSOClass)->isInitialized()) {
  618. setCustomRecursively(NSOClass);
  619. }
  620. }
  621. static void
  622. scanChangedMethodForUnknownClass(const method_t *meth)
  623. {
  624. Class cls;
  625. cls = classNSObject();
  626. if (Domain != Scope::Classes && !isNSObjectSwizzled(NO)) {
  627. for (const auto &meth2: as_objc_class(cls)->data()->methods) {
  628. if (meth == &meth2) {
  629. setNSObjectSwizzled(cls, NO);
  630. break;
  631. }
  632. }
  633. }
  634. cls = metaclassNSObject();
  635. if (Domain != Scope::Instances && !isNSObjectSwizzled(YES)) {
  636. for (const auto &meth2: as_objc_class(cls)->data()->methods) {
  637. if (meth == &meth2) {
  638. setNSObjectSwizzled(cls, YES);
  639. break;
  640. }
  641. }
  642. }
  643. }
  644. static void
  645. scanAddedClassImpl(Class cls, bool isMeta)
  646. {
  647. Class NSOClass = (isMeta ? metaclassNSObject() : classNSObject());
  648. bool setCustom = NO, inherited = NO;
  649. if (isNSObjectSwizzled(isMeta)) {
  650. setCustom = YES;
  651. } else if (cls == NSOClass) {
  652. // NSObject is default but we need to check categories
  653. auto &methods = as_objc_class(cls)->data()->methods;
  654. setCustom = Traits::scanMethodLists(methods.beginCategoryMethodLists(),
  655. methods.endCategoryMethodLists(cls));
  656. } else if (!isMeta && !as_objc_class(cls)->superclass) {
  657. // Custom Root class
  658. setCustom = YES;
  659. } else if (Traits::isCustom(as_objc_class(cls)->superclass)) {
  660. // Superclass is custom, therefore we are too.
  661. setCustom = YES;
  662. inherited = YES;
  663. } else {
  664. // Not NSObject.
  665. auto &methods = as_objc_class(cls)->data()->methods;
  666. setCustom = Traits::scanMethodLists(methods.beginLists(),
  667. methods.endLists());
  668. }
  669. if (slowpath(setCustom)) {
  670. if (ShouldPrint) printCustom(cls, Bundle, inherited);
  671. } else {
  672. Traits::setDefault(cls);
  673. }
  674. }
  675. public:
  676. // Scan a class that is about to be marked Initialized for particular
  677. // bundles of selectors, and mark the class and its children
  678. // accordingly.
  679. //
  680. // This also handles inheriting properties from its superclass.
  681. //
  682. // Caller: objc_class::setInitialized()
  683. static void
  684. scanInitializedClass(Class cls, Class metacls)
  685. {
  686. if (Domain != Scope::Classes) {
  687. scanAddedClassImpl(cls, false);
  688. }
  689. if (Domain != Scope::Instances) {
  690. scanAddedClassImpl(metacls, true);
  691. }
  692. }
  693. // Inherit various properties from the superclass when a class
  694. // is being added to the graph.
  695. //
  696. // Caller: addSubclass()
  697. static void
  698. scanAddedSubClass(Class subcls, Class supercls)
  699. {
  700. if (slowpath(Traits::isCustom(supercls) && !Traits::isCustom(subcls))) {
  701. setCustomRecursively(subcls, true);
  702. }
  703. }
  704. // Scan Method lists for selectors that would override things
  705. // in a Bundle.
  706. //
  707. // This is used to detect when categories override problematic selectors
  708. // are injected in a class after it has been initialized.
  709. //
  710. // Caller: prepareMethodLists()
  711. static void
  712. scanAddedMethodLists(Class cls, method_list_t **mlists, int count)
  713. {
  714. if (slowpath(Traits::isCustom(cls))) {
  715. return;
  716. }
  717. if (slowpath(Traits::scanMethodLists(mlists, mlists + count))) {
  718. setCustomRecursively(cls);
  719. }
  720. }
  721. // Handle IMP Swizzling (the IMP for an exisiting method being changed).
  722. //
  723. // In almost all cases, IMP swizzling does not affect custom bits.
  724. // Custom search will already find the method whether or not
  725. // it is swizzled, so it does not transition from non-custom to custom.
  726. //
  727. // The only cases where IMP swizzling can affect the custom bits is
  728. // if the swizzled method is one of the methods that is assumed to be
  729. // non-custom. These special cases are listed in setInitialized().
  730. // We look for such cases here.
  731. //
  732. // Caller: Swizzling methods via adjustCustomFlagsForMethodChange()
  733. static void
  734. scanChangedMethod(Class cls, const method_t *meth)
  735. {
  736. if (fastpath(!Traits::isInterestingSelector(meth->name))) {
  737. return;
  738. }
  739. if (cls) {
  740. bool isMeta = as_objc_class(cls)->isMetaClass();
  741. if (isMeta && Domain != Scope::Instances) {
  742. if (cls == metaclassNSObject() && !isNSObjectSwizzled(isMeta)) {
  743. setNSObjectSwizzled(cls, isMeta);
  744. }
  745. }
  746. if (!isMeta && Domain != Scope::Classes) {
  747. if (cls == classNSObject() && !isNSObjectSwizzled(isMeta)) {
  748. setNSObjectSwizzled(cls, isMeta);
  749. }
  750. }
  751. } else {
  752. // We're called from method_exchangeImplementations, only NSObject
  753. // class and metaclass may be problematic (exchanging the default
  754. // builtin IMP of an interesting seleector, is a swizzling that,
  755. // may flip our scanned property. For other classes, the previous
  756. // value had already flipped the property).
  757. //
  758. // However, as we don't know the class, we need to scan all of
  759. // NSObject class and metaclass methods (this is SLOW).
  760. scanChangedMethodForUnknownClass(meth);
  761. }
  762. }
  763. };
  764. } // namespace scanner
  765. // AWZ methods: +alloc / +allocWithZone:
  766. struct AWZScanner : scanner::Mixin<AWZScanner, AWZ, PrintCustomAWZ, scanner::Scope::Classes> {
  767. static bool isCustom(Class cls) {
  768. return cls->hasCustomAWZ();
  769. }
  770. static void setCustom(Class cls) {
  771. cls->setHasCustomAWZ();
  772. }
  773. static void setDefault(Class cls) {
  774. cls->setHasDefaultAWZ();
  775. }
  776. static bool isInterestingSelector(SEL sel) {
  777. return sel == @selector(alloc) || sel == @selector(allocWithZone:);
  778. }
  779. static bool scanMethodLists(method_list_t **mlists, method_list_t **end) {
  780. SEL sels[2] = { @selector(alloc), @selector(allocWithZone:), };
  781. return method_lists_contains_any(mlists, end, sels, 2);
  782. }
  783. };
  784. // Retain/Release methods that are extremely rarely overridden
  785. //
  786. // retain/release/autorelease/retainCount/
  787. // _tryRetain/_isDeallocating/retainWeakReference/allowsWeakReference
  788. struct RRScanner : scanner::Mixin<RRScanner, RR, PrintCustomRR
  789. #if !SUPPORT_NONPOINTER_ISA
  790. , scanner::Scope::Instances
  791. #endif
  792. > {
  793. static bool isCustom(Class cls) {
  794. return cls->hasCustomRR();
  795. }
  796. static void setCustom(Class cls) {
  797. cls->setHasCustomRR();
  798. }
  799. static void setDefault(Class cls) {
  800. cls->setHasDefaultRR();
  801. }
  802. static bool isInterestingSelector(SEL sel) {
  803. return sel == @selector(retain) ||
  804. sel == @selector(release) ||
  805. sel == @selector(autorelease) ||
  806. sel == @selector(_tryRetain) ||
  807. sel == @selector(_isDeallocating) ||
  808. sel == @selector(retainCount) ||
  809. sel == @selector(allowsWeakReference) ||
  810. sel == @selector(retainWeakReference);
  811. }
  812. static bool scanMethodLists(method_list_t **mlists, method_list_t **end) {
  813. SEL sels[8] = {
  814. @selector(retain),
  815. @selector(release),
  816. @selector(autorelease),
  817. @selector(_tryRetain),
  818. @selector(_isDeallocating),
  819. @selector(retainCount),
  820. @selector(allowsWeakReference),
  821. @selector(retainWeakReference),
  822. };
  823. return method_lists_contains_any(mlists, end, sels, 8);
  824. }
  825. };
  826. // Core NSObject methods that are extremely rarely overridden
  827. //
  828. // +new, ±class, ±self, ±isKindOfClass:, ±respondsToSelector
  829. struct CoreScanner : scanner::Mixin<CoreScanner, Core, PrintCustomCore> {
  830. static bool isCustom(Class cls) {
  831. return cls->hasCustomCore();
  832. }
  833. static void setCustom(Class cls) {
  834. cls->setHasCustomCore();
  835. }
  836. static void setDefault(Class cls) {
  837. cls->setHasDefaultCore();
  838. }
  839. static bool isInterestingSelector(SEL sel) {
  840. return sel == @selector(new) ||
  841. sel == @selector(self) ||
  842. sel == @selector(class) ||
  843. sel == @selector(isKindOfClass:) ||
  844. sel == @selector(respondsToSelector:);
  845. }
  846. static bool scanMethodLists(method_list_t **mlists, method_list_t **end) {
  847. SEL sels[5] = {
  848. @selector(new),
  849. @selector(self),
  850. @selector(class),
  851. @selector(isKindOfClass:),
  852. @selector(respondsToSelector:)
  853. };
  854. return method_lists_contains_any(mlists, end, sels, 5);
  855. }
  856. };
  857. class category_list : nocopy_t {
  858. union {
  859. locstamped_category_t lc;
  860. struct {
  861. locstamped_category_t *array;
  862. // this aliases with locstamped_category_t::hi
  863. // which is an aliased pointer
  864. uint32_t is_array : 1;
  865. uint32_t count : 31;
  866. uint32_t size : 32;
  867. };
  868. } _u;
  869. public:
  870. category_list() : _u{{nullptr, nullptr}} { }
  871. category_list(locstamped_category_t lc) : _u{{lc}} { }
  872. category_list(category_list &&other) : category_list() {
  873. std::swap(_u, other._u);
  874. }
  875. ~category_list()
  876. {
  877. if (_u.is_array) {
  878. free(_u.array);
  879. }
  880. }
  881. uint32_t count() const
  882. {
  883. if (_u.is_array) return _u.count;
  884. return _u.lc.cat ? 1 : 0;
  885. }
  886. uint32_t arrayByteSize(uint32_t size) const
  887. {
  888. return sizeof(locstamped_category_t) * size;
  889. }
  890. const locstamped_category_t *array() const
  891. {
  892. return _u.is_array ? _u.array : &_u.lc;
  893. }
  894. void append(locstamped_category_t lc)
  895. {
  896. if (_u.is_array) {
  897. if (_u.count == _u.size) {
  898. // Have a typical malloc growth:
  899. // - size <= 8: grow by 2
  900. // - size <= 16: grow by 4
  901. // - size <= 32: grow by 8
  902. // ... etc
  903. _u.size += _u.size < 8 ? 2 : 1 << (fls(_u.size) - 2);
  904. _u.array = (locstamped_category_t *)reallocf(_u.array, arrayByteSize(_u.size));
  905. }
  906. _u.array[_u.count++] = lc;
  907. } else if (_u.lc.cat == NULL) {
  908. _u.lc = lc;
  909. } else {
  910. locstamped_category_t *arr = (locstamped_category_t *)malloc(arrayByteSize(2));
  911. arr[0] = _u.lc;
  912. arr[1] = lc;
  913. _u.array = arr;
  914. _u.is_array = true;
  915. _u.count = 2;
  916. _u.size = 2;
  917. }
  918. }
  919. void erase(category_t *cat)
  920. {
  921. if (_u.is_array) {
  922. for (int i = 0; i < _u.count; i++) {
  923. if (_u.array[i].cat == cat) {
  924. // shift entries to preserve list order
  925. memmove(&_u.array[i], &_u.array[i+1], arrayByteSize(_u.count - i - 1));
  926. return;
  927. }
  928. }
  929. } else if (_u.lc.cat == cat) {
  930. _u.lc.cat = NULL;
  931. _u.lc.hi = NULL;
  932. }
  933. }
  934. };
  935. class UnattachedCategories : public ExplicitInitDenseMap<Class, category_list>
  936. {
  937. public:
  938. void addForClass(locstamped_category_t lc, Class cls)
  939. {
  940. runtimeLock.assertLocked();
  941. if (slowpath(PrintConnecting)) {
  942. _objc_inform("CLASS: found category %c%s(%s)",
  943. cls->isMetaClass() ? '+' : '-',
  944. cls->nameForLogging(), lc.cat->name);
  945. }
  946. auto result = get().try_emplace(cls, lc);
  947. if (!result.second) {
  948. result.first->second.append(lc);
  949. }
  950. }
  951. void attachToClass(Class cls, Class previously, int flags)
  952. {
  953. runtimeLock.assertLocked();
  954. ASSERT((flags & ATTACH_CLASS) ||
  955. (flags & ATTACH_METACLASS) ||
  956. (flags & ATTACH_CLASS_AND_METACLASS));
  957. auto &map = get();
  958. auto it = map.find(previously);
  959. if (it != map.end()) {
  960. category_list &list = it->second;
  961. if (flags & ATTACH_CLASS_AND_METACLASS) {
  962. int otherFlags = flags & ~ATTACH_CLASS_AND_METACLASS;
  963. attachCategories(cls, list.array(), list.count(), otherFlags | ATTACH_CLASS);
  964. attachCategories(cls->ISA(), list.array(), list.count(), otherFlags | ATTACH_METACLASS);
  965. } else {
  966. attachCategories(cls, list.array(), list.count(), flags);
  967. }
  968. map.erase(it);
  969. }
  970. }
  971. void eraseCategoryForClass(category_t *cat, Class cls)
  972. {
  973. runtimeLock.assertLocked();
  974. auto &map = get();
  975. auto it = map.find(cls);
  976. if (it != map.end()) {
  977. category_list &list = it->second;
  978. list.erase(cat);
  979. if (list.count() == 0) {
  980. map.erase(it);
  981. }
  982. }
  983. }
  984. void eraseClass(Class cls)
  985. {
  986. runtimeLock.assertLocked();
  987. get().erase(cls);
  988. }
  989. };
  990. static UnattachedCategories unattachedCategories;
  991. } // namespace objc
  992. static bool isBundleClass(Class cls)
  993. {
  994. return cls->data()->ro->flags & RO_FROM_BUNDLE;
  995. }
  996. static void
  997. fixupMethodList(method_list_t *mlist, bool bundleCopy, bool sort)
  998. {
  999. runtimeLock.assertLocked();
  1000. ASSERT(!mlist->isFixedUp());
  1001. // fixme lock less in attachMethodLists ?
  1002. // dyld3 may have already uniqued, but not sorted, the list
  1003. if (!mlist->isUniqued()) {
  1004. mutex_locker_t lock(selLock);
  1005. // Unique selectors in list.
  1006. for (auto& meth : *mlist) {
  1007. const char *name = sel_cname(meth.name);
  1008. meth.name = sel_registerNameNoLock(name, bundleCopy);
  1009. }
  1010. }
  1011. // Sort by selector address.
  1012. if (sort) {
  1013. method_t::SortBySELAddress sorter;
  1014. std::stable_sort(mlist->begin(), mlist->end(), sorter);
  1015. }
  1016. // Mark method list as uniqued and sorted
  1017. mlist->setFixedUp();
  1018. }
  1019. static void
  1020. prepareMethodLists(Class cls, method_list_t **addedLists, int addedCount,
  1021. bool baseMethods, bool methodsFromBundle)
  1022. {
  1023. runtimeLock.assertLocked();
  1024. if (addedCount == 0) return;
  1025. // There exist RR/AWZ/Core special cases for some class's base methods.
  1026. // But this code should never need to scan base methods for RR/AWZ/Core:
  1027. // default RR/AWZ/Core cannot be set before setInitialized().
  1028. // Therefore we need not handle any special cases here.
  1029. if (baseMethods) {
  1030. ASSERT(cls->hasCustomAWZ() && cls->hasCustomRR() && cls->hasCustomCore());
  1031. }
  1032. // Add method lists to array.
  1033. // Reallocate un-fixed method lists.
  1034. // The new methods are PREPENDED to the method list array.
  1035. for (int i = 0; i < addedCount; i++) {
  1036. method_list_t *mlist = addedLists[i];
  1037. ASSERT(mlist);
  1038. // Fixup selectors if necessary
  1039. if (!mlist->isFixedUp()) {
  1040. fixupMethodList(mlist, methodsFromBundle, true/*sort*/);
  1041. }
  1042. }
  1043. // If the class is initialized, then scan for method implementations
  1044. // tracked by the class's flags. If it's not initialized yet,
  1045. // then objc_class::setInitialized() will take care of it.
  1046. if (cls->isInitialized()) {
  1047. objc::AWZScanner::scanAddedMethodLists(cls, addedLists, addedCount);
  1048. objc::RRScanner::scanAddedMethodLists(cls, addedLists, addedCount);
  1049. objc::CoreScanner::scanAddedMethodLists(cls, addedLists, addedCount);
  1050. }
  1051. }
  1052. // Attach method lists and properties and protocols from categories to a class.
  1053. // Assumes the categories in cats are all loaded and sorted by load order,
  1054. // oldest categories first.
  1055. static void
  1056. attachCategories(Class cls, const locstamped_category_t *cats_list, uint32_t cats_count,
  1057. int flags)
  1058. {
  1059. if (slowpath(PrintReplacedMethods)) {
  1060. printReplacements(cls, cats_list, cats_count);
  1061. }
  1062. if (slowpath(PrintConnecting)) {
  1063. _objc_inform("CLASS: attaching %d categories to%s class '%s'%s",
  1064. cats_count, (flags & ATTACH_EXISTING) ? " existing" : "",
  1065. cls->nameForLogging(), (flags & ATTACH_METACLASS) ? " (meta)" : "");
  1066. }
  1067. /*
  1068. * Only a few classes have more than 64 categories during launch.
  1069. * This uses a little stack, and avoids malloc.
  1070. *
  1071. * Categories must be added in the proper order, which is back
  1072. * to front. To do that with the chunking, we iterate cats_list
  1073. * from front to back, build up the local buffers backwards,
  1074. * and call attachLists on the chunks. attachLists prepends the
  1075. * lists, so the final result is in the expected order.
  1076. */
  1077. constexpr uint32_t ATTACH_BUFSIZ = 64;
  1078. method_list_t *mlists[ATTACH_BUFSIZ];
  1079. property_list_t *proplists[ATTACH_BUFSIZ];
  1080. protocol_list_t *protolists[ATTACH_BUFSIZ];
  1081. uint32_t mcount = 0;
  1082. uint32_t propcount = 0;
  1083. uint32_t protocount = 0;
  1084. bool fromBundle = NO;
  1085. bool isMeta = (flags & ATTACH_METACLASS);
  1086. auto rw = cls->data();
  1087. for (uint32_t i = 0; i < cats_count; i++) {
  1088. auto& entry = cats_list[i];
  1089. method_list_t *mlist = entry.cat->methodsForMeta(isMeta);
  1090. if (mlist) {
  1091. if (mcount == ATTACH_BUFSIZ) {
  1092. prepareMethodLists(cls, mlists, mcount, NO, fromBundle);
  1093. rw->methods.attachLists(mlists, mcount);
  1094. mcount = 0;
  1095. }
  1096. mlists[ATTACH_BUFSIZ - ++mcount] = mlist;
  1097. fromBundle |= entry.hi->isBundle();
  1098. }
  1099. property_list_t *proplist =
  1100. entry.cat->propertiesForMeta(isMeta, entry.hi);
  1101. if (proplist) {
  1102. if (propcount == ATTACH_BUFSIZ) {
  1103. rw->properties.attachLists(proplists, propcount);
  1104. propcount = 0;
  1105. }
  1106. proplists[ATTACH_BUFSIZ - ++propcount] = proplist;
  1107. }
  1108. protocol_list_t *protolist = entry.cat->protocolsForMeta(isMeta);
  1109. if (protolist) {
  1110. if (protocount == ATTACH_BUFSIZ) {
  1111. rw->protocols.attachLists(protolists, protocount);
  1112. protocount = 0;
  1113. }
  1114. protolists[ATTACH_BUFSIZ - ++protocount] = protolist;
  1115. }
  1116. }
  1117. if (mcount > 0) {
  1118. prepareMethodLists(cls, mlists + ATTACH_BUFSIZ - mcount, mcount, NO, fromBundle);
  1119. rw->methods.attachLists(mlists + ATTACH_BUFSIZ - mcount, mcount);
  1120. if (flags & ATTACH_EXISTING) flushCaches(cls);
  1121. }
  1122. rw->properties.attachLists(proplists + ATTACH_BUFSIZ - propcount, propcount);
  1123. rw->protocols.attachLists(protolists + ATTACH_BUFSIZ - protocount, protocount);
  1124. }
  1125. /***********************************************************************
  1126. * methodizeClass
  1127. * Fixes up cls's method list, protocol list, and property list.
  1128. * Attaches any outstanding categories.
  1129. * Locking: runtimeLock must be held by the caller
  1130. **********************************************************************/
  1131. static void methodizeClass(Class cls, Class previously)
  1132. {
  1133. runtimeLock.assertLocked();
  1134. bool isMeta = cls->isMetaClass();
  1135. auto rw = cls->data();
  1136. auto ro = rw->ro;
  1137. // Methodizing for the first time
  1138. if (PrintConnecting) {
  1139. _objc_inform("CLASS: methodizing class '%s' %s",
  1140. cls->nameForLogging(), isMeta ? "(meta)" : "");
  1141. }
  1142. // Install methods and properties that the class implements itself.
  1143. method_list_t *list = ro->baseMethods();
  1144. if (list) {
  1145. prepareMethodLists(cls, &list, 1, YES, isBundleClass(cls));
  1146. rw->methods.attachLists(&list, 1);
  1147. }
  1148. property_list_t *proplist = ro->baseProperties;
  1149. if (proplist) {
  1150. rw->properties.attachLists(&proplist, 1);
  1151. }
  1152. protocol_list_t *protolist = ro->baseProtocols;
  1153. if (protolist) {
  1154. rw->protocols.attachLists(&protolist, 1);
  1155. }
  1156. // Root classes get bonus method implementations if they don't have
  1157. // them already. These apply before category replacements.
  1158. if (cls->isRootMetaclass()) {
  1159. // root metaclass
  1160. addMethod(cls, @selector(initialize), (IMP)&objc_noop_imp, "", NO);
  1161. }
  1162. // Attach categories.
  1163. if (previously) {
  1164. if (isMeta) {
  1165. objc::unattachedCategories.attachToClass(cls, previously,
  1166. ATTACH_METACLASS);
  1167. } else {
  1168. // When a class relocates, categories with class methods
  1169. // may be registered on the class itself rather than on
  1170. // the metaclass. Tell attachToClass to look for those.
  1171. objc::unattachedCategories.attachToClass(cls, previously,
  1172. ATTACH_CLASS_AND_METACLASS);
  1173. }
  1174. }
  1175. objc::unattachedCategories.attachToClass(cls, cls,
  1176. isMeta ? ATTACH_METACLASS : ATTACH_CLASS);
  1177. #if DEBUG
  1178. // Debug: sanity-check all SELs; log method list contents
  1179. for (const auto& meth : rw->methods) {
  1180. if (PrintConnecting) {
  1181. _objc_inform("METHOD %c[%s %s]", isMeta ? '+' : '-',
  1182. cls->nameForLogging(), sel_getName(meth.name));
  1183. }
  1184. ASSERT(sel_registerName(sel_getName(meth.name)) == meth.name);
  1185. }
  1186. #endif
  1187. }
  1188. /***********************************************************************
  1189. * nonMetaClasses
  1190. * Returns the secondary metaclass => class map
  1191. * Used for some cases of +initialize and +resolveClassMethod:.
  1192. * This map does not contain all class and metaclass pairs. It only
  1193. * contains metaclasses whose classes would be in the runtime-allocated
  1194. * named-class table, but are not because some other class with the same name
  1195. * is in that table.
  1196. * Classes with no duplicates are not included.
  1197. * Classes in the preoptimized named-class table are not included.
  1198. * Classes whose duplicates are in the preoptimized table are not included.
  1199. * Most code should use getMaybeUnrealizedNonMetaClass()
  1200. * instead of reading this table.
  1201. * Locking: runtimeLock must be read- or write-locked by the caller
  1202. **********************************************************************/
  1203. static NXMapTable *nonmeta_class_map = nil;
  1204. static NXMapTable *nonMetaClasses(void)
  1205. {
  1206. runtimeLock.assertLocked();
  1207. if (nonmeta_class_map) return nonmeta_class_map;
  1208. // nonmeta_class_map is typically small
  1209. INIT_ONCE_PTR(nonmeta_class_map,
  1210. NXCreateMapTable(NXPtrValueMapPrototype, 32),
  1211. NXFreeMapTable(v));
  1212. return nonmeta_class_map;
  1213. }
  1214. /***********************************************************************
  1215. * addNonMetaClass
  1216. * Adds metacls => cls to the secondary metaclass map
  1217. * Locking: runtimeLock must be held by the caller
  1218. **********************************************************************/
  1219. static void addNonMetaClass(Class cls)
  1220. {
  1221. runtimeLock.assertLocked();
  1222. void *old;
  1223. old = NXMapInsert(nonMetaClasses(), cls->ISA(), cls);
  1224. ASSERT(!cls->isMetaClassMaybeUnrealized());
  1225. ASSERT(cls->ISA()->isMetaClassMaybeUnrealized());
  1226. ASSERT(!old);
  1227. }
  1228. static void removeNonMetaClass(Class cls)
  1229. {
  1230. runtimeLock.assertLocked();
  1231. NXMapRemove(nonMetaClasses(), cls->ISA());
  1232. }
  1233. static bool scanMangledField(const char *&string, const char *end,
  1234. const char *&field, int& length)
  1235. {
  1236. // Leading zero not allowed.
  1237. if (*string == '0') return false;
  1238. length = 0;
  1239. field = string;
  1240. while (field < end) {
  1241. char c = *field;
  1242. if (!isdigit(c)) break;
  1243. field++;
  1244. if (__builtin_smul_overflow(length, 10, &length)) return false;
  1245. if (__builtin_sadd_overflow(length, c - '0', &length)) return false;
  1246. }
  1247. string = field + length;
  1248. return length > 0 && string <= end;
  1249. }
  1250. /***********************************************************************
  1251. * copySwiftV1DemangledName
  1252. * Returns the pretty form of the given Swift-v1-mangled class or protocol name.
  1253. * Returns nil if the string doesn't look like a mangled Swift v1 name.
  1254. * The result must be freed with free().
  1255. **********************************************************************/
  1256. static char *copySwiftV1DemangledName(const char *string, bool isProtocol = false)
  1257. {
  1258. if (!string) return nil;
  1259. // Swift mangling prefix.
  1260. if (strncmp(string, isProtocol ? "_TtP" : "_TtC", 4) != 0) return nil;
  1261. string += 4;
  1262. const char *end = string + strlen(string);
  1263. // Module name.
  1264. const char *prefix;
  1265. int prefixLength;
  1266. if (string[0] == 's') {
  1267. // "s" is the Swift module.
  1268. prefix = "Swift";
  1269. prefixLength = 5;
  1270. string += 1;
  1271. } else {
  1272. if (! scanMangledField(string, end, prefix, prefixLength)) return nil;
  1273. }
  1274. // Class or protocol name.
  1275. const char *suffix;
  1276. int suffixLength;
  1277. if (! scanMangledField(string, end, suffix, suffixLength)) return nil;
  1278. if (isProtocol) {
  1279. // Remainder must be "_".
  1280. if (strcmp(string, "_") != 0) return nil;
  1281. } else {
  1282. // Remainder must be empty.
  1283. if (string != end) return nil;
  1284. }
  1285. char *result;
  1286. asprintf(&result, "%.*s.%.*s", prefixLength,prefix, suffixLength,suffix);
  1287. return result;
  1288. }
  1289. /***********************************************************************
  1290. * copySwiftV1MangledName
  1291. * Returns the Swift 1.0 mangled form of the given class or protocol name.
  1292. * Returns nil if the string doesn't look like an unmangled Swift name.
  1293. * The result must be freed with free().
  1294. **********************************************************************/
  1295. static char *copySwiftV1MangledName(const char *string, bool isProtocol = false)
  1296. {
  1297. if (!string) return nil;
  1298. size_t dotCount = 0;
  1299. size_t dotIndex;
  1300. const char *s;
  1301. for (s = string; *s; s++) {
  1302. if (*s == '.') {
  1303. dotCount++;
  1304. dotIndex = s - string;
  1305. }
  1306. }
  1307. size_t stringLength = s - string;
  1308. if (dotCount != 1 || dotIndex == 0 || dotIndex >= stringLength-1) {
  1309. return nil;
  1310. }
  1311. const char *prefix = string;
  1312. size_t prefixLength = dotIndex;
  1313. const char *suffix = string + dotIndex + 1;
  1314. size_t suffixLength = stringLength - (dotIndex + 1);
  1315. char *name;
  1316. if (prefixLength == 5 && memcmp(prefix, "Swift", 5) == 0) {
  1317. asprintf(&name, "_Tt%cs%zu%.*s%s",
  1318. isProtocol ? 'P' : 'C',
  1319. suffixLength, (int)suffixLength, suffix,
  1320. isProtocol ? "_" : "");
  1321. } else {
  1322. asprintf(&name, "_Tt%c%zu%.*s%zu%.*s%s",
  1323. isProtocol ? 'P' : 'C',
  1324. prefixLength, (int)prefixLength, prefix,
  1325. suffixLength, (int)suffixLength, suffix,
  1326. isProtocol ? "_" : "");
  1327. }
  1328. return name;
  1329. }
  1330. /***********************************************************************
  1331. * getClassExceptSomeSwift
  1332. * Looks up a class by name. The class MIGHT NOT be realized.
  1333. * Demangled Swift names are recognized.
  1334. * Classes known to the Swift runtime but not yet used are NOT recognized.
  1335. * (such as subclasses of un-instantiated generics)
  1336. * Use look_up_class() to find them as well.
  1337. * Locking: runtimeLock must be read- or write-locked by the caller.
  1338. **********************************************************************/
  1339. // This is a misnomer: gdb_objc_realized_classes is actually a list of
  1340. // named classes not in the dyld shared cache, whether realized or not.
  1341. NXMapTable *gdb_objc_realized_classes; // exported for debuggers in objc-gdb.h
  1342. uintptr_t objc_debug_realized_class_generation_count;
  1343. static Class getClass_impl(const char *name)
  1344. {
  1345. runtimeLock.assertLocked();
  1346. // allocated in _read_images
  1347. ASSERT(gdb_objc_realized_classes);
  1348. // Try runtime-allocated table
  1349. Class result = (Class)NXMapGet(gdb_objc_realized_classes, name);
  1350. if (result) return result;
  1351. // Try table from dyld shared cache.
  1352. // Note we do this last to handle the case where we dlopen'ed a shared cache
  1353. // dylib with duplicates of classes already present in the main executable.
  1354. // In that case, we put the class from the main executable in
  1355. // gdb_objc_realized_classes and want to check that before considering any
  1356. // newly loaded shared cache binaries.
  1357. return getPreoptimizedClass(name);
  1358. }
  1359. static Class getClassExceptSomeSwift(const char *name)
  1360. {
  1361. runtimeLock.assertLocked();
  1362. // Try name as-is
  1363. Class result = getClass_impl(name);
  1364. if (result) return result;
  1365. // Try Swift-mangled equivalent of the given name.
  1366. if (char *swName = copySwiftV1MangledName(name)) {
  1367. result = getClass_impl(swName);
  1368. free(swName);
  1369. return result;
  1370. }
  1371. return nil;
  1372. }
  1373. /***********************************************************************
  1374. * addNamedClass
  1375. * Adds name => cls to the named non-meta class map.
  1376. * Warns about duplicate class names and keeps the old mapping.
  1377. * Locking: runtimeLock must be held by the caller
  1378. **********************************************************************/
  1379. static void addNamedClass(Class cls, const char *name, Class replacing = nil)
  1380. {
  1381. runtimeLock.assertLocked();
  1382. Class old;
  1383. if ((old = getClassExceptSomeSwift(name)) && old != replacing) {
  1384. inform_duplicate(name, old, cls);
  1385. // getMaybeUnrealizedNonMetaClass uses name lookups.
  1386. // Classes not found by name lookup must be in the
  1387. // secondary meta->nonmeta table.
  1388. addNonMetaClass(cls);
  1389. } else {
  1390. NXMapInsert(gdb_objc_realized_classes, name, cls);
  1391. }
  1392. ASSERT(!(cls->data()->flags & RO_META));
  1393. // wrong: constructed classes are already realized when they get here
  1394. // ASSERT(!cls->isRealized());
  1395. }
  1396. /***********************************************************************
  1397. * removeNamedClass
  1398. * Removes cls from the name => cls map.
  1399. * Locking: runtimeLock must be held by the caller
  1400. **********************************************************************/
  1401. static void removeNamedClass(Class cls, const char *name)
  1402. {
  1403. runtimeLock.assertLocked();
  1404. ASSERT(!(cls->data()->flags & RO_META));
  1405. if (cls == NXMapGet(gdb_objc_realized_classes, name)) {
  1406. NXMapRemove(gdb_objc_realized_classes, name);
  1407. } else {
  1408. // cls has a name collision with another class - don't remove the other
  1409. // but do remove cls from the secondary metaclass->class map.
  1410. removeNonMetaClass(cls);
  1411. }
  1412. }
  1413. /***********************************************************************
  1414. * futureNamedClasses
  1415. * Returns the classname => future class map for unrealized future classes.
  1416. * Locking: runtimeLock must be held by the caller
  1417. **********************************************************************/
  1418. static NXMapTable *future_named_class_map = nil;
  1419. static NXMapTable *futureNamedClasses()
  1420. {
  1421. runtimeLock.assertLocked();
  1422. if (future_named_class_map) return future_named_class_map;
  1423. // future_named_class_map is big enough for CF's classes and a few others
  1424. future_named_class_map =
  1425. NXCreateMapTable(NXStrValueMapPrototype, 32);
  1426. return future_named_class_map;
  1427. }
  1428. static bool haveFutureNamedClasses() {
  1429. return future_named_class_map && NXCountMapTable(future_named_class_map);
  1430. }
  1431. /***********************************************************************
  1432. * addFutureNamedClass
  1433. * Installs cls as the class structure to use for the named class if it appears.
  1434. * Locking: runtimeLock must be held by the caller
  1435. **********************************************************************/
  1436. static void addFutureNamedClass(const char *name, Class cls)
  1437. {
  1438. void *old;
  1439. runtimeLock.assertLocked();
  1440. if (PrintFuture) {
  1441. _objc_inform("FUTURE: reserving %p for %s", (void*)cls, name);
  1442. }
  1443. class_rw_t *rw = (class_rw_t *)calloc(sizeof(class_rw_t), 1);
  1444. class_ro_t *ro = (class_ro_t *)calloc(sizeof(class_ro_t), 1);
  1445. ro->name = strdupIfMutable(name);
  1446. rw->ro = ro;
  1447. cls->setData(rw);
  1448. cls->data()->flags = RO_FUTURE;
  1449. old = NXMapKeyCopyingInsert(futureNamedClasses(), name, cls);
  1450. ASSERT(!old);
  1451. }
  1452. /***********************************************************************
  1453. * popFutureNamedClass
  1454. * Removes the named class from the unrealized future class list,
  1455. * because it has been realized.
  1456. * Returns nil if the name is not used by a future class.
  1457. * Locking: runtimeLock must be held by the caller
  1458. **********************************************************************/
  1459. static Class popFutureNamedClass(const char *name)
  1460. {
  1461. runtimeLock.assertLocked();
  1462. Class cls = nil;
  1463. if (future_named_class_map) {
  1464. cls = (Class)NXMapKeyFreeingRemove(future_named_class_map, name);
  1465. if (cls && NXCountMapTable(future_named_class_map) == 0) {
  1466. NXFreeMapTable(future_named_class_map);
  1467. future_named_class_map = nil;
  1468. }
  1469. }
  1470. return cls;
  1471. }
  1472. /***********************************************************************
  1473. * remappedClasses
  1474. * Returns the oldClass => newClass map for realized future classes.
  1475. * Returns the oldClass => nil map for ignored weak-linked classes.
  1476. * Locking: runtimeLock must be read- or write-locked by the caller
  1477. **********************************************************************/
  1478. static objc::DenseMap<Class, Class> *remappedClasses(bool create)
  1479. {
  1480. static objc::LazyInitDenseMap<Class, Class> remapped_class_map;
  1481. runtimeLock.assertLocked();
  1482. // start big enough to hold CF's classes and a few others
  1483. return remapped_class_map.get(create, 32);
  1484. }
  1485. /***********************************************************************
  1486. * noClassesRemapped
  1487. * Returns YES if no classes have been remapped
  1488. * Locking: runtimeLock must be read- or write-locked by the caller
  1489. **********************************************************************/
  1490. static bool noClassesRemapped(void)
  1491. {
  1492. runtimeLock.assertLocked();
  1493. bool result = (remappedClasses(NO) == nil);
  1494. #if DEBUG
  1495. // Catch construction of an empty table, which defeats optimization.
  1496. auto *map = remappedClasses(NO);
  1497. if (map) ASSERT(map->size() > 0);
  1498. #endif
  1499. return result;
  1500. }
  1501. /***********************************************************************
  1502. * addRemappedClass
  1503. * newcls is a realized future class, replacing oldcls.
  1504. * OR newcls is nil, replacing ignored weak-linked class oldcls.
  1505. * Locking: runtimeLock must be write-locked by the caller
  1506. **********************************************************************/
  1507. static void addRemappedClass(Class oldcls, Class newcls)
  1508. {
  1509. runtimeLock.assertLocked();
  1510. if (PrintFuture) {
  1511. _objc_inform("FUTURE: using %p instead of %p for %s",
  1512. (void*)newcls, (void*)oldcls, oldcls->nameForLogging());
  1513. }
  1514. auto result = remappedClasses(YES)->insert({ oldcls, newcls });
  1515. #if DEBUG
  1516. if (!std::get<1>(result)) {
  1517. // An existing mapping was overwritten. This is not allowed
  1518. // unless it was to nil.
  1519. auto iterator = std::get<0>(result);
  1520. auto value = std::get<1>(*iterator);
  1521. ASSERT(value == nil);
  1522. }
  1523. #else
  1524. (void)result;
  1525. #endif
  1526. }
  1527. /***********************************************************************
  1528. * remapClass
  1529. * Returns the live class pointer for cls, which may be pointing to
  1530. * a class struct that has been reallocated.
  1531. * Returns nil if cls is ignored because of weak linking.
  1532. * Locking: runtimeLock must be read- or write-locked by the caller
  1533. **********************************************************************/
  1534. static Class remapClass(Class cls)
  1535. {
  1536. runtimeLock.assertLocked();
  1537. if (!cls) return nil;
  1538. auto *map = remappedClasses(NO);
  1539. if (!map)
  1540. return cls;
  1541. auto iterator = map->find(cls);
  1542. if (iterator == map->end())
  1543. return cls;
  1544. return std::get<1>(*iterator);
  1545. }
  1546. static Class remapClass(classref_t cls)
  1547. {
  1548. return remapClass((Class)cls);
  1549. }
  1550. Class _class_remap(Class cls)
  1551. {
  1552. mutex_locker_t lock(runtimeLock);
  1553. return remapClass(cls);
  1554. }
  1555. /***********************************************************************
  1556. * remapClassRef
  1557. * Fix up a class ref, in case the class referenced has been reallocated
  1558. * or is an ignored weak-linked class.
  1559. * Locking: runtimeLock must be read- or write-locked by the caller
  1560. **********************************************************************/
  1561. static void remapClassRef(Class *clsref)
  1562. {
  1563. runtimeLock.assertLocked();
  1564. Class newcls = remapClass(*clsref);
  1565. if (*clsref != newcls) *clsref = newcls;
  1566. }
  1567. _Nullable Class
  1568. objc_loadClassref(_Nullable Class * _Nonnull clsref)
  1569. {
  1570. auto *atomicClsref = explicit_atomic<uintptr_t>::from_pointer((uintptr_t *)clsref);
  1571. uintptr_t cls = atomicClsref->load(std::memory_order_relaxed);
  1572. if (fastpath((cls & 1) == 0))
  1573. return (Class)cls;
  1574. auto stub = (stub_class_t *)(cls & ~1ULL);
  1575. Class initialized = stub->initializer((Class)stub, nil);
  1576. atomicClsref->store((uintptr_t)initialized, std::memory_order_relaxed);
  1577. return initialized;
  1578. }
  1579. /***********************************************************************
  1580. * getMaybeUnrealizedNonMetaClass
  1581. * Return the ordinary class for this class or metaclass.
  1582. * `inst` is an instance of `cls` or a subclass thereof, or nil.
  1583. * Non-nil inst is faster.
  1584. * The result may be unrealized.
  1585. * Used by +initialize.
  1586. * Locking: runtimeLock must be read- or write-locked by the caller
  1587. **********************************************************************/
  1588. static Class getMaybeUnrealizedNonMetaClass(Class metacls, id inst)
  1589. {
  1590. static int total, named, secondary, sharedcache, dyld3;
  1591. runtimeLock.assertLocked();
  1592. ASSERT(metacls->isRealized());
  1593. total++;
  1594. // return cls itself if it's already a non-meta class
  1595. if (!metacls->isMetaClass()) return metacls;
  1596. // metacls really is a metaclass
  1597. // which means inst (if any) is a class
  1598. // special case for root metaclass
  1599. // where inst == inst->ISA() == metacls is possible
  1600. if (metacls->ISA() == metacls) {
  1601. Class cls = metacls->superclass;
  1602. ASSERT(cls->isRealized());
  1603. ASSERT(!cls->isMetaClass());
  1604. ASSERT(cls->ISA() == metacls);
  1605. if (cls->ISA() == metacls) return cls;
  1606. }
  1607. // use inst if available
  1608. if (inst) {
  1609. Class cls = remapClass((Class)inst);
  1610. // cls may be a subclass - find the real class for metacls
  1611. // fixme this probably stops working once Swift starts
  1612. // reallocating classes if cls is unrealized.
  1613. while (cls) {
  1614. if (cls->ISA() == metacls) {
  1615. ASSERT(!cls->isMetaClassMaybeUnrealized());
  1616. return cls;
  1617. }
  1618. cls = cls->superclass;
  1619. }
  1620. #if DEBUG
  1621. _objc_fatal("cls is not an instance of metacls");
  1622. #else
  1623. // release build: be forgiving and fall through to slow lookups
  1624. #endif
  1625. }
  1626. // try name lookup
  1627. {
  1628. Class cls = getClassExceptSomeSwift(metacls->mangledName());
  1629. if (cls && cls->ISA() == metacls) {
  1630. named++;
  1631. if (PrintInitializing) {
  1632. _objc_inform("INITIALIZE: %d/%d (%g%%) "
  1633. "successful by-name metaclass lookups",
  1634. named, total, named*100.0/total);
  1635. }
  1636. return cls;
  1637. }
  1638. }
  1639. // try secondary table
  1640. {
  1641. Class cls = (Class)NXMapGet(nonMetaClasses(), metacls);
  1642. if (cls) {
  1643. secondary++;
  1644. if (PrintInitializing) {
  1645. _objc_inform("INITIALIZE: %d/%d (%g%%) "
  1646. "successful secondary metaclass lookups",
  1647. secondary, total, secondary*100.0/total);
  1648. }
  1649. ASSERT(cls->ISA() == metacls);
  1650. return cls;
  1651. }
  1652. }
  1653. // try the dyld closure table
  1654. if (isPreoptimized())
  1655. {
  1656. // Try table from dyld closure first. It was built to ignore the dupes it
  1657. // knows will come from the cache, so anything left in here was there when
  1658. // we launched
  1659. Class cls = nil;
  1660. // Note, we have to pass the lambda directly here as otherwise we would try
  1661. // message copy and autorelease.
  1662. _dyld_for_each_objc_class(metacls->mangledName(),
  1663. [&cls, metacls](void* classPtr, bool isLoaded, bool* stop) {
  1664. // Skip images which aren't loaded. This supports the case where dyld
  1665. // might soft link an image from the main binary so its possibly not
  1666. // loaded yet.
  1667. if (!isLoaded)
  1668. return;
  1669. // Found a loaded image with this class name, so check if its the right one
  1670. Class result = (Class)classPtr;
  1671. if (result->ISA() == metacls) {
  1672. cls = result;
  1673. *stop = true;
  1674. }
  1675. });
  1676. if (cls) {
  1677. dyld3++;
  1678. if (PrintInitializing) {
  1679. _objc_inform("INITIALIZE: %d/%d (%g%%) "
  1680. "successful dyld closure metaclass lookups",
  1681. dyld3, total, dyld3*100.0/total);
  1682. }
  1683. return cls;
  1684. }
  1685. }
  1686. // try any duplicates in the dyld shared cache
  1687. {
  1688. Class cls = nil;
  1689. int count;
  1690. Class *classes = copyPreoptimizedClasses(metacls->mangledName(),&count);
  1691. if (classes) {
  1692. for (int i = 0; i < count; i++) {
  1693. if (classes[i]->ISA() == metacls) {
  1694. cls = classes[i];
  1695. break;
  1696. }
  1697. }
  1698. free(classes);
  1699. }
  1700. if (cls) {
  1701. sharedcache++;
  1702. if (PrintInitializing) {
  1703. _objc_inform("INITIALIZE: %d/%d (%g%%) "
  1704. "successful shared cache metaclass lookups",
  1705. sharedcache, total, sharedcache*100.0/total);
  1706. }
  1707. return cls;
  1708. }
  1709. }
  1710. _objc_fatal("no class for metaclass %p", (void*)metacls);
  1711. }
  1712. /***********************************************************************
  1713. * class_initialize. Send the '+initialize' message on demand to any
  1714. * uninitialized class. Force initialization of superclasses first.
  1715. * inst is an instance of cls, or nil. Non-nil is better for performance.
  1716. * Returns the class pointer. If the class was unrealized then
  1717. * it may be reallocated.
  1718. * Locking:
  1719. * runtimeLock must be held by the caller
  1720. * This function may drop the lock.
  1721. * On exit the lock is re-acquired or dropped as requested by leaveLocked.
  1722. **********************************************************************/
  1723. static Class initializeAndMaybeRelock(Class cls, id inst,
  1724. mutex_t& lock, bool leaveLocked)
  1725. {
  1726. lock.assertLocked();
  1727. ASSERT(cls->isRealized());
  1728. if (cls->isInitialized()) {
  1729. if (!leaveLocked) lock.unlock();
  1730. return cls;
  1731. }
  1732. // Find the non-meta class for cls, if it is not already one.
  1733. // The +initialize message is sent to the non-meta class object.
  1734. Class nonmeta = getMaybeUnrealizedNonMetaClass(cls, inst);
  1735. // Realize the non-meta class if necessary.
  1736. if (nonmeta->isRealized()) {
  1737. // nonmeta is cls, which was already realized
  1738. // OR nonmeta is distinct, but is already realized
  1739. // - nothing else to do
  1740. lock.unlock();
  1741. } else {
  1742. nonmeta = realizeClassMaybeSwiftAndUnlock(nonmeta, lock);
  1743. // runtimeLock is now unlocked
  1744. // fixme Swift can't relocate the class today,
  1745. // but someday it will:
  1746. cls = object_getClass(nonmeta);
  1747. }
  1748. // runtimeLock is now unlocked, for +initialize dispatch
  1749. ASSERT(nonmeta->isRealized());
  1750. initializeNonMetaClass(nonmeta);
  1751. if (leaveLocked) runtimeLock.lock();
  1752. return cls;
  1753. }
  1754. // Locking: acquires runtimeLock
  1755. Class class_initialize(Class cls, id obj)
  1756. {
  1757. runtimeLock.lock();
  1758. return initializeAndMaybeRelock(cls, obj, runtimeLock, false);
  1759. }
  1760. // Locking: caller must hold runtimeLock; this may drop and re-acquire it
  1761. static Class initializeAndLeaveLocked(Class cls, id obj, mutex_t& lock)
  1762. {
  1763. return initializeAndMaybeRelock(cls, obj, lock, true);
  1764. }
  1765. /***********************************************************************
  1766. * addRootClass
  1767. * Adds cls as a new realized root class.
  1768. * Locking: runtimeLock must be held by the caller.
  1769. **********************************************************************/
  1770. static void addRootClass(Class cls)
  1771. {
  1772. runtimeLock.assertLocked();
  1773. ASSERT(cls->isRealized());
  1774. objc_debug_realized_class_generation_count++;
  1775. cls->data()->nextSiblingClass = _firstRealizedClass;
  1776. _firstRealizedClass = cls;
  1777. }
  1778. static void removeRootClass(Class cls)
  1779. {
  1780. runtimeLock.assertLocked();
  1781. objc_debug_realized_class_generation_count++;
  1782. Class *classp;
  1783. for (classp = &_firstRealizedClass;
  1784. *classp != cls;
  1785. classp = &(*classp)->data()->nextSiblingClass)
  1786. { }
  1787. *classp = (*classp)->data()->nextSiblingClass;
  1788. }
  1789. /***********************************************************************
  1790. * addSubclass
  1791. * Adds subcls as a subclass of supercls.
  1792. * Locking: runtimeLock must be held by the caller.
  1793. **********************************************************************/
  1794. static void addSubclass(Class supercls, Class subcls)
  1795. {
  1796. runtimeLock.assertLocked();
  1797. if (supercls && subcls) {
  1798. ASSERT(supercls->isRealized());
  1799. ASSERT(subcls->isRealized());
  1800. objc_debug_realized_class_generation_count++;
  1801. subcls->data()->nextSiblingClass = supercls->data()->firstSubclass;
  1802. supercls->data()->firstSubclass = subcls;
  1803. if (supercls->hasCxxCtor()) {
  1804. subcls->setHasCxxCtor();
  1805. }
  1806. if (supercls->hasCxxDtor()) {
  1807. subcls->setHasCxxDtor();
  1808. }
  1809. objc::AWZScanner::scanAddedSubClass(subcls, supercls);
  1810. objc::RRScanner::scanAddedSubClass(subcls, supercls);
  1811. objc::CoreScanner::scanAddedSubClass(subcls, supercls);
  1812. // Special case: instancesRequireRawIsa does not propagate
  1813. // from root class to root metaclass
  1814. if (supercls->instancesRequireRawIsa() && supercls->superclass) {
  1815. subcls->setInstancesRequireRawIsaRecursively(true);
  1816. }
  1817. }
  1818. }
  1819. /***********************************************************************
  1820. * removeSubclass
  1821. * Removes subcls as a subclass of supercls.
  1822. * Locking: runtimeLock must be held by the caller.
  1823. **********************************************************************/
  1824. static void removeSubclass(Class supercls, Class subcls)
  1825. {
  1826. runtimeLock.assertLocked();
  1827. ASSERT(supercls->isRealized());
  1828. ASSERT(subcls->isRealized());
  1829. ASSERT(subcls->superclass == supercls);
  1830. objc_debug_realized_class_generation_count++;
  1831. Class *cp;
  1832. for (cp = &supercls->data()->firstSubclass;
  1833. *cp && *cp != subcls;
  1834. cp = &(*cp)->data()->nextSiblingClass)
  1835. ;
  1836. ASSERT(*cp == subcls);
  1837. *cp = subcls->data()->nextSiblingClass;
  1838. }
  1839. /***********************************************************************
  1840. * protocols
  1841. * Returns the protocol name => protocol map for protocols.
  1842. * Locking: runtimeLock must read- or write-locked by the caller
  1843. **********************************************************************/
  1844. static NXMapTable *protocols(void)
  1845. {
  1846. static NXMapTable *protocol_map = nil;
  1847. runtimeLock.assertLocked();
  1848. INIT_ONCE_PTR(protocol_map,
  1849. NXCreateMapTable(NXStrValueMapPrototype, 16),
  1850. NXFreeMapTable(v) );
  1851. return protocol_map;
  1852. }
  1853. /***********************************************************************
  1854. * getProtocol
  1855. * Looks up a protocol by name. Demangled Swift names are recognized.
  1856. * Locking: runtimeLock must be read- or write-locked by the caller.
  1857. **********************************************************************/
  1858. static NEVER_INLINE Protocol *getProtocol(const char *name)
  1859. {
  1860. runtimeLock.assertLocked();
  1861. // Try name as-is.
  1862. Protocol *result = (Protocol *)NXMapGet(protocols(), name);
  1863. if (result) return result;
  1864. // Try Swift-mangled equivalent of the given name.
  1865. if (char *swName = copySwiftV1MangledName(name, true/*isProtocol*/)) {
  1866. result = (Protocol *)NXMapGet(protocols(), swName);
  1867. free(swName);
  1868. if (result) return result;
  1869. }
  1870. // Try table from dyld shared cache
  1871. // Temporarily check that we are using the new table. Eventually this check
  1872. // will always be true.
  1873. // FIXME: Remove this check when we can
  1874. if (sharedCacheSupportsProtocolRoots()) {
  1875. result = getPreoptimizedProtocol(name);
  1876. if (result) return result;
  1877. }
  1878. return nil;
  1879. }
  1880. /***********************************************************************
  1881. * remapProtocol
  1882. * Returns the live protocol pointer for proto, which may be pointing to
  1883. * a protocol struct that has been reallocated.
  1884. * Locking: runtimeLock must be read- or write-locked by the caller
  1885. **********************************************************************/
  1886. static ALWAYS_INLINE protocol_t *remapProtocol(protocol_ref_t proto)
  1887. {
  1888. runtimeLock.assertLocked();
  1889. // Protocols in shared cache images have a canonical bit to mark that they
  1890. // are the definition we should use
  1891. if (((protocol_t *)proto)->isCanonical())
  1892. return (protocol_t *)proto;
  1893. protocol_t *newproto = (protocol_t *)
  1894. getProtocol(((protocol_t *)proto)->mangledName);
  1895. return newproto ? newproto : (protocol_t *)proto;
  1896. }
  1897. /***********************************************************************
  1898. * remapProtocolRef
  1899. * Fix up a protocol ref, in case the protocol referenced has been reallocated.
  1900. * Locking: runtimeLock must be read- or write-locked by the caller
  1901. **********************************************************************/
  1902. static size_t UnfixedProtocolReferences;
  1903. static void remapProtocolRef(protocol_t **protoref)
  1904. {
  1905. runtimeLock.assertLocked();
  1906. protocol_t *newproto = remapProtocol((protocol_ref_t)*protoref);
  1907. if (*protoref != newproto) {
  1908. *protoref = newproto;
  1909. UnfixedProtocolReferences++;
  1910. }
  1911. }
  1912. /***********************************************************************
  1913. * moveIvars
  1914. * Slides a class's ivars to accommodate the given superclass size.
  1915. * Ivars are NOT compacted to compensate for a superclass that shrunk.
  1916. * Locking: runtimeLock must be held by the caller.
  1917. **********************************************************************/
  1918. static void moveIvars(class_ro_t *ro, uint32_t superSize)
  1919. {
  1920. runtimeLock.assertLocked();
  1921. uint32_t diff;
  1922. ASSERT(superSize > ro->instanceStart);
  1923. diff = superSize - ro->instanceStart;
  1924. if (ro->ivars) {
  1925. // Find maximum alignment in this class's ivars
  1926. uint32_t maxAlignment = 1;
  1927. for (const auto& ivar : *ro->ivars) {
  1928. if (!ivar.offset) continue; // anonymous bitfield
  1929. uint32_t alignment = ivar.alignment();
  1930. if (alignment > maxAlignment) maxAlignment = alignment;
  1931. }
  1932. // Compute a slide value that preserves that alignment
  1933. uint32_t alignMask = maxAlignment - 1;
  1934. diff = (diff + alignMask) & ~alignMask;
  1935. // Slide all of this class's ivars en masse
  1936. for (const auto& ivar : *ro->ivars) {
  1937. if (!ivar.offset) continue; // anonymous bitfield
  1938. uint32_t oldOffset = (uint32_t)*ivar.offset;
  1939. uint32_t newOffset = oldOffset + diff;
  1940. *ivar.offset = newOffset;
  1941. if (PrintIvars) {
  1942. _objc_inform("IVARS: offset %u -> %u for %s "
  1943. "(size %u, align %u)",
  1944. oldOffset, newOffset, ivar.name,
  1945. ivar.size, ivar.alignment());
  1946. }
  1947. }
  1948. }
  1949. *(uint32_t *)&ro->instanceStart += diff;
  1950. *(uint32_t *)&ro->instanceSize += diff;
  1951. }
  1952. static void reconcileInstanceVariables(Class cls, Class supercls, const class_ro_t*& ro)
  1953. {
  1954. class_rw_t *rw = cls->data();
  1955. ASSERT(supercls);
  1956. ASSERT(!cls->isMetaClass());
  1957. /* debug: print them all before sliding
  1958. if (ro->ivars) {
  1959. for (const auto& ivar : *ro->ivars) {
  1960. if (!ivar.offset) continue; // anonymous bitfield
  1961. _objc_inform("IVARS: %s.%s (offset %u, size %u, align %u)",
  1962. ro->name, ivar.name,
  1963. *ivar.offset, ivar.size, ivar.alignment());
  1964. }
  1965. }
  1966. */
  1967. // Non-fragile ivars - reconcile this class with its superclass
  1968. const class_ro_t *super_ro = supercls->data()->ro;
  1969. if (DebugNonFragileIvars) {
  1970. // Debugging: Force non-fragile ivars to slide.
  1971. // Intended to find compiler, runtime, and program bugs.
  1972. // If it fails with this and works without, you have a problem.
  1973. // Operation: Reset everything to 0 + misalignment.
  1974. // Then force the normal sliding logic to push everything back.
  1975. // Exceptions: root classes, metaclasses, *NSCF* classes,
  1976. // __CF* classes, NSConstantString, NSSimpleCString
  1977. // (already know it's not root because supercls != nil)
  1978. const char *clsname = cls->mangledName();
  1979. if (!strstr(clsname, "NSCF") &&
  1980. 0 != strncmp(clsname, "__CF", 4) &&
  1981. 0 != strcmp(clsname, "NSConstantString") &&
  1982. 0 != strcmp(clsname, "NSSimpleCString"))
  1983. {
  1984. uint32_t oldStart = ro->instanceStart;
  1985. class_ro_t *ro_w = make_ro_writeable(rw);
  1986. ro = rw->ro;
  1987. // Find max ivar alignment in class.
  1988. // default to word size to simplify ivar update
  1989. uint32_t alignment = 1<<WORD_SHIFT;
  1990. if (ro->ivars) {
  1991. for (const auto& ivar : *ro->ivars) {
  1992. if (ivar.alignment() > alignment) {
  1993. alignment = ivar.alignment();
  1994. }
  1995. }
  1996. }
  1997. uint32_t misalignment = ro->instanceStart % alignment;
  1998. uint32_t delta = ro->instanceStart - misalignment;
  1999. ro_w->instanceStart = misalignment;
  2000. ro_w->instanceSize -= delta;
  2001. if (PrintIvars) {
  2002. _objc_inform("IVARS: DEBUG: forcing ivars for class '%s' "
  2003. "to slide (instanceStart %zu -> %zu)",
  2004. cls->nameForLogging(), (size_t)oldStart,
  2005. (size_t)ro->instanceStart);
  2006. }
  2007. if (ro->ivars) {
  2008. for (const auto& ivar : *ro->ivars) {
  2009. if (!ivar.offset) continue; // anonymous bitfield
  2010. *ivar.offset -= delta;
  2011. }
  2012. }
  2013. }
  2014. }
  2015. if (ro->instanceStart >= super_ro->instanceSize) {
  2016. // Superclass has not overgrown its space. We're done here.
  2017. return;
  2018. }
  2019. // fixme can optimize for "class has no new ivars", etc
  2020. if (ro->instanceStart < super_ro->instanceSize) {
  2021. // Superclass has changed size. This class's ivars must move.
  2022. // Also slide layout bits in parallel.
  2023. // This code is incapable of compacting the subclass to
  2024. // compensate for a superclass that shrunk, so don't do that.
  2025. if (PrintIvars) {
  2026. _objc_inform("IVARS: sliding ivars for class %s "
  2027. "(superclass was %u bytes, now %u)",
  2028. cls->nameForLogging(), ro->instanceStart,
  2029. super_ro->instanceSize);
  2030. }
  2031. class_ro_t *ro_w = make_ro_writeable(rw);
  2032. ro = rw->ro;
  2033. moveIvars(ro_w, super_ro->instanceSize);
  2034. gdb_objc_class_changed(cls, OBJC_CLASS_IVARS_CHANGED, ro->name);
  2035. }
  2036. }
  2037. /***********************************************************************
  2038. * realizeClassWithoutSwift
  2039. * Performs first-time initialization on class cls,
  2040. * including allocating its read-write data.
  2041. * Does not perform any Swift-side initialization.
  2042. * Returns the real class structure for the class.
  2043. * Locking: runtimeLock must be write-locked by the caller
  2044. **********************************************************************/
  2045. static Class realizeClassWithoutSwift(Class cls, Class previously)
  2046. {
  2047. runtimeLock.assertLocked();
  2048. const class_ro_t *ro;
  2049. class_rw_t *rw;
  2050. Class supercls;
  2051. Class metacls;
  2052. bool isMeta;
  2053. if (!cls) return nil;
  2054. if (cls->isRealized()) return cls;
  2055. ASSERT(cls == remapClass(cls));
  2056. // fixme verify class is not in an un-dlopened part of the shared cache?
  2057. ro = (const class_ro_t *)cls->data();
  2058. if (ro->flags & RO_FUTURE) {
  2059. // This was a future class. rw data is already allocated.
  2060. rw = cls->data();
  2061. ro = cls->data()->ro;
  2062. cls->changeInfo(RW_REALIZED|RW_REALIZING, RW_FUTURE);
  2063. } else {
  2064. // Normal class. Allocate writeable class data.
  2065. rw = (class_rw_t *)calloc(sizeof(class_rw_t), 1);
  2066. rw->ro = ro;
  2067. rw->flags = RW_REALIZED|RW_REALIZING;
  2068. cls->setData(rw);
  2069. }
  2070. isMeta = ro->flags & RO_META;
  2071. #if FAST_CACHE_META
  2072. if (isMeta) cls->cache.setBit(FAST_CACHE_META);
  2073. #endif
  2074. rw->version = isMeta ? 7 : 0; // old runtime went up to 6
  2075. // Choose an index for this class.
  2076. // Sets cls->instancesRequireRawIsa if indexes no more indexes are available
  2077. cls->chooseClassArrayIndex();
  2078. if (PrintConnecting) {
  2079. _objc_inform("CLASS: realizing class '%s'%s %p %p #%u %s%s",
  2080. cls->nameForLogging(), isMeta ? " (meta)" : "",
  2081. (void*)cls, ro, cls->classArrayIndex(),
  2082. cls->isSwiftStable() ? "(swift)" : "",
  2083. cls->isSwiftLegacy() ? "(pre-stable swift)" : "");
  2084. }
  2085. // Realize superclass and metaclass, if they aren't already.
  2086. // This needs to be done after RW_REALIZED is set above, for root classes.
  2087. // This needs to be done after class index is chosen, for root metaclasses.
  2088. // This assumes that none of those classes have Swift contents,
  2089. // or that Swift's initializers have already been called.
  2090. // fixme that assumption will be wrong if we add support
  2091. // for ObjC subclasses of Swift classes.
  2092. supercls = realizeClassWithoutSwift(remapClass(cls->superclass), nil);
  2093. metacls = realizeClassWithoutSwift(remapClass(cls->ISA()), nil);
  2094. #if SUPPORT_NONPOINTER_ISA
  2095. if (isMeta) {
  2096. // Metaclasses do not need any features from non pointer ISA
  2097. // This allows for a faspath for classes in objc_retain/objc_release.
  2098. cls->setInstancesRequireRawIsa();
  2099. } else {
  2100. // Disable non-pointer isa for some classes and/or platforms.
  2101. // Set instancesRequireRawIsa.
  2102. bool instancesRequireRawIsa = cls->instancesRequireRawIsa();
  2103. bool rawIsaIsInherited = false;
  2104. static bool hackedDispatch = false;
  2105. if (DisableNonpointerIsa) {
  2106. // Non-pointer isa disabled by environment or app SDK version
  2107. instancesRequireRawIsa = true;
  2108. }
  2109. else if (!hackedDispatch && 0 == strcmp(ro->name, "OS_object"))
  2110. {
  2111. // hack for libdispatch et al - isa also acts as vtable pointer
  2112. hackedDispatch = true;
  2113. instancesRequireRawIsa = true;
  2114. }
  2115. else if (supercls && supercls->superclass &&
  2116. supercls->instancesRequireRawIsa())
  2117. {
  2118. // This is also propagated by addSubclass()
  2119. // but nonpointer isa setup needs it earlier.
  2120. // Special case: instancesRequireRawIsa does not propagate
  2121. // from root class to root metaclass
  2122. instancesRequireRawIsa = true;
  2123. rawIsaIsInherited = true;
  2124. }
  2125. if (instancesRequireRawIsa) {
  2126. cls->setInstancesRequireRawIsaRecursively(rawIsaIsInherited);
  2127. }
  2128. }
  2129. // SUPPORT_NONPOINTER_ISA
  2130. #endif
  2131. // Update superclass and metaclass in case of remapping
  2132. cls->superclass = supercls;
  2133. cls->initClassIsa(metacls);
  2134. // Reconcile instance variable offsets / layout.
  2135. // This may reallocate class_ro_t, updating our ro variable.
  2136. if (supercls && !isMeta) reconcileInstanceVariables(cls, supercls, ro);
  2137. // Set fastInstanceSize if it wasn't set already.
  2138. cls->setInstanceSize(ro->instanceSize);
  2139. // Copy some flags from ro to rw
  2140. if (ro->flags & RO_HAS_CXX_STRUCTORS) {
  2141. cls->setHasCxxDtor();
  2142. if (! (ro->flags & RO_HAS_CXX_DTOR_ONLY)) {
  2143. cls->setHasCxxCtor();
  2144. }
  2145. }
  2146. // Propagate the associated objects forbidden flag from ro or from
  2147. // the superclass.
  2148. if ((ro->flags & RO_FORBIDS_ASSOCIATED_OBJECTS) ||
  2149. (supercls && supercls->forbidsAssociatedObjects()))
  2150. {
  2151. rw->flags |= RW_FORBIDS_ASSOCIATED_OBJECTS;
  2152. }
  2153. // Connect this class to its superclass's subclass lists
  2154. if (supercls) {
  2155. addSubclass(supercls, cls);
  2156. } else {
  2157. addRootClass(cls);
  2158. }
  2159. // Attach categories
  2160. methodizeClass(cls, previously);
  2161. return cls;
  2162. }
  2163. /***********************************************************************
  2164. * _objc_realizeClassFromSwift
  2165. * Called by Swift when it needs the ObjC part of a class to be realized.
  2166. * There are four cases:
  2167. * 1. cls != nil; previously == cls
  2168. * Class cls is being realized in place
  2169. * 2. cls != nil; previously == nil
  2170. * Class cls is being constructed at runtime
  2171. * 3. cls != nil; previously != cls
  2172. * The class that was at previously has been reallocated to cls
  2173. * 4. cls == nil, previously != nil
  2174. * The class at previously is hereby disavowed
  2175. *
  2176. * Only variants #1 and #2 are supported today.
  2177. *
  2178. * Locking: acquires runtimeLock
  2179. **********************************************************************/
  2180. Class _objc_realizeClassFromSwift(Class cls, void *previously)
  2181. {
  2182. if (cls) {
  2183. if (previously && previously != (void*)cls) {
  2184. // #3: relocation
  2185. mutex_locker_t lock(runtimeLock);
  2186. addRemappedClass((Class)previously, cls);
  2187. addClassTableEntry(cls);
  2188. addNamedClass(cls, cls->mangledName(), /*replacing*/nil);
  2189. return realizeClassWithoutSwift(cls, (Class)previously);
  2190. } else {
  2191. // #1 and #2: realization in place, or new class
  2192. mutex_locker_t lock(runtimeLock);
  2193. if (!previously) {
  2194. // #2: new class
  2195. cls = readClass(cls, false/*bundle*/, false/*shared cache*/);
  2196. }
  2197. // #1 and #2: realization in place, or new class
  2198. // We ignore the Swift metadata initializer callback.
  2199. // We assume that's all handled since we're being called from Swift.
  2200. return realizeClassWithoutSwift(cls, nil);
  2201. }
  2202. }
  2203. else {
  2204. // #4: disavowal
  2205. // In the future this will mean remapping the old address to nil
  2206. // and if necessary removing the old address from any other tables.
  2207. _objc_fatal("Swift requested that class %p be ignored, "
  2208. "but libobjc does not support that.", previously);
  2209. }
  2210. }
  2211. /***********************************************************************
  2212. * realizeSwiftClass
  2213. * Performs first-time initialization on class cls,
  2214. * including allocating its read-write data,
  2215. * and any Swift-side initialization.
  2216. * Returns the real class structure for the class.
  2217. * Locking: acquires runtimeLock indirectly
  2218. **********************************************************************/
  2219. static Class realizeSwiftClass(Class cls)
  2220. {
  2221. runtimeLock.assertUnlocked();
  2222. // Some assumptions:
  2223. // * Metaclasses never have a Swift initializer.
  2224. // * Root classes never have a Swift initializer.
  2225. // (These two together avoid initialization order problems at the root.)
  2226. // * Unrealized non-Swift classes have no Swift ancestry.
  2227. // * Unrealized Swift classes with no initializer have no ancestry that
  2228. // does have the initializer.
  2229. // (These two together mean we don't need to scan superclasses here
  2230. // and we don't need to worry about Swift superclasses inside
  2231. // realizeClassWithoutSwift()).
  2232. // fixme some of these assumptions will be wrong
  2233. // if we add support for ObjC sublasses of Swift classes.
  2234. #if DEBUG
  2235. runtimeLock.lock();
  2236. ASSERT(remapClass(cls) == cls);
  2237. ASSERT(cls->isSwiftStable_ButAllowLegacyForNow());
  2238. ASSERT(!cls->isMetaClassMaybeUnrealized());
  2239. ASSERT(cls->superclass);
  2240. runtimeLock.unlock();
  2241. #endif
  2242. // Look for a Swift metadata initialization function
  2243. // installed on the class. If it is present we call it.
  2244. // That function in turn initializes the Swift metadata,
  2245. // prepares the "compiler-generated" ObjC metadata if not
  2246. // already present, and calls _objc_realizeSwiftClass() to finish
  2247. // our own initialization.
  2248. if (auto init = cls->swiftMetadataInitializer()) {
  2249. if (PrintConnecting) {
  2250. _objc_inform("CLASS: calling Swift metadata initializer "
  2251. "for class '%s' (%p)", cls->nameForLogging(), cls);
  2252. }
  2253. Class newcls = init(cls, nil);
  2254. // fixme someday Swift will need to relocate classes at this point,
  2255. // but we don't accept that yet.
  2256. if (cls != newcls) {
  2257. mutex_locker_t lock(runtimeLock);
  2258. addRemappedClass(cls, newcls);
  2259. }
  2260. return newcls;
  2261. }
  2262. else {
  2263. // No Swift-side initialization callback.
  2264. // Perform our own realization directly.
  2265. mutex_locker_t lock(runtimeLock);
  2266. return realizeClassWithoutSwift(cls, nil);
  2267. }
  2268. }
  2269. /***********************************************************************
  2270. * realizeClassMaybeSwift (MaybeRelock / AndUnlock / AndLeaveLocked)
  2271. * Realize a class that might be a Swift class.
  2272. * Returns the real class structure for the class.
  2273. * Locking:
  2274. * runtimeLock must be held on entry
  2275. * runtimeLock may be dropped during execution
  2276. * ...AndUnlock function leaves runtimeLock unlocked on exit
  2277. * ...AndLeaveLocked re-acquires runtimeLock if it was dropped
  2278. * This complication avoids repeated lock transitions in some cases.
  2279. **********************************************************************/
  2280. static Class
  2281. realizeClassMaybeSwiftMaybeRelock(Class cls, mutex_t& lock, bool leaveLocked)
  2282. {
  2283. lock.assertLocked();
  2284. if (!cls->isSwiftStable_ButAllowLegacyForNow()) {
  2285. // Non-Swift class. Realize it now with the lock still held.
  2286. // fixme wrong in the future for objc subclasses of swift classes
  2287. realizeClassWithoutSwift(cls, nil);
  2288. if (!leaveLocked) lock.unlock();
  2289. } else {
  2290. // Swift class. We need to drop locks and call the Swift
  2291. // runtime to initialize it.
  2292. lock.unlock();
  2293. cls = realizeSwiftClass(cls);
  2294. ASSERT(cls->isRealized()); // callback must have provoked realization
  2295. if (leaveLocked) lock.lock();
  2296. }
  2297. return cls;
  2298. }
  2299. static Class
  2300. realizeClassMaybeSwiftAndUnlock(Class cls, mutex_t& lock)
  2301. {
  2302. return realizeClassMaybeSwiftMaybeRelock(cls, lock, false);
  2303. }
  2304. static Class
  2305. realizeClassMaybeSwiftAndLeaveLocked(Class cls, mutex_t& lock)
  2306. {
  2307. return realizeClassMaybeSwiftMaybeRelock(cls, lock, true);
  2308. }
  2309. /***********************************************************************
  2310. * missingWeakSuperclass
  2311. * Return YES if some superclass of cls was weak-linked and is missing.
  2312. **********************************************************************/
  2313. static bool
  2314. missingWeakSuperclass(Class cls)
  2315. {
  2316. ASSERT(!cls->isRealized());
  2317. if (!cls->superclass) {
  2318. // superclass nil. This is normal for root classes only.
  2319. return (!(cls->data()->flags & RO_ROOT));
  2320. } else {
  2321. // superclass not nil. Check if a higher superclass is missing.
  2322. Class supercls = remapClass(cls->superclass);
  2323. ASSERT(cls != cls->superclass);
  2324. ASSERT(cls != supercls);
  2325. if (!supercls) return YES;
  2326. if (supercls->isRealized()) return NO;
  2327. return missingWeakSuperclass(supercls);
  2328. }
  2329. }
  2330. /***********************************************************************
  2331. * realizeAllClassesInImage
  2332. * Non-lazily realizes all unrealized classes in the given image.
  2333. * Locking: runtimeLock must be held by the caller.
  2334. * Locking: this function may drop and re-acquire the lock.
  2335. **********************************************************************/
  2336. static void realizeAllClassesInImage(header_info *hi)
  2337. {
  2338. runtimeLock.assertLocked();
  2339. size_t count, i;
  2340. classref_t const *classlist;
  2341. if (hi->areAllClassesRealized()) return;
  2342. classlist = _getObjc2ClassList(hi, &count);
  2343. for (i = 0; i < count; i++) {
  2344. Class cls = remapClass(classlist[i]);
  2345. if (cls) {
  2346. realizeClassMaybeSwiftAndLeaveLocked(cls, runtimeLock);
  2347. }
  2348. }
  2349. hi->setAllClassesRealized(YES);
  2350. }
  2351. /***********************************************************************
  2352. * realizeAllClasses
  2353. * Non-lazily realizes all unrealized classes in all known images.
  2354. * Locking: runtimeLock must be held by the caller.
  2355. * Locking: this function may drop and re-acquire the lock.
  2356. * Dropping the lock makes this function thread-unsafe with respect
  2357. * to concurrent image unload, but the callers of this function
  2358. * already ultimately do something that is also thread-unsafe with
  2359. * respect to image unload (such as using the list of all classes).
  2360. **********************************************************************/
  2361. static void realizeAllClasses(void)
  2362. {
  2363. runtimeLock.assertLocked();
  2364. header_info *hi;
  2365. for (hi = FirstHeader; hi; hi = hi->getNext()) {
  2366. realizeAllClassesInImage(hi); // may drop and re-acquire runtimeLock
  2367. }
  2368. }
  2369. /***********************************************************************
  2370. * _objc_allocateFutureClass
  2371. * Allocate an unresolved future class for the given class name.
  2372. * Returns any existing allocation if one was already made.
  2373. * Assumes the named class doesn't exist yet.
  2374. * Locking: acquires runtimeLock
  2375. **********************************************************************/
  2376. Class _objc_allocateFutureClass(const char *name)
  2377. {
  2378. mutex_locker_t lock(runtimeLock);
  2379. Class cls;
  2380. NXMapTable *map = futureNamedClasses();
  2381. if ((cls = (Class)NXMapGet(map, name))) {
  2382. // Already have a future class for this name.
  2383. return cls;
  2384. }
  2385. cls = _calloc_class(sizeof(objc_class));
  2386. addFutureNamedClass(name, cls);
  2387. return cls;
  2388. }
  2389. /***********************************************************************
  2390. * objc_getFutureClass. Return the id of the named class.
  2391. * If the class does not exist, return an uninitialized class
  2392. * structure that will be used for the class when and if it
  2393. * does get loaded.
  2394. * Not thread safe.
  2395. **********************************************************************/
  2396. Class objc_getFutureClass(const char *name)
  2397. {
  2398. Class cls;
  2399. // YES unconnected, NO class handler
  2400. // (unconnected is OK because it will someday be the real class)
  2401. cls = look_up_class(name, YES, NO);
  2402. if (cls) {
  2403. if (PrintFuture) {
  2404. _objc_inform("FUTURE: found %p already in use for %s",
  2405. (void*)cls, name);
  2406. }
  2407. return cls;
  2408. }
  2409. // No class or future class with that name yet. Make one.
  2410. // fixme not thread-safe with respect to
  2411. // simultaneous library load or getFutureClass.
  2412. return _objc_allocateFutureClass(name);
  2413. }
  2414. BOOL _class_isFutureClass(Class cls)
  2415. {
  2416. return cls && cls->isFuture();
  2417. }
  2418. /***********************************************************************
  2419. * _objc_flush_caches
  2420. * Flushes all caches.
  2421. * (Historical behavior: flush caches for cls, its metaclass,
  2422. * and subclasses thereof. Nil flushes all classes.)
  2423. * Locking: acquires runtimeLock
  2424. **********************************************************************/
  2425. static void flushCaches(Class cls)
  2426. {
  2427. runtimeLock.assertLocked();
  2428. #if CONFIG_USE_CACHE_LOCK
  2429. mutex_locker_t lock(cacheUpdateLock);
  2430. #endif
  2431. if (cls) {
  2432. foreach_realized_class_and_subclass(cls, [](Class c){
  2433. cache_erase_nolock(c);
  2434. return true;
  2435. });
  2436. }
  2437. else {
  2438. foreach_realized_class_and_metaclass([](Class c){
  2439. cache_erase_nolock(c);
  2440. return true;
  2441. });
  2442. }
  2443. }
  2444. void _objc_flush_caches(Class cls)
  2445. {
  2446. {
  2447. mutex_locker_t lock(runtimeLock);
  2448. flushCaches(cls);
  2449. if (cls && cls->superclass && cls != cls->getIsa()) {
  2450. flushCaches(cls->getIsa());
  2451. } else {
  2452. // cls is a root class or root metaclass. Its metaclass is itself
  2453. // or a subclass so the metaclass caches were already flushed.
  2454. }
  2455. }
  2456. if (!cls) {
  2457. // collectALot if cls==nil
  2458. #if CONFIG_USE_CACHE_LOCK
  2459. mutex_locker_t lock(cacheUpdateLock);
  2460. #else
  2461. mutex_locker_t lock(runtimeLock);
  2462. #endif
  2463. cache_collect(true);
  2464. }
  2465. }
  2466. /***********************************************************************
  2467. * map_images
  2468. * Process the given images which are being mapped in by dyld.
  2469. * Calls ABI-agnostic code after taking ABI-specific locks.
  2470. *
  2471. * Locking: write-locks runtimeLock
  2472. **********************************************************************/
  2473. void
  2474. map_images(unsigned count, const char * const paths[],
  2475. const struct mach_header * const mhdrs[])
  2476. {
  2477. mutex_locker_t lock(runtimeLock);
  2478. return map_images_nolock(count, paths, mhdrs);
  2479. }
  2480. /***********************************************************************
  2481. * load_images
  2482. * Process +load in the given images which are being mapped in by dyld.
  2483. *
  2484. * Locking: write-locks runtimeLock and loadMethodLock
  2485. **********************************************************************/
  2486. extern bool hasLoadMethods(const headerType *mhdr);
  2487. extern void prepare_load_methods(const headerType *mhdr);
  2488. void
  2489. load_images(const char *path __unused, const struct mach_header *mh)
  2490. {
  2491. // Return without taking locks if there are no +load methods here.
  2492. if (!hasLoadMethods((const headerType *)mh)) return;
  2493. recursive_mutex_locker_t lock(loadMethodLock);
  2494. // Discover load methods
  2495. {
  2496. mutex_locker_t lock2(runtimeLock);
  2497. prepare_load_methods((const headerType *)mh);
  2498. }
  2499. // Call +load methods (without runtimeLock - re-entrant)
  2500. call_load_methods();
  2501. }
  2502. /***********************************************************************
  2503. * unmap_image
  2504. * Process the given image which is about to be unmapped by dyld.
  2505. *
  2506. * Locking: write-locks runtimeLock and loadMethodLock
  2507. **********************************************************************/
  2508. void
  2509. unmap_image(const char *path __unused, const struct mach_header *mh)
  2510. {
  2511. recursive_mutex_locker_t lock(loadMethodLock);
  2512. mutex_locker_t lock2(runtimeLock);
  2513. unmap_image_nolock(mh);
  2514. }
  2515. /***********************************************************************
  2516. * mustReadClasses
  2517. * Preflight check in advance of readClass() from an image.
  2518. **********************************************************************/
  2519. bool mustReadClasses(header_info *hi, bool hasDyldRoots)
  2520. {
  2521. const char *reason;
  2522. // If the image is not preoptimized then we must read classes.
  2523. if (!hi->hasPreoptimizedClasses()) {
  2524. reason = nil; // Don't log this one because it is noisy.
  2525. goto readthem;
  2526. }
  2527. // If iOS simulator then we must read classes.
  2528. #if TARGET_OS_SIMULATOR
  2529. reason = "the image is for iOS simulator";
  2530. goto readthem;
  2531. #endif
  2532. ASSERT(!hi->isBundle()); // no MH_BUNDLE in shared cache
  2533. // If the image may have missing weak superclasses then we must read classes
  2534. if (!noMissingWeakSuperclasses() || hasDyldRoots) {
  2535. reason = "the image may contain classes with missing weak superclasses";
  2536. goto readthem;
  2537. }
  2538. // If there are unresolved future classes then we must read classes.
  2539. if (haveFutureNamedClasses()) {
  2540. reason = "there are unresolved future classes pending";
  2541. goto readthem;
  2542. }
  2543. // readClass() rewrites bits in backward-deploying Swift stable ABI code.
  2544. // The assumption here is there there are no such classes
  2545. // in the dyld shared cache.
  2546. #if DEBUG
  2547. {
  2548. size_t count;
  2549. classref_t const *classlist = _getObjc2ClassList(hi, &count);
  2550. for (size_t i = 0; i < count; i++) {
  2551. Class cls = remapClass(classlist[i]);
  2552. ASSERT(!cls->isUnfixedBackwardDeployingStableSwift());
  2553. }
  2554. }
  2555. #endif
  2556. // readClass() does not need to do anything.
  2557. return NO;
  2558. readthem:
  2559. if (PrintPreopt && reason) {
  2560. _objc_inform("PREOPTIMIZATION: reading classes manually from %s "
  2561. "because %s", hi->fname(), reason);
  2562. }
  2563. return YES;
  2564. }
  2565. /***********************************************************************
  2566. * readClass
  2567. * Read a class and metaclass as written by a compiler.
  2568. * Returns the new class pointer. This could be:
  2569. * - cls
  2570. * - nil (cls has a missing weak-linked superclass)
  2571. * - something else (space for this class was reserved by a future class)
  2572. *
  2573. * Note that all work performed by this function is preflighted by
  2574. * mustReadClasses(). Do not change this function without updating that one.
  2575. *
  2576. * Locking: runtimeLock acquired by map_images or objc_readClassPair
  2577. **********************************************************************/
  2578. Class readClass(Class cls, bool headerIsBundle, bool headerIsPreoptimized)
  2579. {
  2580. const char *mangledName = cls->mangledName();
  2581. if (missingWeakSuperclass(cls)) {
  2582. // No superclass (probably weak-linked).
  2583. // Disavow any knowledge of this subclass.
  2584. if (PrintConnecting) {
  2585. _objc_inform("CLASS: IGNORING class '%s' with "
  2586. "missing weak-linked superclass",
  2587. cls->nameForLogging());
  2588. }
  2589. addRemappedClass(cls, nil);
  2590. cls->superclass = nil;
  2591. return nil;
  2592. }
  2593. cls->fixupBackwardDeployingStableSwift();
  2594. Class replacing = nil;
  2595. if (Class newCls = popFutureNamedClass(mangledName)) {
  2596. // This name was previously allocated as a future class.
  2597. // Copy objc_class to future class's struct.
  2598. // Preserve future's rw data block.
  2599. if (newCls->isAnySwift()) {
  2600. _objc_fatal("Can't complete future class request for '%s' "
  2601. "because the real class is too big.",
  2602. cls->nameForLogging());
  2603. }
  2604. class_rw_t *rw = newCls->data();
  2605. const class_ro_t *old_ro = rw->ro;
  2606. memcpy(newCls, cls, sizeof(objc_class));
  2607. rw->ro = (class_ro_t *)newCls->data();
  2608. newCls->setData(rw);
  2609. freeIfMutable((char *)old_ro->name);
  2610. free((void *)old_ro);
  2611. addRemappedClass(cls, newCls);
  2612. replacing = cls;
  2613. cls = newCls;
  2614. }
  2615. if (headerIsPreoptimized && !replacing) {
  2616. // class list built in shared cache
  2617. // fixme strict assert doesn't work because of duplicates
  2618. // ASSERT(cls == getClass(name));
  2619. ASSERT(getClassExceptSomeSwift(mangledName));
  2620. } else {
  2621. addNamedClass(cls, mangledName, replacing);
  2622. addClassTableEntry(cls);
  2623. }
  2624. // for future reference: shared cache never contains MH_BUNDLEs
  2625. if (headerIsBundle) {
  2626. cls->data()->flags |= RO_FROM_BUNDLE;
  2627. cls->ISA()->data()->flags |= RO_FROM_BUNDLE;
  2628. }
  2629. return cls;
  2630. }
  2631. /***********************************************************************
  2632. * readProtocol
  2633. * Read a protocol as written by a compiler.
  2634. **********************************************************************/
  2635. static void
  2636. readProtocol(protocol_t *newproto, Class protocol_class,
  2637. NXMapTable *protocol_map,
  2638. bool headerIsPreoptimized, bool headerIsBundle)
  2639. {
  2640. // This is not enough to make protocols in unloaded bundles safe,
  2641. // but it does prevent crashes when looking up unrelated protocols.
  2642. auto insertFn = headerIsBundle ? NXMapKeyCopyingInsert : NXMapInsert;
  2643. protocol_t *oldproto = (protocol_t *)getProtocol(newproto->mangledName);
  2644. if (oldproto) {
  2645. if (oldproto != newproto) {
  2646. // Some other definition already won.
  2647. if (PrintProtocols) {
  2648. _objc_inform("PROTOCOLS: protocol at %p is %s "
  2649. "(duplicate of %p)",
  2650. newproto, oldproto->nameForLogging(), oldproto);
  2651. }
  2652. // If we are a shared cache binary then we have a definition of this
  2653. // protocol, but if another one was chosen then we need to clear our
  2654. // isCanonical bit so that no-one trusts it.
  2655. // Note, if getProtocol returned a shared cache protocol then the
  2656. // canonical definition is already in the shared cache and we don't
  2657. // need to do anything.
  2658. if (headerIsPreoptimized && !oldproto->isCanonical()) {
  2659. // Note newproto is an entry in our __objc_protolist section which
  2660. // for shared cache binaries points to the original protocol in
  2661. // that binary, not the shared cache uniqued one.
  2662. auto cacheproto = (protocol_t *)
  2663. getSharedCachePreoptimizedProtocol(newproto->mangledName);
  2664. if (cacheproto && cacheproto->isCanonical())
  2665. cacheproto->clearIsCanonical();
  2666. }
  2667. }
  2668. }
  2669. else if (headerIsPreoptimized) {
  2670. // Shared cache initialized the protocol object itself,
  2671. // but in order to allow out-of-cache replacement we need
  2672. // to add it to the protocol table now.
  2673. protocol_t *cacheproto = (protocol_t *)
  2674. getPreoptimizedProtocol(newproto->mangledName);
  2675. protocol_t *installedproto;
  2676. if (cacheproto && cacheproto != newproto) {
  2677. // Another definition in the shared cache wins (because
  2678. // everything in the cache was fixed up to point to it).
  2679. installedproto = cacheproto;
  2680. }
  2681. else {
  2682. // This definition wins.
  2683. installedproto = newproto;
  2684. }
  2685. ASSERT(installedproto->getIsa() == protocol_class);
  2686. ASSERT(installedproto->size >= sizeof(protocol_t));
  2687. insertFn(protocol_map, installedproto->mangledName,
  2688. installedproto);
  2689. if (PrintProtocols) {
  2690. _objc_inform("PROTOCOLS: protocol at %p is %s",
  2691. installedproto, installedproto->nameForLogging());
  2692. if (newproto != installedproto) {
  2693. _objc_inform("PROTOCOLS: protocol at %p is %s "
  2694. "(duplicate of %p)",
  2695. newproto, installedproto->nameForLogging(),
  2696. installedproto);
  2697. }
  2698. }
  2699. }
  2700. else if (newproto->size >= sizeof(protocol_t)) {
  2701. // New protocol from an un-preoptimized image
  2702. // with sufficient storage. Fix it up in place.
  2703. // fixme duplicate protocols from unloadable bundle
  2704. newproto->initIsa(protocol_class); // fixme pinned
  2705. insertFn(protocol_map, newproto->mangledName, newproto);
  2706. if (PrintProtocols) {
  2707. _objc_inform("PROTOCOLS: protocol at %p is %s",
  2708. newproto, newproto->nameForLogging());
  2709. }
  2710. }
  2711. else {
  2712. // New protocol from an un-preoptimized image
  2713. // with insufficient storage. Reallocate it.
  2714. // fixme duplicate protocols from unloadable bundle
  2715. size_t size = max(sizeof(protocol_t), (size_t)newproto->size);
  2716. protocol_t *installedproto = (protocol_t *)calloc(size, 1);
  2717. memcpy(installedproto, newproto, newproto->size);
  2718. installedproto->size = (typeof(installedproto->size))size;
  2719. installedproto->initIsa(protocol_class); // fixme pinned
  2720. insertFn(protocol_map, installedproto->mangledName, installedproto);
  2721. if (PrintProtocols) {
  2722. _objc_inform("PROTOCOLS: protocol at %p is %s ",
  2723. installedproto, installedproto->nameForLogging());
  2724. _objc_inform("PROTOCOLS: protocol at %p is %s "
  2725. "(reallocated to %p)",
  2726. newproto, installedproto->nameForLogging(),
  2727. installedproto);
  2728. }
  2729. }
  2730. }
  2731. /***********************************************************************
  2732. * _read_images
  2733. * Perform initial processing of the headers in the linked
  2734. * list beginning with headerList.
  2735. *
  2736. * Called by: map_images_nolock
  2737. *
  2738. * Locking: runtimeLock acquired by map_images
  2739. **********************************************************************/
  2740. void _read_images(header_info **hList, uint32_t hCount, int totalClasses, int unoptimizedTotalClasses)
  2741. {
  2742. header_info *hi;
  2743. uint32_t hIndex;
  2744. size_t count;
  2745. size_t i;
  2746. Class *resolvedFutureClasses = nil;
  2747. size_t resolvedFutureClassCount = 0;
  2748. static bool doneOnce;
  2749. bool launchTime = NO;
  2750. TimeLogger ts(PrintImageTimes);
  2751. runtimeLock.assertLocked();
  2752. #define EACH_HEADER \
  2753. hIndex = 0; \
  2754. hIndex < hCount && (hi = hList[hIndex]); \
  2755. hIndex++
  2756. if (!doneOnce) {
  2757. doneOnce = YES;
  2758. launchTime = YES;
  2759. #if SUPPORT_NONPOINTER_ISA
  2760. // Disable non-pointer isa under some conditions.
  2761. # if SUPPORT_INDEXED_ISA
  2762. // Disable nonpointer isa if any image contains old Swift code
  2763. for (EACH_HEADER) {
  2764. if (hi->info()->containsSwift() &&
  2765. hi->info()->swiftUnstableVersion() < objc_image_info::SwiftVersion3)
  2766. {
  2767. DisableNonpointerIsa = true;
  2768. if (PrintRawIsa) {
  2769. _objc_inform("RAW ISA: disabling non-pointer isa because "
  2770. "the app or a framework contains Swift code "
  2771. "older than Swift 3.0");
  2772. }
  2773. break;
  2774. }
  2775. }
  2776. # endif
  2777. # if TARGET_OS_OSX
  2778. // Disable non-pointer isa if the app is too old
  2779. // (linked before OS X 10.11)
  2780. if (dyld_get_program_sdk_version() < DYLD_MACOSX_VERSION_10_11) {
  2781. DisableNonpointerIsa = true;
  2782. if (PrintRawIsa) {
  2783. _objc_inform("RAW ISA: disabling non-pointer isa because "
  2784. "the app is too old (SDK version " SDK_FORMAT ")",
  2785. FORMAT_SDK(dyld_get_program_sdk_version()));
  2786. }
  2787. }
  2788. // Disable non-pointer isa if the app has a __DATA,__objc_rawisa section
  2789. // New apps that load old extensions may need this.
  2790. for (EACH_HEADER) {
  2791. if (hi->mhdr()->filetype != MH_EXECUTE) continue;
  2792. unsigned long size;
  2793. if (getsectiondata(hi->mhdr(), "__DATA", "__objc_rawisa", &size)) {
  2794. DisableNonpointerIsa = true;
  2795. if (PrintRawIsa) {
  2796. _objc_inform("RAW ISA: disabling non-pointer isa because "
  2797. "the app has a __DATA,__objc_rawisa section");
  2798. }
  2799. }
  2800. break; // assume only one MH_EXECUTE image
  2801. }
  2802. # endif
  2803. #endif
  2804. if (DisableTaggedPointers) {
  2805. disableTaggedPointers();
  2806. }
  2807. initializeTaggedPointerObfuscator();
  2808. if (PrintConnecting) {
  2809. _objc_inform("CLASS: found %d classes during launch", totalClasses);
  2810. }
  2811. // namedClasses
  2812. // Preoptimized classes don't go in this table.
  2813. // 4/3 is NXMapTable's load factor
  2814. int namedClassesSize =
  2815. (isPreoptimized() ? unoptimizedTotalClasses : totalClasses) * 4 / 3;
  2816. gdb_objc_realized_classes =
  2817. NXCreateMapTable(NXStrValueMapPrototype, namedClassesSize);
  2818. ts.log("IMAGE TIMES: first time tasks");
  2819. }
  2820. // Fix up @selector references
  2821. static size_t UnfixedSelectors;
  2822. {
  2823. mutex_locker_t lock(selLock);
  2824. for (EACH_HEADER) {
  2825. if (hi->hasPreoptimizedSelectors()) continue;
  2826. bool isBundle = hi->isBundle();
  2827. SEL *sels = _getObjc2SelectorRefs(hi, &count);
  2828. UnfixedSelectors += count;
  2829. for (i = 0; i < count; i++) {
  2830. const char *name = sel_cname(sels[i]);
  2831. SEL sel = sel_registerNameNoLock(name, isBundle);
  2832. if (sels[i] != sel) {
  2833. sels[i] = sel;
  2834. }
  2835. }
  2836. }
  2837. }
  2838. ts.log("IMAGE TIMES: fix up selector references");
  2839. // Discover classes. Fix up unresolved future classes. Mark bundle classes.
  2840. bool hasDyldRoots = dyld_shared_cache_some_image_overridden();
  2841. for (EACH_HEADER) {
  2842. if (! mustReadClasses(hi, hasDyldRoots)) {
  2843. // Image is sufficiently optimized that we need not call readClass()
  2844. continue;
  2845. }
  2846. classref_t const *classlist = _getObjc2ClassList(hi, &count);
  2847. bool headerIsBundle = hi->isBundle();
  2848. bool headerIsPreoptimized = hi->hasPreoptimizedClasses();
  2849. for (i = 0; i < count; i++) {
  2850. Class cls = (Class)classlist[i];
  2851. Class newCls = readClass(cls, headerIsBundle, headerIsPreoptimized);
  2852. if (newCls != cls && newCls) {
  2853. // Class was moved but not deleted. Currently this occurs
  2854. // only when the new class resolved a future class.
  2855. // Non-lazily realize the class below.
  2856. resolvedFutureClasses = (Class *)
  2857. realloc(resolvedFutureClasses,
  2858. (resolvedFutureClassCount+1) * sizeof(Class));
  2859. resolvedFutureClasses[resolvedFutureClassCount++] = newCls;
  2860. }
  2861. }
  2862. }
  2863. ts.log("IMAGE TIMES: discover classes");
  2864. // Fix up remapped classes
  2865. // Class list and nonlazy class list remain unremapped.
  2866. // Class refs and super refs are remapped for message dispatching.
  2867. if (!noClassesRemapped()) {
  2868. for (EACH_HEADER) {
  2869. Class *classrefs = _getObjc2ClassRefs(hi, &count);
  2870. for (i = 0; i < count; i++) {
  2871. remapClassRef(&classrefs[i]);
  2872. }
  2873. // fixme why doesn't test future1 catch the absence of this?
  2874. classrefs = _getObjc2SuperRefs(hi, &count);
  2875. for (i = 0; i < count; i++) {
  2876. remapClassRef(&classrefs[i]);
  2877. }
  2878. }
  2879. }
  2880. ts.log("IMAGE TIMES: remap classes");
  2881. #if SUPPORT_FIXUP
  2882. // Fix up old objc_msgSend_fixup call sites
  2883. for (EACH_HEADER) {
  2884. message_ref_t *refs = _getObjc2MessageRefs(hi, &count);
  2885. if (count == 0) continue;
  2886. if (PrintVtables) {
  2887. _objc_inform("VTABLES: repairing %zu unsupported vtable dispatch "
  2888. "call sites in %s", count, hi->fname());
  2889. }
  2890. for (i = 0; i < count; i++) {
  2891. fixupMessageRef(refs+i);
  2892. }
  2893. }
  2894. ts.log("IMAGE TIMES: fix up objc_msgSend_fixup");
  2895. #endif
  2896. bool cacheSupportsProtocolRoots = sharedCacheSupportsProtocolRoots();
  2897. // Discover protocols. Fix up protocol refs.
  2898. for (EACH_HEADER) {
  2899. extern objc_class OBJC_CLASS_$_Protocol;
  2900. Class cls = (Class)&OBJC_CLASS_$_Protocol;
  2901. ASSERT(cls);
  2902. NXMapTable *protocol_map = protocols();
  2903. bool isPreoptimized = hi->hasPreoptimizedProtocols();
  2904. // Skip reading protocols if this is an image from the shared cache
  2905. // and we support roots
  2906. // Note, after launch we do need to walk the protocol as the protocol
  2907. // in the shared cache is marked with isCanonical() and that may not
  2908. // be true if some non-shared cache binary was chosen as the canonical
  2909. // definition
  2910. if (launchTime && isPreoptimized && cacheSupportsProtocolRoots) {
  2911. if (PrintProtocols) {
  2912. _objc_inform("PROTOCOLS: Skipping reading protocols in image: %s",
  2913. hi->fname());
  2914. }
  2915. continue;
  2916. }
  2917. bool isBundle = hi->isBundle();
  2918. protocol_t * const *protolist = _getObjc2ProtocolList(hi, &count);
  2919. for (i = 0; i < count; i++) {
  2920. readProtocol(protolist[i], cls, protocol_map,
  2921. isPreoptimized, isBundle);
  2922. }
  2923. }
  2924. ts.log("IMAGE TIMES: discover protocols");
  2925. // Fix up @protocol references
  2926. // Preoptimized images may have the right
  2927. // answer already but we don't know for sure.
  2928. for (EACH_HEADER) {
  2929. // At launch time, we know preoptimized image refs are pointing at the
  2930. // shared cache definition of a protocol. We can skip the check on
  2931. // launch, but have to visit @protocol refs for shared cache images
  2932. // loaded later.
  2933. if (launchTime && cacheSupportsProtocolRoots && hi->isPreoptimized())
  2934. continue;
  2935. protocol_t **protolist = _getObjc2ProtocolRefs(hi, &count);
  2936. for (i = 0; i < count; i++) {
  2937. remapProtocolRef(&protolist[i]);
  2938. }
  2939. }
  2940. ts.log("IMAGE TIMES: fix up @protocol references");
  2941. // Discover categories.
  2942. for (EACH_HEADER) {
  2943. bool hasClassProperties = hi->info()->hasCategoryClassProperties();
  2944. auto processCatlist = [&](category_t * const *catlist) {
  2945. for (i = 0; i < count; i++) {
  2946. category_t *cat = catlist[i];
  2947. Class cls = remapClass(cat->cls);
  2948. locstamped_category_t lc{cat, hi};
  2949. if (!cls) {
  2950. // Category's target class is missing (probably weak-linked).
  2951. // Ignore the category.
  2952. if (PrintConnecting) {
  2953. _objc_inform("CLASS: IGNORING category \?\?\?(%s) %p with "
  2954. "missing weak-linked target class",
  2955. cat->name, cat);
  2956. }
  2957. continue;
  2958. }
  2959. // Process this category.
  2960. if (cls->isStubClass()) {
  2961. // Stub classes are never realized. Stub classes
  2962. // don't know their metaclass until they're
  2963. // initialized, so we have to add categories with
  2964. // class methods or properties to the stub itself.
  2965. // methodizeClass() will find them and add them to
  2966. // the metaclass as appropriate.
  2967. if (cat->instanceMethods ||
  2968. cat->protocols ||
  2969. cat->instanceProperties ||
  2970. cat->classMethods ||
  2971. cat->protocols ||
  2972. (hasClassProperties && cat->_classProperties))
  2973. {
  2974. objc::unattachedCategories.addForClass(lc, cls);
  2975. }
  2976. } else {
  2977. // First, register the category with its target class.
  2978. // Then, rebuild the class's method lists (etc) if
  2979. // the class is realized.
  2980. if (cat->instanceMethods || cat->protocols
  2981. || cat->instanceProperties)
  2982. {
  2983. if (cls->isRealized()) {
  2984. attachCategories(cls, &lc, 1, ATTACH_EXISTING);
  2985. } else {
  2986. objc::unattachedCategories.addForClass(lc, cls);
  2987. }
  2988. }
  2989. if (cat->classMethods || cat->protocols
  2990. || (hasClassProperties && cat->_classProperties))
  2991. {
  2992. if (cls->ISA()->isRealized()) {
  2993. attachCategories(cls->ISA(), &lc, 1, ATTACH_EXISTING | ATTACH_METACLASS);
  2994. } else {
  2995. objc::unattachedCategories.addForClass(lc, cls->ISA());
  2996. }
  2997. }
  2998. }
  2999. }
  3000. };
  3001. processCatlist(_getObjc2CategoryList(hi, &count));
  3002. processCatlist(_getObjc2CategoryList2(hi, &count));
  3003. }
  3004. ts.log("IMAGE TIMES: discover categories");
  3005. // Category discovery MUST BE Late to avoid potential races
  3006. // when other threads call the new category code before
  3007. // this thread finishes its fixups.
  3008. // +load handled by prepare_load_methods()
  3009. // Realize non-lazy classes (for +load methods and static instances)
  3010. for (EACH_HEADER) {
  3011. classref_t const *classlist =
  3012. _getObjc2NonlazyClassList(hi, &count);
  3013. for (i = 0; i < count; i++) {
  3014. Class cls = remapClass(classlist[i]);
  3015. if (!cls) continue;
  3016. addClassTableEntry(cls);
  3017. if (cls->isSwiftStable()) {
  3018. if (cls->swiftMetadataInitializer()) {
  3019. _objc_fatal("Swift class %s with a metadata initializer "
  3020. "is not allowed to be non-lazy",
  3021. cls->nameForLogging());
  3022. }
  3023. // fixme also disallow relocatable classes
  3024. // We can't disallow all Swift classes because of
  3025. // classes like Swift.__EmptyArrayStorage
  3026. }
  3027. realizeClassWithoutSwift(cls, nil);
  3028. }
  3029. }
  3030. ts.log("IMAGE TIMES: realize non-lazy classes");
  3031. // Realize newly-resolved future classes, in case CF manipulates them
  3032. if (resolvedFutureClasses) {
  3033. for (i = 0; i < resolvedFutureClassCount; i++) {
  3034. Class cls = resolvedFutureClasses[i];
  3035. if (cls->isSwiftStable()) {
  3036. _objc_fatal("Swift class is not allowed to be future");
  3037. }
  3038. realizeClassWithoutSwift(cls, nil);
  3039. cls->setInstancesRequireRawIsaRecursively(false/*inherited*/);
  3040. }
  3041. free(resolvedFutureClasses);
  3042. }
  3043. ts.log("IMAGE TIMES: realize future classes");
  3044. if (DebugNonFragileIvars) {
  3045. realizeAllClasses();
  3046. }
  3047. // Print preoptimization statistics
  3048. if (PrintPreopt) {
  3049. static unsigned int PreoptTotalMethodLists;
  3050. static unsigned int PreoptOptimizedMethodLists;
  3051. static unsigned int PreoptTotalClasses;
  3052. static unsigned int PreoptOptimizedClasses;
  3053. for (EACH_HEADER) {
  3054. if (hi->hasPreoptimizedSelectors()) {
  3055. _objc_inform("PREOPTIMIZATION: honoring preoptimized selectors "
  3056. "in %s", hi->fname());
  3057. }
  3058. else if (hi->info()->optimizedByDyld()) {
  3059. _objc_inform("PREOPTIMIZATION: IGNORING preoptimized selectors "
  3060. "in %s", hi->fname());
  3061. }
  3062. classref_t const *classlist = _getObjc2ClassList(hi, &count);
  3063. for (i = 0; i < count; i++) {
  3064. Class cls = remapClass(classlist[i]);
  3065. if (!cls) continue;
  3066. PreoptTotalClasses++;
  3067. if (hi->hasPreoptimizedClasses()) {
  3068. PreoptOptimizedClasses++;
  3069. }
  3070. const method_list_t *mlist;
  3071. if ((mlist = ((class_ro_t *)cls->data())->baseMethods())) {
  3072. PreoptTotalMethodLists++;
  3073. if (mlist->isFixedUp()) {
  3074. PreoptOptimizedMethodLists++;
  3075. }
  3076. }
  3077. if ((mlist=((class_ro_t *)cls->ISA()->data())->baseMethods())) {
  3078. PreoptTotalMethodLists++;
  3079. if (mlist->isFixedUp()) {
  3080. PreoptOptimizedMethodLists++;
  3081. }
  3082. }
  3083. }
  3084. }
  3085. _objc_inform("PREOPTIMIZATION: %zu selector references not "
  3086. "pre-optimized", UnfixedSelectors);
  3087. _objc_inform("PREOPTIMIZATION: %u/%u (%.3g%%) method lists pre-sorted",
  3088. PreoptOptimizedMethodLists, PreoptTotalMethodLists,
  3089. PreoptTotalMethodLists
  3090. ? 100.0*PreoptOptimizedMethodLists/PreoptTotalMethodLists
  3091. : 0.0);
  3092. _objc_inform("PREOPTIMIZATION: %u/%u (%.3g%%) classes pre-registered",
  3093. PreoptOptimizedClasses, PreoptTotalClasses,
  3094. PreoptTotalClasses
  3095. ? 100.0*PreoptOptimizedClasses/PreoptTotalClasses
  3096. : 0.0);
  3097. _objc_inform("PREOPTIMIZATION: %zu protocol references not "
  3098. "pre-optimized", UnfixedProtocolReferences);
  3099. }
  3100. #undef EACH_HEADER
  3101. }
  3102. /***********************************************************************
  3103. * prepare_load_methods
  3104. * Schedule +load for classes in this image, any un-+load-ed
  3105. * superclasses in other images, and any categories in this image.
  3106. **********************************************************************/
  3107. // Recursively schedule +load for cls and any un-+load-ed superclasses.
  3108. // cls must already be connected.
  3109. static void schedule_class_load(Class cls)
  3110. {
  3111. if (!cls) return;
  3112. ASSERT(cls->isRealized()); // _read_images should realize
  3113. if (cls->data()->flags & RW_LOADED) return;
  3114. // Ensure superclass-first ordering
  3115. schedule_class_load(cls->superclass);
  3116. add_class_to_loadable_list(cls);
  3117. cls->setInfo(RW_LOADED);
  3118. }
  3119. // Quick scan for +load methods that doesn't take a lock.
  3120. bool hasLoadMethods(const headerType *mhdr)
  3121. {
  3122. size_t count;
  3123. if (_getObjc2NonlazyClassList(mhdr, &count) && count > 0) return true;
  3124. if (_getObjc2NonlazyCategoryList(mhdr, &count) && count > 0) return true;
  3125. return false;
  3126. }
  3127. void prepare_load_methods(const headerType *mhdr)
  3128. {
  3129. size_t count, i;
  3130. runtimeLock.assertLocked();
  3131. classref_t const *classlist =
  3132. _getObjc2NonlazyClassList(mhdr, &count);
  3133. for (i = 0; i < count; i++) {
  3134. schedule_class_load(remapClass(classlist[i]));
  3135. }
  3136. category_t * const *categorylist = _getObjc2NonlazyCategoryList(mhdr, &count);
  3137. for (i = 0; i < count; i++) {
  3138. category_t *cat = categorylist[i];
  3139. Class cls = remapClass(cat->cls);
  3140. if (!cls) continue; // category for ignored weak-linked class
  3141. if (cls->isSwiftStable()) {
  3142. _objc_fatal("Swift class extensions and categories on Swift "
  3143. "classes are not allowed to have +load methods");
  3144. }
  3145. realizeClassWithoutSwift(cls, nil);
  3146. ASSERT(cls->ISA()->isRealized());
  3147. add_category_to_loadable_list(cat);
  3148. }
  3149. }
  3150. /***********************************************************************
  3151. * _unload_image
  3152. * Only handles MH_BUNDLE for now.
  3153. * Locking: write-lock and loadMethodLock acquired by unmap_image
  3154. **********************************************************************/
  3155. void _unload_image(header_info *hi)
  3156. {
  3157. size_t count, i;
  3158. loadMethodLock.assertLocked();
  3159. runtimeLock.assertLocked();
  3160. // Unload unattached categories and categories waiting for +load.
  3161. // Ignore __objc_catlist2. We don't support unloading Swift
  3162. // and we never will.
  3163. category_t * const *catlist = _getObjc2CategoryList(hi, &count);
  3164. for (i = 0; i < count; i++) {
  3165. category_t *cat = catlist[i];
  3166. Class cls = remapClass(cat->cls);
  3167. if (!cls) continue; // category for ignored weak-linked class
  3168. // fixme for MH_DYLIB cat's class may have been unloaded already
  3169. // unattached list
  3170. objc::unattachedCategories.eraseCategoryForClass(cat, cls);
  3171. // +load queue
  3172. remove_category_from_loadable_list(cat);
  3173. }
  3174. // Unload classes.
  3175. // Gather classes from both __DATA,__objc_clslist
  3176. // and __DATA,__objc_nlclslist. arclite's hack puts a class in the latter
  3177. // only, and we need to unload that class if we unload an arclite image.
  3178. objc::DenseSet<Class> classes{};
  3179. classref_t const *classlist;
  3180. classlist = _getObjc2ClassList(hi, &count);
  3181. for (i = 0; i < count; i++) {
  3182. Class cls = remapClass(classlist[i]);
  3183. if (cls) classes.insert(cls);
  3184. }
  3185. classlist = _getObjc2NonlazyClassList(hi, &count);
  3186. for (i = 0; i < count; i++) {
  3187. Class cls = remapClass(classlist[i]);
  3188. if (cls) classes.insert(cls);
  3189. }
  3190. // First detach classes from each other. Then free each class.
  3191. // This avoid bugs where this loop unloads a subclass before its superclass
  3192. for (Class cls: classes) {
  3193. remove_class_from_loadable_list(cls);
  3194. detach_class(cls->ISA(), YES);
  3195. detach_class(cls, NO);
  3196. }
  3197. for (Class cls: classes) {
  3198. free_class(cls->ISA());
  3199. free_class(cls);
  3200. }
  3201. // XXX FIXME -- Clean up protocols:
  3202. // <rdar://problem/9033191> Support unloading protocols at dylib/image unload time
  3203. // fixme DebugUnload
  3204. }
  3205. /***********************************************************************
  3206. * method_getDescription
  3207. * Returns a pointer to this method's objc_method_description.
  3208. * Locking: none
  3209. **********************************************************************/
  3210. struct objc_method_description *
  3211. method_getDescription(Method m)
  3212. {
  3213. if (!m) return nil;
  3214. return (struct objc_method_description *)m;
  3215. }
  3216. IMP
  3217. method_getImplementation(Method m)
  3218. {
  3219. return m ? m->imp : nil;
  3220. }
  3221. /***********************************************************************
  3222. * method_getName
  3223. * Returns this method's selector.
  3224. * The method must not be nil.
  3225. * The method must already have been fixed-up.
  3226. * Locking: none
  3227. **********************************************************************/
  3228. SEL
  3229. method_getName(Method m)
  3230. {
  3231. if (!m) return nil;
  3232. ASSERT(m->name == sel_registerName(sel_getName(m->name)));
  3233. return m->name;
  3234. }
  3235. /***********************************************************************
  3236. * method_getTypeEncoding
  3237. * Returns this method's old-style type encoding string.
  3238. * The method must not be nil.
  3239. * Locking: none
  3240. **********************************************************************/
  3241. const char *
  3242. method_getTypeEncoding(Method m)
  3243. {
  3244. if (!m) return nil;
  3245. return m->types;
  3246. }
  3247. /***********************************************************************
  3248. * method_setImplementation
  3249. * Sets this method's implementation to imp.
  3250. * The previous implementation is returned.
  3251. **********************************************************************/
  3252. static IMP
  3253. _method_setImplementation(Class cls, method_t *m, IMP imp)
  3254. {
  3255. runtimeLock.assertLocked();
  3256. if (!m) return nil;
  3257. if (!imp) return nil;
  3258. IMP old = m->imp;
  3259. m->imp = imp;
  3260. // Cache updates are slow if cls is nil (i.e. unknown)
  3261. // RR/AWZ updates are slow if cls is nil (i.e. unknown)
  3262. // fixme build list of classes whose Methods are known externally?
  3263. flushCaches(cls);
  3264. adjustCustomFlagsForMethodChange(cls, m);
  3265. return old;
  3266. }
  3267. IMP
  3268. method_setImplementation(Method m, IMP imp)
  3269. {
  3270. // Don't know the class - will be slow if RR/AWZ are affected
  3271. // fixme build list of classes whose Methods are known externally?
  3272. mutex_locker_t lock(runtimeLock);
  3273. return _method_setImplementation(Nil, m, imp);
  3274. }
  3275. void method_exchangeImplementations(Method m1, Method m2)
  3276. {
  3277. if (!m1 || !m2) return;
  3278. mutex_locker_t lock(runtimeLock);
  3279. IMP m1_imp = m1->imp;
  3280. m1->imp = m2->imp;
  3281. m2->imp = m1_imp;
  3282. // RR/AWZ updates are slow because class is unknown
  3283. // Cache updates are slow because class is unknown
  3284. // fixme build list of classes whose Methods are known externally?
  3285. flushCaches(nil);
  3286. adjustCustomFlagsForMethodChange(nil, m1);
  3287. adjustCustomFlagsForMethodChange(nil, m2);
  3288. }
  3289. /***********************************************************************
  3290. * ivar_getOffset
  3291. * fixme
  3292. * Locking: none
  3293. **********************************************************************/
  3294. ptrdiff_t
  3295. ivar_getOffset(Ivar ivar)
  3296. {
  3297. if (!ivar) return 0;
  3298. return *ivar->offset;
  3299. }
  3300. /***********************************************************************
  3301. * ivar_getName
  3302. * fixme
  3303. * Locking: none
  3304. **********************************************************************/
  3305. const char *
  3306. ivar_getName(Ivar ivar)
  3307. {
  3308. if (!ivar) return nil;
  3309. return ivar->name;
  3310. }
  3311. /***********************************************************************
  3312. * ivar_getTypeEncoding
  3313. * fixme
  3314. * Locking: none
  3315. **********************************************************************/
  3316. const char *
  3317. ivar_getTypeEncoding(Ivar ivar)
  3318. {
  3319. if (!ivar) return nil;
  3320. return ivar->type;
  3321. }
  3322. const char *property_getName(objc_property_t prop)
  3323. {
  3324. return prop->name;
  3325. }
  3326. const char *property_getAttributes(objc_property_t prop)
  3327. {
  3328. return prop->attributes;
  3329. }
  3330. objc_property_attribute_t *property_copyAttributeList(objc_property_t prop,
  3331. unsigned int *outCount)
  3332. {
  3333. if (!prop) {
  3334. if (outCount) *outCount = 0;
  3335. return nil;
  3336. }
  3337. mutex_locker_t lock(runtimeLock);
  3338. return copyPropertyAttributeList(prop->attributes,outCount);
  3339. }
  3340. char * property_copyAttributeValue(objc_property_t prop, const char *name)
  3341. {
  3342. if (!prop || !name || *name == '\0') return nil;
  3343. mutex_locker_t lock(runtimeLock);
  3344. return copyPropertyAttributeValue(prop->attributes, name);
  3345. }
  3346. /***********************************************************************
  3347. * getExtendedTypesIndexesForMethod
  3348. * Returns:
  3349. * a is the count of methods in all method lists before m's method list
  3350. * b is the index of m in m's method list
  3351. * a+b is the index of m's extended types in the extended types array
  3352. **********************************************************************/
  3353. static void getExtendedTypesIndexesForMethod(protocol_t *proto, const method_t *m, bool isRequiredMethod, bool isInstanceMethod, uint32_t& a, uint32_t &b)
  3354. {
  3355. a = 0;
  3356. if (proto->instanceMethods) {
  3357. if (isRequiredMethod && isInstanceMethod) {
  3358. b = proto->instanceMethods->indexOfMethod(m);
  3359. return;
  3360. }
  3361. a += proto->instanceMethods->count;
  3362. }
  3363. if (proto->classMethods) {
  3364. if (isRequiredMethod && !isInstanceMethod) {
  3365. b = proto->classMethods->indexOfMethod(m);
  3366. return;
  3367. }
  3368. a += proto->classMethods->count;
  3369. }
  3370. if (proto->optionalInstanceMethods) {
  3371. if (!isRequiredMethod && isInstanceMethod) {
  3372. b = proto->optionalInstanceMethods->indexOfMethod(m);
  3373. return;
  3374. }
  3375. a += proto->optionalInstanceMethods->count;
  3376. }
  3377. if (proto->optionalClassMethods) {
  3378. if (!isRequiredMethod && !isInstanceMethod) {
  3379. b = proto->optionalClassMethods->indexOfMethod(m);
  3380. return;
  3381. }
  3382. a += proto->optionalClassMethods->count;
  3383. }
  3384. }
  3385. /***********************************************************************
  3386. * getExtendedTypesIndexForMethod
  3387. * Returns the index of m's extended types in proto's extended types array.
  3388. **********************************************************************/
  3389. static uint32_t getExtendedTypesIndexForMethod(protocol_t *proto, const method_t *m, bool isRequiredMethod, bool isInstanceMethod)
  3390. {
  3391. uint32_t a;
  3392. uint32_t b;
  3393. getExtendedTypesIndexesForMethod(proto, m, isRequiredMethod,
  3394. isInstanceMethod, a, b);
  3395. return a + b;
  3396. }
  3397. /***********************************************************************
  3398. * fixupProtocolMethodList
  3399. * Fixes up a single method list in a protocol.
  3400. **********************************************************************/
  3401. static void
  3402. fixupProtocolMethodList(protocol_t *proto, method_list_t *mlist,
  3403. bool required, bool instance)
  3404. {
  3405. runtimeLock.assertLocked();
  3406. if (!mlist) return;
  3407. if (mlist->isFixedUp()) return;
  3408. const char **extTypes = proto->extendedMethodTypes();
  3409. fixupMethodList(mlist, true/*always copy for simplicity*/,
  3410. !extTypes/*sort if no extended method types*/);
  3411. if (extTypes) {
  3412. // Sort method list and extended method types together.
  3413. // fixupMethodList() can't do this.
  3414. // fixme COW stomp
  3415. uint32_t count = mlist->count;
  3416. uint32_t prefix;
  3417. uint32_t junk;
  3418. getExtendedTypesIndexesForMethod(proto, &mlist->get(0),
  3419. required, instance, prefix, junk);
  3420. for (uint32_t i = 0; i < count; i++) {
  3421. for (uint32_t j = i+1; j < count; j++) {
  3422. method_t& mi = mlist->get(i);
  3423. method_t& mj = mlist->get(j);
  3424. if (mi.name > mj.name) {
  3425. std::swap(mi, mj);
  3426. std::swap(extTypes[prefix+i], extTypes[prefix+j]);
  3427. }
  3428. }
  3429. }
  3430. }
  3431. }
  3432. /***********************************************************************
  3433. * fixupProtocol
  3434. * Fixes up all of a protocol's method lists.
  3435. **********************************************************************/
  3436. static void
  3437. fixupProtocol(protocol_t *proto)
  3438. {
  3439. runtimeLock.assertLocked();
  3440. if (proto->protocols) {
  3441. for (uintptr_t i = 0; i < proto->protocols->count; i++) {
  3442. protocol_t *sub = remapProtocol(proto->protocols->list[i]);
  3443. if (!sub->isFixedUp()) fixupProtocol(sub);
  3444. }
  3445. }
  3446. fixupProtocolMethodList(proto, proto->instanceMethods, YES, YES);
  3447. fixupProtocolMethodList(proto, proto->classMethods, YES, NO);
  3448. fixupProtocolMethodList(proto, proto->optionalInstanceMethods, NO, YES);
  3449. fixupProtocolMethodList(proto, proto->optionalClassMethods, NO, NO);
  3450. // fixme memory barrier so we can check this with no lock
  3451. proto->setFixedUp();
  3452. }
  3453. /***********************************************************************
  3454. * fixupProtocolIfNeeded
  3455. * Fixes up all of a protocol's method lists if they aren't fixed up already.
  3456. * Locking: write-locks runtimeLock.
  3457. **********************************************************************/
  3458. static void
  3459. fixupProtocolIfNeeded(protocol_t *proto)
  3460. {
  3461. runtimeLock.assertUnlocked();
  3462. ASSERT(proto);
  3463. if (!proto->isFixedUp()) {
  3464. mutex_locker_t lock(runtimeLock);
  3465. fixupProtocol(proto);
  3466. }
  3467. }
  3468. static method_list_t *
  3469. getProtocolMethodList(protocol_t *proto, bool required, bool instance)
  3470. {
  3471. method_list_t **mlistp = nil;
  3472. if (required) {
  3473. if (instance) {
  3474. mlistp = &proto->instanceMethods;
  3475. } else {
  3476. mlistp = &proto->classMethods;
  3477. }
  3478. } else {
  3479. if (instance) {
  3480. mlistp = &proto->optionalInstanceMethods;
  3481. } else {
  3482. mlistp = &proto->optionalClassMethods;
  3483. }
  3484. }
  3485. return *mlistp;
  3486. }
  3487. /***********************************************************************
  3488. * protocol_getMethod_nolock
  3489. * Locking: runtimeLock must be held by the caller
  3490. **********************************************************************/
  3491. static method_t *
  3492. protocol_getMethod_nolock(protocol_t *proto, SEL sel,
  3493. bool isRequiredMethod, bool isInstanceMethod,
  3494. bool recursive)
  3495. {
  3496. runtimeLock.assertLocked();
  3497. if (!proto || !sel) return nil;
  3498. ASSERT(proto->isFixedUp());
  3499. method_list_t *mlist =
  3500. getProtocolMethodList(proto, isRequiredMethod, isInstanceMethod);
  3501. if (mlist) {
  3502. method_t *m = search_method_list(mlist, sel);
  3503. if (m) return m;
  3504. }
  3505. if (recursive && proto->protocols) {
  3506. method_t *m;
  3507. for (uint32_t i = 0; i < proto->protocols->count; i++) {
  3508. protocol_t *realProto = remapProtocol(proto->protocols->list[i]);
  3509. m = protocol_getMethod_nolock(realProto, sel,
  3510. isRequiredMethod, isInstanceMethod,
  3511. true);
  3512. if (m) return m;
  3513. }
  3514. }
  3515. return nil;
  3516. }
  3517. /***********************************************************************
  3518. * protocol_getMethod
  3519. * fixme
  3520. * Locking: acquires runtimeLock
  3521. **********************************************************************/
  3522. Method
  3523. protocol_getMethod(protocol_t *proto, SEL sel, bool isRequiredMethod, bool isInstanceMethod, bool recursive)
  3524. {
  3525. if (!proto) return nil;
  3526. fixupProtocolIfNeeded(proto);
  3527. mutex_locker_t lock(runtimeLock);
  3528. return protocol_getMethod_nolock(proto, sel, isRequiredMethod,
  3529. isInstanceMethod, recursive);
  3530. }
  3531. /***********************************************************************
  3532. * protocol_getMethodTypeEncoding_nolock
  3533. * Return the @encode string for the requested protocol method.
  3534. * Returns nil if the compiler did not emit any extended @encode data.
  3535. * Locking: runtimeLock must be held by the caller
  3536. **********************************************************************/
  3537. const char *
  3538. protocol_getMethodTypeEncoding_nolock(protocol_t *proto, SEL sel,
  3539. bool isRequiredMethod,
  3540. bool isInstanceMethod)
  3541. {
  3542. runtimeLock.assertLocked();
  3543. if (!proto) return nil;
  3544. if (!proto->extendedMethodTypes()) return nil;
  3545. ASSERT(proto->isFixedUp());
  3546. method_t *m =
  3547. protocol_getMethod_nolock(proto, sel,
  3548. isRequiredMethod, isInstanceMethod, false);
  3549. if (m) {
  3550. uint32_t i = getExtendedTypesIndexForMethod(proto, m,
  3551. isRequiredMethod,
  3552. isInstanceMethod);
  3553. return proto->extendedMethodTypes()[i];
  3554. }
  3555. // No method with that name. Search incorporated protocols.
  3556. if (proto->protocols) {
  3557. for (uintptr_t i = 0; i < proto->protocols->count; i++) {
  3558. const char *enc =
  3559. protocol_getMethodTypeEncoding_nolock(remapProtocol(proto->protocols->list[i]), sel, isRequiredMethod, isInstanceMethod);
  3560. if (enc) return enc;
  3561. }
  3562. }
  3563. return nil;
  3564. }
  3565. /***********************************************************************
  3566. * _protocol_getMethodTypeEncoding
  3567. * Return the @encode string for the requested protocol method.
  3568. * Returns nil if the compiler did not emit any extended @encode data.
  3569. * Locking: acquires runtimeLock
  3570. **********************************************************************/
  3571. const char *
  3572. _protocol_getMethodTypeEncoding(Protocol *proto_gen, SEL sel,
  3573. BOOL isRequiredMethod, BOOL isInstanceMethod)
  3574. {
  3575. protocol_t *proto = newprotocol(proto_gen);
  3576. if (!proto) return nil;
  3577. fixupProtocolIfNeeded(proto);
  3578. mutex_locker_t lock(runtimeLock);
  3579. return protocol_getMethodTypeEncoding_nolock(proto, sel,
  3580. isRequiredMethod,
  3581. isInstanceMethod);
  3582. }
  3583. /***********************************************************************
  3584. * protocol_t::demangledName
  3585. * Returns the (Swift-demangled) name of the given protocol.
  3586. * Locking: none
  3587. **********************************************************************/
  3588. const char *
  3589. protocol_t::demangledName()
  3590. {
  3591. ASSERT(hasDemangledNameField());
  3592. if (! _demangledName) {
  3593. char *de = copySwiftV1DemangledName(mangledName, true/*isProtocol*/);
  3594. if (! OSAtomicCompareAndSwapPtrBarrier(nil, (void*)(de ?: mangledName),
  3595. (void**)&_demangledName))
  3596. {
  3597. if (de) free(de);
  3598. }
  3599. }
  3600. return _demangledName;
  3601. }
  3602. /***********************************************************************
  3603. * protocol_getName
  3604. * Returns the (Swift-demangled) name of the given protocol.
  3605. * Locking: runtimeLock must not be held by the caller
  3606. **********************************************************************/
  3607. const char *
  3608. protocol_getName(Protocol *proto)
  3609. {
  3610. if (!proto) return "nil";
  3611. else return newprotocol(proto)->demangledName();
  3612. }
  3613. /***********************************************************************
  3614. * protocol_getInstanceMethodDescription
  3615. * Returns the description of a named instance method.
  3616. * Locking: runtimeLock must not be held by the caller
  3617. **********************************************************************/
  3618. struct objc_method_description
  3619. protocol_getMethodDescription(Protocol *p, SEL aSel,
  3620. BOOL isRequiredMethod, BOOL isInstanceMethod)
  3621. {
  3622. Method m =
  3623. protocol_getMethod(newprotocol(p), aSel,
  3624. isRequiredMethod, isInstanceMethod, true);
  3625. if (m) return *method_getDescription(m);
  3626. else return (struct objc_method_description){nil, nil};
  3627. }
  3628. /***********************************************************************
  3629. * protocol_conformsToProtocol_nolock
  3630. * Returns YES if self conforms to other.
  3631. * Locking: runtimeLock must be held by the caller.
  3632. **********************************************************************/
  3633. static bool
  3634. protocol_conformsToProtocol_nolock(protocol_t *self, protocol_t *other)
  3635. {
  3636. runtimeLock.assertLocked();
  3637. if (!self || !other) {
  3638. return NO;
  3639. }
  3640. // protocols need not be fixed up
  3641. if (0 == strcmp(self->mangledName, other->mangledName)) {
  3642. return YES;
  3643. }
  3644. if (self->protocols) {
  3645. uintptr_t i;
  3646. for (i = 0; i < self->protocols->count; i++) {
  3647. protocol_t *proto = remapProtocol(self->protocols->list[i]);
  3648. if (other == proto) {
  3649. return YES;
  3650. }
  3651. if (0 == strcmp(other->mangledName, proto->mangledName)) {
  3652. return YES;
  3653. }
  3654. if (protocol_conformsToProtocol_nolock(proto, other)) {
  3655. return YES;
  3656. }
  3657. }
  3658. }
  3659. return NO;
  3660. }
  3661. /***********************************************************************
  3662. * protocol_conformsToProtocol
  3663. * Returns YES if self conforms to other.
  3664. * Locking: acquires runtimeLock
  3665. **********************************************************************/
  3666. BOOL protocol_conformsToProtocol(Protocol *self, Protocol *other)
  3667. {
  3668. mutex_locker_t lock(runtimeLock);
  3669. return protocol_conformsToProtocol_nolock(newprotocol(self),
  3670. newprotocol(other));
  3671. }
  3672. /***********************************************************************
  3673. * protocol_isEqual
  3674. * Return YES if two protocols are equal (i.e. conform to each other)
  3675. * Locking: acquires runtimeLock
  3676. **********************************************************************/
  3677. BOOL protocol_isEqual(Protocol *self, Protocol *other)
  3678. {
  3679. if (self == other) return YES;
  3680. if (!self || !other) return NO;
  3681. if (!protocol_conformsToProtocol(self, other)) return NO;
  3682. if (!protocol_conformsToProtocol(other, self)) return NO;
  3683. return YES;
  3684. }
  3685. /***********************************************************************
  3686. * protocol_copyMethodDescriptionList
  3687. * Returns descriptions of a protocol's methods.
  3688. * Locking: acquires runtimeLock
  3689. **********************************************************************/
  3690. struct objc_method_description *
  3691. protocol_copyMethodDescriptionList(Protocol *p,
  3692. BOOL isRequiredMethod,BOOL isInstanceMethod,
  3693. unsigned int *outCount)
  3694. {
  3695. protocol_t *proto = newprotocol(p);
  3696. struct objc_method_description *result = nil;
  3697. unsigned int count = 0;
  3698. if (!proto) {
  3699. if (outCount) *outCount = 0;
  3700. return nil;
  3701. }
  3702. fixupProtocolIfNeeded(proto);
  3703. mutex_locker_t lock(runtimeLock);
  3704. method_list_t *mlist =
  3705. getProtocolMethodList(proto, isRequiredMethod, isInstanceMethod);
  3706. if (mlist) {
  3707. result = (struct objc_method_description *)
  3708. calloc(mlist->count + 1, sizeof(struct objc_method_description));
  3709. for (const auto& meth : *mlist) {
  3710. result[count].name = meth.name;
  3711. result[count].types = (char *)meth.types;
  3712. count++;
  3713. }
  3714. }
  3715. if (outCount) *outCount = count;
  3716. return result;
  3717. }
  3718. /***********************************************************************
  3719. * protocol_getProperty
  3720. * fixme
  3721. * Locking: runtimeLock must be held by the caller
  3722. **********************************************************************/
  3723. static property_t *
  3724. protocol_getProperty_nolock(protocol_t *proto, const char *name,
  3725. bool isRequiredProperty, bool isInstanceProperty)
  3726. {
  3727. runtimeLock.assertLocked();
  3728. if (!isRequiredProperty) {
  3729. // Only required properties are currently supported.
  3730. return nil;
  3731. }
  3732. property_list_t *plist = isInstanceProperty ?
  3733. proto->instanceProperties : proto->classProperties();
  3734. if (plist) {
  3735. for (auto& prop : *plist) {
  3736. if (0 == strcmp(name, prop.name)) {
  3737. return &prop;
  3738. }
  3739. }
  3740. }
  3741. if (proto->protocols) {
  3742. uintptr_t i;
  3743. for (i = 0; i < proto->protocols->count; i++) {
  3744. protocol_t *p = remapProtocol(proto->protocols->list[i]);
  3745. property_t *prop =
  3746. protocol_getProperty_nolock(p, name,
  3747. isRequiredProperty,
  3748. isInstanceProperty);
  3749. if (prop) return prop;
  3750. }
  3751. }
  3752. return nil;
  3753. }
  3754. objc_property_t protocol_getProperty(Protocol *p, const char *name,
  3755. BOOL isRequiredProperty, BOOL isInstanceProperty)
  3756. {
  3757. if (!p || !name) return nil;
  3758. mutex_locker_t lock(runtimeLock);
  3759. return (objc_property_t)
  3760. protocol_getProperty_nolock(newprotocol(p), name,
  3761. isRequiredProperty, isInstanceProperty);
  3762. }
  3763. /***********************************************************************
  3764. * protocol_copyPropertyList
  3765. * protocol_copyPropertyList2
  3766. * fixme
  3767. * Locking: acquires runtimeLock
  3768. **********************************************************************/
  3769. static property_t **
  3770. copyPropertyList(property_list_t *plist, unsigned int *outCount)
  3771. {
  3772. property_t **result = nil;
  3773. unsigned int count = 0;
  3774. if (plist) {
  3775. count = plist->count;
  3776. }
  3777. if (count > 0) {
  3778. result = (property_t **)malloc((count+1) * sizeof(property_t *));
  3779. count = 0;
  3780. for (auto& prop : *plist) {
  3781. result[count++] = &prop;
  3782. }
  3783. result[count] = nil;
  3784. }
  3785. if (outCount) *outCount = count;
  3786. return result;
  3787. }
  3788. objc_property_t *
  3789. protocol_copyPropertyList2(Protocol *proto, unsigned int *outCount,
  3790. BOOL isRequiredProperty, BOOL isInstanceProperty)
  3791. {
  3792. if (!proto || !isRequiredProperty) {
  3793. // Optional properties are not currently supported.
  3794. if (outCount) *outCount = 0;
  3795. return nil;
  3796. }
  3797. mutex_locker_t lock(runtimeLock);
  3798. property_list_t *plist = isInstanceProperty
  3799. ? newprotocol(proto)->instanceProperties
  3800. : newprotocol(proto)->classProperties();
  3801. return (objc_property_t *)copyPropertyList(plist, outCount);
  3802. }
  3803. objc_property_t *
  3804. protocol_copyPropertyList(Protocol *proto, unsigned int *outCount)
  3805. {
  3806. return protocol_copyPropertyList2(proto, outCount,
  3807. YES/*required*/, YES/*instance*/);
  3808. }
  3809. /***********************************************************************
  3810. * protocol_copyProtocolList
  3811. * Copies this protocol's incorporated protocols.
  3812. * Does not copy those protocol's incorporated protocols in turn.
  3813. * Locking: acquires runtimeLock
  3814. **********************************************************************/
  3815. Protocol * __unsafe_unretained *
  3816. protocol_copyProtocolList(Protocol *p, unsigned int *outCount)
  3817. {
  3818. unsigned int count = 0;
  3819. Protocol **result = nil;
  3820. protocol_t *proto = newprotocol(p);
  3821. if (!proto) {
  3822. if (outCount) *outCount = 0;
  3823. return nil;
  3824. }
  3825. mutex_locker_t lock(runtimeLock);
  3826. if (proto->protocols) {
  3827. count = (unsigned int)proto->protocols->count;
  3828. }
  3829. if (count > 0) {
  3830. result = (Protocol **)malloc((count+1) * sizeof(Protocol *));
  3831. unsigned int i;
  3832. for (i = 0; i < count; i++) {
  3833. result[i] = (Protocol *)remapProtocol(proto->protocols->list[i]);
  3834. }
  3835. result[i] = nil;
  3836. }
  3837. if (outCount) *outCount = count;
  3838. return result;
  3839. }
  3840. /***********************************************************************
  3841. * objc_allocateProtocol
  3842. * Creates a new protocol. The protocol may not be used until
  3843. * objc_registerProtocol() is called.
  3844. * Returns nil if a protocol with the same name already exists.
  3845. * Locking: acquires runtimeLock
  3846. **********************************************************************/
  3847. Protocol *
  3848. objc_allocateProtocol(const char *name)
  3849. {
  3850. mutex_locker_t lock(runtimeLock);
  3851. if (getProtocol(name)) {
  3852. return nil;
  3853. }
  3854. protocol_t *result = (protocol_t *)calloc(sizeof(protocol_t), 1);
  3855. extern objc_class OBJC_CLASS_$___IncompleteProtocol;
  3856. Class cls = (Class)&OBJC_CLASS_$___IncompleteProtocol;
  3857. result->initProtocolIsa(cls);
  3858. result->size = sizeof(protocol_t);
  3859. // fixme mangle the name if it looks swift-y?
  3860. result->mangledName = strdupIfMutable(name);
  3861. // fixme reserve name without installing
  3862. return (Protocol *)result;
  3863. }
  3864. /***********************************************************************
  3865. * objc_registerProtocol
  3866. * Registers a newly-constructed protocol. The protocol is now
  3867. * ready for use and immutable.
  3868. * Locking: acquires runtimeLock
  3869. **********************************************************************/
  3870. void objc_registerProtocol(Protocol *proto_gen)
  3871. {
  3872. protocol_t *proto = newprotocol(proto_gen);
  3873. mutex_locker_t lock(runtimeLock);
  3874. extern objc_class OBJC_CLASS_$___IncompleteProtocol;
  3875. Class oldcls = (Class)&OBJC_CLASS_$___IncompleteProtocol;
  3876. extern objc_class OBJC_CLASS_$_Protocol;
  3877. Class cls = (Class)&OBJC_CLASS_$_Protocol;
  3878. if (proto->ISA() == cls) {
  3879. _objc_inform("objc_registerProtocol: protocol '%s' was already "
  3880. "registered!", proto->nameForLogging());
  3881. return;
  3882. }
  3883. if (proto->ISA() != oldcls) {
  3884. _objc_inform("objc_registerProtocol: protocol '%s' was not allocated "
  3885. "with objc_allocateProtocol!", proto->nameForLogging());
  3886. return;
  3887. }
  3888. // NOT initProtocolIsa(). The protocol object may already
  3889. // have been retained and we must preserve that count.
  3890. proto->changeIsa(cls);
  3891. // Don't add this protocol if we already have it.
  3892. // Should we warn on duplicates?
  3893. if (getProtocol(proto->mangledName) == nil) {
  3894. NXMapKeyCopyingInsert(protocols(), proto->mangledName, proto);
  3895. }
  3896. }
  3897. /***********************************************************************
  3898. * protocol_addProtocol
  3899. * Adds an incorporated protocol to another protocol.
  3900. * No method enforcement is performed.
  3901. * `proto` must be under construction. `addition` must not.
  3902. * Locking: acquires runtimeLock
  3903. **********************************************************************/
  3904. void
  3905. protocol_addProtocol(Protocol *proto_gen, Protocol *addition_gen)
  3906. {
  3907. protocol_t *proto = newprotocol(proto_gen);
  3908. protocol_t *addition = newprotocol(addition_gen);
  3909. extern objc_class OBJC_CLASS_$___IncompleteProtocol;
  3910. Class cls = (Class)&OBJC_CLASS_$___IncompleteProtocol;
  3911. if (!proto_gen) return;
  3912. if (!addition_gen) return;
  3913. mutex_locker_t lock(runtimeLock);
  3914. if (proto->ISA() != cls) {
  3915. _objc_inform("protocol_addProtocol: modified protocol '%s' is not "
  3916. "under construction!", proto->nameForLogging());
  3917. return;
  3918. }
  3919. if (addition->ISA() == cls) {
  3920. _objc_inform("protocol_addProtocol: added protocol '%s' is still "
  3921. "under construction!", addition->nameForLogging());
  3922. return;
  3923. }
  3924. protocol_list_t *protolist = proto->protocols;
  3925. if (!protolist) {
  3926. protolist = (protocol_list_t *)
  3927. calloc(1, sizeof(protocol_list_t)
  3928. + sizeof(protolist->list[0]));
  3929. } else {
  3930. protolist = (protocol_list_t *)
  3931. realloc(protolist, protocol_list_size(protolist)
  3932. + sizeof(protolist->list[0]));
  3933. }
  3934. protolist->list[protolist->count++] = (protocol_ref_t)addition;
  3935. proto->protocols = protolist;
  3936. }
  3937. /***********************************************************************
  3938. * protocol_addMethodDescription
  3939. * Adds a method to a protocol. The protocol must be under construction.
  3940. * Locking: acquires runtimeLock
  3941. **********************************************************************/
  3942. static void
  3943. protocol_addMethod_nolock(method_list_t*& list, SEL name, const char *types)
  3944. {
  3945. if (!list) {
  3946. list = (method_list_t *)calloc(sizeof(method_list_t), 1);
  3947. list->entsizeAndFlags = sizeof(list->first);
  3948. list->setFixedUp();
  3949. } else {
  3950. size_t size = list->byteSize() + list->entsize();
  3951. list = (method_list_t *)realloc(list, size);
  3952. }
  3953. method_t& meth = list->get(list->count++);
  3954. meth.name = name;
  3955. meth.types = types ? strdupIfMutable(types) : "";
  3956. meth.imp = nil;
  3957. }
  3958. void
  3959. protocol_addMethodDescription(Protocol *proto_gen, SEL name, const char *types,
  3960. BOOL isRequiredMethod, BOOL isInstanceMethod)
  3961. {
  3962. protocol_t *proto = newprotocol(proto_gen);
  3963. extern objc_class OBJC_CLASS_$___IncompleteProtocol;
  3964. Class cls = (Class)&OBJC_CLASS_$___IncompleteProtocol;
  3965. if (!proto_gen) return;
  3966. mutex_locker_t lock(runtimeLock);
  3967. if (proto->ISA() != cls) {
  3968. _objc_inform("protocol_addMethodDescription: protocol '%s' is not "
  3969. "under construction!", proto->nameForLogging());
  3970. return;
  3971. }
  3972. if (isRequiredMethod && isInstanceMethod) {
  3973. protocol_addMethod_nolock(proto->instanceMethods, name, types);
  3974. } else if (isRequiredMethod && !isInstanceMethod) {
  3975. protocol_addMethod_nolock(proto->classMethods, name, types);
  3976. } else if (!isRequiredMethod && isInstanceMethod) {
  3977. protocol_addMethod_nolock(proto->optionalInstanceMethods, name,types);
  3978. } else /* !isRequiredMethod && !isInstanceMethod) */ {
  3979. protocol_addMethod_nolock(proto->optionalClassMethods, name, types);
  3980. }
  3981. }
  3982. /***********************************************************************
  3983. * protocol_addProperty
  3984. * Adds a property to a protocol. The protocol must be under construction.
  3985. * Locking: acquires runtimeLock
  3986. **********************************************************************/
  3987. static void
  3988. protocol_addProperty_nolock(property_list_t *&plist, const char *name,
  3989. const objc_property_attribute_t *attrs,
  3990. unsigned int count)
  3991. {
  3992. if (!plist) {
  3993. plist = (property_list_t *)calloc(sizeof(property_list_t), 1);
  3994. plist->entsizeAndFlags = sizeof(property_t);
  3995. } else {
  3996. plist = (property_list_t *)
  3997. realloc(plist, sizeof(property_list_t)
  3998. + plist->count * plist->entsize());
  3999. }
  4000. property_t& prop = plist->get(plist->count++);
  4001. prop.name = strdupIfMutable(name);
  4002. prop.attributes = copyPropertyAttributeString(attrs, count);
  4003. }
  4004. void
  4005. protocol_addProperty(Protocol *proto_gen, const char *name,
  4006. const objc_property_attribute_t *attrs,
  4007. unsigned int count,
  4008. BOOL isRequiredProperty, BOOL isInstanceProperty)
  4009. {
  4010. protocol_t *proto = newprotocol(proto_gen);
  4011. extern objc_class OBJC_CLASS_$___IncompleteProtocol;
  4012. Class cls = (Class)&OBJC_CLASS_$___IncompleteProtocol;
  4013. if (!proto) return;
  4014. if (!name) return;
  4015. mutex_locker_t lock(runtimeLock);
  4016. if (proto->ISA() != cls) {
  4017. _objc_inform("protocol_addProperty: protocol '%s' is not "
  4018. "under construction!", proto->nameForLogging());
  4019. return;
  4020. }
  4021. if (isRequiredProperty && isInstanceProperty) {
  4022. protocol_addProperty_nolock(proto->instanceProperties, name, attrs, count);
  4023. }
  4024. else if (isRequiredProperty && !isInstanceProperty) {
  4025. protocol_addProperty_nolock(proto->_classProperties, name, attrs, count);
  4026. }
  4027. //else if (!isRequiredProperty && isInstanceProperty) {
  4028. // protocol_addProperty_nolock(proto->optionalInstanceProperties, name, attrs, count);
  4029. //}
  4030. //else /* !isRequiredProperty && !isInstanceProperty) */ {
  4031. // protocol_addProperty_nolock(proto->optionalClassProperties, name, attrs, count);
  4032. //}
  4033. }
  4034. static int
  4035. objc_getRealizedClassList_nolock(Class *buffer, int bufferLen)
  4036. {
  4037. int count = 0;
  4038. if (buffer) {
  4039. int c = 0;
  4040. foreach_realized_class([=, &count, &c](Class cls) {
  4041. count++;
  4042. if (c < bufferLen) {
  4043. buffer[c++] = cls;
  4044. }
  4045. return true;
  4046. });
  4047. } else {
  4048. foreach_realized_class([&count](Class cls) {
  4049. count++;
  4050. return true;
  4051. });
  4052. }
  4053. return count;
  4054. }
  4055. static Class *
  4056. objc_copyRealizedClassList_nolock(unsigned int *outCount)
  4057. {
  4058. Class *result = nil;
  4059. unsigned int count = 0;
  4060. foreach_realized_class([&count](Class cls) {
  4061. count++;
  4062. return true;
  4063. });
  4064. if (count > 0) {
  4065. unsigned int c = 0;
  4066. result = (Class *)malloc((1+count) * sizeof(Class));
  4067. foreach_realized_class([=, &c](Class cls) {
  4068. result[c++] = cls;
  4069. return true;
  4070. });
  4071. result[c] = nil;
  4072. }
  4073. if (outCount) *outCount = count;
  4074. return result;
  4075. }
  4076. static void
  4077. class_getImpCache_nolock(Class cls, cache_t &cache, objc_imp_cache_entry *buffer, int len)
  4078. {
  4079. bucket_t *buckets = cache.buckets();
  4080. uintptr_t count = cache.capacity();
  4081. uintptr_t index;
  4082. int wpos = 0;
  4083. for (index = 0; index < count && wpos < len; index += 1) {
  4084. if (buckets[index].sel()) {
  4085. buffer[wpos].imp = buckets[index].imp(cls);
  4086. buffer[wpos].sel = buckets[index].sel();
  4087. wpos++;
  4088. }
  4089. }
  4090. }
  4091. /***********************************************************************
  4092. * objc_getClassList
  4093. * Returns pointers to all classes.
  4094. * This requires all classes be realized, which is regretfully non-lazy.
  4095. * Locking: acquires runtimeLock
  4096. **********************************************************************/
  4097. int
  4098. objc_getClassList(Class *buffer, int bufferLen)
  4099. {
  4100. mutex_locker_t lock(runtimeLock);
  4101. realizeAllClasses();
  4102. return objc_getRealizedClassList_nolock(buffer, bufferLen);
  4103. }
  4104. /***********************************************************************
  4105. * objc_copyClassList
  4106. * Returns pointers to Realized classes.
  4107. *
  4108. * outCount may be nil. *outCount is the number of classes returned.
  4109. * If the returned array is not nil, it is nil-terminated and must be
  4110. * freed with free().
  4111. * Locking: write-locks runtimeLock
  4112. **********************************************************************/
  4113. Class *
  4114. objc_copyRealizedClassList(unsigned int *outCount)
  4115. {
  4116. mutex_locker_t lock(runtimeLock);
  4117. return objc_copyRealizedClassList_nolock(outCount);
  4118. }
  4119. /***********************************************************************
  4120. * objc_copyClassList
  4121. * Returns pointers to all classes.
  4122. * This requires all classes be realized, which is regretfully non-lazy.
  4123. *
  4124. * outCount may be nil. *outCount is the number of classes returned.
  4125. * If the returned array is not nil, it is nil-terminated and must be
  4126. * freed with free().
  4127. * Locking: write-locks runtimeLock
  4128. **********************************************************************/
  4129. Class *
  4130. objc_copyClassList(unsigned int *outCount)
  4131. {
  4132. mutex_locker_t lock(runtimeLock);
  4133. realizeAllClasses();
  4134. return objc_copyRealizedClassList_nolock(outCount);
  4135. }
  4136. /***********************************************************************
  4137. * class_copyImpCache
  4138. * Returns the current content of the Class IMP Cache
  4139. *
  4140. * outCount may be nil. *outCount is the number of entries returned.
  4141. * If the returned array is not nil, it is nil-terminated and must be
  4142. * freed with free().
  4143. * Locking: write-locks cacheUpdateLock
  4144. **********************************************************************/
  4145. objc_imp_cache_entry *
  4146. class_copyImpCache(Class cls, int *outCount)
  4147. {
  4148. objc_imp_cache_entry *buffer = nullptr;
  4149. #if CONFIG_USE_CACHE_LOCK
  4150. mutex_locker_t lock(cacheUpdateLock);
  4151. #else
  4152. mutex_locker_t lock(runtimeLock);
  4153. #endif
  4154. cache_t &cache = cls->cache;
  4155. int count = (int)cache.occupied();
  4156. if (count) {
  4157. buffer = (objc_imp_cache_entry *)calloc(1+count, sizeof(objc_imp_cache_entry));
  4158. class_getImpCache_nolock(cls, cache, buffer, count);
  4159. }
  4160. if (outCount) *outCount = count;
  4161. return buffer;
  4162. }
  4163. /***********************************************************************
  4164. * objc_copyProtocolList
  4165. * Returns pointers to all protocols.
  4166. * Locking: read-locks runtimeLock
  4167. **********************************************************************/
  4168. Protocol * __unsafe_unretained *
  4169. objc_copyProtocolList(unsigned int *outCount)
  4170. {
  4171. mutex_locker_t lock(runtimeLock);
  4172. NXMapTable *protocol_map = protocols();
  4173. // Find all the protocols from the pre-optimized images. These protocols
  4174. // won't be in the protocol map.
  4175. objc::DenseMap<const char*, Protocol*> preoptimizedProtocols;
  4176. if (sharedCacheSupportsProtocolRoots()) {
  4177. header_info *hi;
  4178. for (hi = FirstHeader; hi; hi = hi->getNext()) {
  4179. if (!hi->hasPreoptimizedProtocols())
  4180. continue;
  4181. size_t count, i;
  4182. const protocol_t * const *protolist = _getObjc2ProtocolList(hi, &count);
  4183. for (i = 0; i < count; i++) {
  4184. const protocol_t* protocol = protolist[i];
  4185. // Skip protocols we have in the run time map. These likely
  4186. // correspond to protocols added dynamically which have the same
  4187. // name as a protocol found later in a dlopen'ed shared cache image.
  4188. if (NXMapGet(protocol_map, protocol->mangledName) != nil)
  4189. continue;
  4190. // The protocols in the shared cache protolist point to their
  4191. // original on-disk object, not the optimized one. We can use the name
  4192. // to find the optimized one.
  4193. Protocol* optimizedProto = getPreoptimizedProtocol(protocol->mangledName);
  4194. preoptimizedProtocols.insert({ protocol->mangledName, optimizedProto });
  4195. }
  4196. }
  4197. }
  4198. unsigned int count = NXCountMapTable(protocol_map) + (unsigned int)preoptimizedProtocols.size();
  4199. if (count == 0) {
  4200. if (outCount) *outCount = 0;
  4201. return nil;
  4202. }
  4203. Protocol **result = (Protocol **)malloc((count+1) * sizeof(Protocol*));
  4204. unsigned int i = 0;
  4205. Protocol *proto;
  4206. const char *name;
  4207. NXMapState state = NXInitMapState(protocol_map);
  4208. while (NXNextMapState(protocol_map, &state,
  4209. (const void **)&name, (const void **)&proto))
  4210. {
  4211. result[i++] = proto;
  4212. }
  4213. // Add any protocols found in the pre-optimized table
  4214. for (auto it : preoptimizedProtocols) {
  4215. result[i++] = it.second;
  4216. }
  4217. result[i++] = nil;
  4218. ASSERT(i == count+1);
  4219. if (outCount) *outCount = count;
  4220. return result;
  4221. }
  4222. /***********************************************************************
  4223. * objc_getProtocol
  4224. * Get a protocol by name, or return nil
  4225. * Locking: read-locks runtimeLock
  4226. **********************************************************************/
  4227. Protocol *objc_getProtocol(const char *name)
  4228. {
  4229. mutex_locker_t lock(runtimeLock);
  4230. return getProtocol(name);
  4231. }
  4232. /***********************************************************************
  4233. * class_copyMethodList
  4234. * fixme
  4235. * Locking: read-locks runtimeLock
  4236. **********************************************************************/
  4237. Method *
  4238. class_copyMethodList(Class cls, unsigned int *outCount)
  4239. {
  4240. unsigned int count = 0;
  4241. Method *result = nil;
  4242. if (!cls) {
  4243. if (outCount) *outCount = 0;
  4244. return nil;
  4245. }
  4246. mutex_locker_t lock(runtimeLock);
  4247. ASSERT(cls->isRealized());
  4248. count = cls->data()->methods.count();
  4249. if (count > 0) {
  4250. result = (Method *)malloc((count + 1) * sizeof(Method));
  4251. count = 0;
  4252. for (auto& meth : cls->data()->methods) {
  4253. result[count++] = &meth;
  4254. }
  4255. result[count] = nil;
  4256. }
  4257. if (outCount) *outCount = count;
  4258. return result;
  4259. }
  4260. /***********************************************************************
  4261. * class_copyIvarList
  4262. * fixme
  4263. * Locking: read-locks runtimeLock
  4264. **********************************************************************/
  4265. Ivar *
  4266. class_copyIvarList(Class cls, unsigned int *outCount)
  4267. {
  4268. const ivar_list_t *ivars;
  4269. Ivar *result = nil;
  4270. unsigned int count = 0;
  4271. if (!cls) {
  4272. if (outCount) *outCount = 0;
  4273. return nil;
  4274. }
  4275. mutex_locker_t lock(runtimeLock);
  4276. ASSERT(cls->isRealized());
  4277. if ((ivars = cls->data()->ro->ivars) && ivars->count) {
  4278. result = (Ivar *)malloc((ivars->count+1) * sizeof(Ivar));
  4279. for (auto& ivar : *ivars) {
  4280. if (!ivar.offset) continue; // anonymous bitfield
  4281. result[count++] = &ivar;
  4282. }
  4283. result[count] = nil;
  4284. }
  4285. if (outCount) *outCount = count;
  4286. return result;
  4287. }
  4288. /***********************************************************************
  4289. * class_copyPropertyList. Returns a heap block containing the
  4290. * properties declared in the class, or nil if the class
  4291. * declares no properties. Caller must free the block.
  4292. * Does not copy any superclass's properties.
  4293. * Locking: read-locks runtimeLock
  4294. **********************************************************************/
  4295. objc_property_t *
  4296. class_copyPropertyList(Class cls, unsigned int *outCount)
  4297. {
  4298. if (!cls) {
  4299. if (outCount) *outCount = 0;
  4300. return nil;
  4301. }
  4302. mutex_locker_t lock(runtimeLock);
  4303. checkIsKnownClass(cls);
  4304. ASSERT(cls->isRealized());
  4305. auto rw = cls->data();
  4306. property_t **result = nil;
  4307. unsigned int count = rw->properties.count();
  4308. if (count > 0) {
  4309. result = (property_t **)malloc((count + 1) * sizeof(property_t *));
  4310. count = 0;
  4311. for (auto& prop : rw->properties) {
  4312. result[count++] = &prop;
  4313. }
  4314. result[count] = nil;
  4315. }
  4316. if (outCount) *outCount = count;
  4317. return (objc_property_t *)result;
  4318. }
  4319. /***********************************************************************
  4320. * objc_class::getLoadMethod
  4321. * fixme
  4322. * Called only from add_class_to_loadable_list.
  4323. * Locking: runtimeLock must be read- or write-locked by the caller.
  4324. **********************************************************************/
  4325. IMP
  4326. objc_class::getLoadMethod()
  4327. {
  4328. runtimeLock.assertLocked();
  4329. const method_list_t *mlist;
  4330. ASSERT(isRealized());
  4331. ASSERT(ISA()->isRealized());
  4332. ASSERT(!isMetaClass());
  4333. ASSERT(ISA()->isMetaClass());
  4334. mlist = ISA()->data()->ro->baseMethods();
  4335. if (mlist) {
  4336. for (const auto& meth : *mlist) {
  4337. const char *name = sel_cname(meth.name);
  4338. if (0 == strcmp(name, "load")) {
  4339. return meth.imp;
  4340. }
  4341. }
  4342. }
  4343. return nil;
  4344. }
  4345. /***********************************************************************
  4346. * _category_getName
  4347. * Returns a category's name.
  4348. * Locking: none
  4349. **********************************************************************/
  4350. const char *
  4351. _category_getName(Category cat)
  4352. {
  4353. return cat->name;
  4354. }
  4355. /***********************************************************************
  4356. * _category_getClassName
  4357. * Returns a category's class's name
  4358. * Called only from add_category_to_loadable_list and
  4359. * remove_category_from_loadable_list for logging purposes.
  4360. * Locking: runtimeLock must be read- or write-locked by the caller
  4361. **********************************************************************/
  4362. const char *
  4363. _category_getClassName(Category cat)
  4364. {
  4365. runtimeLock.assertLocked();
  4366. return remapClass(cat->cls)->nameForLogging();
  4367. }
  4368. /***********************************************************************
  4369. * _category_getClass
  4370. * Returns a category's class
  4371. * Called only by call_category_loads.
  4372. * Locking: read-locks runtimeLock
  4373. **********************************************************************/
  4374. Class
  4375. _category_getClass(Category cat)
  4376. {
  4377. mutex_locker_t lock(runtimeLock);
  4378. Class result = remapClass(cat->cls);
  4379. ASSERT(result->isRealized()); // ok for call_category_loads' usage
  4380. return result;
  4381. }
  4382. /***********************************************************************
  4383. * _category_getLoadMethod
  4384. * fixme
  4385. * Called only from add_category_to_loadable_list
  4386. * Locking: runtimeLock must be read- or write-locked by the caller
  4387. **********************************************************************/
  4388. IMP
  4389. _category_getLoadMethod(Category cat)
  4390. {
  4391. runtimeLock.assertLocked();
  4392. const method_list_t *mlist;
  4393. mlist = cat->classMethods;
  4394. if (mlist) {
  4395. for (const auto& meth : *mlist) {
  4396. const char *name = sel_cname(meth.name);
  4397. if (0 == strcmp(name, "load")) {
  4398. return meth.imp;
  4399. }
  4400. }
  4401. }
  4402. return nil;
  4403. }
  4404. /***********************************************************************
  4405. * category_t::propertiesForMeta
  4406. * Return a category's instance or class properties.
  4407. * hi is the image containing the category.
  4408. **********************************************************************/
  4409. property_list_t *
  4410. category_t::propertiesForMeta(bool isMeta, struct header_info *hi)
  4411. {
  4412. if (!isMeta) return instanceProperties;
  4413. else if (hi->info()->hasCategoryClassProperties()) return _classProperties;
  4414. else return nil;
  4415. }
  4416. /***********************************************************************
  4417. * class_copyProtocolList
  4418. * fixme
  4419. * Locking: read-locks runtimeLock
  4420. **********************************************************************/
  4421. Protocol * __unsafe_unretained *
  4422. class_copyProtocolList(Class cls, unsigned int *outCount)
  4423. {
  4424. unsigned int count = 0;
  4425. Protocol **result = nil;
  4426. if (!cls) {
  4427. if (outCount) *outCount = 0;
  4428. return nil;
  4429. }
  4430. mutex_locker_t lock(runtimeLock);
  4431. checkIsKnownClass(cls);
  4432. ASSERT(cls->isRealized());
  4433. count = cls->data()->protocols.count();
  4434. if (count > 0) {
  4435. result = (Protocol **)malloc((count+1) * sizeof(Protocol *));
  4436. count = 0;
  4437. for (const auto& proto : cls->data()->protocols) {
  4438. result[count++] = (Protocol *)remapProtocol(proto);
  4439. }
  4440. result[count] = nil;
  4441. }
  4442. if (outCount) *outCount = count;
  4443. return result;
  4444. }
  4445. /***********************************************************************
  4446. * objc_copyImageNames
  4447. * Copies names of loaded images with ObjC contents.
  4448. *
  4449. * Locking: acquires runtimeLock
  4450. **********************************************************************/
  4451. const char **objc_copyImageNames(unsigned int *outCount)
  4452. {
  4453. mutex_locker_t lock(runtimeLock);
  4454. int HeaderCount = 0;
  4455. for (header_info *hi = FirstHeader; hi != nil; hi = hi->getNext()) {
  4456. HeaderCount++;
  4457. }
  4458. #if TARGET_OS_WIN32
  4459. const TCHAR **names = (const TCHAR **)
  4460. malloc((HeaderCount+1) * sizeof(TCHAR *));
  4461. #else
  4462. const char **names = (const char **)
  4463. malloc((HeaderCount+1) * sizeof(char *));
  4464. #endif
  4465. unsigned int count = 0;
  4466. for (header_info *hi = FirstHeader; hi != nil; hi = hi->getNext()) {
  4467. #if TARGET_OS_WIN32
  4468. if (hi->moduleName) {
  4469. names[count++] = hi->moduleName;
  4470. }
  4471. #else
  4472. const char *fname = hi->fname();
  4473. if (fname) {
  4474. names[count++] = fname;
  4475. }
  4476. #endif
  4477. }
  4478. names[count] = nil;
  4479. if (count == 0) {
  4480. // Return nil instead of empty list if there are no images
  4481. free((void *)names);
  4482. names = nil;
  4483. }
  4484. if (outCount) *outCount = count;
  4485. return names;
  4486. }
  4487. /***********************************************************************
  4488. * copyClassNamesForImage_nolock
  4489. * Copies class names from the given image.
  4490. * Missing weak-import classes are omitted.
  4491. * Swift class names are demangled.
  4492. *
  4493. * Locking: runtimeLock must be held by the caller
  4494. **********************************************************************/
  4495. const char **
  4496. copyClassNamesForImage_nolock(header_info *hi, unsigned int *outCount)
  4497. {
  4498. runtimeLock.assertLocked();
  4499. ASSERT(hi);
  4500. size_t count;
  4501. classref_t const *classlist = _getObjc2ClassList(hi, &count);
  4502. const char **names = (const char **)
  4503. malloc((count+1) * sizeof(const char *));
  4504. size_t shift = 0;
  4505. for (size_t i = 0; i < count; i++) {
  4506. Class cls = remapClass(classlist[i]);
  4507. if (cls) {
  4508. names[i-shift] = cls->demangledName();
  4509. } else {
  4510. shift++; // ignored weak-linked class
  4511. }
  4512. }
  4513. count -= shift;
  4514. names[count] = nil;
  4515. if (outCount) *outCount = (unsigned int)count;
  4516. return names;
  4517. }
  4518. /***********************************************************************
  4519. * objc_copyClassNamesForImage
  4520. * Copies class names from the named image.
  4521. * The image name must be identical to dladdr's dli_fname value.
  4522. * Missing weak-import classes are omitted.
  4523. * Swift class names are demangled.
  4524. *
  4525. * Locking: acquires runtimeLock
  4526. **********************************************************************/
  4527. const char **
  4528. objc_copyClassNamesForImage(const char *image, unsigned int *outCount)
  4529. {
  4530. if (!image) {
  4531. if (outCount) *outCount = 0;
  4532. return nil;
  4533. }
  4534. mutex_locker_t lock(runtimeLock);
  4535. // Find the image.
  4536. header_info *hi;
  4537. for (hi = FirstHeader; hi != nil; hi = hi->getNext()) {
  4538. #if TARGET_OS_WIN32
  4539. if (0 == wcscmp((TCHAR *)image, hi->moduleName)) break;
  4540. #else
  4541. if (0 == strcmp(image, hi->fname())) break;
  4542. #endif
  4543. }
  4544. if (!hi) {
  4545. if (outCount) *outCount = 0;
  4546. return nil;
  4547. }
  4548. return copyClassNamesForImage_nolock(hi, outCount);
  4549. }
  4550. /***********************************************************************
  4551. * objc_copyClassNamesForImageHeader
  4552. * Copies class names from the given image.
  4553. * Missing weak-import classes are omitted.
  4554. * Swift class names are demangled.
  4555. *
  4556. * Locking: acquires runtimeLock
  4557. **********************************************************************/
  4558. const char **
  4559. objc_copyClassNamesForImageHeader(const struct mach_header *mh, unsigned int *outCount)
  4560. {
  4561. if (!mh) {
  4562. if (outCount) *outCount = 0;
  4563. return nil;
  4564. }
  4565. mutex_locker_t lock(runtimeLock);
  4566. // Find the image.
  4567. header_info *hi;
  4568. for (hi = FirstHeader; hi != nil; hi = hi->getNext()) {
  4569. if (hi->mhdr() == (const headerType *)mh) break;
  4570. }
  4571. if (!hi) {
  4572. if (outCount) *outCount = 0;
  4573. return nil;
  4574. }
  4575. return copyClassNamesForImage_nolock(hi, outCount);
  4576. }
  4577. /***********************************************************************
  4578. * saveTemporaryString
  4579. * Save a string in a thread-local FIFO buffer.
  4580. * This is suitable for temporary strings generated for logging purposes.
  4581. **********************************************************************/
  4582. static void
  4583. saveTemporaryString(char *str)
  4584. {
  4585. // Fixed-size FIFO. We free the first string, shift
  4586. // the rest, and add the new string to the end.
  4587. _objc_pthread_data *data = _objc_fetch_pthread_data(true);
  4588. if (data->printableNames[0]) {
  4589. free(data->printableNames[0]);
  4590. }
  4591. int last = countof(data->printableNames) - 1;
  4592. for (int i = 0; i < last; i++) {
  4593. data->printableNames[i] = data->printableNames[i+1];
  4594. }
  4595. data->printableNames[last] = str;
  4596. }
  4597. /***********************************************************************
  4598. * objc_class::nameForLogging
  4599. * Returns the class's name, suitable for display.
  4600. * The returned memory is TEMPORARY. Print it or copy it immediately.
  4601. * Locking: none
  4602. **********************************************************************/
  4603. const char *
  4604. objc_class::nameForLogging()
  4605. {
  4606. // Handle the easy case directly.
  4607. if (isRealized() || isFuture()) {
  4608. if (data()->demangledName) return data()->demangledName;
  4609. }
  4610. char *result;
  4611. const char *name = mangledName();
  4612. char *de = copySwiftV1DemangledName(name);
  4613. if (de) result = de;
  4614. else result = strdup(name);
  4615. saveTemporaryString(result);
  4616. return result;
  4617. }
  4618. /***********************************************************************
  4619. * objc_class::demangledName
  4620. * If realize=false, the class must already be realized or future.
  4621. * Locking: runtimeLock may or may not be held by the caller.
  4622. **********************************************************************/
  4623. mutex_t DemangleCacheLock;
  4624. static objc::DenseSet<const char *> *DemangleCache;
  4625. const char *
  4626. objc_class::demangledName()
  4627. {
  4628. // Return previously demangled name if available.
  4629. if (isRealized() || isFuture()) {
  4630. if (data()->demangledName) return data()->demangledName;
  4631. }
  4632. // Try demangling the mangled name.
  4633. const char *mangled = mangledName();
  4634. char *de = copySwiftV1DemangledName(mangled);
  4635. if (isRealized() || isFuture()) {
  4636. // Class is already realized or future.
  4637. // Save demangling result in rw data.
  4638. // We may not own runtimeLock so use an atomic operation instead.
  4639. if (! OSAtomicCompareAndSwapPtrBarrier(nil, (void*)(de ?: mangled),
  4640. (void**)&data()->demangledName))
  4641. {
  4642. if (de) free(de);
  4643. }
  4644. return data()->demangledName;
  4645. }
  4646. // Class is not yet realized.
  4647. if (!de) {
  4648. // Name is not mangled. Return it without caching.
  4649. return mangled;
  4650. }
  4651. // Class is not yet realized and name is mangled.
  4652. // Allocate the name but don't save it in the class.
  4653. // Save the name in a side cache instead to prevent leaks.
  4654. // When the class is actually realized we may allocate a second
  4655. // copy of the name, but we don't care.
  4656. // (Previously we would try to realize the class now and save the
  4657. // name there, but realization is more complicated for Swift classes.)
  4658. // Only objc_copyClassNamesForImage() should get here.
  4659. // fixme lldb's calls to class_getName() can also get here when
  4660. // interrogating the dyld shared cache. (rdar://27258517)
  4661. // fixme runtimeLock.assertLocked();
  4662. // fixme ASSERT(realize);
  4663. const char *cached;
  4664. {
  4665. mutex_locker_t lock(DemangleCacheLock);
  4666. if (!DemangleCache) {
  4667. DemangleCache = new objc::DenseSet<const char *>{};
  4668. }
  4669. cached = *DemangleCache->insert(de).first;
  4670. }
  4671. if (cached != de) free(de);
  4672. return cached;
  4673. }
  4674. /***********************************************************************
  4675. * class_getName
  4676. * fixme
  4677. * Locking: may acquire DemangleCacheLock
  4678. **********************************************************************/
  4679. const char *class_getName(Class cls)
  4680. {
  4681. if (!cls) return "nil";
  4682. // fixme lldb calls class_getName() on unrealized classes (rdar://27258517)
  4683. // ASSERT(cls->isRealized() || cls->isFuture());
  4684. return cls->demangledName();
  4685. }
  4686. /***********************************************************************
  4687. * objc_debug_class_getNameRaw
  4688. * fixme
  4689. * Locking: none
  4690. **********************************************************************/
  4691. const char *objc_debug_class_getNameRaw(Class cls)
  4692. {
  4693. if (!cls) return "nil";
  4694. return cls->mangledName();
  4695. }
  4696. /***********************************************************************
  4697. * class_getVersion
  4698. * fixme
  4699. * Locking: none
  4700. **********************************************************************/
  4701. int
  4702. class_getVersion(Class cls)
  4703. {
  4704. if (!cls) return 0;
  4705. ASSERT(cls->isRealized());
  4706. return cls->data()->version;
  4707. }
  4708. /***********************************************************************
  4709. * class_setVersion
  4710. * fixme
  4711. * Locking: none
  4712. **********************************************************************/
  4713. void
  4714. class_setVersion(Class cls, int version)
  4715. {
  4716. if (!cls) return;
  4717. ASSERT(cls->isRealized());
  4718. cls->data()->version = version;
  4719. }
  4720. /***********************************************************************
  4721. * search_method_list_inline
  4722. **********************************************************************/
  4723. ALWAYS_INLINE static method_t *
  4724. findMethodInSortedMethodList(SEL key, const method_list_t *list)
  4725. {
  4726. ASSERT(list);
  4727. const method_t * const first = &list->first;
  4728. const method_t *base = first;
  4729. const method_t *probe;
  4730. uintptr_t keyValue = (uintptr_t)key;
  4731. uint32_t count;
  4732. for (count = list->count; count != 0; count >>= 1) {
  4733. probe = base + (count >> 1);
  4734. uintptr_t probeValue = (uintptr_t)probe->name;
  4735. if (keyValue == probeValue) {
  4736. // `probe` is a match.
  4737. // Rewind looking for the *first* occurrence of this value.
  4738. // This is required for correct category overrides.
  4739. while (probe > first && keyValue == (uintptr_t)probe[-1].name) {
  4740. probe--;
  4741. }
  4742. return (method_t *)probe;
  4743. }
  4744. if (keyValue > probeValue) {
  4745. base = probe + 1;
  4746. count--;
  4747. }
  4748. }
  4749. return nil;
  4750. }
  4751. ALWAYS_INLINE static method_t *
  4752. search_method_list_inline(const method_list_t *mlist, SEL sel)
  4753. {
  4754. int methodListIsFixedUp = mlist->isFixedUp();
  4755. int methodListHasExpectedSize = mlist->entsize() == sizeof(method_t);
  4756. if (fastpath(methodListIsFixedUp && methodListHasExpectedSize)) {
  4757. return findMethodInSortedMethodList(sel, mlist);
  4758. } else {
  4759. // Linear search of unsorted method list
  4760. for (auto& meth : *mlist) {
  4761. if (meth.name == sel) return &meth;
  4762. }
  4763. }
  4764. #if DEBUG
  4765. // sanity-check negative results
  4766. if (mlist->isFixedUp()) {
  4767. for (auto& meth : *mlist) {
  4768. if (meth.name == sel) {
  4769. _objc_fatal("linear search worked when binary search did not");
  4770. }
  4771. }
  4772. }
  4773. #endif
  4774. return nil;
  4775. }
  4776. NEVER_INLINE static method_t *
  4777. search_method_list(const method_list_t *mlist, SEL sel)
  4778. {
  4779. return search_method_list_inline(mlist, sel);
  4780. }
  4781. /***********************************************************************
  4782. * method_lists_contains_any
  4783. **********************************************************************/
  4784. static NEVER_INLINE bool
  4785. method_lists_contains_any(method_list_t **mlists, method_list_t **end,
  4786. SEL sels[], size_t selcount)
  4787. {
  4788. while (mlists < end) {
  4789. const method_list_t *mlist = *mlists++;
  4790. int methodListIsFixedUp = mlist->isFixedUp();
  4791. int methodListHasExpectedSize = mlist->entsize() == sizeof(method_t);
  4792. if (fastpath(methodListIsFixedUp && methodListHasExpectedSize)) {
  4793. for (size_t i = 0; i < selcount; i++) {
  4794. if (findMethodInSortedMethodList(sels[i], mlist)) {
  4795. return true;
  4796. }
  4797. }
  4798. } else {
  4799. for (auto& meth : *mlist) {
  4800. for (size_t i = 0; i < selcount; i++) {
  4801. if (meth.name == sels[i]) {
  4802. return true;
  4803. }
  4804. }
  4805. }
  4806. }
  4807. }
  4808. return false;
  4809. }
  4810. /***********************************************************************
  4811. * getMethodNoSuper_nolock
  4812. * fixme
  4813. * Locking: runtimeLock must be read- or write-locked by the caller
  4814. **********************************************************************/
  4815. static method_t *
  4816. getMethodNoSuper_nolock(Class cls, SEL sel)
  4817. {
  4818. runtimeLock.assertLocked();
  4819. ASSERT(cls->isRealized());
  4820. // fixme nil cls?
  4821. // fixme nil sel?
  4822. for (auto mlists = cls->data()->methods.beginLists(),
  4823. end = cls->data()->methods.endLists();
  4824. mlists != end;
  4825. ++mlists)
  4826. {
  4827. // <rdar://problem/46904873> getMethodNoSuper_nolock is the hottest
  4828. // caller of search_method_list, inlining it turns
  4829. // getMethodNoSuper_nolock into a frame-less function and eliminates
  4830. // any store from this codepath.
  4831. method_t *m = search_method_list_inline(*mlists, sel);
  4832. if (m) return m;
  4833. }
  4834. return nil;
  4835. }
  4836. /***********************************************************************
  4837. * getMethod_nolock
  4838. * fixme
  4839. * Locking: runtimeLock must be read- or write-locked by the caller
  4840. **********************************************************************/
  4841. static method_t *
  4842. getMethod_nolock(Class cls, SEL sel)
  4843. {
  4844. method_t *m = nil;
  4845. runtimeLock.assertLocked();
  4846. // fixme nil cls?
  4847. // fixme nil sel?
  4848. ASSERT(cls->isRealized());
  4849. while (cls && ((m = getMethodNoSuper_nolock(cls, sel))) == nil) {
  4850. cls = cls->superclass;
  4851. }
  4852. return m;
  4853. }
  4854. /***********************************************************************
  4855. * _class_getMethod
  4856. * fixme
  4857. * Locking: read-locks runtimeLock
  4858. **********************************************************************/
  4859. static Method _class_getMethod(Class cls, SEL sel)
  4860. {
  4861. mutex_locker_t lock(runtimeLock);
  4862. return getMethod_nolock(cls, sel);
  4863. }
  4864. /***********************************************************************
  4865. * class_getInstanceMethod. Return the instance method for the
  4866. * specified class and selector.
  4867. **********************************************************************/
  4868. Method class_getInstanceMethod(Class cls, SEL sel)
  4869. {
  4870. if (!cls || !sel) return nil;
  4871. // This deliberately avoids +initialize because it historically did so.
  4872. // This implementation is a bit weird because it's the only place that
  4873. // wants a Method instead of an IMP.
  4874. #warning fixme build and search caches
  4875. // Search method lists, try method resolver, etc.
  4876. lookUpImpOrForward(nil, sel, cls, LOOKUP_RESOLVER);
  4877. #warning fixme build and search caches
  4878. return _class_getMethod(cls, sel);
  4879. }
  4880. /***********************************************************************
  4881. * resolveClassMethod
  4882. * Call +resolveClassMethod, looking for a method to be added to class cls.
  4883. * cls should be a metaclass.
  4884. * Does not check if the method already exists.
  4885. **********************************************************************/
  4886. static void resolveClassMethod(id inst, SEL sel, Class cls)
  4887. {
  4888. runtimeLock.assertUnlocked();
  4889. ASSERT(cls->isRealized());
  4890. ASSERT(cls->isMetaClass());
  4891. if (!lookUpImpOrNil(inst, @selector(resolveClassMethod:), cls)) {
  4892. // Resolver not implemented.
  4893. return;
  4894. }
  4895. Class nonmeta;
  4896. {
  4897. mutex_locker_t lock(runtimeLock);
  4898. nonmeta = getMaybeUnrealizedNonMetaClass(cls, inst);
  4899. // +initialize path should have realized nonmeta already
  4900. if (!nonmeta->isRealized()) {
  4901. _objc_fatal("nonmeta class %s (%p) unexpectedly not realized",
  4902. nonmeta->nameForLogging(), nonmeta);
  4903. }
  4904. }
  4905. BOOL (*msg)(Class, SEL, SEL) = (typeof(msg))objc_msgSend;
  4906. bool resolved = msg(nonmeta, @selector(resolveClassMethod:), sel);
  4907. // Cache the result (good or bad) so the resolver doesn't fire next time.
  4908. // +resolveClassMethod adds to self->ISA() a.k.a. cls
  4909. IMP imp = lookUpImpOrNil(inst, sel, cls);
  4910. if (resolved && PrintResolving) {
  4911. if (imp) {
  4912. _objc_inform("RESOLVE: method %c[%s %s] "
  4913. "dynamically resolved to %p",
  4914. cls->isMetaClass() ? '+' : '-',
  4915. cls->nameForLogging(), sel_getName(sel), imp);
  4916. }
  4917. else {
  4918. // Method resolver didn't add anything?
  4919. _objc_inform("RESOLVE: +[%s resolveClassMethod:%s] returned YES"
  4920. ", but no new implementation of %c[%s %s] was found",
  4921. cls->nameForLogging(), sel_getName(sel),
  4922. cls->isMetaClass() ? '+' : '-',
  4923. cls->nameForLogging(), sel_getName(sel));
  4924. }
  4925. }
  4926. }
  4927. /***********************************************************************
  4928. * resolveInstanceMethod
  4929. * Call +resolveInstanceMethod, looking for a method to be added to class cls.
  4930. * cls may be a metaclass or a non-meta class.
  4931. * Does not check if the method already exists.
  4932. **********************************************************************/
  4933. static void resolveInstanceMethod(id inst, SEL sel, Class cls)
  4934. {
  4935. runtimeLock.assertUnlocked();
  4936. ASSERT(cls->isRealized());
  4937. SEL resolve_sel = @selector(resolveInstanceMethod:);
  4938. if (!lookUpImpOrNil(cls, resolve_sel, cls->ISA())) {
  4939. // Resolver not implemented.
  4940. return;
  4941. }
  4942. BOOL (*msg)(Class, SEL, SEL) = (typeof(msg))objc_msgSend;
  4943. bool resolved = msg(cls, resolve_sel, sel);
  4944. // Cache the result (good or bad) so the resolver doesn't fire next time.
  4945. // +resolveInstanceMethod adds to self a.k.a. cls
  4946. IMP imp = lookUpImpOrNil(inst, sel, cls);
  4947. if (resolved && PrintResolving) {
  4948. if (imp) {
  4949. _objc_inform("RESOLVE: method %c[%s %s] "
  4950. "dynamically resolved to %p",
  4951. cls->isMetaClass() ? '+' : '-',
  4952. cls->nameForLogging(), sel_getName(sel), imp);
  4953. }
  4954. else {
  4955. // Method resolver didn't add anything?
  4956. _objc_inform("RESOLVE: +[%s resolveInstanceMethod:%s] returned YES"
  4957. ", but no new implementation of %c[%s %s] was found",
  4958. cls->nameForLogging(), sel_getName(sel),
  4959. cls->isMetaClass() ? '+' : '-',
  4960. cls->nameForLogging(), sel_getName(sel));
  4961. }
  4962. }
  4963. }
  4964. /***********************************************************************
  4965. * resolveMethod_locked
  4966. * Call +resolveClassMethod or +resolveInstanceMethod.
  4967. *
  4968. * Called with the runtimeLock held to avoid pressure in the caller
  4969. * Tail calls into lookUpImpOrForward, also to avoid pressure in the callerb
  4970. **********************************************************************/
  4971. static NEVER_INLINE IMP
  4972. resolveMethod_locked(id inst, SEL sel, Class cls, int behavior)
  4973. {
  4974. runtimeLock.assertLocked();
  4975. ASSERT(cls->isRealized());
  4976. runtimeLock.unlock();
  4977. if (! cls->isMetaClass()) {
  4978. // try [cls resolveInstanceMethod:sel]
  4979. resolveInstanceMethod(inst, sel, cls);
  4980. }
  4981. else {
  4982. // try [nonMetaClass resolveClassMethod:sel]
  4983. // and [cls resolveInstanceMethod:sel]
  4984. resolveClassMethod(inst, sel, cls);
  4985. if (!lookUpImpOrNil(inst, sel, cls)) {
  4986. resolveInstanceMethod(inst, sel, cls);
  4987. }
  4988. }
  4989. // chances are that calling the resolver have populated the cache
  4990. // so attempt using it
  4991. return lookUpImpOrForward(inst, sel, cls, behavior | LOOKUP_CACHE);
  4992. }
  4993. /***********************************************************************
  4994. * log_and_fill_cache
  4995. * Log this method call. If the logger permits it, fill the method cache.
  4996. * cls is the method whose cache should be filled.
  4997. * implementer is the class that owns the implementation in question.
  4998. **********************************************************************/
  4999. static void
  5000. log_and_fill_cache(Class cls, IMP imp, SEL sel, id receiver, Class implementer)
  5001. {
  5002. #if SUPPORT_MESSAGE_LOGGING
  5003. if (slowpath(objcMsgLogEnabled && implementer)) {
  5004. bool cacheIt = logMessageSend(implementer->isMetaClass(),
  5005. cls->nameForLogging(),
  5006. implementer->nameForLogging(),
  5007. sel);
  5008. if (!cacheIt) return;
  5009. }
  5010. #endif
  5011. cache_fill(cls, sel, imp, receiver);
  5012. }
  5013. /***********************************************************************
  5014. * lookUpImpOrForward.
  5015. * The standard IMP lookup.
  5016. * Without LOOKUP_INITIALIZE: tries to avoid +initialize (but sometimes fails)
  5017. * Without LOOKUP_CACHE: skips optimistic unlocked lookup (but uses cache elsewhere)
  5018. * Most callers should use LOOKUP_INITIALIZE and LOOKUP_CACHE
  5019. * inst is an instance of cls or a subclass thereof, or nil if none is known.
  5020. * If cls is an un-initialized metaclass then a non-nil inst is faster.
  5021. * May return _objc_msgForward_impcache. IMPs destined for external use
  5022. * must be converted to _objc_msgForward or _objc_msgForward_stret.
  5023. * If you don't want forwarding at all, use LOOKUP_NIL.
  5024. **********************************************************************/
  5025. IMP lookUpImpOrForward(id inst, SEL sel, Class cls, int behavior)
  5026. {
  5027. const IMP forward_imp = (IMP)_objc_msgForward_impcache;
  5028. IMP imp = nil;
  5029. Class curClass;
  5030. runtimeLock.assertUnlocked();
  5031. // Optimistic cache lookup
  5032. if (fastpath(behavior & LOOKUP_CACHE)) {
  5033. imp = cache_getImp(cls, sel);
  5034. if (imp) goto done_nolock;
  5035. }
  5036. // runtimeLock is held during isRealized and isInitialized checking
  5037. // to prevent races against concurrent realization.
  5038. // runtimeLock is held during method search to make
  5039. // method-lookup + cache-fill atomic with respect to method addition.
  5040. // Otherwise, a category could be added but ignored indefinitely because
  5041. // the cache was re-filled with the old value after the cache flush on
  5042. // behalf of the category.
  5043. runtimeLock.lock();
  5044. // We don't want people to be able to craft a binary blob that looks like
  5045. // a class but really isn't one and do a CFI attack.
  5046. //
  5047. // To make these harder we want to make sure this is a class that was
  5048. // either built into the binary or legitimately registered through
  5049. // objc_duplicateClass, objc_initializeClassPair or objc_allocateClassPair.
  5050. //
  5051. // TODO: this check is quite costly during process startup.
  5052. checkIsKnownClass(cls);
  5053. if (slowpath(!cls->isRealized())) {
  5054. cls = realizeClassMaybeSwiftAndLeaveLocked(cls, runtimeLock);
  5055. // runtimeLock may have been dropped but is now locked again
  5056. }
  5057. if (slowpath((behavior & LOOKUP_INITIALIZE) && !cls->isInitialized())) {
  5058. cls = initializeAndLeaveLocked(cls, inst, runtimeLock);
  5059. // runtimeLock may have been dropped but is now locked again
  5060. // If sel == initialize, class_initialize will send +initialize and
  5061. // then the messenger will send +initialize again after this
  5062. // procedure finishes. Of course, if this is not being called
  5063. // from the messenger then it won't happen. 2778172
  5064. }
  5065. runtimeLock.assertLocked();
  5066. curClass = cls;
  5067. // The code used to lookpu the class's cache again right after
  5068. // we take the lock but for the vast majority of the cases
  5069. // evidence shows this is a miss most of the time, hence a time loss.
  5070. //
  5071. // The only codepath calling into this without having performed some
  5072. // kind of cache lookup is class_getInstanceMethod().
  5073. for (unsigned attempts = unreasonableClassCount();;) {
  5074. // curClass method list.
  5075. Method meth = getMethodNoSuper_nolock(curClass, sel);
  5076. if (meth) {
  5077. imp = meth->imp;
  5078. goto done;
  5079. }
  5080. if (slowpath((curClass = curClass->superclass) == nil)) {
  5081. // No implementation found, and method resolver didn't help.
  5082. // Use forwarding.
  5083. imp = forward_imp;
  5084. break;
  5085. }
  5086. // Halt if there is a cycle in the superclass chain.
  5087. if (slowpath(--attempts == 0)) {
  5088. _objc_fatal("Memory corruption in class list.");
  5089. }
  5090. // Superclass cache.
  5091. imp = cache_getImp(curClass, sel);
  5092. if (slowpath(imp == forward_imp)) {
  5093. // Found a forward:: entry in a superclass.
  5094. // Stop searching, but don't cache yet; call method
  5095. // resolver for this class first.
  5096. break;
  5097. }
  5098. if (fastpath(imp)) {
  5099. // Found the method in a superclass. Cache it in this class.
  5100. goto done;
  5101. }
  5102. }
  5103. // No implementation found. Try method resolver once.
  5104. if (slowpath(behavior & LOOKUP_RESOLVER)) {
  5105. behavior ^= LOOKUP_RESOLVER;
  5106. return resolveMethod_locked(inst, sel, cls, behavior);
  5107. }
  5108. done:
  5109. log_and_fill_cache(cls, imp, sel, inst, curClass);
  5110. runtimeLock.unlock();
  5111. done_nolock:
  5112. if (slowpath((behavior & LOOKUP_NIL) && imp == forward_imp)) {
  5113. return nil;
  5114. }
  5115. return imp;
  5116. }
  5117. /***********************************************************************
  5118. * lookupMethodInClassAndLoadCache.
  5119. * Like lookUpImpOrForward, but does not search superclasses.
  5120. * Caches and returns objc_msgForward if the method is not found in the class.
  5121. **********************************************************************/
  5122. IMP lookupMethodInClassAndLoadCache(Class cls, SEL sel)
  5123. {
  5124. Method meth;
  5125. IMP imp;
  5126. // fixme this is incomplete - no resolver, +initialize -
  5127. // but it's only used for .cxx_construct/destruct so we don't care
  5128. ASSERT(sel == SEL_cxx_construct || sel == SEL_cxx_destruct);
  5129. // Search cache first.
  5130. imp = cache_getImp(cls, sel);
  5131. if (imp) return imp;
  5132. // Cache miss. Search method list.
  5133. mutex_locker_t lock(runtimeLock);
  5134. meth = getMethodNoSuper_nolock(cls, sel);
  5135. if (meth) {
  5136. // Hit in method list. Cache it.
  5137. cache_fill(cls, sel, meth->imp, nil);
  5138. return meth->imp;
  5139. } else {
  5140. // Miss in method list. Cache objc_msgForward.
  5141. cache_fill(cls, sel, _objc_msgForward_impcache, nil);
  5142. return _objc_msgForward_impcache;
  5143. }
  5144. }
  5145. /***********************************************************************
  5146. * class_getProperty
  5147. * fixme
  5148. * Locking: read-locks runtimeLock
  5149. **********************************************************************/
  5150. objc_property_t class_getProperty(Class cls, const char *name)
  5151. {
  5152. if (!cls || !name) return nil;
  5153. mutex_locker_t lock(runtimeLock);
  5154. checkIsKnownClass(cls);
  5155. ASSERT(cls->isRealized());
  5156. for ( ; cls; cls = cls->superclass) {
  5157. for (auto& prop : cls->data()->properties) {
  5158. if (0 == strcmp(name, prop.name)) {
  5159. return (objc_property_t)&prop;
  5160. }
  5161. }
  5162. }
  5163. return nil;
  5164. }
  5165. /***********************************************************************
  5166. * Locking: fixme
  5167. **********************************************************************/
  5168. Class gdb_class_getClass(Class cls)
  5169. {
  5170. const char *className = cls->mangledName();
  5171. if(!className || !strlen(className)) return Nil;
  5172. Class rCls = look_up_class(className, NO, NO);
  5173. return rCls;
  5174. }
  5175. Class gdb_object_getClass(id obj)
  5176. {
  5177. if (!obj) return nil;
  5178. return gdb_class_getClass(obj->getIsa());
  5179. }
  5180. /***********************************************************************
  5181. * Locking: write-locks runtimeLock
  5182. **********************************************************************/
  5183. void
  5184. objc_class::setInitialized()
  5185. {
  5186. Class metacls;
  5187. Class cls;
  5188. ASSERT(!isMetaClass());
  5189. cls = (Class)this;
  5190. metacls = cls->ISA();
  5191. mutex_locker_t lock(runtimeLock);
  5192. // Special cases:
  5193. // - NSObject AWZ class methods are default.
  5194. // - NSObject RR class and instance methods are default.
  5195. // - NSObject Core class and instance methods are default.
  5196. // adjustCustomFlagsForMethodChange() also knows these special cases.
  5197. // attachMethodLists() also knows these special cases.
  5198. objc::AWZScanner::scanInitializedClass(cls, metacls);
  5199. objc::RRScanner::scanInitializedClass(cls, metacls);
  5200. objc::CoreScanner::scanInitializedClass(cls, metacls);
  5201. // Update the +initialize flags.
  5202. // Do this last.
  5203. metacls->changeInfo(RW_INITIALIZED, RW_INITIALIZING);
  5204. }
  5205. void
  5206. objc_class::printInstancesRequireRawIsa(bool inherited)
  5207. {
  5208. ASSERT(PrintRawIsa);
  5209. ASSERT(instancesRequireRawIsa());
  5210. _objc_inform("RAW ISA: %s%s%s", nameForLogging(),
  5211. isMetaClass() ? " (meta)" : "",
  5212. inherited ? " (inherited)" : "");
  5213. }
  5214. /***********************************************************************
  5215. * Mark this class and all of its subclasses as requiring raw isa pointers
  5216. **********************************************************************/
  5217. void objc_class::setInstancesRequireRawIsaRecursively(bool inherited)
  5218. {
  5219. Class cls = (Class)this;
  5220. runtimeLock.assertLocked();
  5221. if (instancesRequireRawIsa()) return;
  5222. foreach_realized_class_and_subclass(cls, [=](Class c){
  5223. if (c->instancesRequireRawIsa()) {
  5224. return false;
  5225. }
  5226. c->setInstancesRequireRawIsa();
  5227. if (PrintRawIsa) c->printInstancesRequireRawIsa(inherited || c != cls);
  5228. return true;
  5229. });
  5230. }
  5231. /***********************************************************************
  5232. * Choose a class index.
  5233. * Set instancesRequireRawIsa if no more class indexes are available.
  5234. **********************************************************************/
  5235. void objc_class::chooseClassArrayIndex()
  5236. {
  5237. #if SUPPORT_INDEXED_ISA
  5238. Class cls = (Class)this;
  5239. runtimeLock.assertLocked();
  5240. if (objc_indexed_classes_count >= ISA_INDEX_COUNT) {
  5241. // No more indexes available.
  5242. ASSERT(cls->classArrayIndex() == 0);
  5243. cls->setInstancesRequireRawIsaRecursively(false/*not inherited*/);
  5244. return;
  5245. }
  5246. unsigned index = objc_indexed_classes_count++;
  5247. if (index == 0) index = objc_indexed_classes_count++; // index 0 is unused
  5248. classForIndex(index) = cls;
  5249. cls->setClassArrayIndex(index);
  5250. #endif
  5251. }
  5252. /***********************************************************************
  5253. * Update custom RR and AWZ when a method changes its IMP
  5254. **********************************************************************/
  5255. static void
  5256. adjustCustomFlagsForMethodChange(Class cls, method_t *meth)
  5257. {
  5258. objc::AWZScanner::scanChangedMethod(cls, meth);
  5259. objc::RRScanner::scanChangedMethod(cls, meth);
  5260. objc::CoreScanner::scanChangedMethod(cls, meth);
  5261. }
  5262. /***********************************************************************
  5263. * class_getIvarLayout
  5264. * Called by the garbage collector.
  5265. * The class must be nil or already realized.
  5266. * Locking: none
  5267. **********************************************************************/
  5268. const uint8_t *
  5269. class_getIvarLayout(Class cls)
  5270. {
  5271. if (cls) return cls->data()->ro->ivarLayout;
  5272. else return nil;
  5273. }
  5274. /***********************************************************************
  5275. * class_getWeakIvarLayout
  5276. * Called by the garbage collector.
  5277. * The class must be nil or already realized.
  5278. * Locking: none
  5279. **********************************************************************/
  5280. const uint8_t *
  5281. class_getWeakIvarLayout(Class cls)
  5282. {
  5283. if (cls) return cls->data()->ro->weakIvarLayout;
  5284. else return nil;
  5285. }
  5286. /***********************************************************************
  5287. * class_setIvarLayout
  5288. * Changes the class's ivar layout.
  5289. * nil layout means no unscanned ivars
  5290. * The class must be under construction.
  5291. * fixme: sanity-check layout vs instance size?
  5292. * fixme: sanity-check layout vs superclass?
  5293. * Locking: acquires runtimeLock
  5294. **********************************************************************/
  5295. void
  5296. class_setIvarLayout(Class cls, const uint8_t *layout)
  5297. {
  5298. if (!cls) return;
  5299. mutex_locker_t lock(runtimeLock);
  5300. checkIsKnownClass(cls);
  5301. // Can only change layout of in-construction classes.
  5302. // note: if modifications to post-construction classes were
  5303. // allowed, there would be a race below (us vs. concurrent object_setIvar)
  5304. if (!(cls->data()->flags & RW_CONSTRUCTING)) {
  5305. _objc_inform("*** Can't set ivar layout for already-registered "
  5306. "class '%s'", cls->nameForLogging());
  5307. return;
  5308. }
  5309. class_ro_t *ro_w = make_ro_writeable(cls->data());
  5310. try_free(ro_w->ivarLayout);
  5311. ro_w->ivarLayout = ustrdupMaybeNil(layout);
  5312. }
  5313. /***********************************************************************
  5314. * class_setWeakIvarLayout
  5315. * Changes the class's weak ivar layout.
  5316. * nil layout means no weak ivars
  5317. * The class must be under construction.
  5318. * fixme: sanity-check layout vs instance size?
  5319. * fixme: sanity-check layout vs superclass?
  5320. * Locking: acquires runtimeLock
  5321. **********************************************************************/
  5322. void
  5323. class_setWeakIvarLayout(Class cls, const uint8_t *layout)
  5324. {
  5325. if (!cls) return;
  5326. mutex_locker_t lock(runtimeLock);
  5327. checkIsKnownClass(cls);
  5328. // Can only change layout of in-construction classes.
  5329. // note: if modifications to post-construction classes were
  5330. // allowed, there would be a race below (us vs. concurrent object_setIvar)
  5331. if (!(cls->data()->flags & RW_CONSTRUCTING)) {
  5332. _objc_inform("*** Can't set weak ivar layout for already-registered "
  5333. "class '%s'", cls->nameForLogging());
  5334. return;
  5335. }
  5336. class_ro_t *ro_w = make_ro_writeable(cls->data());
  5337. try_free(ro_w->weakIvarLayout);
  5338. ro_w->weakIvarLayout = ustrdupMaybeNil(layout);
  5339. }
  5340. /***********************************************************************
  5341. * getIvar
  5342. * Look up an ivar by name.
  5343. * Locking: runtimeLock must be read- or write-locked by the caller.
  5344. **********************************************************************/
  5345. static ivar_t *getIvar(Class cls, const char *name)
  5346. {
  5347. runtimeLock.assertLocked();
  5348. const ivar_list_t *ivars;
  5349. ASSERT(cls->isRealized());
  5350. if ((ivars = cls->data()->ro->ivars)) {
  5351. for (auto& ivar : *ivars) {
  5352. if (!ivar.offset) continue; // anonymous bitfield
  5353. // ivar.name may be nil for anonymous bitfields etc.
  5354. if (ivar.name && 0 == strcmp(name, ivar.name)) {
  5355. return &ivar;
  5356. }
  5357. }
  5358. }
  5359. return nil;
  5360. }
  5361. /***********************************************************************
  5362. * _class_getClassForIvar
  5363. * Given a class and an ivar that is in it or one of its superclasses,
  5364. * find the actual class that defined the ivar.
  5365. **********************************************************************/
  5366. Class _class_getClassForIvar(Class cls, Ivar ivar)
  5367. {
  5368. mutex_locker_t lock(runtimeLock);
  5369. for ( ; cls; cls = cls->superclass) {
  5370. if (auto ivars = cls->data()->ro->ivars) {
  5371. if (ivars->containsIvar(ivar)) {
  5372. return cls;
  5373. }
  5374. }
  5375. }
  5376. return nil;
  5377. }
  5378. /***********************************************************************
  5379. * _class_getVariable
  5380. * fixme
  5381. * Locking: read-locks runtimeLock
  5382. **********************************************************************/
  5383. Ivar
  5384. _class_getVariable(Class cls, const char *name)
  5385. {
  5386. mutex_locker_t lock(runtimeLock);
  5387. for ( ; cls; cls = cls->superclass) {
  5388. ivar_t *ivar = getIvar(cls, name);
  5389. if (ivar) {
  5390. return ivar;
  5391. }
  5392. }
  5393. return nil;
  5394. }
  5395. /***********************************************************************
  5396. * class_conformsToProtocol
  5397. * fixme
  5398. * Locking: read-locks runtimeLock
  5399. **********************************************************************/
  5400. BOOL class_conformsToProtocol(Class cls, Protocol *proto_gen)
  5401. {
  5402. protocol_t *proto = newprotocol(proto_gen);
  5403. if (!cls) return NO;
  5404. if (!proto_gen) return NO;
  5405. mutex_locker_t lock(runtimeLock);
  5406. checkIsKnownClass(cls);
  5407. ASSERT(cls->isRealized());
  5408. for (const auto& proto_ref : cls->data()->protocols) {
  5409. protocol_t *p = remapProtocol(proto_ref);
  5410. if (p == proto || protocol_conformsToProtocol_nolock(p, proto)) {
  5411. return YES;
  5412. }
  5413. }
  5414. return NO;
  5415. }
  5416. /**********************************************************************
  5417. * addMethod
  5418. * fixme
  5419. * Locking: runtimeLock must be held by the caller
  5420. **********************************************************************/
  5421. static IMP
  5422. addMethod(Class cls, SEL name, IMP imp, const char *types, bool replace)
  5423. {
  5424. IMP result = nil;
  5425. runtimeLock.assertLocked();
  5426. checkIsKnownClass(cls);
  5427. ASSERT(types);
  5428. ASSERT(cls->isRealized());
  5429. method_t *m;
  5430. if ((m = getMethodNoSuper_nolock(cls, name))) {
  5431. // already exists
  5432. if (!replace) {
  5433. result = m->imp;
  5434. } else {
  5435. result = _method_setImplementation(cls, m, imp);
  5436. }
  5437. } else {
  5438. // fixme optimize
  5439. method_list_t *newlist;
  5440. newlist = (method_list_t *)calloc(sizeof(*newlist), 1);
  5441. newlist->entsizeAndFlags =
  5442. (uint32_t)sizeof(method_t) | fixed_up_method_list;
  5443. newlist->count = 1;
  5444. newlist->first.name = name;
  5445. newlist->first.types = strdupIfMutable(types);
  5446. newlist->first.imp = imp;
  5447. prepareMethodLists(cls, &newlist, 1, NO, NO);
  5448. cls->data()->methods.attachLists(&newlist, 1);
  5449. flushCaches(cls);
  5450. result = nil;
  5451. }
  5452. return result;
  5453. }
  5454. /**********************************************************************
  5455. * addMethods
  5456. * Add the given methods to a class in bulk.
  5457. * Returns the selectors which could not be added, when replace == NO and a
  5458. * method already exists. The returned selectors are NULL terminated and must be
  5459. * freed by the caller. They are NULL if no failures occurred.
  5460. * Locking: runtimeLock must be held by the caller
  5461. **********************************************************************/
  5462. static SEL *
  5463. addMethods(Class cls, const SEL *names, const IMP *imps, const char **types,
  5464. uint32_t count, bool replace, uint32_t *outFailedCount)
  5465. {
  5466. runtimeLock.assertLocked();
  5467. ASSERT(names);
  5468. ASSERT(imps);
  5469. ASSERT(types);
  5470. ASSERT(cls->isRealized());
  5471. method_list_t *newlist;
  5472. size_t newlistSize = method_list_t::byteSize(sizeof(method_t), count);
  5473. newlist = (method_list_t *)calloc(newlistSize, 1);
  5474. newlist->entsizeAndFlags =
  5475. (uint32_t)sizeof(method_t) | fixed_up_method_list;
  5476. newlist->count = 0;
  5477. method_t *newlistMethods = &newlist->first;
  5478. SEL *failedNames = nil;
  5479. uint32_t failedCount = 0;
  5480. for (uint32_t i = 0; i < count; i++) {
  5481. method_t *m;
  5482. if ((m = getMethodNoSuper_nolock(cls, names[i]))) {
  5483. // already exists
  5484. if (!replace) {
  5485. // report failure
  5486. if (failedNames == nil) {
  5487. // allocate an extra entry for a trailing NULL in case
  5488. // every method fails
  5489. failedNames = (SEL *)calloc(sizeof(*failedNames),
  5490. count + 1);
  5491. }
  5492. failedNames[failedCount] = m->name;
  5493. failedCount++;
  5494. } else {
  5495. _method_setImplementation(cls, m, imps[i]);
  5496. }
  5497. } else {
  5498. method_t *newmethod = &newlistMethods[newlist->count];
  5499. newmethod->name = names[i];
  5500. newmethod->types = strdupIfMutable(types[i]);
  5501. newmethod->imp = imps[i];
  5502. newlist->count++;
  5503. }
  5504. }
  5505. if (newlist->count > 0) {
  5506. // fixme resize newlist because it may have been over-allocated above.
  5507. // Note that realloc() alone doesn't work due to ptrauth.
  5508. method_t::SortBySELAddress sorter;
  5509. std::stable_sort(newlist->begin(), newlist->end(), sorter);
  5510. prepareMethodLists(cls, &newlist, 1, NO, NO);
  5511. cls->data()->methods.attachLists(&newlist, 1);
  5512. flushCaches(cls);
  5513. } else {
  5514. // Attaching the method list to the class consumes it. If we don't
  5515. // do that, we have to free the memory ourselves.
  5516. free(newlist);
  5517. }
  5518. if (outFailedCount) *outFailedCount = failedCount;
  5519. return failedNames;
  5520. }
  5521. BOOL
  5522. class_addMethod(Class cls, SEL name, IMP imp, const char *types)
  5523. {
  5524. if (!cls) return NO;
  5525. mutex_locker_t lock(runtimeLock);
  5526. return ! addMethod(cls, name, imp, types ?: "", NO);
  5527. }
  5528. IMP
  5529. class_replaceMethod(Class cls, SEL name, IMP imp, const char *types)
  5530. {
  5531. if (!cls) return nil;
  5532. mutex_locker_t lock(runtimeLock);
  5533. return addMethod(cls, name, imp, types ?: "", YES);
  5534. }
  5535. SEL *
  5536. class_addMethodsBulk(Class cls, const SEL *names, const IMP *imps,
  5537. const char **types, uint32_t count,
  5538. uint32_t *outFailedCount)
  5539. {
  5540. if (!cls) {
  5541. if (outFailedCount) *outFailedCount = count;
  5542. return (SEL *)memdup(names, count * sizeof(*names));
  5543. }
  5544. mutex_locker_t lock(runtimeLock);
  5545. return addMethods(cls, names, imps, types, count, NO, outFailedCount);
  5546. }
  5547. void
  5548. class_replaceMethodsBulk(Class cls, const SEL *names, const IMP *imps,
  5549. const char **types, uint32_t count)
  5550. {
  5551. if (!cls) return;
  5552. mutex_locker_t lock(runtimeLock);
  5553. addMethods(cls, names, imps, types, count, YES, nil);
  5554. }
  5555. /***********************************************************************
  5556. * class_addIvar
  5557. * Adds an ivar to a class.
  5558. * Locking: acquires runtimeLock
  5559. **********************************************************************/
  5560. BOOL
  5561. class_addIvar(Class cls, const char *name, size_t size,
  5562. uint8_t alignment, const char *type)
  5563. {
  5564. if (!cls) return NO;
  5565. if (!type) type = "";
  5566. if (name && 0 == strcmp(name, "")) name = nil;
  5567. mutex_locker_t lock(runtimeLock);
  5568. checkIsKnownClass(cls);
  5569. ASSERT(cls->isRealized());
  5570. // No class variables
  5571. if (cls->isMetaClass()) {
  5572. return NO;
  5573. }
  5574. // Can only add ivars to in-construction classes.
  5575. if (!(cls->data()->flags & RW_CONSTRUCTING)) {
  5576. return NO;
  5577. }
  5578. // Check for existing ivar with this name, unless it's anonymous.
  5579. // Check for too-big ivar.
  5580. // fixme check for superclass ivar too?
  5581. if ((name && getIvar(cls, name)) || size > UINT32_MAX) {
  5582. return NO;
  5583. }
  5584. class_ro_t *ro_w = make_ro_writeable(cls->data());
  5585. // fixme allocate less memory here
  5586. ivar_list_t *oldlist, *newlist;
  5587. if ((oldlist = (ivar_list_t *)cls->data()->ro->ivars)) {
  5588. size_t oldsize = oldlist->byteSize();
  5589. newlist = (ivar_list_t *)calloc(oldsize + oldlist->entsize(), 1);
  5590. memcpy(newlist, oldlist, oldsize);
  5591. free(oldlist);
  5592. } else {
  5593. newlist = (ivar_list_t *)calloc(sizeof(ivar_list_t), 1);
  5594. newlist->entsizeAndFlags = (uint32_t)sizeof(ivar_t);
  5595. }
  5596. uint32_t offset = cls->unalignedInstanceSize();
  5597. uint32_t alignMask = (1<<alignment)-1;
  5598. offset = (offset + alignMask) & ~alignMask;
  5599. ivar_t& ivar = newlist->get(newlist->count++);
  5600. #if __x86_64__
  5601. // Deliberately over-allocate the ivar offset variable.
  5602. // Use calloc() to clear all 64 bits. See the note in struct ivar_t.
  5603. ivar.offset = (int32_t *)(int64_t *)calloc(sizeof(int64_t), 1);
  5604. #else
  5605. ivar.offset = (int32_t *)malloc(sizeof(int32_t));
  5606. #endif
  5607. *ivar.offset = offset;
  5608. ivar.name = name ? strdupIfMutable(name) : nil;
  5609. ivar.type = strdupIfMutable(type);
  5610. ivar.alignment_raw = alignment;
  5611. ivar.size = (uint32_t)size;
  5612. ro_w->ivars = newlist;
  5613. cls->setInstanceSize((uint32_t)(offset + size));
  5614. // Ivar layout updated in registerClass.
  5615. return YES;
  5616. }
  5617. /***********************************************************************
  5618. * class_addProtocol
  5619. * Adds a protocol to a class.
  5620. * Locking: acquires runtimeLock
  5621. **********************************************************************/
  5622. BOOL class_addProtocol(Class cls, Protocol *protocol_gen)
  5623. {
  5624. protocol_t *protocol = newprotocol(protocol_gen);
  5625. if (!cls) return NO;
  5626. if (class_conformsToProtocol(cls, protocol_gen)) return NO;
  5627. mutex_locker_t lock(runtimeLock);
  5628. ASSERT(cls->isRealized());
  5629. // fixme optimize
  5630. protocol_list_t *protolist = (protocol_list_t *)
  5631. malloc(sizeof(protocol_list_t) + sizeof(protocol_t *));
  5632. protolist->count = 1;
  5633. protolist->list[0] = (protocol_ref_t)protocol;
  5634. cls->data()->protocols.attachLists(&protolist, 1);
  5635. // fixme metaclass?
  5636. return YES;
  5637. }
  5638. /***********************************************************************
  5639. * class_addProperty
  5640. * Adds a property to a class.
  5641. * Locking: acquires runtimeLock
  5642. **********************************************************************/
  5643. static bool
  5644. _class_addProperty(Class cls, const char *name,
  5645. const objc_property_attribute_t *attrs, unsigned int count,
  5646. bool replace)
  5647. {
  5648. if (!cls) return NO;
  5649. if (!name) return NO;
  5650. property_t *prop = class_getProperty(cls, name);
  5651. if (prop && !replace) {
  5652. // already exists, refuse to replace
  5653. return NO;
  5654. }
  5655. else if (prop) {
  5656. // replace existing
  5657. mutex_locker_t lock(runtimeLock);
  5658. try_free(prop->attributes);
  5659. prop->attributes = copyPropertyAttributeString(attrs, count);
  5660. return YES;
  5661. }
  5662. else {
  5663. mutex_locker_t lock(runtimeLock);
  5664. ASSERT(cls->isRealized());
  5665. property_list_t *proplist = (property_list_t *)
  5666. malloc(sizeof(*proplist));
  5667. proplist->count = 1;
  5668. proplist->entsizeAndFlags = sizeof(proplist->first);
  5669. proplist->first.name = strdupIfMutable(name);
  5670. proplist->first.attributes = copyPropertyAttributeString(attrs, count);
  5671. cls->data()->properties.attachLists(&proplist, 1);
  5672. return YES;
  5673. }
  5674. }
  5675. BOOL
  5676. class_addProperty(Class cls, const char *name,
  5677. const objc_property_attribute_t *attrs, unsigned int n)
  5678. {
  5679. return _class_addProperty(cls, name, attrs, n, NO);
  5680. }
  5681. void
  5682. class_replaceProperty(Class cls, const char *name,
  5683. const objc_property_attribute_t *attrs, unsigned int n)
  5684. {
  5685. _class_addProperty(cls, name, attrs, n, YES);
  5686. }
  5687. /***********************************************************************
  5688. * look_up_class
  5689. * Look up a class by name, and realize it.
  5690. * Locking: acquires runtimeLock
  5691. **********************************************************************/
  5692. static BOOL empty_getClass(const char *name, Class *outClass)
  5693. {
  5694. *outClass = nil;
  5695. return NO;
  5696. }
  5697. static ChainedHookFunction<objc_hook_getClass> GetClassHook{empty_getClass};
  5698. void objc_setHook_getClass(objc_hook_getClass newValue,
  5699. objc_hook_getClass *outOldValue)
  5700. {
  5701. GetClassHook.set(newValue, outOldValue);
  5702. }
  5703. Class
  5704. look_up_class(const char *name,
  5705. bool includeUnconnected __attribute__((unused)),
  5706. bool includeClassHandler __attribute__((unused)))
  5707. {
  5708. if (!name) return nil;
  5709. Class result;
  5710. bool unrealized;
  5711. {
  5712. runtimeLock.lock();
  5713. result = getClassExceptSomeSwift(name);
  5714. unrealized = result && !result->isRealized();
  5715. if (unrealized) {
  5716. result = realizeClassMaybeSwiftAndUnlock(result, runtimeLock);
  5717. // runtimeLock is now unlocked
  5718. } else {
  5719. runtimeLock.unlock();
  5720. }
  5721. }
  5722. if (!result) {
  5723. // Ask Swift about its un-instantiated classes.
  5724. // We use thread-local storage to prevent infinite recursion
  5725. // if the hook function provokes another lookup of the same name
  5726. // (for example, if the hook calls objc_allocateClassPair)
  5727. auto *tls = _objc_fetch_pthread_data(true);
  5728. // Stop if this thread is already looking up this name.
  5729. for (unsigned i = 0; i < tls->classNameLookupsUsed; i++) {
  5730. if (0 == strcmp(name, tls->classNameLookups[i])) {
  5731. return nil;
  5732. }
  5733. }
  5734. // Save this lookup in tls.
  5735. if (tls->classNameLookupsUsed == tls->classNameLookupsAllocated) {
  5736. tls->classNameLookupsAllocated =
  5737. (tls->classNameLookupsAllocated * 2 ?: 1);
  5738. size_t size = tls->classNameLookupsAllocated *
  5739. sizeof(tls->classNameLookups[0]);
  5740. tls->classNameLookups = (const char **)
  5741. realloc(tls->classNameLookups, size);
  5742. }
  5743. tls->classNameLookups[tls->classNameLookupsUsed++] = name;
  5744. // Call the hook.
  5745. Class swiftcls = nil;
  5746. if (GetClassHook.get()(name, &swiftcls)) {
  5747. ASSERT(swiftcls->isRealized());
  5748. result = swiftcls;
  5749. }
  5750. // Erase the name from tls.
  5751. unsigned slot = --tls->classNameLookupsUsed;
  5752. ASSERT(slot >= 0 && slot < tls->classNameLookupsAllocated);
  5753. ASSERT(name == tls->classNameLookups[slot]);
  5754. tls->classNameLookups[slot] = nil;
  5755. }
  5756. return result;
  5757. }
  5758. /***********************************************************************
  5759. * objc_duplicateClass
  5760. * fixme
  5761. * Locking: acquires runtimeLock
  5762. **********************************************************************/
  5763. Class
  5764. objc_duplicateClass(Class original, const char *name,
  5765. size_t extraBytes)
  5766. {
  5767. Class duplicate;
  5768. mutex_locker_t lock(runtimeLock);
  5769. checkIsKnownClass(original);
  5770. ASSERT(original->isRealized());
  5771. ASSERT(!original->isMetaClass());
  5772. duplicate = alloc_class_for_subclass(original, extraBytes);
  5773. duplicate->initClassIsa(original->ISA());
  5774. duplicate->superclass = original->superclass;
  5775. duplicate->cache.initializeToEmpty();
  5776. class_rw_t *rw = (class_rw_t *)calloc(sizeof(*original->data()), 1);
  5777. rw->flags = (original->data()->flags | RW_COPIED_RO | RW_REALIZING);
  5778. rw->version = original->data()->version;
  5779. rw->firstSubclass = nil;
  5780. rw->nextSiblingClass = nil;
  5781. duplicate->bits = original->bits;
  5782. duplicate->setData(rw);
  5783. rw->ro = original->data()->ro->duplicate();
  5784. *(char **)&rw->ro->name = strdupIfMutable(name);
  5785. rw->methods = original->data()->methods.duplicate();
  5786. // fixme dies when categories are added to the base
  5787. rw->properties = original->data()->properties;
  5788. rw->protocols = original->data()->protocols;
  5789. duplicate->chooseClassArrayIndex();
  5790. if (duplicate->superclass) {
  5791. addSubclass(duplicate->superclass, duplicate);
  5792. // duplicate->isa == original->isa so don't addSubclass() for it
  5793. } else {
  5794. addRootClass(duplicate);
  5795. }
  5796. // Don't methodize class - construction above is correct
  5797. addNamedClass(duplicate, duplicate->data()->ro->name);
  5798. addClassTableEntry(duplicate, /*addMeta=*/false);
  5799. if (PrintConnecting) {
  5800. _objc_inform("CLASS: realizing class '%s' (duplicate of %s) %p %p",
  5801. name, original->nameForLogging(),
  5802. (void*)duplicate, duplicate->data()->ro);
  5803. }
  5804. duplicate->clearInfo(RW_REALIZING);
  5805. return duplicate;
  5806. }
  5807. /***********************************************************************
  5808. * objc_initializeClassPair
  5809. * Locking: runtimeLock must be write-locked by the caller
  5810. **********************************************************************/
  5811. // &UnsetLayout is the default ivar layout during class construction
  5812. static const uint8_t UnsetLayout = 0;
  5813. static void objc_initializeClassPair_internal(Class superclass, const char *name, Class cls, Class meta)
  5814. {
  5815. runtimeLock.assertLocked();
  5816. class_ro_t *cls_ro_w, *meta_ro_w;
  5817. cls->setData((class_rw_t *)calloc(sizeof(class_rw_t), 1));
  5818. meta->setData((class_rw_t *)calloc(sizeof(class_rw_t), 1));
  5819. cls_ro_w = (class_ro_t *)calloc(sizeof(class_ro_t), 1);
  5820. meta_ro_w = (class_ro_t *)calloc(sizeof(class_ro_t), 1);
  5821. cls->data()->ro = cls_ro_w;
  5822. meta->data()->ro = meta_ro_w;
  5823. // Set basic info
  5824. cls->data()->flags = RW_CONSTRUCTING | RW_COPIED_RO | RW_REALIZED | RW_REALIZING;
  5825. meta->data()->flags = RW_CONSTRUCTING | RW_COPIED_RO | RW_REALIZED | RW_REALIZING;
  5826. cls->data()->version = 0;
  5827. meta->data()->version = 7;
  5828. cls_ro_w->flags = 0;
  5829. meta_ro_w->flags = RO_META;
  5830. if (!superclass) {
  5831. cls_ro_w->flags |= RO_ROOT;
  5832. meta_ro_w->flags |= RO_ROOT;
  5833. }
  5834. if (superclass) {
  5835. uint32_t flagsToCopy = RW_FORBIDS_ASSOCIATED_OBJECTS;
  5836. cls->data()->flags |= superclass->data()->flags & flagsToCopy;
  5837. cls_ro_w->instanceStart = superclass->unalignedInstanceSize();
  5838. meta_ro_w->instanceStart = superclass->ISA()->unalignedInstanceSize();
  5839. cls->setInstanceSize(cls_ro_w->instanceStart);
  5840. meta->setInstanceSize(meta_ro_w->instanceStart);
  5841. } else {
  5842. cls_ro_w->instanceStart = 0;
  5843. meta_ro_w->instanceStart = (uint32_t)sizeof(objc_class);
  5844. cls->setInstanceSize((uint32_t)sizeof(id)); // just an isa
  5845. meta->setInstanceSize(meta_ro_w->instanceStart);
  5846. }
  5847. cls_ro_w->name = strdupIfMutable(name);
  5848. meta_ro_w->name = strdupIfMutable(name);
  5849. cls_ro_w->ivarLayout = &UnsetLayout;
  5850. cls_ro_w->weakIvarLayout = &UnsetLayout;
  5851. meta->chooseClassArrayIndex();
  5852. cls->chooseClassArrayIndex();
  5853. // This absolutely needs to be done before addSubclass
  5854. // as initializeToEmpty() clobbers the FAST_CACHE bits
  5855. cls->cache.initializeToEmpty();
  5856. meta->cache.initializeToEmpty();
  5857. #if FAST_CACHE_META
  5858. meta->cache.setBit(FAST_CACHE_META);
  5859. #endif
  5860. meta->setInstancesRequireRawIsa();
  5861. // Connect to superclasses and metaclasses
  5862. cls->initClassIsa(meta);
  5863. if (superclass) {
  5864. meta->initClassIsa(superclass->ISA()->ISA());
  5865. cls->superclass = superclass;
  5866. meta->superclass = superclass->ISA();
  5867. addSubclass(superclass, cls);
  5868. addSubclass(superclass->ISA(), meta);
  5869. } else {
  5870. meta->initClassIsa(meta);
  5871. cls->superclass = Nil;
  5872. meta->superclass = cls;
  5873. addRootClass(cls);
  5874. addSubclass(cls, meta);
  5875. }
  5876. addClassTableEntry(cls);
  5877. }
  5878. /***********************************************************************
  5879. * verifySuperclass
  5880. * Sanity-check the superclass provided to
  5881. * objc_allocateClassPair, objc_initializeClassPair, or objc_readClassPair.
  5882. **********************************************************************/
  5883. bool
  5884. verifySuperclass(Class superclass, bool rootOK)
  5885. {
  5886. if (!superclass) {
  5887. // Superclass does not exist.
  5888. // If subclass may be a root class, this is OK.
  5889. // If subclass must not be a root class, this is bad.
  5890. return rootOK;
  5891. }
  5892. // Superclass must be realized.
  5893. if (! superclass->isRealized()) return false;
  5894. // Superclass must not be under construction.
  5895. if (superclass->data()->flags & RW_CONSTRUCTING) return false;
  5896. return true;
  5897. }
  5898. /***********************************************************************
  5899. * objc_initializeClassPair
  5900. **********************************************************************/
  5901. Class objc_initializeClassPair(Class superclass, const char *name, Class cls, Class meta)
  5902. {
  5903. // Fail if the class name is in use.
  5904. if (look_up_class(name, NO, NO)) return nil;
  5905. mutex_locker_t lock(runtimeLock);
  5906. // Fail if the class name is in use.
  5907. // Fail if the superclass isn't kosher.
  5908. if (getClassExceptSomeSwift(name) ||
  5909. !verifySuperclass(superclass, true/*rootOK*/))
  5910. {
  5911. return nil;
  5912. }
  5913. objc_initializeClassPair_internal(superclass, name, cls, meta);
  5914. return cls;
  5915. }
  5916. /***********************************************************************
  5917. * objc_allocateClassPair
  5918. * fixme
  5919. * Locking: acquires runtimeLock
  5920. **********************************************************************/
  5921. Class objc_allocateClassPair(Class superclass, const char *name,
  5922. size_t extraBytes)
  5923. {
  5924. Class cls, meta;
  5925. // Fail if the class name is in use.
  5926. if (look_up_class(name, NO, NO)) return nil;
  5927. mutex_locker_t lock(runtimeLock);
  5928. // Fail if the class name is in use.
  5929. // Fail if the superclass isn't kosher.
  5930. if (getClassExceptSomeSwift(name) ||
  5931. !verifySuperclass(superclass, true/*rootOK*/))
  5932. {
  5933. return nil;
  5934. }
  5935. // Allocate new classes.
  5936. cls = alloc_class_for_subclass(superclass, extraBytes);
  5937. meta = alloc_class_for_subclass(superclass, extraBytes);
  5938. // fixme mangle the name if it looks swift-y?
  5939. objc_initializeClassPair_internal(superclass, name, cls, meta);
  5940. return cls;
  5941. }
  5942. /***********************************************************************
  5943. * objc_registerClassPair
  5944. * fixme
  5945. * Locking: acquires runtimeLock
  5946. **********************************************************************/
  5947. void objc_registerClassPair(Class cls)
  5948. {
  5949. mutex_locker_t lock(runtimeLock);
  5950. checkIsKnownClass(cls);
  5951. if ((cls->data()->flags & RW_CONSTRUCTED) ||
  5952. (cls->ISA()->data()->flags & RW_CONSTRUCTED))
  5953. {
  5954. _objc_inform("objc_registerClassPair: class '%s' was already "
  5955. "registered!", cls->data()->ro->name);
  5956. return;
  5957. }
  5958. if (!(cls->data()->flags & RW_CONSTRUCTING) ||
  5959. !(cls->ISA()->data()->flags & RW_CONSTRUCTING))
  5960. {
  5961. _objc_inform("objc_registerClassPair: class '%s' was not "
  5962. "allocated with objc_allocateClassPair!",
  5963. cls->data()->ro->name);
  5964. return;
  5965. }
  5966. // Clear "under construction" bit, set "done constructing" bit
  5967. cls->ISA()->changeInfo(RW_CONSTRUCTED, RW_CONSTRUCTING | RW_REALIZING);
  5968. cls->changeInfo(RW_CONSTRUCTED, RW_CONSTRUCTING | RW_REALIZING);
  5969. // Add to named class table.
  5970. addNamedClass(cls, cls->data()->ro->name);
  5971. }
  5972. /***********************************************************************
  5973. * objc_readClassPair()
  5974. * Read a class and metaclass as written by a compiler.
  5975. * Assumes the class and metaclass are not referenced by other things
  5976. * that might need to be fixed up (such as categories and subclasses).
  5977. * Does not call +load.
  5978. * Returns the class pointer, or nil.
  5979. *
  5980. * Locking: runtimeLock acquired by map_images
  5981. **********************************************************************/
  5982. Class objc_readClassPair(Class bits, const struct objc_image_info *info)
  5983. {
  5984. mutex_locker_t lock(runtimeLock);
  5985. // No info bits are significant yet.
  5986. (void)info;
  5987. // Fail if the superclass isn't kosher.
  5988. bool rootOK = bits->data()->flags & RO_ROOT;
  5989. if (!verifySuperclass(bits->superclass, rootOK)){
  5990. return nil;
  5991. }
  5992. // Duplicate classes are allowed, just like they are for image loading.
  5993. // readClass will complain about the duplicate.
  5994. Class cls = readClass(bits, false/*bundle*/, false/*shared cache*/);
  5995. if (cls != bits) {
  5996. // This function isn't allowed to remap anything.
  5997. _objc_fatal("objc_readClassPair for class %s changed %p to %p",
  5998. cls->nameForLogging(), bits, cls);
  5999. }
  6000. // The only client of this function is old Swift.
  6001. // Stable Swift won't use it.
  6002. // fixme once Swift in the OS settles we can assert(!cls->isSwiftStable()).
  6003. cls = realizeClassWithoutSwift(cls, nil);
  6004. return cls;
  6005. }
  6006. /***********************************************************************
  6007. * detach_class
  6008. * Disconnect a class from other data structures.
  6009. * Exception: does not remove the class from the +load list
  6010. * Call this before free_class.
  6011. * Locking: runtimeLock must be held by the caller.
  6012. **********************************************************************/
  6013. static void detach_class(Class cls, bool isMeta)
  6014. {
  6015. runtimeLock.assertLocked();
  6016. // categories not yet attached to this class
  6017. objc::unattachedCategories.eraseClass(cls);
  6018. // superclass's subclass list
  6019. if (cls->isRealized()) {
  6020. Class supercls = cls->superclass;
  6021. if (supercls) {
  6022. removeSubclass(supercls, cls);
  6023. } else {
  6024. removeRootClass(cls);
  6025. }
  6026. }
  6027. // class tables and +load queue
  6028. if (!isMeta) {
  6029. removeNamedClass(cls, cls->mangledName());
  6030. }
  6031. objc::allocatedClasses.get().erase(cls);
  6032. }
  6033. /***********************************************************************
  6034. * free_class
  6035. * Frees a class's data structures.
  6036. * Call this after detach_class.
  6037. * Locking: runtimeLock must be held by the caller
  6038. **********************************************************************/
  6039. static void free_class(Class cls)
  6040. {
  6041. runtimeLock.assertLocked();
  6042. if (! cls->isRealized()) return;
  6043. auto rw = cls->data();
  6044. auto ro = rw->ro;
  6045. cache_delete(cls);
  6046. for (auto& meth : rw->methods) {
  6047. try_free(meth.types);
  6048. }
  6049. rw->methods.tryFree();
  6050. const ivar_list_t *ivars = ro->ivars;
  6051. if (ivars) {
  6052. for (auto& ivar : *ivars) {
  6053. try_free(ivar.offset);
  6054. try_free(ivar.name);
  6055. try_free(ivar.type);
  6056. }
  6057. try_free(ivars);
  6058. }
  6059. for (auto& prop : rw->properties) {
  6060. try_free(prop.name);
  6061. try_free(prop.attributes);
  6062. }
  6063. rw->properties.tryFree();
  6064. rw->protocols.tryFree();
  6065. try_free(ro->ivarLayout);
  6066. try_free(ro->weakIvarLayout);
  6067. try_free(ro->name);
  6068. try_free(ro);
  6069. try_free(rw);
  6070. try_free(cls);
  6071. }
  6072. void objc_disposeClassPair(Class cls)
  6073. {
  6074. mutex_locker_t lock(runtimeLock);
  6075. checkIsKnownClass(cls);
  6076. if (!(cls->data()->flags & (RW_CONSTRUCTED|RW_CONSTRUCTING)) ||
  6077. !(cls->ISA()->data()->flags & (RW_CONSTRUCTED|RW_CONSTRUCTING)))
  6078. {
  6079. // class not allocated with objc_allocateClassPair
  6080. // disposing still-unregistered class is OK!
  6081. _objc_inform("objc_disposeClassPair: class '%s' was not "
  6082. "allocated with objc_allocateClassPair!",
  6083. cls->data()->ro->name);
  6084. return;
  6085. }
  6086. if (cls->isMetaClass()) {
  6087. _objc_inform("objc_disposeClassPair: class '%s' is a metaclass, "
  6088. "not a class!", cls->data()->ro->name);
  6089. return;
  6090. }
  6091. // Shouldn't have any live subclasses.
  6092. if (cls->data()->firstSubclass) {
  6093. _objc_inform("objc_disposeClassPair: class '%s' still has subclasses, "
  6094. "including '%s'!", cls->data()->ro->name,
  6095. cls->data()->firstSubclass->nameForLogging());
  6096. }
  6097. if (cls->ISA()->data()->firstSubclass) {
  6098. _objc_inform("objc_disposeClassPair: class '%s' still has subclasses, "
  6099. "including '%s'!", cls->data()->ro->name,
  6100. cls->ISA()->data()->firstSubclass->nameForLogging());
  6101. }
  6102. // don't remove_class_from_loadable_list()
  6103. // - it's not there and we don't have the lock
  6104. detach_class(cls->ISA(), YES);
  6105. detach_class(cls, NO);
  6106. free_class(cls->ISA());
  6107. free_class(cls);
  6108. }
  6109. /***********************************************************************
  6110. * objc_constructInstance
  6111. * Creates an instance of `cls` at the location pointed to by `bytes`.
  6112. * `bytes` must point to at least class_getInstanceSize(cls) bytes of
  6113. * well-aligned zero-filled memory.
  6114. * The new object's isa is set. Any C++ constructors are called.
  6115. * Returns `bytes` if successful. Returns nil if `cls` or `bytes` is
  6116. * nil, or if C++ constructors fail.
  6117. * Note: class_createInstance() and class_createInstances() preflight this.
  6118. **********************************************************************/
  6119. id
  6120. objc_constructInstance(Class cls, void *bytes)
  6121. {
  6122. if (!cls || !bytes) return nil;
  6123. id obj = (id)bytes;
  6124. // Read class's info bits all at once for performance
  6125. bool hasCxxCtor = cls->hasCxxCtor();
  6126. bool hasCxxDtor = cls->hasCxxDtor();
  6127. bool fast = cls->canAllocNonpointer();
  6128. if (fast) {
  6129. obj->initInstanceIsa(cls, hasCxxDtor);
  6130. } else {
  6131. obj->initIsa(cls);
  6132. }
  6133. if (hasCxxCtor) {
  6134. return object_cxxConstructFromClass(obj, cls, OBJECT_CONSTRUCT_NONE);
  6135. } else {
  6136. return obj;
  6137. }
  6138. }
  6139. /***********************************************************************
  6140. * class_createInstance
  6141. * fixme
  6142. * Locking: none
  6143. *
  6144. * Note: this function has been carefully written so that the fastpath
  6145. * takes no branch.
  6146. **********************************************************************/
  6147. static ALWAYS_INLINE id
  6148. _class_createInstanceFromZone(Class cls, size_t extraBytes, void *zone,
  6149. int construct_flags = OBJECT_CONSTRUCT_NONE,
  6150. bool cxxConstruct = true,
  6151. size_t *outAllocatedSize = nil)
  6152. {
  6153. ASSERT(cls->isRealized());
  6154. // Read class's info bits all at once for performance
  6155. bool hasCxxCtor = cxxConstruct && cls->hasCxxCtor();
  6156. bool hasCxxDtor = cls->hasCxxDtor();
  6157. bool fast = cls->canAllocNonpointer();
  6158. size_t size;
  6159. size = cls->instanceSize(extraBytes);
  6160. if (outAllocatedSize) *outAllocatedSize = size;
  6161. id obj;
  6162. if (zone) {
  6163. obj = (id)malloc_zone_calloc((malloc_zone_t *)zone, 1, size);
  6164. } else {
  6165. obj = (id)calloc(1, size);
  6166. }
  6167. if (slowpath(!obj)) {
  6168. if (construct_flags & OBJECT_CONSTRUCT_CALL_BADALLOC) {
  6169. return _objc_callBadAllocHandler(cls);
  6170. }
  6171. return nil;
  6172. }
  6173. if (!zone && fast) {
  6174. obj->initInstanceIsa(cls, hasCxxDtor);
  6175. } else {
  6176. // Use raw pointer isa on the assumption that they might be
  6177. // doing something weird with the zone or RR.
  6178. obj->initIsa(cls);
  6179. }
  6180. if (fastpath(!hasCxxCtor)) {
  6181. return obj;
  6182. }
  6183. construct_flags |= OBJECT_CONSTRUCT_FREE_ONFAILURE;
  6184. return object_cxxConstructFromClass(obj, cls, construct_flags);
  6185. }
  6186. id
  6187. class_createInstance(Class cls, size_t extraBytes)
  6188. {
  6189. if (!cls) return nil;
  6190. return _class_createInstanceFromZone(cls, extraBytes, nil);
  6191. }
  6192. NEVER_INLINE
  6193. id
  6194. _objc_rootAllocWithZone(Class cls, malloc_zone_t *zone __unused)
  6195. {
  6196. // allocWithZone under __OBJC2__ ignores the zone parameter
  6197. return _class_createInstanceFromZone(cls, 0, nil,
  6198. OBJECT_CONSTRUCT_CALL_BADALLOC);
  6199. }
  6200. /***********************************************************************
  6201. * class_createInstances
  6202. * fixme
  6203. * Locking: none
  6204. **********************************************************************/
  6205. #if SUPPORT_NONPOINTER_ISA
  6206. #warning fixme optimize class_createInstances
  6207. #endif
  6208. unsigned
  6209. class_createInstances(Class cls, size_t extraBytes,
  6210. id *results, unsigned num_requested)
  6211. {
  6212. return _class_createInstancesFromZone(cls, extraBytes, nil,
  6213. results, num_requested);
  6214. }
  6215. /***********************************************************************
  6216. * object_copyFromZone
  6217. * fixme
  6218. * Locking: none
  6219. **********************************************************************/
  6220. static id
  6221. _object_copyFromZone(id oldObj, size_t extraBytes, void *zone)
  6222. {
  6223. if (!oldObj) return nil;
  6224. if (oldObj->isTaggedPointer()) return oldObj;
  6225. // fixme this doesn't handle C++ ivars correctly (#4619414)
  6226. Class cls = oldObj->ISA();
  6227. size_t size;
  6228. id obj = _class_createInstanceFromZone(cls, extraBytes, zone,
  6229. OBJECT_CONSTRUCT_NONE, false, &size);
  6230. if (!obj) return nil;
  6231. // Copy everything except the isa, which was already set above.
  6232. uint8_t *copyDst = (uint8_t *)obj + sizeof(Class);
  6233. uint8_t *copySrc = (uint8_t *)oldObj + sizeof(Class);
  6234. size_t copySize = size - sizeof(Class);
  6235. memmove(copyDst, copySrc, copySize);
  6236. fixupCopiedIvars(obj, oldObj);
  6237. return obj;
  6238. }
  6239. /***********************************************************************
  6240. * object_copy
  6241. * fixme
  6242. * Locking: none
  6243. **********************************************************************/
  6244. id
  6245. object_copy(id oldObj, size_t extraBytes)
  6246. {
  6247. return _object_copyFromZone(oldObj, extraBytes, malloc_default_zone());
  6248. }
  6249. #if SUPPORT_ZONES
  6250. /***********************************************************************
  6251. * class_createInstanceFromZone
  6252. * fixme
  6253. * Locking: none
  6254. **********************************************************************/
  6255. id
  6256. class_createInstanceFromZone(Class cls, size_t extraBytes, void *zone)
  6257. {
  6258. if (!cls) return nil;
  6259. return _class_createInstanceFromZone(cls, extraBytes, zone);
  6260. }
  6261. /***********************************************************************
  6262. * object_copyFromZone
  6263. * fixme
  6264. * Locking: none
  6265. **********************************************************************/
  6266. id
  6267. object_copyFromZone(id oldObj, size_t extraBytes, void *zone)
  6268. {
  6269. return _object_copyFromZone(oldObj, extraBytes, zone);
  6270. }
  6271. #endif
  6272. /***********************************************************************
  6273. * objc_destructInstance
  6274. * Destroys an instance without freeing memory.
  6275. * Calls C++ destructors.
  6276. * Calls ARC ivar cleanup.
  6277. * Removes associative references.
  6278. * Returns `obj`. Does nothing if `obj` is nil.
  6279. **********************************************************************/
  6280. void *objc_destructInstance(id obj)
  6281. {
  6282. if (obj) {
  6283. // Read all of the flags at once for performance.
  6284. bool cxx = obj->hasCxxDtor();
  6285. bool assoc = obj->hasAssociatedObjects();
  6286. // This order is important.
  6287. if (cxx) object_cxxDestruct(obj);
  6288. if (assoc) _object_remove_assocations(obj);
  6289. obj->clearDeallocating();
  6290. }
  6291. return obj;
  6292. }
  6293. /***********************************************************************
  6294. * object_dispose
  6295. * fixme
  6296. * Locking: none
  6297. **********************************************************************/
  6298. id
  6299. object_dispose(id obj)
  6300. {
  6301. if (!obj) return nil;
  6302. objc_destructInstance(obj);
  6303. free(obj);
  6304. return nil;
  6305. }
  6306. /***********************************************************************
  6307. * _objc_getFreedObjectClass
  6308. * fixme
  6309. * Locking: none
  6310. **********************************************************************/
  6311. Class _objc_getFreedObjectClass (void)
  6312. {
  6313. return nil;
  6314. }
  6315. /***********************************************************************
  6316. * Tagged pointer objects.
  6317. *
  6318. * Tagged pointer objects store the class and the object value in the
  6319. * object pointer; the "pointer" does not actually point to anything.
  6320. *
  6321. * Tagged pointer objects currently use this representation:
  6322. * (LSB)
  6323. * 1 bit set if tagged, clear if ordinary object pointer
  6324. * 3 bits tag index
  6325. * 60 bits payload
  6326. * (MSB)
  6327. * The tag index defines the object's class.
  6328. * The payload format is defined by the object's class.
  6329. *
  6330. * If the tag index is 0b111, the tagged pointer object uses an
  6331. * "extended" representation, allowing more classes but with smaller payloads:
  6332. * (LSB)
  6333. * 1 bit set if tagged, clear if ordinary object pointer
  6334. * 3 bits 0b111
  6335. * 8 bits extended tag index
  6336. * 52 bits payload
  6337. * (MSB)
  6338. *
  6339. * Some architectures reverse the MSB and LSB in these representations.
  6340. *
  6341. * This representation is subject to change. Representation-agnostic SPI is:
  6342. * objc-internal.h for class implementers.
  6343. * objc-gdb.h for debuggers.
  6344. **********************************************************************/
  6345. #if !SUPPORT_TAGGED_POINTERS
  6346. // These variables are always provided for debuggers.
  6347. uintptr_t objc_debug_taggedpointer_obfuscator = 0;
  6348. uintptr_t objc_debug_taggedpointer_mask = 0;
  6349. unsigned objc_debug_taggedpointer_slot_shift = 0;
  6350. uintptr_t objc_debug_taggedpointer_slot_mask = 0;
  6351. unsigned objc_debug_taggedpointer_payload_lshift = 0;
  6352. unsigned objc_debug_taggedpointer_payload_rshift = 0;
  6353. Class objc_debug_taggedpointer_classes[1] = { nil };
  6354. uintptr_t objc_debug_taggedpointer_ext_mask = 0;
  6355. unsigned objc_debug_taggedpointer_ext_slot_shift = 0;
  6356. uintptr_t objc_debug_taggedpointer_ext_slot_mask = 0;
  6357. unsigned objc_debug_taggedpointer_ext_payload_lshift = 0;
  6358. unsigned objc_debug_taggedpointer_ext_payload_rshift = 0;
  6359. Class objc_debug_taggedpointer_ext_classes[1] = { nil };
  6360. static void
  6361. disableTaggedPointers() { }
  6362. static void
  6363. initializeTaggedPointerObfuscator(void) { }
  6364. #else
  6365. // The "slot" used in the class table and given to the debugger
  6366. // includes the is-tagged bit. This makes objc_msgSend faster.
  6367. // The "ext" representation doesn't do that.
  6368. uintptr_t objc_debug_taggedpointer_obfuscator;
  6369. uintptr_t objc_debug_taggedpointer_mask = _OBJC_TAG_MASK;
  6370. unsigned objc_debug_taggedpointer_slot_shift = _OBJC_TAG_SLOT_SHIFT;
  6371. uintptr_t objc_debug_taggedpointer_slot_mask = _OBJC_TAG_SLOT_MASK;
  6372. unsigned objc_debug_taggedpointer_payload_lshift = _OBJC_TAG_PAYLOAD_LSHIFT;
  6373. unsigned objc_debug_taggedpointer_payload_rshift = _OBJC_TAG_PAYLOAD_RSHIFT;
  6374. // objc_debug_taggedpointer_classes is defined in objc-msg-*.s
  6375. uintptr_t objc_debug_taggedpointer_ext_mask = _OBJC_TAG_EXT_MASK;
  6376. unsigned objc_debug_taggedpointer_ext_slot_shift = _OBJC_TAG_EXT_SLOT_SHIFT;
  6377. uintptr_t objc_debug_taggedpointer_ext_slot_mask = _OBJC_TAG_EXT_SLOT_MASK;
  6378. unsigned objc_debug_taggedpointer_ext_payload_lshift = _OBJC_TAG_EXT_PAYLOAD_LSHIFT;
  6379. unsigned objc_debug_taggedpointer_ext_payload_rshift = _OBJC_TAG_EXT_PAYLOAD_RSHIFT;
  6380. // objc_debug_taggedpointer_ext_classes is defined in objc-msg-*.s
  6381. static void
  6382. disableTaggedPointers()
  6383. {
  6384. objc_debug_taggedpointer_mask = 0;
  6385. objc_debug_taggedpointer_slot_shift = 0;
  6386. objc_debug_taggedpointer_slot_mask = 0;
  6387. objc_debug_taggedpointer_payload_lshift = 0;
  6388. objc_debug_taggedpointer_payload_rshift = 0;
  6389. objc_debug_taggedpointer_ext_mask = 0;
  6390. objc_debug_taggedpointer_ext_slot_shift = 0;
  6391. objc_debug_taggedpointer_ext_slot_mask = 0;
  6392. objc_debug_taggedpointer_ext_payload_lshift = 0;
  6393. objc_debug_taggedpointer_ext_payload_rshift = 0;
  6394. }
  6395. // Returns a pointer to the class's storage in the tagged class arrays.
  6396. // Assumes the tag is a valid basic tag.
  6397. static Class *
  6398. classSlotForBasicTagIndex(objc_tag_index_t tag)
  6399. {
  6400. uintptr_t tagObfuscator = ((objc_debug_taggedpointer_obfuscator
  6401. >> _OBJC_TAG_INDEX_SHIFT)
  6402. & _OBJC_TAG_INDEX_MASK);
  6403. uintptr_t obfuscatedTag = tag ^ tagObfuscator;
  6404. // Array index in objc_tag_classes includes the tagged bit itself
  6405. #if SUPPORT_MSB_TAGGED_POINTERS
  6406. return &objc_tag_classes[0x8 | obfuscatedTag];
  6407. #else
  6408. return &objc_tag_classes[(obfuscatedTag << 1) | 1];
  6409. #endif
  6410. }
  6411. // Returns a pointer to the class's storage in the tagged class arrays,
  6412. // or nil if the tag is out of range.
  6413. static Class *
  6414. classSlotForTagIndex(objc_tag_index_t tag)
  6415. {
  6416. if (tag >= OBJC_TAG_First60BitPayload && tag <= OBJC_TAG_Last60BitPayload) {
  6417. return classSlotForBasicTagIndex(tag);
  6418. }
  6419. if (tag >= OBJC_TAG_First52BitPayload && tag <= OBJC_TAG_Last52BitPayload) {
  6420. int index = tag - OBJC_TAG_First52BitPayload;
  6421. uintptr_t tagObfuscator = ((objc_debug_taggedpointer_obfuscator
  6422. >> _OBJC_TAG_EXT_INDEX_SHIFT)
  6423. & _OBJC_TAG_EXT_INDEX_MASK);
  6424. return &objc_tag_ext_classes[index ^ tagObfuscator];
  6425. }
  6426. return nil;
  6427. }
  6428. /***********************************************************************
  6429. * initializeTaggedPointerObfuscator
  6430. * Initialize objc_debug_taggedpointer_obfuscator with randomness.
  6431. *
  6432. * The tagged pointer obfuscator is intended to make it more difficult
  6433. * for an attacker to construct a particular object as a tagged pointer,
  6434. * in the presence of a buffer overflow or other write control over some
  6435. * memory. The obfuscator is XORed with the tagged pointers when setting
  6436. * or retrieving payload values. They are filled with randomness on first
  6437. * use.
  6438. **********************************************************************/
  6439. static void
  6440. initializeTaggedPointerObfuscator(void)
  6441. {
  6442. if (sdkIsOlderThan(10_14, 12_0, 12_0, 5_0, 3_0) ||
  6443. // Set the obfuscator to zero for apps linked against older SDKs,
  6444. // in case they're relying on the tagged pointer representation.
  6445. DisableTaggedPointerObfuscation) {
  6446. objc_debug_taggedpointer_obfuscator = 0;
  6447. } else {
  6448. // Pull random data into the variable, then shift away all non-payload bits.
  6449. arc4random_buf(&objc_debug_taggedpointer_obfuscator,
  6450. sizeof(objc_debug_taggedpointer_obfuscator));
  6451. objc_debug_taggedpointer_obfuscator &= ~_OBJC_TAG_MASK;
  6452. }
  6453. }
  6454. /***********************************************************************
  6455. * _objc_registerTaggedPointerClass
  6456. * Set the class to use for the given tagged pointer index.
  6457. * Aborts if the tag is out of range, or if the tag is already
  6458. * used by some other class.
  6459. **********************************************************************/
  6460. void
  6461. _objc_registerTaggedPointerClass(objc_tag_index_t tag, Class cls)
  6462. {
  6463. if (objc_debug_taggedpointer_mask == 0) {
  6464. _objc_fatal("tagged pointers are disabled");
  6465. }
  6466. Class *slot = classSlotForTagIndex(tag);
  6467. if (!slot) {
  6468. _objc_fatal("tag index %u is invalid", (unsigned int)tag);
  6469. }
  6470. Class oldCls = *slot;
  6471. if (cls && oldCls && cls != oldCls) {
  6472. _objc_fatal("tag index %u used for two different classes "
  6473. "(was %p %s, now %p %s)", tag,
  6474. oldCls, oldCls->nameForLogging(),
  6475. cls, cls->nameForLogging());
  6476. }
  6477. *slot = cls;
  6478. // Store a placeholder class in the basic tag slot that is
  6479. // reserved for the extended tag space, if it isn't set already.
  6480. // Do this lazily when the first extended tag is registered so
  6481. // that old debuggers characterize bogus pointers correctly more often.
  6482. if (tag < OBJC_TAG_First60BitPayload || tag > OBJC_TAG_Last60BitPayload) {
  6483. Class *extSlot = classSlotForBasicTagIndex(OBJC_TAG_RESERVED_7);
  6484. if (*extSlot == nil) {
  6485. extern objc_class OBJC_CLASS_$___NSUnrecognizedTaggedPointer;
  6486. *extSlot = (Class)&OBJC_CLASS_$___NSUnrecognizedTaggedPointer;
  6487. }
  6488. }
  6489. }
  6490. /***********************************************************************
  6491. * _objc_getClassForTag
  6492. * Returns the class that is using the given tagged pointer tag.
  6493. * Returns nil if no class is using that tag or the tag is out of range.
  6494. **********************************************************************/
  6495. Class
  6496. _objc_getClassForTag(objc_tag_index_t tag)
  6497. {
  6498. Class *slot = classSlotForTagIndex(tag);
  6499. if (slot) return *slot;
  6500. else return nil;
  6501. }
  6502. #endif
  6503. #if SUPPORT_FIXUP
  6504. OBJC_EXTERN void objc_msgSend_fixup(void);
  6505. OBJC_EXTERN void objc_msgSendSuper2_fixup(void);
  6506. OBJC_EXTERN void objc_msgSend_stret_fixup(void);
  6507. OBJC_EXTERN void objc_msgSendSuper2_stret_fixup(void);
  6508. #if defined(__i386__) || defined(__x86_64__)
  6509. OBJC_EXTERN void objc_msgSend_fpret_fixup(void);
  6510. #endif
  6511. #if defined(__x86_64__)
  6512. OBJC_EXTERN void objc_msgSend_fp2ret_fixup(void);
  6513. #endif
  6514. OBJC_EXTERN void objc_msgSend_fixedup(void);
  6515. OBJC_EXTERN void objc_msgSendSuper2_fixedup(void);
  6516. OBJC_EXTERN void objc_msgSend_stret_fixedup(void);
  6517. OBJC_EXTERN void objc_msgSendSuper2_stret_fixedup(void);
  6518. #if defined(__i386__) || defined(__x86_64__)
  6519. OBJC_EXTERN void objc_msgSend_fpret_fixedup(void);
  6520. #endif
  6521. #if defined(__x86_64__)
  6522. OBJC_EXTERN void objc_msgSend_fp2ret_fixedup(void);
  6523. #endif
  6524. /***********************************************************************
  6525. * fixupMessageRef
  6526. * Repairs an old vtable dispatch call site.
  6527. * vtable dispatch itself is not supported.
  6528. **********************************************************************/
  6529. static void
  6530. fixupMessageRef(message_ref_t *msg)
  6531. {
  6532. msg->sel = sel_registerName((const char *)msg->sel);
  6533. if (msg->imp == &objc_msgSend_fixup) {
  6534. if (msg->sel == @selector(alloc)) {
  6535. msg->imp = (IMP)&objc_alloc;
  6536. } else if (msg->sel == @selector(allocWithZone:)) {
  6537. msg->imp = (IMP)&objc_allocWithZone;
  6538. } else if (msg->sel == @selector(retain)) {
  6539. msg->imp = (IMP)&objc_retain;
  6540. } else if (msg->sel == @selector(release)) {
  6541. msg->imp = (IMP)&objc_release;
  6542. } else if (msg->sel == @selector(autorelease)) {
  6543. msg->imp = (IMP)&objc_autorelease;
  6544. } else {
  6545. msg->imp = &objc_msgSend_fixedup;
  6546. }
  6547. }
  6548. else if (msg->imp == &objc_msgSendSuper2_fixup) {
  6549. msg->imp = &objc_msgSendSuper2_fixedup;
  6550. }
  6551. else if (msg->imp == &objc_msgSend_stret_fixup) {
  6552. msg->imp = &objc_msgSend_stret_fixedup;
  6553. }
  6554. else if (msg->imp == &objc_msgSendSuper2_stret_fixup) {
  6555. msg->imp = &objc_msgSendSuper2_stret_fixedup;
  6556. }
  6557. #if defined(__i386__) || defined(__x86_64__)
  6558. else if (msg->imp == &objc_msgSend_fpret_fixup) {
  6559. msg->imp = &objc_msgSend_fpret_fixedup;
  6560. }
  6561. #endif
  6562. #if defined(__x86_64__)
  6563. else if (msg->imp == &objc_msgSend_fp2ret_fixup) {
  6564. msg->imp = &objc_msgSend_fp2ret_fixedup;
  6565. }
  6566. #endif
  6567. }
  6568. // SUPPORT_FIXUP
  6569. #endif
  6570. // ProKit SPI
  6571. static Class setSuperclass(Class cls, Class newSuper)
  6572. {
  6573. Class oldSuper;
  6574. runtimeLock.assertLocked();
  6575. ASSERT(cls->isRealized());
  6576. ASSERT(newSuper->isRealized());
  6577. oldSuper = cls->superclass;
  6578. removeSubclass(oldSuper, cls);
  6579. removeSubclass(oldSuper->ISA(), cls->ISA());
  6580. cls->superclass = newSuper;
  6581. cls->ISA()->superclass = newSuper->ISA();
  6582. addSubclass(newSuper, cls);
  6583. addSubclass(newSuper->ISA(), cls->ISA());
  6584. // Flush subclass's method caches.
  6585. flushCaches(cls);
  6586. flushCaches(cls->ISA());
  6587. return oldSuper;
  6588. }
  6589. Class class_setSuperclass(Class cls, Class newSuper)
  6590. {
  6591. mutex_locker_t lock(runtimeLock);
  6592. return setSuperclass(cls, newSuper);
  6593. }
  6594. void runtime_init(void)
  6595. {
  6596. objc::unattachedCategories.init(32);
  6597. objc::allocatedClasses.init();
  6598. }
  6599. // __OBJC2__
  6600. #endif