-
OC对象
实例对象的isa & ISA_MASK = 类对象地址
类对象isa & ISA_MASK = 元类对象地址
源码:objc-runtime-new.h
objc_object
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117
struct objc_object { private: isa_t isa; public: // assumes this is NOT a tagged pointer object Class ISA(); // allows this to be a tagged pointer object Class getIsa(); // initIsa() should be used to init the isa of new objects only // If this object already has an isa, use changeIsa() for correctness. // initInstanceIsa(): objects with no custom RR/AWZ // initClassIsa(): class objects // initProtocolIsa(): protocol objects // initIsa(): other objects void initIsa(Class cls); void initClassIsa(Class cls); void initProtocolIsa(Class cls); void initInstanceIsa(Class cls, bool hasCxxDtor); // changeIsa() should be used to change the isa of existing objects // If this is a new object, use initIsa() for performance. Class changeIsa(Class newCls); bool hasNonpointerIsa(); bool isTaggedPointer(); bool isBasicTaggedPointer(); // objects may have associated objects? bool hasAssociatedObjects(); bool setHasAssociatedObjects(); // objects may be weakly referenced? bool isWeaklyReferenced(); bool setWeaklyReferenced_nolock(); //object may have -.cxx_destruct implementation? bool hasCxxDtor(); // Optimized calls to retain/release methods id retain(); void release(); id autorelease(); // Implementations of retain/release methods id rootRetain(); bool rootRelease(); id rootAutoRelease(); bool rootTryRetain(); bool rootReleaseShouldDealloc(); uintptr_t rootRetainCount(); // Implementation of dealloc methods bool rootIsDeallocating(); bool clearDeallocating(); bool rootDealloc(); private: void initIsa(Class newCls, bool nonpointer, bool hasCxxDtor); // Slow paths for inline control id rootAutorelease2(); uintptr_t overrelease_error(); #if SUPPORT_NONPOINTER_ISA // Controls what parts of root{Retain,Release} to emit/inline // - Full means the full (slow) implementation // - Fast means the fastpaths only // - FastOrMsgSend means the fastpaths but checking whether we should call // -retain/-release or Swift, for the usage of objc_{retain,release} enum class RRVariant { Full, Fast, FastOrMsgSend, }; // Unified retain count manipulation for nonpointer isa inline id rootRetain(bool tryRetain, RRVariant variant); inline bool rootRelease(bool performDealloc, RRVariant variant); id rootRetain_overflow(bool tryRetain); uintptr_t rootRelease_underflow(bool performDealloc); void clearDeallocating_slow(); // Side table retain count overflow for nonpointer isa struct SidetableBorrow { size_t borrowed, remaining; }; void sidetable_lock(); void sidetable_unlock(); void sidetable_moveExtraRC_nolock(size_t extra_rc, bool isDeallocating, bool weaklyReferenced); bool sidetable_addExtraRC_nolock(size_t delta_rc); SidetableBorrow sidetable_subExtraRC_nolock(size_t delta_rc); size_t sidetable_getExtraRC_nolock(); void sidetable_clearExtraRC_nolock(); #endif // Side-table-only retain count bool sidetable_isDeallocating(); void sidetable_clearDeallocating(); bool sidetable_isWeaklyReferenced(); void sidetable_setWeaklyReferenced_nolock(); id sidetable_retain(bool locked = false); id sidetable_retain_slow(SideTable& table); uintptr_t sidetable_release(bool locked = false, bool performDealloc = true); uintptr_t sidetable_release_slow(SideTable& table, bool performDealloc = true); bool sidetable_tryRetain(); uintptr_t sidetable_retainCount(); #if DEBUG bool sidetable_present(); #endif }
objc_class
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488
struct objc_class: objc_object { objc_class(const objc_class&) = delete; objc_class(objc_class&&) = delete; void operator=(const objc_class&) = delete; void operator=(objc_class&&) = delete; // Class ISA; Class superclass; cache_t cache; // formerly cache pointer and vtable class_data_bits_t bits; // class_rw_t * plus custom rr/alloc flags Class getSuperclass() const { #if __has_feature(ptrauth_calls) # if ISA_SIGNING_AUTH_MODE == ISA_SIGNING_AUTH if (superclass == Nil) return Nil; #if SUPERCLASS_SIGNING_TREAT_UNSIGNED_AS_NIL void *stripped = ptrauth_strip((void *)superclass, ISA_SIGNING_KEY); if ((void *)superclass == stripped) { void *resigned = ptrauth_sign_unauthenticated(stripped, ISA_SIGNING_KEY, ptrauth_blend_discriminator(&superclass, ISA_SIGNING_DISCRIMINATOR_CLASS_SUPERCLASS)); if ((void *)superclass != resigned) return Nil; } #endif void *result = ptrauth_auth_data((void *)superclass, ISA_SIGNING_KEY, ptrauth_blend_discriminator(&superclass, ISA_SIGNING_DISCRIMINATOR_CLASS_SUPERCLASS)); return (Class)result; # else return (Class)ptrauth_strip((void *)superclass, ISA_SIGNING_KEY); # endif #else return superclass; #endif } void setSuperclass(Class newSuperclass) { #if ISA_SIGNING_SIGN_MODE == ISA_SIGNING_SIGN_ALL superclass = (Class)ptrauth_sign_unauthenticated((void *)newSuperclass, ISA_SIGNING_KEY, ptrauth_blend_discriminator(&superclass, ISA_SIGNING_DISCRIMINATOR_CLASS_SUPERCLASS)); #else superclass = newSuperclass; #endif } class_rw_t *data() const { return bits.data(); } void setData(class_rw_t *newData) { bits.setData(newData); } void setInfo(uint32_t set) { ASSERT(isFuture() || isRealized()); data()->setFlags(set); } void clearInfo(uint32_t clear) { ASSERT(isFuture() || isRealized()); data()->clearFlags(clear); } // set and clear must not overlap void changeInfo(uint32_t set, uint32_t clear) { ASSERT(isFuture() || isRealized()); ASSERT((set & clear) == 0); data()->changeFlags(set, clear); } #if FAST_HAS_DEFAULT_RR bool hasCustomRR() const { return !bits.getBit(FAST_HAS_DEFAULT_RR); } void setHasDefaultRR() { bits.setBits(FAST_HAS_DEFAULT_RR); } void setHasCustomRR() { bits.clearBits(FAST_HAS_DEFAULT_RR); } #else bool hasCustomRR() const { return !(bits.data()->flags & RW_HAS_DEFAULT_RR); } void setHasDefaultRR() { bits.data()->setFlags(RW_HAS_DEFAULT_RR); } void setHasCustomRR() { bits.data()->clearFlags(RW_HAS_DEFAULT_RR); } #endif #if FAST_CACHE_HAS_DEFAULT_AWZ bool hasCustomAWZ() const { return !cache.getBit(FAST_CACHE_HAS_DEFAULT_AWZ); } void setHasDefaultAWZ() { cache.setBit(FAST_CACHE_HAS_DEFAULT_AWZ); } void setHasCustomAWZ() { cache.clearBit(FAST_CACHE_HAS_DEFAULT_AWZ); } #else bool hasCustomAWZ() const { return !(bits.data()->flags & RW_HAS_DEFAULT_AWZ); } void setHasDefaultAWZ() { bits.data()->setFlags(RW_HAS_DEFAULT_AWZ); } void setHasCustomAWZ() { bits.data()->clearFlags(RW_HAS_DEFAULT_AWZ); } #endif #if FAST_CACHE_HAS_DEFAULT_CORE bool hasCustomCore() const { return !cache.getBit(FAST_CACHE_HAS_DEFAULT_CORE); } void setHasDefaultCore() { return cache.setBit(FAST_CACHE_HAS_DEFAULT_CORE); } void setHasCustomCore() { return cache.clearBit(FAST_CACHE_HAS_DEFAULT_CORE); } #else bool hasCustomCore() const { return !(bits.data()->flags & RW_HAS_DEFAULT_CORE); } void setHasDefaultCore() { bits.data()->setFlags(RW_HAS_DEFAULT_CORE); } void setHasCustomCore() { bits.data()->clearFlags(RW_HAS_DEFAULT_CORE); } #endif #if FAST_CACHE_HAS_CXX_CTOR bool hasCxxCtor() { ASSERT(isRealized()); return cache.getBit(FAST_CACHE_HAS_CXX_CTOR); } void setHasCxxCtor() { cache.setBit(FAST_CACHE_HAS_CXX_CTOR); } #else bool hasCxxCtor() { ASSERT(isRealized()); return bits.data()->flags & RW_HAS_CXX_CTOR; } void setHasCxxCtor() { bits.data()->setFlags(RW_HAS_CXX_CTOR); } #endif #if FAST_CACHE_HAS_CXX_DTOR bool hasCxxDtor() { ASSERT(isRealized()); return cache.getBit(FAST_CACHE_HAS_CXX_DTOR); } void setHasCxxDtor() { cache.setBit(FAST_CACHE_HAS_CXX_DTOR); } #else bool hasCxxDtor() { ASSERT(isRealized()); return bits.data()->flags & RW_HAS_CXX_DTOR; } void setHasCxxDtor() { bits.data()->setFlags(RW_HAS_CXX_DTOR); } #endif if FAST_CACHE_REQUIRES_RAW_ISA bool instancesRequireRawIsa() { return cache.getBit(FAST_CACHE_REQUIRES_RAW_ISA); } void setInstancesRequireRawIsa() { cache.setBit(FAST_CACHE_REQUIRES_RAW_ISA); } #elif SUPPORT_NONPOINTER_ISA bool instancesRequireRawIsa() { return bits.data()->flags & RW_REQUIRES_RAW_ISA; } void setInstancesRequireRawIsa() { bits.data()->setFlags(RW_REQUIRES_RAW_ISA); } #else bool instancesRequireRawIsa() { return true; } void setInstancesRequireRawIsa() { // nothing } #endif void setInstancesRequireRawIsaRecursively(bool inherited = false); void printInstancesRequireRawIsa(bool inherited); #if CONFIG_USE_PREOPT_CACHES bool allowsPreoptCaches() const { return !(bits.data()->flags & RW_NOPREOPT_CACHE); } bool allowsPreoptInlinedSels() const { return !(bits.data()->flags & RW_NOPREOPT_SELS); } void setDisallowPreoptCaches() { bits.data()->setFlags(RW_NOPREOPT_CACHE | RW_NOPREOPT_SELS); } void setDisallowPreoptInlinedSels() { bits.data()->setFlags(RW_NOPREOPT_SELS); } void setDisallowPreoptCachesRecursively(const char *why); void setDisallowPreoptInlinedSelsRecursively(const char *why); #else bool allowsPreoptCaches() const { return false; } bool allowsPreoptInlinedSels() const { return false; } void setDisallowPreoptCaches() { } void setDisallowPreoptInlinedSels() { } void setDisallowPreoptCachesRecursively(const char *why) { } void setDisallowPreoptInlinedSelsRecursively(const char *why) { } #endif bool canAllocNonpointer() { ASSERT(!isFuture()); return !instancesRequireRawIsa(); } bool isSwiftStable() { return bits.isSwiftStable(); } bool isSwiftLegacy() { return bits.isSwiftLegacy(); } bool isAnySwift() { return bits.isAnySwift(); } bool isSwiftStable_ButAllowLegacyForNow() { return bits.isSwiftStable_ButAllowLegacyForNow(); } uint32_t swiftClassFlags() { return *(uint32_t *)(&bits + 1); } bool usesSwiftRefcounting() { if (!isSwiftStable()) return false; return bool(swiftClassFlags() & 2); //ClassFlags::UsesSwiftRefcounting } bool canCallSwiftRR() { // !hasCustomCore() is being used as a proxy for isInitialized(). All // classes with Swift refcounting are !hasCustomCore() (unless there are // category or swizzling shenanigans), but that bit is not set until a // class is initialized. Checking isInitialized requires an extra // indirection that we want to avoid on RR fast paths. // // In the unlikely event that someone causes a class with Swift // refcounting to be hasCustomCore(), we'll fall back to sending -retain // or -release, which is still correct. return !hasCustomCore() && usesSwiftRefcounting(); } bool isStubClass() const { uintptr_t isa = (uintptr_t)isaBits(); return 1 <= isa && isa < 16; } // Swift stable ABI built for old deployment targets looks weird. // The is-legacy bit is set for compatibility with old libobjc. // We are on a "new" deployment target so we need to rewrite that bit. // These stable-with-legacy-bit classes are distinguished from real // legacy classes using another bit in the Swift data // (ClassFlags::IsSwiftPreStableABI) bool isUnfixedBackwardDeployingStableSwift() { // Only classes marked as Swift legacy need apply. if (!bits.isSwiftLegacy()) return false; // Check the true legacy vs stable distinguisher. // The low bit of Swift's ClassFlags is SET for true legacy // and UNSET for stable pretending to be legacy. bool isActuallySwiftLegacy = bool(swiftClassFlags() & 1); return !isActuallySwiftLegacy; } void fixupBackwardDeployingStableSwift() { if (isUnfixedBackwardDeployingStableSwift()) { // Class really is stable Swift, pretending to be pre-stable. // Fix its lie. bits.setIsSwiftStable(); } } _objc_swiftMetadataInitializer swiftMetadataInitializer() { return bits.swiftMetadataInitializer(); } // Return YES if the class's ivars are managed by ARC, // or the class is MRC but has ARC-style weak ivars. bool hasAutomaticIvars() { return data()->ro()->flags & (RO_IS_ARC | RO_HAS_WEAK_WITHOUT_ARC); } // Return YES if the class's ivars are managed by ARC. bool isARC() { return data()->ro()->flags & RO_IS_ARC; } bool forbidsAssociatedObjects() { return (data()->flags & RW_FORBIDS_ASSOCIATED_OBJECTS); } #if SUPPORT_NONPOINTER_ISA // Tracked in non-pointer isas; not tracked otherwise #else bool instancesHaveAssociatedObjects() { // this may be an unrealized future class in the CF-bridged case ASSERT(isFuture() || isRealized()); return data()->flags & RW_INSTANCES_HAVE_ASSOCIATED_OBJECTS; } void setInstancesHaveAssociatedObjects() { // this may be an unrealized future class in the CF-bridged case ASSERT(isFuture() || isRealized()); setInfo(RW_INSTANCES_HAVE_ASSOCIATED_OBJECTS); } #endif bool shouldGrowCache() { return true; } void setShouldGrowCache(bool) { // fixme good or bad for memory use? } bool isInitializing() { return getMeta()->data()->flags & RW_INITIALIZING; } void setInitializing() { ASSERT(!isMetaClass()); ISA()->setInfo(RW_INITIALIZING); } bool isInitialized() { return getMeta()->data()->flags & RW_INITIALIZED; } void setInitialized(); bool isLoadable() { ASSERT(isRealized()); return true; // any class registered for +load is definitely loadable } IMP getLoadMethod(); // Locking: To prevent concurrent realization, hold runtimeLock. bool isRealized() const { return !isStubClass() && (data()->flags & RW_REALIZED); } // Returns true if this is an unrealized future class. // Locking: To prevent concurrent realization, hold runtimeLock. bool isFuture() const { if (isStubClass()) return false; return data()->flags & RW_FUTURE; } bool isMetaClass() const { ASSERT_THIS_NOT_NULL; ASSERT(isRealized()); #if FAST_CACHE_META return cache.getBit(FAST_CACHE_META); #else return data()->flags & RW_META; #endif } // Like isMetaClass, but also valid on un-realized classes bool isMetaClassMaybeUnrealized() { static_assert(offsetof(class_rw_t, flags) == offsetof(class_ro_t, flags), "flags alias"); static_assert(RO_META == RW_META, "flags alias"); if (isStubClass()) return false; return data()->flags & RW_META; } // NOT identical to this->ISA when this is a metaclass Class getMeta() { if (isMetaClassMaybeUnrealized()) return (Class)this; else return this->ISA(); } bool isRootClass() { return getSuperclass() == nil; } bool isRootMetaclass() { return ISA() == (Class)this; } // If this class does not have a name already, we can ask Swift to construct one for us. const char *installMangledNameForLazilyNamedClass(); // Get the class's mangled name, or NULL if the class has a lazy // name that hasn't been created yet. const char *nonlazyMangledName() const { return bits.safe_ro()->getName(); } const char *mangledName() { // fixme can't assert locks here ASSERT_THIS_NOT_NULL; const char *result = nonlazyMangledName(); if (!result) { // This class lazily instantiates its name. Emplace and // return it. result = installMangledNameForLazilyNamedClass(); } return result; } const char *demangledName(bool needsLock); const char *nameForLogging(); // May be unaligned depending on class's ivars. uint32_t unalignedInstanceStart() const { ASSERT(isRealized()); return data()->ro()->instanceStart; } // Class's instance start rounded up to a pointer-size boundary. // This is used for ARC layout bitmaps. uint32_t alignedInstanceStart() const { return word_align(unalignedInstanceStart()); } // May be unaligned depending on class's ivars. uint32_t unalignedInstanceSize() const { ASSERT(isRealized()); return data()->ro()->instanceSize; } // Class's ivar size rounded up to a pointer-size boundary. uint32_t alignedInstanceSize() const { return word_align(unalignedInstanceSize()); } inline size_t instanceSize(size_t extraBytes) const { if (fastpath(cache.hasFastInstanceSize(extraBytes))) { return cache.fastInstanceSize(extraBytes); } size_t size = alignedInstanceSize() + extraBytes; // CF requires all objects be at least 16 bytes. if (size < 16) size = 16; return size; } void setInstanceSize(uint32_t newSize) { ASSERT(isRealized()); ASSERT(data()->flags & RW_REALIZING); auto ro = data()->ro(); if (newSize != ro->instanceSize) { ASSERT(data()->flags & RW_COPIED_RO); *const_cast<uint32_t *>(&ro->instanceSize) = newSize; } cache.setFastInstanceSize(newSize); } void chooseClassArrayIndex(); void setClassArrayIndex(unsigned Idx) { bits.setClassArrayIndex(Idx); } unsigned classArrayIndex() { return bits.classArrayIndex(); } }
class_rw_ext_t
1 2 3 4 5 6 7 8 9
struct class_rw_ext_t { DECLARE_AUTHED_PTR_TEMPLATE(class_ro_t) class_ro_t_authed_ptr<const class_ro_t> ro; method_array_t methods; property_array_t properties; protocol_array_t protocols; char *demangledName; uint32_t version; };
class_ro_t
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
struct class_ro_t { uint32_t flags; uint32_t instanceStart; uint32_t instanceSize; #ifdef __LP64__ uint32_t reserved; #endif union { const uint8_t * ivarLayout; Class nonMetaclass; }; explicit_atomic<const char *> name; // With ptrauth, this is signed if it points to a small list, but // may be unsigned if it points to a big list. void *baseMethodList; protocol_list_t * baseProtocols; const ivar_list_t * ivars; const uint8_t * weakIvarLayout; property_list_t *baseProperties; }
class_rw_t
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113
struct class_rw_t { uint32_t flags; uint16_t witness; #if SUPPORT_INDEXED_ISA uint16_t index; #endif explicit_atomic<uintptr_t> ro_or_rw_ext; Class firstSubclass; Class nextSiblingClass; private: using ro_or_rw_ext_t = objc::PointerUnion<const class_ro_t, class_rw_ext_t, PTRAUTH_STR("class_ro_t"), PTRAUTH_STR("class_rw_ext_t")>; const ro_or_rw_ext_t get_ro_or_rwe() const { return ro_or_rw_ext_t{ro_or_rw_ext}; } void set_ro_or_rwe(const class_ro_t *ro) { ro_or_rw_ext_t{ro, &ro_or_rw_ext}.storeAt(ro_or_rw_ext, memory_order_relaxed); } void set_ro_or_rwe(class_rw_ext_t *rwe, const class_ro_t *ro) { // the release barrier is so that the class_rw_ext_t::ro initialization // is visible to lockless readers rwe->ro = ro; ro_or_rw_ext_t{rwe, &ro_or_rw_ext}.storeAt(ro_or_rw_ext, memory_order_release); } public: void setFlags(uint32_t set) { __c11_atomic_fetch_or((_Atomic(uint32_t) *)&flags, set, __ATOMIC_RELAXED); } void clearFlags(uint32_t clear) { __c11_atomic_fetch_and((_Atomic(uint32_t) *)&flags, ~clear, __ATOMIC_RELAXED); } // set and clear must not overlap void changeFlags(uint32_t set, uint32_t clear) { ASSERT((set & clear) == 0); uint32_t oldf, newf; do { oldf = flags; newf = (oldf | set) & ~clear; } while (!OSAtomicCompareAndSwap32Barrier(oldf, newf, (volatile int32_t *)&flags)); } class_rw_ext_t *ext() const { return get_ro_or_rwe().dyn_cast<class_rw_ext_t *>(&ro_or_rw_ext); } class_rw_ext_t *extAllocIfNeeded() { auto v = get_ro_or_rwe(); if (fastpath(v.is<class_rw_ext_t *>())) { return v.get<class_rw_ext_t *>(&ro_or_rw_ext); } else { return extAlloc(v.get<const class_ro_t *>(&ro_or_rw_ext)); } } class_rw_ext_t *deepCopy(const class_ro_t *ro) { return extAlloc(ro, true); } const class_ro_t *ro() const { auto v = get_ro_or_rwe(); if (slowpath(v.is<class_rw_ext_t *>())) { return v.get<class_rw_ext_t *>(&ro_or_rw_ext)->ro; } return v.get<const class_ro_t *>(&ro_or_rw_ext); } void set_ro(const class_ro_t *ro) { auto v = get_ro_or_rwe(); if (v.is<class_rw_ext_t *>()) { v.get<class_rw_ext_t *>(&ro_or_rw_ext)->ro = ro; } else { set_ro_or_rwe(ro); } } const method_array_t methods() const { auto v = get_ro_or_rwe(); if (v.is<class_rw_ext_t *>()) { return v.get<class_rw_ext_t *>(&ro_or_rw_ext)->methods; } else { return method_array_t{v.get<const class_ro_t *>(&ro_or_rw_ext)->baseMethods()}; } } const property_array_t properties() const { auto v = get_ro_or_rwe(); if (v.is<class_rw_ext_t *>()) { return v.get<class_rw_ext_t *>(&ro_or_rw_ext)->properties; } else { return property_array_t{v.get<const class_ro_t *>(&ro_or_rw_ext)->baseProperties}; } } const protocol_array_t protocols() const { auto v = get_ro_or_rwe(); if (v.is<class_rw_ext_t *>()) { return v.get<class_rw_ext_t *>(&ro_or_rw_ext)->protocols; } else { return protocol_array_t{v.get<const class_ro_t *>(&ro_or_rw_ext)->baseProtocols}; } } }
class_data_bits_t
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109
struct class_data_bits_t { friend objc_class; // Values are the FAST_ flags above. uintptr_t bits; private: bool getBit(uintptr_t bit) const { return bits & bit; } // Atomically set the bits in `set` and clear the bits in `clear`. // set and clear must not overlap. void setAndClearBits(uintptr_t set, uintptr_t clear) { ASSERT((set & clear) == 0); uintptr_t newBits, oldBits = LoadExclusive(&bits); do { newBits = (oldBits | set) & ~clear; } while (slowpath(!StoreReleaseExclusive(&bits, &oldBits, newBits))); } void setBits(uintptr_t set) { __c11_atomic_fetch_or((_Atomic(uintptr_t) *)&bits, set, __ATOMIC_RELAXED); } void clearBits(uintptr_t clear) { __c11_atomic_fetch_and((_Atomic(uintptr_t) *)&bits, ~clear, __ATOMIC_RELAXED); } public: class_rw_t* data() const { return (class_rw_t *)(bits & FAST_DATA_MASK); } void setData(class_rw_t *newData) { ASSERT(!data() || (newData->flags & (RW_REALIZING | RW_FUTURE))); // Set during realization or construction only. No locking needed. // Use a store-release fence because there may be concurrent // readers of data and data's contents. uintptr_t newBits = (bits & ~FAST_DATA_MASK) | (uintptr_t)newData; atomic_thread_fence(memory_order_release); bits = newBits; } // Get the class's ro data, even in the presence of concurrent realization. // fixme this isn't really safe without a compiler barrier at least // and probably a memory barrier when realizeClass changes the data field const class_ro_t *safe_ro() const { class_rw_t *maybe_rw = data(); if (maybe_rw->flags & RW_REALIZED) { // maybe_rw is rw return maybe_rw->ro(); } else { // maybe_rw is actually ro return (class_ro_t *)maybe_rw; } } #if SUPPORT_INDEXED_ISA void setClassArrayIndex(unsigned Idx) { // 0 is unused as then we can rely on zero-initialisation from calloc. ASSERT(Idx > 0); data()->index = Idx; } #else void setClassArrayIndex(__unused unsigned Idx) { } #endif unsigned classArrayIndex() { #if SUPPORT_INDEXED_ISA return data()->index; #else return 0; #endif } bool isAnySwift() { return isSwiftStable() || isSwiftLegacy(); } bool isSwiftStable() { return getBit(FAST_IS_SWIFT_STABLE); } void setIsSwiftStable() { setAndClearBits(FAST_IS_SWIFT_STABLE, FAST_IS_SWIFT_LEGACY); } bool isSwiftLegacy() { return getBit(FAST_IS_SWIFT_LEGACY); } void setIsSwiftLegacy() { setAndClearBits(FAST_IS_SWIFT_LEGACY, FAST_IS_SWIFT_STABLE); } // fixme remove this once the Swift runtime uses the stable bits bool isSwiftStable_ButAllowLegacyForNow() { return isAnySwift(); } _objc_swiftMetadataInitializer swiftMetadataInitializer() { // This function is called on un-realized classes without // holding any locks. // Beware of races with other realizers. return safe_ro()->swiftMetadataInitializer(); } };
isa_t
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
union isa_t { isa_t() { } isa_t(uintptr_t value) : bits(value) { } uintptr_t bits; private: // Accessing the class requires custom ptrauth operations, so // force clients to go through setClass/getClass by making this // private. Class cls; public: #if defined(ISA_BITFIELD) struct { ISA_BITFIELD; // defined in isa.h }; bool isDeallocating() { return extra_rc == 0 && has_sidetable_rc == 0; } void setDeallocating() { extra_rc = 0; has_sidetable_rc = 0; } #endif void setClass(Class cls, objc_object *obj); Class getClass(bool authenticated); Class getDecodedClass(bool authenticated); };
isa.h
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
# define ISA_MASK 0x0000000ffffffff8ULL # define ISA_MAGIC_MASK 0x000003f000000001ULL # define ISA_MAGIC_VALUE 0x000001a000000001ULL # define ISA_HAS_CXX_DTOR_BIT 1 # define ISA_BITFIELD \ uintptr_t nonpointer : 1; \ uintptr_t has_assoc : 1; \ uintptr_t has_cxx_dtor : 1; \ uintptr_t shiftcls : 33; /*MACH_VM_MAX_ADDRESS 0x1000000000*/ \ uintptr_t magic : 6; \ uintptr_t weakly_referenced : 1; \ uintptr_t unused : 1; \ uintptr_t has_sidetable_rc : 1; \ uintptr_t extra_rc : 19 # define RC_ONE (1ULL<<45) # define RC_HALF (1ULL<<18)
-
数据结构和算法
a. 练习学过的常用的
b. 学习新的(已算法为主)
二叉树
搜索二叉树
遍历(前序,中序,后序,广度,深度)
排序算法
二叉树深度
二叉树某层节点数
字符串相关算符
前缀
两数和
堆
栈
队列
-
iOS app性能优化
练习讲解
cpu
gpu
-
https
练习讲解
-
weak
练习讲解
-
runloop
练习讲解
modes
commonModes
currentMode
performSelect:withObject:afterDelay
本质是往runloop添加定时器
mode
timers
sources
source0
source1
observers
-
定时器
NSTimer
依赖于runloop,内部会对target强引用,使用时注意循环引用
不准确
CFDisplay
依赖于runloop,内部会对target强引用,使用时注意循环引用
调用频率云屏幕的刷新频率一致, 60FPS
CGD Timer (不依赖runloop)
-
NSProxy
遵守NSObject协议
跟NSObject同一级别
方法调用:如果自己没有实现,会直接来到转发阶段的methodSignatureForSelector:,因此效率较高
没有init方法
一些身份识别的方法也都返回代理对象的身份
-
autorelease
练习讲解
与runloop的联系
当前线程的当前loop即将休眠时释放
autoreleasepool
存储结构为poolPage的一个链表
通过申明一个局部结构体变量
pool开始时进行push操作(调用结构体上的构造方法),返回一个tag,在poolPage的某处压入一个标记值
pool结束时进行pop操作(调用结构体上的析构方法),从当前位置对存储的每一个对象进行release操作,知道遇到之前压入的标记值为止
-
copy
拷贝的目的就是产生一份全新的副本
如果原来的对象不可变,对其进行copy,由于产生的副本也不可变,因此浅拷贝即可
其余都是深拷贝
如果对象的某个属性用copy修饰,且其为可变类型,注意本质上copy产生不可变对象,所以在其上调用不可变类型的方法会因找不到方法而奔溃
-
程序内存布局
代码段(.text)
数据段 (.data)
堆段(heap)// 低地址到高地址增长
栈段(stack)// 高地址到低地址增长
-
内存管理
TaggedPointer技术
对于NSDate, NSNumber, NSSString等小对象
当值比较小的时候,将其直接存储在指针里
方法调用时会根据TaggedPointer做区别对待,不会走消息机制去查找方法实现
iOS平台如果地址的高位是1,则标识用了TaggedPointer存储技术
copy, strong的setter实现
判等,如果不等,则旧对象做release操作,新对象做retain/copy操作,并赋值
-
block
数据结构
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
struct __block_impl { void *isa; int Flags; int Reserved; void *FuncPtr; } struct __main_block_desc_0 { size_t reserved; size_t Block_size; (void *(void*, void*))copy; // 用于管理捕获的对象类型的内存 (void *(void*)) dispose; // 用于管理捕获的对象类型的内存 } struct __main_block_impl_0 { struct __block_impl impl; struct __main_block_desc_0* Desc; ... //捕获进来的变量 }
类型
__NSGlobalBlock__ (继承自NSBlock,存储在数据区, 没有访问或捕获auto变量)
__NSStackBlock__ (继承自NSBlock,存储在栈区,访问或捕获了auto变量)
__NSMallocBlock__ (继承自NSBlock,存储在堆区)
stack block调用copy, 变为malloc block
global block调用copy, 没有作用
malloc block调用copy, 增加引用计数
ARC下某些情况下,编译器会自动对stack block调用copy,变为malloc block
最为函数返回值时
将block赋值给强指针时
作为方法名含有usingBlock的cocoa ap的参数时
stack block不会引用捕获的对象类型
malloc block会引用捕获的对象类型(如果auto变量是__strong,就强引用;如果是__weak, 就弱引用)
变量捕获
局部auto: 值传递捕获
局部static: 指针传递捕获
全局变量:直接访问,不捕获
block属性的建议写法
MRC下用copy
ARC下用strong, copy都可
__block
修改auto变量的值
不能修饰static和global变量
会把捕获的auto变量包装成以下结构
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
struct __Block_byref_age_0 { viod *__isa; __Block_byref_age_0 *__forwarding; int __flags; int __size; int age; } struct __Block_byref_obj_1 { void *__isa; __Block_byref_obj_1 *__forwarding; int __flags; int __size; void (*__Block_byref_id_object_copy)(void*, void*); void (*__Block_byref_id_object_dispose)(void*); NSObject *obj; } struct __main_block_impl_0 { struct __block_impl impl; struct __main_block_desc_0* Desc; __Block_byref_age_0 *age; //强引用 }
暴露给外面访问的变量也是这个结构体中的变量: age.forwarding.age
当block拷贝到堆上时,会拷贝引用的这个包装对象到堆上
blcok对这个包装结构强引用
ARC下被包装对象如果时__strong(默认)就强引用,如果是__weak就i弱引用
MRC下被包装的对象不会被强引用,而是弱引用
循环引用问题
__weak(ARC)
__unsafe_unretained(ARC, MRC)
__block(MRC)
-
runtime
练习讲解
验证疑惑
在子类上交换子类没有实现而父类实现的方法
1 2 3 4
func class_getInstanceMethod( _ cls: AnyClass?, _ name: Selector ) -> Method?
Note that this function searches superclasses for implementations, whereas
class_copyMethodList(_:_:)
does not.hook
-
关联对象
练习讲解
isa有是否设置过关联对象的存储位
通过关联对象及运行时实现给分类添加属性
关联对象存储在一个全局的类似哈希表的一个结构中
-
消息机制
练习讲解
消息发送
对象方法调用:通过实例对象里存储的isa指针找到类对象,首先在在类对象的cache(一个以Sel为key,方法实现为值的哈希表)里找,如果没有命中缓存,则在方法列表里查找,如果当前类的方法列表里没有找到,则沿着类对象的继承链往上找,如果找到即存入缓存并调用
动态解析
resolveInstanceMethod
resolveClassMethod
可以通过动态添加实现,并return YES; 重新开始查找
消息转发
可以在forwardTarget中返回某个对象,把方法处理转交给返回的对象
如果上面方法没有实现,则有机会在methodSignature返回方法签名,forwardInvocation做进一步处理
-
iOS多线程
练习讲解
pthread (生命周期程序员管理),使用较少,难度较大
NSThread (生命周期程序员管理),使用较少,使用更加面向对象,简单易用
GCD (自动管理),常用
只要是同步就不会开启新线程
主队列中就算异步也不会开启新线程,主队列中的任务就是在主线程执行的
NSOperation(基于GCD),常用,使用更加面向对象
Telegram线程相关
a. 保活 (MediaPlayer解码)
b. db数据读写
死锁
一般串行,同步会死锁
死锁条件
资源互斥访问,即每个资源每次只能给一个进程使用(也是资源有限的必要条件)
不剥夺,即不能强行占用已分配给其他进程的资源
请求和保持,即已经分配到的资源不释放,并请求其他资源
环形等待,即形成一个资源请求或等待回路
预防死锁
资源独占,只有所有资源都可满足,才投入运行,即不会存在资源竞争对手
资源顺序分配,即把资源分级,优先申请较低级的资源,优先释放较高级的资源,这样就不会出现环路
银行家算法,分配之前进行安全性检查(按最大需求预分配,看会不会死锁),比较保守,分配矩阵(Allocation);需求矩阵(Need);最大需求矩阵(Maxreq);可用资源向量Available, Maxreq[i][j] = Need[i][j] + Allocation[i][j]; 尝试分配资源给进程pi, 资源请求矩阵Request,Available[j] := Available[j] - Request[i][j], Allocation[i][j] := Allocation[i][j] + Request[i][j]; Need[i][j] := Need[i][j] - Request[i][j]
发现死锁
进程资源图:资源用举行表示,资源个数用包含在矩形中的小圆点表示,进程用大圆表示;请求用进程指向资源的单向箭头表示;分配用资源指向进程的单向箭头表示
化简进程资源图:试图满足进程的请求,即请求变分配,如果能把所有请求变为分配,则删除所有分配,把该进程变成孤立点
如果能完全化简则不存在死锁,否则存在
解除死锁
资源剥夺,按最小代价来,强行剥夺足够数量的资源分配给死锁进程,以解除死锁状态
撤销进程,按某种顺序逐渐撤销死锁进程,知道获得为接触死锁所需要的足够可用的资源为止
优先级反转(Priority Inversion)wiki
线程 H, M, L, 优先级关系为:P(H) > P(M) > P(L)
H,L同时竞争资源R(或依赖于资源R),而M不要R(或不依赖资源R)
L先得到了R,开始运行
H由于等待R而阻塞
如果M抢占了L的CPU(由于优先级较高),就会造成L不能及时释放资源R
高优先级的H就间接被低优先级的M阻塞了
优先级反转有时不会带来直接危害,这种情况下高优先级的线程被延迟的不那么明显,L最终也能释放共享资源R
然而许多情况下优先级反转会造成严重问题。如果高优先级的线程对于R已经很饥渴了,也就是延迟严重,等了很久了,可能会造成系统故障或者触发系统预定义的一些措施,比如watchdog timer可能会重置整个系统
优先级反转也可能会降低系统的感知性能。低优先级的任务往往由于其是否能即使结束不太重要而优先级较低(例如可能是一个批处理作业,或者非交互性活动)。而高优先级的任务更可能受限于严格的时间限制,(如可能正在向交互式用户提供数据,或者受实时响应保证的约束)
OSSpinLock
等待锁的线程处于忙等状态,一直占用着CPU资源
不再安全,可能会出现优先级反转问题
如果等待锁的线程优先级较高,由于它一直占用着CPU资源,优先级较低的线程可能会无法释放锁
导入头文件 <libkern/OSAtomic.h>
os_unfair_lock
#import <os/lock.h>
OSSpinLock的替代方案
os_unfair_lock lock = OS_UNFAIR_LOCK_INIT;
os_unfair_lock_lock(&lock);
os_unfair_lock_trylock(&lock);
os_unfair_lock_unlock(&lock);
pthread_mutex
#import
pthread_mutexattr_t attr;
pthread_mutexattr_init(&attr);
pthread_mutextattr_settype(&attr, PTHREAD_MUTEX_NORMAL)
pthread_mutex_t mutext;
pthread_mutex_init(&mutex, &attr);
pthread_mutex_lock(&mutex);
pthread_mutex_trylock(&mutex);
pthread_mutex_unlock(&mutex);
pthread_mutexattr_destory(&attr);
pthread_mutext_destroy(&mutex)
pthread_cond_t
pthread_cond_t condition;
pthread_cond_init(&condition, NULL);
pthread_cond_wait(&condition, &mutex);
pthrad_cond_signal(&condition);
pthread_cond_broadcast(&condition);
pthread_cond_destory(&condition)
pthread_rwlock (读写锁)
#import
多读单写
pthread_rwlock_t lock;
pthread_rwlock_init(&lock, NULL);
pthread_rwlock_rdlock(&lock);
pthread_rwlock_tryrdlock(&lock);
pthread_rwlock_wrlock(&lock);
pthread_rwlock_trywrlock(&lock);
pthread_rwlock_unlock(&lock);
pthread_rwlock_destory(&lock);
dispatch_barrier_async (异步栅栏函数)
NSLock
对pthread_mutex普通锁的封装
相当于pthread_mutex_init(&lock, NULL),或者pthread_mutextattr_settype(&attr, PTHREAD_MUTEX_NORMAL)
NSRecursiveLock
对pthread_mutex递归锁的封装
相当于pthread_mutextattr_settype(&lock, PTHREAD_MUTEX_RECURSIVE)
NSCondition
对mutext和cond的封装
wait
signal
broadcast
waitUntilDate:
NSConditionLock
对NSCondition的进一步封装
可以设置具体的条件值
-
app架构
练习讲解
MVVM
-
RxSwift
-
进程调度
分级轮转
由于高优先级阻塞进入高优先级队列
时间片用完进入低优先级队列
一般情况下,调度算法把相同的时间片分配给前台就绪队列的进程,优先满足其需要。只有当前台队列中的所有进程全部运行完毕或因等待I/O操作而没有进程可运行时,才把处理机分配给后台就绪进程,分得处理机的就绪进程立即投入运行。
通常后台就绪进程于前台就绪进程分得的时间片有差异,对长作业可以采取增长时间片的办法来弥补。例如,若短作业的执行时间为50ms,而长作业的时间片可增长到150ms,这就大大降低了长作业的交换频率,减少了系统再交换作业时的时间消耗,提高了系统的效率。
优先级法
把处理机分配给就绪队列中具有最高优先级的就绪进程
根据已占有处理机的进程是否可被剥夺这一原则,分为优先占有法和有效剥夺法
优先占有法
一旦某个最高优先级的就绪进程分得处理机之后,只要不是其自身的原因被阻塞(如要求I/O操作)而不能继续运行时,就一直运行下去,直至运行结束。
优先剥夺法
当一个正在运行的进程其时间片未用完时,无论什么时候,只要就绪队列中有一个比它优先级更高的进程,优先级高的进程就可以取代目前正在运行的进程,投入运行
静态优先级确定
进程类型
系统进程比用户进程具有较高的优先级(设备进程优于前后台用户作业进程)
特别时某些具有频繁I/O要求的进程,必须赋予它一种特权,当它需要处理机时,应尽量得到满足
前台用户进程由于后台用户进程
联机操作用户进程的优先级高于脱机用户进程的优先级
对计算量大的进程所请求的I/O给与一个高优先级
运行时间
通常规定进程优先级于进程所需运行时间成反比
此种方法对于长作业用户来说,有可能长时间等待而得不到运行的机会
作业的优先级
根据作业的优先级来决定其所属进程的优先
级
一种常用于多道批处理系统的方法时,系统把用户作业卡上提供的外部优先级赋给该作业及其所创建的进程
动态优先级
进程的优先级在该进程的生存期间可以改变
大多数动态优先级方案设计成:把交互式和I/O频繁的进程移到优先级队列的顶端;而让计算量大的进程移到较低的优先级上。
对于一定时间周期,一个正在运行的进程,没请求一次I/O操作后其优先级就自动加1,显然此进程的优先级直接反映出I/O请求的频率,从而使I/O设备有很高的利用率
在每级内按先来先服务或轮转法则分配处理机
-
设计模式(主要参考Java课程)
-
最近做项目遇到比较有挑战性的点
练习讲解
-
操作系统之存储管理
分页
把存储分配固定大小的页
把程序分为固定大小的页
页表支持,寄存器支持
把页表相关信息放到进程的PCB
页号,页偏移
页号+页始址找到页表项,查到物理块号(物理页号)
段页式
把存储分页
把程序先分段,段内再分页
段表支持,页表支持,寄存器支持
段号,页号,页内偏移
段表相关信息存到进程的PCB
段始址+段号找到段表项,进而查到页表始址
页表始址+页号找到页表项,进而查到物理块号(物理页号)