summaryrefslogtreecommitdiff
path: root/usr/src/cmd/mdb/common/modules/libpython/libpython.c
blob: 19e40b2476707ed294aedf7d75cacc6d77d6a709 (plain)
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
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
/*
 * CDDL HEADER START
 *
 * The contents of this file are subject to the terms of the
 * Common Development and Distribution License (the "License").
 * You may not use this file except in compliance with the License.
 *
 * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
 * or http://www.opensolaris.org/os/licensing.
 * See the License for the specific language governing permissions
 * and limitations under the License.
 *
 * When distributing Covered Code, include this CDDL HEADER in each
 * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
 * If applicable, add the following below this CDDL HEADER, with the
 * fields enclosed by brackets "[]" replaced with your own identifying
 * information: Portions Copyright [yyyy] [name of copyright owner]
 *
 * CDDL HEADER END
 */
/*
 * Copyright 2010 Sun Microsystems, Inc.  All rights reserved.
 * Use is subject to license terms.
 */

#include <mdb/mdb_modapi.h>

#include <pthread.h>
#include <stddef.h>
#include <dlfcn.h>
#include <link.h>
#include <libproc.h>

#include <Python.h>
#include <frameobject.h>

/*
 * Decoding Python Stack Frames
 * ============================
 *
 * Python2 uses a variety of objects to construct its call chain.  An address
 * space may have one or more PyInterpreterState objects, which are the base
 * object in the interpreter's state.  These objects are kept in a linked list
 * with a head pointer named interp_head.  This makes it possible for the
 * debugger to get a toehold on data structures necessary to understand the
 * interpreter.  Since most of these structures are linked out of the
 * InterpreterState, traversals generally start here.
 *
 * In order to decode a frame, the debugger needs to walk from
 * PyInterpreterState down to a PyCodeObject.  The diagram below shows the
 * the objects that must be examined in order to reach a leaf PyCodeObject.
 *
 *                +--------------------+ next   +--------------------+ next
 * interp_head -> | PyInterpreterState | ---->  | PyInterpreterState | ---> ...
 *                +--------------------+        +--------------------+
 *                  |                            | tstate_head
 *                  | tstate_head                V
 *                  |                 +---------------+  frame
 *                  V                 | PyThreadState | -----> ...
 *  +---------------+  frame          +---------------+
 *  | PyThreadState |  ---> ...
 *  +---------------+
 *          | next
 *          V
 *  +---------------+  frame    +---------------+ f_back +---------------+
 *  | PyThreadState |  ------>  | PyFrameObject | -----> | PyFrameObject |
 *  +---------------+           +---------------+        +---------------+
 *                                      |                       |
 *                                      | f_code                | f_code
 *                                      V                       V
 *                              +--------------+               ...
 *                              | PyCodeObject |
 *                              +--------------+
 *                 co_filename   |      |     | co_lnotab
 *                 +-------------+      |     +-------------+
 *                 |           co_name  |                   |
 *                 V                    V                   V
 * +----------------+          +----------------+         +----------------+
 * | PyStringObject |          | PyStringObject |         | PyStringObject |
 * +----------------+          +----------------+         +----------------+
 *
 * The interp_head pointer is a list of one or more PyInterpreterState
 * objects.  Each of these objects can contain one or more PyThreadState
 * objects.  The PyInterpreterState object keeps a pointer to the head of the
 * list of PyThreadState objects as tstate_head.
 *
 * Each thread keeps ahold of its stack frames.  The PyThreadState object
 * has a pointer to the topmost PyFrameObject, kept in frame.  The
 * successive frames on the stack are kept linked in the PyFrameObject's
 * f_back pointer, with each frame pointing to its caller.
 *
 * In order to decode each call frame, our code needs to look at the
 * PyCodeObject for each frame.  Essentially, this is the code that is
 * being executed in the frame.  The PyFrameObject keeps a pointer to this
 * code object in f_code.  In order to print meaningful debug information,
 * it's necessary to extract the Python filename (co_filename), the
 * function name (co_name), and the line number within the file
 * (co_lnotab).  The filename and function are stored as strings, but the
 * line number is a mapping of bytecode offsets to line numbers.  The
 * description of the lnotab algorithm lives here:
 *
 * http://svn.python.org/projects/python/trunk/Objects/lnotab_notes.txt
 *
 * In order to decode the frame, the debugger needs to walk each
 * InterpreterState object.  For each InterpreterState, every PyThreadState
 * must be traversed.  The PyThreadState objects point to the
 * PyFrameObjects.  For every thread, we must walk the frames backwards and
 * decode the strings that are in the PyCodeObjects.
 */

