Debian Codegraph @

rpython/rlib/rsiphash.py

raw symbols SCIP
1 """
2 This module implements siphash-2-4, the hashing algorithm for strings
3 and unicodes. You can use it explicitly by calling siphash24() with
4 a byte string, or you can use enable_siphash24() to enable the use
5 of siphash-2-4 on all RPython strings and unicodes in your program
6 after translation.
7 """
8 import sys, os, errno
9 from contextlib import contextmanager
10 from rpython.rlib import rarithmetic, rurandom
11 from rpython.rlib.objectmodel import not_rpython, always_inline
12 from rpython.rlib.objectmodel import we_are_translated, dont_inline
13 from rpython.rlib.objectmodel import keepalive_until_here
14 from rpython.rlib.objectmodel import specialize
15 from rpython.rlib import rgc, jit, rposix
16 from rpython.rlib.rarithmetic import r_uint64, r_uint32, r_uint
17 from rpython.rlib.rawstorage import misaligned_is_fine
18 from rpython.rlib.nonconst import NonConstant
19 from rpython.rtyper.lltypesystem import lltype, llmemory, rffi, rstr
20 from rpython.rtyper.lltypesystem.lloperation import llop
21 from rpython.rtyper.extregistry import ExtRegistryEntry
22 from rpython.rtyper.annlowlevel import llhelper
23
24
25 if sys.byteorder == 'little':
26 def _le64toh(x):
27 return x
28 def _le32toh(x):
29 return x
30 BIG_ENDIAN = False
31 else:
32 _le64toh = rarithmetic.byteswap
33 _le32toh = rarithmetic.byteswap
34 BIG_ENDIAN = True
35
36 def _decode64(s):
37 return (r_uint64(ord(s[0])) |
38 r_uint64(ord(s[1])) << 8 |
39 r_uint64(ord(s[2])) << 16 |
40 r_uint64(ord(s[3])) << 24 |
41 r_uint64(ord(s[4])) << 32 |
42 r_uint64(ord(s[5])) << 40 |
43 r_uint64(ord(s[6])) << 48 |
44 r_uint64(ord(s[7])) << 56)
45
46 class Seed:
47 k0l = k1l = r_uint64(0)
48 seed = Seed()
49
50
51 def select_random_seed(s):
52 """'s' is a string of length 16"""
53 seed.k0l = _decode64(s)
54 seed.k1l = _decode64(s[8:16])
55 _update_prebuilt_hashes()
56
57
58 strtoul = rffi.llexternal("strtoul", [rffi.CCHARP, rffi.CCHARPP, rffi.INT],
59 rffi.ULONG, save_err=rffi.RFFI_SAVE_ERRNO)
60
61 env_var_name = "PYTHONHASHSEED"
62
63 def initialize_from_env():
64 # This uses the same algorithms as CPython 3.5. The environment
65 # variable we read also defaults to "PYTHONHASHSEED". If needed,
66 # a different RPython interpreter can patch the value of the
67 # global variable 'env_var_name', or just patch the whole
68 # initialize_from_env() function.
69 value = os.environ.get(env_var_name)
70 if value and value != "random":
71 with rffi.scoped_view_charp(value) as ptr:
72 with lltype.scoped_alloc(rffi.CCHARPP.TO, 1) as endptr:
73 endptr[0] = ptr
74 seed = strtoul(ptr, endptr, 10)
75 full = endptr[0][0] == '\x00'
76 seed = lltype.cast_primitive(lltype.Unsigned, seed)
77 if not full or seed > r_uint(4294967295) or (
78 rposix.get_saved_errno() == errno.ERANGE and
79 seed == lltype.cast_primitive(lltype.Unsigned,
80 rffi.cast(rffi.ULONG, -1))):
81 os.write(2,
82 "%s must be \"random\" or an integer "
83 "in range [0; 4294967295]\n" % (env_var_name,))
84 os._exit(1)
85 if not seed:
86 # disable the randomized hash
87 s = '\x00' * 16
88 else:
89 s = lcg_urandom(seed)
90 else:
91 try:
92 s = rurandom.urandom(16)
93 except Exception as e:
94 os.write(2,
95 "%s: failed to get random numbers to initialize Python\n" %
96 (str(e),))
97 os._exit(1)
98 raise # makes the annotator happy
99 select_random_seed(s)
100
101 def lcg_urandom(x):
102 s = ''
103 for index in range(16):
104 x *= 214013
105 x += 2531011
106 s += chr((x >> 16) & 0xff)
107 return s
108
109
110 _FUNC = lltype.Ptr(lltype.FuncType([], lltype.Void))
111
112 def enable_siphash24():
113 """
114 Enable the use of siphash-2-4 for all RPython strings and unicodes
115 in the translated program. You must call this function anywhere
116 from your interpreter (from a place that is annotated). Don't call
117 more than once.
118 """
119
120 class Entry(ExtRegistryEntry):
121 _about_ = enable_siphash24
122
123 def compute_result_annotation(self):
124 translator = self.bookkeeper.annotator.translator
125 # you should not call enable_siphash24() when translating with the
126 # reverse-debugger, or with sandbox.
127 assert not translator.config.translation.reverse_debugger
128 assert not translator.config.translation.sandbox
129 #
130 if hasattr(translator, 'll_hash_string'):
131 assert translator.ll_hash_string == ll_hash_string_siphash24
132 else:
133 translator.ll_hash_string = ll_hash_string_siphash24
134 bk = self.bookkeeper
135 s_callable = bk.immutablevalue(initialize_from_env)
136 key = (enable_siphash24,)
137 bk.emulate_pbc_call(key, s_callable, [])
138
139 def specialize_call(self, hop):
140 hop.exception_cannot_occur()
141 translator = hop.rtyper.annotator.translator
142 if translator.config.translation.reverse_debugger:
143 return # ignore and use the regular hash, with reverse-debugger
144 bk = hop.rtyper.annotator.bookkeeper
145 s_callable = bk.immutablevalue(initialize_from_env)
146 r_callable = hop.rtyper.getrepr(s_callable)
147 ll_init = r_callable.get_unique_llfn().value
148 bk.annotator.translator._call_at_startup.append(ll_init)
149
150
151 @rgc.no_collect
152 def ll_hash_string_siphash24(ll_s):
153 """Called indirectly from lltypesystem/rstr.py, by redirection from
154 objectmodel.ll_string_hash().
155 """
156 from rpython.rlib.rarithmetic import intmask
157
158 # This function is entirely @rgc.no_collect.
159 length = len(ll_s.chars)
160 if lltype.typeOf(ll_s).TO.chars.OF == lltype.Char: # regular STR
161 addr = rstr._get_raw_buf_string(rstr.STR, ll_s, 0)
162 else:
163 # NOTE: a latin-1 unicode string must have the same hash as the
164 # corresponding byte string. If the unicode is all within
165 # 0-255, then we call _siphash24() with a special argument that
166 # will make it load only one byte for every unicode char.
167 # Note also that we give a
168 # different hash result than CPython on ucs4 platforms, for
169 # unicode strings where CPython uses 2 bytes per character.
170 addr = rstr._get_raw_buf_unicode(rstr.UNICODE, ll_s, 0)
171 SZ = rffi.sizeof(rstr.UNICODE.chars.OF)
172 i = 0
173 while i < length:
174 if ord(ll_s.chars[i]) > 0xFF:
175 length *= SZ
176 break
177 i += 1
178 else:
179 x = _siphash24(addr, length, SZ)
180 keepalive_until_here(ll_s)
181 return intmask(x)
182 x = _siphash24(addr, length)
183 keepalive_until_here(ll_s)
184 return intmask(x)
185
186
187 @contextmanager
188 def choosen_seed(new_k0, new_k1, test_misaligned_path=False,
189 test_prebuilt=False):
190 """For tests."""
191 global misaligned_is_fine, seed
192 old = seed, misaligned_is_fine
193 seed = Seed()
194 seed.k0l = r_uint64(new_k0)
195 seed.k1l = r_uint64(new_k1)
196 if test_prebuilt:
197 _update_prebuilt_hashes()
198 else:
199 seed.bound_prebuilt_size = 0
200 if test_misaligned_path:
201 misaligned_is_fine = False
202 yield
203 seed, misaligned_is_fine = old
204
205 magic0 = r_uint64(0x736f6d6570736575)
206 magic1 = r_uint64(0x646f72616e646f6d)
207 magic2 = r_uint64(0x6c7967656e657261)
208 magic3 = r_uint64(0x7465646279746573)
209
210
211 @always_inline
212 def _rotate(x, b):
213 return (x << b) | (x >> (64 - b))
214
215 @always_inline
216 def _half_round(a, b, c, d, s, t):
217 a += b
218 c += d
219 b = _rotate(b, s) ^ a
220 d = _rotate(d, t) ^ c
221 a = _rotate(a, 32)
222 return a, b, c, d
223
224 @always_inline
225 def _double_round(v0, v1, v2, v3):
226 v0,v1,v2,v3 = _half_round(v0,v1,v2,v3,13,16)
227 v2,v1,v0,v3 = _half_round(v2,v1,v0,v3,17,21)
228 v0,v1,v2,v3 = _half_round(v0,v1,v2,v3,13,16)
229 v2,v1,v0,v3 = _half_round(v2,v1,v0,v3,17,21)
230 return v0, v1, v2, v3
231
232
233 @rgc.no_collect
234 @specialize.arg(2)
235 def _siphash24(addr_in, size, SZ=1):
236 """Takes an address pointer and a size. Returns the hash as a r_uint64,
237 which can then be casted to the expected type."""
238
239 if size < seed.bound_prebuilt_size:
240 if size <= 0:
241 return seed.hash_empty
242 else:
243 if BIG_ENDIAN:
244 index = SZ - 1
245 else:
246 index = 0
247 t = rarithmetic.intmask(llop.raw_load(rffi.UCHAR, addr_in, index))
248 return seed.hash_single[t]
249
250 k0 = seed.k0l
251 k1 = seed.k1l
252 return _siphash24_with_key(addr_in, size, k0, k1, SZ)
253
254
255 @rgc.no_collect
256 @specialize.arg(4)
257 def _siphash24_with_key(addr_in, size, k0, k1, SZ=1):
258 if BIG_ENDIAN:
259 index = SZ - 1
260 else:
261 index = 0
262 b = r_uint64(size) << 56
263 v0 = k0 ^ magic0
264 v1 = k1 ^ magic1
265 v2 = k0 ^ magic2
266 v3 = k1 ^ magic3
267
268 direct = (SZ == 1) and (misaligned_is_fine or
269 (rffi.cast(lltype.Signed, addr_in) & 7) == 0)
270 if direct:
271 assert SZ == 1
272 while size >= 8:
273 mi = llop.raw_load(rffi.ULONGLONG, addr_in, index)
274 mi = _le64toh(mi)
275 size -= 8
276 index += 8
277 v3 ^= mi
278 v0, v1, v2, v3 = _double_round(v0, v1, v2, v3)
279 v0 ^= mi
280 else:
281 while size >= 8:
282 mi = (
283 r_uint64(llop.raw_load(rffi.UCHAR, addr_in, index)) |
284 r_uint64(llop.raw_load(rffi.UCHAR, addr_in, index + 1*SZ)) << 8 |
285 r_uint64(llop.raw_load(rffi.UCHAR, addr_in, index + 2*SZ)) << 16 |
286 r_uint64(llop.raw_load(rffi.UCHAR, addr_in, index + 3*SZ)) << 24 |
287 r_uint64(llop.raw_load(rffi.UCHAR, addr_in, index + 4*SZ)) << 32 |
288 r_uint64(llop.raw_load(rffi.UCHAR, addr_in, index + 5*SZ)) << 40 |
289 r_uint64(llop.raw_load(rffi.UCHAR, addr_in, index + 6*SZ)) << 48 |
290 r_uint64(llop.raw_load(rffi.UCHAR, addr_in, index + 7*SZ)) << 56
291 )
292 size -= 8
293 index += 8*SZ
294 v3 ^= mi
295 v0, v1, v2, v3 = _double_round(v0, v1, v2, v3)
296 v0 ^= mi
297
298 t = r_uint64(0)
299 if size == 7:
300 t = r_uint64(llop.raw_load(rffi.UCHAR, addr_in, index + 6*SZ)) << 48
301 size = 6
302 if size == 6:
303 t |= r_uint64(llop.raw_load(rffi.UCHAR, addr_in, index + 5*SZ)) << 40
304 size = 5
305 if size == 5:
306 t |= r_uint64(llop.raw_load(rffi.UCHAR, addr_in, index + 4*SZ)) << 32
307 size = 4
308 if size == 4:
309 if direct:
310 v = _le32toh(r_uint32(llop.raw_load(rffi.UINT, addr_in, index)))
311 t |= r_uint64(v)
312 size = 0
313 else:
314 t |= r_uint64(llop.raw_load(rffi.UCHAR, addr_in, index + 3*SZ))<< 24
315 size = 3
316 if size == 3:
317 t |= r_uint64(llop.raw_load(rffi.UCHAR, addr_in, index + 2*SZ)) << 16
318 size = 2
319 if size == 2:
320 t |= r_uint64(llop.raw_load(rffi.UCHAR, addr_in, index + 1*SZ)) << 8
321 size = 1
322 if size == 1:
323 t |= r_uint64(llop.raw_load(rffi.UCHAR, addr_in, index))
324 size = 0
325 assert size == 0
326
327 b |= t
328
329 v3 ^= b
330 v0, v1, v2, v3 = _double_round(v0, v1, v2, v3)
331 v0 ^= b
332 v2 ^= 0xff
333 v0, v1, v2, v3 = _double_round(v0, v1, v2, v3)
334 v0, v1, v2, v3 = _double_round(v0, v1, v2, v3)
335
336 return (v0 ^ v1) ^ (v2 ^ v3)
337
338
339 @jit.dont_look_inside
340 def siphash24(s):
341 """'s' is a normal string. Returns its siphash-2-4 as a r_uint64.
342 Don't forget to cast the result to a regular integer if needed,
343 e.g. with rarithmetic.intmask().
344 """
345 with rffi.scoped_nonmovingbuffer(s) as p:
346 return _siphash24(llmemory.cast_ptr_to_adr(p), len(s))
347
348 @jit.dont_look_inside
349 def siphash24_with_key(s, k0, k1=0):
350 """'s' is a normal string. k0 and k1 are the seed keys
351 """
352 with rffi.scoped_nonmovingbuffer(s) as p:
353 return _siphash24_with_key(llmemory.cast_ptr_to_adr(p), len(s), k0, k1)
354
355 # Prebuilt hashes are precomputed here
356 def _update_prebuilt_hashes():
357 seed.bound_prebuilt_size = 0
358 with lltype.scoped_alloc(rffi.CCHARP.TO, 1) as p:
359 addr = llmemory.cast_ptr_to_adr(p)
360 seed.hash_single = [r_uint64(0)] * 256
361 for i in range(256):
362 p[0] = chr(i)
363 seed.hash_single[i] = _siphash24(addr, 1)
364 seed.hash_empty = _siphash24(addr, 0)
365 seed.bound_prebuilt_size = 2
366 _update_prebuilt_hashes()