forked from facebook/hhvm
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathasio.py
342 lines (253 loc) · 9.64 KB
/
asio.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
"""
GDB commands for asio information and stacktraces.
"""
from compatibility import *
import gdb
from itertools import count
import re
from gdbutils import *
import frame
import idx
from nameof import nameof
from sizeof import sizeof
#------------------------------------------------------------------------------
# WaitHandle wrapper class.
class WaitHandle(object):
"""Wrapper class for a HHVM::c_WaitHandle*."""
##
# gdb.Value delegation.
#
def __init__(self, wh):
if not isinstance(wh, gdb.Value):
raise TypeError('bad call to WaitHandle()')
wh = deref(wh)
if not str(wh.type).endswith('WaitHandle'):
raise TypeError('non-WaitHandle[*] value passed to WaitHandle()')
self.wh = wh.address
wh_name = 'HPHP::c_' + self.kind_str() + 'WaitHandle'
self.wh = self.wh.cast(T(wh_name).pointer())
self.type = self.wh.type
def __getitem__(self, idx):
return self.wh[idx]
def get(self):
return self.wh
##
# c_WaitHandle* methods.
#
def kind(self):
kind_ty = T('HPHP::c_WaitHandle::Kind')
return (self.wh['m_kind_state'] >> 4).cast(kind_ty)
def kind_str(self):
return str(self.kind())[len('HPHP::c_WaitHandle::Kind::'):]
def state(self):
return (self.wh['m_kind_state'] & 0xf).cast(T('uint8_t'))
def state_str(self):
kind = self.kind_str()
state = self.state()
res = 'INVALID'
# Each WaitHandle has its own states...
if state == 0:
res = 'SUCCEEDED'
elif state == 1:
res = 'FAILED'
elif state == 2:
if kind == 'Sleep' or kind == 'ExternalThreadEvent':
res = 'WAITING'
elif kind == 'Reschedule':
res = 'SCHEDULED'
else:
res = 'BLOCKED'
elif state == 3 and kind == 'Resumable':
res = 'SCHEDULED'
elif state == 4 and kind == 'Resumable':
res = 'RUNNING'
return res
def finished(self):
return self.state() <= K('HPHP::c_WaitHandle::STATE_FAILED')
def resumable(self):
resumable_ty = T('HPHP::Resumable')
if self.type != T('HPHP::c_AsyncFunctionWaitHandle').pointer():
return None
p = self.wh.cast(T('char').pointer()) - resumable_ty.sizeof
return p.cast(resumable_ty.pointer())
##
# Parent chain.
#
def parent(self):
"""Same as wh->getParentChain().firstInContext(wh->getContextIdx())."""
ctx_idx = self.wh['m_contextIdx']
blockable = self.wh['m_parentChain']['m_firstParent']
while blockable != nullptr():
wh = WaitHandle.from_blockable(blockable)
if not wh.finished() and wh['m_contextIdx'] == ctx_idx:
return wh
blockable = wh['m_parentChain']['m_firstParent']
return None
def chain(self):
"""Generate a WaitHandle's parent chain."""
wh = self
while wh is not None:
yield wh
wh = wh.parent()
##
# Static constructors.
#
@staticmethod
def from_blockable(blockable):
"""Get the containing WaitHandle of an AsioBlockable*."""
bits = blockable['m_bits']
kind_str = 'HPHP::AsioBlockable::Kind'
# The remaining bits point to the next blockable in the chain.
kind = (bits & 0x7).cast(T(kind_str))
m = re.match(kind_str + '::(\w+)WaitHandle\w*', str(kind))
if m is None:
return None
wh_name = m.group(1)
if wh_name == 'AsyncFunction':
offset = 40
elif wh_name == 'AsyncGenerator':
offset = 56
elif wh_name == 'AwaitAll':
offset = 48
elif wh_name == 'Condition':
offset = 48
else:
return None
wh_ptype = T('HPHP::c_' + wh_name + 'WaitHandle').pointer()
wh = (blockable.cast(T('char').pointer()) - offset).cast(wh_ptype)
try:
if blockable != wh['m_blockable'].address:
return None
except:
if blockable != wh['m_children'][0]['m_blockable'].address:
return None
return WaitHandle(wh)
#------------------------------------------------------------------------------
# Other ASIO helpers.
def asio_context(ctx_idx=None):
"""Get the AsioContext in the current thread by index."""
contexts = TL('HPHP::AsioSession::s_current')['m_p']['m_contexts']
top_idx = sizeof(contexts)
if ctx_idx is None:
ctx_idx = top_idx
if ctx_idx > top_idx:
return None
# AsioContexts are numbered from 1.
return idx.vector_at(contexts, ctx_idx - 1)
#------------------------------------------------------------------------------
# ASIO stacktraces.
def asio_stacktrace(wh, limit=None):
"""Produce a list of async frames by following a WaitHandle's parent chain.
The stacktrace ends at the WaitHandle::join().
The whole chain is walked even if `limit' is provided---the return
stacktrace will have `limit' or fewer entries if there were `limit' or
fewer frames, and `limit' + 1 frames otherwise, where the last frame is the
WaitHandle::join().
"""
stacktrace = []
count = 0
for wh in WaitHandle(wh).chain():
resumable = wh.resumable()
if resumable is None:
continue
if limit is None or count < limit:
stacktrace.append(frame.create_resumable(count, resumable))
count += 1
ar = asio_context(wh['m_contextIdx'])['m_savedFP']
if ar != nullptr():
stacktrace.append(frame.create_php(idx=count, ar=ar))
return stacktrace
class AsyncStkCommand(gdb.Command):
"""Dump the async function stacktrace for a given WaitHandle.
The format used is the same as that used by `walkstk'.
"""
def __init__(self):
super(AsyncStkCommand, self).__init__('asyncstk', gdb.COMMAND_STACK)
@errorwrap
def invoke(self, args, from_tty):
try:
wh = gdb.parse_and_eval(args)
except gdb.error:
print('Usage: asyncstk wait-handle')
return
try:
stacktrace = asio_stacktrace(wh)
except TypeError:
print('asyncstk: Argument must be a WaitHandle object or pointer.')
return
for s in frame.stringify_stacktrace(stacktrace):
print(s)
AsyncStkCommand()
#------------------------------------------------------------------------------
# `info asio' command.
class InfoAsioCommand(gdb.Command):
"""Metadata about the currently in-scope AsioContext"""
def __init__(self):
super(InfoAsioCommand, self).__init__('info asio', gdb.COMMAND_STATUS)
@errorwrap
def invoke(self, args, from_tty):
asio_session = TL('HPHP::AsioSession::s_current')['m_p']
contexts = asio_session['m_contexts']
num_contexts = sizeof(contexts)
if num_contexts == 0:
print('Not currently in the scope of an AsioContext')
return
asio_ctx = asio_context()
# Count the number of contexts, and print the topmost.
print('\n%d stacked AsioContext%s (current: (%s) %s)' % (
int(num_contexts),
plural_suffix(num_contexts),
str(asio_ctx.type),
str(asio_ctx)))
# Get the current vmfp().
header_ptype = T('HPHP::rds::Header').pointer()
vmfp = TL('HPHP::rds::tl_base').cast(header_ptype)['vmRegs']['fp']
wh_ptype = T('HPHP::c_WaitableWaitHandle').pointer()
# Find the most recent join().
for i, fp in izip(count(), frame.gen_php(vmfp)):
if nameof(fp['m_func']) == 'HH\WaitHandle::join':
break
if nameof(fp['m_func']) != 'HH\WaitHandle::join':
print("...but couldn't find join(). Something is wrong.\n")
return
wh = fp['m_this'].cast(wh_ptype)
print('\nCurrently %s WaitHandle: (%s) %s [state: %s]' % (
'joining' if i == 0 else 'executing',
str(wh.type),
str(wh),
WaitHandle(wh).state_str()))
# Dump the async stacktrace.
for s in frame.stringify_stacktrace(asio_stacktrace(wh)):
print(' %s' % s)
# Count the number of queued runnables.
queue_size = sizeof(asio_ctx['m_runnableQueue'])
print('%d other resumable%s queued' % (
int(queue_size),
plural_suffix(queue_size)))
sleeps = asio_ctx['m_sleepEvents']
externals = asio_ctx['m_externalThreadEvents']
num_sleeps = sizeof(sleeps)
num_externals = sizeof(externals)
# Count sleep and external thread events.
print('')
print('%d pending sleep event%s' % (
int(num_sleeps), plural_suffix(num_sleeps)))
print('%d pending external thread event%s' % (
int(num_externals), plural_suffix(num_externals)))
# Dump sleep and external thread event stacktraces.
for vec in [sleeps, externals]:
for i in xrange(int(sizeof(vec))):
wh = idx.vector_at(vec, i)
stacktrace = frame.stringify_stacktrace(asio_stacktrace(wh, 3))
print('\n(%s) %s [state: %s]' % (
str(wh.type), str(wh), WaitHandle(wh).state_str()))
if len(stacktrace) == 4:
for s in stacktrace[0:-1]:
print(' %s' % s)
print(' ...')
print(' %s' % stacktrace[-1])
else:
for s in stacktrace:
print(' %s' % s)
print('')
InfoAsioCommand()