/*
 * The Python-dependent debugging functionality lives in its own helper
 * library.  The helper agent is provided by libpython2.[67]_db.so, which
 * is also used by pstack(1) for debugging Python processes.
 *
 * Define needed prototypes here.
 */

#define	PYDB_VERSION	1
typedef struct pydb_agent pydb_agent_t;
typedef struct pydb_iter pydb_iter_t;

typedef pydb_agent_t *(*pydb_agent_create_f)(struct ps_prochandle *P, int vers);
typedef void (*pydb_agent_destroy_f)(pydb_agent_t *py);
typedef int (*pydb_get_frameinfo_f)(pydb_agent_t *py, uintptr_t frame_addr,
    char *fbuf, size_t bufsz, int verbose);
typedef pydb_iter_t *(*pydb_iter_init_f)(pydb_agent_t *py, uintptr_t addr);
typedef uintptr_t (*pydb_iter_next_f)(pydb_iter_t *iter);
typedef void (*pydb_iter_fini_f)(pydb_iter_t *iter);

static pydb_agent_create_f pydb_agent_create;
static pydb_agent_destroy_f pydb_agent_destroy;
static pydb_get_frameinfo_f pydb_get_frameinfo;
static pydb_iter_init_f pydb_frame_iter_init;
static pydb_iter_init_f pydb_interp_iter_init;
static pydb_iter_init_f pydb_thread_iter_init;
static pydb_iter_next_f pydb_iter_next;
static pydb_iter_fini_f pydb_iter_fini;

static pydb_agent_t *pydb_hdl = NULL;
static void *pydb_dlhdl = NULL;

/*ARGSUSED*/
static int
py_frame(uintptr_t addr, uint_t flags, int argc, const mdb_arg_t *argv)
{
	char buf[1024];
	int verbose = FALSE;

	if (mdb_getopts(argc, argv,
	    'v', MDB_OPT_SETBITS, TRUE, &verbose,
	    NULL) != argc) {
		return (DCMD_USAGE);
	}

	if (flags & DCMD_PIPE_OUT) {
		mdb_warn("py_stack cannot output into a pipe\n");
		return (DCMD_ERR);
	}

	if (!(flags & DCMD_ADDRSPEC)) {
		mdb_warn("no address");
		return (DCMD_USAGE);
	}

	if (pydb_get_frameinfo(pydb_hdl, addr, buf, sizeof (buf),
	    verbose) < 0) {
		mdb_warn("Unable to find frame at address %p\n", addr);
		return (DCMD_ERR);
	}

	mdb_printf("%s", buf);

	return (DCMD_OK);
}

int
py_interp_walk_init(mdb_walk_state_t *wsp)
{
	pydb_iter_t *pdi;

	pdi = pydb_interp_iter_init(pydb_hdl, wsp->walk_addr);

	if (pdi == NULL) {
		mdb_warn("unable to create interpreter iterator\n");
		return (DCMD_ERR);
	}

	wsp->walk_data = pdi;

	return (WALK_NEXT);
}

int
py_walk_step(mdb_walk_state_t *wsp)
{
	pydb_iter_t *pdi = wsp->walk_data;
	uintptr_t addr;
	int status;

	addr = pydb_iter_next(pdi);

	if (addr == 0) {
		return (WALK_DONE);
	}

	status = wsp->walk_callback(addr, 0, wsp->walk_cbdata);

	return (status);
}

