blob: ebaf37c3578eac885a2a6af9691e8eaa67eef6c1 [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>
17#include <largeint.h>
Tim Peters1566a172001-10-12 22:08:39 +000018#include <direct.h> /* for getcwd() */
Tim Peters7d99ff22001-10-13 07:37:52 +000019typedef __int64 hs_time;
20#define GETTIMEOFDAY(P_HS_TIME) \
21 { LARGE_INTEGER _temp; \
22 QueryPerformanceCounter(&_temp); \
23 *(P_HS_TIME) = _temp.QuadPart; }
24
Tim Petersfeab23f2001-10-13 00:11:10 +000025
Fred Drake8c081a12001-10-12 20:57:55 +000026#else
27#ifndef HAVE_GETTIMEOFDAY
28#error "This module requires gettimeofday() on non-Windows platforms!"
29#endif
Jack Jansen963659a2001-10-23 22:26:16 +000030#ifdef macintosh
31#include <sys/time.h>
32#else
Fred Drake8c081a12001-10-12 20:57:55 +000033#include <sys/resource.h>
34#include <sys/times.h>
Jack Jansen963659a2001-10-23 22:26:16 +000035#endif
Fred Drake8c081a12001-10-12 20:57:55 +000036typedef struct timeval hs_time;
37#endif
38
39#if !defined(__cplusplus) && !defined(inline)
40#ifdef __GNUC__
41#define inline __inline
42#endif
43#endif
44
45#ifndef inline
46#define inline
47#endif
48
49#define BUFFERSIZE 10240
50
Jack Jansen963659a2001-10-23 22:26:16 +000051#ifdef macintosh
52#define PATH_MAX 254
53#endif
54
Tim Peters1566a172001-10-12 22:08:39 +000055#ifndef PATH_MAX
56# ifdef MAX_PATH
57# define PATH_MAX MAX_PATH
58# else
59# error "Need a defn. for PATH_MAX in _hotshot.c"
60# endif
61#endif
62
Fred Drake8c081a12001-10-12 20:57:55 +000063typedef struct {
64 PyObject_HEAD
65 PyObject *filemap;
66 PyObject *logfilename;
67 int index;
68 unsigned char buffer[BUFFERSIZE];
69 FILE *logfp;
70 int lineevents;
71 int linetimings;
Fred Drake30d1c752001-10-15 22:11:02 +000072 int frametimings;
Fred Drake8c081a12001-10-12 20:57:55 +000073 /* size_t filled; */
74 int active;
75 int next_fileno;
Fred Drake8c081a12001-10-12 20:57:55 +000076 hs_time prev_timeofday;
77} ProfilerObject;
78
79typedef struct {
80 PyObject_HEAD
Fred Drake4c2e1af2001-10-29 20:45:57 +000081 PyObject *info;
Fred Drake8c081a12001-10-12 20:57:55 +000082 FILE *logfp;
83 int filled;
84 int index;
85 int linetimings;
Fred Drake30d1c752001-10-15 22:11:02 +000086 int frametimings;
Fred Drake8c081a12001-10-12 20:57:55 +000087 unsigned char buffer[BUFFERSIZE];
88} 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{
272 int accum = 0;
273 int bits = 0;
274 int index = self->index;
275 int cont;
276
277 do {
278 if (index >= self->filled)
279 return ERR_EOF;
280 /* read byte */
281 accum |= ((self->buffer[index] & 0x7F) >> discard) << bits;
282 bits += (7 - discard);
283 cont = self->buffer[index] & 0x80;
284 /* move to next */
285 discard = 0;
286 index++;
287 } while (cont);
288
289 /* save state */
290 self->index = index;
291 *pvalue = accum;
292
293 return 0;
294}
295
296/* Unpack a string, which is encoded as a packed integer giving the
297 * length of the string, followed by the string data.
298 */
299static int
300unpack_string(LogReaderObject *self, PyObject **pvalue)
301{
302 int len;
303 int oldindex = self->index;
304 int err = unpack_packed_int(self, &len, 0);
305
306 if (!err) {
307 /* need at least len bytes in buffer */
308 if (len > (self->filled - self->index)) {
309 self->index = oldindex;
310 err = ERR_EOF;
311 }
312 else {
Jack Jansen963659a2001-10-23 22:26:16 +0000313 *pvalue = PyString_FromStringAndSize((char *)self->buffer + self->index,
Fred Drake8c081a12001-10-12 20:57:55 +0000314 len);
315 if (*pvalue == NULL) {
316 self->index = oldindex;
317 err = ERR_EXCEPTION;
318 }
319 else
320 self->index += len;
321 }
322 }
323 return err;
324}
325
326
Fred Drake4c2e1af2001-10-29 20:45:57 +0000327static int
328unpack_add_info(LogReaderObject *self, int skip_opcode)
329{
330 PyObject *key;
331 PyObject *value = NULL;
332 int err;
333
334 if (skip_opcode) {
335 if (self->buffer[self->index] != WHAT_ADD_INFO)
336 return ERR_BAD_RECTYPE;
337 self->index++;
338 }
339 err = unpack_string(self, &key);
340 if (!err) {
341 err = unpack_string(self, &value);
342 if (err)
343 Py_DECREF(key);
344 else {
345 PyObject *list = PyDict_GetItem(self->info, key);
346 if (list == NULL) {
347 list = PyList_New(0);
348 if (list == NULL) {
349 err = ERR_EXCEPTION;
350 goto finally;
351 }
352 if (PyDict_SetItem(self->info, key, list)) {
353 err = ERR_EXCEPTION;
354 goto finally;
355 }
356 }
357 if (PyList_Append(list, value))
358 err = ERR_EXCEPTION;
359 }
360 }
361 finally:
362 Py_XDECREF(key);
363 Py_XDECREF(value);
364 return err;
365}
366
367
368static void
369logreader_refill(LogReaderObject *self)
370{
371 int needed;
372 size_t res;
373
374 if (self->index) {
375 memmove(self->buffer, &self->buffer[self->index],
376 self->filled - self->index);
377 self->filled = self->filled - self->index;
378 self->index = 0;
379 }
380 needed = BUFFERSIZE - self->filled;
381 if (needed > 0) {
382 res = fread(&self->buffer[self->filled], 1, needed, self->logfp);
383 self->filled += res;
384 }
385}
386
387static void
388eof_error(void)
389{
390 PyErr_SetString(PyExc_EOFError,
391 "end of file with incomplete profile record");
392}
393
Fred Drake8c081a12001-10-12 20:57:55 +0000394static PyObject *
395logreader_tp_iternext(LogReaderObject *self)
396{
397 int what, oldindex;
398 int err = ERR_NONE;
399 int lineno = -1;
400 int fileno = -1;
401 int tdelta = -1;
402 PyObject *s1 = NULL, *s2 = NULL;
403 PyObject *result = NULL;
404#if 0
405 unsigned char b0, b1;
406#endif
407
408 if (self->logfp == NULL) {
409 PyErr_SetString(ProfilerError,
410 "cannot iterate over closed LogReader object");
411 return NULL;
412 }
413 restart:
Fred Drake4c2e1af2001-10-29 20:45:57 +0000414 if ((self->filled - self->index) < MAXEVENTSIZE)
415 logreader_refill(self);
416
Fred Drake8c081a12001-10-12 20:57:55 +0000417 /* end of input */
418 if (self->filled == 0)
419 return NULL;
420
421 oldindex = self->index;
422
423 /* decode the record type */
424 what = self->buffer[self->index] & WHAT_OTHER;
425 if (what == WHAT_OTHER) {
426 what = self->buffer[self->index];
427 self->index++;
428 }
429 switch (what) {
430 case WHAT_ENTER:
431 err = unpack_packed_int(self, &fileno, 2);
432 if (!err) {
Fred Drake30d1c752001-10-15 22:11:02 +0000433 err = unpack_packed_int(self, &lineno, 0);
434 if (self->frametimings && !err)
435 err = unpack_packed_int(self, &tdelta, 0);
Fred Drake8c081a12001-10-12 20:57:55 +0000436 }
437 break;
438 case WHAT_EXIT:
439 err = unpack_packed_int(self, &tdelta, 2);
440 break;
441 case WHAT_LINENO:
442 err = unpack_packed_int(self, &lineno, 2);
443 if (self->linetimings && !err)
444 err = unpack_packed_int(self, &tdelta, 0);
445 break;
446 case WHAT_ADD_INFO:
Fred Drake4c2e1af2001-10-29 20:45:57 +0000447 err = unpack_add_info(self, 0);
Fred Drake8c081a12001-10-12 20:57:55 +0000448 break;
449 case WHAT_DEFINE_FILE:
450 err = unpack_packed_int(self, &fileno, 0);
451 if (!err) {
452 err = unpack_string(self, &s1);
453 if (!err) {
454 Py_INCREF(Py_None);
455 s2 = Py_None;
456 }
457 }
458 break;
Fred Drake30d1c752001-10-15 22:11:02 +0000459 case WHAT_DEFINE_FUNC:
460 err = unpack_packed_int(self, &fileno, 0);
461 if (!err) {
462 err = unpack_packed_int(self, &lineno, 0);
463 if (!err)
464 err = unpack_string(self, &s1);
465 }
466 break;
Fred Drake8c081a12001-10-12 20:57:55 +0000467 case WHAT_LINE_TIMES:
468 if (self->index >= self->filled)
469 err = ERR_EOF;
470 else {
471 self->linetimings = self->buffer[self->index] ? 1 : 0;
472 self->index++;
473 goto restart;
474 }
Fred Drake4c2e1af2001-10-29 20:45:57 +0000475 break;
Fred Drake30d1c752001-10-15 22:11:02 +0000476 case WHAT_FRAME_TIMES:
477 if (self->index >= self->filled)
478 err = ERR_EOF;
479 else {
480 self->frametimings = self->buffer[self->index] ? 1 : 0;
481 self->index++;
482 goto restart;
483 }
Fred Drake4c2e1af2001-10-29 20:45:57 +0000484 break;
Fred Drake8c081a12001-10-12 20:57:55 +0000485 default:
Fred Drake4c2e1af2001-10-29 20:45:57 +0000486 err = ERR_BAD_RECTYPE;
Fred Drake8c081a12001-10-12 20:57:55 +0000487 }
488 if (err == ERR_EOF && oldindex != 0) {
489 /* It looks like we ran out of data before we had it all; this
490 * could easily happen with large packed integers or string
491 * data. Try forcing the buffer to be re-filled before failing.
492 */
493 err = ERR_NONE;
Fred Drake4c2e1af2001-10-29 20:45:57 +0000494 logreader_refill(self);
Fred Drake8c081a12001-10-12 20:57:55 +0000495 }
Fred Drake4c2e1af2001-10-29 20:45:57 +0000496 if (err == ERR_BAD_RECTYPE) {
497 PyErr_SetString(PyExc_ValueError,
498 "unknown record type in log file");
499 }
500 else if (err == ERR_EOF) {
Fred Drake8c081a12001-10-12 20:57:55 +0000501 /* Could not avoid end-of-buffer error. */
Fred Drake4c2e1af2001-10-29 20:45:57 +0000502 eof_error();
Fred Drake8c081a12001-10-12 20:57:55 +0000503 }
504 else if (!err) {
505 result = PyTuple_New(4);
506 PyTuple_SET_ITEM(result, 0, PyInt_FromLong(what));
507 PyTuple_SET_ITEM(result, 2, PyInt_FromLong(fileno));
Fred Drake30d1c752001-10-15 22:11:02 +0000508 if (s1 == NULL)
Fred Drake8c081a12001-10-12 20:57:55 +0000509 PyTuple_SET_ITEM(result, 1, PyInt_FromLong(tdelta));
Fred Drake30d1c752001-10-15 22:11:02 +0000510 else
Fred Drake8c081a12001-10-12 20:57:55 +0000511 PyTuple_SET_ITEM(result, 1, s1);
Fred Drake30d1c752001-10-15 22:11:02 +0000512 if (s2 == NULL)
513 PyTuple_SET_ITEM(result, 3, PyInt_FromLong(lineno));
514 else
Fred Drake8c081a12001-10-12 20:57:55 +0000515 PyTuple_SET_ITEM(result, 3, s2);
Fred Drake8c081a12001-10-12 20:57:55 +0000516 }
517 /* The only other case is err == ERR_EXCEPTION, in which case the
518 * exception is already set.
519 */
520#if 0
521 b0 = self->buffer[self->index];
522 b1 = self->buffer[self->index + 1];
523 if (b0 & 1) {
524 /* This is a line-number event. */
525 what = PyTrace_LINE;
526 lineno = ((b0 & ~1) << 7) + b1;
527 self->index += 2;
528 }
529 else {
530 what = (b0 & 0x0E) >> 1;
531 tdelta = ((b0 & 0xF0) << 4) + b1;
532 if (what == PyTrace_CALL) {
533 /* we know there's a 2-byte file ID & 2-byte line number */
534 fileno = ((self->buffer[self->index + 2] << 8)
535 + self->buffer[self->index + 3]);
536 lineno = ((self->buffer[self->index + 4] << 8)
537 + self->buffer[self->index + 5]);
538 self->index += 6;
539 }
540 else
541 self->index += 2;
542 }
543#endif
544 return result;
545}
546
547static void
548logreader_dealloc(LogReaderObject *self)
549{
550 if (self->logfp != NULL) {
551 fclose(self->logfp);
552 self->logfp = NULL;
553 }
554 PyObject_Del(self);
555}
556
557static PyObject *
558logreader_sq_item(LogReaderObject *self, int index)
559{
560 PyObject *result = logreader_tp_iternext(self);
561 if (result == NULL && !PyErr_Occurred()) {
562 PyErr_SetString(PyExc_IndexError, "no more events in log");
563 return NULL;
564 }
565 return result;
566}
567
Tim Petersfeab23f2001-10-13 00:11:10 +0000568static char next__doc__[] =
569"next() -> event-info\n"
570"Return the next event record from the log file.";
Fred Drake8c081a12001-10-12 20:57:55 +0000571
572static PyObject *
573logreader_next(LogReaderObject *self, PyObject *args)
574{
575 PyObject *result = NULL;
576
577 if (PyArg_ParseTuple(args, ":next")) {
578 result = logreader_tp_iternext(self);
579 /* XXX return None if there's nothing left */
580 /* tp_iternext does the right thing, though */
581 if (result == NULL && !PyErr_Occurred()) {
582 result = Py_None;
583 Py_INCREF(result);
584 }
585 }
586 return result;
587}
588
Fred Drake62c1e3c2001-12-04 21:40:53 +0000589static void
590do_stop(ProfilerObject *self);
Fred Drake8c081a12001-10-12 20:57:55 +0000591
592static int
593flush_data(ProfilerObject *self)
594{
595 /* Need to dump data to the log file... */
596 size_t written = fwrite(self->buffer, 1, self->index, self->logfp);
Tim Peters1566a172001-10-12 22:08:39 +0000597 if (written == (size_t)self->index)
Fred Drake8c081a12001-10-12 20:57:55 +0000598 self->index = 0;
599 else {
600 memmove(self->buffer, &self->buffer[written],
601 self->index - written);
602 self->index -= written;
603 if (written == 0) {
604 char *s = PyString_AsString(self->logfilename);
605 PyErr_SetFromErrnoWithFilename(PyExc_IOError, s);
Fred Drake62c1e3c2001-12-04 21:40:53 +0000606 do_stop(self);
Fred Drake8c081a12001-10-12 20:57:55 +0000607 return -1;
608 }
609 }
610 if (written > 0) {
611 if (fflush(self->logfp)) {
612 char *s = PyString_AsString(self->logfilename);
613 PyErr_SetFromErrnoWithFilename(PyExc_IOError, s);
Fred Drake62c1e3c2001-12-04 21:40:53 +0000614 do_stop(self);
Fred Drake8c081a12001-10-12 20:57:55 +0000615 return -1;
616 }
617 }
618 return 0;
619}
620
Fred Drake62c1e3c2001-12-04 21:40:53 +0000621static inline int
Fred Drake8c081a12001-10-12 20:57:55 +0000622pack_packed_int(ProfilerObject *self, int value)
623{
624 unsigned char partial;
625
626 do {
627 partial = value & 0x7F;
628 value >>= 7;
629 if (value)
630 partial |= 0x80;
631 self->buffer[self->index] = partial;
632 self->index++;
633 } while (value);
Fred Drake62c1e3c2001-12-04 21:40:53 +0000634 return 0;
Fred Drake8c081a12001-10-12 20:57:55 +0000635}
636
637/* Encode a modified packed integer, with a subfield of modsize bits
638 * containing the value "subfield". The value of subfield is not
639 * checked to ensure it actually fits in modsize bits.
640 */
Fred Drake62c1e3c2001-12-04 21:40:53 +0000641static inline int
Fred Drake8c081a12001-10-12 20:57:55 +0000642pack_modified_packed_int(ProfilerObject *self, int value,
643 int modsize, int subfield)
644{
645 const int maxvalues[] = {-1, 1, 3, 7, 15, 31, 63, 127};
646
647 int bits = 7 - modsize;
648 int partial = value & maxvalues[bits];
649 unsigned char b = subfield | (partial << modsize);
650
651 if (partial != value) {
652 b |= 0x80;
653 self->buffer[self->index] = b;
654 self->index++;
Fred Drake62c1e3c2001-12-04 21:40:53 +0000655 return pack_packed_int(self, value >> bits);
Fred Drake8c081a12001-10-12 20:57:55 +0000656 }
Fred Drake62c1e3c2001-12-04 21:40:53 +0000657 self->buffer[self->index] = b;
658 self->index++;
659 return 0;
Fred Drake8c081a12001-10-12 20:57:55 +0000660}
661
Fred Drake62c1e3c2001-12-04 21:40:53 +0000662static int
Fred Drake30d1c752001-10-15 22:11:02 +0000663pack_string(ProfilerObject *self, const char *s, int len)
Fred Drake8c081a12001-10-12 20:57:55 +0000664{
Fred Drake62c1e3c2001-12-04 21:40:53 +0000665 if (len + PISIZE + self->index >= BUFFERSIZE) {
666 if (flush_data(self) < 0)
667 return -1;
668 }
669 if (pack_packed_int(self, len) < 0)
670 return -1;
Fred Drake8c081a12001-10-12 20:57:55 +0000671 memcpy(self->buffer + self->index, s, len);
672 self->index += len;
Fred Drake62c1e3c2001-12-04 21:40:53 +0000673 return 0;
Fred Drake8c081a12001-10-12 20:57:55 +0000674}
675
Fred Drake62c1e3c2001-12-04 21:40:53 +0000676static int
Fred Drake8c081a12001-10-12 20:57:55 +0000677pack_add_info(ProfilerObject *self, const char *s1, const char *s2)
678{
679 int len1 = strlen(s1);
680 int len2 = strlen(s2);
681
Fred Drake62c1e3c2001-12-04 21:40:53 +0000682 if (len1 + len2 + PISIZE*2 + 1 + self->index >= BUFFERSIZE) {
683 if (flush_data(self) < 0)
684 return -1;
685 }
Fred Drake8c081a12001-10-12 20:57:55 +0000686 self->buffer[self->index] = WHAT_ADD_INFO;
687 self->index++;
Fred Drake62c1e3c2001-12-04 21:40:53 +0000688 if (pack_string(self, s1, len1) < 0)
689 return -1;
690 return pack_string(self, s2, len2);
Fred Drake8c081a12001-10-12 20:57:55 +0000691}
692
Fred Drake62c1e3c2001-12-04 21:40:53 +0000693static int
Fred Drake8c081a12001-10-12 20:57:55 +0000694pack_define_file(ProfilerObject *self, int fileno, const char *filename)
695{
696 int len = strlen(filename);
697
Fred Drake62c1e3c2001-12-04 21:40:53 +0000698 if (len + PISIZE*2 + 1 + self->index >= BUFFERSIZE) {
699 if (flush_data(self) < 0)
700 return -1;
701 }
Fred Drake8c081a12001-10-12 20:57:55 +0000702 self->buffer[self->index] = WHAT_DEFINE_FILE;
703 self->index++;
Fred Drake62c1e3c2001-12-04 21:40:53 +0000704 if (pack_packed_int(self, fileno) < 0)
705 return -1;
706 return pack_string(self, filename, len);
Fred Drake30d1c752001-10-15 22:11:02 +0000707}
708
Fred Drake62c1e3c2001-12-04 21:40:53 +0000709static int
Fred Drake30d1c752001-10-15 22:11:02 +0000710pack_define_func(ProfilerObject *self, int fileno, int lineno,
711 const char *funcname)
712{
713 int len = strlen(funcname);
714
Fred Drake62c1e3c2001-12-04 21:40:53 +0000715 if (len + PISIZE*3 + 1 + self->index >= BUFFERSIZE) {
716 if (flush_data(self) < 0)
717 return -1;
718 }
Fred Drake30d1c752001-10-15 22:11:02 +0000719 self->buffer[self->index] = WHAT_DEFINE_FUNC;
720 self->index++;
Fred Drake62c1e3c2001-12-04 21:40:53 +0000721 if (pack_packed_int(self, fileno) < 0)
722 return -1;
723 if (pack_packed_int(self, lineno) < 0)
724 return -1;
725 return pack_string(self, funcname, len);
Fred Drake8c081a12001-10-12 20:57:55 +0000726}
727
Fred Drake62c1e3c2001-12-04 21:40:53 +0000728static int
Fred Drake8c081a12001-10-12 20:57:55 +0000729pack_line_times(ProfilerObject *self)
730{
Fred Drake62c1e3c2001-12-04 21:40:53 +0000731 if (2 + self->index >= BUFFERSIZE) {
732 if (flush_data(self) < 0)
733 return -1;
734 }
Fred Drake8c081a12001-10-12 20:57:55 +0000735 self->buffer[self->index] = WHAT_LINE_TIMES;
736 self->buffer[self->index + 1] = self->linetimings ? 1 : 0;
737 self->index += 2;
Fred Drake62c1e3c2001-12-04 21:40:53 +0000738 return 0;
Fred Drake8c081a12001-10-12 20:57:55 +0000739}
740
Fred Drake62c1e3c2001-12-04 21:40:53 +0000741static int
Fred Drake30d1c752001-10-15 22:11:02 +0000742pack_frame_times(ProfilerObject *self)
743{
Fred Drake62c1e3c2001-12-04 21:40:53 +0000744 if (2 + self->index >= BUFFERSIZE) {
745 if (flush_data(self) < 0)
746 return -1;
747 }
Fred Drake30d1c752001-10-15 22:11:02 +0000748 self->buffer[self->index] = WHAT_FRAME_TIMES;
749 self->buffer[self->index + 1] = self->frametimings ? 1 : 0;
750 self->index += 2;
Fred Drake62c1e3c2001-12-04 21:40:53 +0000751 return 0;
Fred Drake30d1c752001-10-15 22:11:02 +0000752}
753
Fred Drake62c1e3c2001-12-04 21:40:53 +0000754static inline int
Fred Drake8c081a12001-10-12 20:57:55 +0000755pack_enter(ProfilerObject *self, int fileno, int tdelta, int lineno)
756{
Fred Drake62c1e3c2001-12-04 21:40:53 +0000757 if (MPISIZE + PISIZE*2 + self->index >= BUFFERSIZE) {
758 if (flush_data(self) < 0)
759 return -1;
760 }
Fred Drake8c081a12001-10-12 20:57:55 +0000761 pack_modified_packed_int(self, fileno, 2, WHAT_ENTER);
Fred Drake8c081a12001-10-12 20:57:55 +0000762 pack_packed_int(self, lineno);
Fred Drake30d1c752001-10-15 22:11:02 +0000763 if (self->frametimings)
Fred Drake62c1e3c2001-12-04 21:40:53 +0000764 return pack_packed_int(self, tdelta);
765 else
766 return 0;
Fred Drake8c081a12001-10-12 20:57:55 +0000767}
768
Fred Drake62c1e3c2001-12-04 21:40:53 +0000769static inline int
Fred Drake8c081a12001-10-12 20:57:55 +0000770pack_exit(ProfilerObject *self, int tdelta)
771{
Fred Drake62c1e3c2001-12-04 21:40:53 +0000772 if (MPISIZE + self->index >= BUFFERSIZE) {
773 if (flush_data(self) < 0)
774 return -1;
Fred Drake30d1c752001-10-15 22:11:02 +0000775 }
Fred Drake62c1e3c2001-12-04 21:40:53 +0000776 if (self->frametimings)
777 return pack_modified_packed_int(self, tdelta, 2, WHAT_EXIT);
778 self->buffer[self->index] = WHAT_EXIT;
779 self->index++;
780 return 0;
Fred Drake8c081a12001-10-12 20:57:55 +0000781}
782
Fred Drake62c1e3c2001-12-04 21:40:53 +0000783static inline int
Fred Drake8c081a12001-10-12 20:57:55 +0000784pack_lineno(ProfilerObject *self, int lineno)
785{
Fred Drake62c1e3c2001-12-04 21:40:53 +0000786 if (MPISIZE + self->index >= BUFFERSIZE) {
787 if (flush_data(self) < 0)
788 return -1;
789 }
790 return pack_modified_packed_int(self, lineno, 2, WHAT_LINENO);
Fred Drake8c081a12001-10-12 20:57:55 +0000791}
792
Fred Drake62c1e3c2001-12-04 21:40:53 +0000793static inline int
Fred Drake8c081a12001-10-12 20:57:55 +0000794pack_lineno_tdelta(ProfilerObject *self, int lineno, int tdelta)
795{
Fred Drake62c1e3c2001-12-04 21:40:53 +0000796 if (MPISIZE + PISIZE + self->index >= BUFFERSIZE) {
797 if (flush_data(self) < 0)
798 return 0;
799 }
800 if (pack_modified_packed_int(self, lineno, 2, WHAT_LINENO) < 0)
801 return -1;
802 return pack_packed_int(self, tdelta);
Fred Drake8c081a12001-10-12 20:57:55 +0000803}
804
805static inline int
806get_fileno(ProfilerObject *self, PyCodeObject *fcode)
807{
Fred Drake30d1c752001-10-15 22:11:02 +0000808 /* This is only used for ENTER events. */
809
810 PyObject *obj;
811 PyObject *dict;
Fred Drake8c081a12001-10-12 20:57:55 +0000812 int fileno;
813
Fred Drake30d1c752001-10-15 22:11:02 +0000814 obj = PyDict_GetItem(self->filemap, fcode->co_filename);
815 if (obj == NULL) {
Fred Drake8c081a12001-10-12 20:57:55 +0000816 /* first sighting of this file */
Fred Drake30d1c752001-10-15 22:11:02 +0000817 dict = PyDict_New();
818 if (dict == NULL) {
Fred Drake8c081a12001-10-12 20:57:55 +0000819 return -1;
820 }
Fred Drake30d1c752001-10-15 22:11:02 +0000821 fileno = self->next_fileno;
822 obj = Py_BuildValue("iN", fileno, dict);
823 if (obj == NULL) {
824 return -1;
825 }
826 if (PyDict_SetItem(self->filemap, fcode->co_filename, obj)) {
827 Py_DECREF(obj);
Fred Drake8c081a12001-10-12 20:57:55 +0000828 return -1;
829 }
830 self->next_fileno++;
Fred Drake30d1c752001-10-15 22:11:02 +0000831 Py_DECREF(obj);
Fred Drake62c1e3c2001-12-04 21:40:53 +0000832 if (pack_define_file(self, fileno,
833 PyString_AS_STRING(fcode->co_filename)) < 0)
834 return -1;
Fred Drake8c081a12001-10-12 20:57:55 +0000835 }
836 else {
837 /* already know this ID */
Fred Drake30d1c752001-10-15 22:11:02 +0000838 fileno = PyInt_AS_LONG(PyTuple_GET_ITEM(obj, 0));
839 dict = PyTuple_GET_ITEM(obj, 1);
840 }
841 /* make sure we save a function name for this (fileno, lineno) */
842 obj = PyInt_FromLong(fcode->co_firstlineno);
843 if (obj == NULL) {
844 /* We just won't have it saved; too bad. */
845 PyErr_Clear();
846 }
847 else {
848 PyObject *name = PyDict_GetItem(dict, obj);
849 if (name == NULL) {
Fred Drake62c1e3c2001-12-04 21:40:53 +0000850 if (pack_define_func(self, fileno, fcode->co_firstlineno,
851 PyString_AS_STRING(fcode->co_name)) < 0)
852 return -1;
Fred Drake30d1c752001-10-15 22:11:02 +0000853 if (PyDict_SetItem(dict, obj, fcode->co_name))
854 return -1;
855 }
Fred Drake8c081a12001-10-12 20:57:55 +0000856 }
857 return fileno;
858}
859
860static inline int
861get_tdelta(ProfilerObject *self)
862{
863 int tdelta;
864#ifdef MS_WIN32
865 hs_time tv;
Tim Peters7d99ff22001-10-13 07:37:52 +0000866 hs_time diff;
Fred Drake8c081a12001-10-12 20:57:55 +0000867
Tim Peters7d99ff22001-10-13 07:37:52 +0000868 GETTIMEOFDAY(&tv);
869 diff = tv - self->prev_timeofday;
870 tdelta = (int)diff;
Fred Drake8c081a12001-10-12 20:57:55 +0000871#else
872 struct timeval tv;
873
874 GETTIMEOFDAY(&tv);
875
876 if (tv.tv_sec == self->prev_timeofday.tv_sec)
877 tdelta = tv.tv_usec - self->prev_timeofday.tv_usec;
878 else
879 tdelta = ((tv.tv_sec - self->prev_timeofday.tv_sec) * 1000000
880 + tv.tv_usec);
881#endif
882 self->prev_timeofday = tv;
883 return tdelta;
884}
885
886
887/* The workhorse: the profiler callback function. */
888
889static int
890profiler_callback(ProfilerObject *self, PyFrameObject *frame, int what,
891 PyObject *arg)
892{
Fred Drake30d1c752001-10-15 22:11:02 +0000893 int tdelta = -1;
Fred Drake8c081a12001-10-12 20:57:55 +0000894 int fileno;
895
Fred Drake30d1c752001-10-15 22:11:02 +0000896 if (self->frametimings)
897 tdelta = get_tdelta(self);
Fred Drake8c081a12001-10-12 20:57:55 +0000898 switch (what) {
899 case PyTrace_CALL:
900 fileno = get_fileno(self, frame->f_code);
901 if (fileno < 0)
902 return -1;
Fred Drake62c1e3c2001-12-04 21:40:53 +0000903 if (pack_enter(self, fileno, tdelta,
904 frame->f_code->co_firstlineno) < 0)
905 return -1;
Fred Drake8c081a12001-10-12 20:57:55 +0000906 break;
907 case PyTrace_RETURN:
Fred Drake62c1e3c2001-12-04 21:40:53 +0000908 if (pack_exit(self, tdelta) < 0)
909 return -1;
Fred Drake8c081a12001-10-12 20:57:55 +0000910 break;
911 default:
912 /* should never get here */
913 break;
914 }
915 return 0;
916}
917
918
919/* Alternate callback when we want PyTrace_LINE events */
920
921static int
922tracer_callback(ProfilerObject *self, PyFrameObject *frame, int what,
923 PyObject *arg)
924{
925 int fileno;
926
Fred Drake8c081a12001-10-12 20:57:55 +0000927 switch (what) {
928 case PyTrace_CALL:
929 fileno = get_fileno(self, frame->f_code);
930 if (fileno < 0)
931 return -1;
Fred Drake62c1e3c2001-12-04 21:40:53 +0000932 return pack_enter(self, fileno,
933 self->frametimings ? get_tdelta(self) : -1,
934 frame->f_code->co_firstlineno);
935
Fred Drake8c081a12001-10-12 20:57:55 +0000936 case PyTrace_RETURN:
Fred Drake62c1e3c2001-12-04 21:40:53 +0000937 return pack_exit(self, get_tdelta(self));
938
Tim Peters1566a172001-10-12 22:08:39 +0000939 case PyTrace_LINE:
Fred Drake8c081a12001-10-12 20:57:55 +0000940 if (self->linetimings)
Fred Drake62c1e3c2001-12-04 21:40:53 +0000941 return pack_lineno_tdelta(self, frame->f_lineno, get_tdelta(self));
Fred Drake8c081a12001-10-12 20:57:55 +0000942 else
Fred Drake62c1e3c2001-12-04 21:40:53 +0000943 return pack_lineno(self, frame->f_lineno);
944
Fred Drake8c081a12001-10-12 20:57:55 +0000945 default:
946 /* ignore PyTrace_EXCEPTION */
947 break;
948 }
949 return 0;
950}
951
952
953/* A couple of useful helper functions. */
954
955#ifdef MS_WIN32
Tim Petersfeab23f2001-10-13 00:11:10 +0000956static LARGE_INTEGER frequency = {0, 0};
Fred Drake8c081a12001-10-12 20:57:55 +0000957#endif
958
959static unsigned long timeofday_diff = 0;
960static unsigned long rusage_diff = 0;
961
962static void
963calibrate(void)
964{
965 hs_time tv1, tv2;
966
967#ifdef MS_WIN32
Tim Peters7d99ff22001-10-13 07:37:52 +0000968 hs_time diff;
Fred Drake8c081a12001-10-12 20:57:55 +0000969 QueryPerformanceFrequency(&frequency);
970#endif
971
972 GETTIMEOFDAY(&tv1);
973 while (1) {
974 GETTIMEOFDAY(&tv2);
975#ifdef MS_WIN32
Tim Peters7d99ff22001-10-13 07:37:52 +0000976 diff = tv2 - tv1;
977 if (diff != 0) {
978 timeofday_diff = (unsigned long)diff;
Fred Drake8c081a12001-10-12 20:57:55 +0000979 break;
980 }
981#else
982 if (tv1.tv_sec != tv2.tv_sec || tv1.tv_usec != tv2.tv_usec) {
983 if (tv1.tv_sec == tv2.tv_sec)
984 timeofday_diff = tv2.tv_usec - tv1.tv_usec;
985 else
986 timeofday_diff = (1000000 - tv1.tv_usec) + tv2.tv_usec;
987 break;
988 }
989#endif
990 }
Jack Jansen963659a2001-10-23 22:26:16 +0000991#if defined(MS_WIN32) || defined(macintosh)
Fred Drake8c081a12001-10-12 20:57:55 +0000992 rusage_diff = -1;
993#else
994 {
995 struct rusage ru1, ru2;
996
997 getrusage(RUSAGE_SELF, &ru1);
998 while (1) {
999 getrusage(RUSAGE_SELF, &ru2);
1000 if (ru1.ru_utime.tv_sec != ru2.ru_utime.tv_sec) {
1001 rusage_diff = ((1000000 - ru1.ru_utime.tv_usec)
1002 + ru2.ru_utime.tv_usec);
1003 break;
1004 }
1005 else if (ru1.ru_utime.tv_usec != ru2.ru_utime.tv_usec) {
1006 rusage_diff = ru2.ru_utime.tv_usec - ru1.ru_utime.tv_usec;
1007 break;
1008 }
1009 else if (ru1.ru_stime.tv_sec != ru2.ru_stime.tv_sec) {
1010 rusage_diff = ((1000000 - ru1.ru_stime.tv_usec)
1011 + ru2.ru_stime.tv_usec);
1012 break;
1013 }
1014 else if (ru1.ru_stime.tv_usec != ru2.ru_stime.tv_usec) {
1015 rusage_diff = ru2.ru_stime.tv_usec - ru1.ru_stime.tv_usec;
1016 break;
1017 }
1018 }
1019 }
1020#endif
1021}
1022
1023static void
1024do_start(ProfilerObject *self)
1025{
1026 self->active = 1;
1027 GETTIMEOFDAY(&self->prev_timeofday);
1028 if (self->lineevents)
1029 PyEval_SetTrace((Py_tracefunc) tracer_callback, (PyObject *)self);
1030 else
1031 PyEval_SetProfile((Py_tracefunc) profiler_callback, (PyObject *)self);
1032}
1033
1034static void
1035do_stop(ProfilerObject *self)
1036{
1037 if (self->active) {
1038 self->active = 0;
1039 if (self->lineevents)
1040 PyEval_SetTrace(NULL, NULL);
1041 else
1042 PyEval_SetProfile(NULL, NULL);
1043 }
1044 if (self->index > 0) {
1045 /* Best effort to dump out any remaining data. */
1046 flush_data(self);
1047 }
1048}
1049
1050static int
1051is_available(ProfilerObject *self)
1052{
1053 if (self->active) {
1054 PyErr_SetString(ProfilerError, "profiler already active");
1055 return 0;
1056 }
1057 if (self->logfp == NULL) {
1058 PyErr_SetString(ProfilerError, "profiler already closed");
1059 return 0;
1060 }
1061 return 1;
1062}
1063
1064
1065/* Profiler object interface methods. */
1066
Fred Drake4c2e1af2001-10-29 20:45:57 +00001067static char addinfo__doc__[] =
1068"addinfo(key, value)\n"
1069"Insert an ADD_INFO record into the log.";
1070
1071static PyObject *
1072profiler_addinfo(ProfilerObject *self, PyObject *args)
1073{
1074 PyObject *result = NULL;
1075 char *key, *value;
1076
1077 if (PyArg_ParseTuple(args, "ss:addinfo", &key, &value)) {
1078 if (self->logfp == NULL)
1079 PyErr_SetString(ProfilerError, "profiler already closed");
1080 else {
Fred Drake62c1e3c2001-12-04 21:40:53 +00001081 if (pack_add_info(self, key, value) == 0) {
1082 result = Py_None;
1083 Py_INCREF(result);
1084 }
Fred Drake4c2e1af2001-10-29 20:45:57 +00001085 }
1086 }
1087 return result;
1088}
1089
Tim Petersfeab23f2001-10-13 00:11:10 +00001090static char close__doc__[] =
1091"close()\n"
1092"Shut down this profiler and close the log files, even if its active.";
Fred Drake8c081a12001-10-12 20:57:55 +00001093
1094static PyObject *
1095profiler_close(ProfilerObject *self, PyObject *args)
1096{
1097 PyObject *result = NULL;
1098
1099 if (PyArg_ParseTuple(args, ":close")) {
1100 do_stop(self);
1101 if (self->logfp != NULL) {
1102 fclose(self->logfp);
1103 self->logfp = NULL;
1104 }
1105 Py_INCREF(Py_None);
1106 result = Py_None;
1107 }
1108 return result;
1109}
1110
Tim Petersfeab23f2001-10-13 00:11:10 +00001111static char runcall__doc__[] =
1112"runcall(callable[, args[, kw]]) -> callable()\n"
1113"Profile a specific function call, returning the result of that call.";
Fred Drake8c081a12001-10-12 20:57:55 +00001114
1115static PyObject *
1116profiler_runcall(ProfilerObject *self, PyObject *args)
1117{
1118 PyObject *result = NULL;
1119 PyObject *callargs = NULL;
1120 PyObject *callkw = NULL;
1121 PyObject *callable;
1122
1123 if (PyArg_ParseTuple(args, "O|OO:runcall",
1124 &callable, &callargs, &callkw)) {
1125 if (is_available(self)) {
1126 do_start(self);
1127 result = PyEval_CallObjectWithKeywords(callable, callargs, callkw);
1128 do_stop(self);
1129 }
1130 }
1131 return result;
1132}
1133
Tim Petersfeab23f2001-10-13 00:11:10 +00001134static char runcode__doc__[] =
1135"runcode(code, globals[, locals])\n"
1136"Execute a code object while collecting profile data. If locals is\n"
1137"omitted, globals is used for the locals as well.";
Fred Drake8c081a12001-10-12 20:57:55 +00001138
1139static PyObject *
1140profiler_runcode(ProfilerObject *self, PyObject *args)
1141{
1142 PyObject *result = NULL;
1143 PyCodeObject *code;
1144 PyObject *globals;
1145 PyObject *locals = NULL;
1146
1147 if (PyArg_ParseTuple(args, "O!O!|O:runcode",
1148 &PyCode_Type, &code,
1149 &PyDict_Type, &globals,
1150 &locals)) {
1151 if (is_available(self)) {
1152 if (locals == NULL || locals == Py_None)
1153 locals = globals;
1154 else if (!PyDict_Check(locals)) {
1155 PyErr_SetString(PyExc_TypeError,
1156 "locals must be a dictionary or None");
1157 return NULL;
1158 }
1159 do_start(self);
1160 result = PyEval_EvalCode(code, globals, locals);
1161 do_stop(self);
1162#if 0
1163 if (!PyErr_Occurred()) {
1164 result = Py_None;
1165 Py_INCREF(result);
1166 }
1167#endif
1168 }
1169 }
1170 return result;
1171}
1172
Tim Petersfeab23f2001-10-13 00:11:10 +00001173static char start__doc__[] =
1174"start()\n"
1175"Install this profiler for the current thread.";
Fred Drake8c081a12001-10-12 20:57:55 +00001176
1177static PyObject *
1178profiler_start(ProfilerObject *self, PyObject *args)
1179{
1180 PyObject *result = NULL;
1181
1182 if (PyArg_ParseTuple(args, ":start")) {
1183 if (is_available(self))
1184 do_start(self);
1185 }
1186 return result;
1187}
1188
Tim Petersfeab23f2001-10-13 00:11:10 +00001189static char stop__doc__[] =
1190"stop()\n"
1191"Remove this profiler from the current thread.";
Fred Drake8c081a12001-10-12 20:57:55 +00001192
1193static PyObject *
1194profiler_stop(ProfilerObject *self, PyObject *args)
1195{
1196 PyObject *result = NULL;
1197
1198 if (PyArg_ParseTuple(args, ":stop")) {
1199 if (!self->active)
1200 PyErr_SetString(ProfilerError, "profiler not active");
1201 else
1202 do_stop(self);
1203 }
1204 return result;
1205}
1206
1207
1208/* Python API support. */
1209
1210static void
1211profiler_dealloc(ProfilerObject *self)
1212{
1213 do_stop(self);
1214 if (self->logfp != NULL)
1215 fclose(self->logfp);
1216 Py_XDECREF(self->filemap);
1217 Py_XDECREF(self->logfilename);
1218 PyObject_Del((PyObject *)self);
1219}
1220
1221/* Always use METH_VARARGS even though some of these could be METH_NOARGS;
1222 * this allows us to maintain compatibility with Python versions < 2.2
1223 * more easily, requiring only the changes to the dispatcher to be made.
1224 */
1225static PyMethodDef profiler_methods[] = {
Fred Drake4c2e1af2001-10-29 20:45:57 +00001226 {"addinfo", (PyCFunction)profiler_addinfo, METH_VARARGS, addinfo__doc__},
Fred Drake8c081a12001-10-12 20:57:55 +00001227 {"close", (PyCFunction)profiler_close, METH_VARARGS, close__doc__},
1228 {"runcall", (PyCFunction)profiler_runcall, METH_VARARGS, runcall__doc__},
1229 {"runcode", (PyCFunction)profiler_runcode, METH_VARARGS, runcode__doc__},
1230 {"start", (PyCFunction)profiler_start, METH_VARARGS, start__doc__},
1231 {"stop", (PyCFunction)profiler_stop, METH_VARARGS, stop__doc__},
1232 {NULL, NULL}
1233};
1234
1235/* Use a table even though there's only one "simple" member; this allows
1236 * __members__ and therefore dir() to work.
1237 */
1238static struct memberlist profiler_members[] = {
Fred Drake30d1c752001-10-15 22:11:02 +00001239 {"closed", T_INT, -1, READONLY},
1240 {"frametimings", T_LONG, offsetof(ProfilerObject, linetimings), READONLY},
1241 {"lineevents", T_LONG, offsetof(ProfilerObject, lineevents), READONLY},
1242 {"linetimings", T_LONG, offsetof(ProfilerObject, linetimings), READONLY},
Fred Drake8c081a12001-10-12 20:57:55 +00001243 {NULL}
1244};
1245
1246static PyObject *
1247profiler_getattr(ProfilerObject *self, char *name)
1248{
1249 PyObject *result;
1250 if (strcmp(name, "closed") == 0) {
1251 result = (self->logfp == NULL) ? Py_True : Py_False;
1252 Py_INCREF(result);
1253 }
1254 else {
1255 result = PyMember_Get((char *)self, profiler_members, name);
1256 if (result == NULL) {
1257 PyErr_Clear();
1258 result = Py_FindMethod(profiler_methods, (PyObject *)self, name);
1259 }
1260 }
1261 return result;
1262}
1263
1264
Tim Petersfeab23f2001-10-13 00:11:10 +00001265static char profiler_object__doc__[] =
1266"High-performance profiler object.\n"
1267"\n"
1268"Methods:\n"
1269"\n"
Fred Drake30d1c752001-10-15 22:11:02 +00001270"close(): Stop the profiler and close the log files.\n"
1271"runcall(): Run a single function call with profiling enabled.\n"
1272"runcode(): Execute a code object with profiling enabled.\n"
1273"start(): Install the profiler and return.\n"
1274"stop(): Remove the profiler.\n"
Tim Petersfeab23f2001-10-13 00:11:10 +00001275"\n"
1276"Attributes (read-only):\n"
1277"\n"
Fred Drake30d1c752001-10-15 22:11:02 +00001278"closed: True if the profiler has already been closed.\n"
1279"frametimings: True if ENTER/EXIT events collect timing information.\n"
1280"lineevents: True if SET_LINENO events are reported to the profiler.\n"
1281"linetimings: True if SET_LINENO events collect timing information.";
Fred Drake8c081a12001-10-12 20:57:55 +00001282
1283static PyTypeObject ProfilerType = {
1284 PyObject_HEAD_INIT(NULL)
1285 0, /* ob_size */
Fred Drake4c2e1af2001-10-29 20:45:57 +00001286 "_hotshot.ProfilerType", /* tp_name */
Fred Drake8c081a12001-10-12 20:57:55 +00001287 (int) sizeof(ProfilerObject), /* tp_basicsize */
1288 0, /* tp_itemsize */
1289 (destructor)profiler_dealloc, /* tp_dealloc */
1290 0, /* tp_print */
1291 (getattrfunc)profiler_getattr, /* tp_getattr */
1292 0, /* tp_setattr */
1293 0, /* tp_compare */
1294 0, /* tp_repr */
1295 0, /* tp_as_number */
1296 0, /* tp_as_sequence */
1297 0, /* tp_as_mapping */
1298 0, /* tp_hash */
1299 0, /* tp_call */
1300 0, /* tp_str */
1301 0, /* tp_getattro */
1302 0, /* tp_setattro */
1303 0, /* tp_as_buffer */
Fred Drake4c2e1af2001-10-29 20:45:57 +00001304 Py_TPFLAGS_DEFAULT, /* tp_flags */
Fred Drake8c081a12001-10-12 20:57:55 +00001305 profiler_object__doc__, /* tp_doc */
1306};
1307
1308
1309static PyMethodDef logreader_methods[] = {
1310 {"close", (PyCFunction)logreader_close, METH_VARARGS,
1311 logreader_close__doc__},
1312 {"next", (PyCFunction)logreader_next, METH_VARARGS,
1313 next__doc__},
1314 {NULL, NULL}
1315};
1316
1317static PyObject *
Fred Drake4c2e1af2001-10-29 20:45:57 +00001318logreader_getattr(LogReaderObject *self, char *name)
Fred Drake8c081a12001-10-12 20:57:55 +00001319{
Fred Drake4c2e1af2001-10-29 20:45:57 +00001320 if (strcmp(name, "info") == 0) {
1321 Py_INCREF(self->info);
1322 return self->info;
1323 }
Fred Drake8c081a12001-10-12 20:57:55 +00001324 return Py_FindMethod(logreader_methods, (PyObject *)self, name);
1325}
1326
1327
1328static char logreader__doc__[] = "\
1329logreader(filename) --> log-iterator\n\
1330Create a log-reader for the timing information file.";
1331
1332static PySequenceMethods logreader_as_sequence = {
1333 0, /* sq_length */
1334 0, /* sq_concat */
1335 0, /* sq_repeat */
1336 (intargfunc)logreader_sq_item, /* sq_item */
1337 0, /* sq_slice */
1338 0, /* sq_ass_item */
1339 0, /* sq_ass_slice */
1340 0, /* sq_contains */
1341 0, /* sq_inplace_concat */
1342 0, /* sq_inplace_repeat */
1343};
1344
1345static PyTypeObject LogReaderType = {
1346 PyObject_HEAD_INIT(NULL)
1347 0, /* ob_size */
Fred Drake4c2e1af2001-10-29 20:45:57 +00001348 "_hotshot.LogReaderType", /* tp_name */
Fred Drake8c081a12001-10-12 20:57:55 +00001349 (int) sizeof(LogReaderObject), /* tp_basicsize */
1350 0, /* tp_itemsize */
1351 (destructor)logreader_dealloc, /* tp_dealloc */
1352 0, /* tp_print */
1353 (getattrfunc)logreader_getattr, /* tp_getattr */
1354 0, /* tp_setattr */
1355 0, /* tp_compare */
1356 0, /* tp_repr */
1357 0, /* tp_as_number */
1358 &logreader_as_sequence, /* tp_as_sequence */
1359 0, /* tp_as_mapping */
1360 0, /* tp_hash */
1361 0, /* tp_call */
1362 0, /* tp_str */
1363 0, /* tp_getattro */
1364 0, /* tp_setattro */
1365 0, /* tp_as_buffer */
Fred Drake4c2e1af2001-10-29 20:45:57 +00001366 Py_TPFLAGS_DEFAULT, /* tp_flags */
Fred Drake8c081a12001-10-12 20:57:55 +00001367 logreader__doc__, /* tp_doc */
1368#if Py_TPFLAGS_HAVE_ITER
1369 0, /* tp_traverse */
1370 0, /* tp_clear */
1371 0, /* tp_richcompare */
1372 0, /* tp_weaklistoffset */
1373 (getiterfunc)logreader_tp_iter, /* tp_iter */
1374 (iternextfunc)logreader_tp_iternext,/* tp_iternext */
1375#endif
1376};
1377
1378static PyObject *
1379hotshot_logreader(PyObject *unused, PyObject *args)
1380{
1381 LogReaderObject *self = NULL;
1382 char *filename;
1383
1384 if (PyArg_ParseTuple(args, "s:logreader", &filename)) {
1385 self = PyObject_New(LogReaderObject, &LogReaderType);
1386 if (self != NULL) {
1387 self->filled = 0;
1388 self->index = 0;
Fred Drake30d1c752001-10-15 22:11:02 +00001389 self->frametimings = 1;
Fred Drake8c081a12001-10-12 20:57:55 +00001390 self->linetimings = 0;
Fred Drake4c2e1af2001-10-29 20:45:57 +00001391 self->info = NULL;
Fred Drake8c081a12001-10-12 20:57:55 +00001392 self->logfp = fopen(filename, "rb");
1393 if (self->logfp == NULL) {
1394 PyErr_SetFromErrnoWithFilename(PyExc_IOError, filename);
1395 Py_DECREF(self);
1396 self = NULL;
Fred Drake4c2e1af2001-10-29 20:45:57 +00001397 goto finally;
1398 }
1399 self->info = PyDict_New();
1400 if (self->info == NULL) {
1401 Py_DECREF(self);
1402 goto finally;
1403 }
1404 /* Aggressively attempt to load all preliminary ADD_INFO
1405 * records from the log so the info records are available
1406 * from a fresh logreader object.
1407 */
1408 logreader_refill(self);
1409 while (self->filled > self->index
1410 && self->buffer[self->index] == WHAT_ADD_INFO) {
1411 int err = unpack_add_info(self, 1);
1412 if (err) {
1413 if (err == ERR_EOF)
1414 eof_error();
1415 else
1416 PyErr_SetString(PyExc_RuntimeError,
1417 "unexpected error");
1418 break;
1419 }
1420 /* Refill agressively so we can avoid EOF during
1421 * initialization unless there's a real EOF condition
1422 * (the tp_iternext handler loops attempts to refill
1423 * and try again).
1424 */
1425 logreader_refill(self);
Fred Drake8c081a12001-10-12 20:57:55 +00001426 }
1427 }
1428 }
Fred Drake4c2e1af2001-10-29 20:45:57 +00001429 finally:
Fred Drake8c081a12001-10-12 20:57:55 +00001430 return (PyObject *) self;
1431}
1432
1433
1434/* Return a Python string that represents the version number without the
1435 * extra cruft added by revision control, even if the right options were
1436 * given to the "cvs export" command to make it not include the extra
1437 * cruft.
1438 */
1439static char *
1440get_version_string(void)
1441{
1442 static char *rcsid = "$Revision$";
1443 char *rev = rcsid;
1444 char *buffer;
1445 int i = 0;
1446
1447 while (*rev && !isdigit(*rev))
1448 ++rev;
1449 while (rev[i] != ' ' && rev[i] != '\0')
1450 ++i;
1451 buffer = malloc(i + 1);
1452 if (buffer != NULL) {
1453 memmove(buffer, rev, i);
1454 buffer[i] = '\0';
1455 }
1456 return buffer;
1457}
1458
1459/* Write out a RFC 822-style header with various useful bits of
1460 * information to make the output easier to manage.
1461 */
1462static int
1463write_header(ProfilerObject *self)
1464{
1465 char *buffer;
1466 char cwdbuffer[PATH_MAX];
1467 PyObject *temp;
1468 int i, len;
1469
1470 buffer = get_version_string();
1471 if (buffer == NULL) {
1472 PyErr_NoMemory();
1473 return -1;
1474 }
Fred Drake4c2e1af2001-10-29 20:45:57 +00001475 pack_add_info(self, "hotshot-version", buffer);
1476 pack_add_info(self, "requested-frame-timings",
1477 (self->frametimings ? "yes" : "no"));
1478 pack_add_info(self, "requested-line-events",
Fred Drake8c081a12001-10-12 20:57:55 +00001479 (self->lineevents ? "yes" : "no"));
Fred Drake4c2e1af2001-10-29 20:45:57 +00001480 pack_add_info(self, "requested-line-timings",
1481 (self->linetimings ? "yes" : "no"));
1482 pack_add_info(self, "platform", Py_GetPlatform());
1483 pack_add_info(self, "executable", Py_GetProgramFullPath());
Fred Drakef12a68c2001-11-09 15:59:36 +00001484 free(buffer);
Fred Drake8c081a12001-10-12 20:57:55 +00001485 buffer = (char *) Py_GetVersion();
1486 if (buffer == NULL)
1487 PyErr_Clear();
1488 else
Fred Drake4c2e1af2001-10-29 20:45:57 +00001489 pack_add_info(self, "executable-version", buffer);
Fred Drake8c081a12001-10-12 20:57:55 +00001490
1491#ifdef MS_WIN32
Tim Peters885d4572001-11-28 20:27:42 +00001492 PyOS_snprintf(cwdbuffer, sizeof(cwdbuffer), "%I64d", frequency.QuadPart);
Fred Drake4c2e1af2001-10-29 20:45:57 +00001493 pack_add_info(self, "reported-performance-frequency", cwdbuffer);
Fred Drake8c081a12001-10-12 20:57:55 +00001494#else
Tim Peters885d4572001-11-28 20:27:42 +00001495 PyOS_snprintf(cwdbuffer, sizeof(cwdbuffer), "%lu", rusage_diff);
Fred Drake4c2e1af2001-10-29 20:45:57 +00001496 pack_add_info(self, "observed-interval-getrusage", cwdbuffer);
Tim Peters885d4572001-11-28 20:27:42 +00001497 PyOS_snprintf(cwdbuffer, sizeof(cwdbuffer), "%lu", timeofday_diff);
Fred Drake4c2e1af2001-10-29 20:45:57 +00001498 pack_add_info(self, "observed-interval-gettimeofday", cwdbuffer);
Fred Drake8c081a12001-10-12 20:57:55 +00001499#endif
Fred Drake8c081a12001-10-12 20:57:55 +00001500
Fred Drake4c2e1af2001-10-29 20:45:57 +00001501 pack_add_info(self, "current-directory",
Fred Drake8c081a12001-10-12 20:57:55 +00001502 getcwd(cwdbuffer, sizeof cwdbuffer));
1503
1504 temp = PySys_GetObject("path");
1505 len = PyList_GET_SIZE(temp);
1506 for (i = 0; i < len; ++i) {
1507 PyObject *item = PyList_GET_ITEM(temp, i);
1508 buffer = PyString_AsString(item);
1509 if (buffer == NULL)
1510 return -1;
Fred Drake4c2e1af2001-10-29 20:45:57 +00001511 pack_add_info(self, "sys-path-entry", buffer);
Fred Drake8c081a12001-10-12 20:57:55 +00001512 }
Fred Drake4c2e1af2001-10-29 20:45:57 +00001513 pack_frame_times(self);
1514 pack_line_times(self);
1515
Fred Drake8c081a12001-10-12 20:57:55 +00001516 return 0;
1517}
1518
1519static char profiler__doc__[] = "\
1520profiler(logfilename[, lineevents[, linetimes]]) -> profiler\n\
1521Create a new profiler object.";
1522
1523static PyObject *
1524hotshot_profiler(PyObject *unused, PyObject *args)
1525{
1526 char *logfilename;
1527 ProfilerObject *self = NULL;
1528 int lineevents = 0;
1529 int linetimings = 1;
1530
1531 if (PyArg_ParseTuple(args, "s|ii:profiler", &logfilename,
1532 &lineevents, &linetimings)) {
1533 self = PyObject_New(ProfilerObject, &ProfilerType);
1534 if (self == NULL)
1535 return NULL;
Fred Drake30d1c752001-10-15 22:11:02 +00001536 self->frametimings = 1;
Fred Drake8c081a12001-10-12 20:57:55 +00001537 self->lineevents = lineevents ? 1 : 0;
1538 self->linetimings = (lineevents && linetimings) ? 1 : 0;
1539 self->index = 0;
1540 self->active = 0;
1541 self->next_fileno = 0;
Tim Peters1566a172001-10-12 22:08:39 +00001542 self->logfp = NULL;
Fred Drake8c081a12001-10-12 20:57:55 +00001543 self->logfilename = PyTuple_GET_ITEM(args, 0);
1544 Py_INCREF(self->logfilename);
1545 self->filemap = PyDict_New();
1546 if (self->filemap == NULL) {
1547 Py_DECREF(self);
1548 return NULL;
1549 }
1550 self->logfp = fopen(logfilename, "wb");
1551 if (self->logfp == NULL) {
1552 Py_DECREF(self);
1553 PyErr_SetFromErrnoWithFilename(PyExc_IOError, logfilename);
1554 return NULL;
1555 }
1556 if (timeofday_diff == 0) {
1557 /* Run this several times since sometimes the first
1558 * doesn't give the lowest values, and we're really trying
1559 * to determine the lowest.
1560 */
1561 calibrate();
1562 calibrate();
1563 calibrate();
1564 }
1565 if (write_header(self))
1566 /* some error occurred, exception has been set */
1567 self = NULL;
1568 }
1569 return (PyObject *) self;
1570}
1571
Fred Drake30d1c752001-10-15 22:11:02 +00001572static char coverage__doc__[] = "\
1573coverage(logfilename) -> profiler\n\
1574Returns a profiler that doesn't collect any timing information, which is\n\
1575useful in building a coverage analysis tool.";
1576
1577static PyObject *
1578hotshot_coverage(PyObject *unused, PyObject *args)
1579{
1580 char *logfilename;
1581 PyObject *result = NULL;
1582
1583 if (PyArg_ParseTuple(args, "s:coverage", &logfilename)) {
1584 result = hotshot_profiler(unused, args);
1585 if (result != NULL) {
1586 ProfilerObject *self = (ProfilerObject *) result;
1587 self->frametimings = 0;
1588 self->linetimings = 0;
1589 self->lineevents = 1;
1590 }
1591 }
1592 return result;
1593}
1594
Fred Drake8c081a12001-10-12 20:57:55 +00001595static char resolution__doc__[] =
1596#ifdef MS_WIN32
Tim Petersfeab23f2001-10-13 00:11:10 +00001597"resolution() -> (performance-counter-ticks, update-frequency)\n"
1598"Return the resolution of the timer provided by the QueryPerformanceCounter()\n"
1599"function. The first value is the smallest observed change, and the second\n"
1600"is the result of QueryPerformanceFrequency().";
Fred Drake8c081a12001-10-12 20:57:55 +00001601#else
Tim Petersfeab23f2001-10-13 00:11:10 +00001602"resolution() -> (gettimeofday-usecs, getrusage-usecs)\n"
1603"Return the resolution of the timers provided by the gettimeofday() and\n"
1604"getrusage() system calls, or -1 if the call is not supported.";
Fred Drake8c081a12001-10-12 20:57:55 +00001605#endif
1606
1607static PyObject *
1608hotshot_resolution(PyObject *unused, PyObject *args)
1609{
1610 PyObject *result = NULL;
1611
1612 if (PyArg_ParseTuple(args, ":resolution")) {
1613 if (timeofday_diff == 0) {
1614 calibrate();
1615 calibrate();
1616 calibrate();
1617 }
1618#ifdef MS_WIN32
1619 result = Py_BuildValue("ii", timeofday_diff, frequency.LowPart);
1620#else
1621 result = Py_BuildValue("ii", timeofday_diff, rusage_diff);
1622#endif
1623 }
1624 return result;
1625}
1626
1627
1628static PyMethodDef functions[] = {
Fred Drake30d1c752001-10-15 22:11:02 +00001629 {"coverage", hotshot_coverage, METH_VARARGS, coverage__doc__},
Fred Drake8c081a12001-10-12 20:57:55 +00001630 {"profiler", hotshot_profiler, METH_VARARGS, profiler__doc__},
1631 {"logreader", hotshot_logreader, METH_VARARGS, logreader__doc__},
1632 {"resolution", hotshot_resolution, METH_VARARGS, resolution__doc__},
1633 {NULL, NULL}
1634};
1635
1636
1637void
1638init_hotshot(void)
1639{
1640 PyObject *module;
1641
1642 LogReaderType.ob_type = &PyType_Type;
1643 ProfilerType.ob_type = &PyType_Type;
1644 module = Py_InitModule("_hotshot", functions);
1645 if (module != NULL) {
1646 char *s = get_version_string();
1647
1648 PyModule_AddStringConstant(module, "__version__", s);
1649 free(s);
1650 Py_INCREF(&LogReaderType);
1651 PyModule_AddObject(module, "LogReaderType",
1652 (PyObject *)&LogReaderType);
1653 Py_INCREF(&ProfilerType);
1654 PyModule_AddObject(module, "ProfilerType",
1655 (PyObject *)&ProfilerType);
1656
1657 if (ProfilerError == NULL)
1658 ProfilerError = PyErr_NewException("hotshot.ProfilerError",
1659 NULL, NULL);
1660 if (ProfilerError != NULL) {
1661 Py_INCREF(ProfilerError);
1662 PyModule_AddObject(module, "ProfilerError", ProfilerError);
1663 }
1664 PyModule_AddIntConstant(module, "WHAT_ENTER", WHAT_ENTER);
1665 PyModule_AddIntConstant(module, "WHAT_EXIT", WHAT_EXIT);
1666 PyModule_AddIntConstant(module, "WHAT_LINENO", WHAT_LINENO);
1667 PyModule_AddIntConstant(module, "WHAT_OTHER", WHAT_OTHER);
1668 PyModule_AddIntConstant(module, "WHAT_ADD_INFO", WHAT_ADD_INFO);
1669 PyModule_AddIntConstant(module, "WHAT_DEFINE_FILE", WHAT_DEFINE_FILE);
Fred Drake30d1c752001-10-15 22:11:02 +00001670 PyModule_AddIntConstant(module, "WHAT_DEFINE_FUNC", WHAT_DEFINE_FUNC);
Fred Drake8c081a12001-10-12 20:57:55 +00001671 PyModule_AddIntConstant(module, "WHAT_LINE_TIMES", WHAT_LINE_TIMES);
1672 }
1673}