Debian Codegraph @

rpython/memory/gctransform/shadowstack.py

raw symbols SCIP
1 from rpython.annotator import model as annmodel
2 from rpython.rtyper.llannotation import SomePtr
3 from rpython.rlib.debug import ll_assert
4 from rpython.rlib.nonconst import NonConstant
5 from rpython.rlib import rgc
6 from rpython.rlib.objectmodel import specialize
7 from rpython.rtyper import rmodel
8 from rpython.rtyper.annlowlevel import llhelper
9 from rpython.rtyper.lltypesystem import lltype, llmemory
10 from rpython.rtyper.llannotation import SomeAddress
11 from rpython.memory.gctransform.framework import (
12 BaseFrameworkGCTransformer, BaseRootWalker, sizeofaddr)
13 from rpython.rtyper.rbuiltin import gen_cast
14 from rpython.memory.gctransform.log import log
15
16
17 class ShadowStackFrameworkGCTransformer(BaseFrameworkGCTransformer):
18 def annotate_walker_functions(self, getfn):
19 self.incr_stack_ptr = getfn(self.root_walker.incr_stack,
20 [annmodel.SomeInteger()],
21 SomeAddress(),
22 inline = True)
23 self.decr_stack_ptr = getfn(self.root_walker.decr_stack,
24 [annmodel.SomeInteger()],
25 SomeAddress(),
26 inline = True)
27
28 def build_root_walker(self):
29 return ShadowStackRootWalker(self)
30
31 def push_roots(self, hop, keep_current_args=False):
32 livevars = self.get_livevars_for_roots(hop, keep_current_args)
33 self.num_pushs += len(livevars)
34 hop.genop("gc_push_roots", livevars)
35 return livevars
36
37 def pop_roots(self, hop, livevars):
38 hop.genop("gc_pop_roots", livevars)
39 # NB. we emit it even if len(livevars) == 0; this is needed for
40 # shadowcolor.move_pushes_earlier()
41
42
43 @specialize.call_location()
44 def walk_stack_root(invoke, arg0, arg1, arg2, start, addr, is_minor):
45 skip = 0
46 while addr != start:
47 addr -= sizeofaddr
48 #XXX reintroduce support for tagged values?
49 #if gc.points_to_valid_gc_object(addr):
50 # callback(gc, addr)
51
52 if skip & 1 == 0:
53 content = addr.address[0]
54 n = llmemory.cast_adr_to_int(content)
55 if n & 1 == 0:
56 if content: # non-0, non-odd: a regular ptr
57 invoke(arg0, arg1, arg2, addr)
58 else:
59 # odd number: a skip bitmask
60 if n > 0: # initially, an unmarked value
61 if is_minor:
62 newcontent = llmemory.cast_int_to_adr(-n)
63 addr.address[0] = newcontent # mark
64 skip = n
65 else:
66 # a marked value
67 if is_minor:
68 return
69 skip = -n
70 skip >>= 1
71
72
73 class ShadowStackRootWalker(BaseRootWalker):
74 def __init__(self, gctransformer):
75 BaseRootWalker.__init__(self, gctransformer)
76 # NB. 'self' is frozen, but we can use self.gcdata to store state
77 gcdata = self.gcdata
78 gcdata.can_look_at_partial_stack = True
79
80 def incr_stack(n):
81 top = gcdata.root_stack_top
82 gcdata.root_stack_top = top + n*sizeofaddr
83 return top
84 self.incr_stack = incr_stack
85
86 def decr_stack(n):
87 top = gcdata.root_stack_top - n*sizeofaddr
88 gcdata.root_stack_top = top
89 return top
90 self.decr_stack = decr_stack
91
92 self.invoke_collect_stack_root = specialize.call_location()(
93 lambda arg0, arg1, arg2, addr: arg0(self.gc, addr))
94
95 self.shadow_stack_pool = ShadowStackPool(gcdata)
96 rsd = gctransformer.root_stack_depth
97 if rsd is not None:
98 self.shadow_stack_pool.root_stack_depth = rsd
99
100 def push_stack(self, addr):
101 top = self.incr_stack(1)
102 top.address[0] = addr
103
104 def pop_stack(self):
105 top = self.decr_stack(1)
106 return top.address[0]
107
108 def setup_root_walker(self):
109 self.shadow_stack_pool.initial_setup()
110 BaseRootWalker.setup_root_walker(self)
111
112 def walk_stack_roots(self, collect_stack_root, is_minor=False):
113 # Note that if we're the first minor collection after a thread
114 # switch, then we also need to disable the 'is_minor'
115 # optimization. The reason is subtle: we need to walk the whole
116 # stack because otherwise, we can be in the middle of an
117 # incremental major collection, and the new stack was just moved
118 # off a ShadowStackRef object (gctransform/shadowstack.py) which
119 # was not seen yet. We might completely miss some old objects
120 # from the parts of that stack that are skipped by this is_minor
121 # optimization.
122 gcdata = self.gcdata
123 if is_minor and not gcdata.can_look_at_partial_stack:
124 is_minor = False
125 gcdata.can_look_at_partial_stack = True
126 walk_stack_root(self.invoke_collect_stack_root, collect_stack_root,
127 None, None, gcdata.root_stack_base, gcdata.root_stack_top,
128 is_minor=is_minor)
129
130 def need_thread_support(self, gctransformer, getfn):
131 from rpython.rlib import rthread # xxx fish
132 gcdata = self.gcdata
133 # the interfacing between the threads and the GC is done via
134 # two completely ad-hoc operations at the moment:
135 # gc_thread_run and gc_thread_die. See docstrings below.
136
137 shadow_stack_pool = self.shadow_stack_pool
138 SHADOWSTACKREF = get_shadowstackref(self, gctransformer)
139
140 # this is a dict {tid: SHADOWSTACKREF}, where the tid for the
141 # current thread may be missing so far
142 gcdata.thread_stacks = None
143 shadow_stack_pool.has_threads = True
144
145 # Return the thread identifier, as an integer.
146 get_tid = rthread.get_ident
147
148 def thread_setup():
149 tid = get_tid()
150 gcdata.main_tid = tid
151 gcdata.active_tid = tid
152
153 def thread_run():
154 """Called whenever the current thread (re-)acquired the GIL.
155 This should ensure that the shadow stack installed in
156 gcdata.root_stack_top/root_stack_base is the one corresponding
157 to the current thread.
158 No GC operation here, e.g. no mallocs or storing in a dict!
159
160 Note that here specifically we don't call rthread.get_ident(),
161 but rthread.get_or_make_ident(). We are possibly in a fresh
162 new thread, so we need to be careful.
163 """
164 tid = rthread.get_or_make_ident()
165 if gcdata.active_tid != tid:
166 switch_shadow_stacks(tid)
167
168 def thread_die():
169 """Called just before the final GIL release done by a dying
170 thread. After a thread_die(), no more gc operation should
171 occur in this thread.
172 """
173 tid = get_tid()
174 if tid == gcdata.main_tid:
175 return # ignore calls to thread_die() in the main thread
176 # (which can occur after a fork()).
177 # we need to switch somewhere else, so go to main_tid
178 gcdata.active_tid = gcdata.main_tid
179 thread_stacks = gcdata.thread_stacks
180 new_ref = thread_stacks[gcdata.active_tid]
181 try:
182 del thread_stacks[tid]
183 except KeyError:
184 pass
185 # no more GC operation from here -- switching shadowstack!
186 shadow_stack_pool.forget_current_state()
187 shadow_stack_pool.restore_state_from(new_ref)
188
189 def switch_shadow_stacks(new_tid):
190 # we have the wrong shadowstack right now, but it should not matter
191 thread_stacks = gcdata.thread_stacks
192 try:
193 if thread_stacks is None:
194 gcdata.thread_stacks = thread_stacks = {}
195 raise KeyError
196 new_ref = thread_stacks[new_tid]
197 except KeyError:
198 new_ref = lltype.nullptr(SHADOWSTACKREF)
199 try:
200 old_ref = thread_stacks[gcdata.active_tid]
201 except KeyError:
202 # first time we ask for a SHADOWSTACKREF for this active_tid
203 old_ref = shadow_stack_pool.allocate(SHADOWSTACKREF)
204 thread_stacks[gcdata.active_tid] = old_ref
205 #
206 # no GC operation from here -- switching shadowstack!
207 shadow_stack_pool.save_current_state_away(old_ref)
208 if new_ref:
209 shadow_stack_pool.restore_state_from(new_ref)
210 else:
211 shadow_stack_pool.start_fresh_new_state()
212 # done
213 #
214 gcdata.active_tid = new_tid
215 switch_shadow_stacks._dont_inline_ = True
216
217 def thread_after_fork(result_of_fork, opaqueaddr):
218 # we don't need a thread_before_fork in this case, so
219 # opaqueaddr == NULL. This is called after fork().
220 if result_of_fork == 0:
221 # We are in the child process. Assumes that only the
222 # current thread survived, so frees the shadow stacks
223 # of all the other ones.
224 gcdata.thread_stacks = None
225 # Finally, reset the stored thread IDs, in case it
226 # changed because of fork(). Also change the main
227 # thread to the current one (because there is not any
228 # other left).
229 tid = get_tid()
230 gcdata.main_tid = tid
231 gcdata.active_tid = tid
232
233 self.thread_setup = thread_setup
234 self.thread_run_ptr = getfn(thread_run, [], annmodel.s_None,
235 minimal_transform=False)
236 self.thread_die_ptr = getfn(thread_die, [], annmodel.s_None,
237 minimal_transform=False)
238 # no thread_before_fork_ptr here
239 self.thread_after_fork_ptr = getfn(thread_after_fork,
240 [annmodel.SomeInteger(),
241 SomeAddress()],
242 annmodel.s_None,
243 minimal_transform=False)
244
245 def need_stacklet_support(self, gctransformer, getfn):
246 from rpython.rlib import _stacklet_shadowstack
247 _stacklet_shadowstack.complete_destrptr(gctransformer)
248
249 gcdata = self.gcdata
250 def gc_modified_shadowstack():
251 gcdata.can_look_at_partial_stack = False
252
253 self.gc_modified_shadowstack_ptr = getfn(gc_modified_shadowstack,
254 [], annmodel.s_None)
255
256 def build_increase_root_stack_depth_ptr(self, getfn):
257 shadow_stack_pool = self.shadow_stack_pool
258 def gc_increase_root_stack_depth(new_size):
259 shadow_stack_pool.increase_root_stack_depth(new_size)
260
261 self.gc_increase_root_stack_depth_ptr = getfn(
262 gc_increase_root_stack_depth, [annmodel.SomeInteger()],
263 annmodel.s_None)
264
265 def postprocess_graph(self, gct, graph, any_inlining):
266 from rpython.memory.gctransform import shadowcolor
267 if any_inlining:
268 shadowcolor.postprocess_inlining(graph)
269 use_push_pop = shadowcolor.postprocess_graph(graph, gct.c_const_gcdata)
270 if use_push_pop and graph in gct.graphs_to_inline:
271 log.WARNING("%r is marked for later inlining, "
272 "but is using push/pop roots. Disabled" % (graph,))
273 del gct.graphs_to_inline[graph]
274
275 # ____________________________________________________________
276
277 class ShadowStackPool(object):
278 """Manages a pool of shadowstacks.
279 """
280 _alloc_flavor_ = "raw"
281 root_stack_depth = 163840
282 has_threads = False
283
284 def __init__(self, gcdata):
285 self.unused_full_stack = llmemory.NULL
286 self.gcdata = gcdata
287
288 def initial_setup(self):
289 self._prepare_unused_stack()
290 self.start_fresh_new_state()
291
292 def allocate(self, SHADOWSTACKREF):
293 """Allocate an empty SHADOWSTACKREF object."""
294 return lltype.malloc(SHADOWSTACKREF, zero=True)
295
296 def save_current_state_away(self, shadowstackref):
297 """Save the current state away into 'shadowstackref'.
298 This either works, or raise MemoryError and nothing is done.
299 To do a switch, first call save_current_state_away() or
300 forget_current_state(), and then call restore_state_from()
301 or start_fresh_new_state().
302 """
303 self._prepare_unused_stack()
304 shadowstackref.base = self.gcdata.root_stack_base
305 shadowstackref.top = self.gcdata.root_stack_top
306 ll_assert(shadowstackref.base <= shadowstackref.top,
307 "save_current_state_away: broken shadowstack")
308 #
309 # cannot use llop.gc_writebarrier() here, because
310 # we are in a minimally-transformed GC helper :-/
311 gc = self.gcdata.gc
312 if hasattr(gc.__class__, 'write_barrier'):
313 shadowstackadr = llmemory.cast_ptr_to_adr(shadowstackref)
314 gc.write_barrier(shadowstackadr)
315 #
316 self.gcdata.root_stack_top = llmemory.NULL # to detect missing restore
317
318 def forget_current_state(self):
319 ll_assert(self.gcdata.root_stack_base == self.gcdata.root_stack_top,
320 "forget_current_state: shadowstack not empty!")
321 if self.unused_full_stack:
322 llmemory.raw_free(self.unused_full_stack)
323 self.unused_full_stack = self.gcdata.root_stack_base
324 self.gcdata.root_stack_top = llmemory.NULL # to detect missing restore
325
326 def restore_state_from(self, shadowstackref):
327 ll_assert(bool(shadowstackref.base), "empty shadowstackref!")
328 ll_assert(shadowstackref.base <= shadowstackref.top,
329 "restore_state_from: broken shadowstack")
330 self.gcdata.root_stack_base = shadowstackref.base
331 self.gcdata.root_stack_top = shadowstackref.top
332 self.gcdata.can_look_at_partial_stack = False
333 self._cleanup(shadowstackref)
334
335 def start_fresh_new_state(self):
336 self.gcdata.root_stack_base = self.unused_full_stack
337 self.gcdata.root_stack_top = self.unused_full_stack
338 self.unused_full_stack = llmemory.NULL
339
340 def _cleanup(self, shadowstackref):
341 shadowstackref.base = llmemory.NULL
342 shadowstackref.top = llmemory.NULL
343
344 def _prepare_unused_stack(self):
345 if self.unused_full_stack == llmemory.NULL:
346 root_stack_size = sizeofaddr * self.root_stack_depth
347 self.unused_full_stack = llmemory.raw_malloc(root_stack_size)
348 if self.unused_full_stack == llmemory.NULL:
349 raise MemoryError
350
351 def increase_root_stack_depth(self, new_depth):
352 if new_depth <= self.root_stack_depth:
353 return # can't easily decrease the size
354 if self.unused_full_stack:
355 llmemory.raw_free(self.unused_full_stack)
356 self.unused_full_stack = llmemory.NULL
357 used = self.gcdata.root_stack_top - self.gcdata.root_stack_base
358 addr = self._resize(self.gcdata.root_stack_base, used, new_depth)
359 self.gcdata.root_stack_base = addr
360 self.gcdata.root_stack_top = addr + used
361 # no gc operations above: we just switched shadowstacks
362 if self.has_threads:
363 self._resize_thread_shadowstacks(new_depth)
364 self.root_stack_depth = new_depth
365
366 def _resize_thread_shadowstacks(self, new_depth):
367 if self.gcdata.thread_stacks is not None:
368 for ssref in self.gcdata.thread_stacks.values():
369 if ssref.base:
370 used = ssref.top - ssref.base
371 addr = self._resize(ssref.base, used, new_depth)
372 ssref.base = addr
373 ssref.top = addr + used
374 _resize_thread_shadowstacks._dont_inline_ = True
375
376 def _resize(self, base, used, new_depth):
377 new_size = sizeofaddr * new_depth
378 ll_assert(used <= new_size, "shadowstack resize: overflow detected")
379 addr = llmemory.raw_malloc(new_size)
380 if addr == llmemory.NULL:
381 raise MemoryError
382 # note that we don't know the total memory size of 'base', but we
383 # know the size of the part that is used right now, and we only need
384 # to copy that
385 llmemory.raw_memmove(base, addr, used)
386 llmemory.raw_free(base)
387 return addr
388
389
390 def get_shadowstackref(root_walker, gctransformer):
391 if hasattr(gctransformer, '_SHADOWSTACKREF'):
392 return gctransformer._SHADOWSTACKREF
393
394 SHADOWSTACKREFPTR = lltype.Ptr(lltype.GcForwardReference())
395 SHADOWSTACKREF = lltype.GcStruct('ShadowStackRef',
396 ('base', llmemory.Address),
397 ('top', llmemory.Address),
398 rtti=True)
399 SHADOWSTACKREFPTR.TO.become(SHADOWSTACKREF)
400
401 def customtrace(gc, obj, callback, arg1, arg2):
402 obj = llmemory.cast_adr_to_ptr(obj, SHADOWSTACKREFPTR)
403 walk_stack_root(gc._trace_callback, callback, arg1, arg2, obj.base, obj.top,
404 is_minor=False) # xxx optimize?
405
406 gc = gctransformer.gcdata.gc
407 assert not hasattr(gc, 'custom_trace_dispatcher')
408 # ^^^ create_custom_trace_funcs() must not run before this
409 gctransformer.translator.rtyper.custom_trace_funcs.append(
410 (SHADOWSTACKREF, customtrace))
411
412 def shadowstack_destructor(shadowstackref):
413 base = shadowstackref.base
414 shadowstackref.base = llmemory.NULL
415 shadowstackref.top = llmemory.NULL
416 llmemory.raw_free(base)
417
418 destrptr = gctransformer.annotate_helper(shadowstack_destructor,
419 [SHADOWSTACKREFPTR], lltype.Void)
420
421 lltype.attachRuntimeTypeInfo(SHADOWSTACKREF, destrptr=destrptr)
422
423 gctransformer._SHADOWSTACKREF = SHADOWSTACKREF
424 return SHADOWSTACKREF