void
py_walk_fini(mdb_walk_state_t *wsp)
{
	pydb_iter_t *pdi = wsp->walk_data;
	pydb_iter_fini(pdi);
}

int
py_thread_walk_init(mdb_walk_state_t *wsp)
{
	pydb_iter_t *pdi;

	pdi = pydb_thread_iter_init(pydb_hdl, wsp->walk_addr);
	if (pdi == NULL) {
		mdb_warn("unable to create thread iterator\n");
		return (DCMD_ERR);
	}

	wsp->walk_data = pdi;

	return (WALK_NEXT);
}

int
py_frame_walk_init(mdb_walk_state_t *wsp)
{
	pydb_iter_t *pdi;

	pdi = pydb_frame_iter_init(pydb_hdl, wsp->walk_addr);
	if (pdi == NULL) {
		mdb_warn("unable to create frame iterator\n");
		return (DCMD_ERR);
	}

	wsp->walk_data = pdi;

	return (WALK_NEXT);
}

/*ARGSUSED*/
static int
python_stack(uintptr_t addr, const PyThreadState *ts, uint_t *verbose)
{
	mdb_arg_t nargv;
	uint_t nargc = (verbose != NULL && *verbose) ? 1 : 0;
	/*
	 * Pass the ThreadState to the frame walker. Have frame walker
	 * call frame dcmd.
	 */
	mdb_printf("PyThreadState: %0?p\n", addr);

	nargv.a_type = MDB_TYPE_STRING;
	nargv.a_un.a_str = "-v";

	if (mdb_pwalk_dcmd("pyframe", "pyframe", nargc, &nargv, addr) == -1) {
		mdb_warn("can't walk 'pyframe'");
		return (WALK_ERR);
	}

	return (WALK_NEXT);
}

/*ARGSUSED*/
static int
python_thread(uintptr_t addr, const PyInterpreterState *is, uint_t *verbose)
{
	/*
	 * Pass the InterpreterState to the threadstate walker.
	 */
	if (mdb_pwalk("pythread", (mdb_walk_cb_t)python_stack, verbose,
	    addr) == -1) {
		mdb_warn("can't walk 'pythread'");
		return (WALK_ERR);
	}

	return (WALK_NEXT);
}

/*ARGSUSED*/
static int
py_stack(uintptr_t addr, uint_t flags, int argc, const mdb_arg_t *argv)
{
	uint_t verbose = FALSE;

	if (mdb_getopts(argc, argv,
	    'v', MDB_OPT_SETBITS, TRUE, &verbose,
	    NULL) != argc)
		return (DCMD_USAGE);

	if (flags & DCMD_PIPE_OUT) {
		mdb_warn("py_stack cannot output into a pipe\n");
		return (DCMD_ERR);
	}

	if (flags & DCMD_ADDRSPEC) {
		mdb_arg_t nargv;
		uint_t nargc = verbose ? 1 : 0;

		nargv.a_type = MDB_TYPE_STRING;
		nargv.a_un.a_str = "-v";

		if (mdb_pwalk_dcmd("pyframe", "pyframe", nargc, &nargv, addr)
		    == -1) {
			mdb_warn("can't walk 'pyframe'");
			return (DCMD_ERR);
		}
		return (DCMD_OK);
	}

	if (mdb_walk("pyinterp", (mdb_walk_cb_t)python_thread,
	    &verbose) == -1) {
		mdb_warn("can't walk 'pyinterp'");
		return (DCMD_ERR);
	}

	return (DCMD_OK);
}

static const mdb_dcmd_t dcmds[] = {
	{ "pystack", "[-v]", "print python stacks", py_stack },
	{ "pyframe", "[-v]", "print python frames", py_frame },
	{ NULL }
};

static const mdb_walker_t walkers[] = {
	{ "pyinterp", "walk python interpreter structures",
		py_interp_walk_init, py_walk_step, py_walk_fini },
	{ "pythread", "given an interpreter, walk the list of python threads",
		py_thread_walk_init, py_walk_step, py_walk_fini },
	{ "pyframe", "given a thread state, walk the list of frame objects",
		py_frame_walk_init, py_walk_step, py_walk_fini },
	{ NULL }
};

