hmaptool 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296
  1. #!/usr/bin/env python
  2. from __future__ import print_function
  3. import json
  4. import optparse
  5. import os
  6. import struct
  7. import sys
  8. ###
  9. k_header_magic_LE = 'pamh'
  10. k_header_magic_BE = 'hmap'
  11. def hmap_hash(str):
  12. """hash(str) -> int
  13. Apply the "well-known" headermap hash function.
  14. """
  15. return sum((ord(c.lower()) * 13
  16. for c in str), 0)
  17. class HeaderMap(object):
  18. @staticmethod
  19. def frompath(path):
  20. with open(path, 'rb') as f:
  21. magic = f.read(4)
  22. if magic == k_header_magic_LE:
  23. endian_code = '<'
  24. elif magic == k_header_magic_BE:
  25. endian_code = '>'
  26. else:
  27. raise SystemExit("error: %s: not a headermap" % (
  28. path,))
  29. # Read the header information.
  30. header_fmt = endian_code + 'HHIIII'
  31. header_size = struct.calcsize(header_fmt)
  32. data = f.read(header_size)
  33. if len(data) != header_size:
  34. raise SystemExit("error: %s: truncated headermap header" % (
  35. path,))
  36. (version, reserved, strtable_offset, num_entries,
  37. num_buckets, max_value_len) = struct.unpack(header_fmt, data)
  38. if version != 1:
  39. raise SystemExit("error: %s: unknown headermap version: %r" % (
  40. path, version))
  41. if reserved != 0:
  42. raise SystemExit("error: %s: invalid reserved value in header" % (
  43. path,))
  44. # The number of buckets must be a power of two.
  45. if num_buckets == 0 or (num_buckets & num_buckets - 1) != 0:
  46. raise SystemExit("error: %s: invalid number of buckets" % (
  47. path,))
  48. # Read all of the buckets.
  49. bucket_fmt = endian_code + 'III'
  50. bucket_size = struct.calcsize(bucket_fmt)
  51. buckets_data = f.read(num_buckets * bucket_size)
  52. if len(buckets_data) != num_buckets * bucket_size:
  53. raise SystemExit("error: %s: truncated headermap buckets" % (
  54. path,))
  55. buckets = [struct.unpack(bucket_fmt,
  56. buckets_data[i*bucket_size:(i+1)*bucket_size])
  57. for i in range(num_buckets)]
  58. # Read the string table; the format doesn't explicitly communicate the
  59. # size of the string table (which is dumb), so assume it is the rest of
  60. # the file.
  61. f.seek(0, 2)
  62. strtable_size = f.tell() - strtable_offset
  63. f.seek(strtable_offset)
  64. if strtable_size == 0:
  65. raise SystemExit("error: %s: unable to read zero-sized string table"%(
  66. path,))
  67. strtable = f.read(strtable_size)
  68. if len(strtable) != strtable_size:
  69. raise SystemExit("error: %s: unable to read complete string table"%(
  70. path,))
  71. if strtable[-1] != '\0':
  72. raise SystemExit("error: %s: invalid string table in headermap" % (
  73. path,))
  74. return HeaderMap(num_entries, buckets, strtable)
  75. def __init__(self, num_entries, buckets, strtable):
  76. self.num_entries = num_entries
  77. self.buckets = buckets
  78. self.strtable = strtable
  79. def get_string(self, idx):
  80. if idx >= len(self.strtable):
  81. raise SystemExit("error: %s: invalid string index" % (
  82. path,))
  83. end_idx = self.strtable.index('\0', idx)
  84. return self.strtable[idx:end_idx]
  85. @property
  86. def mappings(self):
  87. for key_idx,prefix_idx,suffix_idx in self.buckets:
  88. if key_idx == 0:
  89. continue
  90. yield (self.get_string(key_idx),
  91. self.get_string(prefix_idx) + self.get_string(suffix_idx))
  92. ###
  93. def action_dump(name, args):
  94. "dump a headermap file"
  95. parser = optparse.OptionParser("%%prog %s [options] <headermap path>" % (
  96. name,))
  97. parser.add_option("-v", "--verbose", dest="verbose",
  98. help="show more verbose output [%default]",
  99. action="store_true", default=False)
  100. (opts, args) = parser.parse_args(args)
  101. if len(args) != 1:
  102. parser.error("invalid number of arguments")
  103. path, = args
  104. hmap = HeaderMap.frompath(path)
  105. # Dump all of the buckets.
  106. print ('Header Map: %s' % (path,))
  107. if opts.verbose:
  108. print ('headermap: %r' % (path,))
  109. print (' num entries: %d' % (hmap.num_entries,))
  110. print (' num buckets: %d' % (len(hmap.buckets),))
  111. print (' string table size: %d' % (len(hmap.strtable),))
  112. for i,bucket in enumerate(hmap.buckets):
  113. key_idx,prefix_idx,suffix_idx = bucket
  114. if key_idx == 0:
  115. continue
  116. # Get the strings.
  117. key = hmap.get_string(key_idx)
  118. prefix = hmap.get_string(prefix_idx)
  119. suffix = hmap.get_string(suffix_idx)
  120. print (" bucket[%d]: %r -> (%r, %r) -- %d" % (
  121. i, key, prefix, suffix, (hmap_hash(key) & (num_buckets - 1))))
  122. else:
  123. mappings = sorted(hmap.mappings)
  124. for key,value in mappings:
  125. print ("%s -> %s" % (key, value))
  126. print ()
  127. def next_power_of_two(value):
  128. if value < 0:
  129. raise ArgumentError
  130. return 1 if value == 0 else 2**(value - 1).bit_length()
  131. def action_write(name, args):
  132. "write a headermap file from a JSON definition"
  133. parser = optparse.OptionParser("%%prog %s [options] <input path> <output path>" % (
  134. name,))
  135. (opts, args) = parser.parse_args(args)
  136. if len(args) != 2:
  137. parser.error("invalid number of arguments")
  138. input_path,output_path = args
  139. with open(input_path, "r") as f:
  140. input_data = json.load(f)
  141. # Compute the headermap contents, we make a table that is 1/3 full.
  142. mappings = input_data['mappings']
  143. num_buckets = next_power_of_two(len(mappings) * 3)
  144. table = [(0, 0, 0)
  145. for i in range(num_buckets)]
  146. max_value_len = 0
  147. strtable = "\0"
  148. for key,value in mappings.items():
  149. if not isinstance(key, str):
  150. key = key.decode('utf-8')
  151. if not isinstance(value, str):
  152. value = value.decode('utf-8')
  153. max_value_len = max(max_value_len, len(value))
  154. key_idx = len(strtable)
  155. strtable += key + '\0'
  156. prefix = os.path.dirname(value) + '/'
  157. suffix = os.path.basename(value)
  158. prefix_idx = len(strtable)
  159. strtable += prefix + '\0'
  160. suffix_idx = len(strtable)
  161. strtable += suffix + '\0'
  162. hash = hmap_hash(key)
  163. for i in range(num_buckets):
  164. idx = (hash + i) % num_buckets
  165. if table[idx][0] == 0:
  166. table[idx] = (key_idx, prefix_idx, suffix_idx)
  167. break
  168. else:
  169. raise RuntimeError
  170. endian_code = '<'
  171. magic = k_header_magic_LE
  172. magic_size = 4
  173. header_fmt = endian_code + 'HHIIII'
  174. header_size = struct.calcsize(header_fmt)
  175. bucket_fmt = endian_code + 'III'
  176. bucket_size = struct.calcsize(bucket_fmt)
  177. strtable_offset = magic_size + header_size + num_buckets * bucket_size
  178. header = (1, 0, strtable_offset, len(mappings),
  179. num_buckets, max_value_len)
  180. # Write out the headermap.
  181. with open(output_path, 'wb') as f:
  182. f.write(magic.encode())
  183. f.write(struct.pack(header_fmt, *header))
  184. for bucket in table:
  185. f.write(struct.pack(bucket_fmt, *bucket))
  186. f.write(strtable.encode())
  187. def action_tovfs(name, args):
  188. "convert a headermap to a VFS layout"
  189. parser = optparse.OptionParser("%%prog %s [options] <headermap path>" % (
  190. name,))
  191. parser.add_option("", "--build-path", dest="build_path",
  192. help="build path prefix",
  193. action="store", type=str)
  194. (opts, args) = parser.parse_args(args)
  195. if len(args) != 2:
  196. parser.error("invalid number of arguments")
  197. if opts.build_path is None:
  198. parser.error("--build-path is required")
  199. input_path,output_path = args
  200. hmap = HeaderMap.frompath(input_path)
  201. # Create the table for all the objects.
  202. vfs = {}
  203. vfs['version'] = 0
  204. build_dir_contents = []
  205. vfs['roots'] = [{
  206. 'name' : opts.build_path,
  207. 'type' : 'directory',
  208. 'contents' : build_dir_contents }]
  209. # We assume we are mapping framework paths, so a key of "Foo/Bar.h" maps to
  210. # "<build path>/Foo.framework/Headers/Bar.h".
  211. for key,value in hmap.mappings:
  212. # If this isn't a framework style mapping, ignore it.
  213. components = key.split('/')
  214. if len(components) != 2:
  215. continue
  216. framework_name,header_name = components
  217. build_dir_contents.append({
  218. 'name' : '%s.framework/Headers/%s' % (framework_name,
  219. header_name),
  220. 'type' : 'file',
  221. 'external-contents' : value })
  222. with open(output_path, 'w') as f:
  223. json.dump(vfs, f, indent=2)
  224. commands = dict((name[7:].replace("_","-"), f)
  225. for name,f in locals().items()
  226. if name.startswith('action_'))
  227. def usage():
  228. print ("Usage: %s command [options]" % (
  229. os.path.basename(sys.argv[0])), file=sys.stderr)
  230. print (file=sys.stderr)
  231. print ("Available commands:", file=sys.stderr)
  232. cmds_width = max(map(len, commands))
  233. for name,func in sorted(commands.items()):
  234. print (" %-*s - %s" % (cmds_width, name, func.__doc__), file=sys.stderr)
  235. sys.exit(1)
  236. def main():
  237. if len(sys.argv) < 2 or sys.argv[1] not in commands:
  238. usage()
  239. cmd = sys.argv[1]
  240. commands[cmd](cmd, sys.argv[2:])
  241. if __name__ == '__main__':
  242. main()