GPBRootObject.m 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245
  1. // Protocol Buffers - Google's data interchange format
  2. // Copyright 2008 Google Inc. All rights reserved.
  3. // https://developers.google.com/protocol-buffers/
  4. //
  5. // Redistribution and use in source and binary forms, with or without
  6. // modification, are permitted provided that the following conditions are
  7. // met:
  8. //
  9. // * Redistributions of source code must retain the above copyright
  10. // notice, this list of conditions and the following disclaimer.
  11. // * Redistributions in binary form must reproduce the above
  12. // copyright notice, this list of conditions and the following disclaimer
  13. // in the documentation and/or other materials provided with the
  14. // distribution.
  15. // * Neither the name of Google Inc. nor the names of its
  16. // contributors may be used to endorse or promote products derived from
  17. // this software without specific prior written permission.
  18. //
  19. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  20. // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  21. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  22. // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  23. // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  24. // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  25. // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  26. // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  27. // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  28. // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  29. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  30. #import "GPBRootObject_PackagePrivate.h"
  31. #import <objc/runtime.h>
  32. #import <CoreFoundation/CoreFoundation.h>
  33. #import "GPBDescriptor.h"
  34. #import "GPBExtensionRegistry.h"
  35. #import "GPBUtilities_PackagePrivate.h"
  36. @interface GPBExtensionDescriptor (GPBRootObject)
  37. // Get singletonName as a c string.
  38. - (const char *)singletonNameC;
  39. @end
  40. // We need some object to conform to the MessageSignatureProtocol to make sure
  41. // the selectors in it are recorded in our Objective C runtime information.
  42. // GPBMessage is arguably the more "obvious" choice, but given that all messages
  43. // inherit from GPBMessage, conflicts seem likely, so we are using GPBRootObject
  44. // instead.
  45. @interface GPBRootObject () <GPBMessageSignatureProtocol>
  46. @end
  47. @implementation GPBRootObject
  48. // Taken from http://www.burtleburtle.net/bob/hash/doobs.html
  49. // Public Domain
  50. static uint32_t jenkins_one_at_a_time_hash(const char *key) {
  51. uint32_t hash = 0;
  52. for (uint32_t i = 0; key[i] != '\0'; ++i) {
  53. hash += key[i];
  54. hash += (hash << 10);
  55. hash ^= (hash >> 6);
  56. }
  57. hash += (hash << 3);
  58. hash ^= (hash >> 11);
  59. hash += (hash << 15);
  60. return hash;
  61. }
  62. // Key methods for our custom CFDictionary.
  63. // Note that the dictionary lasts for the lifetime of our app, so no need
  64. // to worry about deallocation. All of the items are added to it at
  65. // startup, and so the keys don't need to be retained/released.
  66. // Keys are NULL terminated char *.
  67. static const void *GPBRootExtensionKeyRetain(CFAllocatorRef allocator,
  68. const void *value) {
  69. #pragma unused(allocator)
  70. return value;
  71. }
  72. static void GPBRootExtensionKeyRelease(CFAllocatorRef allocator,
  73. const void *value) {
  74. #pragma unused(allocator)
  75. #pragma unused(value)
  76. }
  77. static CFStringRef GPBRootExtensionCopyKeyDescription(const void *value) {
  78. const char *key = (const char *)value;
  79. return CFStringCreateWithCString(kCFAllocatorDefault, key,
  80. kCFStringEncodingUTF8);
  81. }
  82. static Boolean GPBRootExtensionKeyEqual(const void *value1,
  83. const void *value2) {
  84. const char *key1 = (const char *)value1;
  85. const char *key2 = (const char *)value2;
  86. return strcmp(key1, key2) == 0;
  87. }
  88. static CFHashCode GPBRootExtensionKeyHash(const void *value) {
  89. const char *key = (const char *)value;
  90. return jenkins_one_at_a_time_hash(key);
  91. }
  92. // NOTE: OSSpinLock may seem like a good fit here but Apple engineers have
  93. // pointed out that they are vulnerable to live locking on iOS in cases of
  94. // priority inversion:
  95. // http://mjtsai.com/blog/2015/12/16/osspinlock-is-unsafe/
  96. // https://lists.swift.org/pipermail/swift-dev/Week-of-Mon-20151214/000372.html
  97. static dispatch_semaphore_t gExtensionSingletonDictionarySemaphore;
  98. static CFMutableDictionaryRef gExtensionSingletonDictionary = NULL;
  99. static GPBExtensionRegistry *gDefaultExtensionRegistry = NULL;
  100. + (void)initialize {
  101. // Ensure the global is started up.
  102. if (!gExtensionSingletonDictionary) {
  103. gExtensionSingletonDictionarySemaphore = dispatch_semaphore_create(1);
  104. CFDictionaryKeyCallBacks keyCallBacks = {
  105. // See description above for reason for using custom dictionary.
  106. 0,
  107. GPBRootExtensionKeyRetain,
  108. GPBRootExtensionKeyRelease,
  109. GPBRootExtensionCopyKeyDescription,
  110. GPBRootExtensionKeyEqual,
  111. GPBRootExtensionKeyHash,
  112. };
  113. gExtensionSingletonDictionary =
  114. CFDictionaryCreateMutable(kCFAllocatorDefault, 0, &keyCallBacks,
  115. &kCFTypeDictionaryValueCallBacks);
  116. gDefaultExtensionRegistry = [[GPBExtensionRegistry alloc] init];
  117. }
  118. if ([self superclass] == [GPBRootObject class]) {
  119. // This is here to start up all the per file "Root" subclasses.
  120. // This must be done in initialize to enforce thread safety of start up of
  121. // the protocol buffer library.
  122. [self extensionRegistry];
  123. }
  124. }
  125. + (GPBExtensionRegistry *)extensionRegistry {
  126. // Is overridden in all the subclasses that provide extensions to provide the
  127. // per class one.
  128. return gDefaultExtensionRegistry;
  129. }
  130. + (void)globallyRegisterExtension:(GPBExtensionDescriptor *)field {
  131. const char *key = [field singletonNameC];
  132. dispatch_semaphore_wait(gExtensionSingletonDictionarySemaphore,
  133. DISPATCH_TIME_FOREVER);
  134. CFDictionarySetValue(gExtensionSingletonDictionary, key, field);
  135. dispatch_semaphore_signal(gExtensionSingletonDictionarySemaphore);
  136. }
  137. static id ExtensionForName(id self, SEL _cmd) {
  138. // Really fast way of doing "classname_selName".
  139. // This came up as a hotspot (creation of NSString *) when accessing a
  140. // lot of extensions.
  141. const char *selName = sel_getName(_cmd);
  142. if (selName[0] == '_') {
  143. return nil; // Apple internal selector.
  144. }
  145. size_t selNameLen = 0;
  146. while (1) {
  147. char c = selName[selNameLen];
  148. if (c == '\0') { // String end.
  149. break;
  150. }
  151. if (c == ':') {
  152. return nil; // Selector took an arg, not one of the runtime methods.
  153. }
  154. ++selNameLen;
  155. }
  156. const char *className = class_getName(self);
  157. size_t classNameLen = strlen(className);
  158. char key[classNameLen + selNameLen + 2];
  159. memcpy(key, className, classNameLen);
  160. key[classNameLen] = '_';
  161. memcpy(&key[classNameLen + 1], selName, selNameLen);
  162. key[classNameLen + 1 + selNameLen] = '\0';
  163. // NOTE: Even though this method is called from another C function,
  164. // gExtensionSingletonDictionarySemaphore and gExtensionSingletonDictionary
  165. // will always be initialized. This is because this call flow is just to
  166. // lookup the Extension, meaning the code is calling an Extension class
  167. // message on a Message or Root class. This guarantees that the class was
  168. // initialized and Message classes ensure their Root was also initialized.
  169. NSAssert(gExtensionSingletonDictionary, @"Startup order broken!");
  170. dispatch_semaphore_wait(gExtensionSingletonDictionarySemaphore,
  171. DISPATCH_TIME_FOREVER);
  172. id extension = (id)CFDictionaryGetValue(gExtensionSingletonDictionary, key);
  173. // We can't remove the key from the dictionary here (as an optimization),
  174. // two threads could have gone into +resolveClassMethod: for the same method,
  175. // and ended up here; there's no way to ensure both return YES without letting
  176. // both try to wire in the method.
  177. dispatch_semaphore_signal(gExtensionSingletonDictionarySemaphore);
  178. return extension;
  179. }
  180. BOOL GPBResolveExtensionClassMethod(Class self, SEL sel) {
  181. // Another option would be to register the extensions with the class at
  182. // globallyRegisterExtension:
  183. // Timing the two solutions, this solution turned out to be much faster
  184. // and reduced startup time, and runtime memory.
  185. // The advantage to globallyRegisterExtension is that it would reduce the
  186. // size of the protos somewhat because the singletonNameC wouldn't need
  187. // to include the class name. For a class with a lot of extensions it
  188. // can add up. You could also significantly reduce the code complexity of this
  189. // file.
  190. id extension = ExtensionForName(self, sel);
  191. if (extension != nil) {
  192. const char *encoding =
  193. GPBMessageEncodingForSelector(@selector(getClassValue), NO);
  194. Class metaClass = objc_getMetaClass(class_getName(self));
  195. IMP imp = imp_implementationWithBlock(^(id obj) {
  196. #pragma unused(obj)
  197. return extension;
  198. });
  199. BOOL methodAdded = class_addMethod(metaClass, sel, imp, encoding);
  200. // class_addMethod() is documented as also failing if the method was already
  201. // added; so we check if the method is already there and return success so
  202. // the method dispatch will still happen. Why would it already be added?
  203. // Two threads could cause the same method to be bound at the same time,
  204. // but only one will actually bind it; the other still needs to return true
  205. // so things will dispatch.
  206. if (!methodAdded) {
  207. methodAdded = GPBClassHasSel(metaClass, sel);
  208. }
  209. return methodAdded;
  210. }
  211. return NO;
  212. }
  213. + (BOOL)resolveClassMethod:(SEL)sel {
  214. if (GPBResolveExtensionClassMethod(self, sel)) {
  215. return YES;
  216. }
  217. return [super resolveClassMethod:sel];
  218. }
  219. @end