blob: 1eecc7efcc07c8f40c7a2ae2a12dee0d0a78a5b8 [file] [log] [blame]
Fred Drake8c081a12001-10-12 20:57:55 +00001/*
2 * This is the High Performance Python Profiler portion of HotShot.
3 */
4
Tim Peters885d4572001-11-28 20:27:42 +00005#include "Python.h"
6#include "compile.h"
7#include "eval.h"
8#include "frameobject.h"
9#include "structmember.h"
Fred Drake8c081a12001-10-12 20:57:55 +000010
Fred Drake8c081a12001-10-12 20:57:55 +000011/*
12 * Which timer to use should be made more configurable, but that should not
Tim Petersfeab23f2001-10-13 00:11:10 +000013 * be difficult. This will do for now.
Fred Drake8c081a12001-10-12 20:57:55 +000014 */
15#ifdef MS_WIN32
16#include <windows.h>
Tim Peters1566a172001-10-12 22:08:39 +000017#include <direct.h> /* for getcwd() */
Tim Peters7d99ff22001-10-13 07:37:52 +000018typedef __int64 hs_time;
19#define GETTIMEOFDAY(P_HS_TIME) \
20 { LARGE_INTEGER _temp; \
21 QueryPerformanceCounter(&_temp); \
22 *(P_HS_TIME) = _temp.QuadPart; }
23
Tim Petersfeab23f2001-10-13 00:11:10 +000024
Fred Drake8c081a12001-10-12 20:57:55 +000025#else
26#ifndef HAVE_GETTIMEOFDAY
27#error "This module requires gettimeofday() on non-Windows platforms!"
28#endif
Jack Jansen963659a2001-10-23 22:26:16 +000029#ifdef macintosh
30#include <sys/time.h>
31#else
Fred Drake8c081a12001-10-12 20:57:55 +000032#include <sys/resource.h>
33#include <sys/times.h>
Jack Jansen963659a2001-10-23 22:26:16 +000034#endif
Fred Drake8c081a12001-10-12 20:57:55 +000035typedef struct timeval hs_time;
36#endif
37
38#if !defined(__cplusplus) && !defined(inline)
39#ifdef __GNUC__
40#define inline __inline
41#endif
42#endif
43
44#ifndef inline
45#define inline
46#endif
47
48#define BUFFERSIZE 10240
49
Jack Jansen963659a2001-10-23 22:26:16 +000050#ifdef macintosh
51#define PATH_MAX 254
52#endif
53
Tim Peters1566a172001-10-12 22:08:39 +000054#ifndef PATH_MAX
55# ifdef MAX_PATH
56# define PATH_MAX MAX_PATH
57# else
58# error "Need a defn. for PATH_MAX in _hotshot.c"
59# endif
60#endif
61
Fred Drake8c081a12001-10-12 20:57:55 +000062typedef struct {
63 PyObject_HEAD
64 PyObject *filemap;
65 PyObject *logfilename;
66 int index;
67 unsigned char buffer[BUFFERSIZE];
68 FILE *logfp;
69 int lineevents;
70 int linetimings;
Fred Drake30d1c752001-10-15 22:11:02 +000071 int frametimings;
Fred Drake8c081a12001-10-12 20:57:55 +000072 /* size_t filled; */
73 int active;
74 int next_fileno;
Fred Drake8c081a12001-10-12 20:57:55 +000075 hs_time prev_timeofday;
76} ProfilerObject;
77
78typedef struct {
79 PyObject_HEAD
Fred Drake4c2e1af2001-10-29 20:45:57 +000080 PyObject *info;
Fred Drake8c081a12001-10-12 20:57:55 +000081 FILE *logfp;
82 int filled;
83 int index;
84 int linetimings;
Fred Drake30d1c752001-10-15 22:11:02 +000085 int frametimings;
Fred Drake8c081a12001-10-12 20:57:55 +000086 unsigned char buffer[BUFFERSIZE];
87} LogReaderObject;
88
89static PyObject * ProfilerError = NULL;
90
91
92#ifndef MS_WIN32
93#ifdef GETTIMEOFDAY_NO_TZ
94#define GETTIMEOFDAY(ptv) gettimeofday((ptv))
95#else
96#define GETTIMEOFDAY(ptv) gettimeofday((ptv), (struct timezone *)NULL)
97#endif
98#endif
99
100
101/* The log reader... */
102
Tim Petersfeab23f2001-10-13 00:11:10 +0000103static char logreader_close__doc__[] =
104"close()\n"
105"Close the log file, preventing additional records from being read.";
Fred Drake8c081a12001-10-12 20:57:55 +0000106
107static PyObject *
108logreader_close(LogReaderObject *self, PyObject *args)
109{
110 PyObject *result = NULL;
111 if (PyArg_ParseTuple(args, ":close")) {
112 if (self->logfp != NULL) {
113 fclose(self->logfp);
114 self->logfp = NULL;
115 }
116 result = Py_None;
117 Py_INCREF(result);
118 }
119 return result;
120}
121
122#if Py_TPFLAGS_HAVE_ITER
123/* This is only used if the interpreter has iterator support; the
124 * iternext handler is also used as a helper for other functions, so
125 * does not need to be included in this conditional section.
126 */
127static PyObject *
128logreader_tp_iter(LogReaderObject *self)
129{
130 Py_INCREF(self);
131 return (PyObject *) self;
132}
133#endif
134
135
136/* Log File Format
137 * ---------------
138 *
139 * The log file consists of a sequence of variable-length records.
140 * Each record is identified with a record type identifier in two
141 * bits of the first byte. The two bits are the "least significant"
142 * bits of the byte.
143 *
144 * Low bits: Opcode: Meaning:
145 * 0x00 ENTER enter a frame
146 * 0x01 EXIT exit a frame
147 * 0x02 LINENO SET_LINENO instruction was executed
148 * 0x03 OTHER more bits are needed to deecode
149 *
150 * If the type is OTHER, the record is not packed so tightly, and the
151 * remaining bits are used to disambiguate the record type. These
152 * records are not used as frequently so compaction is not an issue.
153 * Each of the first three record types has a highly tailored
154 * structure that allows it to be packed tightly.
155 *
156 * The OTHER records have the following identifiers:
157 *
158 * First byte: Opcode: Meaning:
159 * 0x13 ADD_INFO define a key/value pair
160 * 0x23 DEFINE_FILE define an int->filename mapping
161 * 0x33 LINE_TIMES indicates if LINENO events have tdeltas
Fred Drake30d1c752001-10-15 22:11:02 +0000162 * 0x43 DEFINE_FUNC define a (fileno,lineno)->funcname mapping
163 * 0x53 FRAME_TIMES indicates if ENTER/EXIT events have tdeltas
Fred Drake8c081a12001-10-12 20:57:55 +0000164 *
165 * Packed Integers
166 *
167 * "Packed integers" are non-negative integer values encoded as a
168 * sequence of bytes. Each byte is encoded such that the most
169 * significant bit is set if the next byte is also part of the
170 * integer. Each byte provides bits to the least-significant end of
171 * the result; the accumulated value must be shifted up to place the
172 * new bits into the result.
173 *
174 * "Modified packed integers" are packed integers where only a portion
175 * of the first byte is used. In the rest of the specification, these
176 * are referred to as "MPI(n,name)", where "n" is the number of bits
177 * discarded from the least-signicant positions of the byte, and
178 * "name" is a name being given to those "discarded" bits, since they
179 * are a field themselves.
180 *
181 * ENTER records:
182 *
183 * MPI(2,type) fileno -- type is 0x00
Fred Drake8c081a12001-10-12 20:57:55 +0000184 * PI lineno
Fred Drake30d1c752001-10-15 22:11:02 +0000185 * PI tdelta -- iff frame times are enabled
Fred Drake8c081a12001-10-12 20:57:55 +0000186 *
187 * EXIT records
188 *
Fred Drake30d1c752001-10-15 22:11:02 +0000189 * MPI(2,type) tdelta -- type is 0x01; tdelta will be 0
190 * if frame times are disabled
Fred Drake8c081a12001-10-12 20:57:55 +0000191 *
192 * LINENO records
193 *
194 * MPI(2,type) lineno -- type is 0x02
195 * PI tdelta -- iff LINENO includes it
196 *
197 * ADD_INFO records
198 *
Fred Drake30d1c752001-10-15 22:11:02 +0000199 * BYTE type -- always 0x13
Fred Drake8c081a12001-10-12 20:57:55 +0000200 * PI len1 -- length of first string
201 * BYTE string1[len1] -- len1 bytes of string data
202 * PI len2 -- length of second string
203 * BYTE string2[len2] -- len2 bytes of string data
204 *
205 * DEFINE_FILE records
206 *
Fred Drake30d1c752001-10-15 22:11:02 +0000207 * BYTE type -- always 0x23
Fred Drake8c081a12001-10-12 20:57:55 +0000208 * PI fileno
209 * PI len -- length of filename
210 * BYTE filename[len] -- len bytes of string data
211 *
Fred Drake30d1c752001-10-15 22:11:02 +0000212 * DEFINE_FUNC records
213 *
214 * BYTE type -- always 0x43
215 * PI fileno
216 * PI lineno
217 * PI len -- length of funcname
218 * BYTE funcname[len] -- len bytes of string data
219 *
Fred Drake8c081a12001-10-12 20:57:55 +0000220 * LINE_TIMES records
Fred Drake30d1c752001-10-15 22:11:02 +0000221 *
222 * This record can be used only before the start of ENTER/EXIT/LINENO
223 * records. If have_tdelta is true, LINENO records will include the
224 * tdelta field, otherwise it will be omitted. If this record is not
225 * given, LINENO records will not contain the tdelta field.
226 *
227 * BYTE type -- always 0x33
Fred Drake8c081a12001-10-12 20:57:55 +0000228 * BYTE have_tdelta -- 0 if LINENO does *not* have
229 * timing information
Fred Drake30d1c752001-10-15 22:11:02 +0000230 * FRAME_TIMES records
231 *
232 * This record can be used only before the start of ENTER/EXIT/LINENO
233 * records. If have_tdelta is true, ENTER and EXIT records will
234 * include the tdelta field, otherwise it will be omitted. If this
235 * record is not given, ENTER and EXIT records will contain the tdelta
236 * field.
237 *
238 * BYTE type -- always 0x53
239 * BYTE have_tdelta -- 0 if ENTER/EXIT do *not* have
240 * timing information
Fred Drake8c081a12001-10-12 20:57:55 +0000241 */
242
243#define WHAT_ENTER 0x00
244#define WHAT_EXIT 0x01
245#define WHAT_LINENO 0x02
246#define WHAT_OTHER 0x03 /* only used in decoding */
247#define WHAT_ADD_INFO 0x13
248#define WHAT_DEFINE_FILE 0x23
249#define WHAT_LINE_TIMES 0x33
Fred Drake30d1c752001-10-15 22:11:02 +0000250#define WHAT_DEFINE_FUNC 0x43
251#define WHAT_FRAME_TIMES 0x53
Fred Drake8c081a12001-10-12 20:57:55 +0000252
253#define ERR_NONE 0
254#define ERR_EOF -1
255#define ERR_EXCEPTION -2
Fred Drake4c2e1af2001-10-29 20:45:57 +0000256#define ERR_BAD_RECTYPE -3
Fred Drake8c081a12001-10-12 20:57:55 +0000257
258#define PISIZE (sizeof(int) + 1)
259#define MPISIZE (PISIZE + 1)
260
261/* Maximum size of "normal" events -- nothing that contains string data */
262#define MAXEVENTSIZE (MPISIZE + PISIZE*2)
263
264
265/* Unpack a packed integer; if "discard" is non-zero, unpack a modified
266 * packed integer with "discard" discarded bits.
267 */
268static int
269unpack_packed_int(LogReaderObject *self, int *pvalue, int discard)
270{
271 int accum = 0;
272 int bits = 0;
273 int index = self->index;
274 int cont;
275
276 do {
277 if (index >= self->filled)
278 return ERR_EOF;
279 /* read byte */
280 accum |= ((self->buffer[index] & 0x7F) >> discard) << bits;
281 bits += (7 - discard);
282 cont = self->buffer[index] & 0x80;
283 /* move to next */
284 discard = 0;
285 index++;
286 } while (cont);
287
288 /* save state */
289 self->index = index;
290 *pvalue = accum;
291
292 return 0;
293}
294
295/* Unpack a string, which is encoded as a packed integer giving the
296 * length of the string, followed by the string data.
297 */
298static int
299unpack_string(LogReaderObject *self, PyObject **pvalue)
300{
301 int len;
302 int oldindex = self->index;
303 int err = unpack_packed_int(self, &len, 0);
304
305 if (!err) {
306 /* need at least len bytes in buffer */
307 if (len > (self->filled - self->index)) {
308 self->index = oldindex;
309 err = ERR_EOF;
310 }
311 else {
Jack Jansen963659a2001-10-23 22:26:16 +0000312 *pvalue = PyString_FromStringAndSize((char *)self->buffer + self->index,
Fred Drake8c081a12001-10-12 20:57:55 +0000313 len);
314 if (*pvalue == NULL) {
315 self->index = oldindex;
316 err = ERR_EXCEPTION;
317 }
318 else
319 self->index += len;
320 }
321 }
322 return err;
323}
324
325
Fred Drake4c2e1af2001-10-29 20:45:57 +0000326static int
327unpack_add_info(LogReaderObject *self, int skip_opcode)
328{
329 PyObject *key;
330 PyObject *value = NULL;
331 int err;
332
333 if (skip_opcode) {
334 if (self->buffer[self->index] != WHAT_ADD_INFO)
335 return ERR_BAD_RECTYPE;
336 self->index++;
337 }
338 err = unpack_string(self, &key);
339 if (!err) {
340 err = unpack_string(self, &value);
341 if (err)
342 Py_DECREF(key);
343 else {
344 PyObject *list = PyDict_GetItem(self->info, key);
345 if (list == NULL) {
346 list = PyList_New(0);
347 if (list == NULL) {
348 err = ERR_EXCEPTION;
349 goto finally;
350 }
351 if (PyDict_SetItem(self->info, key, list)) {
352 err = ERR_EXCEPTION;
353 goto finally;
354 }
355 }
356 if (PyList_Append(list, value))
357 err = ERR_EXCEPTION;
358 }
359 }
360 finally:
361 Py_XDECREF(key);
362 Py_XDECREF(value);
363 return err;
364}
365
366
367static void
368logreader_refill(LogReaderObject *self)
369{
370 int needed;
371 size_t res;
372
373 if (self->index) {
374 memmove(self->buffer, &self->buffer[self->index],
375 self->filled - self->index);
376 self->filled = self->filled - self->index;
377 self->index = 0;
378 }
379 needed = BUFFERSIZE - self->filled;
380 if (needed > 0) {
381 res = fread(&self->buffer[self->filled], 1, needed, self->logfp);
382 self->filled += res;
383 }
384}
385
386static void
387eof_error(void)
388{
389 PyErr_SetString(PyExc_EOFError,
390 "end of file with incomplete profile record");
391}
392
Fred Drake8c081a12001-10-12 20:57:55 +0000393static PyObject *
394logreader_tp_iternext(LogReaderObject *self)
395{
396 int what, oldindex;
397 int err = ERR_NONE;
398 int lineno = -1;
399 int fileno = -1;
400 int tdelta = -1;
401 PyObject *s1 = NULL, *s2 = NULL;
402 PyObject *result = NULL;
403#if 0
404 unsigned char b0, b1;
405#endif
406
407 if (self->logfp == NULL) {
408 PyErr_SetString(ProfilerError,
409 "cannot iterate over closed LogReader object");
410 return NULL;
411 }
412 restart:
Fred Drake4c2e1af2001-10-29 20:45:57 +0000413 if ((self->filled - self->index) < MAXEVENTSIZE)
414 logreader_refill(self);
415
Fred Drake8c081a12001-10-12 20:57:55 +0000416 /* end of input */
417 if (self->filled == 0)
418 return NULL;
419
420 oldindex = self->index;
421
422 /* decode the record type */
423 what = self->buffer[self->index] & WHAT_OTHER;
424 if (what == WHAT_OTHER) {
425 what = self->buffer[self->index];
426 self->index++;
427 }
428 switch (what) {
429 case WHAT_ENTER:
430 err = unpack_packed_int(self, &fileno, 2);
431 if (!err) {
Fred Drake30d1c752001-10-15 22:11:02 +0000432 err = unpack_packed_int(self, &lineno, 0);
433 if (self->frametimings && !err)
434 err = unpack_packed_int(self, &tdelta, 0);
Fred Drake8c081a12001-10-12 20:57:55 +0000435 }
436 break;
437 case WHAT_EXIT:
438 err = unpack_packed_int(self, &tdelta, 2);
439 break;
440 case WHAT_LINENO:
441 err = unpack_packed_int(self, &lineno, 2);
442 if (self->linetimings && !err)
443 err = unpack_packed_int(self, &tdelta, 0);
444 break;
445 case WHAT_ADD_INFO:
Fred Drake4c2e1af2001-10-29 20:45:57 +0000446 err = unpack_add_info(self, 0);
Fred Drake8c081a12001-10-12 20:57:55 +0000447 break;
448 case WHAT_DEFINE_FILE:
449 err = unpack_packed_int(self, &fileno, 0);
450 if (!err) {
451 err = unpack_string(self, &s1);
452 if (!err) {
453 Py_INCREF(Py_None);
454 s2 = Py_None;
455 }
456 }
457 break;
Fred Drake30d1c752001-10-15 22:11:02 +0000458 case WHAT_DEFINE_FUNC:
459 err = unpack_packed_int(self, &fileno, 0);
460 if (!err) {
461 err = unpack_packed_int(self, &lineno, 0);
462 if (!err)
463 err = unpack_string(self, &s1);
464 }
465 break;
Fred Drake8c081a12001-10-12 20:57:55 +0000466 case WHAT_LINE_TIMES:
467 if (self->index >= self->filled)
468 err = ERR_EOF;
469 else {
470 self->linetimings = self->buffer[self->index] ? 1 : 0;
471 self->index++;
472 goto restart;
473 }
Fred Drake4c2e1af2001-10-29 20:45:57 +0000474 break;
Fred Drake30d1c752001-10-15 22:11:02 +0000475 case WHAT_FRAME_TIMES:
476 if (self->index >= self->filled)
477 err = ERR_EOF;
478 else {
479 self->frametimings = self->buffer[self->index] ? 1 : 0;
480 self->index++;
481 goto restart;
482 }
Fred Drake4c2e1af2001-10-29 20:45:57 +0000483 break;
Fred Drake8c081a12001-10-12 20:57:55 +0000484 default:
Fred Drake4c2e1af2001-10-29 20:45:57 +0000485 err = ERR_BAD_RECTYPE;
Fred Drake8c081a12001-10-12 20:57:55 +0000486 }
487 if (err == ERR_EOF && oldindex != 0) {
488 /* It looks like we ran out of data before we had it all; this
489 * could easily happen with large packed integers or string
490 * data. Try forcing the buffer to be re-filled before failing.
491 */
492 err = ERR_NONE;
Fred Drake4c2e1af2001-10-29 20:45:57 +0000493 logreader_refill(self);
Fred Drake8c081a12001-10-12 20:57:55 +0000494 }
Fred Drake4c2e1af2001-10-29 20:45:57 +0000495 if (err == ERR_BAD_RECTYPE) {
496 PyErr_SetString(PyExc_ValueError,
497 "unknown record type in log file");
498 }
499 else if (err == ERR_EOF) {
Fred Drake8c081a12001-10-12 20:57:55 +0000500 /* Could not avoid end-of-buffer error. */
Fred Drake4c2e1af2001-10-29 20:45:57 +0000501 eof_error();
Fred Drake8c081a12001-10-12 20:57:55 +0000502 }
503 else if (!err) {
504 result = PyTuple_New(4);
505 PyTuple_SET_ITEM(result, 0, PyInt_FromLong(what));
506 PyTuple_SET_ITEM(result, 2, PyInt_FromLong(fileno));
Fred Drake30d1c752001-10-15 22:11:02 +0000507 if (s1 == NULL)
Fred Drake8c081a12001-10-12 20:57:55 +0000508 PyTuple_SET_ITEM(result, 1, PyInt_FromLong(tdelta));
Fred Drake30d1c752001-10-15 22:11:02 +0000509 else
Fred Drake8c081a12001-10-12 20:57:55 +0000510 PyTuple_SET_ITEM(result, 1, s1);
Fred Drake30d1c752001-10-15 22:11:02 +0000511 if (s2 == NULL)
512 PyTuple_SET_ITEM(result, 3, PyInt_FromLong(lineno));
513 else
Fred Drake8c081a12001-10-12 20:57:55 +0000514 PyTuple_SET_ITEM(result, 3, s2);
Fred Drake8c081a12001-10-12 20:57:55 +0000515 }
516 /* The only other case is err == ERR_EXCEPTION, in which case the
517 * exception is already set.
518 */
519#if 0
520 b0 = self->buffer[self->index];
521 b1 = self->buffer[self->index + 1];
522 if (b0 & 1) {
523 /* This is a line-number event. */
524 what = PyTrace_LINE;
525 lineno = ((b0 & ~1) << 7) + b1;
526 self->index += 2;
527 }
528 else {
529 what = (b0 & 0x0E) >> 1;
530 tdelta = ((b0 & 0xF0) << 4) + b1;
531 if (what == PyTrace_CALL) {
532 /* we know there's a 2-byte file ID & 2-byte line number */
533 fileno = ((self->buffer[self->index + 2] << 8)
534 + self->buffer[self->index + 3]);
535 lineno = ((self->buffer[self->index + 4] << 8)
536 + self->buffer[self->index + 5]);
537 self->index += 6;
538 }
539 else
540 self->index += 2;
541 }
542#endif
543 return result;
544}
545
546static void
547logreader_dealloc(LogReaderObject *self)
548{
549 if (self->logfp != NULL) {
550 fclose(self->logfp);
551 self->logfp = NULL;
552 }
553 PyObject_Del(self);
554}
555
556static PyObject *
557logreader_sq_item(LogReaderObject *self, int index)
558{
559 PyObject *result = logreader_tp_iternext(self);
560 if (result == NULL && !PyErr_Occurred()) {
561 PyErr_SetString(PyExc_IndexError, "no more events in log");
562 return NULL;
563 }
564 return result;
565}
566
Tim Petersfeab23f2001-10-13 00:11:10 +0000567static char next__doc__[] =
568"next() -> event-info\n"
569"Return the next event record from the log file.";
Fred Drake8c081a12001-10-12 20:57:55 +0000570
571static PyObject *
572logreader_next(LogReaderObject *self, PyObject *args)
573{
574 PyObject *result = NULL;
575
576 if (PyArg_ParseTuple(args, ":next")) {
577 result = logreader_tp_iternext(self);
578 /* XXX return None if there's nothing left */
579 /* tp_iternext does the right thing, though */
580 if (result == NULL && !PyErr_Occurred()) {
581 result = Py_None;
582 Py_INCREF(result);
583 }
584 }
585 return result;
586}
587
Fred Drake62c1e3c2001-12-04 21:40:53 +0000588static void
589do_stop(ProfilerObject *self);
Fred Drake8c081a12001-10-12 20:57:55 +0000590
591static int
592flush_data(ProfilerObject *self)
593{
594 /* Need to dump data to the log file... */
595 size_t written = fwrite(self->buffer, 1, self->index, self->logfp);
Tim Peters1566a172001-10-12 22:08:39 +0000596 if (written == (size_t)self->index)
Fred Drake8c081a12001-10-12 20:57:55 +0000597 self->index = 0;
598 else {
599 memmove(self->buffer, &self->buffer[written],
600 self->index - written);
601 self->index -= written;
602 if (written == 0) {
603 char *s = PyString_AsString(self->logfilename);
604 PyErr_SetFromErrnoWithFilename(PyExc_IOError, s);
Fred Drake62c1e3c2001-12-04 21:40:53 +0000605 do_stop(self);
Fred Drake8c081a12001-10-12 20:57:55 +0000606 return -1;
607 }
608 }
609 if (written > 0) {
610 if (fflush(self->logfp)) {
611 char *s = PyString_AsString(self->logfilename);
612 PyErr_SetFromErrnoWithFilename(PyExc_IOError, s);
Fred Drake62c1e3c2001-12-04 21:40:53 +0000613 do_stop(self);
Fred Drake8c081a12001-10-12 20:57:55 +0000614 return -1;
615 }
616 }
617 return 0;
618}
619
Fred Drake62c1e3c2001-12-04 21:40:53 +0000620static inline int
Fred Drake8c081a12001-10-12 20:57:55 +0000621pack_packed_int(ProfilerObject *self, int value)
622{
623 unsigned char partial;
624
625 do {
626 partial = value & 0x7F;
627 value >>= 7;
628 if (value)
629 partial |= 0x80;
630 self->buffer[self->index] = partial;
631 self->index++;
632 } while (value);
Fred Drake62c1e3c2001-12-04 21:40:53 +0000633 return 0;
Fred Drake8c081a12001-10-12 20:57:55 +0000634}
635
636/* Encode a modified packed integer, with a subfield of modsize bits
637 * containing the value "subfield". The value of subfield is not
638 * checked to ensure it actually fits in modsize bits.
639 */
Fred Drake62c1e3c2001-12-04 21:40:53 +0000640static inline int
Fred Drake8c081a12001-10-12 20:57:55 +0000641pack_modified_packed_int(ProfilerObject *self, int value,
642 int modsize, int subfield)
643{
644 const int maxvalues[] = {-1, 1, 3, 7, 15, 31, 63, 127};
645
646 int bits = 7 - modsize;
647 int partial = value & maxvalues[bits];
648 unsigned char b = subfield | (partial << modsize);
649
650 if (partial != value) {
651 b |= 0x80;
652 self->buffer[self->index] = b;
653 self->index++;
Fred Drake62c1e3c2001-12-04 21:40:53 +0000654 return pack_packed_int(self, value >> bits);
Fred Drake8c081a12001-10-12 20:57:55 +0000655 }
Fred Drake62c1e3c2001-12-04 21:40:53 +0000656 self->buffer[self->index] = b;
657 self->index++;
658 return 0;
Fred Drake8c081a12001-10-12 20:57:55 +0000659}
660
Fred Drake62c1e3c2001-12-04 21:40:53 +0000661static int
Fred Drake30d1c752001-10-15 22:11:02 +0000662pack_string(ProfilerObject *self, const char *s, int len)
Fred Drake8c081a12001-10-12 20:57:55 +0000663{
Fred Drake62c1e3c2001-12-04 21:40:53 +0000664 if (len + PISIZE + self->index >= BUFFERSIZE) {
665 if (flush_data(self) < 0)
666 return -1;
667 }
668 if (pack_packed_int(self, len) < 0)
669 return -1;
Fred Drake8c081a12001-10-12 20:57:55 +0000670 memcpy(self->buffer + self->index, s, len);
671 self->index += len;
Fred Drake62c1e3c2001-12-04 21:40:53 +0000672 return 0;
Fred Drake8c081a12001-10-12 20:57:55 +0000673}
674
Fred Drake62c1e3c2001-12-04 21:40:53 +0000675static int
Fred Drake8c081a12001-10-12 20:57:55 +0000676pack_add_info(ProfilerObject *self, const char *s1, const char *s2)
677{
678 int len1 = strlen(s1);
679 int len2 = strlen(s2);
680
Fred Drake62c1e3c2001-12-04 21:40:53 +0000681 if (len1 + len2 + PISIZE*2 + 1 + self->index >= BUFFERSIZE) {
682 if (flush_data(self) < 0)
683 return -1;
684 }
Fred Drake8c081a12001-10-12 20:57:55 +0000685 self->buffer[self->index] = WHAT_ADD_INFO;
686 self->index++;
Fred Drake62c1e3c2001-12-04 21:40:53 +0000687 if (pack_string(self, s1, len1) < 0)
688 return -1;
689 return pack_string(self, s2, len2);
Fred Drake8c081a12001-10-12 20:57:55 +0000690}
691
Fred Drake62c1e3c2001-12-04 21:40:53 +0000692static int
Fred Drake8c081a12001-10-12 20:57:55 +0000693pack_define_file(ProfilerObject *self, int fileno, const char *filename)
694{
695 int len = strlen(filename);
696
Fred Drake62c1e3c2001-12-04 21:40:53 +0000697 if (len + PISIZE*2 + 1 + self->index >= BUFFERSIZE) {
698 if (flush_data(self) < 0)
699 return -1;
700 }
Fred Drake8c081a12001-10-12 20:57:55 +0000701 self->buffer[self->index] = WHAT_DEFINE_FILE;
702 self->index++;
Fred Drake62c1e3c2001-12-04 21:40:53 +0000703 if (pack_packed_int(self, fileno) < 0)
704 return -1;
705 return pack_string(self, filename, len);
Fred Drake30d1c752001-10-15 22:11:02 +0000706}
707
Fred Drake62c1e3c2001-12-04 21:40:53 +0000708static int
Fred Drake30d1c752001-10-15 22:11:02 +0000709pack_define_func(ProfilerObject *self, int fileno, int lineno,
710 const char *funcname)
711{
712 int len = strlen(funcname);
713
Fred Drake62c1e3c2001-12-04 21:40:53 +0000714 if (len + PISIZE*3 + 1 + self->index >= BUFFERSIZE) {
715 if (flush_data(self) < 0)
716 return -1;
717 }
Fred Drake30d1c752001-10-15 22:11:02 +0000718 self->buffer[self->index] = WHAT_DEFINE_FUNC;
719 self->index++;
Fred Drake62c1e3c2001-12-04 21:40:53 +0000720 if (pack_packed_int(self, fileno) < 0)
721 return -1;
722 if (pack_packed_int(self, lineno) < 0)
723 return -1;
724 return pack_string(self, funcname, len);
Fred Drake8c081a12001-10-12 20:57:55 +0000725}
726
Fred Drake62c1e3c2001-12-04 21:40:53 +0000727static int
Fred Drake8c081a12001-10-12 20:57:55 +0000728pack_line_times(ProfilerObject *self)
729{
Fred Drake62c1e3c2001-12-04 21:40:53 +0000730 if (2 + self->index >= BUFFERSIZE) {
731 if (flush_data(self) < 0)
732 return -1;
733 }
Fred Drake8c081a12001-10-12 20:57:55 +0000734 self->buffer[self->index] = WHAT_LINE_TIMES;
735 self->buffer[self->index + 1] = self->linetimings ? 1 : 0;
736 self->index += 2;
Fred Drake62c1e3c2001-12-04 21:40:53 +0000737 return 0;
Fred Drake8c081a12001-10-12 20:57:55 +0000738}
739
Fred Drake62c1e3c2001-12-04 21:40:53 +0000740static int
Fred Drake30d1c752001-10-15 22:11:02 +0000741pack_frame_times(ProfilerObject *self)
742{
Fred Drake62c1e3c2001-12-04 21:40:53 +0000743 if (2 + self->index >= BUFFERSIZE) {
744 if (flush_data(self) < 0)
745 return -1;
746 }
Fred Drake30d1c752001-10-15 22:11:02 +0000747 self->buffer[self->index] = WHAT_FRAME_TIMES;
748 self->buffer[self->index + 1] = self->frametimings ? 1 : 0;
749 self->index += 2;
Fred Drake62c1e3c2001-12-04 21:40:53 +0000750 return 0;
Fred Drake30d1c752001-10-15 22:11:02 +0000751}
752
Fred Drake62c1e3c2001-12-04 21:40:53 +0000753static inline int
Fred Drake8c081a12001-10-12 20:57:55 +0000754pack_enter(ProfilerObject *self, int fileno, int tdelta, int lineno)
755{
Fred Drake62c1e3c2001-12-04 21:40:53 +0000756 if (MPISIZE + PISIZE*2 + self->index >= BUFFERSIZE) {
757 if (flush_data(self) < 0)
758 return -1;
759 }
Fred Drake8c081a12001-10-12 20:57:55 +0000760 pack_modified_packed_int(self, fileno, 2, WHAT_ENTER);
Fred Drake8c081a12001-10-12 20:57:55 +0000761 pack_packed_int(self, lineno);
Fred Drake30d1c752001-10-15 22:11:02 +0000762 if (self->frametimings)
Fred Drake62c1e3c2001-12-04 21:40:53 +0000763 return pack_packed_int(self, tdelta);
764 else
765 return 0;
Fred Drake8c081a12001-10-12 20:57:55 +0000766}
767
Fred Drake62c1e3c2001-12-04 21:40:53 +0000768static inline int
Fred Drake8c081a12001-10-12 20:57:55 +0000769pack_exit(ProfilerObject *self, int tdelta)
770{
Fred Drake62c1e3c2001-12-04 21:40:53 +0000771 if (MPISIZE + self->index >= BUFFERSIZE) {
772 if (flush_data(self) < 0)
773 return -1;
Fred Drake30d1c752001-10-15 22:11:02 +0000774 }
Fred Drake62c1e3c2001-12-04 21:40:53 +0000775 if (self->frametimings)
776 return pack_modified_packed_int(self, tdelta, 2, WHAT_EXIT);
777 self->buffer[self->index] = WHAT_EXIT;
778 self->index++;
779 return 0;
Fred Drake8c081a12001-10-12 20:57:55 +0000780}
781
Fred Drake62c1e3c2001-12-04 21:40:53 +0000782static inline int
Fred Drake8c081a12001-10-12 20:57:55 +0000783pack_lineno(ProfilerObject *self, int lineno)
784{
Fred Drake62c1e3c2001-12-04 21:40:53 +0000785 if (MPISIZE + self->index >= BUFFERSIZE) {
786 if (flush_data(self) < 0)
787 return -1;
788 }
789 return pack_modified_packed_int(self, lineno, 2, WHAT_LINENO);
Fred Drake8c081a12001-10-12 20:57:55 +0000790}
791
Fred Drake62c1e3c2001-12-04 21:40:53 +0000792static inline int
Fred Drake8c081a12001-10-12 20:57:55 +0000793pack_lineno_tdelta(ProfilerObject *self, int lineno, int tdelta)
794{
Fred Drake62c1e3c2001-12-04 21:40:53 +0000795 if (MPISIZE + PISIZE + self->index >= BUFFERSIZE) {
796 if (flush_data(self) < 0)
797 return 0;
798 }
799 if (pack_modified_packed_int(self, lineno, 2, WHAT_LINENO) < 0)
800 return -1;
801 return pack_packed_int(self, tdelta);
Fred Drake8c081a12001-10-12 20:57:55 +0000802}
803
804static inline int
805get_fileno(ProfilerObject *self, PyCodeObject *fcode)
806{
Fred Drake30d1c752001-10-15 22:11:02 +0000807 /* This is only used for ENTER events. */
808
809 PyObject *obj;
810 PyObject *dict;
Fred Drake8c081a12001-10-12 20:57:55 +0000811 int fileno;
812
Fred Drake30d1c752001-10-15 22:11:02 +0000813 obj = PyDict_GetItem(self->filemap, fcode->co_filename);
814 if (obj == NULL) {
Fred Drake8c081a12001-10-12 20:57:55 +0000815 /* first sighting of this file */
Fred Drake30d1c752001-10-15 22:11:02 +0000816 dict = PyDict_New();
817 if (dict == NULL) {
Fred Drake8c081a12001-10-12 20:57:55 +0000818 return -1;
819 }
Fred Drake30d1c752001-10-15 22:11:02 +0000820 fileno = self->next_fileno;
821 obj = Py_BuildValue("iN", fileno, dict);
822 if (obj == NULL) {
823 return -1;
824 }
825 if (PyDict_SetItem(self->filemap, fcode->co_filename, obj)) {
826 Py_DECREF(obj);
Fred Drake8c081a12001-10-12 20:57:55 +0000827 return -1;
828 }
829 self->next_fileno++;
Fred Drake30d1c752001-10-15 22:11:02 +0000830 Py_DECREF(obj);
Fred Drake62c1e3c2001-12-04 21:40:53 +0000831 if (pack_define_file(self, fileno,
832 PyString_AS_STRING(fcode->co_filename)) < 0)
833 return -1;
Fred Drake8c081a12001-10-12 20:57:55 +0000834 }
835 else {
836 /* already know this ID */
Fred Drake30d1c752001-10-15 22:11:02 +0000837 fileno = PyInt_AS_LONG(PyTuple_GET_ITEM(obj, 0));
838 dict = PyTuple_GET_ITEM(obj, 1);
839 }
840 /* make sure we save a function name for this (fileno, lineno) */
841 obj = PyInt_FromLong(fcode->co_firstlineno);
842 if (obj == NULL) {
843 /* We just won't have it saved; too bad. */
844 PyErr_Clear();
845 }
846 else {
847 PyObject *name = PyDict_GetItem(dict, obj);
848 if (name == NULL) {
Fred Drake62c1e3c2001-12-04 21:40:53 +0000849 if (pack_define_func(self, fileno, fcode->co_firstlineno,
850 PyString_AS_STRING(fcode->co_name)) < 0)
851 return -1;
Fred Drake30d1c752001-10-15 22:11:02 +0000852 if (PyDict_SetItem(dict, obj, fcode->co_name))
853 return -1;
854 }
Fred Drake8c081a12001-10-12 20:57:55 +0000855 }
856 return fileno;
857}
858
859static inline int
860get_tdelta(ProfilerObject *self)
861{
862 int tdelta;
863#ifdef MS_WIN32
864 hs_time tv;
Tim Peters7d99ff22001-10-13 07:37:52 +0000865 hs_time diff;
Fred Drake8c081a12001-10-12 20:57:55 +0000866
Tim Peters7d99ff22001-10-13 07:37:52 +0000867 GETTIMEOFDAY(&tv);
868 diff = tv - self->prev_timeofday;
869 tdelta = (int)diff;
Fred Drake8c081a12001-10-12 20:57:55 +0000870#else
871 struct timeval tv;
872
873 GETTIMEOFDAY(&tv);
874
875 if (tv.tv_sec == self->prev_timeofday.tv_sec)
876 tdelta = tv.tv_usec - self->prev_timeofday.tv_usec;
877 else
878 tdelta = ((tv.tv_sec - self->prev_timeofday.tv_sec) * 1000000
879 + tv.tv_usec);
880#endif
881 self->prev_timeofday = tv;
882 return tdelta;
883}
884
885
886/* The workhorse: the profiler callback function. */
887
888static int
889profiler_callback(ProfilerObject *self, PyFrameObject *frame, int what,
890 PyObject *arg)
891{
Fred Drake30d1c752001-10-15 22:11:02 +0000892 int tdelta = -1;
Fred Drake8c081a12001-10-12 20:57:55 +0000893 int fileno;
894
Fred Drake30d1c752001-10-15 22:11:02 +0000895 if (self->frametimings)
896 tdelta = get_tdelta(self);
Fred Drake8c081a12001-10-12 20:57:55 +0000897 switch (what) {
898 case PyTrace_CALL:
899 fileno = get_fileno(self, frame->f_code);
900 if (fileno < 0)
901 return -1;
Fred Drake62c1e3c2001-12-04 21:40:53 +0000902 if (pack_enter(self, fileno, tdelta,
903 frame->f_code->co_firstlineno) < 0)
904 return -1;
Fred Drake8c081a12001-10-12 20:57:55 +0000905 break;
906 case PyTrace_RETURN:
Fred Drake62c1e3c2001-12-04 21:40:53 +0000907 if (pack_exit(self, tdelta) < 0)
908 return -1;
Fred Drake8c081a12001-10-12 20:57:55 +0000909 break;
910 default:
911 /* should never get here */
912 break;
913 }
914 return 0;
915}
916
917
918/* Alternate callback when we want PyTrace_LINE events */
919
920static int
921tracer_callback(ProfilerObject *self, PyFrameObject *frame, int what,
922 PyObject *arg)
923{
924 int fileno;
925
Fred Drake8c081a12001-10-12 20:57:55 +0000926 switch (what) {
927 case PyTrace_CALL:
928 fileno = get_fileno(self, frame->f_code);
929 if (fileno < 0)
930 return -1;
Fred Drake62c1e3c2001-12-04 21:40:53 +0000931 return pack_enter(self, fileno,
932 self->frametimings ? get_tdelta(self) : -1,
933 frame->f_code->co_firstlineno);
934
Fred Drake8c081a12001-10-12 20:57:55 +0000935 case PyTrace_RETURN:
Fred Drake62c1e3c2001-12-04 21:40:53 +0000936 return pack_exit(self, get_tdelta(self));
937
Tim Peters1566a172001-10-12 22:08:39 +0000938 case PyTrace_LINE:
Fred Drake8c081a12001-10-12 20:57:55 +0000939 if (self->linetimings)
Fred Drake62c1e3c2001-12-04 21:40:53 +0000940 return pack_lineno_tdelta(self, frame->f_lineno, get_tdelta(self));
Fred Drake8c081a12001-10-12 20:57:55 +0000941 else
Fred Drake62c1e3c2001-12-04 21:40:53 +0000942 return pack_lineno(self, frame->f_lineno);
943
Fred Drake8c081a12001-10-12 20:57:55 +0000944 default:
945 /* ignore PyTrace_EXCEPTION */
946 break;
947 }
948 return 0;
949}
950
951
952/* A couple of useful helper functions. */
953
954#ifdef MS_WIN32
Tim Petersfeab23f2001-10-13 00:11:10 +0000955static LARGE_INTEGER frequency = {0, 0};
Fred Drake8c081a12001-10-12 20:57:55 +0000956#endif
957
958static unsigned long timeofday_diff = 0;
959static unsigned long rusage_diff = 0;
960
961static void
962calibrate(void)
963{
964 hs_time tv1, tv2;
965
966#ifdef MS_WIN32
Tim Peters7d99ff22001-10-13 07:37:52 +0000967 hs_time diff;
Fred Drake8c081a12001-10-12 20:57:55 +0000968 QueryPerformanceFrequency(&frequency);
969#endif
970
971 GETTIMEOFDAY(&tv1);
972 while (1) {
973 GETTIMEOFDAY(&tv2);
974#ifdef MS_WIN32
Tim Peters7d99ff22001-10-13 07:37:52 +0000975 diff = tv2 - tv1;
976 if (diff != 0) {
977 timeofday_diff = (unsigned long)diff;
Fred Drake8c081a12001-10-12 20:57:55 +0000978 break;
979 }
980#else
981 if (tv1.tv_sec != tv2.tv_sec || tv1.tv_usec != tv2.tv_usec) {
982 if (tv1.tv_sec == tv2.tv_sec)
983 timeofday_diff = tv2.tv_usec - tv1.tv_usec;
984 else
985 timeofday_diff = (1000000 - tv1.tv_usec) + tv2.tv_usec;
986 break;
987 }
988#endif
989 }
Jack Jansen963659a2001-10-23 22:26:16 +0000990#if defined(MS_WIN32) || defined(macintosh)
Fred Drake8c081a12001-10-12 20:57:55 +0000991 rusage_diff = -1;
992#else
993 {
994 struct rusage ru1, ru2;
995
996 getrusage(RUSAGE_SELF, &ru1);
997 while (1) {
998 getrusage(RUSAGE_SELF, &ru2);
999 if (ru1.ru_utime.tv_sec != ru2.ru_utime.tv_sec) {
1000 rusage_diff = ((1000000 - ru1.ru_utime.tv_usec)
1001 + ru2.ru_utime.tv_usec);
1002 break;
1003 }
1004 else if (ru1.ru_utime.tv_usec != ru2.ru_utime.tv_usec) {
1005 rusage_diff = ru2.ru_utime.tv_usec - ru1.ru_utime.tv_usec;
1006 break;
1007 }
1008 else if (ru1.ru_stime.tv_sec != ru2.ru_stime.tv_sec) {
1009 rusage_diff = ((1000000 - ru1.ru_stime.tv_usec)
1010 + ru2.ru_stime.tv_usec);
1011 break;
1012 }
1013 else if (ru1.ru_stime.tv_usec != ru2.ru_stime.tv_usec) {
1014 rusage_diff = ru2.ru_stime.tv_usec - ru1.ru_stime.tv_usec;
1015 break;
1016 }
1017 }
1018 }
1019#endif
1020}
1021
1022static void
1023do_start(ProfilerObject *self)
1024{
1025 self->active = 1;
1026 GETTIMEOFDAY(&self->prev_timeofday);
1027 if (self->lineevents)
1028 PyEval_SetTrace((Py_tracefunc) tracer_callback, (PyObject *)self);
1029 else
1030 PyEval_SetProfile((Py_tracefunc) profiler_callback, (PyObject *)self);
1031}
1032
1033static void
1034do_stop(ProfilerObject *self)
1035{
1036 if (self->active) {
1037 self->active = 0;
1038 if (self->lineevents)
1039 PyEval_SetTrace(NULL, NULL);
1040 else
1041 PyEval_SetProfile(NULL, NULL);
1042 }
1043 if (self->index > 0) {
1044 /* Best effort to dump out any remaining data. */
1045 flush_data(self);
1046 }
1047}
1048
1049static int
1050is_available(ProfilerObject *self)
1051{
1052 if (self->active) {
1053 PyErr_SetString(ProfilerError, "profiler already active");
1054 return 0;
1055 }
1056 if (self->logfp == NULL) {
1057 PyErr_SetString(ProfilerError, "profiler already closed");
1058 return 0;
1059 }
1060 return 1;
1061}
1062
1063
1064/* Profiler object interface methods. */
1065
Fred Drake4c2e1af2001-10-29 20:45:57 +00001066static char addinfo__doc__[] =
1067"addinfo(key, value)\n"
1068"Insert an ADD_INFO record into the log.";
1069
1070static PyObject *
1071profiler_addinfo(ProfilerObject *self, PyObject *args)
1072{
1073 PyObject *result = NULL;
1074 char *key, *value;
1075
1076 if (PyArg_ParseTuple(args, "ss:addinfo", &key, &value)) {
1077 if (self->logfp == NULL)
1078 PyErr_SetString(ProfilerError, "profiler already closed");
1079 else {
Fred Drake62c1e3c2001-12-04 21:40:53 +00001080 if (pack_add_info(self, key, value) == 0) {
1081 result = Py_None;
1082 Py_INCREF(result);
1083 }
Fred Drake4c2e1af2001-10-29 20:45:57 +00001084 }
1085 }
1086 return result;
1087}
1088
Tim Petersfeab23f2001-10-13 00:11:10 +00001089static char close__doc__[] =
1090"close()\n"
1091"Shut down this profiler and close the log files, even if its active.";
Fred Drake8c081a12001-10-12 20:57:55 +00001092
1093static PyObject *
1094profiler_close(ProfilerObject *self, PyObject *args)
1095{
1096 PyObject *result = NULL;
1097
1098 if (PyArg_ParseTuple(args, ":close")) {
1099 do_stop(self);
1100 if (self->logfp != NULL) {
1101 fclose(self->logfp);
1102 self->logfp = NULL;
1103 }
1104 Py_INCREF(Py_None);
1105 result = Py_None;
1106 }
1107 return result;
1108}
1109
Tim Petersfeab23f2001-10-13 00:11:10 +00001110static char runcall__doc__[] =
1111"runcall(callable[, args[, kw]]) -> callable()\n"
1112"Profile a specific function call, returning the result of that call.";
Fred Drake8c081a12001-10-12 20:57:55 +00001113
1114static PyObject *
1115profiler_runcall(ProfilerObject *self, PyObject *args)
1116{
1117 PyObject *result = NULL;
1118 PyObject *callargs = NULL;
1119 PyObject *callkw = NULL;
1120 PyObject *callable;
1121
1122 if (PyArg_ParseTuple(args, "O|OO:runcall",
1123 &callable, &callargs, &callkw)) {
1124 if (is_available(self)) {
1125 do_start(self);
1126 result = PyEval_CallObjectWithKeywords(callable, callargs, callkw);
1127 do_stop(self);
1128 }
1129 }
1130 return result;
1131}
1132
Tim Petersfeab23f2001-10-13 00:11:10 +00001133static char runcode__doc__[] =
1134"runcode(code, globals[, locals])\n"
1135"Execute a code object while collecting profile data. If locals is\n"
1136"omitted, globals is used for the locals as well.";
Fred Drake8c081a12001-10-12 20:57:55 +00001137
1138static PyObject *
1139profiler_runcode(ProfilerObject *self, PyObject *args)
1140{
1141 PyObject *result = NULL;
1142 PyCodeObject *code;
1143 PyObject *globals;
1144 PyObject *locals = NULL;
1145
1146 if (PyArg_ParseTuple(args, "O!O!|O:runcode",
1147 &PyCode_Type, &code,
1148 &PyDict_Type, &globals,
1149 &locals)) {
1150 if (is_available(self)) {
1151 if (locals == NULL || locals == Py_None)
1152 locals = globals;
1153 else if (!PyDict_Check(locals)) {
1154 PyErr_SetString(PyExc_TypeError,
1155 "locals must be a dictionary or None");
1156 return NULL;
1157 }
1158 do_start(self);
1159 result = PyEval_EvalCode(code, globals, locals);
1160 do_stop(self);
1161#if 0
1162 if (!PyErr_Occurred()) {
1163 result = Py_None;
1164 Py_INCREF(result);
1165 }
1166#endif
1167 }
1168 }
1169 return result;
1170}
1171
Tim Petersfeab23f2001-10-13 00:11:10 +00001172static char start__doc__[] =
1173"start()\n"
1174"Install this profiler for the current thread.";
Fred Drake8c081a12001-10-12 20:57:55 +00001175
1176static PyObject *
1177profiler_start(ProfilerObject *self, PyObject *args)
1178{
1179 PyObject *result = NULL;
1180
1181 if (PyArg_ParseTuple(args, ":start")) {
Fred Drake2c146bf2002-02-08 21:27:50 +00001182 if (is_available(self)) {
Fred Drake8c081a12001-10-12 20:57:55 +00001183 do_start(self);
Fred Drake2c146bf2002-02-08 21:27:50 +00001184 result = Py_None;
1185 Py_INCREF(result);
1186 }
Fred Drake8c081a12001-10-12 20:57:55 +00001187 }
1188 return result;
1189}
1190
Tim Petersfeab23f2001-10-13 00:11:10 +00001191static char stop__doc__[] =
1192"stop()\n"
1193"Remove this profiler from the current thread.";
Fred Drake8c081a12001-10-12 20:57:55 +00001194
1195static PyObject *
1196profiler_stop(ProfilerObject *self, PyObject *args)
1197{
1198 PyObject *result = NULL;
1199
1200 if (PyArg_ParseTuple(args, ":stop")) {
1201 if (!self->active)
1202 PyErr_SetString(ProfilerError, "profiler not active");
Fred Drake2c146bf2002-02-08 21:27:50 +00001203 else {
Fred Drake8c081a12001-10-12 20:57:55 +00001204 do_stop(self);
Fred Drake2c146bf2002-02-08 21:27:50 +00001205 result = Py_None;
1206 Py_INCREF(result);
1207 }
Fred Drake8c081a12001-10-12 20:57:55 +00001208 }
1209 return result;
1210}
1211
1212
1213/* Python API support. */
1214
1215static void
1216profiler_dealloc(ProfilerObject *self)
1217{
1218 do_stop(self);
1219 if (self->logfp != NULL)
1220 fclose(self->logfp);
1221 Py_XDECREF(self->filemap);
1222 Py_XDECREF(self->logfilename);
1223 PyObject_Del((PyObject *)self);
1224}
1225
1226/* Always use METH_VARARGS even though some of these could be METH_NOARGS;
1227 * this allows us to maintain compatibility with Python versions < 2.2
1228 * more easily, requiring only the changes to the dispatcher to be made.
1229 */
1230static PyMethodDef profiler_methods[] = {
Fred Drake4c2e1af2001-10-29 20:45:57 +00001231 {"addinfo", (PyCFunction)profiler_addinfo, METH_VARARGS, addinfo__doc__},
Fred Drake8c081a12001-10-12 20:57:55 +00001232 {"close", (PyCFunction)profiler_close, METH_VARARGS, close__doc__},
1233 {"runcall", (PyCFunction)profiler_runcall, METH_VARARGS, runcall__doc__},
1234 {"runcode", (PyCFunction)profiler_runcode, METH_VARARGS, runcode__doc__},
1235 {"start", (PyCFunction)profiler_start, METH_VARARGS, start__doc__},
1236 {"stop", (PyCFunction)profiler_stop, METH_VARARGS, stop__doc__},
1237 {NULL, NULL}
1238};
1239
1240/* Use a table even though there's only one "simple" member; this allows
1241 * __members__ and therefore dir() to work.
1242 */
1243static struct memberlist profiler_members[] = {
Fred Drake30d1c752001-10-15 22:11:02 +00001244 {"closed", T_INT, -1, READONLY},
1245 {"frametimings", T_LONG, offsetof(ProfilerObject, linetimings), READONLY},
1246 {"lineevents", T_LONG, offsetof(ProfilerObject, lineevents), READONLY},
1247 {"linetimings", T_LONG, offsetof(ProfilerObject, linetimings), READONLY},
Fred Drake8c081a12001-10-12 20:57:55 +00001248 {NULL}
1249};
1250
1251static PyObject *
1252profiler_getattr(ProfilerObject *self, char *name)
1253{
1254 PyObject *result;
1255 if (strcmp(name, "closed") == 0) {
1256 result = (self->logfp == NULL) ? Py_True : Py_False;
1257 Py_INCREF(result);
1258 }
1259 else {
1260 result = PyMember_Get((char *)self, profiler_members, name);
1261 if (result == NULL) {
1262 PyErr_Clear();
1263 result = Py_FindMethod(profiler_methods, (PyObject *)self, name);
1264 }
1265 }
1266 return result;
1267}
1268
1269
Tim Petersfeab23f2001-10-13 00:11:10 +00001270static char profiler_object__doc__[] =
1271"High-performance profiler object.\n"
1272"\n"
1273"Methods:\n"
1274"\n"
Fred Drake30d1c752001-10-15 22:11:02 +00001275"close(): Stop the profiler and close the log files.\n"
1276"runcall(): Run a single function call with profiling enabled.\n"
1277"runcode(): Execute a code object with profiling enabled.\n"
1278"start(): Install the profiler and return.\n"
1279"stop(): Remove the profiler.\n"
Tim Petersfeab23f2001-10-13 00:11:10 +00001280"\n"
1281"Attributes (read-only):\n"
1282"\n"
Fred Drake30d1c752001-10-15 22:11:02 +00001283"closed: True if the profiler has already been closed.\n"
1284"frametimings: True if ENTER/EXIT events collect timing information.\n"
1285"lineevents: True if SET_LINENO events are reported to the profiler.\n"
1286"linetimings: True if SET_LINENO events collect timing information.";
Fred Drake8c081a12001-10-12 20:57:55 +00001287
1288static PyTypeObject ProfilerType = {
1289 PyObject_HEAD_INIT(NULL)
1290 0, /* ob_size */
Fred Drake4c2e1af2001-10-29 20:45:57 +00001291 "_hotshot.ProfilerType", /* tp_name */
Fred Drake8c081a12001-10-12 20:57:55 +00001292 (int) sizeof(ProfilerObject), /* tp_basicsize */
1293 0, /* tp_itemsize */
1294 (destructor)profiler_dealloc, /* tp_dealloc */
1295 0, /* tp_print */
1296 (getattrfunc)profiler_getattr, /* tp_getattr */
1297 0, /* tp_setattr */
1298 0, /* tp_compare */
1299 0, /* tp_repr */
1300 0, /* tp_as_number */
1301 0, /* tp_as_sequence */
1302 0, /* tp_as_mapping */
1303 0, /* tp_hash */
1304 0, /* tp_call */
1305 0, /* tp_str */
1306 0, /* tp_getattro */
1307 0, /* tp_setattro */
1308 0, /* tp_as_buffer */
Fred Drake4c2e1af2001-10-29 20:45:57 +00001309 Py_TPFLAGS_DEFAULT, /* tp_flags */
Fred Drake8c081a12001-10-12 20:57:55 +00001310 profiler_object__doc__, /* tp_doc */
1311};
1312
1313
1314static PyMethodDef logreader_methods[] = {
1315 {"close", (PyCFunction)logreader_close, METH_VARARGS,
1316 logreader_close__doc__},
1317 {"next", (PyCFunction)logreader_next, METH_VARARGS,
1318 next__doc__},
1319 {NULL, NULL}
1320};
1321
1322static PyObject *
Fred Drake4c2e1af2001-10-29 20:45:57 +00001323logreader_getattr(LogReaderObject *self, char *name)
Fred Drake8c081a12001-10-12 20:57:55 +00001324{
Fred Drake4c2e1af2001-10-29 20:45:57 +00001325 if (strcmp(name, "info") == 0) {
1326 Py_INCREF(self->info);
1327 return self->info;
1328 }
Fred Drake8c081a12001-10-12 20:57:55 +00001329 return Py_FindMethod(logreader_methods, (PyObject *)self, name);
1330}
1331
1332
1333static char logreader__doc__[] = "\
1334logreader(filename) --> log-iterator\n\
1335Create a log-reader for the timing information file.";
1336
1337static PySequenceMethods logreader_as_sequence = {
1338 0, /* sq_length */
1339 0, /* sq_concat */
1340 0, /* sq_repeat */
1341 (intargfunc)logreader_sq_item, /* sq_item */
1342 0, /* sq_slice */
1343 0, /* sq_ass_item */
1344 0, /* sq_ass_slice */
1345 0, /* sq_contains */
1346 0, /* sq_inplace_concat */
1347 0, /* sq_inplace_repeat */
1348};
1349
1350static PyTypeObject LogReaderType = {
1351 PyObject_HEAD_INIT(NULL)
1352 0, /* ob_size */
Fred Drake4c2e1af2001-10-29 20:45:57 +00001353 "_hotshot.LogReaderType", /* tp_name */
Fred Drake8c081a12001-10-12 20:57:55 +00001354 (int) sizeof(LogReaderObject), /* tp_basicsize */
1355 0, /* tp_itemsize */
1356 (destructor)logreader_dealloc, /* tp_dealloc */
1357 0, /* tp_print */
1358 (getattrfunc)logreader_getattr, /* tp_getattr */
1359 0, /* tp_setattr */
1360 0, /* tp_compare */
1361 0, /* tp_repr */
1362 0, /* tp_as_number */
1363 &logreader_as_sequence, /* tp_as_sequence */
1364 0, /* tp_as_mapping */
1365 0, /* tp_hash */
1366 0, /* tp_call */
1367 0, /* tp_str */
1368 0, /* tp_getattro */
1369 0, /* tp_setattro */
1370 0, /* tp_as_buffer */
Fred Drake4c2e1af2001-10-29 20:45:57 +00001371 Py_TPFLAGS_DEFAULT, /* tp_flags */
Fred Drake8c081a12001-10-12 20:57:55 +00001372 logreader__doc__, /* tp_doc */
1373#if Py_TPFLAGS_HAVE_ITER
1374 0, /* tp_traverse */
1375 0, /* tp_clear */
1376 0, /* tp_richcompare */
1377 0, /* tp_weaklistoffset */
1378 (getiterfunc)logreader_tp_iter, /* tp_iter */
1379 (iternextfunc)logreader_tp_iternext,/* tp_iternext */
1380#endif
1381};
1382
1383static PyObject *
1384hotshot_logreader(PyObject *unused, PyObject *args)
1385{
1386 LogReaderObject *self = NULL;
1387 char *filename;
1388
1389 if (PyArg_ParseTuple(args, "s:logreader", &filename)) {
1390 self = PyObject_New(LogReaderObject, &LogReaderType);
1391 if (self != NULL) {
1392 self->filled = 0;
1393 self->index = 0;
Fred Drake30d1c752001-10-15 22:11:02 +00001394 self->frametimings = 1;
Fred Drake8c081a12001-10-12 20:57:55 +00001395 self->linetimings = 0;
Fred Drake4c2e1af2001-10-29 20:45:57 +00001396 self->info = NULL;
Fred Drake8c081a12001-10-12 20:57:55 +00001397 self->logfp = fopen(filename, "rb");
1398 if (self->logfp == NULL) {
1399 PyErr_SetFromErrnoWithFilename(PyExc_IOError, filename);
1400 Py_DECREF(self);
1401 self = NULL;
Fred Drake4c2e1af2001-10-29 20:45:57 +00001402 goto finally;
1403 }
1404 self->info = PyDict_New();
1405 if (self->info == NULL) {
1406 Py_DECREF(self);
1407 goto finally;
1408 }
1409 /* Aggressively attempt to load all preliminary ADD_INFO
1410 * records from the log so the info records are available
1411 * from a fresh logreader object.
1412 */
1413 logreader_refill(self);
1414 while (self->filled > self->index
1415 && self->buffer[self->index] == WHAT_ADD_INFO) {
1416 int err = unpack_add_info(self, 1);
1417 if (err) {
1418 if (err == ERR_EOF)
1419 eof_error();
1420 else
1421 PyErr_SetString(PyExc_RuntimeError,
1422 "unexpected error");
1423 break;
1424 }
1425 /* Refill agressively so we can avoid EOF during
1426 * initialization unless there's a real EOF condition
1427 * (the tp_iternext handler loops attempts to refill
1428 * and try again).
1429 */
1430 logreader_refill(self);
Fred Drake8c081a12001-10-12 20:57:55 +00001431 }
1432 }
1433 }
Fred Drake4c2e1af2001-10-29 20:45:57 +00001434 finally:
Fred Drake8c081a12001-10-12 20:57:55 +00001435 return (PyObject *) self;
1436}
1437
1438
1439/* Return a Python string that represents the version number without the
1440 * extra cruft added by revision control, even if the right options were
1441 * given to the "cvs export" command to make it not include the extra
1442 * cruft.
1443 */
1444static char *
1445get_version_string(void)
1446{
1447 static char *rcsid = "$Revision$";
1448 char *rev = rcsid;
1449 char *buffer;
1450 int i = 0;
1451
1452 while (*rev && !isdigit(*rev))
1453 ++rev;
1454 while (rev[i] != ' ' && rev[i] != '\0')
1455 ++i;
1456 buffer = malloc(i + 1);
1457 if (buffer != NULL) {
1458 memmove(buffer, rev, i);
1459 buffer[i] = '\0';
1460 }
1461 return buffer;
1462}
1463
1464/* Write out a RFC 822-style header with various useful bits of
1465 * information to make the output easier to manage.
1466 */
1467static int
1468write_header(ProfilerObject *self)
1469{
1470 char *buffer;
1471 char cwdbuffer[PATH_MAX];
1472 PyObject *temp;
1473 int i, len;
1474
1475 buffer = get_version_string();
1476 if (buffer == NULL) {
1477 PyErr_NoMemory();
1478 return -1;
1479 }
Fred Drake4c2e1af2001-10-29 20:45:57 +00001480 pack_add_info(self, "hotshot-version", buffer);
1481 pack_add_info(self, "requested-frame-timings",
1482 (self->frametimings ? "yes" : "no"));
1483 pack_add_info(self, "requested-line-events",
Fred Drake8c081a12001-10-12 20:57:55 +00001484 (self->lineevents ? "yes" : "no"));
Fred Drake4c2e1af2001-10-29 20:45:57 +00001485 pack_add_info(self, "requested-line-timings",
1486 (self->linetimings ? "yes" : "no"));
1487 pack_add_info(self, "platform", Py_GetPlatform());
1488 pack_add_info(self, "executable", Py_GetProgramFullPath());
Fred Drakef12a68c2001-11-09 15:59:36 +00001489 free(buffer);
Fred Drake8c081a12001-10-12 20:57:55 +00001490 buffer = (char *) Py_GetVersion();
1491 if (buffer == NULL)
1492 PyErr_Clear();
1493 else
Fred Drake4c2e1af2001-10-29 20:45:57 +00001494 pack_add_info(self, "executable-version", buffer);
Fred Drake8c081a12001-10-12 20:57:55 +00001495
1496#ifdef MS_WIN32
Tim Peters885d4572001-11-28 20:27:42 +00001497 PyOS_snprintf(cwdbuffer, sizeof(cwdbuffer), "%I64d", frequency.QuadPart);
Fred Drake4c2e1af2001-10-29 20:45:57 +00001498 pack_add_info(self, "reported-performance-frequency", cwdbuffer);
Fred Drake8c081a12001-10-12 20:57:55 +00001499#else
Tim Peters885d4572001-11-28 20:27:42 +00001500 PyOS_snprintf(cwdbuffer, sizeof(cwdbuffer), "%lu", rusage_diff);
Fred Drake4c2e1af2001-10-29 20:45:57 +00001501 pack_add_info(self, "observed-interval-getrusage", cwdbuffer);
Tim Peters885d4572001-11-28 20:27:42 +00001502 PyOS_snprintf(cwdbuffer, sizeof(cwdbuffer), "%lu", timeofday_diff);
Fred Drake4c2e1af2001-10-29 20:45:57 +00001503 pack_add_info(self, "observed-interval-gettimeofday", cwdbuffer);
Fred Drake8c081a12001-10-12 20:57:55 +00001504#endif
Fred Drake8c081a12001-10-12 20:57:55 +00001505
Fred Drake4c2e1af2001-10-29 20:45:57 +00001506 pack_add_info(self, "current-directory",
Fred Drake8c081a12001-10-12 20:57:55 +00001507 getcwd(cwdbuffer, sizeof cwdbuffer));
1508
1509 temp = PySys_GetObject("path");
1510 len = PyList_GET_SIZE(temp);
1511 for (i = 0; i < len; ++i) {
1512 PyObject *item = PyList_GET_ITEM(temp, i);
1513 buffer = PyString_AsString(item);
1514 if (buffer == NULL)
1515 return -1;
Fred Drake4c2e1af2001-10-29 20:45:57 +00001516 pack_add_info(self, "sys-path-entry", buffer);
Fred Drake8c081a12001-10-12 20:57:55 +00001517 }
Fred Drake4c2e1af2001-10-29 20:45:57 +00001518 pack_frame_times(self);
1519 pack_line_times(self);
1520
Fred Drake8c081a12001-10-12 20:57:55 +00001521 return 0;
1522}
1523
1524static char profiler__doc__[] = "\
1525profiler(logfilename[, lineevents[, linetimes]]) -> profiler\n\
1526Create a new profiler object.";
1527
1528static PyObject *
1529hotshot_profiler(PyObject *unused, PyObject *args)
1530{
1531 char *logfilename;
1532 ProfilerObject *self = NULL;
1533 int lineevents = 0;
1534 int linetimings = 1;
1535
1536 if (PyArg_ParseTuple(args, "s|ii:profiler", &logfilename,
1537 &lineevents, &linetimings)) {
1538 self = PyObject_New(ProfilerObject, &ProfilerType);
1539 if (self == NULL)
1540 return NULL;
Fred Drake30d1c752001-10-15 22:11:02 +00001541 self->frametimings = 1;
Fred Drake8c081a12001-10-12 20:57:55 +00001542 self->lineevents = lineevents ? 1 : 0;
1543 self->linetimings = (lineevents && linetimings) ? 1 : 0;
1544 self->index = 0;
1545 self->active = 0;
1546 self->next_fileno = 0;
Tim Peters1566a172001-10-12 22:08:39 +00001547 self->logfp = NULL;
Fred Drake8c081a12001-10-12 20:57:55 +00001548 self->logfilename = PyTuple_GET_ITEM(args, 0);
1549 Py_INCREF(self->logfilename);
1550 self->filemap = PyDict_New();
1551 if (self->filemap == NULL) {
1552 Py_DECREF(self);
1553 return NULL;
1554 }
1555 self->logfp = fopen(logfilename, "wb");
1556 if (self->logfp == NULL) {
1557 Py_DECREF(self);
1558 PyErr_SetFromErrnoWithFilename(PyExc_IOError, logfilename);
1559 return NULL;
1560 }
1561 if (timeofday_diff == 0) {
1562 /* Run this several times since sometimes the first
1563 * doesn't give the lowest values, and we're really trying
1564 * to determine the lowest.
1565 */
1566 calibrate();
1567 calibrate();
1568 calibrate();
1569 }
1570 if (write_header(self))
1571 /* some error occurred, exception has been set */
1572 self = NULL;
1573 }
1574 return (PyObject *) self;
1575}
1576
Fred Drake30d1c752001-10-15 22:11:02 +00001577static char coverage__doc__[] = "\
1578coverage(logfilename) -> profiler\n\
1579Returns a profiler that doesn't collect any timing information, which is\n\
1580useful in building a coverage analysis tool.";
1581
1582static PyObject *
1583hotshot_coverage(PyObject *unused, PyObject *args)
1584{
1585 char *logfilename;
1586 PyObject *result = NULL;
1587
1588 if (PyArg_ParseTuple(args, "s:coverage", &logfilename)) {
1589 result = hotshot_profiler(unused, args);
1590 if (result != NULL) {
1591 ProfilerObject *self = (ProfilerObject *) result;
1592 self->frametimings = 0;
1593 self->linetimings = 0;
1594 self->lineevents = 1;
1595 }
1596 }
1597 return result;
1598}
1599
Fred Drake8c081a12001-10-12 20:57:55 +00001600static char resolution__doc__[] =
1601#ifdef MS_WIN32
Tim Petersfeab23f2001-10-13 00:11:10 +00001602"resolution() -> (performance-counter-ticks, update-frequency)\n"
1603"Return the resolution of the timer provided by the QueryPerformanceCounter()\n"
1604"function. The first value is the smallest observed change, and the second\n"
1605"is the result of QueryPerformanceFrequency().";
Fred Drake8c081a12001-10-12 20:57:55 +00001606#else
Tim Petersfeab23f2001-10-13 00:11:10 +00001607"resolution() -> (gettimeofday-usecs, getrusage-usecs)\n"
1608"Return the resolution of the timers provided by the gettimeofday() and\n"
1609"getrusage() system calls, or -1 if the call is not supported.";
Fred Drake8c081a12001-10-12 20:57:55 +00001610#endif
1611
1612static PyObject *
1613hotshot_resolution(PyObject *unused, PyObject *args)
1614{
1615 PyObject *result = NULL;
1616
1617 if (PyArg_ParseTuple(args, ":resolution")) {
1618 if (timeofday_diff == 0) {
1619 calibrate();
1620 calibrate();
1621 calibrate();
1622 }
1623#ifdef MS_WIN32
1624 result = Py_BuildValue("ii", timeofday_diff, frequency.LowPart);
1625#else
1626 result = Py_BuildValue("ii", timeofday_diff, rusage_diff);
1627#endif
1628 }
1629 return result;
1630}
1631
1632
1633static PyMethodDef functions[] = {
Fred Drake30d1c752001-10-15 22:11:02 +00001634 {"coverage", hotshot_coverage, METH_VARARGS, coverage__doc__},
Fred Drake8c081a12001-10-12 20:57:55 +00001635 {"profiler", hotshot_profiler, METH_VARARGS, profiler__doc__},
1636 {"logreader", hotshot_logreader, METH_VARARGS, logreader__doc__},
1637 {"resolution", hotshot_resolution, METH_VARARGS, resolution__doc__},
1638 {NULL, NULL}
1639};
1640
1641
1642void
1643init_hotshot(void)
1644{
1645 PyObject *module;
1646
1647 LogReaderType.ob_type = &PyType_Type;
1648 ProfilerType.ob_type = &PyType_Type;
1649 module = Py_InitModule("_hotshot", functions);
1650 if (module != NULL) {
1651 char *s = get_version_string();
1652
1653 PyModule_AddStringConstant(module, "__version__", s);
1654 free(s);
1655 Py_INCREF(&LogReaderType);
1656 PyModule_AddObject(module, "LogReaderType",
1657 (PyObject *)&LogReaderType);
1658 Py_INCREF(&ProfilerType);
1659 PyModule_AddObject(module, "ProfilerType",
1660 (PyObject *)&ProfilerType);
1661
1662 if (ProfilerError == NULL)
1663 ProfilerError = PyErr_NewException("hotshot.ProfilerError",
1664 NULL, NULL);
1665 if (ProfilerError != NULL) {
1666 Py_INCREF(ProfilerError);
1667 PyModule_AddObject(module, "ProfilerError", ProfilerError);
1668 }
1669 PyModule_AddIntConstant(module, "WHAT_ENTER", WHAT_ENTER);
1670 PyModule_AddIntConstant(module, "WHAT_EXIT", WHAT_EXIT);
1671 PyModule_AddIntConstant(module, "WHAT_LINENO", WHAT_LINENO);
1672 PyModule_AddIntConstant(module, "WHAT_OTHER", WHAT_OTHER);
1673 PyModule_AddIntConstant(module, "WHAT_ADD_INFO", WHAT_ADD_INFO);
1674 PyModule_AddIntConstant(module, "WHAT_DEFINE_FILE", WHAT_DEFINE_FILE);
Fred Drake30d1c752001-10-15 22:11:02 +00001675 PyModule_AddIntConstant(module, "WHAT_DEFINE_FUNC", WHAT_DEFINE_FUNC);
Fred Drake8c081a12001-10-12 20:57:55 +00001676 PyModule_AddIntConstant(module, "WHAT_LINE_TIMES", WHAT_LINE_TIMES);
1677 }
1678}