objc-class-old.mm 75 KB

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