PageRenderTime 53ms CodeModel.GetById 17ms RepoModel.GetById 0ms app.codeStats 1ms

/rpython/memory/gctransform/asmgcroot.py

https://bitbucket.org/pypy/pypy/
Python | 866 lines | 648 code | 64 blank | 154 comment | 82 complexity | efaed6df5949b9b2b05391c7e774c360 MD5 | raw file
Possible License(s): AGPL-3.0, BSD-3-Clause, Apache-2.0
  1. from rpython.flowspace.model import (Constant, Variable, Block, Link,
  2. copygraph, SpaceOperation, checkgraph)
  3. from rpython.rlib.debug import ll_assert
  4. from rpython.rlib.nonconst import NonConstant
  5. from rpython.rlib import rgil
  6. from rpython.rtyper.annlowlevel import llhelper
  7. from rpython.rtyper.lltypesystem import lltype, llmemory, rffi
  8. from rpython.rtyper.lltypesystem.lloperation import llop
  9. from rpython.memory.gctransform.framework import (
  10. BaseFrameworkGCTransformer, BaseRootWalker)
  11. from rpython.rtyper.llannotation import SomeAddress
  12. from rpython.rtyper.rbuiltin import gen_cast
  13. from rpython.translator.unsimplify import varoftype
  14. from rpython.translator.tool.cbuild import ExternalCompilationInfo
  15. import sys
  16. #
  17. # This transformer avoids the use of a shadow stack in a completely
  18. # platform-specific way, by directing genc to insert asm() special
  19. # instructions in the C source, which are recognized by GCC.
  20. # The .s file produced by GCC is then parsed by trackgcroot.py.
  21. #
  22. IS_64_BITS = sys.maxint > 2147483647
  23. class AsmGcRootFrameworkGCTransformer(BaseFrameworkGCTransformer):
  24. _asmgcc_save_restore_arguments = None
  25. _seen_gctransformer_hint_close_stack = None
  26. def push_roots(self, hop, keep_current_args=False):
  27. livevars = self.get_livevars_for_roots(hop, keep_current_args)
  28. self.num_pushs += len(livevars)
  29. return livevars
  30. def pop_roots(self, hop, livevars):
  31. if not livevars:
  32. return
  33. # mark the values as gc roots
  34. for var in livevars:
  35. v_adr = gen_cast(hop.llops, llmemory.Address, var)
  36. v_newaddr = hop.genop("direct_call", [c_asm_gcroot, v_adr],
  37. resulttype=llmemory.Address)
  38. hop.genop("gc_reload_possibly_moved", [v_newaddr, var])
  39. def build_root_walker(self):
  40. return AsmStackRootWalker(self)
  41. def mark_call_cannotcollect(self, hop, name):
  42. hop.genop("direct_call", [c_asm_nocollect, name])
  43. def gct_direct_call(self, hop):
  44. fnptr = hop.spaceop.args[0].value
  45. try:
  46. close_stack = fnptr._obj._callable._gctransformer_hint_close_stack_
  47. except AttributeError:
  48. close_stack = False
  49. if close_stack:
  50. self.handle_call_with_close_stack(hop)
  51. else:
  52. BaseFrameworkGCTransformer.gct_direct_call(self, hop)
  53. def handle_call_with_close_stack(self, hop):
  54. fnptr = hop.spaceop.args[0].value
  55. if self._seen_gctransformer_hint_close_stack is None:
  56. self._seen_gctransformer_hint_close_stack = {}
  57. if fnptr._obj.graph not in self._seen_gctransformer_hint_close_stack:
  58. self._transform_hint_close_stack(fnptr)
  59. self._seen_gctransformer_hint_close_stack[fnptr._obj.graph] = True
  60. #
  61. livevars = self.push_roots(hop)
  62. self.default(hop)
  63. self.pop_roots(hop, livevars)
  64. def _transform_hint_close_stack(self, fnptr):
  65. # We cannot easily pass variable amount of arguments of the call
  66. # across the call to the pypy_asm_stackwalk helper. So we store
  67. # them away and restore them. More precisely, we need to
  68. # replace 'graph' with code that saves the arguments, and make
  69. # a new graph that starts with restoring the arguments.
  70. if self._asmgcc_save_restore_arguments is None:
  71. self._asmgcc_save_restore_arguments = {}
  72. sradict = self._asmgcc_save_restore_arguments
  73. sra = [] # list of pointers to raw-malloced containers for args
  74. seen = {}
  75. FUNC1 = lltype.typeOf(fnptr).TO
  76. for TYPE in FUNC1.ARGS:
  77. if isinstance(TYPE, lltype.Ptr):
  78. TYPE = llmemory.Address
  79. num = seen.get(TYPE, 0)
  80. seen[TYPE] = num + 1
  81. key = (TYPE, num)
  82. if key not in sradict:
  83. CONTAINER = lltype.FixedSizeArray(TYPE, 1)
  84. p = lltype.malloc(CONTAINER, flavor='raw', zero=True,
  85. immortal=True)
  86. sradict[key] = Constant(p, lltype.Ptr(CONTAINER))
  87. sra.append(sradict[key])
  88. #
  89. # make a copy of the graph that will reload the values
  90. graph = fnptr._obj.graph
  91. graph2 = copygraph(graph)
  92. #
  93. # edit the original graph to only store the value of the arguments
  94. block = Block(graph.startblock.inputargs)
  95. c_item0 = Constant('item0', lltype.Void)
  96. assert len(block.inputargs) == len(sra)
  97. for v_arg, c_p in zip(block.inputargs, sra):
  98. if isinstance(v_arg.concretetype, lltype.Ptr):
  99. v_adr = varoftype(llmemory.Address)
  100. block.operations.append(
  101. SpaceOperation("cast_ptr_to_adr", [v_arg], v_adr))
  102. v_arg = v_adr
  103. v_void = varoftype(lltype.Void)
  104. block.operations.append(
  105. SpaceOperation("bare_setfield", [c_p, c_item0, v_arg], v_void))
  106. #
  107. # call asm_stackwalk(graph2)
  108. FUNC2 = lltype.FuncType([], FUNC1.RESULT)
  109. fnptr2 = lltype.functionptr(FUNC2,
  110. fnptr._obj._name + '_reload',
  111. graph=graph2)
  112. c_fnptr2 = Constant(fnptr2, lltype.Ptr(FUNC2))
  113. HELPERFUNC = lltype.FuncType([lltype.Ptr(FUNC2),
  114. ASM_FRAMEDATA_HEAD_PTR], FUNC1.RESULT)
  115. v_asm_stackwalk = varoftype(lltype.Ptr(HELPERFUNC), "asm_stackwalk")
  116. block.operations.append(
  117. SpaceOperation("cast_pointer", [c_asm_stackwalk], v_asm_stackwalk))
  118. v_result = varoftype(FUNC1.RESULT)
  119. block.operations.append(
  120. SpaceOperation("indirect_call", [v_asm_stackwalk, c_fnptr2,
  121. c_gcrootanchor,
  122. Constant(None, lltype.Void)],
  123. v_result))
  124. block.closeblock(Link([v_result], graph.returnblock))
  125. graph.startblock = block
  126. #
  127. # edit the copy of the graph to reload the values
  128. block2 = graph2.startblock
  129. block1 = Block([])
  130. reloadedvars = []
  131. for v, c_p in zip(block2.inputargs, sra):
  132. v = v.copy()
  133. if isinstance(v.concretetype, lltype.Ptr):
  134. w = varoftype(llmemory.Address)
  135. else:
  136. w = v
  137. block1.operations.append(SpaceOperation('getfield',
  138. [c_p, c_item0], w))
  139. if w is not v:
  140. block1.operations.append(SpaceOperation('cast_adr_to_ptr',
  141. [w], v))
  142. reloadedvars.append(v)
  143. block1.closeblock(Link(reloadedvars, block2))
  144. graph2.startblock = block1
  145. #
  146. checkgraph(graph)
  147. checkgraph(graph2)
  148. class AsmStackRootWalker(BaseRootWalker):
  149. def __init__(self, gctransformer):
  150. BaseRootWalker.__init__(self, gctransformer)
  151. def _asm_callback():
  152. self.walk_stack_from()
  153. self._asm_callback = _asm_callback
  154. self._shape_decompressor = ShapeDecompressor()
  155. self._with_jit = hasattr(gctransformer.translator, '_jit2gc')
  156. if self._with_jit:
  157. jit2gc = gctransformer.translator._jit2gc
  158. self.frame_tid = jit2gc['frame_tid']
  159. self.gctransformer = gctransformer
  160. #
  161. # unless overridden in need_thread_support():
  162. self.belongs_to_current_thread = lambda framedata: True
  163. def need_stacklet_support(self, gctransformer, getfn):
  164. from rpython.annotator import model as annmodel
  165. from rpython.rlib import _stacklet_asmgcc
  166. # stacklet support: BIG HACK for rlib.rstacklet
  167. _stacklet_asmgcc._asmstackrootwalker = self # as a global! argh
  168. _stacklet_asmgcc.complete_destrptr(gctransformer)
  169. #
  170. def gc_detach_callback_pieces():
  171. anchor = llmemory.cast_ptr_to_adr(gcrootanchor)
  172. result = llmemory.NULL
  173. framedata = anchor.address[1]
  174. while framedata != anchor:
  175. next = framedata.address[1]
  176. if self.belongs_to_current_thread(framedata):
  177. # detach it
  178. prev = framedata.address[0]
  179. prev.address[1] = next
  180. next.address[0] = prev
  181. # update the global stack counter
  182. rffi.stackcounter.stacks_counter -= 1
  183. # reattach framedata into the singly-linked list 'result'
  184. framedata.address[0] = rffi.cast(llmemory.Address, -1)
  185. framedata.address[1] = result
  186. result = framedata
  187. framedata = next
  188. return result
  189. #
  190. def gc_reattach_callback_pieces(pieces):
  191. anchor = llmemory.cast_ptr_to_adr(gcrootanchor)
  192. while pieces != llmemory.NULL:
  193. framedata = pieces
  194. pieces = pieces.address[1]
  195. # attach 'framedata' into the normal doubly-linked list
  196. following = anchor.address[1]
  197. following.address[0] = framedata
  198. framedata.address[1] = following
  199. anchor.address[1] = framedata
  200. framedata.address[0] = anchor
  201. # update the global stack counter
  202. rffi.stackcounter.stacks_counter += 1
  203. #
  204. s_addr = SomeAddress()
  205. s_None = annmodel.s_None
  206. self.gc_detach_callback_pieces_ptr = getfn(gc_detach_callback_pieces,
  207. [], s_addr)
  208. self.gc_reattach_callback_pieces_ptr=getfn(gc_reattach_callback_pieces,
  209. [s_addr], s_None)
  210. def need_thread_support(self, gctransformer, getfn):
  211. # Threads supported "out of the box" by the rest of the code.
  212. # The whole code in this function is only there to support
  213. # fork()ing in a multithreaded process :-(
  214. # For this, we need to handle gc_thread_start and gc_thread_die
  215. # to record the mapping {thread_id: stack_start}, and
  216. # gc_thread_before_fork and gc_thread_after_fork to get rid of
  217. # all ASM_FRAMEDATA structures that do no belong to the current
  218. # thread after a fork().
  219. from rpython.rlib import rthread
  220. from rpython.memory.support import AddressDict
  221. from rpython.memory.support import copy_without_null_values
  222. from rpython.annotator import model as annmodel
  223. gcdata = self.gcdata
  224. def get_aid():
  225. """Return the thread identifier, cast to an (opaque) address."""
  226. return llmemory.cast_int_to_adr(rthread.get_ident())
  227. def thread_start():
  228. value = llmemory.cast_int_to_adr(llop.stack_current(lltype.Signed))
  229. gcdata.aid2stack.setitem(get_aid(), value)
  230. thread_start._always_inline_ = True
  231. def thread_setup():
  232. gcdata.aid2stack = AddressDict()
  233. gcdata.dead_threads_count = 0
  234. # to also register the main thread's stack
  235. thread_start()
  236. thread_setup._always_inline_ = True
  237. def thread_die():
  238. gcdata.aid2stack.setitem(get_aid(), llmemory.NULL)
  239. # from time to time, rehash the dictionary to remove
  240. # old NULL entries
  241. gcdata.dead_threads_count += 1
  242. if (gcdata.dead_threads_count & 511) == 0:
  243. copy = copy_without_null_values(gcdata.aid2stack)
  244. gcdata.aid2stack.delete()
  245. gcdata.aid2stack = copy
  246. def belongs_to_current_thread(framedata):
  247. # xxx obscure: the answer is Yes if, as a pointer, framedata
  248. # lies between the start of the current stack and the top of it.
  249. stack_start = gcdata.aid2stack.get(get_aid(), llmemory.NULL)
  250. ll_assert(stack_start != llmemory.NULL,
  251. "current thread not found in gcdata.aid2stack!")
  252. stack_stop = llmemory.cast_int_to_adr(
  253. llop.stack_current(lltype.Signed))
  254. return (stack_start <= framedata <= stack_stop or
  255. stack_start >= framedata >= stack_stop)
  256. self.belongs_to_current_thread = belongs_to_current_thread
  257. def thread_before_fork():
  258. # before fork(): collect all ASM_FRAMEDATA structures that do
  259. # not belong to the current thread, and move them out of the
  260. # way, i.e. out of the main circular doubly linked list.
  261. detached_pieces = llmemory.NULL
  262. anchor = llmemory.cast_ptr_to_adr(gcrootanchor)
  263. initialframedata = anchor.address[1]
  264. while initialframedata != anchor: # while we have not looped back
  265. if not belongs_to_current_thread(initialframedata):
  266. # Unlink it
  267. prev = initialframedata.address[0]
  268. next = initialframedata.address[1]
  269. prev.address[1] = next
  270. next.address[0] = prev
  271. # Link it to the singly linked list 'detached_pieces'
  272. initialframedata.address[0] = detached_pieces
  273. detached_pieces = initialframedata
  274. rffi.stackcounter.stacks_counter -= 1
  275. # Then proceed to the next piece of stack
  276. initialframedata = initialframedata.address[1]
  277. return detached_pieces
  278. def thread_after_fork(result_of_fork, detached_pieces):
  279. if result_of_fork == 0:
  280. # We are in the child process. Assumes that only the
  281. # current thread survived. All the detached_pieces
  282. # are pointers in other stacks, so have likely been
  283. # freed already by the multithreaded library.
  284. # Nothing more for us to do.
  285. pass
  286. else:
  287. # We are still in the parent process. The fork() may
  288. # have succeeded or not, but that's irrelevant here.
  289. # We need to reattach the detached_pieces now, to the
  290. # circular doubly linked list at 'gcrootanchor'. The
  291. # order is not important.
  292. anchor = llmemory.cast_ptr_to_adr(gcrootanchor)
  293. while detached_pieces != llmemory.NULL:
  294. reattach = detached_pieces
  295. detached_pieces = detached_pieces.address[0]
  296. a_next = anchor.address[1]
  297. reattach.address[0] = anchor
  298. reattach.address[1] = a_next
  299. anchor.address[1] = reattach
  300. a_next.address[0] = reattach
  301. rffi.stackcounter.stacks_counter += 1
  302. self.thread_setup = thread_setup
  303. self.thread_start_ptr = getfn(thread_start, [], annmodel.s_None,
  304. inline=True)
  305. self.thread_die_ptr = getfn(thread_die, [], annmodel.s_None)
  306. self.thread_before_fork_ptr = getfn(thread_before_fork, [],
  307. SomeAddress())
  308. self.thread_after_fork_ptr = getfn(thread_after_fork,
  309. [annmodel.SomeInteger(),
  310. SomeAddress()],
  311. annmodel.s_None)
  312. #
  313. # check that the order of the need_*() is correct for us: if we
  314. # need both threads and stacklets, need_thread_support() must be
  315. # called first, to initialize self.belongs_to_current_thread.
  316. assert not hasattr(self, 'gc_detach_callback_pieces_ptr')
  317. def walk_stack_roots(self, collect_stack_root, is_minor=False):
  318. gcdata = self.gcdata
  319. gcdata._gc_collect_stack_root = collect_stack_root
  320. gcdata._gc_collect_is_minor = is_minor
  321. pypy_asm_stackwalk(llhelper(ASM_CALLBACK_PTR, self._asm_callback),
  322. gcrootanchor)
  323. def walk_stack_from(self):
  324. curframe = lltype.malloc(WALKFRAME, flavor='raw')
  325. otherframe = lltype.malloc(WALKFRAME, flavor='raw')
  326. # Walk over all the pieces of stack. They are in a circular linked
  327. # list of structures of 7 words, the 2 first words being prev/next.
  328. # The anchor of this linked list is:
  329. anchor = llmemory.cast_ptr_to_adr(gcrootanchor)
  330. initialframedata = anchor.address[1]
  331. stackscount = 0
  332. while initialframedata != anchor: # while we have not looped back
  333. self.walk_frames(curframe, otherframe, initialframedata)
  334. # Then proceed to the next piece of stack
  335. initialframedata = initialframedata.address[1]
  336. stackscount += 1
  337. #
  338. # for the JIT: rpy_fastgil may contain an extra framedata
  339. rpy_fastgil = rgil.gil_fetch_fastgil().signed[0]
  340. if rpy_fastgil != 1:
  341. ll_assert(rpy_fastgil != 0, "walk_stack_from doesn't have the GIL")
  342. initialframedata = rffi.cast(llmemory.Address, rpy_fastgil)
  343. #
  344. # very rare issue: initialframedata.address[0] is uninitialized
  345. # in this case, but "retaddr = callee.frame_address.address[0]"
  346. # reads it. If it happens to be exactly a valid return address
  347. # inside the C code, then bad things occur.
  348. initialframedata.address[0] = llmemory.NULL
  349. #
  350. self.walk_frames(curframe, otherframe, initialframedata)
  351. stackscount += 1
  352. #
  353. expected = rffi.stackcounter.stacks_counter
  354. if NonConstant(0):
  355. rffi.stackcounter.stacks_counter += 42 # hack to force it
  356. ll_assert(not (stackscount < expected), "non-closed stacks around")
  357. ll_assert(not (stackscount > expected), "stacks counter corruption?")
  358. lltype.free(otherframe, flavor='raw')
  359. lltype.free(curframe, flavor='raw')
  360. def walk_frames(self, curframe, otherframe, initialframedata):
  361. self.fill_initial_frame(curframe, initialframedata)
  362. # Loop over all the frames in the stack
  363. while self.walk_to_parent_frame(curframe, otherframe):
  364. swap = curframe
  365. curframe = otherframe # caller becomes callee
  366. otherframe = swap
  367. def fill_initial_frame(self, curframe, initialframedata):
  368. # Read the information provided by initialframedata
  369. initialframedata += 2*sizeofaddr #skip the prev/next words at the start
  370. reg = 0
  371. while reg < CALLEE_SAVED_REGS:
  372. # NB. 'initialframedata' stores the actual values of the
  373. # registers %ebx etc., and if these values are modified
  374. # they are reloaded by pypy_asm_stackwalk(). By contrast,
  375. # 'regs_stored_at' merely points to the actual values
  376. # from the 'initialframedata'.
  377. curframe.regs_stored_at[reg] = initialframedata + reg*sizeofaddr
  378. reg += 1
  379. curframe.frame_address = initialframedata.address[CALLEE_SAVED_REGS]
  380. def walk_to_parent_frame(self, callee, caller):
  381. """Starting from 'callee', walk the next older frame on the stack
  382. and fill 'caller' accordingly. Also invokes the collect_stack_root()
  383. callback from the GC code for each GC root found in 'caller'.
  384. """
  385. #
  386. # The gcmap table is a list of entries, two machine words each:
  387. # void *SafePointAddress;
  388. # int Shape;
  389. #
  390. # A "safe point" is the return address of a call.
  391. # The "shape" of a safe point is a list of integers
  392. # that represent "locations". A "location" can be
  393. # either in the stack or in a register. See
  394. # getlocation() for the decoding of this integer.
  395. # The locations stored in a "shape" are as follows:
  396. #
  397. # * The "location" of the return address. This is just
  398. # after the end of the frame of 'callee'; it is the
  399. # first word of the frame of 'caller' (see picture
  400. # below).
  401. #
  402. # * Four "locations" that specify where the function saves
  403. # each of the four callee-saved registers (%ebx, %esi,
  404. # %edi, %ebp).
  405. #
  406. # * The number of live GC roots around the call.
  407. #
  408. # * For each GC root, an integer that specify where the
  409. # GC pointer is stored. This is a "location" too.
  410. #
  411. # XXX the details are completely specific to X86!!!
  412. # a picture of the stack may help:
  413. # ^ ^ ^
  414. # | ... | to older frames
  415. # +--------------+
  416. # | ret addr | <------ caller_frame (addr of retaddr)
  417. # | ... |
  418. # | caller frame |
  419. # | ... |
  420. # +--------------+
  421. # | ret addr | <------ callee_frame (addr of retaddr)
  422. # | ... |
  423. # | callee frame |
  424. # | ... | lower addresses
  425. # +--------------+ v v v
  426. #
  427. retaddr = callee.frame_address.address[0]
  428. #
  429. # try to locate the caller function based on retaddr.
  430. # set up self._shape_decompressor.
  431. #
  432. ebp_in_caller = callee.regs_stored_at[INDEX_OF_EBP].address[0]
  433. self.locate_caller_based_on_retaddr(retaddr, ebp_in_caller)
  434. #
  435. # found! Enumerate the GC roots in the caller frame
  436. #
  437. collect_stack_root = self.gcdata._gc_collect_stack_root
  438. gc = self.gc
  439. while True:
  440. location = self._shape_decompressor.next()
  441. if location == 0:
  442. break
  443. addr = self.getlocation(callee, ebp_in_caller, location)
  444. if gc.points_to_valid_gc_object(addr):
  445. collect_stack_root(gc, addr)
  446. #
  447. # small hack: the JIT reserves THREADLOCAL_OFS's last bit for
  448. # us. We use it to store an "already traced past this frame"
  449. # flag.
  450. if self._with_jit and self.gcdata._gc_collect_is_minor:
  451. if self.mark_jit_frame_can_stop(callee):
  452. return False
  453. #
  454. # track where the caller_frame saved the registers from its own
  455. # caller
  456. #
  457. reg = CALLEE_SAVED_REGS - 1
  458. while reg >= 0:
  459. location = self._shape_decompressor.next()
  460. addr = self.getlocation(callee, ebp_in_caller, location)
  461. caller.regs_stored_at[reg] = addr
  462. reg -= 1
  463. location = self._shape_decompressor.next()
  464. caller.frame_address = self.getlocation(callee, ebp_in_caller,
  465. location)
  466. # we get a NULL marker to mean "I'm the frame
  467. # of the entry point, stop walking"
  468. return caller.frame_address != llmemory.NULL
  469. def locate_caller_based_on_retaddr(self, retaddr, ebp_in_caller):
  470. gcmapstart = llop.gc_asmgcroot_static(llmemory.Address, 0)
  471. gcmapend = llop.gc_asmgcroot_static(llmemory.Address, 1)
  472. item = search_in_gcmap(gcmapstart, gcmapend, retaddr)
  473. if item:
  474. self._shape_decompressor.setpos(item.signed[1])
  475. return
  476. if not self._shape_decompressor.sorted:
  477. # the item may have been not found because the main array was
  478. # not sorted. Sort it and try again.
  479. win32_follow_gcmap_jmp(gcmapstart, gcmapend)
  480. sort_gcmap(gcmapstart, gcmapend)
  481. self._shape_decompressor.sorted = True
  482. item = search_in_gcmap(gcmapstart, gcmapend, retaddr)
  483. if item:
  484. self._shape_decompressor.setpos(item.signed[1])
  485. return
  486. if self._with_jit:
  487. # item not found. We assume that it's a JIT-generated
  488. # location -- but we check for consistency that ebp points
  489. # to a JITFRAME object.
  490. from rpython.jit.backend.llsupport.jitframe import STACK_DEPTH_OFS
  491. tid = self.gc.get_possibly_forwarded_type_id(ebp_in_caller)
  492. if (rffi.cast(lltype.Signed, tid) ==
  493. rffi.cast(lltype.Signed, self.frame_tid)):
  494. # fish the depth
  495. extra_stack_depth = (ebp_in_caller + STACK_DEPTH_OFS).signed[0]
  496. ll_assert((extra_stack_depth & (rffi.sizeof(lltype.Signed) - 1))
  497. == 0, "asmgcc: misaligned extra_stack_depth")
  498. extra_stack_depth //= rffi.sizeof(lltype.Signed)
  499. self._shape_decompressor.setjitframe(extra_stack_depth)
  500. return
  501. llop.debug_fatalerror(lltype.Void, "cannot find gc roots!")
  502. def getlocation(self, callee, ebp_in_caller, location):
  503. """Get the location in the 'caller' frame of a variable, based
  504. on the integer 'location' that describes it. All locations are
  505. computed based on information saved by the 'callee'.
  506. """
  507. ll_assert(location >= 0, "negative location")
  508. kind = location & LOC_MASK
  509. offset = location & ~ LOC_MASK
  510. if IS_64_BITS:
  511. offset <<= 1
  512. if kind == LOC_REG: # register
  513. if location == LOC_NOWHERE:
  514. return llmemory.NULL
  515. reg = (location >> 2) - 1
  516. ll_assert(reg < CALLEE_SAVED_REGS, "bad register location")
  517. return callee.regs_stored_at[reg]
  518. elif kind == LOC_ESP_PLUS: # in the caller stack frame at N(%esp)
  519. esp_in_caller = callee.frame_address + sizeofaddr
  520. return esp_in_caller + offset
  521. elif kind == LOC_EBP_PLUS: # in the caller stack frame at N(%ebp)
  522. return ebp_in_caller + offset
  523. else: # kind == LOC_EBP_MINUS: at -N(%ebp)
  524. return ebp_in_caller - offset
  525. def mark_jit_frame_can_stop(self, callee):
  526. location = self._shape_decompressor.get_threadlocal_loc()
  527. if location == LOC_NOWHERE:
  528. return False
  529. addr = self.getlocation(callee, llmemory.NULL, location)
  530. #
  531. x = addr.signed[0]
  532. if x & 1:
  533. return True # this JIT stack frame is already marked!
  534. else:
  535. addr.signed[0] = x | 1 # otherwise, mark it but don't stop
  536. return False
  537. LOC_REG = 0
  538. LOC_ESP_PLUS = 1
  539. LOC_EBP_PLUS = 2
  540. LOC_EBP_MINUS = 3
  541. LOC_MASK = 0x03
  542. LOC_NOWHERE = LOC_REG | 0
  543. # ____________________________________________________________
  544. sizeofaddr = llmemory.sizeof(llmemory.Address)
  545. arrayitemsize = 2 * sizeofaddr
  546. def binary_search(start, end, addr1):
  547. """Search for an element in a sorted array.
  548. The interval from the start address (included) to the end address
  549. (excluded) is assumed to be a sorted arrays of pairs (addr1, addr2).
  550. This searches for the item with a given addr1 and returns its
  551. address. If not found exactly, it tries to return the address
  552. of the item left of addr1 (i.e. such that result.address[0] < addr1).
  553. """
  554. count = (end - start) // arrayitemsize
  555. while count > 1:
  556. middleindex = count // 2
  557. middle = start + middleindex * arrayitemsize
  558. if addr1 < middle.address[0]:
  559. count = middleindex
  560. else:
  561. start = middle
  562. count -= middleindex
  563. return start
  564. def search_in_gcmap(gcmapstart, gcmapend, retaddr):
  565. item = binary_search(gcmapstart, gcmapend, retaddr)
  566. if item.address[0] == retaddr:
  567. return item # found
  568. # 'retaddr' not exactly found. Check that 'item' is the start of a
  569. # compressed range that includes 'retaddr'.
  570. if retaddr > item.address[0] and item.signed[1] < 0:
  571. return item # ok
  572. else:
  573. return llmemory.NULL # failed
  574. def search_in_gcmap2(gcmapstart, gcmapend, retaddr):
  575. # same as 'search_in_gcmap', but without range checking support
  576. # (item.signed[1] is an address in this case, not a signed at all!)
  577. item = binary_search(gcmapstart, gcmapend, retaddr)
  578. if item.address[0] == retaddr:
  579. return item.address[1] # found
  580. else:
  581. return llmemory.NULL # failed
  582. def sort_gcmap(gcmapstart, gcmapend):
  583. count = (gcmapend - gcmapstart) // arrayitemsize
  584. qsort(gcmapstart,
  585. rffi.cast(rffi.SIZE_T, count),
  586. rffi.cast(rffi.SIZE_T, arrayitemsize),
  587. c_compare_gcmap_entries)
  588. def replace_dead_entries_with_nulls(start, end):
  589. # replace the dead entries (null value) with a null key.
  590. count = (end - start) // arrayitemsize - 1
  591. while count >= 0:
  592. item = start + count * arrayitemsize
  593. if item.address[1] == llmemory.NULL:
  594. item.address[0] = llmemory.NULL
  595. count -= 1
  596. if sys.platform == 'win32':
  597. def win32_follow_gcmap_jmp(start, end):
  598. # The initial gcmap table contains addresses to a JMP
  599. # instruction that jumps indirectly to the real code.
  600. # Replace them with the target addresses.
  601. assert rffi.SIGNEDP is rffi.LONGP, "win64 support missing"
  602. while start < end:
  603. code = rffi.cast(rffi.CCHARP, start.address[0])[0]
  604. if code == '\xe9': # jmp
  605. rel32 = rffi.cast(rffi.SIGNEDP, start.address[0]+1)[0]
  606. target = start.address[0] + (rel32 + 5)
  607. start.address[0] = target
  608. start += arrayitemsize
  609. else:
  610. def win32_follow_gcmap_jmp(start, end):
  611. pass
  612. # ____________________________________________________________
  613. class ShapeDecompressor:
  614. _alloc_flavor_ = "raw"
  615. sorted = False
  616. def setpos(self, pos):
  617. if pos < 0:
  618. pos = ~ pos # can ignore this "range" marker here
  619. gccallshapes = llop.gc_asmgcroot_static(llmemory.Address, 2)
  620. self.addr = gccallshapes + pos
  621. self.jit_index = -1
  622. def setjitframe(self, extra_stack_depth):
  623. self.jit_index = 0
  624. self.extra_stack_depth = extra_stack_depth
  625. def next(self):
  626. index = self.jit_index
  627. if index < 0:
  628. # case "outside the jit"
  629. addr = self.addr
  630. value = 0
  631. while True:
  632. b = ord(addr.char[0])
  633. addr += 1
  634. value += b
  635. if b < 0x80:
  636. break
  637. value = (value - 0x80) << 7
  638. self.addr = addr
  639. return value
  640. else:
  641. # case "in the jit"
  642. from rpython.jit.backend.x86.arch import FRAME_FIXED_SIZE
  643. from rpython.jit.backend.x86.arch import PASS_ON_MY_FRAME
  644. self.jit_index = index + 1
  645. if index == 0:
  646. # the jitframe is an object in EBP
  647. return LOC_REG | ((INDEX_OF_EBP + 1) << 2)
  648. if index == 1:
  649. return 0
  650. # the remaining returned values should be:
  651. # saved %rbp
  652. # saved %r15 or on 32bit:
  653. # saved %r14 saved %ebp
  654. # saved %r13 saved %edi
  655. # saved %r12 saved %esi
  656. # saved %rbx saved %ebx
  657. # return addr return addr
  658. stack_depth = PASS_ON_MY_FRAME + self.extra_stack_depth
  659. if IS_64_BITS:
  660. if index == 2: # rbp
  661. return LOC_ESP_PLUS | (stack_depth << 2)
  662. if index == 3: # r15
  663. return LOC_ESP_PLUS | ((stack_depth + 5) << 2)
  664. if index == 4: # r14
  665. return LOC_ESP_PLUS | ((stack_depth + 4) << 2)
  666. if index == 5: # r13
  667. return LOC_ESP_PLUS | ((stack_depth + 3) << 2)
  668. if index == 6: # r12
  669. return LOC_ESP_PLUS | ((stack_depth + 2) << 2)
  670. if index == 7: # rbx
  671. return LOC_ESP_PLUS | ((stack_depth + 1) << 2)
  672. if index == 8: # return addr
  673. return (LOC_ESP_PLUS |
  674. ((FRAME_FIXED_SIZE + self.extra_stack_depth) << 2))
  675. else:
  676. if index == 2: # ebp
  677. return LOC_ESP_PLUS | (stack_depth << 2)
  678. if index == 3: # edi
  679. return LOC_ESP_PLUS | ((stack_depth + 3) << 2)
  680. if index == 4: # esi
  681. return LOC_ESP_PLUS | ((stack_depth + 2) << 2)
  682. if index == 5: # ebx
  683. return LOC_ESP_PLUS | ((stack_depth + 1) << 2)
  684. if index == 6: # return addr
  685. return (LOC_ESP_PLUS |
  686. ((FRAME_FIXED_SIZE + self.extra_stack_depth) << 2))
  687. llop.debug_fatalerror(lltype.Void, "asmgcroot: invalid index")
  688. return 0 # annotator fix
  689. def get_threadlocal_loc(self):
  690. index = self.jit_index
  691. if index < 0:
  692. return LOC_NOWHERE # case "outside the jit"
  693. else:
  694. # case "in the jit"
  695. from rpython.jit.backend.x86.arch import THREADLOCAL_OFS, WORD
  696. return (LOC_ESP_PLUS |
  697. ((THREADLOCAL_OFS // WORD + self.extra_stack_depth) << 2))
  698. # ____________________________________________________________
  699. #
  700. # The special pypy_asm_stackwalk(), implemented directly in
  701. # assembler, fills information about the current stack top in an
  702. # ASM_FRAMEDATA array and invokes an RPython callback with it.
  703. # An ASM_FRAMEDATA is an array of 5 values that describe everything
  704. # we need to know about a stack frame:
  705. #
  706. # - the value that %ebx had when the current function started
  707. # - the value that %esi had when the current function started
  708. # - the value that %edi had when the current function started
  709. # - the value that %ebp had when the current function started
  710. # - frame address (actually the addr of the retaddr of the current function;
  711. # that's the last word of the frame in memory)
  712. #
  713. # On 64 bits, it is an array of 7 values instead of 5:
  714. #
  715. # - %rbx, %r12, %r13, %r14, %r15, %rbp; and the frame address
  716. #
  717. if IS_64_BITS:
  718. CALLEE_SAVED_REGS = 6
  719. INDEX_OF_EBP = 5
  720. FRAME_PTR = CALLEE_SAVED_REGS
  721. else:
  722. CALLEE_SAVED_REGS = 4 # there are 4 callee-saved registers
  723. INDEX_OF_EBP = 3
  724. FRAME_PTR = CALLEE_SAVED_REGS # the frame is at index 4 in the array
  725. JIT_USE_WORDS = 2 + FRAME_PTR + 1
  726. ASM_CALLBACK_PTR = lltype.Ptr(lltype.FuncType([], lltype.Void))
  727. # used internally by walk_stack_from()
  728. WALKFRAME = lltype.Struct('WALKFRAME',
  729. ('regs_stored_at', # address of where the registers have been saved
  730. lltype.FixedSizeArray(llmemory.Address, CALLEE_SAVED_REGS)),
  731. ('frame_address',
  732. llmemory.Address),
  733. )
  734. # We have a circular doubly-linked list of all the ASM_FRAMEDATAs currently
  735. # alive. The list's starting point is given by 'gcrootanchor', which is not
  736. # a full ASM_FRAMEDATA but only contains the prev/next pointers:
  737. ASM_FRAMEDATA_HEAD_PTR = lltype.Ptr(lltype.ForwardReference())
  738. ASM_FRAMEDATA_HEAD_PTR.TO.become(lltype.Struct('ASM_FRAMEDATA_HEAD',
  739. ('prev', ASM_FRAMEDATA_HEAD_PTR),
  740. ('next', ASM_FRAMEDATA_HEAD_PTR)
  741. ))
  742. gcrootanchor = lltype.malloc(ASM_FRAMEDATA_HEAD_PTR.TO, immortal=True)
  743. gcrootanchor.prev = gcrootanchor
  744. gcrootanchor.next = gcrootanchor
  745. c_gcrootanchor = Constant(gcrootanchor, ASM_FRAMEDATA_HEAD_PTR)
  746. eci = ExternalCompilationInfo(compile_extra=['-DPYPY_USE_ASMGCC'],
  747. post_include_bits=["""
  748. static int pypy_compare_gcmap_entries(const void *addr1, const void *addr2)
  749. {
  750. char *key1 = * (char * const *) addr1;
  751. char *key2 = * (char * const *) addr2;
  752. if (key1 < key2)
  753. return -1;
  754. else if (key1 == key2)
  755. return 0;
  756. else
  757. return 1;
  758. }
  759. """])
  760. pypy_asm_stackwalk = rffi.llexternal('pypy_asm_stackwalk',
  761. [ASM_CALLBACK_PTR,
  762. ASM_FRAMEDATA_HEAD_PTR],
  763. lltype.Signed,
  764. sandboxsafe=True,
  765. _nowrapper=True,
  766. random_effects_on_gcobjs=True,
  767. compilation_info=eci)
  768. c_asm_stackwalk = Constant(pypy_asm_stackwalk,
  769. lltype.typeOf(pypy_asm_stackwalk))
  770. pypy_asm_gcroot = rffi.llexternal('pypy_asm_gcroot',
  771. [llmemory.Address],
  772. llmemory.Address,
  773. sandboxsafe=True,
  774. _nowrapper=True)
  775. c_asm_gcroot = Constant(pypy_asm_gcroot, lltype.typeOf(pypy_asm_gcroot))
  776. pypy_asm_nocollect = rffi.llexternal('pypy_asm_gc_nocollect',
  777. [rffi.CCHARP], lltype.Void,
  778. sandboxsafe=True,
  779. _nowrapper=True)
  780. c_asm_nocollect = Constant(pypy_asm_nocollect, lltype.typeOf(pypy_asm_nocollect))
  781. QSORT_CALLBACK_PTR = lltype.Ptr(lltype.FuncType([llmemory.Address,
  782. llmemory.Address], rffi.INT))
  783. c_compare_gcmap_entries = rffi.llexternal('pypy_compare_gcmap_entries',
  784. [llmemory.Address, llmemory.Address],
  785. rffi.INT, compilation_info=eci,
  786. _nowrapper=True, sandboxsafe=True)
  787. qsort = rffi.llexternal('qsort',
  788. [llmemory.Address,
  789. rffi.SIZE_T,
  790. rffi.SIZE_T,
  791. QSORT_CALLBACK_PTR],
  792. lltype.Void,
  793. sandboxsafe=True,
  794. random_effects_on_gcobjs=False, # but has a callback
  795. _nowrapper=True)