blob: 43995258523c7c36b06e026d6655be7127c35025 [file] [log] [blame]
Fred Drake8c081a12001-10-12 20:57:55 +00001/*
2 * This is the High Performance Python Profiler portion of HotShot.
3 */
4
Tim Peters885d4572001-11-28 20:27:42 +00005#include "Python.h"
6#include "compile.h"
7#include "eval.h"
8#include "frameobject.h"
9#include "structmember.h"
Fred Drake8c081a12001-10-12 20:57:55 +000010
Fred Drake8c081a12001-10-12 20:57:55 +000011/*
12 * Which timer to use should be made more configurable, but that should not
Tim Petersfeab23f2001-10-13 00:11:10 +000013 * be difficult. This will do for now.
Fred Drake8c081a12001-10-12 20:57:55 +000014 */
15#ifdef MS_WIN32
16#include <windows.h>
Tim Peters1566a172001-10-12 22:08:39 +000017#include <direct.h> /* for getcwd() */
Tim Peters7d99ff22001-10-13 07:37:52 +000018typedef __int64 hs_time;
19#define GETTIMEOFDAY(P_HS_TIME) \
20 { LARGE_INTEGER _temp; \
21 QueryPerformanceCounter(&_temp); \
22 *(P_HS_TIME) = _temp.QuadPart; }
23
Tim Petersfeab23f2001-10-13 00:11:10 +000024
Fred Drake8c081a12001-10-12 20:57:55 +000025#else
26#ifndef HAVE_GETTIMEOFDAY
27#error "This module requires gettimeofday() on non-Windows platforms!"
28#endif
Andrew MacIntyre7bf68332002-03-03 02:59:16 +000029#if defined(macintosh) || (defined(PYOS_OS2) && defined(PYCC_GCC))
Jack Jansen963659a2001-10-23 22:26:16 +000030#include <sys/time.h>
31#else
Fred Drake8c081a12001-10-12 20:57:55 +000032#include <sys/resource.h>
33#include <sys/times.h>
Jack Jansen963659a2001-10-23 22:26:16 +000034#endif
Fred Drake8c081a12001-10-12 20:57:55 +000035typedef struct timeval hs_time;
36#endif
37
38#if !defined(__cplusplus) && !defined(inline)
39#ifdef __GNUC__
40#define inline __inline
41#endif
42#endif
43
44#ifndef inline
45#define inline
46#endif
47
48#define BUFFERSIZE 10240
49
Jack Jansen963659a2001-10-23 22:26:16 +000050#ifdef macintosh
51#define PATH_MAX 254
52#endif
53
Andrew MacIntyre7bf68332002-03-03 02:59:16 +000054#if defined(PYOS_OS2) && defined(PYCC_GCC)
55#define PATH_MAX 260
56#endif
57
Tim Peters1566a172001-10-12 22:08:39 +000058#ifndef PATH_MAX
59# ifdef MAX_PATH
60# define PATH_MAX MAX_PATH
61# else
62# error "Need a defn. for PATH_MAX in _hotshot.c"
63# endif
64#endif
65
Fred Drake8c081a12001-10-12 20:57:55 +000066typedef struct {
67 PyObject_HEAD
68 PyObject *filemap;
69 PyObject *logfilename;
70 int index;
71 unsigned char buffer[BUFFERSIZE];
72 FILE *logfp;
73 int lineevents;
74 int linetimings;
Fred Drake30d1c752001-10-15 22:11:02 +000075 int frametimings;
Fred Drake8c081a12001-10-12 20:57:55 +000076 /* size_t filled; */
77 int active;
78 int next_fileno;
Fred Drake8c081a12001-10-12 20:57:55 +000079 hs_time prev_timeofday;
80} ProfilerObject;
81
82typedef struct {
83 PyObject_HEAD
Fred Drake4c2e1af2001-10-29 20:45:57 +000084 PyObject *info;
Fred Drake8c081a12001-10-12 20:57:55 +000085 FILE *logfp;
Fred Drake8c081a12001-10-12 20:57:55 +000086 int linetimings;
Fred Drake30d1c752001-10-15 22:11:02 +000087 int frametimings;
Fred Drake8c081a12001-10-12 20:57:55 +000088} LogReaderObject;
89
90static PyObject * ProfilerError = NULL;
91
92
93#ifndef MS_WIN32
94#ifdef GETTIMEOFDAY_NO_TZ
95#define GETTIMEOFDAY(ptv) gettimeofday((ptv))
96#else
97#define GETTIMEOFDAY(ptv) gettimeofday((ptv), (struct timezone *)NULL)
98#endif
99#endif
100
101
102/* The log reader... */
103
Tim Petersfeab23f2001-10-13 00:11:10 +0000104static char logreader_close__doc__[] =
105"close()\n"
106"Close the log file, preventing additional records from being read.";
Fred Drake8c081a12001-10-12 20:57:55 +0000107
108static PyObject *
109logreader_close(LogReaderObject *self, PyObject *args)
110{
111 PyObject *result = NULL;
112 if (PyArg_ParseTuple(args, ":close")) {
113 if (self->logfp != NULL) {
114 fclose(self->logfp);
115 self->logfp = NULL;
116 }
117 result = Py_None;
118 Py_INCREF(result);
119 }
120 return result;
121}
122
123#if Py_TPFLAGS_HAVE_ITER
124/* This is only used if the interpreter has iterator support; the
125 * iternext handler is also used as a helper for other functions, so
126 * does not need to be included in this conditional section.
127 */
128static PyObject *
129logreader_tp_iter(LogReaderObject *self)
130{
131 Py_INCREF(self);
132 return (PyObject *) self;
133}
134#endif
135
136
137/* Log File Format
138 * ---------------
139 *
140 * The log file consists of a sequence of variable-length records.
141 * Each record is identified with a record type identifier in two
142 * bits of the first byte. The two bits are the "least significant"
143 * bits of the byte.
144 *
145 * Low bits: Opcode: Meaning:
146 * 0x00 ENTER enter a frame
147 * 0x01 EXIT exit a frame
148 * 0x02 LINENO SET_LINENO instruction was executed
149 * 0x03 OTHER more bits are needed to deecode
150 *
151 * If the type is OTHER, the record is not packed so tightly, and the
152 * remaining bits are used to disambiguate the record type. These
153 * records are not used as frequently so compaction is not an issue.
154 * Each of the first three record types has a highly tailored
155 * structure that allows it to be packed tightly.
156 *
157 * The OTHER records have the following identifiers:
158 *
159 * First byte: Opcode: Meaning:
160 * 0x13 ADD_INFO define a key/value pair
161 * 0x23 DEFINE_FILE define an int->filename mapping
162 * 0x33 LINE_TIMES indicates if LINENO events have tdeltas
Fred Drake30d1c752001-10-15 22:11:02 +0000163 * 0x43 DEFINE_FUNC define a (fileno,lineno)->funcname mapping
164 * 0x53 FRAME_TIMES indicates if ENTER/EXIT events have tdeltas
Fred Drake8c081a12001-10-12 20:57:55 +0000165 *
166 * Packed Integers
167 *
168 * "Packed integers" are non-negative integer values encoded as a
169 * sequence of bytes. Each byte is encoded such that the most
170 * significant bit is set if the next byte is also part of the
171 * integer. Each byte provides bits to the least-significant end of
172 * the result; the accumulated value must be shifted up to place the
173 * new bits into the result.
174 *
175 * "Modified packed integers" are packed integers where only a portion
176 * of the first byte is used. In the rest of the specification, these
177 * are referred to as "MPI(n,name)", where "n" is the number of bits
178 * discarded from the least-signicant positions of the byte, and
179 * "name" is a name being given to those "discarded" bits, since they
180 * are a field themselves.
181 *
182 * ENTER records:
183 *
184 * MPI(2,type) fileno -- type is 0x00
Fred Drake8c081a12001-10-12 20:57:55 +0000185 * PI lineno
Fred Drake30d1c752001-10-15 22:11:02 +0000186 * PI tdelta -- iff frame times are enabled
Fred Drake8c081a12001-10-12 20:57:55 +0000187 *
188 * EXIT records
189 *
Fred Drake30d1c752001-10-15 22:11:02 +0000190 * MPI(2,type) tdelta -- type is 0x01; tdelta will be 0
191 * if frame times are disabled
Fred Drake8c081a12001-10-12 20:57:55 +0000192 *
193 * LINENO records
194 *
195 * MPI(2,type) lineno -- type is 0x02
196 * PI tdelta -- iff LINENO includes it
197 *
198 * ADD_INFO records
199 *
Fred Drake30d1c752001-10-15 22:11:02 +0000200 * BYTE type -- always 0x13
Fred Drake8c081a12001-10-12 20:57:55 +0000201 * PI len1 -- length of first string
202 * BYTE string1[len1] -- len1 bytes of string data
203 * PI len2 -- length of second string
204 * BYTE string2[len2] -- len2 bytes of string data
205 *
206 * DEFINE_FILE records
207 *
Fred Drake30d1c752001-10-15 22:11:02 +0000208 * BYTE type -- always 0x23
Fred Drake8c081a12001-10-12 20:57:55 +0000209 * PI fileno
210 * PI len -- length of filename
211 * BYTE filename[len] -- len bytes of string data
212 *
Fred Drake30d1c752001-10-15 22:11:02 +0000213 * DEFINE_FUNC records
214 *
215 * BYTE type -- always 0x43
216 * PI fileno
217 * PI lineno
218 * PI len -- length of funcname
219 * BYTE funcname[len] -- len bytes of string data
220 *
Fred Drake8c081a12001-10-12 20:57:55 +0000221 * LINE_TIMES records
Fred Drake30d1c752001-10-15 22:11:02 +0000222 *
223 * This record can be used only before the start of ENTER/EXIT/LINENO
224 * records. If have_tdelta is true, LINENO records will include the
225 * tdelta field, otherwise it will be omitted. If this record is not
226 * given, LINENO records will not contain the tdelta field.
227 *
228 * BYTE type -- always 0x33
Fred Drake8c081a12001-10-12 20:57:55 +0000229 * BYTE have_tdelta -- 0 if LINENO does *not* have
230 * timing information
Fred Drake30d1c752001-10-15 22:11:02 +0000231 * FRAME_TIMES records
232 *
233 * This record can be used only before the start of ENTER/EXIT/LINENO
234 * records. If have_tdelta is true, ENTER and EXIT records will
235 * include the tdelta field, otherwise it will be omitted. If this
236 * record is not given, ENTER and EXIT records will contain the tdelta
237 * field.
238 *
239 * BYTE type -- always 0x53
240 * BYTE have_tdelta -- 0 if ENTER/EXIT do *not* have
241 * timing information
Fred Drake8c081a12001-10-12 20:57:55 +0000242 */
243
244#define WHAT_ENTER 0x00
245#define WHAT_EXIT 0x01
246#define WHAT_LINENO 0x02
247#define WHAT_OTHER 0x03 /* only used in decoding */
248#define WHAT_ADD_INFO 0x13
249#define WHAT_DEFINE_FILE 0x23
250#define WHAT_LINE_TIMES 0x33
Fred Drake30d1c752001-10-15 22:11:02 +0000251#define WHAT_DEFINE_FUNC 0x43
252#define WHAT_FRAME_TIMES 0x53
Fred Drake8c081a12001-10-12 20:57:55 +0000253
254#define ERR_NONE 0
255#define ERR_EOF -1
256#define ERR_EXCEPTION -2
Fred Drake4c2e1af2001-10-29 20:45:57 +0000257#define ERR_BAD_RECTYPE -3
Fred Drake8c081a12001-10-12 20:57:55 +0000258
259#define PISIZE (sizeof(int) + 1)
260#define MPISIZE (PISIZE + 1)
261
262/* Maximum size of "normal" events -- nothing that contains string data */
263#define MAXEVENTSIZE (MPISIZE + PISIZE*2)
264
265
266/* Unpack a packed integer; if "discard" is non-zero, unpack a modified
267 * packed integer with "discard" discarded bits.
268 */
269static int
270unpack_packed_int(LogReaderObject *self, int *pvalue, int discard)
271{
Neil Schemenauer8b6b4912002-05-29 18:19:14 +0000272 int c;
Fred Drake8c081a12001-10-12 20:57:55 +0000273 int accum = 0;
274 int bits = 0;
Fred Drake8c081a12001-10-12 20:57:55 +0000275 int cont;
276
277 do {
Fred Drake8c081a12001-10-12 20:57:55 +0000278 /* read byte */
Neil Schemenauer8b6b4912002-05-29 18:19:14 +0000279 if ((c = fgetc(self->logfp)) == EOF)
280 return ERR_EOF;
281 accum |= ((c & 0x7F) >> discard) << bits;
Fred Drake8c081a12001-10-12 20:57:55 +0000282 bits += (7 - discard);
Neil Schemenauer8b6b4912002-05-29 18:19:14 +0000283 cont = c & 0x80;
Fred Drake8c081a12001-10-12 20:57:55 +0000284 discard = 0;
Fred Drake8c081a12001-10-12 20:57:55 +0000285 } while (cont);
286
Fred Drake8c081a12001-10-12 20:57:55 +0000287 *pvalue = accum;
288
289 return 0;
290}
291
292/* Unpack a string, which is encoded as a packed integer giving the
293 * length of the string, followed by the string data.
294 */
295static int
296unpack_string(LogReaderObject *self, PyObject **pvalue)
297{
Neil Schemenauer8b6b4912002-05-29 18:19:14 +0000298 int i;
Fred Drake8c081a12001-10-12 20:57:55 +0000299 int len;
Neil Schemenauer8b6b4912002-05-29 18:19:14 +0000300 int err;
301 char *buf;
302
303 if ((err = unpack_packed_int(self, &len, 0)))
304 return err;
Fred Drake8c081a12001-10-12 20:57:55 +0000305
Neil Schemenauer8b6b4912002-05-29 18:19:14 +0000306 buf = malloc(len);
307 for (i=0; i < len; i++) {
308 if ((buf[i] = fgetc(self->logfp)) == EOF) {
309 free(buf);
310 return ERR_EOF;
Fred Drake8c081a12001-10-12 20:57:55 +0000311 }
312 }
Neil Schemenauer8b6b4912002-05-29 18:19:14 +0000313 *pvalue = PyString_FromStringAndSize(buf, len);
314 free(buf);
315 if (*pvalue == NULL) {
316 return ERR_EXCEPTION;
317 }
318 return 0;
Fred Drake8c081a12001-10-12 20:57:55 +0000319}
320
321
Fred Drake4c2e1af2001-10-29 20:45:57 +0000322static int
Neil Schemenauer8b6b4912002-05-29 18:19:14 +0000323unpack_add_info(LogReaderObject *self)
Fred Drake4c2e1af2001-10-29 20:45:57 +0000324{
325 PyObject *key;
326 PyObject *value = NULL;
327 int err;
328
Fred Drake4c2e1af2001-10-29 20:45:57 +0000329 err = unpack_string(self, &key);
330 if (!err) {
331 err = unpack_string(self, &value);
332 if (err)
333 Py_DECREF(key);
334 else {
335 PyObject *list = PyDict_GetItem(self->info, key);
336 if (list == NULL) {
337 list = PyList_New(0);
338 if (list == NULL) {
339 err = ERR_EXCEPTION;
340 goto finally;
341 }
342 if (PyDict_SetItem(self->info, key, list)) {
343 err = ERR_EXCEPTION;
344 goto finally;
345 }
346 }
347 if (PyList_Append(list, value))
348 err = ERR_EXCEPTION;
349 }
350 }
351 finally:
352 Py_XDECREF(key);
353 Py_XDECREF(value);
354 return err;
355}
356
357
358static void
Fred Drake4c2e1af2001-10-29 20:45:57 +0000359eof_error(void)
360{
361 PyErr_SetString(PyExc_EOFError,
362 "end of file with incomplete profile record");
363}
364
Fred Drake8c081a12001-10-12 20:57:55 +0000365static PyObject *
366logreader_tp_iternext(LogReaderObject *self)
367{
Neil Schemenauer8b6b4912002-05-29 18:19:14 +0000368 int c;
369 int what;
Fred Drake8c081a12001-10-12 20:57:55 +0000370 int err = ERR_NONE;
371 int lineno = -1;
372 int fileno = -1;
373 int tdelta = -1;
374 PyObject *s1 = NULL, *s2 = NULL;
375 PyObject *result = NULL;
376#if 0
377 unsigned char b0, b1;
378#endif
379
380 if (self->logfp == NULL) {
381 PyErr_SetString(ProfilerError,
382 "cannot iterate over closed LogReader object");
383 return NULL;
384 }
Fred Drake4c2e1af2001-10-29 20:45:57 +0000385
Neil Schemenauer8b6b4912002-05-29 18:19:14 +0000386restart:
387 /* decode the record type */
388 if ((c = fgetc(self->logfp)) == EOF)
Fred Drake8c081a12001-10-12 20:57:55 +0000389 return NULL;
390
Neil Schemenauer8b6b4912002-05-29 18:19:14 +0000391 what = c & WHAT_OTHER;
392 if (what == WHAT_OTHER)
393 what = c; /* need all the bits for type */
394 else
395 ungetc(c, self->logfp); /* type byte includes packed int */
Fred Drake8c081a12001-10-12 20:57:55 +0000396
Fred Drake8c081a12001-10-12 20:57:55 +0000397 switch (what) {
398 case WHAT_ENTER:
399 err = unpack_packed_int(self, &fileno, 2);
400 if (!err) {
Fred Drake30d1c752001-10-15 22:11:02 +0000401 err = unpack_packed_int(self, &lineno, 0);
402 if (self->frametimings && !err)
403 err = unpack_packed_int(self, &tdelta, 0);
Fred Drake8c081a12001-10-12 20:57:55 +0000404 }
405 break;
406 case WHAT_EXIT:
407 err = unpack_packed_int(self, &tdelta, 2);
408 break;
409 case WHAT_LINENO:
410 err = unpack_packed_int(self, &lineno, 2);
411 if (self->linetimings && !err)
412 err = unpack_packed_int(self, &tdelta, 0);
413 break;
414 case WHAT_ADD_INFO:
Neil Schemenauer8b6b4912002-05-29 18:19:14 +0000415 err = unpack_add_info(self);
Fred Drake8c081a12001-10-12 20:57:55 +0000416 break;
417 case WHAT_DEFINE_FILE:
418 err = unpack_packed_int(self, &fileno, 0);
419 if (!err) {
420 err = unpack_string(self, &s1);
421 if (!err) {
422 Py_INCREF(Py_None);
423 s2 = Py_None;
424 }
425 }
426 break;
Fred Drake30d1c752001-10-15 22:11:02 +0000427 case WHAT_DEFINE_FUNC:
428 err = unpack_packed_int(self, &fileno, 0);
429 if (!err) {
430 err = unpack_packed_int(self, &lineno, 0);
431 if (!err)
432 err = unpack_string(self, &s1);
433 }
434 break;
Fred Drake8c081a12001-10-12 20:57:55 +0000435 case WHAT_LINE_TIMES:
Neil Schemenauer8b6b4912002-05-29 18:19:14 +0000436 if ((c = fgetc(self->logfp)) == EOF)
Fred Drake8c081a12001-10-12 20:57:55 +0000437 err = ERR_EOF;
438 else {
Neil Schemenauer8b6b4912002-05-29 18:19:14 +0000439 self->linetimings = c ? 1 : 0;
440 goto restart;
441 }
Fred Drake4c2e1af2001-10-29 20:45:57 +0000442 break;
Fred Drake30d1c752001-10-15 22:11:02 +0000443 case WHAT_FRAME_TIMES:
Neil Schemenauer8b6b4912002-05-29 18:19:14 +0000444 if ((c = fgetc(self->logfp)) == EOF)
Fred Drake30d1c752001-10-15 22:11:02 +0000445 err = ERR_EOF;
446 else {
Neil Schemenauer8b6b4912002-05-29 18:19:14 +0000447 self->frametimings = c ? 1 : 0;
448 goto restart;
449 }
Fred Drake4c2e1af2001-10-29 20:45:57 +0000450 break;
Fred Drake8c081a12001-10-12 20:57:55 +0000451 default:
Fred Drake4c2e1af2001-10-29 20:45:57 +0000452 err = ERR_BAD_RECTYPE;
Fred Drake8c081a12001-10-12 20:57:55 +0000453 }
Fred Drake4c2e1af2001-10-29 20:45:57 +0000454 if (err == ERR_BAD_RECTYPE) {
455 PyErr_SetString(PyExc_ValueError,
456 "unknown record type in log file");
457 }
458 else if (err == ERR_EOF) {
Fred Drake4c2e1af2001-10-29 20:45:57 +0000459 eof_error();
Fred Drake8c081a12001-10-12 20:57:55 +0000460 }
461 else if (!err) {
462 result = PyTuple_New(4);
463 PyTuple_SET_ITEM(result, 0, PyInt_FromLong(what));
464 PyTuple_SET_ITEM(result, 2, PyInt_FromLong(fileno));
Fred Drake30d1c752001-10-15 22:11:02 +0000465 if (s1 == NULL)
Fred Drake8c081a12001-10-12 20:57:55 +0000466 PyTuple_SET_ITEM(result, 1, PyInt_FromLong(tdelta));
Fred Drake30d1c752001-10-15 22:11:02 +0000467 else
Fred Drake8c081a12001-10-12 20:57:55 +0000468 PyTuple_SET_ITEM(result, 1, s1);
Fred Drake30d1c752001-10-15 22:11:02 +0000469 if (s2 == NULL)
470 PyTuple_SET_ITEM(result, 3, PyInt_FromLong(lineno));
471 else
Fred Drake8c081a12001-10-12 20:57:55 +0000472 PyTuple_SET_ITEM(result, 3, s2);
Fred Drake8c081a12001-10-12 20:57:55 +0000473 }
474 /* The only other case is err == ERR_EXCEPTION, in which case the
475 * exception is already set.
476 */
477#if 0
478 b0 = self->buffer[self->index];
479 b1 = self->buffer[self->index + 1];
480 if (b0 & 1) {
481 /* This is a line-number event. */
482 what = PyTrace_LINE;
483 lineno = ((b0 & ~1) << 7) + b1;
484 self->index += 2;
485 }
486 else {
487 what = (b0 & 0x0E) >> 1;
488 tdelta = ((b0 & 0xF0) << 4) + b1;
489 if (what == PyTrace_CALL) {
490 /* we know there's a 2-byte file ID & 2-byte line number */
491 fileno = ((self->buffer[self->index + 2] << 8)
492 + self->buffer[self->index + 3]);
493 lineno = ((self->buffer[self->index + 4] << 8)
494 + self->buffer[self->index + 5]);
495 self->index += 6;
496 }
497 else
498 self->index += 2;
499 }
500#endif
501 return result;
502}
503
504static void
505logreader_dealloc(LogReaderObject *self)
506{
507 if (self->logfp != NULL) {
508 fclose(self->logfp);
509 self->logfp = NULL;
510 }
511 PyObject_Del(self);
512}
513
514static PyObject *
515logreader_sq_item(LogReaderObject *self, int index)
516{
517 PyObject *result = logreader_tp_iternext(self);
518 if (result == NULL && !PyErr_Occurred()) {
519 PyErr_SetString(PyExc_IndexError, "no more events in log");
520 return NULL;
521 }
522 return result;
523}
524
Tim Petersfeab23f2001-10-13 00:11:10 +0000525static char next__doc__[] =
526"next() -> event-info\n"
527"Return the next event record from the log file.";
Fred Drake8c081a12001-10-12 20:57:55 +0000528
529static PyObject *
530logreader_next(LogReaderObject *self, PyObject *args)
531{
532 PyObject *result = NULL;
533
534 if (PyArg_ParseTuple(args, ":next")) {
535 result = logreader_tp_iternext(self);
536 /* XXX return None if there's nothing left */
537 /* tp_iternext does the right thing, though */
538 if (result == NULL && !PyErr_Occurred()) {
539 result = Py_None;
540 Py_INCREF(result);
541 }
542 }
543 return result;
544}
545
Fred Drake62c1e3c2001-12-04 21:40:53 +0000546static void
547do_stop(ProfilerObject *self);
Fred Drake8c081a12001-10-12 20:57:55 +0000548
549static int
550flush_data(ProfilerObject *self)
551{
552 /* Need to dump data to the log file... */
553 size_t written = fwrite(self->buffer, 1, self->index, self->logfp);
Tim Peters1566a172001-10-12 22:08:39 +0000554 if (written == (size_t)self->index)
Fred Drake8c081a12001-10-12 20:57:55 +0000555 self->index = 0;
556 else {
557 memmove(self->buffer, &self->buffer[written],
558 self->index - written);
559 self->index -= written;
560 if (written == 0) {
561 char *s = PyString_AsString(self->logfilename);
562 PyErr_SetFromErrnoWithFilename(PyExc_IOError, s);
Fred Drake62c1e3c2001-12-04 21:40:53 +0000563 do_stop(self);
Fred Drake8c081a12001-10-12 20:57:55 +0000564 return -1;
565 }
566 }
567 if (written > 0) {
568 if (fflush(self->logfp)) {
569 char *s = PyString_AsString(self->logfilename);
570 PyErr_SetFromErrnoWithFilename(PyExc_IOError, s);
Fred Drake62c1e3c2001-12-04 21:40:53 +0000571 do_stop(self);
Fred Drake8c081a12001-10-12 20:57:55 +0000572 return -1;
573 }
574 }
575 return 0;
576}
577
Fred Drake62c1e3c2001-12-04 21:40:53 +0000578static inline int
Fred Drake8c081a12001-10-12 20:57:55 +0000579pack_packed_int(ProfilerObject *self, int value)
580{
581 unsigned char partial;
582
583 do {
584 partial = value & 0x7F;
585 value >>= 7;
586 if (value)
587 partial |= 0x80;
588 self->buffer[self->index] = partial;
589 self->index++;
590 } while (value);
Fred Drake62c1e3c2001-12-04 21:40:53 +0000591 return 0;
Fred Drake8c081a12001-10-12 20:57:55 +0000592}
593
594/* Encode a modified packed integer, with a subfield of modsize bits
595 * containing the value "subfield". The value of subfield is not
596 * checked to ensure it actually fits in modsize bits.
597 */
Fred Drake62c1e3c2001-12-04 21:40:53 +0000598static inline int
Fred Drake8c081a12001-10-12 20:57:55 +0000599pack_modified_packed_int(ProfilerObject *self, int value,
600 int modsize, int subfield)
601{
602 const int maxvalues[] = {-1, 1, 3, 7, 15, 31, 63, 127};
603
604 int bits = 7 - modsize;
605 int partial = value & maxvalues[bits];
606 unsigned char b = subfield | (partial << modsize);
607
608 if (partial != value) {
609 b |= 0x80;
610 self->buffer[self->index] = b;
611 self->index++;
Fred Drake62c1e3c2001-12-04 21:40:53 +0000612 return pack_packed_int(self, value >> bits);
Fred Drake8c081a12001-10-12 20:57:55 +0000613 }
Fred Drake62c1e3c2001-12-04 21:40:53 +0000614 self->buffer[self->index] = b;
615 self->index++;
616 return 0;
Fred Drake8c081a12001-10-12 20:57:55 +0000617}
618
Fred Drake62c1e3c2001-12-04 21:40:53 +0000619static int
Fred Drake30d1c752001-10-15 22:11:02 +0000620pack_string(ProfilerObject *self, const char *s, int len)
Fred Drake8c081a12001-10-12 20:57:55 +0000621{
Fred Drake62c1e3c2001-12-04 21:40:53 +0000622 if (len + PISIZE + self->index >= BUFFERSIZE) {
623 if (flush_data(self) < 0)
624 return -1;
625 }
626 if (pack_packed_int(self, len) < 0)
627 return -1;
Fred Drake8c081a12001-10-12 20:57:55 +0000628 memcpy(self->buffer + self->index, s, len);
629 self->index += len;
Fred Drake62c1e3c2001-12-04 21:40:53 +0000630 return 0;
Fred Drake8c081a12001-10-12 20:57:55 +0000631}
632
Fred Drake62c1e3c2001-12-04 21:40:53 +0000633static int
Fred Drake8c081a12001-10-12 20:57:55 +0000634pack_add_info(ProfilerObject *self, const char *s1, const char *s2)
635{
636 int len1 = strlen(s1);
637 int len2 = strlen(s2);
638
Fred Drake62c1e3c2001-12-04 21:40:53 +0000639 if (len1 + len2 + PISIZE*2 + 1 + self->index >= BUFFERSIZE) {
640 if (flush_data(self) < 0)
641 return -1;
642 }
Fred Drake8c081a12001-10-12 20:57:55 +0000643 self->buffer[self->index] = WHAT_ADD_INFO;
644 self->index++;
Fred Drake62c1e3c2001-12-04 21:40:53 +0000645 if (pack_string(self, s1, len1) < 0)
646 return -1;
647 return pack_string(self, s2, len2);
Fred Drake8c081a12001-10-12 20:57:55 +0000648}
649
Fred Drake62c1e3c2001-12-04 21:40:53 +0000650static int
Fred Drake8c081a12001-10-12 20:57:55 +0000651pack_define_file(ProfilerObject *self, int fileno, const char *filename)
652{
653 int len = strlen(filename);
654
Fred Drake62c1e3c2001-12-04 21:40:53 +0000655 if (len + PISIZE*2 + 1 + self->index >= BUFFERSIZE) {
656 if (flush_data(self) < 0)
657 return -1;
658 }
Fred Drake8c081a12001-10-12 20:57:55 +0000659 self->buffer[self->index] = WHAT_DEFINE_FILE;
660 self->index++;
Fred Drake62c1e3c2001-12-04 21:40:53 +0000661 if (pack_packed_int(self, fileno) < 0)
662 return -1;
663 return pack_string(self, filename, len);
Fred Drake30d1c752001-10-15 22:11:02 +0000664}
665
Fred Drake62c1e3c2001-12-04 21:40:53 +0000666static int
Fred Drake30d1c752001-10-15 22:11:02 +0000667pack_define_func(ProfilerObject *self, int fileno, int lineno,
668 const char *funcname)
669{
670 int len = strlen(funcname);
671
Fred Drake62c1e3c2001-12-04 21:40:53 +0000672 if (len + PISIZE*3 + 1 + self->index >= BUFFERSIZE) {
673 if (flush_data(self) < 0)
674 return -1;
675 }
Fred Drake30d1c752001-10-15 22:11:02 +0000676 self->buffer[self->index] = WHAT_DEFINE_FUNC;
677 self->index++;
Fred Drake62c1e3c2001-12-04 21:40:53 +0000678 if (pack_packed_int(self, fileno) < 0)
679 return -1;
680 if (pack_packed_int(self, lineno) < 0)
681 return -1;
682 return pack_string(self, funcname, len);
Fred Drake8c081a12001-10-12 20:57:55 +0000683}
684
Fred Drake62c1e3c2001-12-04 21:40:53 +0000685static int
Fred Drake8c081a12001-10-12 20:57:55 +0000686pack_line_times(ProfilerObject *self)
687{
Fred Drake62c1e3c2001-12-04 21:40:53 +0000688 if (2 + self->index >= BUFFERSIZE) {
689 if (flush_data(self) < 0)
690 return -1;
691 }
Fred Drake8c081a12001-10-12 20:57:55 +0000692 self->buffer[self->index] = WHAT_LINE_TIMES;
693 self->buffer[self->index + 1] = self->linetimings ? 1 : 0;
694 self->index += 2;
Fred Drake62c1e3c2001-12-04 21:40:53 +0000695 return 0;
Fred Drake8c081a12001-10-12 20:57:55 +0000696}
697
Fred Drake62c1e3c2001-12-04 21:40:53 +0000698static int
Fred Drake30d1c752001-10-15 22:11:02 +0000699pack_frame_times(ProfilerObject *self)
700{
Fred Drake62c1e3c2001-12-04 21:40:53 +0000701 if (2 + self->index >= BUFFERSIZE) {
702 if (flush_data(self) < 0)
703 return -1;
704 }
Fred Drake30d1c752001-10-15 22:11:02 +0000705 self->buffer[self->index] = WHAT_FRAME_TIMES;
706 self->buffer[self->index + 1] = self->frametimings ? 1 : 0;
707 self->index += 2;
Fred Drake62c1e3c2001-12-04 21:40:53 +0000708 return 0;
Fred Drake30d1c752001-10-15 22:11:02 +0000709}
710
Fred Drake62c1e3c2001-12-04 21:40:53 +0000711static inline int
Fred Drake8c081a12001-10-12 20:57:55 +0000712pack_enter(ProfilerObject *self, int fileno, int tdelta, int lineno)
713{
Fred Drake62c1e3c2001-12-04 21:40:53 +0000714 if (MPISIZE + PISIZE*2 + self->index >= BUFFERSIZE) {
715 if (flush_data(self) < 0)
716 return -1;
717 }
Fred Drake8c081a12001-10-12 20:57:55 +0000718 pack_modified_packed_int(self, fileno, 2, WHAT_ENTER);
Fred Drake8c081a12001-10-12 20:57:55 +0000719 pack_packed_int(self, lineno);
Fred Drake30d1c752001-10-15 22:11:02 +0000720 if (self->frametimings)
Fred Drake62c1e3c2001-12-04 21:40:53 +0000721 return pack_packed_int(self, tdelta);
722 else
723 return 0;
Fred Drake8c081a12001-10-12 20:57:55 +0000724}
725
Fred Drake62c1e3c2001-12-04 21:40:53 +0000726static inline int
Fred Drake8c081a12001-10-12 20:57:55 +0000727pack_exit(ProfilerObject *self, int tdelta)
728{
Fred Drake62c1e3c2001-12-04 21:40:53 +0000729 if (MPISIZE + self->index >= BUFFERSIZE) {
730 if (flush_data(self) < 0)
731 return -1;
Fred Drake30d1c752001-10-15 22:11:02 +0000732 }
Fred Drake62c1e3c2001-12-04 21:40:53 +0000733 if (self->frametimings)
734 return pack_modified_packed_int(self, tdelta, 2, WHAT_EXIT);
735 self->buffer[self->index] = WHAT_EXIT;
736 self->index++;
737 return 0;
Fred Drake8c081a12001-10-12 20:57:55 +0000738}
739
Fred Drake62c1e3c2001-12-04 21:40:53 +0000740static inline int
Fred Drake8c081a12001-10-12 20:57:55 +0000741pack_lineno(ProfilerObject *self, int lineno)
742{
Fred Drake62c1e3c2001-12-04 21:40:53 +0000743 if (MPISIZE + self->index >= BUFFERSIZE) {
744 if (flush_data(self) < 0)
745 return -1;
746 }
747 return pack_modified_packed_int(self, lineno, 2, WHAT_LINENO);
Fred Drake8c081a12001-10-12 20:57:55 +0000748}
749
Fred Drake62c1e3c2001-12-04 21:40:53 +0000750static inline int
Fred Drake8c081a12001-10-12 20:57:55 +0000751pack_lineno_tdelta(ProfilerObject *self, int lineno, int tdelta)
752{
Fred Drake62c1e3c2001-12-04 21:40:53 +0000753 if (MPISIZE + PISIZE + self->index >= BUFFERSIZE) {
754 if (flush_data(self) < 0)
755 return 0;
756 }
757 if (pack_modified_packed_int(self, lineno, 2, WHAT_LINENO) < 0)
758 return -1;
759 return pack_packed_int(self, tdelta);
Fred Drake8c081a12001-10-12 20:57:55 +0000760}
761
762static inline int
763get_fileno(ProfilerObject *self, PyCodeObject *fcode)
764{
Fred Drake30d1c752001-10-15 22:11:02 +0000765 /* This is only used for ENTER events. */
766
767 PyObject *obj;
768 PyObject *dict;
Fred Drake8c081a12001-10-12 20:57:55 +0000769 int fileno;
770
Fred Drake30d1c752001-10-15 22:11:02 +0000771 obj = PyDict_GetItem(self->filemap, fcode->co_filename);
772 if (obj == NULL) {
Fred Drake8c081a12001-10-12 20:57:55 +0000773 /* first sighting of this file */
Fred Drake30d1c752001-10-15 22:11:02 +0000774 dict = PyDict_New();
775 if (dict == NULL) {
Fred Drake8c081a12001-10-12 20:57:55 +0000776 return -1;
777 }
Fred Drake30d1c752001-10-15 22:11:02 +0000778 fileno = self->next_fileno;
779 obj = Py_BuildValue("iN", fileno, dict);
780 if (obj == NULL) {
781 return -1;
782 }
783 if (PyDict_SetItem(self->filemap, fcode->co_filename, obj)) {
784 Py_DECREF(obj);
Fred Drake8c081a12001-10-12 20:57:55 +0000785 return -1;
786 }
787 self->next_fileno++;
Fred Drake30d1c752001-10-15 22:11:02 +0000788 Py_DECREF(obj);
Fred Drake62c1e3c2001-12-04 21:40:53 +0000789 if (pack_define_file(self, fileno,
790 PyString_AS_STRING(fcode->co_filename)) < 0)
791 return -1;
Fred Drake8c081a12001-10-12 20:57:55 +0000792 }
793 else {
794 /* already know this ID */
Fred Drake30d1c752001-10-15 22:11:02 +0000795 fileno = PyInt_AS_LONG(PyTuple_GET_ITEM(obj, 0));
796 dict = PyTuple_GET_ITEM(obj, 1);
797 }
798 /* make sure we save a function name for this (fileno, lineno) */
799 obj = PyInt_FromLong(fcode->co_firstlineno);
800 if (obj == NULL) {
801 /* We just won't have it saved; too bad. */
802 PyErr_Clear();
803 }
804 else {
805 PyObject *name = PyDict_GetItem(dict, obj);
806 if (name == NULL) {
Fred Drake62c1e3c2001-12-04 21:40:53 +0000807 if (pack_define_func(self, fileno, fcode->co_firstlineno,
808 PyString_AS_STRING(fcode->co_name)) < 0)
809 return -1;
Fred Drake30d1c752001-10-15 22:11:02 +0000810 if (PyDict_SetItem(dict, obj, fcode->co_name))
811 return -1;
812 }
Fred Drake8c081a12001-10-12 20:57:55 +0000813 }
814 return fileno;
815}
816
817static inline int
818get_tdelta(ProfilerObject *self)
819{
820 int tdelta;
821#ifdef MS_WIN32
822 hs_time tv;
Tim Peters7d99ff22001-10-13 07:37:52 +0000823 hs_time diff;
Fred Drake8c081a12001-10-12 20:57:55 +0000824
Tim Peters7d99ff22001-10-13 07:37:52 +0000825 GETTIMEOFDAY(&tv);
826 diff = tv - self->prev_timeofday;
827 tdelta = (int)diff;
Fred Drake8c081a12001-10-12 20:57:55 +0000828#else
829 struct timeval tv;
830
831 GETTIMEOFDAY(&tv);
832
833 if (tv.tv_sec == self->prev_timeofday.tv_sec)
834 tdelta = tv.tv_usec - self->prev_timeofday.tv_usec;
835 else
836 tdelta = ((tv.tv_sec - self->prev_timeofday.tv_sec) * 1000000
837 + tv.tv_usec);
838#endif
839 self->prev_timeofday = tv;
840 return tdelta;
841}
842
843
844/* The workhorse: the profiler callback function. */
845
846static int
847profiler_callback(ProfilerObject *self, PyFrameObject *frame, int what,
848 PyObject *arg)
849{
Fred Drake30d1c752001-10-15 22:11:02 +0000850 int tdelta = -1;
Fred Drake8c081a12001-10-12 20:57:55 +0000851 int fileno;
852
Fred Drake30d1c752001-10-15 22:11:02 +0000853 if (self->frametimings)
854 tdelta = get_tdelta(self);
Fred Drake8c081a12001-10-12 20:57:55 +0000855 switch (what) {
856 case PyTrace_CALL:
857 fileno = get_fileno(self, frame->f_code);
858 if (fileno < 0)
859 return -1;
Fred Drake62c1e3c2001-12-04 21:40:53 +0000860 if (pack_enter(self, fileno, tdelta,
861 frame->f_code->co_firstlineno) < 0)
862 return -1;
Fred Drake8c081a12001-10-12 20:57:55 +0000863 break;
864 case PyTrace_RETURN:
Fred Drake62c1e3c2001-12-04 21:40:53 +0000865 if (pack_exit(self, tdelta) < 0)
866 return -1;
Fred Drake8c081a12001-10-12 20:57:55 +0000867 break;
868 default:
869 /* should never get here */
870 break;
871 }
872 return 0;
873}
874
875
876/* Alternate callback when we want PyTrace_LINE events */
877
878static int
879tracer_callback(ProfilerObject *self, PyFrameObject *frame, int what,
880 PyObject *arg)
881{
882 int fileno;
883
Fred Drake8c081a12001-10-12 20:57:55 +0000884 switch (what) {
885 case PyTrace_CALL:
886 fileno = get_fileno(self, frame->f_code);
887 if (fileno < 0)
888 return -1;
Fred Drake62c1e3c2001-12-04 21:40:53 +0000889 return pack_enter(self, fileno,
890 self->frametimings ? get_tdelta(self) : -1,
891 frame->f_code->co_firstlineno);
892
Fred Drake8c081a12001-10-12 20:57:55 +0000893 case PyTrace_RETURN:
Fred Drake62c1e3c2001-12-04 21:40:53 +0000894 return pack_exit(self, get_tdelta(self));
895
Tim Peters1566a172001-10-12 22:08:39 +0000896 case PyTrace_LINE:
Fred Drake8c081a12001-10-12 20:57:55 +0000897 if (self->linetimings)
Fred Drake62c1e3c2001-12-04 21:40:53 +0000898 return pack_lineno_tdelta(self, frame->f_lineno, get_tdelta(self));
Fred Drake8c081a12001-10-12 20:57:55 +0000899 else
Fred Drake62c1e3c2001-12-04 21:40:53 +0000900 return pack_lineno(self, frame->f_lineno);
901
Fred Drake8c081a12001-10-12 20:57:55 +0000902 default:
903 /* ignore PyTrace_EXCEPTION */
904 break;
905 }
906 return 0;
907}
908
909
910/* A couple of useful helper functions. */
911
912#ifdef MS_WIN32
Tim Petersfeab23f2001-10-13 00:11:10 +0000913static LARGE_INTEGER frequency = {0, 0};
Fred Drake8c081a12001-10-12 20:57:55 +0000914#endif
915
916static unsigned long timeofday_diff = 0;
917static unsigned long rusage_diff = 0;
918
919static void
920calibrate(void)
921{
922 hs_time tv1, tv2;
923
924#ifdef MS_WIN32
Tim Peters7d99ff22001-10-13 07:37:52 +0000925 hs_time diff;
Fred Drake8c081a12001-10-12 20:57:55 +0000926 QueryPerformanceFrequency(&frequency);
927#endif
928
929 GETTIMEOFDAY(&tv1);
930 while (1) {
931 GETTIMEOFDAY(&tv2);
932#ifdef MS_WIN32
Tim Peters7d99ff22001-10-13 07:37:52 +0000933 diff = tv2 - tv1;
934 if (diff != 0) {
935 timeofday_diff = (unsigned long)diff;
Fred Drake8c081a12001-10-12 20:57:55 +0000936 break;
937 }
938#else
939 if (tv1.tv_sec != tv2.tv_sec || tv1.tv_usec != tv2.tv_usec) {
940 if (tv1.tv_sec == tv2.tv_sec)
941 timeofday_diff = tv2.tv_usec - tv1.tv_usec;
942 else
943 timeofday_diff = (1000000 - tv1.tv_usec) + tv2.tv_usec;
944 break;
945 }
946#endif
947 }
Andrew MacIntyre7bf68332002-03-03 02:59:16 +0000948#if defined(MS_WIN32) || defined(macintosh) || defined(PYOS_OS2)
Fred Drake8c081a12001-10-12 20:57:55 +0000949 rusage_diff = -1;
950#else
951 {
952 struct rusage ru1, ru2;
953
954 getrusage(RUSAGE_SELF, &ru1);
955 while (1) {
956 getrusage(RUSAGE_SELF, &ru2);
957 if (ru1.ru_utime.tv_sec != ru2.ru_utime.tv_sec) {
958 rusage_diff = ((1000000 - ru1.ru_utime.tv_usec)
959 + ru2.ru_utime.tv_usec);
960 break;
961 }
962 else if (ru1.ru_utime.tv_usec != ru2.ru_utime.tv_usec) {
963 rusage_diff = ru2.ru_utime.tv_usec - ru1.ru_utime.tv_usec;
964 break;
965 }
966 else if (ru1.ru_stime.tv_sec != ru2.ru_stime.tv_sec) {
967 rusage_diff = ((1000000 - ru1.ru_stime.tv_usec)
968 + ru2.ru_stime.tv_usec);
969 break;
970 }
971 else if (ru1.ru_stime.tv_usec != ru2.ru_stime.tv_usec) {
972 rusage_diff = ru2.ru_stime.tv_usec - ru1.ru_stime.tv_usec;
973 break;
974 }
975 }
976 }
977#endif
978}
979
980static void
981do_start(ProfilerObject *self)
982{
983 self->active = 1;
984 GETTIMEOFDAY(&self->prev_timeofday);
985 if (self->lineevents)
986 PyEval_SetTrace((Py_tracefunc) tracer_callback, (PyObject *)self);
987 else
988 PyEval_SetProfile((Py_tracefunc) profiler_callback, (PyObject *)self);
989}
990
991static void
992do_stop(ProfilerObject *self)
993{
994 if (self->active) {
995 self->active = 0;
996 if (self->lineevents)
997 PyEval_SetTrace(NULL, NULL);
998 else
999 PyEval_SetProfile(NULL, NULL);
1000 }
1001 if (self->index > 0) {
1002 /* Best effort to dump out any remaining data. */
1003 flush_data(self);
1004 }
1005}
1006
1007static int
1008is_available(ProfilerObject *self)
1009{
1010 if (self->active) {
1011 PyErr_SetString(ProfilerError, "profiler already active");
1012 return 0;
1013 }
1014 if (self->logfp == NULL) {
1015 PyErr_SetString(ProfilerError, "profiler already closed");
1016 return 0;
1017 }
1018 return 1;
1019}
1020
1021
1022/* Profiler object interface methods. */
1023
Fred Drake4c2e1af2001-10-29 20:45:57 +00001024static char addinfo__doc__[] =
1025"addinfo(key, value)\n"
1026"Insert an ADD_INFO record into the log.";
1027
1028static PyObject *
1029profiler_addinfo(ProfilerObject *self, PyObject *args)
1030{
1031 PyObject *result = NULL;
1032 char *key, *value;
1033
1034 if (PyArg_ParseTuple(args, "ss:addinfo", &key, &value)) {
1035 if (self->logfp == NULL)
1036 PyErr_SetString(ProfilerError, "profiler already closed");
1037 else {
Fred Drake62c1e3c2001-12-04 21:40:53 +00001038 if (pack_add_info(self, key, value) == 0) {
1039 result = Py_None;
1040 Py_INCREF(result);
1041 }
Fred Drake4c2e1af2001-10-29 20:45:57 +00001042 }
1043 }
1044 return result;
1045}
1046
Tim Petersfeab23f2001-10-13 00:11:10 +00001047static char close__doc__[] =
1048"close()\n"
1049"Shut down this profiler and close the log files, even if its active.";
Fred Drake8c081a12001-10-12 20:57:55 +00001050
1051static PyObject *
1052profiler_close(ProfilerObject *self, PyObject *args)
1053{
1054 PyObject *result = NULL;
1055
1056 if (PyArg_ParseTuple(args, ":close")) {
1057 do_stop(self);
1058 if (self->logfp != NULL) {
1059 fclose(self->logfp);
1060 self->logfp = NULL;
1061 }
1062 Py_INCREF(Py_None);
1063 result = Py_None;
1064 }
1065 return result;
1066}
1067
Tim Petersfeab23f2001-10-13 00:11:10 +00001068static char runcall__doc__[] =
1069"runcall(callable[, args[, kw]]) -> callable()\n"
1070"Profile a specific function call, returning the result of that call.";
Fred Drake8c081a12001-10-12 20:57:55 +00001071
1072static PyObject *
1073profiler_runcall(ProfilerObject *self, PyObject *args)
1074{
1075 PyObject *result = NULL;
1076 PyObject *callargs = NULL;
1077 PyObject *callkw = NULL;
1078 PyObject *callable;
1079
1080 if (PyArg_ParseTuple(args, "O|OO:runcall",
1081 &callable, &callargs, &callkw)) {
1082 if (is_available(self)) {
1083 do_start(self);
1084 result = PyEval_CallObjectWithKeywords(callable, callargs, callkw);
1085 do_stop(self);
1086 }
1087 }
1088 return result;
1089}
1090
Tim Petersfeab23f2001-10-13 00:11:10 +00001091static char runcode__doc__[] =
1092"runcode(code, globals[, locals])\n"
1093"Execute a code object while collecting profile data. If locals is\n"
1094"omitted, globals is used for the locals as well.";
Fred Drake8c081a12001-10-12 20:57:55 +00001095
1096static PyObject *
1097profiler_runcode(ProfilerObject *self, PyObject *args)
1098{
1099 PyObject *result = NULL;
1100 PyCodeObject *code;
1101 PyObject *globals;
1102 PyObject *locals = NULL;
1103
1104 if (PyArg_ParseTuple(args, "O!O!|O:runcode",
1105 &PyCode_Type, &code,
1106 &PyDict_Type, &globals,
1107 &locals)) {
1108 if (is_available(self)) {
1109 if (locals == NULL || locals == Py_None)
1110 locals = globals;
1111 else if (!PyDict_Check(locals)) {
1112 PyErr_SetString(PyExc_TypeError,
1113 "locals must be a dictionary or None");
1114 return NULL;
1115 }
1116 do_start(self);
1117 result = PyEval_EvalCode(code, globals, locals);
1118 do_stop(self);
1119#if 0
1120 if (!PyErr_Occurred()) {
1121 result = Py_None;
1122 Py_INCREF(result);
1123 }
1124#endif
1125 }
1126 }
1127 return result;
1128}
1129
Tim Petersfeab23f2001-10-13 00:11:10 +00001130static char start__doc__[] =
1131"start()\n"
1132"Install this profiler for the current thread.";
Fred Drake8c081a12001-10-12 20:57:55 +00001133
1134static PyObject *
1135profiler_start(ProfilerObject *self, PyObject *args)
1136{
1137 PyObject *result = NULL;
1138
1139 if (PyArg_ParseTuple(args, ":start")) {
Fred Drake2c146bf2002-02-08 21:27:50 +00001140 if (is_available(self)) {
Fred Drake8c081a12001-10-12 20:57:55 +00001141 do_start(self);
Fred Drake2c146bf2002-02-08 21:27:50 +00001142 result = Py_None;
1143 Py_INCREF(result);
1144 }
Fred Drake8c081a12001-10-12 20:57:55 +00001145 }
1146 return result;
1147}
1148
Tim Petersfeab23f2001-10-13 00:11:10 +00001149static char stop__doc__[] =
1150"stop()\n"
1151"Remove this profiler from the current thread.";
Fred Drake8c081a12001-10-12 20:57:55 +00001152
1153static PyObject *
1154profiler_stop(ProfilerObject *self, PyObject *args)
1155{
1156 PyObject *result = NULL;
1157
1158 if (PyArg_ParseTuple(args, ":stop")) {
1159 if (!self->active)
1160 PyErr_SetString(ProfilerError, "profiler not active");
Fred Drake2c146bf2002-02-08 21:27:50 +00001161 else {
Fred Drake8c081a12001-10-12 20:57:55 +00001162 do_stop(self);
Fred Drake2c146bf2002-02-08 21:27:50 +00001163 result = Py_None;
1164 Py_INCREF(result);
1165 }
Fred Drake8c081a12001-10-12 20:57:55 +00001166 }
1167 return result;
1168}
1169
1170
1171/* Python API support. */
1172
1173static void
1174profiler_dealloc(ProfilerObject *self)
1175{
1176 do_stop(self);
1177 if (self->logfp != NULL)
1178 fclose(self->logfp);
1179 Py_XDECREF(self->filemap);
1180 Py_XDECREF(self->logfilename);
1181 PyObject_Del((PyObject *)self);
1182}
1183
1184/* Always use METH_VARARGS even though some of these could be METH_NOARGS;
1185 * this allows us to maintain compatibility with Python versions < 2.2
1186 * more easily, requiring only the changes to the dispatcher to be made.
1187 */
1188static PyMethodDef profiler_methods[] = {
Fred Drake4c2e1af2001-10-29 20:45:57 +00001189 {"addinfo", (PyCFunction)profiler_addinfo, METH_VARARGS, addinfo__doc__},
Fred Drake8c081a12001-10-12 20:57:55 +00001190 {"close", (PyCFunction)profiler_close, METH_VARARGS, close__doc__},
1191 {"runcall", (PyCFunction)profiler_runcall, METH_VARARGS, runcall__doc__},
1192 {"runcode", (PyCFunction)profiler_runcode, METH_VARARGS, runcode__doc__},
1193 {"start", (PyCFunction)profiler_start, METH_VARARGS, start__doc__},
1194 {"stop", (PyCFunction)profiler_stop, METH_VARARGS, stop__doc__},
1195 {NULL, NULL}
1196};
1197
1198/* Use a table even though there's only one "simple" member; this allows
1199 * __members__ and therefore dir() to work.
1200 */
1201static struct memberlist profiler_members[] = {
Fred Drake30d1c752001-10-15 22:11:02 +00001202 {"closed", T_INT, -1, READONLY},
1203 {"frametimings", T_LONG, offsetof(ProfilerObject, linetimings), READONLY},
1204 {"lineevents", T_LONG, offsetof(ProfilerObject, lineevents), READONLY},
1205 {"linetimings", T_LONG, offsetof(ProfilerObject, linetimings), READONLY},
Fred Drake8c081a12001-10-12 20:57:55 +00001206 {NULL}
1207};
1208
1209static PyObject *
1210profiler_getattr(ProfilerObject *self, char *name)
1211{
1212 PyObject *result;
1213 if (strcmp(name, "closed") == 0) {
1214 result = (self->logfp == NULL) ? Py_True : Py_False;
1215 Py_INCREF(result);
1216 }
1217 else {
1218 result = PyMember_Get((char *)self, profiler_members, name);
1219 if (result == NULL) {
1220 PyErr_Clear();
1221 result = Py_FindMethod(profiler_methods, (PyObject *)self, name);
1222 }
1223 }
1224 return result;
1225}
1226
1227
Tim Petersfeab23f2001-10-13 00:11:10 +00001228static char profiler_object__doc__[] =
1229"High-performance profiler object.\n"
1230"\n"
1231"Methods:\n"
1232"\n"
Fred Drake30d1c752001-10-15 22:11:02 +00001233"close(): Stop the profiler and close the log files.\n"
1234"runcall(): Run a single function call with profiling enabled.\n"
1235"runcode(): Execute a code object with profiling enabled.\n"
1236"start(): Install the profiler and return.\n"
1237"stop(): Remove the profiler.\n"
Tim Petersfeab23f2001-10-13 00:11:10 +00001238"\n"
1239"Attributes (read-only):\n"
1240"\n"
Fred Drake30d1c752001-10-15 22:11:02 +00001241"closed: True if the profiler has already been closed.\n"
1242"frametimings: True if ENTER/EXIT events collect timing information.\n"
1243"lineevents: True if SET_LINENO events are reported to the profiler.\n"
1244"linetimings: True if SET_LINENO events collect timing information.";
Fred Drake8c081a12001-10-12 20:57:55 +00001245
1246static PyTypeObject ProfilerType = {
1247 PyObject_HEAD_INIT(NULL)
1248 0, /* ob_size */
Fred Drake4c2e1af2001-10-29 20:45:57 +00001249 "_hotshot.ProfilerType", /* tp_name */
Fred Drake8c081a12001-10-12 20:57:55 +00001250 (int) sizeof(ProfilerObject), /* tp_basicsize */
1251 0, /* tp_itemsize */
1252 (destructor)profiler_dealloc, /* tp_dealloc */
1253 0, /* tp_print */
1254 (getattrfunc)profiler_getattr, /* tp_getattr */
1255 0, /* tp_setattr */
1256 0, /* tp_compare */
1257 0, /* tp_repr */
1258 0, /* tp_as_number */
1259 0, /* tp_as_sequence */
1260 0, /* tp_as_mapping */
1261 0, /* tp_hash */
1262 0, /* tp_call */
1263 0, /* tp_str */
1264 0, /* tp_getattro */
1265 0, /* tp_setattro */
1266 0, /* tp_as_buffer */
Fred Drake4c2e1af2001-10-29 20:45:57 +00001267 Py_TPFLAGS_DEFAULT, /* tp_flags */
Fred Drake8c081a12001-10-12 20:57:55 +00001268 profiler_object__doc__, /* tp_doc */
1269};
1270
1271
1272static PyMethodDef logreader_methods[] = {
1273 {"close", (PyCFunction)logreader_close, METH_VARARGS,
1274 logreader_close__doc__},
1275 {"next", (PyCFunction)logreader_next, METH_VARARGS,
1276 next__doc__},
1277 {NULL, NULL}
1278};
1279
1280static PyObject *
Fred Drake4c2e1af2001-10-29 20:45:57 +00001281logreader_getattr(LogReaderObject *self, char *name)
Fred Drake8c081a12001-10-12 20:57:55 +00001282{
Fred Drake4c2e1af2001-10-29 20:45:57 +00001283 if (strcmp(name, "info") == 0) {
1284 Py_INCREF(self->info);
1285 return self->info;
1286 }
Fred Drake8c081a12001-10-12 20:57:55 +00001287 return Py_FindMethod(logreader_methods, (PyObject *)self, name);
1288}
1289
1290
1291static char logreader__doc__[] = "\
1292logreader(filename) --> log-iterator\n\
1293Create a log-reader for the timing information file.";
1294
1295static PySequenceMethods logreader_as_sequence = {
1296 0, /* sq_length */
1297 0, /* sq_concat */
1298 0, /* sq_repeat */
1299 (intargfunc)logreader_sq_item, /* sq_item */
1300 0, /* sq_slice */
1301 0, /* sq_ass_item */
1302 0, /* sq_ass_slice */
1303 0, /* sq_contains */
1304 0, /* sq_inplace_concat */
1305 0, /* sq_inplace_repeat */
1306};
1307
1308static PyTypeObject LogReaderType = {
1309 PyObject_HEAD_INIT(NULL)
1310 0, /* ob_size */
Fred Drake4c2e1af2001-10-29 20:45:57 +00001311 "_hotshot.LogReaderType", /* tp_name */
Fred Drake8c081a12001-10-12 20:57:55 +00001312 (int) sizeof(LogReaderObject), /* tp_basicsize */
1313 0, /* tp_itemsize */
1314 (destructor)logreader_dealloc, /* tp_dealloc */
1315 0, /* tp_print */
1316 (getattrfunc)logreader_getattr, /* tp_getattr */
1317 0, /* tp_setattr */
1318 0, /* tp_compare */
1319 0, /* tp_repr */
1320 0, /* tp_as_number */
1321 &logreader_as_sequence, /* tp_as_sequence */
1322 0, /* tp_as_mapping */
1323 0, /* tp_hash */
1324 0, /* tp_call */
1325 0, /* tp_str */
1326 0, /* tp_getattro */
1327 0, /* tp_setattro */
1328 0, /* tp_as_buffer */
Fred Drake4c2e1af2001-10-29 20:45:57 +00001329 Py_TPFLAGS_DEFAULT, /* tp_flags */
Fred Drake8c081a12001-10-12 20:57:55 +00001330 logreader__doc__, /* tp_doc */
1331#if Py_TPFLAGS_HAVE_ITER
1332 0, /* tp_traverse */
1333 0, /* tp_clear */
1334 0, /* tp_richcompare */
1335 0, /* tp_weaklistoffset */
1336 (getiterfunc)logreader_tp_iter, /* tp_iter */
1337 (iternextfunc)logreader_tp_iternext,/* tp_iternext */
1338#endif
1339};
1340
1341static PyObject *
1342hotshot_logreader(PyObject *unused, PyObject *args)
1343{
1344 LogReaderObject *self = NULL;
1345 char *filename;
Neil Schemenauer8b6b4912002-05-29 18:19:14 +00001346 int c;
1347 int err = 0;
Fred Drake8c081a12001-10-12 20:57:55 +00001348
1349 if (PyArg_ParseTuple(args, "s:logreader", &filename)) {
1350 self = PyObject_New(LogReaderObject, &LogReaderType);
1351 if (self != NULL) {
Fred Drake30d1c752001-10-15 22:11:02 +00001352 self->frametimings = 1;
Fred Drake8c081a12001-10-12 20:57:55 +00001353 self->linetimings = 0;
Fred Drake4c2e1af2001-10-29 20:45:57 +00001354 self->info = NULL;
Fred Drake8c081a12001-10-12 20:57:55 +00001355 self->logfp = fopen(filename, "rb");
1356 if (self->logfp == NULL) {
1357 PyErr_SetFromErrnoWithFilename(PyExc_IOError, filename);
1358 Py_DECREF(self);
1359 self = NULL;
Fred Drake4c2e1af2001-10-29 20:45:57 +00001360 goto finally;
1361 }
1362 self->info = PyDict_New();
1363 if (self->info == NULL) {
1364 Py_DECREF(self);
1365 goto finally;
1366 }
Neil Schemenauer8b6b4912002-05-29 18:19:14 +00001367 /* read initial info */
1368 for (;;) {
1369 if ((c = fgetc(self->logfp)) == EOF) {
1370 eof_error();
1371 break;
1372 }
1373 if (c != WHAT_ADD_INFO) {
1374 ungetc(c, self->logfp);
1375 break;
1376 }
1377 err = unpack_add_info(self);
Fred Drake4c2e1af2001-10-29 20:45:57 +00001378 if (err) {
1379 if (err == ERR_EOF)
1380 eof_error();
1381 else
1382 PyErr_SetString(PyExc_RuntimeError,
1383 "unexpected error");
1384 break;
1385 }
Fred Drake8c081a12001-10-12 20:57:55 +00001386 }
1387 }
1388 }
Fred Drake4c2e1af2001-10-29 20:45:57 +00001389 finally:
Fred Drake8c081a12001-10-12 20:57:55 +00001390 return (PyObject *) self;
1391}
1392
1393
1394/* Return a Python string that represents the version number without the
1395 * extra cruft added by revision control, even if the right options were
1396 * given to the "cvs export" command to make it not include the extra
1397 * cruft.
1398 */
1399static char *
1400get_version_string(void)
1401{
1402 static char *rcsid = "$Revision$";
1403 char *rev = rcsid;
1404 char *buffer;
1405 int i = 0;
1406
Neal Norwitz3afb2d22002-03-20 21:32:07 +00001407 while (*rev && !isdigit((int)*rev))
Fred Drake8c081a12001-10-12 20:57:55 +00001408 ++rev;
1409 while (rev[i] != ' ' && rev[i] != '\0')
1410 ++i;
1411 buffer = malloc(i + 1);
1412 if (buffer != NULL) {
1413 memmove(buffer, rev, i);
1414 buffer[i] = '\0';
1415 }
1416 return buffer;
1417}
1418
1419/* Write out a RFC 822-style header with various useful bits of
1420 * information to make the output easier to manage.
1421 */
1422static int
1423write_header(ProfilerObject *self)
1424{
1425 char *buffer;
1426 char cwdbuffer[PATH_MAX];
1427 PyObject *temp;
1428 int i, len;
1429
1430 buffer = get_version_string();
1431 if (buffer == NULL) {
1432 PyErr_NoMemory();
1433 return -1;
1434 }
Fred Drake4c2e1af2001-10-29 20:45:57 +00001435 pack_add_info(self, "hotshot-version", buffer);
1436 pack_add_info(self, "requested-frame-timings",
1437 (self->frametimings ? "yes" : "no"));
1438 pack_add_info(self, "requested-line-events",
Fred Drake8c081a12001-10-12 20:57:55 +00001439 (self->lineevents ? "yes" : "no"));
Fred Drake4c2e1af2001-10-29 20:45:57 +00001440 pack_add_info(self, "requested-line-timings",
1441 (self->linetimings ? "yes" : "no"));
1442 pack_add_info(self, "platform", Py_GetPlatform());
1443 pack_add_info(self, "executable", Py_GetProgramFullPath());
Fred Drakef12a68c2001-11-09 15:59:36 +00001444 free(buffer);
Fred Drake8c081a12001-10-12 20:57:55 +00001445 buffer = (char *) Py_GetVersion();
1446 if (buffer == NULL)
1447 PyErr_Clear();
1448 else
Fred Drake4c2e1af2001-10-29 20:45:57 +00001449 pack_add_info(self, "executable-version", buffer);
Fred Drake8c081a12001-10-12 20:57:55 +00001450
1451#ifdef MS_WIN32
Tim Peters885d4572001-11-28 20:27:42 +00001452 PyOS_snprintf(cwdbuffer, sizeof(cwdbuffer), "%I64d", frequency.QuadPart);
Fred Drake4c2e1af2001-10-29 20:45:57 +00001453 pack_add_info(self, "reported-performance-frequency", cwdbuffer);
Fred Drake8c081a12001-10-12 20:57:55 +00001454#else
Tim Peters885d4572001-11-28 20:27:42 +00001455 PyOS_snprintf(cwdbuffer, sizeof(cwdbuffer), "%lu", rusage_diff);
Fred Drake4c2e1af2001-10-29 20:45:57 +00001456 pack_add_info(self, "observed-interval-getrusage", cwdbuffer);
Tim Peters885d4572001-11-28 20:27:42 +00001457 PyOS_snprintf(cwdbuffer, sizeof(cwdbuffer), "%lu", timeofday_diff);
Fred Drake4c2e1af2001-10-29 20:45:57 +00001458 pack_add_info(self, "observed-interval-gettimeofday", cwdbuffer);
Fred Drake8c081a12001-10-12 20:57:55 +00001459#endif
Fred Drake8c081a12001-10-12 20:57:55 +00001460
Fred Drake4c2e1af2001-10-29 20:45:57 +00001461 pack_add_info(self, "current-directory",
Fred Drake8c081a12001-10-12 20:57:55 +00001462 getcwd(cwdbuffer, sizeof cwdbuffer));
1463
1464 temp = PySys_GetObject("path");
1465 len = PyList_GET_SIZE(temp);
1466 for (i = 0; i < len; ++i) {
1467 PyObject *item = PyList_GET_ITEM(temp, i);
1468 buffer = PyString_AsString(item);
1469 if (buffer == NULL)
1470 return -1;
Fred Drake4c2e1af2001-10-29 20:45:57 +00001471 pack_add_info(self, "sys-path-entry", buffer);
Fred Drake8c081a12001-10-12 20:57:55 +00001472 }
Fred Drake4c2e1af2001-10-29 20:45:57 +00001473 pack_frame_times(self);
1474 pack_line_times(self);
1475
Fred Drake8c081a12001-10-12 20:57:55 +00001476 return 0;
1477}
1478
1479static char profiler__doc__[] = "\
1480profiler(logfilename[, lineevents[, linetimes]]) -> profiler\n\
1481Create a new profiler object.";
1482
1483static PyObject *
1484hotshot_profiler(PyObject *unused, PyObject *args)
1485{
1486 char *logfilename;
1487 ProfilerObject *self = NULL;
1488 int lineevents = 0;
1489 int linetimings = 1;
1490
1491 if (PyArg_ParseTuple(args, "s|ii:profiler", &logfilename,
1492 &lineevents, &linetimings)) {
1493 self = PyObject_New(ProfilerObject, &ProfilerType);
1494 if (self == NULL)
1495 return NULL;
Fred Drake30d1c752001-10-15 22:11:02 +00001496 self->frametimings = 1;
Fred Drake8c081a12001-10-12 20:57:55 +00001497 self->lineevents = lineevents ? 1 : 0;
1498 self->linetimings = (lineevents && linetimings) ? 1 : 0;
1499 self->index = 0;
1500 self->active = 0;
1501 self->next_fileno = 0;
Tim Peters1566a172001-10-12 22:08:39 +00001502 self->logfp = NULL;
Fred Drake8c081a12001-10-12 20:57:55 +00001503 self->logfilename = PyTuple_GET_ITEM(args, 0);
1504 Py_INCREF(self->logfilename);
1505 self->filemap = PyDict_New();
1506 if (self->filemap == NULL) {
1507 Py_DECREF(self);
1508 return NULL;
1509 }
1510 self->logfp = fopen(logfilename, "wb");
1511 if (self->logfp == NULL) {
1512 Py_DECREF(self);
1513 PyErr_SetFromErrnoWithFilename(PyExc_IOError, logfilename);
1514 return NULL;
1515 }
1516 if (timeofday_diff == 0) {
1517 /* Run this several times since sometimes the first
1518 * doesn't give the lowest values, and we're really trying
1519 * to determine the lowest.
1520 */
1521 calibrate();
1522 calibrate();
1523 calibrate();
1524 }
1525 if (write_header(self))
1526 /* some error occurred, exception has been set */
1527 self = NULL;
1528 }
1529 return (PyObject *) self;
1530}
1531
Fred Drake30d1c752001-10-15 22:11:02 +00001532static char coverage__doc__[] = "\
1533coverage(logfilename) -> profiler\n\
1534Returns a profiler that doesn't collect any timing information, which is\n\
1535useful in building a coverage analysis tool.";
1536
1537static PyObject *
1538hotshot_coverage(PyObject *unused, PyObject *args)
1539{
1540 char *logfilename;
1541 PyObject *result = NULL;
1542
1543 if (PyArg_ParseTuple(args, "s:coverage", &logfilename)) {
1544 result = hotshot_profiler(unused, args);
1545 if (result != NULL) {
1546 ProfilerObject *self = (ProfilerObject *) result;
1547 self->frametimings = 0;
1548 self->linetimings = 0;
1549 self->lineevents = 1;
1550 }
1551 }
1552 return result;
1553}
1554
Fred Drake8c081a12001-10-12 20:57:55 +00001555static char resolution__doc__[] =
1556#ifdef MS_WIN32
Tim Petersfeab23f2001-10-13 00:11:10 +00001557"resolution() -> (performance-counter-ticks, update-frequency)\n"
1558"Return the resolution of the timer provided by the QueryPerformanceCounter()\n"
1559"function. The first value is the smallest observed change, and the second\n"
1560"is the result of QueryPerformanceFrequency().";
Fred Drake8c081a12001-10-12 20:57:55 +00001561#else
Tim Petersfeab23f2001-10-13 00:11:10 +00001562"resolution() -> (gettimeofday-usecs, getrusage-usecs)\n"
1563"Return the resolution of the timers provided by the gettimeofday() and\n"
1564"getrusage() system calls, or -1 if the call is not supported.";
Fred Drake8c081a12001-10-12 20:57:55 +00001565#endif
1566
1567static PyObject *
1568hotshot_resolution(PyObject *unused, PyObject *args)
1569{
1570 PyObject *result = NULL;
1571
1572 if (PyArg_ParseTuple(args, ":resolution")) {
1573 if (timeofday_diff == 0) {
1574 calibrate();
1575 calibrate();
1576 calibrate();
1577 }
1578#ifdef MS_WIN32
1579 result = Py_BuildValue("ii", timeofday_diff, frequency.LowPart);
1580#else
1581 result = Py_BuildValue("ii", timeofday_diff, rusage_diff);
1582#endif
1583 }
1584 return result;
1585}
1586
1587
1588static PyMethodDef functions[] = {
Fred Drake30d1c752001-10-15 22:11:02 +00001589 {"coverage", hotshot_coverage, METH_VARARGS, coverage__doc__},
Fred Drake8c081a12001-10-12 20:57:55 +00001590 {"profiler", hotshot_profiler, METH_VARARGS, profiler__doc__},
1591 {"logreader", hotshot_logreader, METH_VARARGS, logreader__doc__},
1592 {"resolution", hotshot_resolution, METH_VARARGS, resolution__doc__},
1593 {NULL, NULL}
1594};
1595
1596
1597void
1598init_hotshot(void)
1599{
1600 PyObject *module;
1601
1602 LogReaderType.ob_type = &PyType_Type;
1603 ProfilerType.ob_type = &PyType_Type;
1604 module = Py_InitModule("_hotshot", functions);
1605 if (module != NULL) {
1606 char *s = get_version_string();
1607
1608 PyModule_AddStringConstant(module, "__version__", s);
1609 free(s);
1610 Py_INCREF(&LogReaderType);
1611 PyModule_AddObject(module, "LogReaderType",
1612 (PyObject *)&LogReaderType);
1613 Py_INCREF(&ProfilerType);
1614 PyModule_AddObject(module, "ProfilerType",
1615 (PyObject *)&ProfilerType);
1616
1617 if (ProfilerError == NULL)
1618 ProfilerError = PyErr_NewException("hotshot.ProfilerError",
1619 NULL, NULL);
1620 if (ProfilerError != NULL) {
1621 Py_INCREF(ProfilerError);
1622 PyModule_AddObject(module, "ProfilerError", ProfilerError);
1623 }
1624 PyModule_AddIntConstant(module, "WHAT_ENTER", WHAT_ENTER);
1625 PyModule_AddIntConstant(module, "WHAT_EXIT", WHAT_EXIT);
1626 PyModule_AddIntConstant(module, "WHAT_LINENO", WHAT_LINENO);
1627 PyModule_AddIntConstant(module, "WHAT_OTHER", WHAT_OTHER);
1628 PyModule_AddIntConstant(module, "WHAT_ADD_INFO", WHAT_ADD_INFO);
1629 PyModule_AddIntConstant(module, "WHAT_DEFINE_FILE", WHAT_DEFINE_FILE);
Fred Drake30d1c752001-10-15 22:11:02 +00001630 PyModule_AddIntConstant(module, "WHAT_DEFINE_FUNC", WHAT_DEFINE_FUNC);
Fred Drake8c081a12001-10-12 20:57:55 +00001631 PyModule_AddIntConstant(module, "WHAT_LINE_TIMES", WHAT_LINE_TIMES);
1632 }
1633}