static const mdb_modinfo_t modinfo = {
	MDB_API_VERSION, dcmds, walkers
};

/*ARGSUSED*/
static int
python_object_iter(void *cd, const prmap_t *pmp, const char *obj)
{
	char path[PATH_MAX];
	char *name;
	char *s1, *s2;
	struct ps_prochandle *Pr = cd;

	name = strstr(obj, "/libpython");

	if (name) {
		(void) strcpy(path, obj);
		if (Pstatus(Pr)->pr_dmodel != PR_MODEL_NATIVE) {
			s1 = name;
			s2 = path + (s1 - obj);
			(void) strcpy(s2, "/64");
			s2 += 3;
			(void) strcpy(s2, s1);
		}

		s1 = strstr(obj, ".so");
		s2 = strstr(path, ".so");
		(void) strcpy(s2, "_db");
		s2 += 3;
		(void) strcpy(s2, s1);

		if ((pydb_dlhdl = dlopen(path, RTLD_LAZY|RTLD_GLOBAL)) != NULL)
			return (1);
	}

	return (0);
}

static int
python_db_init(void)
{
	struct ps_prochandle *Ph;

	if (mdb_get_xdata("pshandle", &Ph, sizeof (Ph)) == -1) {
		mdb_warn("couldn't read pshandle xdata\n");
		dlclose(pydb_dlhdl);
		pydb_dlhdl = NULL;
		return (-1);
	}

	(void) Pobject_iter(Ph, python_object_iter, Ph);

	pydb_agent_create = (pydb_agent_create_f)
	    dlsym(pydb_dlhdl, "pydb_agent_create");
	pydb_agent_destroy = (pydb_agent_destroy_f)
	    dlsym(pydb_dlhdl, "pydb_agent_destroy");
	pydb_get_frameinfo = (pydb_get_frameinfo_f)
	    dlsym(pydb_dlhdl, "pydb_get_frameinfo");

	pydb_frame_iter_init = (pydb_iter_init_f)
	    dlsym(pydb_dlhdl, "pydb_frame_iter_init");
	pydb_interp_iter_init = (pydb_iter_init_f)
	    dlsym(pydb_dlhdl, "pydb_interp_iter_init");
	pydb_thread_iter_init = (pydb_iter_init_f)
	    dlsym(pydb_dlhdl, "pydb_thread_iter_init");
	pydb_iter_next = (pydb_iter_next_f)dlsym(pydb_dlhdl, "pydb_iter_next");
	pydb_iter_fini = (pydb_iter_fini_f)dlsym(pydb_dlhdl, "pydb_iter_fini");


	if (pydb_agent_create == NULL || pydb_agent_destroy == NULL ||
	    pydb_get_frameinfo == NULL || pydb_frame_iter_init == NULL ||
	    pydb_interp_iter_init == NULL || pydb_thread_iter_init == NULL ||
	    pydb_iter_next == NULL || pydb_iter_fini == NULL) {
		mdb_warn("couldn't load pydb functions");
		dlclose(pydb_dlhdl);
		pydb_dlhdl = NULL;
		return (-1);
	}

	pydb_hdl = pydb_agent_create(Ph, PYDB_VERSION);
	if (pydb_hdl == NULL) {
		mdb_warn("unable to create pydb_agent");
		dlclose(pydb_dlhdl);
		pydb_dlhdl = NULL;
		return (-1);
	}

	return (0);
}

static void
python_db_fini(void)
{
	if (pydb_dlhdl) {
		pydb_agent_destroy(pydb_hdl);
		pydb_hdl = NULL;

		dlclose(pydb_dlhdl);
		pydb_dlhdl = NULL;
	}
}

const mdb_modinfo_t *
_mdb_init(void)
{
	if (python_db_init() != 0)
		return (NULL);

	return (&modinfo);
}

void
_mdb_fini(void)
{
	python_db_fini();
}