objc-class-old.mm 79 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610
  1. /*
  2. * Copyright (c) 1999-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-class-old.m
  25. * Support for old-ABI classes, methods, and categories.
  26. **********************************************************************/
  27. #if !__OBJC2__
  28. #include "objc-private.h"
  29. #include "objc-runtime-old.h"
  30. #include "objc-file-old.h"
  31. #include "objc-cache-old.h"
  32. static Method _class_getMethod(Class cls, SEL sel);
  33. static Method _class_getMethodNoSuper(Class cls, SEL sel);
  34. static Method _class_getMethodNoSuper_nolock(Class cls, SEL sel);
  35. static Class _class_getNonMetaClass(Class cls, id obj);
  36. static void flush_caches(Class cls, bool flush_meta);
  37. // Freed objects have their isa set to point to this dummy class.
  38. // This avoids the need to check for Nil classes in the messenger.
  39. static const void* freedObjectClass[12] =
  40. {
  41. Nil, // isa
  42. Nil, // superclass
  43. "FREED(id)", // name
  44. 0, // version
  45. 0, // info
  46. 0, // instance_size
  47. nil, // ivars
  48. nil, // methodLists
  49. (Cache) &_objc_empty_cache, // cache
  50. nil, // protocols
  51. nil, // ivar_layout;
  52. nil // ext
  53. };
  54. /***********************************************************************
  55. * _class_getFreedObjectClass. Return a pointer to the dummy freed
  56. * object class. Freed objects get their isa pointers replaced with
  57. * a pointer to the freedObjectClass, so that we can catch usages of
  58. * the freed object.
  59. **********************************************************************/
  60. static Class _class_getFreedObjectClass(void)
  61. {
  62. return (Class)freedObjectClass;
  63. }
  64. /***********************************************************************
  65. * _objc_getFreedObjectClass. Return a pointer to the dummy freed
  66. * object class. Freed objects get their isa pointers replaced with
  67. * a pointer to the freedObjectClass, so that we can catch usages of
  68. * the freed object.
  69. **********************************************************************/
  70. Class _objc_getFreedObjectClass(void)
  71. {
  72. return _class_getFreedObjectClass();
  73. }
  74. static void allocateExt(Class cls)
  75. {
  76. if (! (cls->info & CLS_EXT)) {
  77. _objc_inform("class '%s' needs to be recompiled", cls->name);
  78. return;
  79. }
  80. if (!cls->ext) {
  81. uint32_t size = (uint32_t)sizeof(old_class_ext);
  82. cls->ext = (old_class_ext *)calloc(size, 1);
  83. cls->ext->size = size;
  84. }
  85. }
  86. static inline old_method *_findNamedMethodInList(old_method_list * mlist, const char *meth_name) {
  87. int i;
  88. if (!mlist) return nil;
  89. for (i = 0; i < mlist->method_count; i++) {
  90. old_method *m = &mlist->method_list[i];
  91. if (0 == strcmp((const char *)(m->method_name), meth_name)) {
  92. return m;
  93. }
  94. }
  95. return nil;
  96. }
  97. /***********************************************************************
  98. * Method list fixup markers.
  99. * mlist->obsolete == fixed_up_method_list marks method lists with real SELs
  100. * versus method lists with un-uniqued char*.
  101. * PREOPTIMIZED VERSION:
  102. * Fixed-up method lists get mlist->obsolete == OBJC_FIXED_UP
  103. * dyld shared cache sets this for method lists it preoptimizes.
  104. * UN-PREOPTIMIZED VERSION
  105. * Fixed-up method lists get mlist->obsolete == OBJC_FIXED_UP_outside_dyld
  106. * dyld shared cache uses OBJC_FIXED_UP, but those aren't trusted.
  107. **********************************************************************/
  108. #define OBJC_FIXED_UP ((void *)1771)
  109. #define OBJC_FIXED_UP_outside_dyld ((void *)1773)
  110. static void *fixed_up_method_list = OBJC_FIXED_UP;
  111. // sel_init() decided that selectors in the dyld shared cache are untrustworthy
  112. void disableSharedCacheOptimizations(void)
  113. {
  114. fixed_up_method_list = OBJC_FIXED_UP_outside_dyld;
  115. }
  116. /***********************************************************************
  117. * fixupSelectorsInMethodList
  118. * Uniques selectors in the given method list.
  119. * The given method list must be non-nil and not already fixed-up.
  120. * If the class was loaded from a bundle:
  121. * fixes up the given list in place with heap-allocated selector strings
  122. * If the class was not from a bundle:
  123. * allocates a copy of the method list, fixes up the copy, and returns
  124. * the copy. The given list is unmodified.
  125. *
  126. * If cls is already in use, methodListLock must be held by the caller.
  127. **********************************************************************/
  128. static old_method_list *fixupSelectorsInMethodList(Class cls, old_method_list *mlist)
  129. {
  130. int i;
  131. size_t size;
  132. old_method *method;
  133. old_method_list *old_mlist;
  134. if ( ! mlist ) return nil;
  135. if ( mlist->obsolete == fixed_up_method_list ) {
  136. // method list OK
  137. } else {
  138. bool isBundle = cls->info & CLS_FROM_BUNDLE;
  139. if (!isBundle) {
  140. old_mlist = mlist;
  141. size = sizeof(old_method_list) - sizeof(old_method) + old_mlist->method_count * sizeof(old_method);
  142. mlist = (old_method_list *)malloc(size);
  143. memmove(mlist, old_mlist, size);
  144. } else {
  145. // Mach-O bundles are fixed up in place.
  146. // This prevents leaks when a bundle is unloaded.
  147. }
  148. mutex_locker_t lock(selLock);
  149. for ( i = 0; i < mlist->method_count; i += 1 ) {
  150. method = &mlist->method_list[i];
  151. method->method_name =
  152. sel_registerNameNoLock((const char *)method->method_name, isBundle); // Always copy selector data from bundles.
  153. }
  154. mlist->obsolete = fixed_up_method_list;
  155. }
  156. return mlist;
  157. }
  158. /***********************************************************************
  159. * nextMethodList
  160. * Returns successive method lists from the given class.
  161. * Method lists are returned in method search order (i.e. highest-priority
  162. * implementations first).
  163. * All necessary method list fixups are performed, so the
  164. * returned method list is fully-constructed.
  165. *
  166. * If cls is already in use, methodListLock must be held by the caller.
  167. * For full thread-safety, methodListLock must be continuously held by the
  168. * caller across all calls to nextMethodList(). If the lock is released,
  169. * the bad results listed in class_nextMethodList() may occur.
  170. *
  171. * void *iterator = nil;
  172. * old_method_list *mlist;
  173. * mutex_locker_t lock(methodListLock);
  174. * while ((mlist = nextMethodList(cls, &iterator))) {
  175. * // do something with mlist
  176. * }
  177. **********************************************************************/
  178. static old_method_list *nextMethodList(Class cls,
  179. void **it)
  180. {
  181. uintptr_t index = *(uintptr_t *)it;
  182. old_method_list **resultp;
  183. if (index == 0) {
  184. // First call to nextMethodList.
  185. if (!cls->methodLists) {
  186. resultp = nil;
  187. } else if (cls->info & CLS_NO_METHOD_ARRAY) {
  188. resultp = (old_method_list **)&cls->methodLists;
  189. } else {
  190. resultp = &cls->methodLists[0];
  191. if (!*resultp || *resultp == END_OF_METHODS_LIST) {
  192. resultp = nil;
  193. }
  194. }
  195. } else {
  196. // Subsequent call to nextMethodList.
  197. if (!cls->methodLists) {
  198. resultp = nil;
  199. } else if (cls->info & CLS_NO_METHOD_ARRAY) {
  200. resultp = nil;
  201. } else {
  202. resultp = &cls->methodLists[index];
  203. if (!*resultp || *resultp == END_OF_METHODS_LIST) {
  204. resultp = nil;
  205. }
  206. }
  207. }
  208. // resultp now is nil, meaning there are no more method lists,
  209. // OR the address of the method list pointer to fix up and return.
  210. if (resultp) {
  211. if (*resultp) {
  212. *resultp = fixupSelectorsInMethodList(cls, *resultp);
  213. }
  214. *it = (void *)(index + 1);
  215. return *resultp;
  216. } else {
  217. *it = 0;
  218. return nil;
  219. }
  220. }
  221. /* These next three functions are the heart of ObjC method lookup.
  222. * If the class is currently in use, methodListLock must be held by the caller.
  223. */
  224. static inline old_method *_findMethodInList(old_method_list * mlist, SEL sel) {
  225. int i;
  226. if (!mlist) return nil;
  227. for (i = 0; i < mlist->method_count; i++) {
  228. old_method *m = &mlist->method_list[i];
  229. if (m->method_name == sel) {
  230. return m;
  231. }
  232. }
  233. return nil;
  234. }
  235. static inline old_method * _findMethodInClass(Class cls, SEL sel) __attribute__((always_inline));
  236. static inline old_method * _findMethodInClass(Class cls, SEL sel) {
  237. // Flattened version of nextMethodList(). The optimizer doesn't
  238. // do a good job with hoisting the conditionals out of the loop.
  239. // Conceptually, this looks like:
  240. // while ((mlist = nextMethodList(cls, &iterator))) {
  241. // old_method *m = _findMethodInList(mlist, sel);
  242. // if (m) return m;
  243. // }
  244. if (!cls->methodLists) {
  245. // No method lists.
  246. return nil;
  247. }
  248. else if (cls->info & CLS_NO_METHOD_ARRAY) {
  249. // One method list.
  250. old_method_list **mlistp;
  251. mlistp = (old_method_list **)&cls->methodLists;
  252. *mlistp = fixupSelectorsInMethodList(cls, *mlistp);
  253. return _findMethodInList(*mlistp, sel);
  254. }
  255. else {
  256. // Multiple method lists.
  257. old_method_list **mlistp;
  258. for (mlistp = cls->methodLists;
  259. *mlistp != nil && *mlistp != END_OF_METHODS_LIST;
  260. mlistp++)
  261. {
  262. old_method *m;
  263. *mlistp = fixupSelectorsInMethodList(cls, *mlistp);
  264. m = _findMethodInList(*mlistp, sel);
  265. if (m) return m;
  266. }
  267. return nil;
  268. }
  269. }
  270. static inline old_method * _getMethod(Class cls, SEL sel) {
  271. for (; cls; cls = cls->superclass) {
  272. old_method *m;
  273. m = _findMethodInClass(cls, sel);
  274. if (m) return m;
  275. }
  276. return nil;
  277. }
  278. // called by a debugging check in _objc_insertMethods
  279. IMP findIMPInClass(Class cls, SEL sel)
  280. {
  281. old_method *m = _findMethodInClass(cls, sel);
  282. if (m) return m->method_imp;
  283. else return nil;
  284. }
  285. /***********************************************************************
  286. * _freedHandler.
  287. **********************************************************************/
  288. static void _freedHandler(id obj, SEL sel)
  289. {
  290. __objc_error (obj, "message %s sent to freed object=%p",
  291. sel_getName(sel), (void*)obj);
  292. }
  293. /***********************************************************************
  294. * _class_resolveClassMethod
  295. * Call +resolveClassMethod, looking for a method to be added to class cls.
  296. * cls should be a metaclass.
  297. * Does not check if the method already exists.
  298. **********************************************************************/
  299. static void _class_resolveClassMethod(id inst, SEL sel, Class cls)
  300. {
  301. ASSERT(cls->isMetaClass());
  302. SEL resolve_sel = @selector(resolveClassMethod:);
  303. if (!lookUpImpOrNil(inst, resolve_sel, cls)) {
  304. // Resolver not implemented.
  305. return;
  306. }
  307. BOOL (*msg)(Class, SEL, SEL) = (typeof(msg))objc_msgSend;
  308. bool resolved = msg(_class_getNonMetaClass(cls, inst), resolve_sel, sel);
  309. // Cache the result (good or bad) so the resolver doesn't fire next time.
  310. // +resolveClassMethod adds to self->ISA() a.k.a. cls
  311. IMP imp = lookUpImpOrNil(inst, sel, cls);
  312. if (resolved && PrintResolving) {
  313. if (imp) {
  314. _objc_inform("RESOLVE: method %c[%s %s] "
  315. "dynamically resolved to %p",
  316. cls->isMetaClass() ? '+' : '-',
  317. cls->nameForLogging(), sel_getName(sel), imp);
  318. }
  319. else {
  320. // Method resolver didn't add anything?
  321. _objc_inform("RESOLVE: +[%s resolveClassMethod:%s] returned YES"
  322. ", but no new implementation of %c[%s %s] was found",
  323. cls->nameForLogging(), sel_getName(sel),
  324. cls->isMetaClass() ? '+' : '-',
  325. cls->nameForLogging(), sel_getName(sel));
  326. }
  327. }
  328. }
  329. /***********************************************************************
  330. * _class_resolveInstanceMethod
  331. * Call +resolveInstanceMethod, looking for a method to be added to class cls.
  332. * cls may be a metaclass or a non-meta class.
  333. * Does not check if the method already exists.
  334. **********************************************************************/
  335. static void _class_resolveInstanceMethod(id inst, SEL sel, Class cls)
  336. {
  337. SEL resolve_sel = @selector(resolveInstanceMethod:);
  338. if (! lookUpImpOrNil(cls, resolve_sel, cls->ISA())) {
  339. // Resolver not implemented.
  340. return;
  341. }
  342. BOOL (*msg)(Class, SEL, SEL) = (typeof(msg))objc_msgSend;
  343. bool resolved = msg(cls, resolve_sel, sel);
  344. // Cache the result (good or bad) so the resolver doesn't fire next time.
  345. // +resolveInstanceMethod adds to self a.k.a. cls
  346. IMP imp = lookUpImpOrNil(inst, sel, cls);
  347. if (resolved && PrintResolving) {
  348. if (imp) {
  349. _objc_inform("RESOLVE: method %c[%s %s] "
  350. "dynamically resolved to %p",
  351. cls->isMetaClass() ? '+' : '-',
  352. cls->nameForLogging(), sel_getName(sel), imp);
  353. }
  354. else {
  355. // Method resolver didn't add anything?
  356. _objc_inform("RESOLVE: +[%s resolveInstanceMethod:%s] returned YES"
  357. ", but no new implementation of %c[%s %s] was found",
  358. cls->nameForLogging(), sel_getName(sel),
  359. cls->isMetaClass() ? '+' : '-',
  360. cls->nameForLogging(), sel_getName(sel));
  361. }
  362. }
  363. }
  364. /***********************************************************************
  365. * _class_resolveMethod
  366. * Call +resolveClassMethod or +resolveInstanceMethod.
  367. * Returns nothing; any result would be potentially out-of-date already.
  368. * Does not check if the method already exists.
  369. **********************************************************************/
  370. static void
  371. _class_resolveMethod(id inst, SEL sel, Class cls)
  372. {
  373. if (! cls->isMetaClass()) {
  374. // try [cls resolveInstanceMethod:sel]
  375. _class_resolveInstanceMethod(inst, sel, cls);
  376. }
  377. else {
  378. // try [nonMetaClass resolveClassMethod:sel]
  379. // and [cls resolveInstanceMethod:sel]
  380. _class_resolveClassMethod(inst, sel, cls);
  381. if (!lookUpImpOrNil(inst, sel, cls)) {
  382. _class_resolveInstanceMethod(inst, sel, cls);
  383. }
  384. }
  385. }
  386. /***********************************************************************
  387. * log_and_fill_cache
  388. * Log this method call. If the logger permits it, fill the method cache.
  389. * cls is the method whose cache should be filled.
  390. * implementer is the class that owns the implementation in question.
  391. **********************************************************************/
  392. static void
  393. log_and_fill_cache(Class cls, Class implementer, Method meth, SEL sel)
  394. {
  395. #if SUPPORT_MESSAGE_LOGGING
  396. if (objcMsgLogEnabled) {
  397. bool cacheIt = logMessageSend(implementer->isMetaClass(),
  398. cls->nameForLogging(),
  399. implementer->nameForLogging(),
  400. sel);
  401. if (!cacheIt) return;
  402. }
  403. #endif
  404. _cache_fill (cls, meth, sel);
  405. }
  406. /***********************************************************************
  407. * lookUpImpOrForward.
  408. * The standard IMP lookup.
  409. * Without LOOKUP_INITIALIZE: tries to avoid +initialize (but sometimes fails)
  410. * Without LOOKUP_CACHE: skips optimistic unlocked lookup (but uses cache elsewhere)
  411. * Most callers should use LOOKUP_INITIALIZE and LOOKUP_CACHE
  412. * inst is an instance of cls or a subclass thereof, or nil if none is known.
  413. * If cls is an un-initialized metaclass then a non-nil inst is faster.
  414. * May return _objc_msgForward_impcache. IMPs destined for external use
  415. * must be converted to _objc_msgForward or _objc_msgForward_stret.
  416. * If you don't want forwarding at all, use LOOKUP_NIL.
  417. **********************************************************************/
  418. IMP lookUpImpOrForward(id inst, SEL sel, Class cls, int behavior)
  419. {
  420. Class curClass;
  421. IMP methodPC = nil;
  422. Method meth;
  423. bool triedResolver = NO;
  424. methodListLock.assertUnlocked();
  425. // Optimistic cache lookup
  426. if (behavior & LOOKUP_CACHE) {
  427. methodPC = _cache_getImp(cls, sel);
  428. if (methodPC) goto out_nolock;
  429. }
  430. // Check for freed class
  431. if (cls == _class_getFreedObjectClass())
  432. return (IMP) _freedHandler;
  433. // Check for +initialize
  434. if ((behavior & LOOKUP_INITIALIZE) && !cls->isInitialized()) {
  435. initializeNonMetaClass (_class_getNonMetaClass(cls, inst));
  436. // If sel == initialize, initializeNonMetaClass will send +initialize
  437. // and then the messenger will send +initialize again after this
  438. // procedure finishes. Of course, if this is not being called
  439. // from the messenger then it won't happen. 2778172
  440. }
  441. // The lock is held to make method-lookup + cache-fill atomic
  442. // with respect to method addition. Otherwise, a category could
  443. // be added but ignored indefinitely because the cache was re-filled
  444. // with the old value after the cache flush on behalf of the category.
  445. retry:
  446. methodListLock.lock();
  447. // Try this class's cache.
  448. methodPC = _cache_getImp(cls, sel);
  449. if (methodPC) goto done;
  450. // Try this class's method lists.
  451. meth = _class_getMethodNoSuper_nolock(cls, sel);
  452. if (meth) {
  453. log_and_fill_cache(cls, cls, meth, sel);
  454. methodPC = method_getImplementation(meth);
  455. goto done;
  456. }
  457. // Try superclass caches and method lists.
  458. curClass = cls;
  459. while ((curClass = curClass->superclass)) {
  460. // Superclass cache.
  461. meth = _cache_getMethod(curClass, sel, _objc_msgForward_impcache);
  462. if (meth) {
  463. if (meth != (Method)1) {
  464. // Found the method in a superclass. Cache it in this class.
  465. log_and_fill_cache(cls, curClass, meth, sel);
  466. methodPC = method_getImplementation(meth);
  467. goto done;
  468. }
  469. else {
  470. // Found a forward:: entry in a superclass.
  471. // Stop searching, but don't cache yet; call method
  472. // resolver for this class first.
  473. break;
  474. }
  475. }
  476. // Superclass method list.
  477. meth = _class_getMethodNoSuper_nolock(curClass, sel);
  478. if (meth) {
  479. log_and_fill_cache(cls, curClass, meth, sel);
  480. methodPC = method_getImplementation(meth);
  481. goto done;
  482. }
  483. }
  484. // No implementation found. Try method resolver once.
  485. if ((behavior & LOOKUP_RESOLVER) && !triedResolver) {
  486. methodListLock.unlock();
  487. _class_resolveMethod(cls, sel, inst);
  488. triedResolver = YES;
  489. goto retry;
  490. }
  491. // No implementation found, and method resolver didn't help.
  492. // Use forwarding.
  493. _cache_addForwardEntry(cls, sel);
  494. methodPC = _objc_msgForward_impcache;
  495. done:
  496. methodListLock.unlock();
  497. out_nolock:
  498. if ((behavior & LOOKUP_NIL) && methodPC == (IMP)_objc_msgForward_impcache) {
  499. return nil;
  500. }
  501. return methodPC;
  502. }
  503. /***********************************************************************
  504. * lookupMethodInClassAndLoadCache.
  505. * Like _class_lookupMethodAndLoadCache, but does not search superclasses.
  506. * Caches and returns objc_msgForward if the method is not found in the class.
  507. **********************************************************************/
  508. IMP lookupMethodInClassAndLoadCache(Class cls, SEL sel)
  509. {
  510. Method meth;
  511. IMP imp;
  512. // fixme this still has the method list vs method cache race
  513. // because it doesn't hold a lock across lookup+cache_fill,
  514. // but it's only used for .cxx_construct/destruct and we assume
  515. // categories don't change them.
  516. // Search cache first.
  517. imp = _cache_getImp(cls, sel);
  518. if (imp) return imp;
  519. // Cache miss. Search method list.
  520. meth = _class_getMethodNoSuper(cls, sel);
  521. if (meth) {
  522. // Hit in method list. Cache it.
  523. _cache_fill(cls, meth, sel);
  524. return method_getImplementation(meth);
  525. } else {
  526. // Miss in method list. Cache objc_msgForward.
  527. _cache_addForwardEntry(cls, sel);
  528. return _objc_msgForward_impcache;
  529. }
  530. }
  531. /***********************************************************************
  532. * _class_getClassForIvar
  533. * Given a class and an ivar that is in it or one of its superclasses,
  534. * find the actual class that defined the ivar.
  535. **********************************************************************/
  536. Class _class_getClassForIvar(Class cls, Ivar ivar)
  537. {
  538. for ( ; cls; cls = cls->superclass) {
  539. if (auto ivars = cls->ivars) {
  540. if (ivar >= &ivars->ivar_list[0] &&
  541. ivar < &ivars->ivar_list[ivars->ivar_count])
  542. {
  543. return cls;
  544. }
  545. }
  546. }
  547. return nil;
  548. }
  549. /***********************************************************************
  550. * class_getVariable. Return the named instance variable.
  551. **********************************************************************/
  552. Ivar _class_getVariable(Class cls, const char *name)
  553. {
  554. for (; cls != Nil; cls = cls->superclass) {
  555. int i;
  556. // Skip class having no ivars
  557. if (!cls->ivars) continue;
  558. for (i = 0; i < cls->ivars->ivar_count; i++) {
  559. // Check this ivar's name. Be careful because the
  560. // compiler generates ivar entries with nil ivar_name
  561. // (e.g. for anonymous bit fields).
  562. old_ivar *ivar = &cls->ivars->ivar_list[i];
  563. if (ivar->ivar_name && 0 == strcmp(name, ivar->ivar_name)) {
  564. return (Ivar)ivar;
  565. }
  566. }
  567. }
  568. // Not found
  569. return nil;
  570. }
  571. old_property *
  572. property_list_nth(const old_property_list *plist, uint32_t i)
  573. {
  574. return (old_property *)(i*plist->entsize + (char *)&plist->first);
  575. }
  576. old_property **
  577. copyPropertyList(old_property_list *plist, unsigned int *outCount)
  578. {
  579. old_property **result = nil;
  580. unsigned int count = 0;
  581. if (plist) {
  582. count = plist->count;
  583. }
  584. if (count > 0) {
  585. unsigned int i;
  586. result = (old_property **)malloc((count+1) * sizeof(old_property *));
  587. for (i = 0; i < count; i++) {
  588. result[i] = property_list_nth(plist, i);
  589. }
  590. result[i] = nil;
  591. }
  592. if (outCount) *outCount = count;
  593. return result;
  594. }
  595. static old_property_list *
  596. nextPropertyList(Class cls, uintptr_t *indexp)
  597. {
  598. old_property_list *result = nil;
  599. classLock.assertLocked();
  600. if (! ((cls->info & CLS_EXT) && cls->ext)) {
  601. // No class ext
  602. result = nil;
  603. } else if (!cls->ext->propertyLists) {
  604. // No property lists
  605. result = nil;
  606. } else if (cls->info & CLS_NO_PROPERTY_ARRAY) {
  607. // Only one property list
  608. if (*indexp == 0) {
  609. result = (old_property_list *)cls->ext->propertyLists;
  610. } else {
  611. result = nil;
  612. }
  613. } else {
  614. // More than one property list
  615. result = cls->ext->propertyLists[*indexp];
  616. }
  617. if (result) {
  618. ++*indexp;
  619. return result;
  620. } else {
  621. *indexp = 0;
  622. return nil;
  623. }
  624. }
  625. /***********************************************************************
  626. * class_getIvarLayout
  627. * nil means all-scanned. "" means non-scanned.
  628. **********************************************************************/
  629. const uint8_t *
  630. class_getIvarLayout(Class cls)
  631. {
  632. if (cls && (cls->info & CLS_EXT)) {
  633. return cls->ivar_layout;
  634. } else {
  635. return nil; // conservative scan
  636. }
  637. }
  638. /***********************************************************************
  639. * class_getWeakIvarLayout
  640. * nil means no weak ivars.
  641. **********************************************************************/
  642. const uint8_t *
  643. class_getWeakIvarLayout(Class cls)
  644. {
  645. if (cls && (cls->info & CLS_EXT) && cls->ext) {
  646. return cls->ext->weak_ivar_layout;
  647. } else {
  648. return nil; // no weak ivars
  649. }
  650. }
  651. /***********************************************************************
  652. * class_setIvarLayout
  653. * nil means all-scanned. "" means non-scanned.
  654. **********************************************************************/
  655. void class_setIvarLayout(Class cls, const uint8_t *layout)
  656. {
  657. if (!cls) return;
  658. if (! (cls->info & CLS_EXT)) {
  659. _objc_inform("class '%s' needs to be recompiled", cls->name);
  660. return;
  661. }
  662. // fixme leak
  663. cls->ivar_layout = ustrdupMaybeNil(layout);
  664. }
  665. /***********************************************************************
  666. * class_setWeakIvarLayout
  667. * nil means no weak ivars.
  668. **********************************************************************/
  669. void class_setWeakIvarLayout(Class cls, const uint8_t *layout)
  670. {
  671. if (!cls) return;
  672. mutex_locker_t lock(classLock);
  673. allocateExt(cls);
  674. // fixme leak
  675. cls->ext->weak_ivar_layout = ustrdupMaybeNil(layout);
  676. }
  677. /***********************************************************************
  678. * class_setVersion. Record the specified version with the class.
  679. **********************************************************************/
  680. void class_setVersion(Class cls, int version)
  681. {
  682. if (!cls) return;
  683. cls->version = version;
  684. }
  685. /***********************************************************************
  686. * class_getVersion. Return the version recorded with the class.
  687. **********************************************************************/
  688. int class_getVersion(Class cls)
  689. {
  690. if (!cls) return 0;
  691. return (int)cls->version;
  692. }
  693. /***********************************************************************
  694. * class_getName.
  695. **********************************************************************/
  696. const char *class_getName(Class cls)
  697. {
  698. if (!cls) return "nil";
  699. else return cls->demangledName();
  700. }
  701. /***********************************************************************
  702. * _class_getNonMetaClass.
  703. * Return the ordinary class for this class or metaclass.
  704. * Used by +initialize.
  705. **********************************************************************/
  706. static Class _class_getNonMetaClass(Class cls, id obj)
  707. {
  708. // fixme ick
  709. if (cls->isMetaClass()) {
  710. if (cls->info & CLS_CONSTRUCTING) {
  711. // Class is under construction and isn't in the class_hash,
  712. // so objc_getClass doesn't work.
  713. cls = obj; // fixme this may be nil in some paths
  714. }
  715. else if (strncmp(cls->name, "_%", 2) == 0) {
  716. // Posee's meta's name is smashed and isn't in the class_hash,
  717. // so objc_getClass doesn't work.
  718. const char *baseName = strchr(cls->name, '%'); // get posee's real name
  719. cls = objc_getClass(baseName);
  720. }
  721. else {
  722. cls = objc_getClass(cls->name);
  723. }
  724. ASSERT(cls);
  725. }
  726. return cls;
  727. }
  728. Class class_initialize(Class cls, id inst) {
  729. if (!cls->isInitialized()) {
  730. initializeNonMetaClass (_class_getNonMetaClass(cls, inst));
  731. }
  732. return cls;
  733. }
  734. Cache _class_getCache(Class cls)
  735. {
  736. return cls->cache;
  737. }
  738. void _class_setCache(Class cls, Cache cache)
  739. {
  740. cls->cache = cache;
  741. }
  742. const char *_category_getName(Category cat)
  743. {
  744. return oldcategory(cat)->category_name;
  745. }
  746. const char *_category_getClassName(Category cat)
  747. {
  748. return oldcategory(cat)->class_name;
  749. }
  750. Class _category_getClass(Category cat)
  751. {
  752. return objc_getClass(oldcategory(cat)->class_name);
  753. }
  754. IMP _category_getLoadMethod(Category cat)
  755. {
  756. old_method_list *mlist = oldcategory(cat)->class_methods;
  757. if (mlist) {
  758. return lookupNamedMethodInMethodList(mlist, "load");
  759. } else {
  760. return nil;
  761. }
  762. }
  763. /***********************************************************************
  764. * class_nextMethodList.
  765. * External version of nextMethodList().
  766. *
  767. * This function is not fully thread-safe. A series of calls to
  768. * class_nextMethodList() may fail if methods are added to or removed
  769. * from the class between calls.
  770. * If methods are added between calls to class_nextMethodList(), it may
  771. * return previously-returned method lists again, and may fail to return
  772. * newly-added lists.
  773. * If methods are removed between calls to class_nextMethodList(), it may
  774. * omit surviving method lists or simply crash.
  775. **********************************************************************/
  776. struct objc_method_list *class_nextMethodList(Class cls, void **it)
  777. {
  778. OBJC_WARN_DEPRECATED;
  779. mutex_locker_t lock(methodListLock);
  780. return (struct objc_method_list *) nextMethodList(cls, it);
  781. }
  782. /***********************************************************************
  783. * class_addMethods.
  784. *
  785. * Formerly class_addInstanceMethods ()
  786. **********************************************************************/
  787. void class_addMethods(Class cls, struct objc_method_list *meths)
  788. {
  789. OBJC_WARN_DEPRECATED;
  790. // Add the methods.
  791. {
  792. mutex_locker_t lock(methodListLock);
  793. _objc_insertMethods(cls, (old_method_list *)meths, nil);
  794. }
  795. // Must flush when dynamically adding methods. No need to flush
  796. // all the class method caches. If cls is a meta class, though,
  797. // this will still flush it and any of its sub-meta classes.
  798. flush_caches (cls, NO);
  799. }
  800. /***********************************************************************
  801. * class_removeMethods.
  802. **********************************************************************/
  803. void class_removeMethods(Class cls, struct objc_method_list *meths)
  804. {
  805. OBJC_WARN_DEPRECATED;
  806. // Remove the methods
  807. {
  808. mutex_locker_t lock(methodListLock);
  809. _objc_removeMethods(cls, (old_method_list *)meths);
  810. }
  811. // Must flush when dynamically removing methods. No need to flush
  812. // all the class method caches. If cls is a meta class, though,
  813. // this will still flush it and any of its sub-meta classes.
  814. flush_caches (cls, NO);
  815. }
  816. /***********************************************************************
  817. * lookupNamedMethodInMethodList
  818. * Only called to find +load/-.cxx_construct/-.cxx_destruct methods,
  819. * without fixing up the entire method list.
  820. * The class is not yet in use, so methodListLock is not taken.
  821. **********************************************************************/
  822. IMP lookupNamedMethodInMethodList(old_method_list *mlist, const char *meth_name)
  823. {
  824. old_method *m;
  825. m = meth_name ? _findNamedMethodInList(mlist, meth_name) : nil;
  826. return (m ? m->method_imp : nil);
  827. }
  828. static Method _class_getMethod(Class cls, SEL sel)
  829. {
  830. mutex_locker_t lock(methodListLock);
  831. return (Method)_getMethod(cls, sel);
  832. }
  833. static Method _class_getMethodNoSuper(Class cls, SEL sel)
  834. {
  835. mutex_locker_t lock(methodListLock);
  836. return (Method)_findMethodInClass(cls, sel);
  837. }
  838. static Method _class_getMethodNoSuper_nolock(Class cls, SEL sel)
  839. {
  840. methodListLock.assertLocked();
  841. return (Method)_findMethodInClass(cls, sel);
  842. }
  843. /***********************************************************************
  844. * class_getInstanceMethod. Return the instance method for the
  845. * specified class and selector.
  846. **********************************************************************/
  847. Method class_getInstanceMethod(Class cls, SEL sel)
  848. {
  849. if (!cls || !sel) return nil;
  850. // This deliberately avoids +initialize because it historically did so.
  851. // This implementation is a bit weird because it's the only place that
  852. // wants a Method instead of an IMP.
  853. Method meth;
  854. meth = _cache_getMethod(cls, sel, _objc_msgForward_impcache);
  855. if (meth == (Method)1) {
  856. // Cache contains forward:: . Stop searching.
  857. return nil;
  858. } else if (meth) {
  859. return meth;
  860. }
  861. // Search method lists, try method resolver, etc.
  862. lookUpImpOrForward(nil, sel, cls, LOOKUP_INITIALIZE | LOOKUP_RESOLVER);
  863. meth = _cache_getMethod(cls, sel, _objc_msgForward_impcache);
  864. if (meth == (Method)1) {
  865. // Cache contains forward:: . Stop searching.
  866. return nil;
  867. } else if (meth) {
  868. return meth;
  869. }
  870. return _class_getMethod(cls, sel);
  871. }
  872. BOOL class_conformsToProtocol(Class cls, Protocol *proto_gen)
  873. {
  874. old_protocol *proto = oldprotocol(proto_gen);
  875. if (!cls) return NO;
  876. if (!proto) return NO;
  877. if (cls->ISA()->version >= 3) {
  878. old_protocol_list *list;
  879. for (list = cls->protocols; list != nil; list = list->next) {
  880. int i;
  881. for (i = 0; i < list->count; i++) {
  882. if (list->list[i] == proto) return YES;
  883. if (protocol_conformsToProtocol((Protocol *)list->list[i], proto_gen)) return YES;
  884. }
  885. if (cls->ISA()->version <= 4) break;
  886. }
  887. }
  888. return NO;
  889. }
  890. static NXMapTable * posed_class_hash = nil;
  891. /***********************************************************************
  892. * objc_getOrigClass.
  893. **********************************************************************/
  894. extern "C"
  895. Class _objc_getOrigClass(const char *name)
  896. {
  897. // Look for class among the posers
  898. {
  899. mutex_locker_t lock(classLock);
  900. if (posed_class_hash) {
  901. Class cls = (Class) NXMapGet (posed_class_hash, name);
  902. if (cls) return cls;
  903. }
  904. }
  905. // Not a poser. Do a normal lookup.
  906. Class cls = objc_getClass (name);
  907. if (cls) return cls;
  908. _objc_inform ("class `%s' not linked into application", name);
  909. return nil;
  910. }
  911. Class objc_getOrigClass(const char *name)
  912. {
  913. OBJC_WARN_DEPRECATED;
  914. return _objc_getOrigClass(name);
  915. }
  916. /***********************************************************************
  917. * _objc_addOrigClass. This function is only used from class_poseAs.
  918. * Registers the original class names, before they get obscured by
  919. * posing, so that [super ..] will work correctly from categories
  920. * in posing classes and in categories in classes being posed for.
  921. **********************************************************************/
  922. static void _objc_addOrigClass (Class origClass)
  923. {
  924. mutex_locker_t lock(classLock);
  925. // Create the poser's hash table on first use
  926. if (!posed_class_hash)
  927. {
  928. posed_class_hash = NXCreateMapTable(NXStrValueMapPrototype, 8);
  929. }
  930. // Add the named class iff it is not already there (or collides?)
  931. if (NXMapGet (posed_class_hash, origClass->name) == 0)
  932. NXMapInsert (posed_class_hash, origClass->name, origClass);
  933. }
  934. /***********************************************************************
  935. * change_class_references
  936. * Change classrefs and superclass pointers from original to imposter
  937. * But if copy!=nil, don't change copy->superclass.
  938. * If changeSuperRefs==YES, also change [super message] classrefs.
  939. * Used by class_poseAs and objc_setFutureClass
  940. * classLock must be locked.
  941. **********************************************************************/
  942. void change_class_references(Class imposter,
  943. Class original,
  944. Class copy,
  945. bool changeSuperRefs)
  946. {
  947. header_info *hInfo;
  948. Class clsObject;
  949. NXHashState state;
  950. // Change all subclasses of the original to point to the imposter.
  951. state = NXInitHashState (class_hash);
  952. while (NXNextHashState (class_hash, &state, (void **) &clsObject))
  953. {
  954. while ((clsObject) && (clsObject != imposter) &&
  955. (clsObject != copy))
  956. {
  957. if (clsObject->superclass == original)
  958. {
  959. clsObject->superclass = imposter;
  960. clsObject->ISA()->superclass = imposter->ISA();
  961. // We must flush caches here!
  962. break;
  963. }
  964. clsObject = clsObject->superclass;
  965. }
  966. }
  967. // Replace the original with the imposter in all class refs
  968. // Major loop - process all headers
  969. for (hInfo = FirstHeader; hInfo != nil; hInfo = hInfo->getNext())
  970. {
  971. Class *cls_refs;
  972. size_t refCount;
  973. unsigned int index;
  974. // Fix class refs associated with this header
  975. cls_refs = _getObjcClassRefs(hInfo, &refCount);
  976. if (cls_refs) {
  977. for (index = 0; index < refCount; index += 1) {
  978. if (cls_refs[index] == original) {
  979. cls_refs[index] = imposter;
  980. }
  981. }
  982. }
  983. }
  984. }
  985. /***********************************************************************
  986. * class_poseAs.
  987. *
  988. * !!! class_poseAs () does not currently flush any caches.
  989. **********************************************************************/
  990. Class class_poseAs(Class imposter, Class original)
  991. {
  992. char * imposterNamePtr;
  993. Class copy;
  994. OBJC_WARN_DEPRECATED;
  995. // Trivial case is easy
  996. if (imposter == original)
  997. return imposter;
  998. // Imposter must be an immediate subclass of the original
  999. if (imposter->superclass != original) {
  1000. __objc_error(imposter,
  1001. "[%s poseAs:%s]: target not immediate superclass",
  1002. imposter->name, original->name);
  1003. }
  1004. // Can't pose when you have instance variables (how could it work?)
  1005. if (imposter->ivars) {
  1006. __objc_error(imposter,
  1007. "[%s poseAs:%s]: %s defines new instance variables",
  1008. imposter->name, original->name, imposter->name);
  1009. }
  1010. // Build a string to use to replace the name of the original class.
  1011. #if TARGET_OS_WIN32
  1012. # define imposterNamePrefix "_%"
  1013. imposterNamePtr = malloc(strlen(original->name) + strlen(imposterNamePrefix) + 1);
  1014. strcpy(imposterNamePtr, imposterNamePrefix);
  1015. strcat(imposterNamePtr, original->name);
  1016. # undef imposterNamePrefix
  1017. #else
  1018. asprintf(&imposterNamePtr, "_%%%s", original->name);
  1019. #endif
  1020. // We lock the class hashtable, so we are thread safe with respect to
  1021. // calls to objc_getClass (). However, the class names are not
  1022. // changed atomically, nor are all of the subclasses updated
  1023. // atomically. I have ordered the operations so that you will
  1024. // never crash, but you may get inconsistent results....
  1025. // Register the original class so that [super ..] knows
  1026. // exactly which classes are the "original" classes.
  1027. _objc_addOrigClass (original);
  1028. _objc_addOrigClass (imposter);
  1029. // Copy the imposter, so that the imposter can continue
  1030. // its normal life in addition to changing the behavior of
  1031. // the original. As a hack we don't bother to copy the metaclass.
  1032. // For some reason we modify the original rather than the copy.
  1033. copy = (Class)malloc(sizeof(objc_class));
  1034. memmove(copy, imposter, sizeof(objc_class));
  1035. mutex_locker_t lock(classLock);
  1036. // Remove both the imposter and the original class.
  1037. NXHashRemove (class_hash, imposter);
  1038. NXHashRemove (class_hash, original);
  1039. NXHashInsert (class_hash, copy);
  1040. // Mark the imposter as such
  1041. imposter->setInfo(CLS_POSING);
  1042. imposter->ISA()->setInfo(CLS_POSING);
  1043. // Change the name of the imposter to that of the original class.
  1044. imposter->name = original->name;
  1045. imposter->ISA()->name = original->ISA()->name;
  1046. // Also copy the version field to avoid archiving problems.
  1047. imposter->version = original->version;
  1048. // Change classrefs and superclass pointers
  1049. // Don't change copy->superclass
  1050. // Don't change [super ...] messages
  1051. change_class_references(imposter, original, copy, NO);
  1052. // Change the name of the original class.
  1053. original->name = imposterNamePtr + 1;
  1054. original->ISA()->name = imposterNamePtr;
  1055. // Restore the imposter and the original class with their new names.
  1056. NXHashInsert (class_hash, imposter);
  1057. NXHashInsert (class_hash, original);
  1058. return imposter;
  1059. }
  1060. /***********************************************************************
  1061. * _objc_flush_caches. Flush the instance and class method caches
  1062. * of cls and all its subclasses.
  1063. *
  1064. * Specifying Nil for the class "all classes."
  1065. **********************************************************************/
  1066. static void flush_caches(Class target, bool flush_meta)
  1067. {
  1068. bool collectALot = (target == nil);
  1069. NXHashState state;
  1070. Class clsObject;
  1071. #ifdef OBJC_INSTRUMENTED
  1072. unsigned int classesVisited;
  1073. unsigned int subclassCount;
  1074. #endif
  1075. mutex_locker_t lock(classLock);
  1076. mutex_locker_t lock2(cacheUpdateLock);
  1077. // Leaf classes are fastest because there are no subclass caches to flush.
  1078. // fixme instrument
  1079. if (target && (target->info & CLS_LEAF)) {
  1080. _cache_flush (target);
  1081. if (target->ISA() && (target->ISA()->info & CLS_LEAF)) {
  1082. _cache_flush (target->ISA());
  1083. return; // done
  1084. } else {
  1085. // Reset target and handle it by one of the methods below.
  1086. target = target->ISA();
  1087. flush_meta = NO;
  1088. // NOT done
  1089. }
  1090. }
  1091. state = NXInitHashState(class_hash);
  1092. // Handle nil and root instance class specially: flush all
  1093. // instance and class method caches. Nice that this
  1094. // loop is linear vs the N-squared loop just below.
  1095. if (!target || !target->superclass)
  1096. {
  1097. #ifdef OBJC_INSTRUMENTED
  1098. LinearFlushCachesCount += 1;
  1099. classesVisited = 0;
  1100. subclassCount = 0;
  1101. #endif
  1102. // Traverse all classes in the hash table
  1103. while (NXNextHashState(class_hash, &state, (void**)&clsObject))
  1104. {
  1105. Class metaClsObject;
  1106. #ifdef OBJC_INSTRUMENTED
  1107. classesVisited += 1;
  1108. #endif
  1109. // Skip class that is known not to be a subclass of this root
  1110. // (the isa pointer of any meta class points to the meta class
  1111. // of the root).
  1112. // NOTE: When is an isa pointer of a hash tabled class ever nil?
  1113. metaClsObject = clsObject->ISA();
  1114. if (target && metaClsObject && target->ISA() != metaClsObject->ISA()) {
  1115. continue;
  1116. }
  1117. #ifdef OBJC_INSTRUMENTED
  1118. subclassCount += 1;
  1119. #endif
  1120. _cache_flush (clsObject);
  1121. if (flush_meta && metaClsObject != nil) {
  1122. _cache_flush (metaClsObject);
  1123. }
  1124. }
  1125. #ifdef OBJC_INSTRUMENTED
  1126. LinearFlushCachesVisitedCount += classesVisited;
  1127. if (classesVisited > MaxLinearFlushCachesVisitedCount)
  1128. MaxLinearFlushCachesVisitedCount = classesVisited;
  1129. IdealFlushCachesCount += subclassCount;
  1130. if (subclassCount > MaxIdealFlushCachesCount)
  1131. MaxIdealFlushCachesCount = subclassCount;
  1132. #endif
  1133. goto done;
  1134. }
  1135. // Outer loop - flush any cache that could now get a method from
  1136. // cls (i.e. the cache associated with cls and any of its subclasses).
  1137. #ifdef OBJC_INSTRUMENTED
  1138. NonlinearFlushCachesCount += 1;
  1139. classesVisited = 0;
  1140. subclassCount = 0;
  1141. #endif
  1142. while (NXNextHashState(class_hash, &state, (void**)&clsObject))
  1143. {
  1144. Class clsIter;
  1145. #ifdef OBJC_INSTRUMENTED
  1146. NonlinearFlushCachesClassCount += 1;
  1147. #endif
  1148. // Inner loop - Process a given class
  1149. clsIter = clsObject;
  1150. while (clsIter)
  1151. {
  1152. #ifdef OBJC_INSTRUMENTED
  1153. classesVisited += 1;
  1154. #endif
  1155. // Flush clsObject instance method cache if
  1156. // clsObject is a subclass of cls, or is cls itself
  1157. // Flush the class method cache if that was asked for
  1158. if (clsIter == target)
  1159. {
  1160. #ifdef OBJC_INSTRUMENTED
  1161. subclassCount += 1;
  1162. #endif
  1163. _cache_flush (clsObject);
  1164. if (flush_meta)
  1165. _cache_flush (clsObject->ISA());
  1166. break;
  1167. }
  1168. // Flush clsObject class method cache if cls is
  1169. // the meta class of clsObject or of one
  1170. // of clsObject's superclasses
  1171. else if (clsIter->ISA() == target)
  1172. {
  1173. #ifdef OBJC_INSTRUMENTED
  1174. subclassCount += 1;
  1175. #endif
  1176. _cache_flush (clsObject->ISA());
  1177. break;
  1178. }
  1179. // Move up superclass chain
  1180. // else if (clsIter->isInitialized())
  1181. clsIter = clsIter->superclass;
  1182. // clsIter is not initialized, so its cache
  1183. // must be empty. This happens only when
  1184. // clsIter == clsObject, because
  1185. // superclasses are initialized before
  1186. // subclasses, and this loop traverses
  1187. // from sub- to super- classes.
  1188. // else
  1189. // break;
  1190. }
  1191. }
  1192. #ifdef OBJC_INSTRUMENTED
  1193. NonlinearFlushCachesVisitedCount += classesVisited;
  1194. if (classesVisited > MaxNonlinearFlushCachesVisitedCount)
  1195. MaxNonlinearFlushCachesVisitedCount = classesVisited;
  1196. IdealFlushCachesCount += subclassCount;
  1197. if (subclassCount > MaxIdealFlushCachesCount)
  1198. MaxIdealFlushCachesCount = subclassCount;
  1199. #endif
  1200. done:
  1201. if (collectALot) {
  1202. _cache_collect(true);
  1203. }
  1204. }
  1205. void _objc_flush_caches(Class target)
  1206. {
  1207. flush_caches(target, YES);
  1208. }
  1209. /***********************************************************************
  1210. * flush_marked_caches. Flush the method cache of any class marked
  1211. * CLS_FLUSH_CACHE (and all subclasses thereof)
  1212. * fixme instrument
  1213. **********************************************************************/
  1214. void flush_marked_caches(void)
  1215. {
  1216. Class cls;
  1217. Class supercls;
  1218. NXHashState state;
  1219. mutex_locker_t lock(classLock);
  1220. mutex_locker_t lock2(cacheUpdateLock);
  1221. state = NXInitHashState(class_hash);
  1222. while (NXNextHashState(class_hash, &state, (void**)&cls)) {
  1223. for (supercls = cls; supercls; supercls = supercls->superclass) {
  1224. if (supercls->info & CLS_FLUSH_CACHE) {
  1225. _cache_flush(cls);
  1226. break;
  1227. }
  1228. }
  1229. for (supercls = cls->ISA(); supercls; supercls = supercls->superclass) {
  1230. if (supercls->info & CLS_FLUSH_CACHE) {
  1231. _cache_flush(cls->ISA());
  1232. break;
  1233. }
  1234. }
  1235. }
  1236. state = NXInitHashState(class_hash);
  1237. while (NXNextHashState(class_hash, &state, (void**)&cls)) {
  1238. if (cls->info & CLS_FLUSH_CACHE) {
  1239. cls->clearInfo(CLS_FLUSH_CACHE);
  1240. }
  1241. if (cls->ISA()->info & CLS_FLUSH_CACHE) {
  1242. cls->ISA()->clearInfo(CLS_FLUSH_CACHE);
  1243. }
  1244. }
  1245. }
  1246. /***********************************************************************
  1247. * get_base_method_list
  1248. * Returns the method list containing the class's own methods,
  1249. * ignoring any method lists added by categories or class_addMethods.
  1250. * Called only by add_class_to_loadable_list.
  1251. * Does not hold methodListLock because add_class_to_loadable_list
  1252. * does not manipulate in-use classes.
  1253. **********************************************************************/
  1254. static old_method_list *get_base_method_list(Class cls)
  1255. {
  1256. old_method_list **ptr;
  1257. if (!cls->methodLists) return nil;
  1258. if (cls->info & CLS_NO_METHOD_ARRAY) return (old_method_list *)cls->methodLists;
  1259. ptr = cls->methodLists;
  1260. if (!*ptr || *ptr == END_OF_METHODS_LIST) return nil;
  1261. while ( *ptr != 0 && *ptr != END_OF_METHODS_LIST ) { ptr++; }
  1262. --ptr;
  1263. return *ptr;
  1264. }
  1265. static IMP _class_getLoadMethod_nocheck(Class cls)
  1266. {
  1267. old_method_list *mlist;
  1268. mlist = get_base_method_list(cls->ISA());
  1269. if (mlist) {
  1270. return lookupNamedMethodInMethodList (mlist, "load");
  1271. }
  1272. return nil;
  1273. }
  1274. bool _class_hasLoadMethod(Class cls)
  1275. {
  1276. if (cls->ISA()->info & CLS_HAS_LOAD_METHOD) return YES;
  1277. return _class_getLoadMethod_nocheck(cls);
  1278. }
  1279. /***********************************************************************
  1280. * objc_class::getLoadMethod
  1281. * Returns cls's +load implementation, or nil if it doesn't have one.
  1282. **********************************************************************/
  1283. IMP objc_class::getLoadMethod()
  1284. {
  1285. if (ISA()->info & CLS_HAS_LOAD_METHOD) {
  1286. return _class_getLoadMethod_nocheck((Class)this);
  1287. }
  1288. return nil;
  1289. }
  1290. ptrdiff_t ivar_getOffset(Ivar ivar)
  1291. {
  1292. return oldivar(ivar)->ivar_offset;
  1293. }
  1294. const char *ivar_getName(Ivar ivar)
  1295. {
  1296. return oldivar(ivar)->ivar_name;
  1297. }
  1298. const char *ivar_getTypeEncoding(Ivar ivar)
  1299. {
  1300. return oldivar(ivar)->ivar_type;
  1301. }
  1302. IMP method_getImplementation(Method m)
  1303. {
  1304. if (!m) return nil;
  1305. return oldmethod(m)->method_imp;
  1306. }
  1307. SEL method_getName(Method m)
  1308. {
  1309. if (!m) return nil;
  1310. return oldmethod(m)->method_name;
  1311. }
  1312. const char *method_getTypeEncoding(Method m)
  1313. {
  1314. if (!m) return nil;
  1315. return oldmethod(m)->method_types;
  1316. }
  1317. unsigned int method_getSizeOfArguments(Method m)
  1318. {
  1319. OBJC_WARN_DEPRECATED;
  1320. if (!m) return 0;
  1321. return encoding_getSizeOfArguments(method_getTypeEncoding(m));
  1322. }
  1323. // This function was accidentally un-exported beginning in macOS 10.9.
  1324. // As of macOS 10.13 nobody had complained.
  1325. /*
  1326. unsigned int method_getArgumentInfo(Method m, int arg,
  1327. const char **type, int *offset)
  1328. {
  1329. OBJC_WARN_DEPRECATED;
  1330. if (!m) return 0;
  1331. return encoding_getArgumentInfo(method_getTypeEncoding(m),
  1332. arg, type, offset);
  1333. }
  1334. */
  1335. spinlock_t impLock;
  1336. IMP method_setImplementation(Method m_gen, IMP imp)
  1337. {
  1338. IMP old;
  1339. old_method *m = oldmethod(m_gen);
  1340. if (!m) return nil;
  1341. if (!imp) return nil;
  1342. impLock.lock();
  1343. old = m->method_imp;
  1344. m->method_imp = imp;
  1345. impLock.unlock();
  1346. return old;
  1347. }
  1348. void method_exchangeImplementations(Method m1_gen, Method m2_gen)
  1349. {
  1350. IMP m1_imp;
  1351. old_method *m1 = oldmethod(m1_gen);
  1352. old_method *m2 = oldmethod(m2_gen);
  1353. if (!m1 || !m2) return;
  1354. impLock.lock();
  1355. m1_imp = m1->method_imp;
  1356. m1->method_imp = m2->method_imp;
  1357. m2->method_imp = m1_imp;
  1358. impLock.unlock();
  1359. }
  1360. struct objc_method_description * method_getDescription(Method m)
  1361. {
  1362. if (!m) return nil;
  1363. return (struct objc_method_description *)oldmethod(m);
  1364. }
  1365. const char *property_getName(objc_property_t prop)
  1366. {
  1367. return oldproperty(prop)->name;
  1368. }
  1369. const char *property_getAttributes(objc_property_t prop)
  1370. {
  1371. return oldproperty(prop)->attributes;
  1372. }
  1373. objc_property_attribute_t *property_copyAttributeList(objc_property_t prop,
  1374. unsigned int *outCount)
  1375. {
  1376. if (!prop) {
  1377. if (outCount) *outCount = 0;
  1378. return nil;
  1379. }
  1380. mutex_locker_t lock(classLock);
  1381. return copyPropertyAttributeList(oldproperty(prop)->attributes,outCount);
  1382. }
  1383. char * property_copyAttributeValue(objc_property_t prop, const char *name)
  1384. {
  1385. if (!prop || !name || *name == '\0') return nil;
  1386. mutex_locker_t lock(classLock);
  1387. return copyPropertyAttributeValue(oldproperty(prop)->attributes, name);
  1388. }
  1389. /***********************************************************************
  1390. * class_addMethod
  1391. **********************************************************************/
  1392. static IMP _class_addMethod(Class cls, SEL name, IMP imp,
  1393. const char *types, bool replace)
  1394. {
  1395. old_method *m;
  1396. IMP result = nil;
  1397. if (!types) types = "";
  1398. mutex_locker_t lock(methodListLock);
  1399. if ((m = _findMethodInClass(cls, name))) {
  1400. // already exists
  1401. // fixme atomic
  1402. result = method_getImplementation((Method)m);
  1403. if (replace) {
  1404. method_setImplementation((Method)m, imp);
  1405. }
  1406. } else {
  1407. // fixme could be faster
  1408. old_method_list *mlist =
  1409. (old_method_list *)calloc(sizeof(old_method_list), 1);
  1410. mlist->obsolete = fixed_up_method_list;
  1411. mlist->method_count = 1;
  1412. mlist->method_list[0].method_name = name;
  1413. mlist->method_list[0].method_types = strdup(types);
  1414. mlist->method_list[0].method_imp = imp;
  1415. _objc_insertMethods(cls, mlist, nil);
  1416. if (!(cls->info & CLS_CONSTRUCTING)) {
  1417. flush_caches(cls, NO);
  1418. } else {
  1419. // in-construction class has no subclasses
  1420. flush_cache(cls);
  1421. }
  1422. result = nil;
  1423. }
  1424. return result;
  1425. }
  1426. /***********************************************************************
  1427. * class_addMethod
  1428. **********************************************************************/
  1429. BOOL class_addMethod(Class cls, SEL name, IMP imp, const char *types)
  1430. {
  1431. IMP old;
  1432. if (!cls) return NO;
  1433. old = _class_addMethod(cls, name, imp, types, NO);
  1434. return !old;
  1435. }
  1436. /***********************************************************************
  1437. * class_replaceMethod
  1438. **********************************************************************/
  1439. IMP class_replaceMethod(Class cls, SEL name, IMP imp, const char *types)
  1440. {
  1441. if (!cls) return nil;
  1442. return _class_addMethod(cls, name, imp, types, YES);
  1443. }
  1444. /***********************************************************************
  1445. * class_addIvar
  1446. **********************************************************************/
  1447. BOOL class_addIvar(Class cls, const char *name, size_t size,
  1448. uint8_t alignment, const char *type)
  1449. {
  1450. bool result = YES;
  1451. if (!cls) return NO;
  1452. if (ISMETA(cls)) return NO;
  1453. if (!(cls->info & CLS_CONSTRUCTING)) return NO;
  1454. if (!type) type = "";
  1455. if (name && 0 == strcmp(name, "")) name = nil;
  1456. mutex_locker_t lock(classLock);
  1457. // Check for existing ivar with this name
  1458. // fixme check superclasses?
  1459. if (cls->ivars) {
  1460. int i;
  1461. for (i = 0; i < cls->ivars->ivar_count; i++) {
  1462. if (0 == strcmp(cls->ivars->ivar_list[i].ivar_name, name)) {
  1463. result = NO;
  1464. break;
  1465. }
  1466. }
  1467. }
  1468. if (result) {
  1469. old_ivar_list *old = cls->ivars;
  1470. size_t oldSize;
  1471. int newCount;
  1472. old_ivar *ivar;
  1473. size_t alignBytes;
  1474. size_t misalign;
  1475. if (old) {
  1476. oldSize = sizeof(old_ivar_list) +
  1477. (old->ivar_count - 1) * sizeof(old_ivar);
  1478. newCount = 1 + old->ivar_count;
  1479. } else {
  1480. oldSize = sizeof(old_ivar_list) - sizeof(old_ivar);
  1481. newCount = 1;
  1482. }
  1483. // allocate new ivar list
  1484. cls->ivars = (old_ivar_list *)
  1485. calloc(oldSize+sizeof(old_ivar), 1);
  1486. if (old) memcpy(cls->ivars, old, oldSize);
  1487. if (old && malloc_size(old)) free(old);
  1488. cls->ivars->ivar_count = newCount;
  1489. ivar = &cls->ivars->ivar_list[newCount-1];
  1490. // set ivar name and type
  1491. ivar->ivar_name = strdup(name);
  1492. ivar->ivar_type = strdup(type);
  1493. // align if necessary
  1494. alignBytes = 1 << alignment;
  1495. misalign = cls->instance_size % alignBytes;
  1496. if (misalign) cls->instance_size += (long)(alignBytes - misalign);
  1497. // set ivar offset and increase instance size
  1498. ivar->ivar_offset = (int)cls->instance_size;
  1499. cls->instance_size += (long)size;
  1500. }
  1501. return result;
  1502. }
  1503. /***********************************************************************
  1504. * class_addProtocol
  1505. **********************************************************************/
  1506. BOOL class_addProtocol(Class cls, Protocol *protocol_gen)
  1507. {
  1508. old_protocol *protocol = oldprotocol(protocol_gen);
  1509. old_protocol_list *plist;
  1510. if (!cls) return NO;
  1511. if (class_conformsToProtocol(cls, protocol_gen)) return NO;
  1512. mutex_locker_t lock(classLock);
  1513. // fixme optimize - protocol list doesn't escape?
  1514. plist = (old_protocol_list*)calloc(sizeof(old_protocol_list), 1);
  1515. plist->count = 1;
  1516. plist->list[0] = protocol;
  1517. plist->next = cls->protocols;
  1518. cls->protocols = plist;
  1519. // fixme metaclass?
  1520. return YES;
  1521. }
  1522. /***********************************************************************
  1523. * _class_addProperties
  1524. * Internal helper to add properties to a class.
  1525. * Used by category attachment and class_addProperty()
  1526. * Locking: acquires classLock
  1527. **********************************************************************/
  1528. bool
  1529. _class_addProperties(Class cls,
  1530. old_property_list *additions)
  1531. {
  1532. old_property_list *newlist;
  1533. if (!(cls->info & CLS_EXT)) return NO;
  1534. newlist = (old_property_list *)
  1535. memdup(additions, sizeof(*newlist) - sizeof(newlist->first)
  1536. + (additions->entsize * additions->count));
  1537. mutex_locker_t lock(classLock);
  1538. allocateExt(cls);
  1539. if (!cls->ext->propertyLists) {
  1540. // cls has no properties - simply use this list
  1541. cls->ext->propertyLists = (old_property_list **)newlist;
  1542. cls->setInfo(CLS_NO_PROPERTY_ARRAY);
  1543. }
  1544. else if (cls->info & CLS_NO_PROPERTY_ARRAY) {
  1545. // cls has one property list - make a new array
  1546. old_property_list **newarray = (old_property_list **)
  1547. malloc(3 * sizeof(*newarray));
  1548. newarray[0] = newlist;
  1549. newarray[1] = (old_property_list *)cls->ext->propertyLists;
  1550. newarray[2] = nil;
  1551. cls->ext->propertyLists = newarray;
  1552. cls->clearInfo(CLS_NO_PROPERTY_ARRAY);
  1553. }
  1554. else {
  1555. // cls has a property array - make a bigger one
  1556. old_property_list **newarray;
  1557. int count = 0;
  1558. while (cls->ext->propertyLists[count]) count++;
  1559. newarray = (old_property_list **)
  1560. malloc((count+2) * sizeof(*newarray));
  1561. newarray[0] = newlist;
  1562. memcpy(&newarray[1], &cls->ext->propertyLists[0],
  1563. count * sizeof(*newarray));
  1564. newarray[count+1] = nil;
  1565. free(cls->ext->propertyLists);
  1566. cls->ext->propertyLists = newarray;
  1567. }
  1568. return YES;
  1569. }
  1570. /***********************************************************************
  1571. * class_addProperty
  1572. * Adds a property to a class. Returns NO if the proeprty already exists.
  1573. * Locking: acquires classLock
  1574. **********************************************************************/
  1575. static bool
  1576. _class_addProperty(Class cls, const char *name,
  1577. const objc_property_attribute_t *attrs, unsigned int count,
  1578. bool replace)
  1579. {
  1580. if (!cls) return NO;
  1581. if (!name) return NO;
  1582. old_property *prop = oldproperty(class_getProperty(cls, name));
  1583. if (prop && !replace) {
  1584. // already exists, refuse to replace
  1585. return NO;
  1586. }
  1587. else if (prop) {
  1588. // replace existing
  1589. mutex_locker_t lock(classLock);
  1590. try_free(prop->attributes);
  1591. prop->attributes = copyPropertyAttributeString(attrs, count);
  1592. return YES;
  1593. }
  1594. else {
  1595. // add new
  1596. old_property_list proplist;
  1597. proplist.entsize = sizeof(old_property);
  1598. proplist.count = 1;
  1599. proplist.first.name = strdup(name);
  1600. proplist.first.attributes = copyPropertyAttributeString(attrs, count);
  1601. return _class_addProperties(cls, &proplist);
  1602. }
  1603. }
  1604. BOOL
  1605. class_addProperty(Class cls, const char *name,
  1606. const objc_property_attribute_t *attrs, unsigned int n)
  1607. {
  1608. return _class_addProperty(cls, name, attrs, n, NO);
  1609. }
  1610. void
  1611. class_replaceProperty(Class cls, const char *name,
  1612. const objc_property_attribute_t *attrs, unsigned int n)
  1613. {
  1614. _class_addProperty(cls, name, attrs, n, YES);
  1615. }
  1616. /***********************************************************************
  1617. * class_copyProtocolList. Returns a heap block containing the
  1618. * protocols implemented by the class, or nil if the class
  1619. * implements no protocols. Caller must free the block.
  1620. * Does not copy any superclass's protocols.
  1621. **********************************************************************/
  1622. Protocol * __unsafe_unretained *
  1623. class_copyProtocolList(Class cls, unsigned int *outCount)
  1624. {
  1625. old_protocol_list *plist;
  1626. Protocol **result = nil;
  1627. unsigned int count = 0;
  1628. unsigned int p;
  1629. if (!cls) {
  1630. if (outCount) *outCount = 0;
  1631. return nil;
  1632. }
  1633. mutex_locker_t lock(classLock);
  1634. for (plist = cls->protocols; plist != nil; plist = plist->next) {
  1635. count += (int)plist->count;
  1636. }
  1637. if (count > 0) {
  1638. result = (Protocol **)malloc((count+1) * sizeof(Protocol *));
  1639. for (p = 0, plist = cls->protocols;
  1640. plist != nil;
  1641. plist = plist->next)
  1642. {
  1643. int i;
  1644. for (i = 0; i < plist->count; i++) {
  1645. result[p++] = (Protocol *)plist->list[i];
  1646. }
  1647. }
  1648. result[p] = nil;
  1649. }
  1650. if (outCount) *outCount = count;
  1651. return result;
  1652. }
  1653. /***********************************************************************
  1654. * class_getProperty. Return the named property.
  1655. **********************************************************************/
  1656. objc_property_t class_getProperty(Class cls, const char *name)
  1657. {
  1658. if (!cls || !name) return nil;
  1659. mutex_locker_t lock(classLock);
  1660. for (; cls; cls = cls->superclass) {
  1661. uintptr_t iterator = 0;
  1662. old_property_list *plist;
  1663. while ((plist = nextPropertyList(cls, &iterator))) {
  1664. uint32_t i;
  1665. for (i = 0; i < plist->count; i++) {
  1666. old_property *p = property_list_nth(plist, i);
  1667. if (0 == strcmp(name, p->name)) {
  1668. return (objc_property_t)p;
  1669. }
  1670. }
  1671. }
  1672. }
  1673. return nil;
  1674. }
  1675. /***********************************************************************
  1676. * class_copyPropertyList. Returns a heap block containing the
  1677. * properties declared in the class, or nil if the class
  1678. * declares no properties. Caller must free the block.
  1679. * Does not copy any superclass's properties.
  1680. **********************************************************************/
  1681. objc_property_t *class_copyPropertyList(Class cls, unsigned int *outCount)
  1682. {
  1683. old_property_list *plist;
  1684. uintptr_t iterator = 0;
  1685. old_property **result = nil;
  1686. unsigned int count = 0;
  1687. unsigned int p, i;
  1688. if (!cls) {
  1689. if (outCount) *outCount = 0;
  1690. return nil;
  1691. }
  1692. mutex_locker_t lock(classLock);
  1693. iterator = 0;
  1694. while ((plist = nextPropertyList(cls, &iterator))) {
  1695. count += plist->count;
  1696. }
  1697. if (count > 0) {
  1698. result = (old_property **)malloc((count+1) * sizeof(old_property *));
  1699. p = 0;
  1700. iterator = 0;
  1701. while ((plist = nextPropertyList(cls, &iterator))) {
  1702. for (i = 0; i < plist->count; i++) {
  1703. result[p++] = property_list_nth(plist, i);
  1704. }
  1705. }
  1706. result[p] = nil;
  1707. }
  1708. if (outCount) *outCount = count;
  1709. return (objc_property_t *)result;
  1710. }
  1711. /***********************************************************************
  1712. * class_copyMethodList. Returns a heap block containing the
  1713. * methods implemented by the class, or nil if the class
  1714. * implements no methods. Caller must free the block.
  1715. * Does not copy any superclass's methods.
  1716. **********************************************************************/
  1717. Method *class_copyMethodList(Class cls, unsigned int *outCount)
  1718. {
  1719. old_method_list *mlist;
  1720. void *iterator = nil;
  1721. Method *result = nil;
  1722. unsigned int count = 0;
  1723. unsigned int m;
  1724. if (!cls) {
  1725. if (outCount) *outCount = 0;
  1726. return nil;
  1727. }
  1728. mutex_locker_t lock(methodListLock);
  1729. iterator = nil;
  1730. while ((mlist = nextMethodList(cls, &iterator))) {
  1731. count += mlist->method_count;
  1732. }
  1733. if (count > 0) {
  1734. result = (Method *)malloc((count+1) * sizeof(Method));
  1735. m = 0;
  1736. iterator = nil;
  1737. while ((mlist = nextMethodList(cls, &iterator))) {
  1738. int i;
  1739. for (i = 0; i < mlist->method_count; i++) {
  1740. result[m++] = (Method)&mlist->method_list[i];
  1741. }
  1742. }
  1743. result[m] = nil;
  1744. }
  1745. if (outCount) *outCount = count;
  1746. return result;
  1747. }
  1748. /***********************************************************************
  1749. * class_copyIvarList. Returns a heap block containing the
  1750. * ivars declared in the class, or nil if the class
  1751. * declares no ivars. Caller must free the block.
  1752. * Does not copy any superclass's ivars.
  1753. **********************************************************************/
  1754. Ivar *class_copyIvarList(Class cls, unsigned int *outCount)
  1755. {
  1756. Ivar *result = nil;
  1757. unsigned int count = 0;
  1758. int i;
  1759. if (!cls) {
  1760. if (outCount) *outCount = 0;
  1761. return nil;
  1762. }
  1763. if (cls->ivars) {
  1764. count = cls->ivars->ivar_count;
  1765. }
  1766. if (count > 0) {
  1767. result = (Ivar *)malloc((count+1) * sizeof(Ivar));
  1768. for (i = 0; i < cls->ivars->ivar_count; i++) {
  1769. result[i] = (Ivar)&cls->ivars->ivar_list[i];
  1770. }
  1771. result[i] = nil;
  1772. }
  1773. if (outCount) *outCount = count;
  1774. return result;
  1775. }
  1776. /***********************************************************************
  1777. * objc_allocateClass.
  1778. **********************************************************************/
  1779. void set_superclass(Class cls, Class supercls, bool cls_is_new)
  1780. {
  1781. Class meta = cls->ISA();
  1782. if (supercls) {
  1783. cls->superclass = supercls;
  1784. meta->superclass = supercls->ISA();
  1785. meta->initIsa(supercls->ISA()->ISA());
  1786. // Propagate C++ cdtors from superclass.
  1787. if (supercls->info & CLS_HAS_CXX_STRUCTORS) {
  1788. if (cls_is_new) cls->info |= CLS_HAS_CXX_STRUCTORS;
  1789. else cls->setInfo(CLS_HAS_CXX_STRUCTORS);
  1790. }
  1791. // Superclass is no longer a leaf for cache flushing
  1792. if (supercls->info & CLS_LEAF) {
  1793. supercls->clearInfo(CLS_LEAF);
  1794. supercls->ISA()->clearInfo(CLS_LEAF);
  1795. }
  1796. } else {
  1797. cls->superclass = Nil; // superclass of root class is nil
  1798. meta->superclass = cls; // superclass of root metaclass is root class
  1799. meta->initIsa(meta); // metaclass of root metaclass is root metaclass
  1800. // Root class is never a leaf for cache flushing, because the
  1801. // root metaclass is a subclass. (This could be optimized, but
  1802. // is too uncommon to bother.)
  1803. cls->clearInfo(CLS_LEAF);
  1804. meta->clearInfo(CLS_LEAF);
  1805. }
  1806. }
  1807. // &UnsetLayout is the default ivar layout during class construction
  1808. static const uint8_t UnsetLayout = 0;
  1809. Class objc_initializeClassPair(Class supercls, const char *name, Class cls, Class meta)
  1810. {
  1811. // Connect to superclasses and metaclasses
  1812. cls->initIsa(meta);
  1813. set_superclass(cls, supercls, YES);
  1814. // Set basic info
  1815. cls->name = strdup(name);
  1816. meta->name = strdup(name);
  1817. cls->version = 0;
  1818. meta->version = 7;
  1819. cls->info = CLS_CLASS | CLS_CONSTRUCTING | CLS_EXT | CLS_LEAF;
  1820. meta->info = CLS_META | CLS_CONSTRUCTING | CLS_EXT | CLS_LEAF;
  1821. // Set instance size based on superclass.
  1822. if (supercls) {
  1823. cls->instance_size = supercls->instance_size;
  1824. meta->instance_size = supercls->ISA()->instance_size;
  1825. } else {
  1826. cls->instance_size = sizeof(Class); // just an isa
  1827. meta->instance_size = sizeof(objc_class);
  1828. }
  1829. // No ivars. No methods. Empty cache. No protocols. No layout. Empty ext.
  1830. cls->ivars = nil;
  1831. cls->methodLists = nil;
  1832. cls->cache = (Cache)&_objc_empty_cache;
  1833. cls->protocols = nil;
  1834. cls->ivar_layout = &UnsetLayout;
  1835. cls->ext = nil;
  1836. allocateExt(cls);
  1837. cls->ext->weak_ivar_layout = &UnsetLayout;
  1838. meta->ivars = nil;
  1839. meta->methodLists = nil;
  1840. meta->cache = (Cache)&_objc_empty_cache;
  1841. meta->protocols = nil;
  1842. meta->ext = nil;
  1843. return cls;
  1844. }
  1845. Class objc_allocateClassPair(Class supercls, const char *name,
  1846. size_t extraBytes)
  1847. {
  1848. Class cls, meta;
  1849. if (objc_getClass(name)) return nil;
  1850. // fixme reserve class name against simultaneous allocation
  1851. if (supercls && (supercls->info & CLS_CONSTRUCTING)) {
  1852. // Can't make subclass of an in-construction class
  1853. return nil;
  1854. }
  1855. // Allocate new classes.
  1856. if (supercls) {
  1857. cls = _calloc_class(supercls->ISA()->alignedInstanceSize() + extraBytes);
  1858. meta = _calloc_class(supercls->ISA()->ISA()->alignedInstanceSize() + extraBytes);
  1859. } else {
  1860. cls = _calloc_class(sizeof(objc_class) + extraBytes);
  1861. meta = _calloc_class(sizeof(objc_class) + extraBytes);
  1862. }
  1863. objc_initializeClassPair(supercls, name, cls, meta);
  1864. return cls;
  1865. }
  1866. void objc_registerClassPair(Class cls)
  1867. {
  1868. if ((cls->info & CLS_CONSTRUCTED) ||
  1869. (cls->ISA()->info & CLS_CONSTRUCTED))
  1870. {
  1871. _objc_inform("objc_registerClassPair: class '%s' was already "
  1872. "registered!", cls->name);
  1873. return;
  1874. }
  1875. if (!(cls->info & CLS_CONSTRUCTING) ||
  1876. !(cls->ISA()->info & CLS_CONSTRUCTING))
  1877. {
  1878. _objc_inform("objc_registerClassPair: class '%s' was not "
  1879. "allocated with objc_allocateClassPair!", cls->name);
  1880. return;
  1881. }
  1882. if (ISMETA(cls)) {
  1883. _objc_inform("objc_registerClassPair: class '%s' is a metaclass, "
  1884. "not a class!", cls->name);
  1885. return;
  1886. }
  1887. mutex_locker_t lock(classLock);
  1888. // Clear "under construction" bit, set "done constructing" bit
  1889. cls->info &= ~CLS_CONSTRUCTING;
  1890. cls->ISA()->info &= ~CLS_CONSTRUCTING;
  1891. cls->info |= CLS_CONSTRUCTED;
  1892. cls->ISA()->info |= CLS_CONSTRUCTED;
  1893. NXHashInsertIfAbsent(class_hash, cls);
  1894. }
  1895. Class objc_duplicateClass(Class original, const char *name, size_t extraBytes)
  1896. {
  1897. unsigned int count, i;
  1898. old_method **originalMethods;
  1899. old_method_list *duplicateMethods;
  1900. // Don't use sizeof(objc_class) here because
  1901. // instance_size has historically contained two extra words,
  1902. // and instance_size is what objc_getIndexedIvars() actually uses.
  1903. Class duplicate =
  1904. _calloc_class(original->ISA()->alignedInstanceSize() + extraBytes);
  1905. duplicate->initIsa(original->ISA());
  1906. duplicate->superclass = original->superclass;
  1907. duplicate->name = strdup(name);
  1908. duplicate->version = original->version;
  1909. duplicate->info = original->info & (CLS_CLASS|CLS_META|CLS_INITIALIZED|CLS_JAVA_HYBRID|CLS_JAVA_CLASS|CLS_HAS_CXX_STRUCTORS|CLS_HAS_LOAD_METHOD);
  1910. duplicate->instance_size = original->instance_size;
  1911. duplicate->ivars = original->ivars;
  1912. // methodLists handled below
  1913. duplicate->cache = (Cache)&_objc_empty_cache;
  1914. duplicate->protocols = original->protocols;
  1915. if (original->info & CLS_EXT) {
  1916. duplicate->info |= original->info & (CLS_EXT|CLS_NO_PROPERTY_ARRAY);
  1917. duplicate->ivar_layout = original->ivar_layout;
  1918. if (original->ext) {
  1919. duplicate->ext = (old_class_ext *)malloc(original->ext->size);
  1920. memcpy(duplicate->ext, original->ext, original->ext->size);
  1921. } else {
  1922. duplicate->ext = nil;
  1923. }
  1924. }
  1925. // Method lists are deep-copied so they can be stomped.
  1926. originalMethods = (old_method **)class_copyMethodList(original, &count);
  1927. if (originalMethods) {
  1928. duplicateMethods = (old_method_list *)
  1929. calloc(sizeof(old_method_list) +
  1930. (count-1)*sizeof(old_method), 1);
  1931. duplicateMethods->obsolete = fixed_up_method_list;
  1932. duplicateMethods->method_count = count;
  1933. for (i = 0; i < count; i++) {
  1934. duplicateMethods->method_list[i] = *(originalMethods[i]);
  1935. }
  1936. duplicate->methodLists = (old_method_list **)duplicateMethods;
  1937. duplicate->info |= CLS_NO_METHOD_ARRAY;
  1938. free(originalMethods);
  1939. }
  1940. mutex_locker_t lock(classLock);
  1941. NXHashInsert(class_hash, duplicate);
  1942. return duplicate;
  1943. }
  1944. void objc_disposeClassPair(Class cls)
  1945. {
  1946. if (!(cls->info & (CLS_CONSTRUCTED|CLS_CONSTRUCTING)) ||
  1947. !(cls->ISA()->info & (CLS_CONSTRUCTED|CLS_CONSTRUCTING)))
  1948. {
  1949. // class not allocated with objc_allocateClassPair
  1950. // disposing still-unregistered class is OK!
  1951. _objc_inform("objc_disposeClassPair: class '%s' was not "
  1952. "allocated with objc_allocateClassPair!", cls->name);
  1953. return;
  1954. }
  1955. if (ISMETA(cls)) {
  1956. _objc_inform("objc_disposeClassPair: class '%s' is a metaclass, "
  1957. "not a class!", cls->name);
  1958. return;
  1959. }
  1960. mutex_locker_t lock(classLock);
  1961. NXHashRemove(class_hash, cls);
  1962. unload_class(cls->ISA());
  1963. unload_class(cls);
  1964. }
  1965. /***********************************************************************
  1966. * objc_constructInstance
  1967. * Creates an instance of `cls` at the location pointed to by `bytes`.
  1968. * `bytes` must point to at least class_getInstanceSize(cls) bytes of
  1969. * well-aligned zero-filled memory.
  1970. * The new object's isa is set. Any C++ constructors are called.
  1971. * Returns `bytes` if successful. Returns nil if `cls` or `bytes` is
  1972. * nil, or if C++ constructors fail.
  1973. **********************************************************************/
  1974. id
  1975. objc_constructInstance(Class cls, void *bytes)
  1976. {
  1977. if (!cls || !bytes) return nil;
  1978. id obj = (id)bytes;
  1979. obj->initIsa(cls);
  1980. if (cls->hasCxxCtor()) {
  1981. return object_cxxConstructFromClass(obj, cls, OBJECT_CONSTRUCT_NONE);
  1982. } else {
  1983. return obj;
  1984. }
  1985. }
  1986. /***********************************************************************
  1987. * _class_createInstanceFromZone. Allocate an instance of the
  1988. * specified class with the specified number of bytes for indexed
  1989. * variables, in the specified zone. The isa field is set to the
  1990. * class, C++ default constructors are called, and all other fields are zeroed.
  1991. **********************************************************************/
  1992. id
  1993. _class_createInstanceFromZone(Class cls, size_t extraBytes, void *zone)
  1994. {
  1995. void *bytes;
  1996. size_t size;
  1997. // Can't create something for nothing
  1998. if (!cls) return nil;
  1999. // Allocate and initialize
  2000. size = cls->alignedInstanceSize() + extraBytes;
  2001. // CF requires all objects be at least 16 bytes.
  2002. if (size < 16) size = 16;
  2003. if (zone) {
  2004. bytes = malloc_zone_calloc((malloc_zone_t *)zone, 1, size);
  2005. } else {
  2006. bytes = calloc(1, size);
  2007. }
  2008. return objc_constructInstance(cls, bytes);
  2009. }
  2010. /***********************************************************************
  2011. * _class_createInstance. Allocate an instance of the specified
  2012. * class with the specified number of bytes for indexed variables, in
  2013. * the default zone, using _class_createInstanceFromZone.
  2014. **********************************************************************/
  2015. static id _class_createInstance(Class cls, size_t extraBytes)
  2016. {
  2017. return _class_createInstanceFromZone (cls, extraBytes, nil);
  2018. }
  2019. static id _object_copyFromZone(id oldObj, size_t extraBytes, void *zone)
  2020. {
  2021. id obj;
  2022. size_t size;
  2023. if (!oldObj) return nil;
  2024. obj = (*_zoneAlloc)(oldObj->ISA(), extraBytes, zone);
  2025. size = oldObj->ISA()->alignedInstanceSize() + extraBytes;
  2026. // fixme need C++ copy constructor
  2027. memmove(obj, oldObj, size);
  2028. fixupCopiedIvars(obj, oldObj);
  2029. return obj;
  2030. }
  2031. /***********************************************************************
  2032. * objc_destructInstance
  2033. * Destroys an instance without freeing memory.
  2034. * Calls C++ destructors.
  2035. * Removes associative references.
  2036. * Returns `obj`. Does nothing if `obj` is nil.
  2037. * CoreFoundation and other clients do call this under GC.
  2038. **********************************************************************/
  2039. void *objc_destructInstance(id obj)
  2040. {
  2041. if (obj) {
  2042. Class isa = obj->getIsa();
  2043. if (isa->hasCxxDtor()) {
  2044. object_cxxDestruct(obj);
  2045. }
  2046. if (isa->instancesHaveAssociatedObjects()) {
  2047. _object_remove_assocations(obj);
  2048. }
  2049. objc_clear_deallocating(obj);
  2050. }
  2051. return obj;
  2052. }
  2053. static id
  2054. _object_dispose(id anObject)
  2055. {
  2056. if (anObject==nil) return nil;
  2057. objc_destructInstance(anObject);
  2058. anObject->initIsa(_objc_getFreedObjectClass ());
  2059. free(anObject);
  2060. return nil;
  2061. }
  2062. static id _object_copy(id oldObj, size_t extraBytes)
  2063. {
  2064. void *z = malloc_zone_from_ptr(oldObj);
  2065. return _object_copyFromZone(oldObj, extraBytes,
  2066. z ? z : malloc_default_zone());
  2067. }
  2068. static id _object_reallocFromZone(id anObject, size_t nBytes, void *zone)
  2069. {
  2070. id newObject;
  2071. Class tmp;
  2072. if (anObject == nil)
  2073. __objc_error(nil, "reallocating nil object");
  2074. if (anObject->ISA() == _objc_getFreedObjectClass ())
  2075. __objc_error(anObject, "reallocating freed object");
  2076. if (nBytes < anObject->ISA()->alignedInstanceSize())
  2077. __objc_error(anObject, "(%s, %zu) requested size too small",
  2078. object_getClassName(anObject), nBytes);
  2079. // fixme need C++ copy constructor
  2080. // fixme GC copy
  2081. // Make sure not to modify space that has been declared free
  2082. tmp = anObject->ISA();
  2083. anObject->initIsa(_objc_getFreedObjectClass ());
  2084. newObject = (id)malloc_zone_realloc((malloc_zone_t *)zone, anObject, nBytes);
  2085. if (newObject) {
  2086. newObject->initIsa(tmp);
  2087. } else {
  2088. // realloc failed, anObject is still alive
  2089. anObject->initIsa(tmp);
  2090. }
  2091. return newObject;
  2092. }
  2093. static id _object_realloc(id anObject, size_t nBytes)
  2094. {
  2095. void *z = malloc_zone_from_ptr(anObject);
  2096. return _object_reallocFromZone(anObject,
  2097. nBytes,
  2098. z ? z : malloc_default_zone());
  2099. }
  2100. id (*_alloc)(Class, size_t) = _class_createInstance;
  2101. id (*_copy)(id, size_t) = _object_copy;
  2102. id (*_realloc)(id, size_t) = _object_realloc;
  2103. id (*_dealloc)(id) = _object_dispose;
  2104. id (*_zoneAlloc)(Class, size_t, void *) = _class_createInstanceFromZone;
  2105. id (*_zoneCopy)(id, size_t, void *) = _object_copyFromZone;
  2106. id (*_zoneRealloc)(id, size_t, void *) = _object_reallocFromZone;
  2107. void (*_error)(id, const char *, va_list) = _objc_error;
  2108. id class_createInstance(Class cls, size_t extraBytes)
  2109. {
  2110. return (*_alloc)(cls, extraBytes);
  2111. }
  2112. id class_createInstanceFromZone(Class cls, size_t extraBytes, void *z)
  2113. {
  2114. OBJC_WARN_DEPRECATED;
  2115. return (*_zoneAlloc)(cls, extraBytes, z);
  2116. }
  2117. id
  2118. _objc_rootAllocWithZone(Class cls, malloc_zone_t *zone)
  2119. {
  2120. id obj;
  2121. if (fastpath(!zone)) {
  2122. obj = class_createInstance(cls, 0);
  2123. } else {
  2124. obj = class_createInstanceFromZone(cls, 0, zone);
  2125. }
  2126. if (slowpath(!obj)) obj = _objc_callBadAllocHandler(cls);
  2127. return obj;
  2128. }
  2129. unsigned class_createInstances(Class cls, size_t extraBytes,
  2130. id *results, unsigned num_requested)
  2131. {
  2132. if (_alloc == &_class_createInstance) {
  2133. return _class_createInstancesFromZone(cls, extraBytes, nil,
  2134. results, num_requested);
  2135. } else {
  2136. // _alloc in use, which isn't understood by the batch allocator
  2137. return 0;
  2138. }
  2139. }
  2140. id object_copy(id obj, size_t extraBytes)
  2141. {
  2142. return (*_copy)(obj, extraBytes);
  2143. }
  2144. id object_copyFromZone(id obj, size_t extraBytes, void *z)
  2145. {
  2146. OBJC_WARN_DEPRECATED;
  2147. return (*_zoneCopy)(obj, extraBytes, z);
  2148. }
  2149. id object_dispose(id obj)
  2150. {
  2151. return (*_dealloc)(obj);
  2152. }
  2153. id object_realloc(id obj, size_t nBytes)
  2154. {
  2155. OBJC_WARN_DEPRECATED;
  2156. return (*_realloc)(obj, nBytes);
  2157. }
  2158. id object_reallocFromZone(id obj, size_t nBytes, void *z)
  2159. {
  2160. OBJC_WARN_DEPRECATED;
  2161. return (*_zoneRealloc)(obj, nBytes, z);
  2162. }
  2163. /***********************************************************************
  2164. * object_getIndexedIvars.
  2165. **********************************************************************/
  2166. void *object_getIndexedIvars(id obj)
  2167. {
  2168. // ivars are tacked onto the end of the object
  2169. if (!obj) return nil;
  2170. if (obj->isTaggedPointer()) return nil;
  2171. return ((char *) obj) + obj->ISA()->alignedInstanceSize();
  2172. }
  2173. // ProKit SPI
  2174. Class class_setSuperclass(Class cls, Class newSuper)
  2175. {
  2176. Class oldSuper = cls->superclass;
  2177. set_superclass(cls, newSuper, NO);
  2178. flush_caches(cls, YES);
  2179. return oldSuper;
  2180. }
  2181. #endif