make_dafsa.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482
  1. #!/usr/bin/env python3
  2. # Copyright 2017 The Chromium Authors. All rights reserved.
  3. # Use of this source code is governed by a BSD-style license that can be
  4. # found in the LICENSE file.
  5. from __future__ import print_function
  6. import array
  7. import json
  8. import sys
  9. import os
  10. import urllib.parse
  11. """
  12. A Deterministic acyclic finite state automaton (DAFSA) is a compact
  13. representation of an unordered word list (dictionary).
  14. https://en.wikipedia.org/wiki/Deterministic_acyclic_finite_state_automaton
  15. This python program converts a list of strings to a byte array in C++.
  16. This python program fetches strings and return values from a gperf file
  17. and generates a C++ file with a byte array representing graph that can be
  18. used as a memory efficient replacement for the perfect hash table.
  19. The input strings are assumed to consist of printable 7-bit ASCII characters
  20. and the return values are assumed to be one digit integers.
  21. In this program a DAFSA is a diamond shaped graph starting at a common
  22. source node and ending at a common sink node. All internal nodes contain
  23. a label and each word is represented by the labels in one path from
  24. the source node to the sink node.
  25. The following python represention is used for nodes:
  26. Source node: [ children ]
  27. Internal node: (label, [ children ])
  28. Sink node: None
  29. The graph is first compressed by prefixes like a trie. In the next step
  30. suffixes are compressed so that the graph gets diamond shaped. Finally
  31. one to one linked nodes are replaced by nodes with the labels joined.
  32. The order of the operations is crucial since lookups will be performed
  33. starting from the source with no backtracking. Thus a node must have at
  34. most one child with a label starting by the same character. The output
  35. is also arranged so that all jumps are to increasing addresses, thus forward
  36. in memory.
  37. The generated output has suffix free decoding so that the sign of leading
  38. bits in a link (a reference to a child node) indicate if it has a size of one,
  39. two or three bytes and if it is the last outgoing link from the actual node.
  40. A node label is terminated by a byte with the leading bit set.
  41. The generated byte array can described by the following BNF:
  42. <byte> ::= < 8-bit value in range [0x00-0xFF] >
  43. <char> ::= < printable 7-bit ASCII character, byte in range [0x20-0x7F] >
  44. <end_char> ::= < char + 0x80, byte in range [0xA0-0xFF] >
  45. <return value> ::= < value + 0x80, byte in range [0x80-0x8F] >
  46. <offset1> ::= < byte in range [0x00-0x3F] >
  47. <offset2> ::= < byte in range [0x40-0x5F] >
  48. <offset3> ::= < byte in range [0x60-0x7F] >
  49. <end_offset1> ::= < byte in range [0x80-0xBF] >
  50. <end_offset2> ::= < byte in range [0xC0-0xDF] >
  51. <end_offset3> ::= < byte in range [0xE0-0xFF] >
  52. <prefix> ::= <char>
  53. <label> ::= <end_char>
  54. | <char> <label>
  55. <end_label> ::= <return_value>
  56. | <char> <end_label>
  57. <offset> ::= <offset1>
  58. | <offset2> <byte>
  59. | <offset3> <byte> <byte>
  60. <end_offset> ::= <end_offset1>
  61. | <end_offset2> <byte>
  62. | <end_offset3> <byte> <byte>
  63. <offsets> ::= <end_offset>
  64. | <offset> <offsets>
  65. <source> ::= <offsets>
  66. <node> ::= <label> <offsets>
  67. | <prefix> <node>
  68. | <end_label>
  69. <dafsa> ::= <source>
  70. | <dafsa> <node>
  71. Decoding:
  72. <char> -> printable 7-bit ASCII character
  73. <end_char> & 0x7F -> printable 7-bit ASCII character
  74. <return value> & 0x0F -> integer
  75. <offset1 & 0x3F> -> integer
  76. ((<offset2> & 0x1F>) << 8) + <byte> -> integer
  77. ((<offset3> & 0x1F>) << 16) + (<byte> << 8) + <byte> -> integer
  78. end_offset1, end_offset2 and and_offset3 are decoded same as offset1,
  79. offset2 and offset3 respectively.
  80. The first offset in a list of offsets is the distance in bytes between the
  81. offset itself and the first child node. Subsequent offsets are the distance
  82. between previous child node and next child node. Thus each offset links a node
  83. to a child node. The distance is always counted between start addresses, i.e.
  84. first byte in decoded offset or first byte in child node.
  85. Example 1:
  86. %%
  87. aa, 1
  88. a, 2
  89. %%
  90. The input is first parsed to a list of words:
  91. ["aa1", "a2"]
  92. A fully expanded graph is created from the words:
  93. source = [node1, node4]
  94. node1 = ("a", [node2])
  95. node2 = ("a", [node3])
  96. node3 = ("\x01", [sink])
  97. node4 = ("a", [node5])
  98. node5 = ("\x02", [sink])
  99. sink = None
  100. Compression results in the following graph:
  101. source = [node1]
  102. node1 = ("a", [node2, node3])
  103. node2 = ("\x02", [sink])
  104. node3 = ("a\x01", [sink])
  105. sink = None
  106. A C++ representation of the compressed graph is generated:
  107. const unsigned char dafsa[7] = {
  108. 0x81, 0xE1, 0x02, 0x81, 0x82, 0x61, 0x81,
  109. };
  110. The bytes in the generated array has the following meaning:
  111. 0: 0x81 <end_offset1> child at position 0 + (0x81 & 0x3F) -> jump to 1
  112. 1: 0xE1 <end_char> label character (0xE1 & 0x7F) -> match "a"
  113. 2: 0x02 <offset1> child at position 2 + (0x02 & 0x3F) -> jump to 4
  114. 3: 0x81 <end_offset1> child at position 4 + (0x81 & 0x3F) -> jump to 5
  115. 4: 0x82 <return_value> 0x82 & 0x0F -> return 2
  116. 5: 0x61 <char> label character 0x61 -> match "a"
  117. 6: 0x81 <return_value> 0x81 & 0x0F -> return 1
  118. Example 2:
  119. %%
  120. aa, 1
  121. bbb, 2
  122. baa, 1
  123. %%
  124. The input is first parsed to a list of words:
  125. ["aa1", "bbb2", "baa1"]
  126. Compression results in the following graph:
  127. source = [node1, node2]
  128. node1 = ("b", [node2, node3])
  129. node2 = ("aa\x01", [sink])
  130. node3 = ("bb\x02", [sink])
  131. sink = None
  132. A C++ representation of the compressed graph is generated:
  133. const unsigned char dafsa[11] = {
  134. 0x02, 0x83, 0xE2, 0x02, 0x83, 0x61, 0x61, 0x81, 0x62, 0x62, 0x82,
  135. };
  136. The bytes in the generated array has the following meaning:
  137. 0: 0x02 <offset1> child at position 0 + (0x02 & 0x3F) -> jump to 2
  138. 1: 0x83 <end_offset1> child at position 2 + (0x83 & 0x3F) -> jump to 5
  139. 2: 0xE2 <end_char> label character (0xE2 & 0x7F) -> match "b"
  140. 3: 0x02 <offset1> child at position 3 + (0x02 & 0x3F) -> jump to 5
  141. 4: 0x83 <end_offset1> child at position 5 + (0x83 & 0x3F) -> jump to 8
  142. 5: 0x61 <char> label character 0x61 -> match "a"
  143. 6: 0x61 <char> label character 0x61 -> match "a"
  144. 7: 0x81 <return_value> 0x81 & 0x0F -> return 1
  145. 8: 0x62 <char> label character 0x62 -> match "b"
  146. 9: 0x62 <char> label character 0x62 -> match "b"
  147. 10: 0x82 <return_value> 0x82 & 0x0F -> return 2
  148. """
  149. HTTPS_ONLY = 0
  150. HTTP_AND_HTTPS = 1
  151. class InputError(Exception):
  152. """Exception raised for errors in the input file."""
  153. def to_dafsa(words):
  154. """Generates a DAFSA from a word list and returns the source node.
  155. Each word is split into characters so that each character is represented by
  156. a unique node. It is assumed the word list is not empty.
  157. """
  158. if not words:
  159. raise InputError('The origin list must not be empty')
  160. def ToNodes(word):
  161. """Split words into characters"""
  162. if not 0x1F < ord(word[0]) < 0x80:
  163. raise InputError('Origins must be printable 7-bit ASCII')
  164. if len(word) == 1:
  165. return chr(ord(word[0]) & 0x0F), [None]
  166. return word[0], [ToNodes(word[1:])]
  167. return [ToNodes(word) for word in words]
  168. def to_words(node):
  169. """Generates a word list from all paths starting from an internal node."""
  170. if not node:
  171. return ['']
  172. return [(node[0] + word) for child in node[1] for word in to_words(child)]
  173. def reverse(dafsa):
  174. """Generates a new DAFSA that is reversed, so that the old sink node becomes
  175. the new source node.
  176. """
  177. sink = []
  178. nodemap = {}
  179. def dfs(node, parent):
  180. """Creates reverse nodes.
  181. A new reverse node will be created for each old node. The new node will
  182. get a reversed label and the parents of the old node as children.
  183. """
  184. if not node:
  185. sink.append(parent)
  186. elif id(node) not in nodemap:
  187. nodemap[id(node)] = (node[0][::-1], [parent])
  188. for child in node[1]:
  189. dfs(child, nodemap[id(node)])
  190. else:
  191. nodemap[id(node)][1].append(parent)
  192. for node in dafsa:
  193. dfs(node, None)
  194. return sink
  195. def join_labels(dafsa):
  196. """Generates a new DAFSA where internal nodes are merged if there is a one to
  197. one connection.
  198. """
  199. parentcount = { id(None): 2 }
  200. nodemap = { id(None): None }
  201. def count_parents(node):
  202. """Count incoming references"""
  203. if id(node) in parentcount:
  204. parentcount[id(node)] += 1
  205. else:
  206. parentcount[id(node)] = 1
  207. for child in node[1]:
  208. count_parents(child)
  209. def join(node):
  210. """Create new nodes"""
  211. if id(node) not in nodemap:
  212. children = [join(child) for child in node[1]]
  213. if len(children) == 1 and parentcount[id(node[1][0])] == 1:
  214. child = children[0]
  215. nodemap[id(node)] = (node[0] + child[0], child[1])
  216. else:
  217. nodemap[id(node)] = (node[0], children)
  218. return nodemap[id(node)]
  219. for node in dafsa:
  220. count_parents(node)
  221. return [join(node) for node in dafsa]
  222. def join_suffixes(dafsa):
  223. """Generates a new DAFSA where nodes that represent the same word lists
  224. towards the sink are merged.
  225. """
  226. nodemap = { frozenset(('',)): None }
  227. def join(node):
  228. """Returns a macthing node. A new node is created if no matching node
  229. exists. The graph is accessed in dfs order.
  230. """
  231. suffixes = frozenset(to_words(node))
  232. if suffixes not in nodemap:
  233. nodemap[suffixes] = (node[0], [join(child) for child in node[1]])
  234. return nodemap[suffixes]
  235. return [join(node) for node in dafsa]
  236. def top_sort(dafsa):
  237. """Generates list of nodes in topological sort order."""
  238. incoming = {}
  239. def count_incoming(node):
  240. """Counts incoming references."""
  241. if node:
  242. if id(node) not in incoming:
  243. incoming[id(node)] = 1
  244. for child in node[1]:
  245. count_incoming(child)
  246. else:
  247. incoming[id(node)] += 1
  248. for node in dafsa:
  249. count_incoming(node)
  250. for node in dafsa:
  251. incoming[id(node)] -= 1
  252. waiting = [node for node in dafsa if incoming[id(node)] == 0]
  253. nodes = []
  254. while waiting:
  255. node = waiting.pop()
  256. assert incoming[id(node)] == 0
  257. nodes.append(node)
  258. for child in node[1]:
  259. if child:
  260. incoming[id(child)] -= 1
  261. if incoming[id(child)] == 0:
  262. waiting.append(child)
  263. return nodes
  264. def encode_links(children, offsets, current):
  265. """Encodes a list of children as one, two or three byte offsets."""
  266. if not children[0]:
  267. # This is an <end_label> node and no links follow such nodes
  268. assert len(children) == 1
  269. return []
  270. guess = 3 * len(children)
  271. assert children
  272. children = sorted(children, key = lambda x: -offsets[id(x)])
  273. while True:
  274. offset = current + guess
  275. buf = []
  276. for child in children:
  277. last = len(buf)
  278. distance = offset - offsets[id(child)]
  279. assert distance > 0 and distance < (1 << 21)
  280. if distance < (1 << 6):
  281. # A 6-bit offset: "s0xxxxxx"
  282. buf.append(distance)
  283. elif distance < (1 << 13):
  284. # A 13-bit offset: "s10xxxxxxxxxxxxx"
  285. buf.append(0x40 | (distance >> 8))
  286. buf.append(distance & 0xFF)
  287. else:
  288. # A 21-bit offset: "s11xxxxxxxxxxxxxxxxxxxxx"
  289. buf.append(0x60 | (distance >> 16))
  290. buf.append((distance >> 8) & 0xFF)
  291. buf.append(distance & 0xFF)
  292. # Distance in first link is relative to following record.
  293. # Distance in other links are relative to previous link.
  294. offset -= distance
  295. if len(buf) == guess:
  296. break
  297. guess = len(buf)
  298. # Set most significant bit to mark end of links in this node.
  299. buf[last] |= (1 << 7)
  300. buf.reverse()
  301. return buf
  302. def encode_prefix(label):
  303. """Encodes a node label as a list of bytes without a trailing high byte.
  304. This method encodes a node if there is exactly one child and the
  305. child follows immidiately after so that no jump is needed. This label
  306. will then be a prefix to the label in the child node.
  307. """
  308. assert label
  309. return [ord(c) for c in reversed(label)]
  310. def encode_label(label):
  311. """Encodes a node label as a list of bytes with a trailing high byte >0x80.
  312. """
  313. buf = encode_prefix(label)
  314. # Set most significant bit to mark end of label in this node.
  315. buf[0] |= (1 << 7)
  316. return buf
  317. def encode(dafsa):
  318. """Encodes a DAFSA to a list of bytes"""
  319. output = []
  320. offsets = {}
  321. for node in reversed(top_sort(dafsa)):
  322. if (len(node[1]) == 1 and node[1][0] and
  323. (offsets[id(node[1][0])] == len(output))):
  324. output.extend(encode_prefix(node[0]))
  325. else:
  326. output.extend(encode_links(node[1], offsets, len(output)))
  327. output.extend(encode_label(node[0]))
  328. offsets[id(node)] = len(output)
  329. output.extend(encode_links(dafsa, offsets, len(output)))
  330. output.reverse()
  331. return bytes(output)
  332. def words_to_encoded_dafsa(words):
  333. """Generates an encoded DAFSA from a word list"""
  334. dafsa = to_dafsa(words)
  335. for fun in (reverse, join_suffixes, reverse, join_suffixes, join_labels):
  336. dafsa = fun(dafsa)
  337. return encode(dafsa)
  338. def parse_json(infile):
  339. """Parses the JSON input file and appends a 0 or 1 based on protocol."""
  340. try:
  341. netlocs = {}
  342. for entry in json.loads(infile):
  343. # Parse the origin and reject any with an invalid protocol.
  344. parsed = urllib.parse.urlparse(entry)
  345. if parsed.scheme != 'http' and parsed.scheme != 'https':
  346. raise InputError('Invalid protocol: %s' % entry)
  347. # Store the netloc in netlocs with a flag for either HTTP+HTTPS or HTTPS
  348. # only. The HTTP+HTTPS value is numerically higher than HTTPS only so it
  349. # will take priority.
  350. netlocs[parsed.netloc] = max(
  351. netlocs.get(parsed.netloc, HTTPS_ONLY),
  352. HTTP_AND_HTTPS if parsed.scheme == 'http' else HTTPS_ONLY)
  353. # Join the numerical values to the netlocs.
  354. output = []
  355. for location, value in netlocs.items():
  356. output.append(location + str(value))
  357. return output
  358. except ValueError:
  359. raise InputError('Failed to parse JSON.')
  360. def main():
  361. if len(sys.argv) != 4:
  362. print('usage: %s builddir infile outfile' % sys.argv[0])
  363. return 1
  364. pyproto = os.path.join(sys.argv[1], 'pyproto')
  365. sys.path.insert(0, pyproto)
  366. sys.path.insert(0, os.path.join(pyproto, 'chrome', 'browser', 'media'))
  367. import media_engagement_preload_pb2
  368. with open(sys.argv[2], 'r') as infile, open(sys.argv[3], 'wb') as outfile:
  369. dafsa = words_to_encoded_dafsa(parse_json(infile.read()))
  370. message = media_engagement_preload_pb2.PreloadedData()
  371. message.dafsa = dafsa
  372. outfile.write(message.SerializeToString())
  373. return 0
  374. if __name__ == '__main__':
  375. sys.exit(main())