objc-shared-cache.h 50 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483
  1. /*
  2. * Copyright (c) 2008 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. Portions derived from:
  25. --------------------------------------------------------------------
  26. lookup8.c, by Bob Jenkins, January 4 1997, Public Domain.
  27. hash(), hash2(), hash3, and mix() are externally useful functions.
  28. Routines to test the hash are included if SELF_TEST is defined.
  29. You can use this free for any purpose. It has no warranty.
  30. --------------------------------------------------------------------
  31. ------------------------------------------------------------------------------
  32. perfect.c: code to generate code for a hash for perfect hashing.
  33. (c) Bob Jenkins, September 1996, December 1999
  34. You may use this code in any way you wish, and it is free. No warranty.
  35. I hereby place this in the public domain.
  36. Source is http://burtleburtle.net/bob/c/perfect.c
  37. ------------------------------------------------------------------------------
  38. */
  39. /*
  40. * objc-selopt.h
  41. * Interface between libobjc and dyld
  42. * for selector uniquing in the dyld shared cache.
  43. *
  44. * When building the shared cache, dyld locates all selectors and selector
  45. * references in the cached images. It builds a perfect hash table out of
  46. * them and writes the table into the shared cache copy of libobjc.
  47. * libobjc then uses that table as the builtin selector list.
  48. *
  49. * Versioning
  50. * The table has a version number. dyld and objc can both ignore the table
  51. * if the other used the wrong version number.
  52. *
  53. * Completeness
  54. * Not all libraries are in the shared cache. Libraries that are in the
  55. * shared cache and were optimized are specially marked. Libraries on
  56. * disk never include those marks.
  57. *
  58. * Coherency
  59. * Libraries optimized in the shared cache can be replaced by unoptimized
  60. * copies from disk when loaded. The copy from disk is not marked and will
  61. * be fixed up by libobjc. The shared cache copy is still mapped into the
  62. * process, so the table can point to cstring data in that library's part
  63. * of the shared cache without trouble.
  64. *
  65. * Atomicity
  66. * dyld writes the table itself last. If dyld marks some metadata as
  67. * updated but then fails to write a table for some reason, libobjc
  68. * fixes up all metadata as if it were not marked.
  69. */
  70. #ifndef _OBJC_SELOPT_H
  71. #define _OBJC_SELOPT_H
  72. /*
  73. DO NOT INCLUDE ANY objc HEADERS HERE
  74. dyld USES THIS FILE AND CANNOT SEE THEM
  75. */
  76. #include <stdint.h>
  77. #include <stdlib.h>
  78. #ifdef SELOPT_WRITE
  79. #include <unordered_map>
  80. #endif
  81. /*
  82. DO NOT INCLUDE ANY objc HEADERS HERE
  83. dyld USES THIS FILE AND CANNOT SEE THEM
  84. */
  85. #ifndef STATIC_ASSERT
  86. # define STATIC_ASSERT(x) _STATIC_ASSERT2(x, __LINE__)
  87. # define _STATIC_ASSERT2(x, line) _STATIC_ASSERT3(x, line)
  88. # define _STATIC_ASSERT3(x, line) \
  89. typedef struct { \
  90. int _static_assert[(x) ? 0 : -1]; \
  91. } _static_assert_ ## line __attribute__((unavailable))
  92. #endif
  93. #define SELOPT_DEBUG 0
  94. #define S32(x) x = little_endian ? OSSwapHostToLittleInt32(x) : OSSwapHostToBigInt32(x)
  95. #define S64(x) x = little_endian ? OSSwapHostToLittleInt64(x) : OSSwapHostToBigInt64(x)
  96. namespace objc_opt {
  97. typedef int32_t objc_stringhash_offset_t;
  98. typedef uint8_t objc_stringhash_check_t;
  99. static uint64_t lookup8( uint8_t *k, size_t length, uint64_t level);
  100. #ifdef SELOPT_WRITE
  101. // Perfect hash code is at the end of this file.
  102. struct __attribute__((packed)) perfect_hash {
  103. uint32_t capacity;
  104. uint32_t occupied;
  105. uint32_t shift;
  106. uint32_t mask;
  107. uint64_t salt;
  108. uint32_t scramble[256];
  109. uint8_t *tab; // count == mask+1; free with delete[]
  110. perfect_hash() : tab(0) { }
  111. ~perfect_hash() { if (tab) delete[] tab; }
  112. };
  113. struct eqstr {
  114. bool operator()(const char* s1, const char* s2) const {
  115. return strcmp(s1, s2) == 0;
  116. }
  117. };
  118. struct hashstr {
  119. size_t operator()(const char *s) const {
  120. return (size_t)lookup8((uint8_t *)s, strlen(s), 0);
  121. }
  122. };
  123. // cstring => cstring's vmaddress
  124. // (used for selector names and class names)
  125. typedef std::unordered_map<const char *, uint64_t, hashstr, eqstr> string_map;
  126. // protocol name => protocol vmaddress
  127. typedef std::unordered_map<const char *, uint64_t, hashstr, eqstr> protocol_map;
  128. // class name => (class vmaddress, header_info vmaddress)
  129. typedef std::unordered_multimap<const char *, std::pair<uint64_t, uint64_t>, hashstr, eqstr> class_map;
  130. static perfect_hash make_perfect(const string_map& strings);
  131. #endif
  132. // Precomputed perfect hash table of strings.
  133. // Base class for precomputed selector table and class table.
  134. // Edit objc-sel-table.s if you change this structure.
  135. struct __attribute__((packed)) objc_stringhash_t {
  136. uint32_t capacity;
  137. uint32_t occupied;
  138. uint32_t shift;
  139. uint32_t mask;
  140. uint32_t unused1; // was zero
  141. uint32_t unused2; // alignment pad
  142. uint64_t salt;
  143. uint32_t scramble[256];
  144. uint8_t tab[0]; /* tab[mask+1] (always power-of-2) */
  145. // uint8_t checkbytes[capacity]; /* check byte for each string */
  146. // int32_t offsets[capacity]; /* offsets from &capacity to cstrings */
  147. objc_stringhash_check_t *checkbytes() { return (objc_stringhash_check_t *)&tab[mask+1]; }
  148. const objc_stringhash_check_t *checkbytes() const { return (const objc_stringhash_check_t *)&tab[mask+1]; }
  149. objc_stringhash_offset_t *offsets() { return (objc_stringhash_offset_t *)&checkbytes()[capacity]; }
  150. const objc_stringhash_offset_t *offsets() const { return (const objc_stringhash_offset_t *)&checkbytes()[capacity]; }
  151. uint32_t hash(const char *key, size_t keylen) const
  152. {
  153. uint64_t val = lookup8((uint8_t*)key, keylen, salt);
  154. uint32_t index = (uint32_t)(val>>shift) ^ scramble[tab[val&mask]];
  155. return index;
  156. }
  157. uint32_t hash(const char *key) const
  158. {
  159. return hash(key, strlen(key));
  160. }
  161. // The check bytes areused to reject strings that aren't in the table
  162. // without paging in the table's cstring data. This checkbyte calculation
  163. // catches 4785/4815 rejects when launching Safari; a perfect checkbyte
  164. // would catch 4796/4815.
  165. objc_stringhash_check_t checkbyte(const char *key, size_t keylen) const
  166. {
  167. return
  168. ((key[0] & 0x7) << 5)
  169. |
  170. ((uint8_t)keylen & 0x1f);
  171. }
  172. objc_stringhash_check_t checkbyte(const char *key) const
  173. {
  174. return checkbyte(key, strlen(key));
  175. }
  176. #define INDEX_NOT_FOUND (~(uint32_t)0)
  177. uint32_t getIndex(const char *key) const
  178. {
  179. size_t keylen = strlen(key);
  180. uint32_t h = hash(key, keylen);
  181. // Use check byte to reject without paging in the table's cstrings
  182. objc_stringhash_check_t h_check = checkbytes()[h];
  183. objc_stringhash_check_t key_check = checkbyte(key, keylen);
  184. bool check_fail = (h_check != key_check);
  185. #if ! SELOPT_DEBUG
  186. if (check_fail) return INDEX_NOT_FOUND;
  187. #endif
  188. objc_stringhash_offset_t offset = offsets()[h];
  189. if (offset == 0) return INDEX_NOT_FOUND;
  190. const char *result = (const char *)this + offset;
  191. if (0 != strcmp(key, result)) return INDEX_NOT_FOUND;
  192. #if SELOPT_DEBUG
  193. if (check_fail) abort();
  194. #endif
  195. return h;
  196. }
  197. #ifdef SELOPT_WRITE
  198. size_t size()
  199. {
  200. return sizeof(objc_stringhash_t)
  201. + mask+1
  202. + capacity * sizeof(objc_stringhash_check_t)
  203. + capacity * sizeof(objc_stringhash_offset_t);
  204. }
  205. void byteswap(bool little_endian)
  206. {
  207. // tab and checkbytes are arrays of bytes, no swap needed
  208. for (uint32_t i = 0; i < 256; i++) {
  209. S32(scramble[i]);
  210. }
  211. objc_stringhash_offset_t *o = offsets();
  212. for (uint32_t i = 0; i < capacity; i++) {
  213. S32(o[i]);
  214. }
  215. S32(capacity);
  216. S32(occupied);
  217. S32(shift);
  218. S32(mask);
  219. S64(salt);
  220. }
  221. const char *write(uint64_t base, size_t remaining, string_map& strings)
  222. {
  223. if (sizeof(objc_stringhash_t) > remaining) {
  224. return "selector section too small (metadata not optimized)";
  225. }
  226. if (strings.size() == 0) {
  227. bzero(this, sizeof(objc_stringhash_t));
  228. return NULL;
  229. }
  230. perfect_hash phash = make_perfect(strings);
  231. if (phash.capacity == 0) {
  232. return "perfect hash failed (metadata not optimized)";
  233. }
  234. // Set header
  235. capacity = phash.capacity;
  236. occupied = phash.occupied;
  237. shift = phash.shift;
  238. mask = phash.mask;
  239. unused1 = 0;
  240. unused2 = 0;
  241. salt = phash.salt;
  242. if (size() > remaining) {
  243. return "selector section too small (metadata not optimized)";
  244. }
  245. // Set hash data
  246. for (uint32_t i = 0; i < 256; i++) {
  247. scramble[i] = phash.scramble[i];
  248. }
  249. for (uint32_t i = 0; i < phash.mask+1; i++) {
  250. tab[i] = phash.tab[i];
  251. }
  252. // Set offsets to 0
  253. for (uint32_t i = 0; i < phash.capacity; i++) {
  254. offsets()[i] = 0;
  255. }
  256. // Set checkbytes to 0
  257. for (uint32_t i = 0; i < phash.capacity; i++) {
  258. checkbytes()[i] = 0;
  259. }
  260. // Set real string offsets and checkbytes
  261. # define SHIFT (64 - 8*sizeof(objc_stringhash_offset_t))
  262. string_map::const_iterator s;
  263. for (s = strings.begin(); s != strings.end(); ++s) {
  264. int64_t offset = s->second - base;
  265. if ((offset<<SHIFT)>>SHIFT != offset) {
  266. return "selector offset too big (metadata not optimized)";
  267. }
  268. uint32_t h = hash(s->first);
  269. offsets()[h] = (objc_stringhash_offset_t)offset;
  270. checkbytes()[h] = checkbyte(s->first);
  271. }
  272. # undef SHIFT
  273. return NULL;
  274. }
  275. // SELOPT_WRITE
  276. #endif
  277. };
  278. // Precomputed selector table.
  279. // Edit objc-sel-table.s if you change this structure.
  280. struct objc_selopt_t : objc_stringhash_t {
  281. const char *get(const char *key) const
  282. {
  283. uint32_t h = getIndex(key);
  284. if (h == INDEX_NOT_FOUND) return NULL;
  285. return (const char *)this + offsets()[h];
  286. }
  287. };
  288. // Precomputed class list.
  289. // Edit objc-sel-table.s if you change these structures.
  290. struct objc_classheader_t {
  291. objc_stringhash_offset_t clsOffset;
  292. objc_stringhash_offset_t hiOffset;
  293. // For duplicate class names:
  294. // clsOffset = count<<1 | 1
  295. // duplicated classes are duplicateOffsets[hiOffset..hiOffset+count-1]
  296. bool isDuplicate() const { return clsOffset & 1; }
  297. uint32_t duplicateCount() const { return clsOffset >> 1; }
  298. uint32_t duplicateIndex() const { return hiOffset; }
  299. };
  300. struct objc_clsopt_t : objc_stringhash_t {
  301. // ...objc_stringhash_t fields...
  302. // objc_classheader_t classOffsets[capacity]; /* offsets from &capacity to class_t and header_info */
  303. // uint32_t duplicateCount;
  304. // objc_classheader_t duplicateOffsets[duplicatedClasses];
  305. objc_classheader_t *classOffsets() { return (objc_classheader_t *)&offsets()[capacity]; }
  306. const objc_classheader_t *classOffsets() const { return (const objc_classheader_t *)&offsets()[capacity]; }
  307. uint32_t& duplicateCount() { return *(uint32_t *)&classOffsets()[capacity]; }
  308. const uint32_t& duplicateCount() const { return *(const uint32_t *)&classOffsets()[capacity]; }
  309. objc_classheader_t *duplicateOffsets() { return (objc_classheader_t *)(&duplicateCount()+1); }
  310. const objc_classheader_t *duplicateOffsets() const { return (const objc_classheader_t *)(&duplicateCount()+1); }
  311. // 0/NULL/NULL: not found
  312. // 1/ptr/ptr: found exactly one
  313. // n/NULL/NULL: found N - use getClassesAndHeaders() instead
  314. uint32_t getClassAndHeader(const char *key, void*& cls, void*& hi) const
  315. {
  316. uint32_t h = getIndex(key);
  317. if (h == INDEX_NOT_FOUND) {
  318. cls = NULL;
  319. hi = NULL;
  320. return 0;
  321. }
  322. const objc_classheader_t& clshi = classOffsets()[h];
  323. if (! clshi.isDuplicate()) {
  324. // class appears in exactly one header
  325. cls = (void *)((const char *)this + clshi.clsOffset);
  326. hi = (void *)((const char *)this + clshi.hiOffset);
  327. return 1;
  328. }
  329. else {
  330. // class appears in more than one header - use getClassesAndHeaders
  331. cls = NULL;
  332. hi = NULL;
  333. return clshi.duplicateCount();
  334. }
  335. }
  336. void getClassesAndHeaders(const char *key, void **cls, void **hi) const
  337. {
  338. uint32_t h = getIndex(key);
  339. if (h == INDEX_NOT_FOUND) return;
  340. const objc_classheader_t& clshi = classOffsets()[h];
  341. if (! clshi.isDuplicate()) {
  342. // class appears in exactly one header
  343. cls[0] = (void *)((const char *)this + clshi.clsOffset);
  344. hi[0] = (void *)((const char *)this + clshi.hiOffset);
  345. }
  346. else {
  347. // class appears in more than one header
  348. uint32_t count = clshi.duplicateCount();
  349. const objc_classheader_t *list =
  350. &duplicateOffsets()[clshi.duplicateIndex()];
  351. for (uint32_t i = 0; i < count; i++) {
  352. cls[i] = (void *)((const char *)this + list[i].clsOffset);
  353. hi[i] = (void *)((const char *)this + list[i].hiOffset);
  354. }
  355. }
  356. }
  357. #ifdef SELOPT_WRITE
  358. size_t size()
  359. {
  360. return
  361. objc_stringhash_t::size()
  362. + capacity * sizeof(objc_classheader_t)
  363. + sizeof(duplicateCount())
  364. + duplicateCount() * sizeof(objc_classheader_t);
  365. }
  366. void byteswap(bool little_endian)
  367. {
  368. objc_classheader_t *o;
  369. o = classOffsets();
  370. for (uint32_t i = 0; i < capacity; i++) {
  371. S32(o[i].clsOffset);
  372. S32(o[i].hiOffset);
  373. }
  374. o = duplicateOffsets();
  375. for (uint32_t i = 0; i < duplicateCount(); i++) {
  376. S32(o[i].clsOffset);
  377. S32(o[i].hiOffset);
  378. }
  379. S32(duplicateCount());
  380. objc_stringhash_t::byteswap(little_endian);
  381. }
  382. const char *write(uint64_t base, size_t remaining,
  383. string_map& strings, class_map& classes, bool verbose)
  384. {
  385. const char *err;
  386. err = objc_stringhash_t::write(base, remaining, strings);
  387. if (err) return err;
  388. if (size() > remaining) {
  389. return "selector section too small (metadata not optimized)";
  390. }
  391. // Set class offsets to 0
  392. for (uint32_t i = 0; i < capacity; i++) {
  393. classOffsets()[i].clsOffset = 0;
  394. classOffsets()[i].hiOffset = 0;
  395. }
  396. // Set real class offsets
  397. # define SHIFT (64 - 8*sizeof(objc_stringhash_offset_t))
  398. class_map::const_iterator c;
  399. for (c = classes.begin(); c != classes.end(); ++c) {
  400. uint32_t h = getIndex(c->first);
  401. if (h == INDEX_NOT_FOUND) {
  402. return "class list busted (metadata not optimized)";
  403. }
  404. if (classOffsets()[h].clsOffset != 0) {
  405. // already did this class
  406. continue;
  407. }
  408. uint32_t count = (uint32_t)classes.count(c->first);
  409. if (count == 1) {
  410. // only one class with this name
  411. int64_t coff = c->second.first - base;
  412. int64_t hoff = c->second.second - base;
  413. if ((coff<<SHIFT)>>SHIFT != coff) {
  414. return "class offset too big (metadata not optimized)";
  415. }
  416. if ((hoff<<SHIFT)>>SHIFT != hoff) {
  417. return "header offset too big (metadata not optimized)";
  418. }
  419. classOffsets()[h].clsOffset = (objc_stringhash_offset_t)coff;
  420. classOffsets()[h].hiOffset = (objc_stringhash_offset_t)hoff;
  421. }
  422. else {
  423. // class name has duplicates - write them all now
  424. if (verbose) {
  425. fprintf(stderr, "update_dyld_shared_cache: %u duplicates of Objective-C class %s\n", count, c->first);
  426. }
  427. uint32_t dest = duplicateCount();
  428. duplicateCount() += count;
  429. if (size() > remaining) {
  430. return "selector section too small (metadata not optimized)";
  431. }
  432. // classOffsets() instead contains count and array index
  433. classOffsets()[h].clsOffset = count*2 + 1;
  434. classOffsets()[h].hiOffset = dest;
  435. std::pair<class_map::const_iterator, class_map::const_iterator>
  436. duplicates = classes.equal_range(c->first);
  437. class_map::const_iterator dup;
  438. for (dup = duplicates.first; dup != duplicates.second; ++dup) {
  439. int64_t coff = dup->second.first - base;
  440. int64_t hoff = dup->second.second - base;
  441. if ((coff<<SHIFT)>>SHIFT != coff) {
  442. return "class offset too big (metadata not optimized)";
  443. }
  444. if ((hoff<<SHIFT)>>SHIFT != hoff) {
  445. return "header offset too big (metadata not optimized)";
  446. }
  447. duplicateOffsets()[dest].clsOffset = (objc_stringhash_offset_t)coff;
  448. duplicateOffsets()[dest].hiOffset = (objc_stringhash_offset_t)hoff;
  449. dest++;
  450. }
  451. }
  452. }
  453. # undef SHIFT
  454. return NULL;
  455. }
  456. // SELOPT_WRITE
  457. #endif
  458. };
  459. struct objc_protocolopt_t : objc_stringhash_t {
  460. // ...objc_stringhash_t fields...
  461. // uint32_t protocolOffsets[capacity]; /* offsets from &capacity to protocol_t */
  462. objc_stringhash_offset_t *protocolOffsets() { return (objc_stringhash_offset_t *)&offsets()[capacity]; }
  463. const objc_stringhash_offset_t *protocolOffsets() const { return (const objc_stringhash_offset_t *)&offsets()[capacity]; }
  464. void* getProtocol(const char *key) const
  465. {
  466. uint32_t h = getIndex(key);
  467. if (h == INDEX_NOT_FOUND) {
  468. return NULL;
  469. }
  470. return (void *)((const char *)this + protocolOffsets()[h]);
  471. }
  472. #ifdef SELOPT_WRITE
  473. size_t size()
  474. {
  475. return
  476. objc_stringhash_t::size() + capacity * sizeof(objc_stringhash_offset_t);
  477. }
  478. void byteswap(bool little_endian)
  479. {
  480. objc_stringhash_offset_t *o;
  481. o = protocolOffsets();
  482. for (objc_stringhash_offset_t i = 0; i < (int)capacity; i++) {
  483. S32(o[i]);
  484. }
  485. objc_stringhash_t::byteswap(little_endian);
  486. }
  487. const char *write(uint64_t base, size_t remaining,
  488. string_map& strings, protocol_map& protocols,
  489. bool verbose)
  490. {
  491. const char *err;
  492. err = objc_stringhash_t::write(base, remaining, strings);
  493. if (err) return err;
  494. if (size() > remaining) {
  495. return "selector section too small (metadata not optimized)";
  496. }
  497. // Set protocol offsets to 0
  498. for (uint32_t i = 0; i < capacity; i++) {
  499. protocolOffsets()[i] = 0;
  500. }
  501. // Set real protocol offsets
  502. # define SHIFT (64 - 8*sizeof(objc_stringhash_offset_t))
  503. protocol_map::const_iterator c;
  504. for (c = protocols.begin(); c != protocols.end(); ++c) {
  505. uint32_t h = getIndex(c->first);
  506. if (h == INDEX_NOT_FOUND) {
  507. return "protocol list busted (metadata not optimized)";
  508. }
  509. int64_t offset = c->second - base;
  510. if ((offset<<SHIFT)>>SHIFT != offset) {
  511. return "protocol offset too big (metadata not optimized)";
  512. }
  513. protocolOffsets()[h] = (objc_stringhash_offset_t)offset;
  514. }
  515. # undef SHIFT
  516. return NULL;
  517. }
  518. // SELOPT_WRITE
  519. #endif
  520. };
  521. // Precomputed image list.
  522. struct objc_headeropt_ro_t;
  523. // Precomputed image list.
  524. struct objc_headeropt_rw_t;
  525. // Precomputed class list.
  526. struct objc_clsopt_t;
  527. // Edit objc-sel-table.s if you change this value.
  528. // lldb and Symbolication read these structures. Inform them of any changes.
  529. enum { VERSION = 15 };
  530. // Values for objc_opt_t::flags
  531. enum : uint32_t {
  532. IsProduction = (1 << 0), // never set in development cache
  533. NoMissingWeakSuperclasses = (1 << 1), // never set in development cache
  534. };
  535. // Top-level optimization structure.
  536. // Edit objc-sel-table.s if you change this structure.
  537. struct alignas(alignof(void*)) objc_opt_t {
  538. uint32_t version;
  539. uint32_t flags;
  540. int32_t selopt_offset;
  541. int32_t headeropt_ro_offset;
  542. int32_t clsopt_offset;
  543. int32_t protocolopt_offset;
  544. int32_t headeropt_rw_offset;
  545. const objc_selopt_t* selopt() const {
  546. if (selopt_offset == 0) return NULL;
  547. return (objc_selopt_t *)((uint8_t *)this + selopt_offset);
  548. }
  549. objc_selopt_t* selopt() {
  550. if (selopt_offset == 0) return NULL;
  551. return (objc_selopt_t *)((uint8_t *)this + selopt_offset);
  552. }
  553. struct objc_headeropt_ro_t* headeropt_ro() const {
  554. if (headeropt_ro_offset == 0) return NULL;
  555. return (struct objc_headeropt_ro_t *)((uint8_t *)this + headeropt_ro_offset);
  556. }
  557. struct objc_clsopt_t* clsopt() const {
  558. if (clsopt_offset == 0) return NULL;
  559. return (objc_clsopt_t *)((uint8_t *)this + clsopt_offset);
  560. }
  561. struct objc_protocolopt_t* protocolopt() const {
  562. if (protocolopt_offset == 0) return NULL;
  563. return (objc_protocolopt_t *)((uint8_t *)this + protocolopt_offset);
  564. }
  565. struct objc_headeropt_rw_t* headeropt_rw() const {
  566. if (headeropt_rw_offset == 0) return NULL;
  567. return (struct objc_headeropt_rw_t *)((uint8_t *)this + headeropt_rw_offset);
  568. }
  569. };
  570. // sizeof(objc_opt_t) must be pointer-aligned
  571. STATIC_ASSERT(sizeof(objc_opt_t) % sizeof(void*) == 0);
  572. // List of offsets in libobjc that the shared cache optimization needs to use.
  573. template <typename T>
  574. struct objc_opt_pointerlist_tt {
  575. T protocolClass;
  576. };
  577. typedef struct objc_opt_pointerlist_tt<uintptr_t> objc_opt_pointerlist_t;
  578. /*
  579. --------------------------------------------------------------------
  580. mix -- mix 3 64-bit values reversibly.
  581. mix() takes 48 machine instructions, but only 24 cycles on a superscalar
  582. machine (like Intel's new MMX architecture). It requires 4 64-bit
  583. registers for 4::2 parallelism.
  584. All 1-bit deltas, all 2-bit deltas, all deltas composed of top bits of
  585. (a,b,c), and all deltas of bottom bits were tested. All deltas were
  586. tested both on random keys and on keys that were nearly all zero.
  587. These deltas all cause every bit of c to change between 1/3 and 2/3
  588. of the time (well, only 113/400 to 287/400 of the time for some
  589. 2-bit delta). These deltas all cause at least 80 bits to change
  590. among (a,b,c) when the mix is run either forward or backward (yes it
  591. is reversible).
  592. This implies that a hash using mix64 has no funnels. There may be
  593. characteristics with 3-bit deltas or bigger, I didn't test for
  594. those.
  595. --------------------------------------------------------------------
  596. */
  597. #define mix64(a,b,c) \
  598. { \
  599. a -= b; a -= c; a ^= (c>>43); \
  600. b -= c; b -= a; b ^= (a<<9); \
  601. c -= a; c -= b; c ^= (b>>8); \
  602. a -= b; a -= c; a ^= (c>>38); \
  603. b -= c; b -= a; b ^= (a<<23); \
  604. c -= a; c -= b; c ^= (b>>5); \
  605. a -= b; a -= c; a ^= (c>>35); \
  606. b -= c; b -= a; b ^= (a<<49); \
  607. c -= a; c -= b; c ^= (b>>11); \
  608. a -= b; a -= c; a ^= (c>>12); \
  609. b -= c; b -= a; b ^= (a<<18); \
  610. c -= a; c -= b; c ^= (b>>22); \
  611. }
  612. /*
  613. --------------------------------------------------------------------
  614. hash() -- hash a variable-length key into a 64-bit value
  615. k : the key (the unaligned variable-length array of bytes)
  616. len : the length of the key, counting by bytes
  617. level : can be any 8-byte value
  618. Returns a 64-bit value. Every bit of the key affects every bit of
  619. the return value. No funnels. Every 1-bit and 2-bit delta achieves
  620. avalanche. About 41+5len instructions.
  621. The best hash table sizes are powers of 2. There is no need to do
  622. mod a prime (mod is sooo slow!). If you need less than 64 bits,
  623. use a bitmask. For example, if you need only 10 bits, do
  624. h = (h & hashmask(10));
  625. In which case, the hash table should have hashsize(10) elements.
  626. If you are hashing n strings (uint8_t **)k, do it like this:
  627. for (i=0, h=0; i<n; ++i) h = hash( k[i], len[i], h);
  628. By Bob Jenkins, Jan 4 1997. bob_jenkins@burtleburtle.net. You may
  629. use this code any way you wish, private, educational, or commercial,
  630. but I would appreciate if you give me credit.
  631. See http://burtleburtle.net/bob/hash/evahash.html
  632. Use for hash table lookup, or anything where one collision in 2^^64
  633. is acceptable. Do NOT use for cryptographic purposes.
  634. --------------------------------------------------------------------
  635. */
  636. static uint64_t lookup8( uint8_t *k, size_t length, uint64_t level)
  637. // uint8_t *k; /* the key */
  638. // uint64_t length; /* the length of the key */
  639. // uint64_t level; /* the previous hash, or an arbitrary value */
  640. {
  641. uint64_t a,b,c;
  642. size_t len;
  643. /* Set up the internal state */
  644. len = length;
  645. a = b = level; /* the previous hash value */
  646. c = 0x9e3779b97f4a7c13LL; /* the golden ratio; an arbitrary value */
  647. /*---------------------------------------- handle most of the key */
  648. while (len >= 24)
  649. {
  650. a += (k[0] +((uint64_t)k[ 1]<< 8)+((uint64_t)k[ 2]<<16)+((uint64_t)k[ 3]<<24)
  651. +((uint64_t)k[4 ]<<32)+((uint64_t)k[ 5]<<40)+((uint64_t)k[ 6]<<48)+((uint64_t)k[ 7]<<56));
  652. b += (k[8] +((uint64_t)k[ 9]<< 8)+((uint64_t)k[10]<<16)+((uint64_t)k[11]<<24)
  653. +((uint64_t)k[12]<<32)+((uint64_t)k[13]<<40)+((uint64_t)k[14]<<48)+((uint64_t)k[15]<<56));
  654. c += (k[16] +((uint64_t)k[17]<< 8)+((uint64_t)k[18]<<16)+((uint64_t)k[19]<<24)
  655. +((uint64_t)k[20]<<32)+((uint64_t)k[21]<<40)+((uint64_t)k[22]<<48)+((uint64_t)k[23]<<56));
  656. mix64(a,b,c);
  657. k += 24; len -= 24;
  658. }
  659. /*------------------------------------- handle the last 23 bytes */
  660. c += length;
  661. switch(len) /* all the case statements fall through */
  662. {
  663. case 23: c+=((uint64_t)k[22]<<56);
  664. case 22: c+=((uint64_t)k[21]<<48);
  665. case 21: c+=((uint64_t)k[20]<<40);
  666. case 20: c+=((uint64_t)k[19]<<32);
  667. case 19: c+=((uint64_t)k[18]<<24);
  668. case 18: c+=((uint64_t)k[17]<<16);
  669. case 17: c+=((uint64_t)k[16]<<8);
  670. /* the first byte of c is reserved for the length */
  671. case 16: b+=((uint64_t)k[15]<<56);
  672. case 15: b+=((uint64_t)k[14]<<48);
  673. case 14: b+=((uint64_t)k[13]<<40);
  674. case 13: b+=((uint64_t)k[12]<<32);
  675. case 12: b+=((uint64_t)k[11]<<24);
  676. case 11: b+=((uint64_t)k[10]<<16);
  677. case 10: b+=((uint64_t)k[ 9]<<8);
  678. case 9: b+=((uint64_t)k[ 8]);
  679. case 8: a+=((uint64_t)k[ 7]<<56);
  680. case 7: a+=((uint64_t)k[ 6]<<48);
  681. case 6: a+=((uint64_t)k[ 5]<<40);
  682. case 5: a+=((uint64_t)k[ 4]<<32);
  683. case 4: a+=((uint64_t)k[ 3]<<24);
  684. case 3: a+=((uint64_t)k[ 2]<<16);
  685. case 2: a+=((uint64_t)k[ 1]<<8);
  686. case 1: a+=((uint64_t)k[ 0]);
  687. /* case 0: nothing left to add */
  688. }
  689. mix64(a,b,c);
  690. /*-------------------------------------------- report the result */
  691. return c;
  692. }
  693. #ifdef SELOPT_WRITE
  694. /*
  695. ------------------------------------------------------------------------------
  696. This generates a minimal perfect hash function. That means, given a
  697. set of n keys, this determines a hash function that maps each of
  698. those keys into a value in 0..n-1 with no collisions.
  699. The perfect hash function first uses a normal hash function on the key
  700. to determine (a,b) such that the pair (a,b) is distinct for all
  701. keys, then it computes a^scramble[tab[b]] to get the final perfect hash.
  702. tab[] is an array of 1-byte values and scramble[] is a 256-term array of
  703. 2-byte or 4-byte values. If there are n keys, the length of tab[] is a
  704. power of two between n/3 and n.
  705. I found the idea of computing distinct (a,b) values in "Practical minimal
  706. perfect hash functions for large databases", Fox, Heath, Chen, and Daoud,
  707. Communications of the ACM, January 1992. They found the idea in Chichelli
  708. (CACM Jan 1980). Beyond that, our methods differ.
  709. The key is hashed to a pair (a,b) where a in 0..*alen*-1 and b in
  710. 0..*blen*-1. A fast hash function determines both a and b
  711. simultaneously. Any decent hash function is likely to produce
  712. hashes so that (a,b) is distinct for all pairs. I try the hash
  713. using different values of *salt* until all pairs are distinct.
  714. The final hash is (a XOR scramble[tab[b]]). *scramble* is a
  715. predetermined mapping of 0..255 into 0..smax-1. *tab* is an
  716. array that we fill in in such a way as to make the hash perfect.
  717. First we fill in all values of *tab* that are used by more than one
  718. key. We try all possible values for each position until one works.
  719. This leaves m unmapped keys and m values that something could hash to.
  720. If you treat unmapped keys as lefthand nodes and unused hash values
  721. as righthand nodes, and draw a line connecting each key to each hash
  722. value it could map to, you get a bipartite graph. We attempt to
  723. find a perfect matching in this graph. If we succeed, we have
  724. determined a perfect hash for the whole set of keys.
  725. *scramble* is used because (a^tab[i]) clusters keys around *a*.
  726. ------------------------------------------------------------------------------
  727. */
  728. typedef uint64_t ub8;
  729. #define UB8MAXVAL 0xffffffffffffffffLL
  730. #define UB8BITS 64
  731. typedef uint32_t ub4;
  732. #define UB4MAXVAL 0xffffffff
  733. #define UB4BITS 32
  734. typedef uint16_t ub2;
  735. #define UB2MAXVAL 0xffff
  736. #define UB2BITS 16
  737. typedef uint8_t ub1;
  738. #define UB1MAXVAL 0xff
  739. #define UB1BITS 8
  740. #define TRUE 1
  741. #define FALSE 0
  742. #define SCRAMBLE_LEN 256 // ((ub4)1<<16) /* length of *scramble* */
  743. #define RETRY_INITKEY 2048 /* number of times to try to find distinct (a,b) */
  744. #define RETRY_PERFECT 4 /* number of times to try to make a perfect hash */
  745. /* representation of a key */
  746. struct key
  747. {
  748. ub1 *name_k; /* the actual key */
  749. ub4 len_k; /* the length of the actual key */
  750. ub4 hash_k; /* the initial hash value for this key */
  751. /* beyond this point is mapping-dependent */
  752. ub4 a_k; /* a, of the key maps to (a,b) */
  753. ub4 b_k; /* b, of the key maps to (a,b) */
  754. struct key *nextb_k; /* next key with this b */
  755. };
  756. typedef struct key key;
  757. /* things indexed by b of original (a,b) pair */
  758. struct bstuff
  759. {
  760. ub2 val_b; /* hash=a^tabb[b].val_b */
  761. key *list_b; /* tabb[i].list_b is list of keys with b==i */
  762. ub4 listlen_b; /* length of list_b */
  763. ub4 water_b; /* high watermark of who has visited this map node */
  764. };
  765. typedef struct bstuff bstuff;
  766. /* things indexed by final hash value */
  767. struct hstuff
  768. {
  769. key *key_h; /* tabh[i].key_h is the key with a hash of i */
  770. };
  771. typedef struct hstuff hstuff;
  772. /* things indexed by queue position */
  773. struct qstuff
  774. {
  775. bstuff *b_q; /* b that currently occupies this hash */
  776. ub4 parent_q; /* queue position of parent that could use this hash */
  777. ub2 newval_q; /* what to change parent tab[b] to to use this hash */
  778. ub2 oldval_q; /* original value of tab[b] */
  779. };
  780. typedef struct qstuff qstuff;
  781. /*
  782. ------------------------------------------------------------------------------
  783. Find the mapping that will produce a perfect hash
  784. ------------------------------------------------------------------------------
  785. */
  786. /* return the ceiling of the log (base 2) of val */
  787. static ub4 log2u(ub4 val)
  788. {
  789. ub4 i;
  790. for (i=0; ((ub4)1<<i) < val; ++i)
  791. ;
  792. return i;
  793. }
  794. /* compute p(x), where p is a permutation of 0..(1<<nbits)-1 */
  795. /* permute(0)=0. This is intended and useful. */
  796. static ub4 permute(ub4 x, ub4 nbits)
  797. // ub4 x; /* input, a value in some range */
  798. // ub4 nbits; /* input, number of bits in range */
  799. {
  800. int i;
  801. int mask = ((ub4)1<<nbits)-1; /* all ones */
  802. int const2 = 1+nbits/2;
  803. int const3 = 1+nbits/3;
  804. int const4 = 1+nbits/4;
  805. int const5 = 1+nbits/5;
  806. for (i=0; i<20; ++i)
  807. {
  808. x = (x+(x<<const2)) & mask;
  809. x = (x^(x>>const3));
  810. x = (x+(x<<const4)) & mask;
  811. x = (x^(x>>const5));
  812. }
  813. return x;
  814. }
  815. /* initialize scramble[] with distinct random values in 0..smax-1 */
  816. static void scrambleinit(ub4 *scramble, ub4 smax)
  817. // ub4 *scramble; /* hash is a^scramble[tab[b]] */
  818. // ub4 smax; /* scramble values should be in 0..smax-1 */
  819. {
  820. ub4 i;
  821. /* fill scramble[] with distinct random integers in 0..smax-1 */
  822. for (i=0; i<SCRAMBLE_LEN; ++i)
  823. {
  824. scramble[i] = permute(i, log2u(smax));
  825. }
  826. }
  827. /*
  828. * put keys in tabb according to key->b_k
  829. * check if the initial hash might work
  830. */
  831. static int inittab(bstuff *tabb, ub4 blen, key *keys, ub4 nkeys, int complete)
  832. // bstuff *tabb; /* output, list of keys with b for (a,b) */
  833. // ub4 blen; /* length of tabb */
  834. // key *keys; /* list of keys already hashed */
  835. // int complete; /* TRUE means to complete init despite collisions */
  836. {
  837. int nocollision = TRUE;
  838. ub4 i;
  839. memset((void *)tabb, 0, (size_t)(sizeof(bstuff)*blen));
  840. /* Two keys with the same (a,b) guarantees a collision */
  841. for (i = 0; i < nkeys; i++) {
  842. key *mykey = keys+i;
  843. key *otherkey;
  844. for (otherkey=tabb[mykey->b_k].list_b;
  845. otherkey;
  846. otherkey=otherkey->nextb_k)
  847. {
  848. if (mykey->a_k == otherkey->a_k)
  849. {
  850. nocollision = FALSE;
  851. if (!complete)
  852. return FALSE;
  853. }
  854. }
  855. ++tabb[mykey->b_k].listlen_b;
  856. mykey->nextb_k = tabb[mykey->b_k].list_b;
  857. tabb[mykey->b_k].list_b = mykey;
  858. }
  859. /* no two keys have the same (a,b) pair */
  860. return nocollision;
  861. }
  862. /* Do the initial hash for normal mode (use lookup and checksum) */
  863. static void initnorm(key *keys, ub4 nkeys, ub4 alen, ub4 blen, ub4 smax, ub8 salt)
  864. // key *keys; /* list of all keys */
  865. // ub4 alen; /* (a,b) has a in 0..alen-1, a power of 2 */
  866. // ub4 blen; /* (a,b) has b in 0..blen-1, a power of 2 */
  867. // ub4 smax; /* maximum range of computable hash values */
  868. // ub4 salt; /* used to initialize the hash function */
  869. // gencode *final; /* output, code for the final hash */
  870. {
  871. ub4 loga = log2u(alen); /* log based 2 of blen */
  872. dispatch_apply(nkeys, DISPATCH_APPLY_AUTO, ^(size_t index) {
  873. ub4 i = (ub4)index;
  874. key *mykey = keys+i;
  875. ub8 hash = lookup8(mykey->name_k, mykey->len_k, salt);
  876. mykey->a_k = (loga > 0) ? (ub4)(hash >> (UB8BITS-loga)) : 0;
  877. mykey->b_k = (blen > 1) ? (hash & (blen-1)) : 0;
  878. });
  879. }
  880. /* Try to apply an augmenting list */
  881. static int apply(bstuff *tabb, hstuff *tabh, qstuff *tabq, ub4 blen, ub4 *scramble, ub4 tail, int rollback)
  882. // bstuff *tabb;
  883. // hstuff *tabh;
  884. // qstuff *tabq;
  885. // ub4 blen;
  886. // ub4 *scramble;
  887. // ub4 tail;
  888. // int rollback; /* FALSE applies augmenting path, TRUE rolls back */
  889. {
  890. ub4 hash;
  891. key *mykey;
  892. bstuff *pb;
  893. ub4 child;
  894. ub4 parent;
  895. ub4 stabb; /* scramble[tab[b]] */
  896. /* walk from child to parent */
  897. for (child=tail-1; child; child=parent)
  898. {
  899. parent = tabq[child].parent_q; /* find child's parent */
  900. pb = tabq[parent].b_q; /* find parent's list of siblings */
  901. /* erase old hash values */
  902. stabb = scramble[pb->val_b];
  903. for (mykey=pb->list_b; mykey; mykey=mykey->nextb_k)
  904. {
  905. hash = mykey->a_k^stabb;
  906. if (mykey == tabh[hash].key_h)
  907. { /* erase hash for all of child's siblings */
  908. tabh[hash].key_h = (key *)0;
  909. }
  910. }
  911. /* change pb->val_b, which will change the hashes of all parent siblings */
  912. pb->val_b = (rollback ? tabq[child].oldval_q : tabq[child].newval_q);
  913. /* set new hash values */
  914. stabb = scramble[pb->val_b];
  915. for (mykey=pb->list_b; mykey; mykey=mykey->nextb_k)
  916. {
  917. hash = mykey->a_k^stabb;
  918. if (rollback)
  919. {
  920. if (parent == 0) continue; /* root never had a hash */
  921. }
  922. else if (tabh[hash].key_h)
  923. {
  924. /* very rare: roll back any changes */
  925. apply(tabb, tabh, tabq, blen, scramble, tail, TRUE);
  926. return FALSE; /* failure, collision */
  927. }
  928. tabh[hash].key_h = mykey;
  929. }
  930. }
  931. return TRUE;
  932. }
  933. /*
  934. -------------------------------------------------------------------------------
  935. augment(): Add item to the mapping.
  936. Construct a spanning tree of *b*s with *item* as root, where each
  937. parent can have all its hashes changed (by some new val_b) with
  938. at most one collision, and each child is the b of that collision.
  939. I got this from Tarjan's "Data Structures and Network Algorithms". The
  940. path from *item* to a *b* that can be remapped with no collision is
  941. an "augmenting path". Change values of tab[b] along the path so that
  942. the unmapped key gets mapped and the unused hash value gets used.
  943. Assuming 1 key per b, if m out of n hash values are still unused,
  944. you should expect the transitive closure to cover n/m nodes before
  945. an unused node is found. Sum(i=1..n)(n/i) is about nlogn, so expect
  946. this approach to take about nlogn time to map all single-key b's.
  947. -------------------------------------------------------------------------------
  948. */
  949. static int augment(bstuff *tabb, hstuff *tabh, qstuff *tabq, ub4 blen, ub4 *scramble, ub4 smax, bstuff *item, ub4 nkeys,
  950. ub4 highwater)
  951. // bstuff *tabb; /* stuff indexed by b */
  952. // hstuff *tabh; /* which key is associated with which hash, indexed by hash */
  953. // qstuff *tabq; /* queue of *b* values, this is the spanning tree */
  954. // ub4 blen; /* length of tabb */
  955. // ub4 *scramble; /* final hash is a^scramble[tab[b]] */
  956. // ub4 smax; /* highest value in scramble */
  957. // bstuff *item; /* &tabb[b] for the b to be mapped */
  958. // ub4 nkeys; /* final hash must be in 0..nkeys-1 */
  959. // ub4 highwater; /* a value higher than any now in tabb[].water_b */
  960. {
  961. ub4 q; /* current position walking through the queue */
  962. ub4 tail; /* tail of the queue. 0 is the head of the queue. */
  963. ub4 limit=UB1MAXVAL+1;
  964. ub4 highhash = smax;
  965. /* initialize the root of the spanning tree */
  966. tabq[0].b_q = item;
  967. tail = 1;
  968. /* construct the spanning tree by walking the queue, add children to tail */
  969. for (q=0; q<tail; ++q)
  970. {
  971. bstuff *myb = tabq[q].b_q; /* the b for this node */
  972. ub4 i; /* possible value for myb->val_b */
  973. if (q == 1)
  974. break; /* don't do transitive closure */
  975. for (i=0; i<limit; ++i)
  976. {
  977. bstuff *childb = (bstuff *)0; /* the b that this i maps to */
  978. key *mykey; /* for walking through myb's keys */
  979. for (mykey = myb->list_b; mykey; mykey=mykey->nextb_k)
  980. {
  981. key *childkey;
  982. ub4 hash = mykey->a_k^scramble[i];
  983. if (hash >= highhash) break; /* out of bounds */
  984. childkey = tabh[hash].key_h;
  985. if (childkey)
  986. {
  987. bstuff *hitb = &tabb[childkey->b_k];
  988. if (childb)
  989. {
  990. if (childb != hitb) break; /* hit at most one child b */
  991. }
  992. else
  993. {
  994. childb = hitb; /* remember this as childb */
  995. if (childb->water_b == highwater) break; /* already explored */
  996. }
  997. }
  998. }
  999. if (mykey) continue; /* myb with i has multiple collisions */
  1000. /* add childb to the queue of reachable things */
  1001. if (childb) childb->water_b = highwater;
  1002. tabq[tail].b_q = childb;
  1003. tabq[tail].newval_q = i; /* how to make parent (myb) use this hash */
  1004. tabq[tail].oldval_q = myb->val_b; /* need this for rollback */
  1005. tabq[tail].parent_q = q;
  1006. ++tail;
  1007. if (!childb)
  1008. { /* found an *i* with no collisions? */
  1009. /* try to apply the augmenting path */
  1010. if (apply(tabb, tabh, tabq, blen, scramble, tail, FALSE))
  1011. return TRUE; /* success, item was added to the perfect hash */
  1012. --tail; /* don't know how to handle such a child! */
  1013. }
  1014. }
  1015. }
  1016. return FALSE;
  1017. }
  1018. /* find a mapping that makes this a perfect hash */
  1019. static int perfect(bstuff *tabb, hstuff *tabh, qstuff *tabq, ub4 blen, ub4 smax, ub4 *scramble, ub4 nkeys)
  1020. {
  1021. ub4 maxkeys; /* maximum number of keys for any b */
  1022. ub4 i, j;
  1023. #if SELOPT_DEBUG
  1024. fprintf(stderr, " blen %d smax %d nkeys %d\n", blen, smax, nkeys);
  1025. #endif
  1026. /* clear any state from previous attempts */
  1027. memset((void *)tabh, 0, sizeof(hstuff)*smax);
  1028. memset((void *)tabq, 0, sizeof(qstuff)*(blen+1));
  1029. for (maxkeys=0,i=0; i<blen; ++i)
  1030. if (tabb[i].listlen_b > maxkeys)
  1031. maxkeys = tabb[i].listlen_b;
  1032. /* In descending order by number of keys, map all *b*s */
  1033. for (j=maxkeys; j>0; --j)
  1034. for (i=0; i<blen; ++i)
  1035. if (tabb[i].listlen_b == j)
  1036. if (!augment(tabb, tabh, tabq, blen, scramble, smax, &tabb[i], nkeys,
  1037. i+1))
  1038. {
  1039. return FALSE;
  1040. }
  1041. /* Success! We found a perfect hash of all keys into 0..nkeys-1. */
  1042. return TRUE;
  1043. }
  1044. /* guess initial values for alen and blen */
  1045. static void initalen(ub4 *alen, ub4 *blen, ub4 smax, ub4 nkeys)
  1046. // ub4 *alen; /* output, initial alen */
  1047. // ub4 *blen; /* output, initial blen */
  1048. // ub4 smax; /* input, power of two greater or equal to max hash value */
  1049. // ub4 nkeys; /* number of keys being hashed */
  1050. {
  1051. /*
  1052. * Find initial *alen, *blen
  1053. * Initial alen and blen values were found empirically. Some factors:
  1054. *
  1055. * If smax<256 there is no scramble, so tab[b] needs to cover 0..smax-1.
  1056. *
  1057. * alen and blen must be powers of 2 because the values in 0..alen-1 and
  1058. * 0..blen-1 are produced by applying a bitmask to the initial hash function.
  1059. *
  1060. * alen must be less than smax, in fact less than nkeys, because otherwise
  1061. * there would often be no i such that a^scramble[i] is in 0..nkeys-1 for
  1062. * all the *a*s associated with a given *b*, so there would be no legal
  1063. * value to assign to tab[b]. This only matters when we're doing a minimal
  1064. * perfect hash.
  1065. *
  1066. * It takes around 800 trials to find distinct (a,b) with nkey=smax*(5/8)
  1067. * and alen*blen = smax*smax/32.
  1068. *
  1069. * Values of blen less than smax/4 never work, and smax/2 always works.
  1070. *
  1071. * We want blen as small as possible because it is the number of bytes in
  1072. * the huge array we must create for the perfect hash.
  1073. *
  1074. * When nkey <= smax*(5/8), blen=smax/4 works much more often with
  1075. * alen=smax/8 than with alen=smax/4. Above smax*(5/8), blen=smax/4
  1076. * doesn't seem to care whether alen=smax/8 or alen=smax/4. I think it
  1077. * has something to do with 5/8 = 1/8 * 5. For example examine 80000,
  1078. * 85000, and 90000 keys with different values of alen. This only matters
  1079. * if we're doing a minimal perfect hash.
  1080. *
  1081. * When alen*blen <= 1<<UB4BITS, the initial hash must produce one integer.
  1082. * Bigger than that it must produce two integers, which increases the
  1083. * cost of the hash per character hashed.
  1084. */
  1085. *alen = smax; /* no reason to restrict alen to smax/2 */
  1086. *blen = ((nkeys <= smax*0.6) ? smax/16 :
  1087. (nkeys <= smax*0.8) ? smax/8 : smax/4);
  1088. if (*alen < 1) *alen = 1;
  1089. if (*blen < 1) *blen = 1;
  1090. #if SELOPT_DEBUG
  1091. fprintf(stderr, "alen %d blen %d smax %d nkeys %d\n", *alen, *blen, smax, nkeys);
  1092. #endif
  1093. }
  1094. /*
  1095. ** Try to find a perfect hash function.
  1096. ** Return the successful initializer for the initial hash.
  1097. ** Return 0 if no perfect hash could be found.
  1098. */
  1099. static int findhash(bstuff **tabb, ub4 *alen, ub4 *blen, ub8 *salt,
  1100. ub4 *scramble, ub4 smax, key *keys, ub4 nkeys)
  1101. // bstuff **tabb; /* output, tab[] of the perfect hash, length *blen */
  1102. // ub4 *alen; /* output, 0..alen-1 is range for a of (a,b) */
  1103. // ub4 *blen; /* output, 0..blen-1 is range for b of (a,b) */
  1104. // ub4 *salt; /* output, initializes initial hash */
  1105. // ub4 *scramble; /* input, hash = a^scramble[tab[b]] */
  1106. // ub4 smax; /* input, scramble[i] in 0..smax-1 */
  1107. // key *keys; /* input, keys to hash */
  1108. // ub4 nkeys; /* input, number of keys being hashed */
  1109. {
  1110. ub4 bad_initkey; /* how many times did initkey fail? */
  1111. ub4 bad_perfect; /* how many times did perfect fail? */
  1112. ub4 si; /* trial initializer for initial hash */
  1113. ub4 maxalen;
  1114. hstuff *tabh; /* table of keys indexed by hash value */
  1115. qstuff *tabq; /* table of stuff indexed by queue value, used by augment */
  1116. /* guess initial values for alen and blen */
  1117. initalen(alen, blen, smax, nkeys);
  1118. scrambleinit(scramble, smax);
  1119. maxalen = smax;
  1120. /* allocate working memory */
  1121. *tabb = new bstuff[*blen];
  1122. tabq = new qstuff[*blen+1];
  1123. tabh = new hstuff[smax];
  1124. /* Actually find the perfect hash */
  1125. *salt = 0;
  1126. bad_initkey = 0;
  1127. bad_perfect = 0;
  1128. for (si=1; ; ++si)
  1129. {
  1130. ub4 rslinit;
  1131. /* Try to find distinct (A,B) for all keys */
  1132. *salt = si * 0x9e3779b97f4a7c13LL; /* golden ratio (arbitrary value) */
  1133. initnorm(keys, nkeys, *alen, *blen, smax, *salt);
  1134. rslinit = inittab(*tabb, *blen, keys, nkeys, FALSE);
  1135. if (rslinit == 0)
  1136. {
  1137. /* didn't find distinct (a,b) */
  1138. if (++bad_initkey >= RETRY_INITKEY)
  1139. {
  1140. /* Try to put more bits in (A,B) to make distinct (A,B) more likely */
  1141. if (*alen < maxalen)
  1142. {
  1143. *alen *= 2;
  1144. }
  1145. else if (*blen < smax)
  1146. {
  1147. *blen *= 2;
  1148. delete[] tabq;
  1149. delete[] *tabb;
  1150. *tabb = new bstuff[*blen];
  1151. tabq = new qstuff[*blen+1];
  1152. }
  1153. bad_initkey = 0;
  1154. bad_perfect = 0;
  1155. }
  1156. continue; /* two keys have same (a,b) pair */
  1157. }
  1158. /* Given distinct (A,B) for all keys, build a perfect hash */
  1159. if (!perfect(*tabb, tabh, tabq, *blen, smax, scramble, nkeys))
  1160. {
  1161. if (++bad_perfect >= RETRY_PERFECT)
  1162. {
  1163. if (*blen < smax)
  1164. {
  1165. *blen *= 2;
  1166. delete[] *tabb;
  1167. delete[] tabq;
  1168. *tabb = new bstuff[*blen];
  1169. tabq = new qstuff[*blen+1];
  1170. --si; /* we know this salt got distinct (A,B) */
  1171. }
  1172. else
  1173. {
  1174. return 0;
  1175. }
  1176. bad_perfect = 0;
  1177. }
  1178. continue;
  1179. }
  1180. break;
  1181. }
  1182. /* free working memory */
  1183. delete[] tabh;
  1184. delete[] tabq;
  1185. return 1;
  1186. }
  1187. /*
  1188. ------------------------------------------------------------------------------
  1189. Input/output type routines
  1190. ------------------------------------------------------------------------------
  1191. */
  1192. /* get the list of keys */
  1193. static void getkeys(key **keys, ub4 *nkeys, const string_map& strings)
  1194. {
  1195. key *buf = new key[strings.size()];
  1196. size_t i;
  1197. string_map::const_iterator s;
  1198. for (i = 0, s = strings.begin(); s != strings.end(); ++s, ++i) {
  1199. key *mykey = buf+i;
  1200. mykey->name_k = (ub1 *)s->first;
  1201. mykey->len_k = (ub4)strlen(s->first);
  1202. }
  1203. *keys = buf;
  1204. *nkeys = (ub4)strings.size();
  1205. }
  1206. static perfect_hash
  1207. make_perfect(const string_map& strings)
  1208. {
  1209. ub4 nkeys; /* number of keys */
  1210. key *keys; /* head of list of keys */
  1211. bstuff *tab; /* table indexed by b */
  1212. ub4 smax; /* scramble[] values in 0..smax-1, a power of 2 */
  1213. ub4 alen; /* a in 0..alen-1, a power of 2 */
  1214. ub4 blen; /* b in 0..blen-1, a power of 2 */
  1215. ub8 salt; /* a parameter to the hash function */
  1216. ub4 scramble[SCRAMBLE_LEN]; /* used in final hash function */
  1217. int ok;
  1218. uint32_t i;
  1219. perfect_hash result;
  1220. /* read in the list of keywords */
  1221. getkeys(&keys, &nkeys, strings);
  1222. /* find the hash */
  1223. smax = ((ub4)1<<log2u(nkeys));
  1224. ok = findhash(&tab, &alen, &blen, &salt,
  1225. scramble, smax, keys, nkeys);
  1226. if (!ok) {
  1227. smax = 2 * ((ub4)1<<log2u(nkeys));
  1228. ok = findhash(&tab, &alen, &blen, &salt,
  1229. scramble, smax, keys, nkeys);
  1230. }
  1231. if (!ok) {
  1232. bzero(&result, sizeof(result));
  1233. } else {
  1234. /* build the tables */
  1235. result.capacity = smax;
  1236. result.occupied = nkeys;
  1237. result.shift = UB8BITS - log2u(alen);
  1238. result.mask = blen - 1;
  1239. result.salt = salt;
  1240. result.tab = new uint8_t[blen];
  1241. for (i = 0; i < blen; i++) {
  1242. result.tab[i] = tab[i].val_b;
  1243. }
  1244. for (i = 0; i < 256; i++) {
  1245. result.scramble[i] = scramble[i];
  1246. }
  1247. }
  1248. delete[] keys;
  1249. delete[] tab;
  1250. return result;
  1251. }
  1252. // SELOPT_WRITE
  1253. #endif
  1254. // namespace objc_selopt
  1255. };
  1256. #undef S32
  1257. #undef S64
  1258. #endif