blob: 03eafb19a03cb543bc3a779e561708f7ab39407b [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
11#ifdef HAVE_UNISTD_H
12#include <unistd.h>
13#endif
14
15/*
16 * Which timer to use should be made more configurable, but that should not
Tim Petersfeab23f2001-10-13 00:11:10 +000017 * be difficult. This will do for now.
Fred Drake8c081a12001-10-12 20:57:55 +000018 */
19#ifdef MS_WIN32
20#include <windows.h>
21#include <largeint.h>
Tim Peters1566a172001-10-12 22:08:39 +000022#include <direct.h> /* for getcwd() */
Tim Peters7d99ff22001-10-13 07:37:52 +000023typedef __int64 hs_time;
24#define GETTIMEOFDAY(P_HS_TIME) \
25 { LARGE_INTEGER _temp; \
26 QueryPerformanceCounter(&_temp); \
27 *(P_HS_TIME) = _temp.QuadPart; }
28
Tim Petersfeab23f2001-10-13 00:11:10 +000029
Fred Drake8c081a12001-10-12 20:57:55 +000030#else
31#ifndef HAVE_GETTIMEOFDAY
32#error "This module requires gettimeofday() on non-Windows platforms!"
33#endif
Jack Jansen963659a2001-10-23 22:26:16 +000034#ifdef macintosh
35#include <sys/time.h>
36#else
Fred Drake8c081a12001-10-12 20:57:55 +000037#include <sys/resource.h>
38#include <sys/times.h>
Jack Jansen963659a2001-10-23 22:26:16 +000039#endif
Fred Drake8c081a12001-10-12 20:57:55 +000040typedef struct timeval hs_time;
41#endif
42
43#if !defined(__cplusplus) && !defined(inline)
44#ifdef __GNUC__
45#define inline __inline
46#endif
47#endif
48
49#ifndef inline
50#define inline
51#endif
52
53#define BUFFERSIZE 10240
54
Jack Jansen963659a2001-10-23 22:26:16 +000055#ifdef macintosh
56#define PATH_MAX 254
57#endif
58
Tim Peters1566a172001-10-12 22:08:39 +000059#ifndef PATH_MAX
60# ifdef MAX_PATH
61# define PATH_MAX MAX_PATH
62# else
63# error "Need a defn. for PATH_MAX in _hotshot.c"
64# endif
65#endif
66
Fred Drake8c081a12001-10-12 20:57:55 +000067typedef struct {
68 PyObject_HEAD
69 PyObject *filemap;
70 PyObject *logfilename;
71 int index;
72 unsigned char buffer[BUFFERSIZE];
73 FILE *logfp;
74 int lineevents;
75 int linetimings;
Fred Drake30d1c752001-10-15 22:11:02 +000076 int frametimings;
Fred Drake8c081a12001-10-12 20:57:55 +000077 /* size_t filled; */
78 int active;
79 int next_fileno;
Fred Drake8c081a12001-10-12 20:57:55 +000080 hs_time prev_timeofday;
81} ProfilerObject;
82
83typedef struct {
84 PyObject_HEAD
Fred Drake4c2e1af2001-10-29 20:45:57 +000085 PyObject *info;
Fred Drake8c081a12001-10-12 20:57:55 +000086 FILE *logfp;
87 int filled;
88 int index;
89 int linetimings;
Fred Drake30d1c752001-10-15 22:11:02 +000090 int frametimings;
Fred Drake8c081a12001-10-12 20:57:55 +000091 unsigned char buffer[BUFFERSIZE];
92} LogReaderObject;
93
94static PyObject * ProfilerError = NULL;
95
96
97#ifndef MS_WIN32
98#ifdef GETTIMEOFDAY_NO_TZ
99#define GETTIMEOFDAY(ptv) gettimeofday((ptv))
100#else
101#define GETTIMEOFDAY(ptv) gettimeofday((ptv), (struct timezone *)NULL)
102#endif
103#endif
104
105
106/* The log reader... */
107
Tim Petersfeab23f2001-10-13 00:11:10 +0000108static char logreader_close__doc__[] =
109"close()\n"
110"Close the log file, preventing additional records from being read.";
Fred Drake8c081a12001-10-12 20:57:55 +0000111
112static PyObject *
113logreader_close(LogReaderObject *self, PyObject *args)
114{
115 PyObject *result = NULL;
116 if (PyArg_ParseTuple(args, ":close")) {
117 if (self->logfp != NULL) {
118 fclose(self->logfp);
119 self->logfp = NULL;
120 }
121 result = Py_None;
122 Py_INCREF(result);
123 }
124 return result;
125}
126
127#if Py_TPFLAGS_HAVE_ITER
128/* This is only used if the interpreter has iterator support; the
129 * iternext handler is also used as a helper for other functions, so
130 * does not need to be included in this conditional section.
131 */
132static PyObject *
133logreader_tp_iter(LogReaderObject *self)
134{
135 Py_INCREF(self);
136 return (PyObject *) self;
137}
138#endif
139
140
141/* Log File Format
142 * ---------------
143 *
144 * The log file consists of a sequence of variable-length records.
145 * Each record is identified with a record type identifier in two
146 * bits of the first byte. The two bits are the "least significant"
147 * bits of the byte.
148 *
149 * Low bits: Opcode: Meaning:
150 * 0x00 ENTER enter a frame
151 * 0x01 EXIT exit a frame
152 * 0x02 LINENO SET_LINENO instruction was executed
153 * 0x03 OTHER more bits are needed to deecode
154 *
155 * If the type is OTHER, the record is not packed so tightly, and the
156 * remaining bits are used to disambiguate the record type. These
157 * records are not used as frequently so compaction is not an issue.
158 * Each of the first three record types has a highly tailored
159 * structure that allows it to be packed tightly.
160 *
161 * The OTHER records have the following identifiers:
162 *
163 * First byte: Opcode: Meaning:
164 * 0x13 ADD_INFO define a key/value pair
165 * 0x23 DEFINE_FILE define an int->filename mapping
166 * 0x33 LINE_TIMES indicates if LINENO events have tdeltas
Fred Drake30d1c752001-10-15 22:11:02 +0000167 * 0x43 DEFINE_FUNC define a (fileno,lineno)->funcname mapping
168 * 0x53 FRAME_TIMES indicates if ENTER/EXIT events have tdeltas
Fred Drake8c081a12001-10-12 20:57:55 +0000169 *
170 * Packed Integers
171 *
172 * "Packed integers" are non-negative integer values encoded as a
173 * sequence of bytes. Each byte is encoded such that the most
174 * significant bit is set if the next byte is also part of the
175 * integer. Each byte provides bits to the least-significant end of
176 * the result; the accumulated value must be shifted up to place the
177 * new bits into the result.
178 *
179 * "Modified packed integers" are packed integers where only a portion
180 * of the first byte is used. In the rest of the specification, these
181 * are referred to as "MPI(n,name)", where "n" is the number of bits
182 * discarded from the least-signicant positions of the byte, and
183 * "name" is a name being given to those "discarded" bits, since they
184 * are a field themselves.
185 *
186 * ENTER records:
187 *
188 * MPI(2,type) fileno -- type is 0x00
Fred Drake8c081a12001-10-12 20:57:55 +0000189 * PI lineno
Fred Drake30d1c752001-10-15 22:11:02 +0000190 * PI tdelta -- iff frame times are enabled
Fred Drake8c081a12001-10-12 20:57:55 +0000191 *
192 * EXIT records
193 *
Fred Drake30d1c752001-10-15 22:11:02 +0000194 * MPI(2,type) tdelta -- type is 0x01; tdelta will be 0
195 * if frame times are disabled
Fred Drake8c081a12001-10-12 20:57:55 +0000196 *
197 * LINENO records
198 *
199 * MPI(2,type) lineno -- type is 0x02
200 * PI tdelta -- iff LINENO includes it
201 *
202 * ADD_INFO records
203 *
Fred Drake30d1c752001-10-15 22:11:02 +0000204 * BYTE type -- always 0x13
Fred Drake8c081a12001-10-12 20:57:55 +0000205 * PI len1 -- length of first string
206 * BYTE string1[len1] -- len1 bytes of string data
207 * PI len2 -- length of second string
208 * BYTE string2[len2] -- len2 bytes of string data
209 *
210 * DEFINE_FILE records
211 *
Fred Drake30d1c752001-10-15 22:11:02 +0000212 * BYTE type -- always 0x23
Fred Drake8c081a12001-10-12 20:57:55 +0000213 * PI fileno
214 * PI len -- length of filename
215 * BYTE filename[len] -- len bytes of string data
216 *
Fred Drake30d1c752001-10-15 22:11:02 +0000217 * DEFINE_FUNC records
218 *
219 * BYTE type -- always 0x43
220 * PI fileno
221 * PI lineno
222 * PI len -- length of funcname
223 * BYTE funcname[len] -- len bytes of string data
224 *
Fred Drake8c081a12001-10-12 20:57:55 +0000225 * LINE_TIMES records
Fred Drake30d1c752001-10-15 22:11:02 +0000226 *
227 * This record can be used only before the start of ENTER/EXIT/LINENO
228 * records. If have_tdelta is true, LINENO records will include the
229 * tdelta field, otherwise it will be omitted. If this record is not
230 * given, LINENO records will not contain the tdelta field.
231 *
232 * BYTE type -- always 0x33
Fred Drake8c081a12001-10-12 20:57:55 +0000233 * BYTE have_tdelta -- 0 if LINENO does *not* have
234 * timing information
Fred Drake30d1c752001-10-15 22:11:02 +0000235 * FRAME_TIMES records
236 *
237 * This record can be used only before the start of ENTER/EXIT/LINENO
238 * records. If have_tdelta is true, ENTER and EXIT records will
239 * include the tdelta field, otherwise it will be omitted. If this
240 * record is not given, ENTER and EXIT records will contain the tdelta
241 * field.
242 *
243 * BYTE type -- always 0x53
244 * BYTE have_tdelta -- 0 if ENTER/EXIT do *not* have
245 * timing information
Fred Drake8c081a12001-10-12 20:57:55 +0000246 */
247
248#define WHAT_ENTER 0x00
249#define WHAT_EXIT 0x01
250#define WHAT_LINENO 0x02
251#define WHAT_OTHER 0x03 /* only used in decoding */
252#define WHAT_ADD_INFO 0x13
253#define WHAT_DEFINE_FILE 0x23
254#define WHAT_LINE_TIMES 0x33
Fred Drake30d1c752001-10-15 22:11:02 +0000255#define WHAT_DEFINE_FUNC 0x43
256#define WHAT_FRAME_TIMES 0x53
Fred Drake8c081a12001-10-12 20:57:55 +0000257
258#define ERR_NONE 0
259#define ERR_EOF -1
260#define ERR_EXCEPTION -2
Fred Drake4c2e1af2001-10-29 20:45:57 +0000261#define ERR_BAD_RECTYPE -3
Fred Drake8c081a12001-10-12 20:57:55 +0000262
263#define PISIZE (sizeof(int) + 1)
264#define MPISIZE (PISIZE + 1)
265
266/* Maximum size of "normal" events -- nothing that contains string data */
267#define MAXEVENTSIZE (MPISIZE + PISIZE*2)
268
269
270/* Unpack a packed integer; if "discard" is non-zero, unpack a modified
271 * packed integer with "discard" discarded bits.
272 */
273static int
274unpack_packed_int(LogReaderObject *self, int *pvalue, int discard)
275{
276 int accum = 0;
277 int bits = 0;
278 int index = self->index;
279 int cont;
280
281 do {
282 if (index >= self->filled)
283 return ERR_EOF;
284 /* read byte */
285 accum |= ((self->buffer[index] & 0x7F) >> discard) << bits;
286 bits += (7 - discard);
287 cont = self->buffer[index] & 0x80;
288 /* move to next */
289 discard = 0;
290 index++;
291 } while (cont);
292
293 /* save state */
294 self->index = index;
295 *pvalue = accum;
296
297 return 0;
298}
299
300/* Unpack a string, which is encoded as a packed integer giving the
301 * length of the string, followed by the string data.
302 */
303static int
304unpack_string(LogReaderObject *self, PyObject **pvalue)
305{
306 int len;
307 int oldindex = self->index;
308 int err = unpack_packed_int(self, &len, 0);
309
310 if (!err) {
311 /* need at least len bytes in buffer */
312 if (len > (self->filled - self->index)) {
313 self->index = oldindex;
314 err = ERR_EOF;
315 }
316 else {
Jack Jansen963659a2001-10-23 22:26:16 +0000317 *pvalue = PyString_FromStringAndSize((char *)self->buffer + self->index,
Fred Drake8c081a12001-10-12 20:57:55 +0000318 len);
319 if (*pvalue == NULL) {
320 self->index = oldindex;
321 err = ERR_EXCEPTION;
322 }
323 else
324 self->index += len;
325 }
326 }
327 return err;
328}
329
330
Fred Drake4c2e1af2001-10-29 20:45:57 +0000331static int
332unpack_add_info(LogReaderObject *self, int skip_opcode)
333{
334 PyObject *key;
335 PyObject *value = NULL;
336 int err;
337
338 if (skip_opcode) {
339 if (self->buffer[self->index] != WHAT_ADD_INFO)
340 return ERR_BAD_RECTYPE;
341 self->index++;
342 }
343 err = unpack_string(self, &key);
344 if (!err) {
345 err = unpack_string(self, &value);
346 if (err)
347 Py_DECREF(key);
348 else {
349 PyObject *list = PyDict_GetItem(self->info, key);
350 if (list == NULL) {
351 list = PyList_New(0);
352 if (list == NULL) {
353 err = ERR_EXCEPTION;
354 goto finally;
355 }
356 if (PyDict_SetItem(self->info, key, list)) {
357 err = ERR_EXCEPTION;
358 goto finally;
359 }
360 }
361 if (PyList_Append(list, value))
362 err = ERR_EXCEPTION;
363 }
364 }
365 finally:
366 Py_XDECREF(key);
367 Py_XDECREF(value);
368 return err;
369}
370
371
372static void
373logreader_refill(LogReaderObject *self)
374{
375 int needed;
376 size_t res;
377
378 if (self->index) {
379 memmove(self->buffer, &self->buffer[self->index],
380 self->filled - self->index);
381 self->filled = self->filled - self->index;
382 self->index = 0;
383 }
384 needed = BUFFERSIZE - self->filled;
385 if (needed > 0) {
386 res = fread(&self->buffer[self->filled], 1, needed, self->logfp);
387 self->filled += res;
388 }
389}
390
391static void
392eof_error(void)
393{
394 PyErr_SetString(PyExc_EOFError,
395 "end of file with incomplete profile record");
396}
397
Fred Drake8c081a12001-10-12 20:57:55 +0000398static PyObject *
399logreader_tp_iternext(LogReaderObject *self)
400{
401 int what, oldindex;
402 int err = ERR_NONE;
403 int lineno = -1;
404 int fileno = -1;
405 int tdelta = -1;
406 PyObject *s1 = NULL, *s2 = NULL;
407 PyObject *result = NULL;
408#if 0
409 unsigned char b0, b1;
410#endif
411
412 if (self->logfp == NULL) {
413 PyErr_SetString(ProfilerError,
414 "cannot iterate over closed LogReader object");
415 return NULL;
416 }
417 restart:
Fred Drake4c2e1af2001-10-29 20:45:57 +0000418 if ((self->filled - self->index) < MAXEVENTSIZE)
419 logreader_refill(self);
420
Fred Drake8c081a12001-10-12 20:57:55 +0000421 /* end of input */
422 if (self->filled == 0)
423 return NULL;
424
425 oldindex = self->index;
426
427 /* decode the record type */
428 what = self->buffer[self->index] & WHAT_OTHER;
429 if (what == WHAT_OTHER) {
430 what = self->buffer[self->index];
431 self->index++;
432 }
433 switch (what) {
434 case WHAT_ENTER:
435 err = unpack_packed_int(self, &fileno, 2);
436 if (!err) {
Fred Drake30d1c752001-10-15 22:11:02 +0000437 err = unpack_packed_int(self, &lineno, 0);
438 if (self->frametimings && !err)
439 err = unpack_packed_int(self, &tdelta, 0);
Fred Drake8c081a12001-10-12 20:57:55 +0000440 }
441 break;
442 case WHAT_EXIT:
443 err = unpack_packed_int(self, &tdelta, 2);
444 break;
445 case WHAT_LINENO:
446 err = unpack_packed_int(self, &lineno, 2);
447 if (self->linetimings && !err)
448 err = unpack_packed_int(self, &tdelta, 0);
449 break;
450 case WHAT_ADD_INFO:
Fred Drake4c2e1af2001-10-29 20:45:57 +0000451 err = unpack_add_info(self, 0);
Fred Drake8c081a12001-10-12 20:57:55 +0000452 break;
453 case WHAT_DEFINE_FILE:
454 err = unpack_packed_int(self, &fileno, 0);
455 if (!err) {
456 err = unpack_string(self, &s1);
457 if (!err) {
458 Py_INCREF(Py_None);
459 s2 = Py_None;
460 }
461 }
462 break;
Fred Drake30d1c752001-10-15 22:11:02 +0000463 case WHAT_DEFINE_FUNC:
464 err = unpack_packed_int(self, &fileno, 0);
465 if (!err) {
466 err = unpack_packed_int(self, &lineno, 0);
467 if (!err)
468 err = unpack_string(self, &s1);
469 }
470 break;
Fred Drake8c081a12001-10-12 20:57:55 +0000471 case WHAT_LINE_TIMES:
472 if (self->index >= self->filled)
473 err = ERR_EOF;
474 else {
475 self->linetimings = self->buffer[self->index] ? 1 : 0;
476 self->index++;
477 goto restart;
478 }
Fred Drake4c2e1af2001-10-29 20:45:57 +0000479 break;
Fred Drake30d1c752001-10-15 22:11:02 +0000480 case WHAT_FRAME_TIMES:
481 if (self->index >= self->filled)
482 err = ERR_EOF;
483 else {
484 self->frametimings = self->buffer[self->index] ? 1 : 0;
485 self->index++;
486 goto restart;
487 }
Fred Drake4c2e1af2001-10-29 20:45:57 +0000488 break;
Fred Drake8c081a12001-10-12 20:57:55 +0000489 default:
Fred Drake4c2e1af2001-10-29 20:45:57 +0000490 err = ERR_BAD_RECTYPE;
Fred Drake8c081a12001-10-12 20:57:55 +0000491 }
492 if (err == ERR_EOF && oldindex != 0) {
493 /* It looks like we ran out of data before we had it all; this
494 * could easily happen with large packed integers or string
495 * data. Try forcing the buffer to be re-filled before failing.
496 */
497 err = ERR_NONE;
Fred Drake4c2e1af2001-10-29 20:45:57 +0000498 logreader_refill(self);
Fred Drake8c081a12001-10-12 20:57:55 +0000499 }
Fred Drake4c2e1af2001-10-29 20:45:57 +0000500 if (err == ERR_BAD_RECTYPE) {
501 PyErr_SetString(PyExc_ValueError,
502 "unknown record type in log file");
503 }
504 else if (err == ERR_EOF) {
Fred Drake8c081a12001-10-12 20:57:55 +0000505 /* Could not avoid end-of-buffer error. */
Fred Drake4c2e1af2001-10-29 20:45:57 +0000506 eof_error();
Fred Drake8c081a12001-10-12 20:57:55 +0000507 }
508 else if (!err) {
509 result = PyTuple_New(4);
510 PyTuple_SET_ITEM(result, 0, PyInt_FromLong(what));
511 PyTuple_SET_ITEM(result, 2, PyInt_FromLong(fileno));
Fred Drake30d1c752001-10-15 22:11:02 +0000512 if (s1 == NULL)
Fred Drake8c081a12001-10-12 20:57:55 +0000513 PyTuple_SET_ITEM(result, 1, PyInt_FromLong(tdelta));
Fred Drake30d1c752001-10-15 22:11:02 +0000514 else
Fred Drake8c081a12001-10-12 20:57:55 +0000515 PyTuple_SET_ITEM(result, 1, s1);
Fred Drake30d1c752001-10-15 22:11:02 +0000516 if (s2 == NULL)
517 PyTuple_SET_ITEM(result, 3, PyInt_FromLong(lineno));
518 else
Fred Drake8c081a12001-10-12 20:57:55 +0000519 PyTuple_SET_ITEM(result, 3, s2);
Fred Drake8c081a12001-10-12 20:57:55 +0000520 }
521 /* The only other case is err == ERR_EXCEPTION, in which case the
522 * exception is already set.
523 */
524#if 0
525 b0 = self->buffer[self->index];
526 b1 = self->buffer[self->index + 1];
527 if (b0 & 1) {
528 /* This is a line-number event. */
529 what = PyTrace_LINE;
530 lineno = ((b0 & ~1) << 7) + b1;
531 self->index += 2;
532 }
533 else {
534 what = (b0 & 0x0E) >> 1;
535 tdelta = ((b0 & 0xF0) << 4) + b1;
536 if (what == PyTrace_CALL) {
537 /* we know there's a 2-byte file ID & 2-byte line number */
538 fileno = ((self->buffer[self->index + 2] << 8)
539 + self->buffer[self->index + 3]);
540 lineno = ((self->buffer[self->index + 4] << 8)
541 + self->buffer[self->index + 5]);
542 self->index += 6;
543 }
544 else
545 self->index += 2;
546 }
547#endif
548 return result;
549}
550
551static void
552logreader_dealloc(LogReaderObject *self)
553{
554 if (self->logfp != NULL) {
555 fclose(self->logfp);
556 self->logfp = NULL;
557 }
558 PyObject_Del(self);
559}
560
561static PyObject *
562logreader_sq_item(LogReaderObject *self, int index)
563{
564 PyObject *result = logreader_tp_iternext(self);
565 if (result == NULL && !PyErr_Occurred()) {
566 PyErr_SetString(PyExc_IndexError, "no more events in log");
567 return NULL;
568 }
569 return result;
570}
571
Tim Petersfeab23f2001-10-13 00:11:10 +0000572static char next__doc__[] =
573"next() -> event-info\n"
574"Return the next event record from the log file.";
Fred Drake8c081a12001-10-12 20:57:55 +0000575
576static PyObject *
577logreader_next(LogReaderObject *self, PyObject *args)
578{
579 PyObject *result = NULL;
580
581 if (PyArg_ParseTuple(args, ":next")) {
582 result = logreader_tp_iternext(self);
583 /* XXX return None if there's nothing left */
584 /* tp_iternext does the right thing, though */
585 if (result == NULL && !PyErr_Occurred()) {
586 result = Py_None;
587 Py_INCREF(result);
588 }
589 }
590 return result;
591}
592
Fred Drake62c1e3c2001-12-04 21:40:53 +0000593static void
594do_stop(ProfilerObject *self);
Fred Drake8c081a12001-10-12 20:57:55 +0000595
596static int
597flush_data(ProfilerObject *self)
598{
599 /* Need to dump data to the log file... */
600 size_t written = fwrite(self->buffer, 1, self->index, self->logfp);
Tim Peters1566a172001-10-12 22:08:39 +0000601 if (written == (size_t)self->index)
Fred Drake8c081a12001-10-12 20:57:55 +0000602 self->index = 0;
603 else {
604 memmove(self->buffer, &self->buffer[written],
605 self->index - written);
606 self->index -= written;
607 if (written == 0) {
608 char *s = PyString_AsString(self->logfilename);
609 PyErr_SetFromErrnoWithFilename(PyExc_IOError, s);
Fred Drake62c1e3c2001-12-04 21:40:53 +0000610 do_stop(self);
Fred Drake8c081a12001-10-12 20:57:55 +0000611 return -1;
612 }
613 }
614 if (written > 0) {
615 if (fflush(self->logfp)) {
616 char *s = PyString_AsString(self->logfilename);
617 PyErr_SetFromErrnoWithFilename(PyExc_IOError, s);
Fred Drake62c1e3c2001-12-04 21:40:53 +0000618 do_stop(self);
Fred Drake8c081a12001-10-12 20:57:55 +0000619 return -1;
620 }
621 }
622 return 0;
623}
624
Fred Drake62c1e3c2001-12-04 21:40:53 +0000625static inline int
Fred Drake8c081a12001-10-12 20:57:55 +0000626pack_packed_int(ProfilerObject *self, int value)
627{
628 unsigned char partial;
629
630 do {
631 partial = value & 0x7F;
632 value >>= 7;
633 if (value)
634 partial |= 0x80;
635 self->buffer[self->index] = partial;
636 self->index++;
637 } while (value);
Fred Drake62c1e3c2001-12-04 21:40:53 +0000638 return 0;
Fred Drake8c081a12001-10-12 20:57:55 +0000639}
640
641/* Encode a modified packed integer, with a subfield of modsize bits
642 * containing the value "subfield". The value of subfield is not
643 * checked to ensure it actually fits in modsize bits.
644 */
Fred Drake62c1e3c2001-12-04 21:40:53 +0000645static inline int
Fred Drake8c081a12001-10-12 20:57:55 +0000646pack_modified_packed_int(ProfilerObject *self, int value,
647 int modsize, int subfield)
648{
649 const int maxvalues[] = {-1, 1, 3, 7, 15, 31, 63, 127};
650
651 int bits = 7 - modsize;
652 int partial = value & maxvalues[bits];
653 unsigned char b = subfield | (partial << modsize);
654
655 if (partial != value) {
656 b |= 0x80;
657 self->buffer[self->index] = b;
658 self->index++;
Fred Drake62c1e3c2001-12-04 21:40:53 +0000659 return pack_packed_int(self, value >> bits);
Fred Drake8c081a12001-10-12 20:57:55 +0000660 }
Fred Drake62c1e3c2001-12-04 21:40:53 +0000661 self->buffer[self->index] = b;
662 self->index++;
663 return 0;
Fred Drake8c081a12001-10-12 20:57:55 +0000664}
665
Fred Drake62c1e3c2001-12-04 21:40:53 +0000666static int
Fred Drake30d1c752001-10-15 22:11:02 +0000667pack_string(ProfilerObject *self, const char *s, int len)
Fred Drake8c081a12001-10-12 20:57:55 +0000668{
Fred Drake62c1e3c2001-12-04 21:40:53 +0000669 if (len + PISIZE + self->index >= BUFFERSIZE) {
670 if (flush_data(self) < 0)
671 return -1;
672 }
673 if (pack_packed_int(self, len) < 0)
674 return -1;
Fred Drake8c081a12001-10-12 20:57:55 +0000675 memcpy(self->buffer + self->index, s, len);
676 self->index += len;
Fred Drake62c1e3c2001-12-04 21:40:53 +0000677 return 0;
Fred Drake8c081a12001-10-12 20:57:55 +0000678}
679
Fred Drake62c1e3c2001-12-04 21:40:53 +0000680static int
Fred Drake8c081a12001-10-12 20:57:55 +0000681pack_add_info(ProfilerObject *self, const char *s1, const char *s2)
682{
683 int len1 = strlen(s1);
684 int len2 = strlen(s2);
685
Fred Drake62c1e3c2001-12-04 21:40:53 +0000686 if (len1 + len2 + PISIZE*2 + 1 + self->index >= BUFFERSIZE) {
687 if (flush_data(self) < 0)
688 return -1;
689 }
Fred Drake8c081a12001-10-12 20:57:55 +0000690 self->buffer[self->index] = WHAT_ADD_INFO;
691 self->index++;
Fred Drake62c1e3c2001-12-04 21:40:53 +0000692 if (pack_string(self, s1, len1) < 0)
693 return -1;
694 return pack_string(self, s2, len2);
Fred Drake8c081a12001-10-12 20:57:55 +0000695}
696
Fred Drake62c1e3c2001-12-04 21:40:53 +0000697static int
Fred Drake8c081a12001-10-12 20:57:55 +0000698pack_define_file(ProfilerObject *self, int fileno, const char *filename)
699{
700 int len = strlen(filename);
701
Fred Drake62c1e3c2001-12-04 21:40:53 +0000702 if (len + PISIZE*2 + 1 + self->index >= BUFFERSIZE) {
703 if (flush_data(self) < 0)
704 return -1;
705 }
Fred Drake8c081a12001-10-12 20:57:55 +0000706 self->buffer[self->index] = WHAT_DEFINE_FILE;
707 self->index++;
Fred Drake62c1e3c2001-12-04 21:40:53 +0000708 if (pack_packed_int(self, fileno) < 0)
709 return -1;
710 return pack_string(self, filename, len);
Fred Drake30d1c752001-10-15 22:11:02 +0000711}
712
Fred Drake62c1e3c2001-12-04 21:40:53 +0000713static int
Fred Drake30d1c752001-10-15 22:11:02 +0000714pack_define_func(ProfilerObject *self, int fileno, int lineno,
715 const char *funcname)
716{
717 int len = strlen(funcname);
718
Fred Drake62c1e3c2001-12-04 21:40:53 +0000719 if (len + PISIZE*3 + 1 + self->index >= BUFFERSIZE) {
720 if (flush_data(self) < 0)
721 return -1;
722 }
Fred Drake30d1c752001-10-15 22:11:02 +0000723 self->buffer[self->index] = WHAT_DEFINE_FUNC;
724 self->index++;
Fred Drake62c1e3c2001-12-04 21:40:53 +0000725 if (pack_packed_int(self, fileno) < 0)
726 return -1;
727 if (pack_packed_int(self, lineno) < 0)
728 return -1;
729 return pack_string(self, funcname, len);
Fred Drake8c081a12001-10-12 20:57:55 +0000730}
731
Fred Drake62c1e3c2001-12-04 21:40:53 +0000732static int
Fred Drake8c081a12001-10-12 20:57:55 +0000733pack_line_times(ProfilerObject *self)
734{
Fred Drake62c1e3c2001-12-04 21:40:53 +0000735 if (2 + self->index >= BUFFERSIZE) {
736 if (flush_data(self) < 0)
737 return -1;
738 }
Fred Drake8c081a12001-10-12 20:57:55 +0000739 self->buffer[self->index] = WHAT_LINE_TIMES;
740 self->buffer[self->index + 1] = self->linetimings ? 1 : 0;
741 self->index += 2;
Fred Drake62c1e3c2001-12-04 21:40:53 +0000742 return 0;
Fred Drake8c081a12001-10-12 20:57:55 +0000743}
744
Fred Drake62c1e3c2001-12-04 21:40:53 +0000745static int
Fred Drake30d1c752001-10-15 22:11:02 +0000746pack_frame_times(ProfilerObject *self)
747{
Fred Drake62c1e3c2001-12-04 21:40:53 +0000748 if (2 + self->index >= BUFFERSIZE) {
749 if (flush_data(self) < 0)
750 return -1;
751 }
Fred Drake30d1c752001-10-15 22:11:02 +0000752 self->buffer[self->index] = WHAT_FRAME_TIMES;
753 self->buffer[self->index + 1] = self->frametimings ? 1 : 0;
754 self->index += 2;
Fred Drake62c1e3c2001-12-04 21:40:53 +0000755 return 0;
Fred Drake30d1c752001-10-15 22:11:02 +0000756}
757
Fred Drake62c1e3c2001-12-04 21:40:53 +0000758static inline int
Fred Drake8c081a12001-10-12 20:57:55 +0000759pack_enter(ProfilerObject *self, int fileno, int tdelta, int lineno)
760{
Fred Drake62c1e3c2001-12-04 21:40:53 +0000761 if (MPISIZE + PISIZE*2 + self->index >= BUFFERSIZE) {
762 if (flush_data(self) < 0)
763 return -1;
764 }
Fred Drake8c081a12001-10-12 20:57:55 +0000765 pack_modified_packed_int(self, fileno, 2, WHAT_ENTER);
Fred Drake8c081a12001-10-12 20:57:55 +0000766 pack_packed_int(self, lineno);
Fred Drake30d1c752001-10-15 22:11:02 +0000767 if (self->frametimings)
Fred Drake62c1e3c2001-12-04 21:40:53 +0000768 return pack_packed_int(self, tdelta);
769 else
770 return 0;
Fred Drake8c081a12001-10-12 20:57:55 +0000771}
772
Fred Drake62c1e3c2001-12-04 21:40:53 +0000773static inline int
Fred Drake8c081a12001-10-12 20:57:55 +0000774pack_exit(ProfilerObject *self, int tdelta)
775{
Fred Drake62c1e3c2001-12-04 21:40:53 +0000776 if (MPISIZE + self->index >= BUFFERSIZE) {
777 if (flush_data(self) < 0)
778 return -1;
Fred Drake30d1c752001-10-15 22:11:02 +0000779 }
Fred Drake62c1e3c2001-12-04 21:40:53 +0000780 if (self->frametimings)
781 return pack_modified_packed_int(self, tdelta, 2, WHAT_EXIT);
782 self->buffer[self->index] = WHAT_EXIT;
783 self->index++;
784 return 0;
Fred Drake8c081a12001-10-12 20:57:55 +0000785}
786
Fred Drake62c1e3c2001-12-04 21:40:53 +0000787static inline int
Fred Drake8c081a12001-10-12 20:57:55 +0000788pack_lineno(ProfilerObject *self, int lineno)
789{
Fred Drake62c1e3c2001-12-04 21:40:53 +0000790 if (MPISIZE + self->index >= BUFFERSIZE) {
791 if (flush_data(self) < 0)
792 return -1;
793 }
794 return pack_modified_packed_int(self, lineno, 2, WHAT_LINENO);
Fred Drake8c081a12001-10-12 20:57:55 +0000795}
796
Fred Drake62c1e3c2001-12-04 21:40:53 +0000797static inline int
Fred Drake8c081a12001-10-12 20:57:55 +0000798pack_lineno_tdelta(ProfilerObject *self, int lineno, int tdelta)
799{
Fred Drake62c1e3c2001-12-04 21:40:53 +0000800 if (MPISIZE + PISIZE + self->index >= BUFFERSIZE) {
801 if (flush_data(self) < 0)
802 return 0;
803 }
804 if (pack_modified_packed_int(self, lineno, 2, WHAT_LINENO) < 0)
805 return -1;
806 return pack_packed_int(self, tdelta);
Fred Drake8c081a12001-10-12 20:57:55 +0000807}
808
809static inline int
810get_fileno(ProfilerObject *self, PyCodeObject *fcode)
811{
Fred Drake30d1c752001-10-15 22:11:02 +0000812 /* This is only used for ENTER events. */
813
814 PyObject *obj;
815 PyObject *dict;
Fred Drake8c081a12001-10-12 20:57:55 +0000816 int fileno;
817
Fred Drake30d1c752001-10-15 22:11:02 +0000818 obj = PyDict_GetItem(self->filemap, fcode->co_filename);
819 if (obj == NULL) {
Fred Drake8c081a12001-10-12 20:57:55 +0000820 /* first sighting of this file */
Fred Drake30d1c752001-10-15 22:11:02 +0000821 dict = PyDict_New();
822 if (dict == NULL) {
Fred Drake8c081a12001-10-12 20:57:55 +0000823 return -1;
824 }
Fred Drake30d1c752001-10-15 22:11:02 +0000825 fileno = self->next_fileno;
826 obj = Py_BuildValue("iN", fileno, dict);
827 if (obj == NULL) {
828 return -1;
829 }
830 if (PyDict_SetItem(self->filemap, fcode->co_filename, obj)) {
831 Py_DECREF(obj);
Fred Drake8c081a12001-10-12 20:57:55 +0000832 return -1;
833 }
834 self->next_fileno++;
Fred Drake30d1c752001-10-15 22:11:02 +0000835 Py_DECREF(obj);
Fred Drake62c1e3c2001-12-04 21:40:53 +0000836 if (pack_define_file(self, fileno,
837 PyString_AS_STRING(fcode->co_filename)) < 0)
838 return -1;
Fred Drake8c081a12001-10-12 20:57:55 +0000839 }
840 else {
841 /* already know this ID */
Fred Drake30d1c752001-10-15 22:11:02 +0000842 fileno = PyInt_AS_LONG(PyTuple_GET_ITEM(obj, 0));
843 dict = PyTuple_GET_ITEM(obj, 1);
844 }
845 /* make sure we save a function name for this (fileno, lineno) */
846 obj = PyInt_FromLong(fcode->co_firstlineno);
847 if (obj == NULL) {
848 /* We just won't have it saved; too bad. */
849 PyErr_Clear();
850 }
851 else {
852 PyObject *name = PyDict_GetItem(dict, obj);
853 if (name == NULL) {
Fred Drake62c1e3c2001-12-04 21:40:53 +0000854 if (pack_define_func(self, fileno, fcode->co_firstlineno,
855 PyString_AS_STRING(fcode->co_name)) < 0)
856 return -1;
Fred Drake30d1c752001-10-15 22:11:02 +0000857 if (PyDict_SetItem(dict, obj, fcode->co_name))
858 return -1;
859 }
Fred Drake8c081a12001-10-12 20:57:55 +0000860 }
861 return fileno;
862}
863
864static inline int
865get_tdelta(ProfilerObject *self)
866{
867 int tdelta;
868#ifdef MS_WIN32
869 hs_time tv;
Tim Peters7d99ff22001-10-13 07:37:52 +0000870 hs_time diff;
Fred Drake8c081a12001-10-12 20:57:55 +0000871
Tim Peters7d99ff22001-10-13 07:37:52 +0000872 GETTIMEOFDAY(&tv);
873 diff = tv - self->prev_timeofday;
874 tdelta = (int)diff;
Fred Drake8c081a12001-10-12 20:57:55 +0000875#else
876 struct timeval tv;
877
878 GETTIMEOFDAY(&tv);
879
880 if (tv.tv_sec == self->prev_timeofday.tv_sec)
881 tdelta = tv.tv_usec - self->prev_timeofday.tv_usec;
882 else
883 tdelta = ((tv.tv_sec - self->prev_timeofday.tv_sec) * 1000000
884 + tv.tv_usec);
885#endif
886 self->prev_timeofday = tv;
887 return tdelta;
888}
889
890
891/* The workhorse: the profiler callback function. */
892
893static int
894profiler_callback(ProfilerObject *self, PyFrameObject *frame, int what,
895 PyObject *arg)
896{
Fred Drake30d1c752001-10-15 22:11:02 +0000897 int tdelta = -1;
Fred Drake8c081a12001-10-12 20:57:55 +0000898 int fileno;
899
Fred Drake30d1c752001-10-15 22:11:02 +0000900 if (self->frametimings)
901 tdelta = get_tdelta(self);
Fred Drake8c081a12001-10-12 20:57:55 +0000902 switch (what) {
903 case PyTrace_CALL:
904 fileno = get_fileno(self, frame->f_code);
905 if (fileno < 0)
906 return -1;
Fred Drake62c1e3c2001-12-04 21:40:53 +0000907 if (pack_enter(self, fileno, tdelta,
908 frame->f_code->co_firstlineno) < 0)
909 return -1;
Fred Drake8c081a12001-10-12 20:57:55 +0000910 break;
911 case PyTrace_RETURN:
Fred Drake62c1e3c2001-12-04 21:40:53 +0000912 if (pack_exit(self, tdelta) < 0)
913 return -1;
Fred Drake8c081a12001-10-12 20:57:55 +0000914 break;
915 default:
916 /* should never get here */
917 break;
918 }
919 return 0;
920}
921
922
923/* Alternate callback when we want PyTrace_LINE events */
924
925static int
926tracer_callback(ProfilerObject *self, PyFrameObject *frame, int what,
927 PyObject *arg)
928{
929 int fileno;
930
Fred Drake8c081a12001-10-12 20:57:55 +0000931 switch (what) {
932 case PyTrace_CALL:
933 fileno = get_fileno(self, frame->f_code);
934 if (fileno < 0)
935 return -1;
Fred Drake62c1e3c2001-12-04 21:40:53 +0000936 return pack_enter(self, fileno,
937 self->frametimings ? get_tdelta(self) : -1,
938 frame->f_code->co_firstlineno);
939
Fred Drake8c081a12001-10-12 20:57:55 +0000940 case PyTrace_RETURN:
Fred Drake62c1e3c2001-12-04 21:40:53 +0000941 return pack_exit(self, get_tdelta(self));
942
Tim Peters1566a172001-10-12 22:08:39 +0000943 case PyTrace_LINE:
Fred Drake8c081a12001-10-12 20:57:55 +0000944 if (self->linetimings)
Fred Drake62c1e3c2001-12-04 21:40:53 +0000945 return pack_lineno_tdelta(self, frame->f_lineno, get_tdelta(self));
Fred Drake8c081a12001-10-12 20:57:55 +0000946 else
Fred Drake62c1e3c2001-12-04 21:40:53 +0000947 return pack_lineno(self, frame->f_lineno);
948
Fred Drake8c081a12001-10-12 20:57:55 +0000949 default:
950 /* ignore PyTrace_EXCEPTION */
951 break;
952 }
953 return 0;
954}
955
956
957/* A couple of useful helper functions. */
958
959#ifdef MS_WIN32
Tim Petersfeab23f2001-10-13 00:11:10 +0000960static LARGE_INTEGER frequency = {0, 0};
Fred Drake8c081a12001-10-12 20:57:55 +0000961#endif
962
963static unsigned long timeofday_diff = 0;
964static unsigned long rusage_diff = 0;
965
966static void
967calibrate(void)
968{
969 hs_time tv1, tv2;
970
971#ifdef MS_WIN32
Tim Peters7d99ff22001-10-13 07:37:52 +0000972 hs_time diff;
Fred Drake8c081a12001-10-12 20:57:55 +0000973 QueryPerformanceFrequency(&frequency);
974#endif
975
976 GETTIMEOFDAY(&tv1);
977 while (1) {
978 GETTIMEOFDAY(&tv2);
979#ifdef MS_WIN32
Tim Peters7d99ff22001-10-13 07:37:52 +0000980 diff = tv2 - tv1;
981 if (diff != 0) {
982 timeofday_diff = (unsigned long)diff;
Fred Drake8c081a12001-10-12 20:57:55 +0000983 break;
984 }
985#else
986 if (tv1.tv_sec != tv2.tv_sec || tv1.tv_usec != tv2.tv_usec) {
987 if (tv1.tv_sec == tv2.tv_sec)
988 timeofday_diff = tv2.tv_usec - tv1.tv_usec;
989 else
990 timeofday_diff = (1000000 - tv1.tv_usec) + tv2.tv_usec;
991 break;
992 }
993#endif
994 }
Jack Jansen963659a2001-10-23 22:26:16 +0000995#if defined(MS_WIN32) || defined(macintosh)
Fred Drake8c081a12001-10-12 20:57:55 +0000996 rusage_diff = -1;
997#else
998 {
999 struct rusage ru1, ru2;
1000
1001 getrusage(RUSAGE_SELF, &ru1);
1002 while (1) {
1003 getrusage(RUSAGE_SELF, &ru2);
1004 if (ru1.ru_utime.tv_sec != ru2.ru_utime.tv_sec) {
1005 rusage_diff = ((1000000 - ru1.ru_utime.tv_usec)
1006 + ru2.ru_utime.tv_usec);
1007 break;
1008 }
1009 else if (ru1.ru_utime.tv_usec != ru2.ru_utime.tv_usec) {
1010 rusage_diff = ru2.ru_utime.tv_usec - ru1.ru_utime.tv_usec;
1011 break;
1012 }
1013 else if (ru1.ru_stime.tv_sec != ru2.ru_stime.tv_sec) {
1014 rusage_diff = ((1000000 - ru1.ru_stime.tv_usec)
1015 + ru2.ru_stime.tv_usec);
1016 break;
1017 }
1018 else if (ru1.ru_stime.tv_usec != ru2.ru_stime.tv_usec) {
1019 rusage_diff = ru2.ru_stime.tv_usec - ru1.ru_stime.tv_usec;
1020 break;
1021 }
1022 }
1023 }
1024#endif
1025}
1026
1027static void
1028do_start(ProfilerObject *self)
1029{
1030 self->active = 1;
1031 GETTIMEOFDAY(&self->prev_timeofday);
1032 if (self->lineevents)
1033 PyEval_SetTrace((Py_tracefunc) tracer_callback, (PyObject *)self);
1034 else
1035 PyEval_SetProfile((Py_tracefunc) profiler_callback, (PyObject *)self);
1036}
1037
1038static void
1039do_stop(ProfilerObject *self)
1040{
1041 if (self->active) {
1042 self->active = 0;
1043 if (self->lineevents)
1044 PyEval_SetTrace(NULL, NULL);
1045 else
1046 PyEval_SetProfile(NULL, NULL);
1047 }
1048 if (self->index > 0) {
1049 /* Best effort to dump out any remaining data. */
1050 flush_data(self);
1051 }
1052}
1053
1054static int
1055is_available(ProfilerObject *self)
1056{
1057 if (self->active) {
1058 PyErr_SetString(ProfilerError, "profiler already active");
1059 return 0;
1060 }
1061 if (self->logfp == NULL) {
1062 PyErr_SetString(ProfilerError, "profiler already closed");
1063 return 0;
1064 }
1065 return 1;
1066}
1067
1068
1069/* Profiler object interface methods. */
1070
Fred Drake4c2e1af2001-10-29 20:45:57 +00001071static char addinfo__doc__[] =
1072"addinfo(key, value)\n"
1073"Insert an ADD_INFO record into the log.";
1074
1075static PyObject *
1076profiler_addinfo(ProfilerObject *self, PyObject *args)
1077{
1078 PyObject *result = NULL;
1079 char *key, *value;
1080
1081 if (PyArg_ParseTuple(args, "ss:addinfo", &key, &value)) {
1082 if (self->logfp == NULL)
1083 PyErr_SetString(ProfilerError, "profiler already closed");
1084 else {
Fred Drake62c1e3c2001-12-04 21:40:53 +00001085 if (pack_add_info(self, key, value) == 0) {
1086 result = Py_None;
1087 Py_INCREF(result);
1088 }
Fred Drake4c2e1af2001-10-29 20:45:57 +00001089 }
1090 }
1091 return result;
1092}
1093
Tim Petersfeab23f2001-10-13 00:11:10 +00001094static char close__doc__[] =
1095"close()\n"
1096"Shut down this profiler and close the log files, even if its active.";
Fred Drake8c081a12001-10-12 20:57:55 +00001097
1098static PyObject *
1099profiler_close(ProfilerObject *self, PyObject *args)
1100{
1101 PyObject *result = NULL;
1102
1103 if (PyArg_ParseTuple(args, ":close")) {
1104 do_stop(self);
1105 if (self->logfp != NULL) {
1106 fclose(self->logfp);
1107 self->logfp = NULL;
1108 }
1109 Py_INCREF(Py_None);
1110 result = Py_None;
1111 }
1112 return result;
1113}
1114
Tim Petersfeab23f2001-10-13 00:11:10 +00001115static char runcall__doc__[] =
1116"runcall(callable[, args[, kw]]) -> callable()\n"
1117"Profile a specific function call, returning the result of that call.";
Fred Drake8c081a12001-10-12 20:57:55 +00001118
1119static PyObject *
1120profiler_runcall(ProfilerObject *self, PyObject *args)
1121{
1122 PyObject *result = NULL;
1123 PyObject *callargs = NULL;
1124 PyObject *callkw = NULL;
1125 PyObject *callable;
1126
1127 if (PyArg_ParseTuple(args, "O|OO:runcall",
1128 &callable, &callargs, &callkw)) {
1129 if (is_available(self)) {
1130 do_start(self);
1131 result = PyEval_CallObjectWithKeywords(callable, callargs, callkw);
1132 do_stop(self);
1133 }
1134 }
1135 return result;
1136}
1137
Tim Petersfeab23f2001-10-13 00:11:10 +00001138static char runcode__doc__[] =
1139"runcode(code, globals[, locals])\n"
1140"Execute a code object while collecting profile data. If locals is\n"
1141"omitted, globals is used for the locals as well.";
Fred Drake8c081a12001-10-12 20:57:55 +00001142
1143static PyObject *
1144profiler_runcode(ProfilerObject *self, PyObject *args)
1145{
1146 PyObject *result = NULL;
1147 PyCodeObject *code;
1148 PyObject *globals;
1149 PyObject *locals = NULL;
1150
1151 if (PyArg_ParseTuple(args, "O!O!|O:runcode",
1152 &PyCode_Type, &code,
1153 &PyDict_Type, &globals,
1154 &locals)) {
1155 if (is_available(self)) {
1156 if (locals == NULL || locals == Py_None)
1157 locals = globals;
1158 else if (!PyDict_Check(locals)) {
1159 PyErr_SetString(PyExc_TypeError,
1160 "locals must be a dictionary or None");
1161 return NULL;
1162 }
1163 do_start(self);
1164 result = PyEval_EvalCode(code, globals, locals);
1165 do_stop(self);
1166#if 0
1167 if (!PyErr_Occurred()) {
1168 result = Py_None;
1169 Py_INCREF(result);
1170 }
1171#endif
1172 }
1173 }
1174 return result;
1175}
1176
Tim Petersfeab23f2001-10-13 00:11:10 +00001177static char start__doc__[] =
1178"start()\n"
1179"Install this profiler for the current thread.";
Fred Drake8c081a12001-10-12 20:57:55 +00001180
1181static PyObject *
1182profiler_start(ProfilerObject *self, PyObject *args)
1183{
1184 PyObject *result = NULL;
1185
1186 if (PyArg_ParseTuple(args, ":start")) {
1187 if (is_available(self))
1188 do_start(self);
1189 }
1190 return result;
1191}
1192
Tim Petersfeab23f2001-10-13 00:11:10 +00001193static char stop__doc__[] =
1194"stop()\n"
1195"Remove this profiler from the current thread.";
Fred Drake8c081a12001-10-12 20:57:55 +00001196
1197static PyObject *
1198profiler_stop(ProfilerObject *self, PyObject *args)
1199{
1200 PyObject *result = NULL;
1201
1202 if (PyArg_ParseTuple(args, ":stop")) {
1203 if (!self->active)
1204 PyErr_SetString(ProfilerError, "profiler not active");
1205 else
1206 do_stop(self);
1207 }
1208 return result;
1209}
1210
1211
1212/* Python API support. */
1213
1214static void
1215profiler_dealloc(ProfilerObject *self)
1216{
1217 do_stop(self);
1218 if (self->logfp != NULL)
1219 fclose(self->logfp);
1220 Py_XDECREF(self->filemap);
1221 Py_XDECREF(self->logfilename);
1222 PyObject_Del((PyObject *)self);
1223}
1224
1225/* Always use METH_VARARGS even though some of these could be METH_NOARGS;
1226 * this allows us to maintain compatibility with Python versions < 2.2
1227 * more easily, requiring only the changes to the dispatcher to be made.
1228 */
1229static PyMethodDef profiler_methods[] = {
Fred Drake4c2e1af2001-10-29 20:45:57 +00001230 {"addinfo", (PyCFunction)profiler_addinfo, METH_VARARGS, addinfo__doc__},
Fred Drake8c081a12001-10-12 20:57:55 +00001231 {"close", (PyCFunction)profiler_close, METH_VARARGS, close__doc__},
1232 {"runcall", (PyCFunction)profiler_runcall, METH_VARARGS, runcall__doc__},
1233 {"runcode", (PyCFunction)profiler_runcode, METH_VARARGS, runcode__doc__},
1234 {"start", (PyCFunction)profiler_start, METH_VARARGS, start__doc__},
1235 {"stop", (PyCFunction)profiler_stop, METH_VARARGS, stop__doc__},
1236 {NULL, NULL}
1237};
1238
1239/* Use a table even though there's only one "simple" member; this allows
1240 * __members__ and therefore dir() to work.
1241 */
1242static struct memberlist profiler_members[] = {
Fred Drake30d1c752001-10-15 22:11:02 +00001243 {"closed", T_INT, -1, READONLY},
1244 {"frametimings", T_LONG, offsetof(ProfilerObject, linetimings), READONLY},
1245 {"lineevents", T_LONG, offsetof(ProfilerObject, lineevents), READONLY},
1246 {"linetimings", T_LONG, offsetof(ProfilerObject, linetimings), READONLY},
Fred Drake8c081a12001-10-12 20:57:55 +00001247 {NULL}
1248};
1249
1250static PyObject *
1251profiler_getattr(ProfilerObject *self, char *name)
1252{
1253 PyObject *result;
1254 if (strcmp(name, "closed") == 0) {
1255 result = (self->logfp == NULL) ? Py_True : Py_False;
1256 Py_INCREF(result);
1257 }
1258 else {
1259 result = PyMember_Get((char *)self, profiler_members, name);
1260 if (result == NULL) {
1261 PyErr_Clear();
1262 result = Py_FindMethod(profiler_methods, (PyObject *)self, name);
1263 }
1264 }
1265 return result;
1266}
1267
1268
Tim Petersfeab23f2001-10-13 00:11:10 +00001269static char profiler_object__doc__[] =
1270"High-performance profiler object.\n"
1271"\n"
1272"Methods:\n"
1273"\n"
Fred Drake30d1c752001-10-15 22:11:02 +00001274"close(): Stop the profiler and close the log files.\n"
1275"runcall(): Run a single function call with profiling enabled.\n"
1276"runcode(): Execute a code object with profiling enabled.\n"
1277"start(): Install the profiler and return.\n"
1278"stop(): Remove the profiler.\n"
Tim Petersfeab23f2001-10-13 00:11:10 +00001279"\n"
1280"Attributes (read-only):\n"
1281"\n"
Fred Drake30d1c752001-10-15 22:11:02 +00001282"closed: True if the profiler has already been closed.\n"
1283"frametimings: True if ENTER/EXIT events collect timing information.\n"
1284"lineevents: True if SET_LINENO events are reported to the profiler.\n"
1285"linetimings: True if SET_LINENO events collect timing information.";
Fred Drake8c081a12001-10-12 20:57:55 +00001286
1287static PyTypeObject ProfilerType = {
1288 PyObject_HEAD_INIT(NULL)
1289 0, /* ob_size */
Fred Drake4c2e1af2001-10-29 20:45:57 +00001290 "_hotshot.ProfilerType", /* tp_name */
Fred Drake8c081a12001-10-12 20:57:55 +00001291 (int) sizeof(ProfilerObject), /* tp_basicsize */
1292 0, /* tp_itemsize */
1293 (destructor)profiler_dealloc, /* tp_dealloc */
1294 0, /* tp_print */
1295 (getattrfunc)profiler_getattr, /* tp_getattr */
1296 0, /* tp_setattr */
1297 0, /* tp_compare */
1298 0, /* tp_repr */
1299 0, /* tp_as_number */
1300 0, /* tp_as_sequence */
1301 0, /* tp_as_mapping */
1302 0, /* tp_hash */
1303 0, /* tp_call */
1304 0, /* tp_str */
1305 0, /* tp_getattro */
1306 0, /* tp_setattro */
1307 0, /* tp_as_buffer */
Fred Drake4c2e1af2001-10-29 20:45:57 +00001308 Py_TPFLAGS_DEFAULT, /* tp_flags */
Fred Drake8c081a12001-10-12 20:57:55 +00001309 profiler_object__doc__, /* tp_doc */
1310};
1311
1312
1313static PyMethodDef logreader_methods[] = {
1314 {"close", (PyCFunction)logreader_close, METH_VARARGS,
1315 logreader_close__doc__},
1316 {"next", (PyCFunction)logreader_next, METH_VARARGS,
1317 next__doc__},
1318 {NULL, NULL}
1319};
1320
1321static PyObject *
Fred Drake4c2e1af2001-10-29 20:45:57 +00001322logreader_getattr(LogReaderObject *self, char *name)
Fred Drake8c081a12001-10-12 20:57:55 +00001323{
Fred Drake4c2e1af2001-10-29 20:45:57 +00001324 if (strcmp(name, "info") == 0) {
1325 Py_INCREF(self->info);
1326 return self->info;
1327 }
Fred Drake8c081a12001-10-12 20:57:55 +00001328 return Py_FindMethod(logreader_methods, (PyObject *)self, name);
1329}
1330
1331
1332static char logreader__doc__[] = "\
1333logreader(filename) --> log-iterator\n\
1334Create a log-reader for the timing information file.";
1335
1336static PySequenceMethods logreader_as_sequence = {
1337 0, /* sq_length */
1338 0, /* sq_concat */
1339 0, /* sq_repeat */
1340 (intargfunc)logreader_sq_item, /* sq_item */
1341 0, /* sq_slice */
1342 0, /* sq_ass_item */
1343 0, /* sq_ass_slice */
1344 0, /* sq_contains */
1345 0, /* sq_inplace_concat */
1346 0, /* sq_inplace_repeat */
1347};
1348
1349static PyTypeObject LogReaderType = {
1350 PyObject_HEAD_INIT(NULL)
1351 0, /* ob_size */
Fred Drake4c2e1af2001-10-29 20:45:57 +00001352 "_hotshot.LogReaderType", /* tp_name */
Fred Drake8c081a12001-10-12 20:57:55 +00001353 (int) sizeof(LogReaderObject), /* tp_basicsize */
1354 0, /* tp_itemsize */
1355 (destructor)logreader_dealloc, /* tp_dealloc */
1356 0, /* tp_print */
1357 (getattrfunc)logreader_getattr, /* tp_getattr */
1358 0, /* tp_setattr */
1359 0, /* tp_compare */
1360 0, /* tp_repr */
1361 0, /* tp_as_number */
1362 &logreader_as_sequence, /* tp_as_sequence */
1363 0, /* tp_as_mapping */
1364 0, /* tp_hash */
1365 0, /* tp_call */
1366 0, /* tp_str */
1367 0, /* tp_getattro */
1368 0, /* tp_setattro */
1369 0, /* tp_as_buffer */
Fred Drake4c2e1af2001-10-29 20:45:57 +00001370 Py_TPFLAGS_DEFAULT, /* tp_flags */
Fred Drake8c081a12001-10-12 20:57:55 +00001371 logreader__doc__, /* tp_doc */
1372#if Py_TPFLAGS_HAVE_ITER
1373 0, /* tp_traverse */
1374 0, /* tp_clear */
1375 0, /* tp_richcompare */
1376 0, /* tp_weaklistoffset */
1377 (getiterfunc)logreader_tp_iter, /* tp_iter */
1378 (iternextfunc)logreader_tp_iternext,/* tp_iternext */
1379#endif
1380};
1381
1382static PyObject *
1383hotshot_logreader(PyObject *unused, PyObject *args)
1384{
1385 LogReaderObject *self = NULL;
1386 char *filename;
1387
1388 if (PyArg_ParseTuple(args, "s:logreader", &filename)) {
1389 self = PyObject_New(LogReaderObject, &LogReaderType);
1390 if (self != NULL) {
1391 self->filled = 0;
1392 self->index = 0;
Fred Drake30d1c752001-10-15 22:11:02 +00001393 self->frametimings = 1;
Fred Drake8c081a12001-10-12 20:57:55 +00001394 self->linetimings = 0;
Fred Drake4c2e1af2001-10-29 20:45:57 +00001395 self->info = NULL;
Fred Drake8c081a12001-10-12 20:57:55 +00001396 self->logfp = fopen(filename, "rb");
1397 if (self->logfp == NULL) {
1398 PyErr_SetFromErrnoWithFilename(PyExc_IOError, filename);
1399 Py_DECREF(self);
1400 self = NULL;
Fred Drake4c2e1af2001-10-29 20:45:57 +00001401 goto finally;
1402 }
1403 self->info = PyDict_New();
1404 if (self->info == NULL) {
1405 Py_DECREF(self);
1406 goto finally;
1407 }
1408 /* Aggressively attempt to load all preliminary ADD_INFO
1409 * records from the log so the info records are available
1410 * from a fresh logreader object.
1411 */
1412 logreader_refill(self);
1413 while (self->filled > self->index
1414 && self->buffer[self->index] == WHAT_ADD_INFO) {
1415 int err = unpack_add_info(self, 1);
1416 if (err) {
1417 if (err == ERR_EOF)
1418 eof_error();
1419 else
1420 PyErr_SetString(PyExc_RuntimeError,
1421 "unexpected error");
1422 break;
1423 }
1424 /* Refill agressively so we can avoid EOF during
1425 * initialization unless there's a real EOF condition
1426 * (the tp_iternext handler loops attempts to refill
1427 * and try again).
1428 */
1429 logreader_refill(self);
Fred Drake8c081a12001-10-12 20:57:55 +00001430 }
1431 }
1432 }
Fred Drake4c2e1af2001-10-29 20:45:57 +00001433 finally:
Fred Drake8c081a12001-10-12 20:57:55 +00001434 return (PyObject *) self;
1435}
1436
1437
1438/* Return a Python string that represents the version number without the
1439 * extra cruft added by revision control, even if the right options were
1440 * given to the "cvs export" command to make it not include the extra
1441 * cruft.
1442 */
1443static char *
1444get_version_string(void)
1445{
1446 static char *rcsid = "$Revision$";
1447 char *rev = rcsid;
1448 char *buffer;
1449 int i = 0;
1450
1451 while (*rev && !isdigit(*rev))
1452 ++rev;
1453 while (rev[i] != ' ' && rev[i] != '\0')
1454 ++i;
1455 buffer = malloc(i + 1);
1456 if (buffer != NULL) {
1457 memmove(buffer, rev, i);
1458 buffer[i] = '\0';
1459 }
1460 return buffer;
1461}
1462
1463/* Write out a RFC 822-style header with various useful bits of
1464 * information to make the output easier to manage.
1465 */
1466static int
1467write_header(ProfilerObject *self)
1468{
1469 char *buffer;
1470 char cwdbuffer[PATH_MAX];
1471 PyObject *temp;
1472 int i, len;
1473
1474 buffer = get_version_string();
1475 if (buffer == NULL) {
1476 PyErr_NoMemory();
1477 return -1;
1478 }
Fred Drake4c2e1af2001-10-29 20:45:57 +00001479 pack_add_info(self, "hotshot-version", buffer);
1480 pack_add_info(self, "requested-frame-timings",
1481 (self->frametimings ? "yes" : "no"));
1482 pack_add_info(self, "requested-line-events",
Fred Drake8c081a12001-10-12 20:57:55 +00001483 (self->lineevents ? "yes" : "no"));
Fred Drake4c2e1af2001-10-29 20:45:57 +00001484 pack_add_info(self, "requested-line-timings",
1485 (self->linetimings ? "yes" : "no"));
1486 pack_add_info(self, "platform", Py_GetPlatform());
1487 pack_add_info(self, "executable", Py_GetProgramFullPath());
Fred Drakef12a68c2001-11-09 15:59:36 +00001488 free(buffer);
Fred Drake8c081a12001-10-12 20:57:55 +00001489 buffer = (char *) Py_GetVersion();
1490 if (buffer == NULL)
1491 PyErr_Clear();
1492 else
Fred Drake4c2e1af2001-10-29 20:45:57 +00001493 pack_add_info(self, "executable-version", buffer);
Fred Drake8c081a12001-10-12 20:57:55 +00001494
1495#ifdef MS_WIN32
Tim Peters885d4572001-11-28 20:27:42 +00001496 PyOS_snprintf(cwdbuffer, sizeof(cwdbuffer), "%I64d", frequency.QuadPart);
Fred Drake4c2e1af2001-10-29 20:45:57 +00001497 pack_add_info(self, "reported-performance-frequency", cwdbuffer);
Fred Drake8c081a12001-10-12 20:57:55 +00001498#else
Tim Peters885d4572001-11-28 20:27:42 +00001499 PyOS_snprintf(cwdbuffer, sizeof(cwdbuffer), "%lu", rusage_diff);
Fred Drake4c2e1af2001-10-29 20:45:57 +00001500 pack_add_info(self, "observed-interval-getrusage", cwdbuffer);
Tim Peters885d4572001-11-28 20:27:42 +00001501 PyOS_snprintf(cwdbuffer, sizeof(cwdbuffer), "%lu", timeofday_diff);
Fred Drake4c2e1af2001-10-29 20:45:57 +00001502 pack_add_info(self, "observed-interval-gettimeofday", cwdbuffer);
Fred Drake8c081a12001-10-12 20:57:55 +00001503#endif
Fred Drake8c081a12001-10-12 20:57:55 +00001504
Fred Drake4c2e1af2001-10-29 20:45:57 +00001505 pack_add_info(self, "current-directory",
Fred Drake8c081a12001-10-12 20:57:55 +00001506 getcwd(cwdbuffer, sizeof cwdbuffer));
1507
1508 temp = PySys_GetObject("path");
1509 len = PyList_GET_SIZE(temp);
1510 for (i = 0; i < len; ++i) {
1511 PyObject *item = PyList_GET_ITEM(temp, i);
1512 buffer = PyString_AsString(item);
1513 if (buffer == NULL)
1514 return -1;
Fred Drake4c2e1af2001-10-29 20:45:57 +00001515 pack_add_info(self, "sys-path-entry", buffer);
Fred Drake8c081a12001-10-12 20:57:55 +00001516 }
Fred Drake4c2e1af2001-10-29 20:45:57 +00001517 pack_frame_times(self);
1518 pack_line_times(self);
1519
Fred Drake8c081a12001-10-12 20:57:55 +00001520 return 0;
1521}
1522
1523static char profiler__doc__[] = "\
1524profiler(logfilename[, lineevents[, linetimes]]) -> profiler\n\
1525Create a new profiler object.";
1526
1527static PyObject *
1528hotshot_profiler(PyObject *unused, PyObject *args)
1529{
1530 char *logfilename;
1531 ProfilerObject *self = NULL;
1532 int lineevents = 0;
1533 int linetimings = 1;
1534
1535 if (PyArg_ParseTuple(args, "s|ii:profiler", &logfilename,
1536 &lineevents, &linetimings)) {
1537 self = PyObject_New(ProfilerObject, &ProfilerType);
1538 if (self == NULL)
1539 return NULL;
Fred Drake30d1c752001-10-15 22:11:02 +00001540 self->frametimings = 1;
Fred Drake8c081a12001-10-12 20:57:55 +00001541 self->lineevents = lineevents ? 1 : 0;
1542 self->linetimings = (lineevents && linetimings) ? 1 : 0;
1543 self->index = 0;
1544 self->active = 0;
1545 self->next_fileno = 0;
Tim Peters1566a172001-10-12 22:08:39 +00001546 self->logfp = NULL;
Fred Drake8c081a12001-10-12 20:57:55 +00001547 self->logfilename = PyTuple_GET_ITEM(args, 0);
1548 Py_INCREF(self->logfilename);
1549 self->filemap = PyDict_New();
1550 if (self->filemap == NULL) {
1551 Py_DECREF(self);
1552 return NULL;
1553 }
1554 self->logfp = fopen(logfilename, "wb");
1555 if (self->logfp == NULL) {
1556 Py_DECREF(self);
1557 PyErr_SetFromErrnoWithFilename(PyExc_IOError, logfilename);
1558 return NULL;
1559 }
1560 if (timeofday_diff == 0) {
1561 /* Run this several times since sometimes the first
1562 * doesn't give the lowest values, and we're really trying
1563 * to determine the lowest.
1564 */
1565 calibrate();
1566 calibrate();
1567 calibrate();
1568 }
1569 if (write_header(self))
1570 /* some error occurred, exception has been set */
1571 self = NULL;
1572 }
1573 return (PyObject *) self;
1574}
1575
Fred Drake30d1c752001-10-15 22:11:02 +00001576static char coverage__doc__[] = "\
1577coverage(logfilename) -> profiler\n\
1578Returns a profiler that doesn't collect any timing information, which is\n\
1579useful in building a coverage analysis tool.";
1580
1581static PyObject *
1582hotshot_coverage(PyObject *unused, PyObject *args)
1583{
1584 char *logfilename;
1585 PyObject *result = NULL;
1586
1587 if (PyArg_ParseTuple(args, "s:coverage", &logfilename)) {
1588 result = hotshot_profiler(unused, args);
1589 if (result != NULL) {
1590 ProfilerObject *self = (ProfilerObject *) result;
1591 self->frametimings = 0;
1592 self->linetimings = 0;
1593 self->lineevents = 1;
1594 }
1595 }
1596 return result;
1597}
1598
Fred Drake8c081a12001-10-12 20:57:55 +00001599static char resolution__doc__[] =
1600#ifdef MS_WIN32
Tim Petersfeab23f2001-10-13 00:11:10 +00001601"resolution() -> (performance-counter-ticks, update-frequency)\n"
1602"Return the resolution of the timer provided by the QueryPerformanceCounter()\n"
1603"function. The first value is the smallest observed change, and the second\n"
1604"is the result of QueryPerformanceFrequency().";
Fred Drake8c081a12001-10-12 20:57:55 +00001605#else
Tim Petersfeab23f2001-10-13 00:11:10 +00001606"resolution() -> (gettimeofday-usecs, getrusage-usecs)\n"
1607"Return the resolution of the timers provided by the gettimeofday() and\n"
1608"getrusage() system calls, or -1 if the call is not supported.";
Fred Drake8c081a12001-10-12 20:57:55 +00001609#endif
1610
1611static PyObject *
1612hotshot_resolution(PyObject *unused, PyObject *args)
1613{
1614 PyObject *result = NULL;
1615
1616 if (PyArg_ParseTuple(args, ":resolution")) {
1617 if (timeofday_diff == 0) {
1618 calibrate();
1619 calibrate();
1620 calibrate();
1621 }
1622#ifdef MS_WIN32
1623 result = Py_BuildValue("ii", timeofday_diff, frequency.LowPart);
1624#else
1625 result = Py_BuildValue("ii", timeofday_diff, rusage_diff);
1626#endif
1627 }
1628 return result;
1629}
1630
1631
1632static PyMethodDef functions[] = {
Fred Drake30d1c752001-10-15 22:11:02 +00001633 {"coverage", hotshot_coverage, METH_VARARGS, coverage__doc__},
Fred Drake8c081a12001-10-12 20:57:55 +00001634 {"profiler", hotshot_profiler, METH_VARARGS, profiler__doc__},
1635 {"logreader", hotshot_logreader, METH_VARARGS, logreader__doc__},
1636 {"resolution", hotshot_resolution, METH_VARARGS, resolution__doc__},
1637 {NULL, NULL}
1638};
1639
1640
1641void
1642init_hotshot(void)
1643{
1644 PyObject *module;
1645
1646 LogReaderType.ob_type = &PyType_Type;
1647 ProfilerType.ob_type = &PyType_Type;
1648 module = Py_InitModule("_hotshot", functions);
1649 if (module != NULL) {
1650 char *s = get_version_string();
1651
1652 PyModule_AddStringConstant(module, "__version__", s);
1653 free(s);
1654 Py_INCREF(&LogReaderType);
1655 PyModule_AddObject(module, "LogReaderType",
1656 (PyObject *)&LogReaderType);
1657 Py_INCREF(&ProfilerType);
1658 PyModule_AddObject(module, "ProfilerType",
1659 (PyObject *)&ProfilerType);
1660
1661 if (ProfilerError == NULL)
1662 ProfilerError = PyErr_NewException("hotshot.ProfilerError",
1663 NULL, NULL);
1664 if (ProfilerError != NULL) {
1665 Py_INCREF(ProfilerError);
1666 PyModule_AddObject(module, "ProfilerError", ProfilerError);
1667 }
1668 PyModule_AddIntConstant(module, "WHAT_ENTER", WHAT_ENTER);
1669 PyModule_AddIntConstant(module, "WHAT_EXIT", WHAT_EXIT);
1670 PyModule_AddIntConstant(module, "WHAT_LINENO", WHAT_LINENO);
1671 PyModule_AddIntConstant(module, "WHAT_OTHER", WHAT_OTHER);
1672 PyModule_AddIntConstant(module, "WHAT_ADD_INFO", WHAT_ADD_INFO);
1673 PyModule_AddIntConstant(module, "WHAT_DEFINE_FILE", WHAT_DEFINE_FILE);
Fred Drake30d1c752001-10-15 22:11:02 +00001674 PyModule_AddIntConstant(module, "WHAT_DEFINE_FUNC", WHAT_DEFINE_FUNC);
Fred Drake8c081a12001-10-12 20:57:55 +00001675 PyModule_AddIntConstant(module, "WHAT_LINE_TIMES", WHAT_LINE_TIMES);
1676 }
1677}