blob: 4a6d7fc1fceda85b7e7f1776b8caa757961f558b [file] [log] [blame]
Fred Drake8c081a12001-10-12 20:57:55 +00001/*
2 * This is the High Performance Python Profiler portion of HotShot.
3 */
4
5#include <Python.h>
6#include <compile.h>
7#include <eval.h>
8#include <frameobject.h>
9#include <structmember.h>
10
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
34#include <sys/resource.h>
35#include <sys/times.h>
36typedef struct timeval hs_time;
37#endif
38
39#if !defined(__cplusplus) && !defined(inline)
40#ifdef __GNUC__
41#define inline __inline
42#endif
43#endif
44
45#ifndef inline
46#define inline
47#endif
48
49#define BUFFERSIZE 10240
50
Tim Peters1566a172001-10-12 22:08:39 +000051#ifndef PATH_MAX
52# ifdef MAX_PATH
53# define PATH_MAX MAX_PATH
54# else
55# error "Need a defn. for PATH_MAX in _hotshot.c"
56# endif
57#endif
58
Fred Drake8c081a12001-10-12 20:57:55 +000059typedef struct {
60 PyObject_HEAD
61 PyObject *filemap;
62 PyObject *logfilename;
63 int index;
64 unsigned char buffer[BUFFERSIZE];
65 FILE *logfp;
66 int lineevents;
67 int linetimings;
68 /* size_t filled; */
69 int active;
70 int next_fileno;
71 long callcount;
72 hs_time prev_timeofday;
73} ProfilerObject;
74
75typedef struct {
76 PyObject_HEAD
77 FILE *logfp;
78 int filled;
79 int index;
80 int linetimings;
81 unsigned char buffer[BUFFERSIZE];
82} LogReaderObject;
83
84static PyObject * ProfilerError = NULL;
85
86
87#ifndef MS_WIN32
88#ifdef GETTIMEOFDAY_NO_TZ
89#define GETTIMEOFDAY(ptv) gettimeofday((ptv))
90#else
91#define GETTIMEOFDAY(ptv) gettimeofday((ptv), (struct timezone *)NULL)
92#endif
93#endif
94
95
96/* The log reader... */
97
Tim Petersfeab23f2001-10-13 00:11:10 +000098static char logreader_close__doc__[] =
99"close()\n"
100"Close the log file, preventing additional records from being read.";
Fred Drake8c081a12001-10-12 20:57:55 +0000101
102static PyObject *
103logreader_close(LogReaderObject *self, PyObject *args)
104{
105 PyObject *result = NULL;
106 if (PyArg_ParseTuple(args, ":close")) {
107 if (self->logfp != NULL) {
108 fclose(self->logfp);
109 self->logfp = NULL;
110 }
111 result = Py_None;
112 Py_INCREF(result);
113 }
114 return result;
115}
116
117#if Py_TPFLAGS_HAVE_ITER
118/* This is only used if the interpreter has iterator support; the
119 * iternext handler is also used as a helper for other functions, so
120 * does not need to be included in this conditional section.
121 */
122static PyObject *
123logreader_tp_iter(LogReaderObject *self)
124{
125 Py_INCREF(self);
126 return (PyObject *) self;
127}
128#endif
129
130
131/* Log File Format
132 * ---------------
133 *
134 * The log file consists of a sequence of variable-length records.
135 * Each record is identified with a record type identifier in two
136 * bits of the first byte. The two bits are the "least significant"
137 * bits of the byte.
138 *
139 * Low bits: Opcode: Meaning:
140 * 0x00 ENTER enter a frame
141 * 0x01 EXIT exit a frame
142 * 0x02 LINENO SET_LINENO instruction was executed
143 * 0x03 OTHER more bits are needed to deecode
144 *
145 * If the type is OTHER, the record is not packed so tightly, and the
146 * remaining bits are used to disambiguate the record type. These
147 * records are not used as frequently so compaction is not an issue.
148 * Each of the first three record types has a highly tailored
149 * structure that allows it to be packed tightly.
150 *
151 * The OTHER records have the following identifiers:
152 *
153 * First byte: Opcode: Meaning:
154 * 0x13 ADD_INFO define a key/value pair
155 * 0x23 DEFINE_FILE define an int->filename mapping
156 * 0x33 LINE_TIMES indicates if LINENO events have tdeltas
157 *
158 * Packed Integers
159 *
160 * "Packed integers" are non-negative integer values encoded as a
161 * sequence of bytes. Each byte is encoded such that the most
162 * significant bit is set if the next byte is also part of the
163 * integer. Each byte provides bits to the least-significant end of
164 * the result; the accumulated value must be shifted up to place the
165 * new bits into the result.
166 *
167 * "Modified packed integers" are packed integers where only a portion
168 * of the first byte is used. In the rest of the specification, these
169 * are referred to as "MPI(n,name)", where "n" is the number of bits
170 * discarded from the least-signicant positions of the byte, and
171 * "name" is a name being given to those "discarded" bits, since they
172 * are a field themselves.
173 *
174 * ENTER records:
175 *
176 * MPI(2,type) fileno -- type is 0x00
177 * PI tdelta
178 * PI lineno
179 *
180 * EXIT records
181 *
182 * MPI(2,type) tdelta -- type is 0x01
183 *
184 * LINENO records
185 *
186 * MPI(2,type) lineno -- type is 0x02
187 * PI tdelta -- iff LINENO includes it
188 *
189 * ADD_INFO records
190 *
191 * BYTE type -- always 0x03
192 * PI len1 -- length of first string
193 * BYTE string1[len1] -- len1 bytes of string data
194 * PI len2 -- length of second string
195 * BYTE string2[len2] -- len2 bytes of string data
196 *
197 * DEFINE_FILE records
198 *
199 * BYTE type -- always 0x13
200 * PI fileno
201 * PI len -- length of filename
202 * BYTE filename[len] -- len bytes of string data
203 *
204 * LINE_TIMES records
205 * BYTE type -- always 0x23
206 * BYTE have_tdelta -- 0 if LINENO does *not* have
207 * timing information
208 */
209
210#define WHAT_ENTER 0x00
211#define WHAT_EXIT 0x01
212#define WHAT_LINENO 0x02
213#define WHAT_OTHER 0x03 /* only used in decoding */
214#define WHAT_ADD_INFO 0x13
215#define WHAT_DEFINE_FILE 0x23
216#define WHAT_LINE_TIMES 0x33
217
218#define ERR_NONE 0
219#define ERR_EOF -1
220#define ERR_EXCEPTION -2
221
222#define PISIZE (sizeof(int) + 1)
223#define MPISIZE (PISIZE + 1)
224
225/* Maximum size of "normal" events -- nothing that contains string data */
226#define MAXEVENTSIZE (MPISIZE + PISIZE*2)
227
228
229/* Unpack a packed integer; if "discard" is non-zero, unpack a modified
230 * packed integer with "discard" discarded bits.
231 */
232static int
233unpack_packed_int(LogReaderObject *self, int *pvalue, int discard)
234{
235 int accum = 0;
236 int bits = 0;
237 int index = self->index;
238 int cont;
239
240 do {
241 if (index >= self->filled)
242 return ERR_EOF;
243 /* read byte */
244 accum |= ((self->buffer[index] & 0x7F) >> discard) << bits;
245 bits += (7 - discard);
246 cont = self->buffer[index] & 0x80;
247 /* move to next */
248 discard = 0;
249 index++;
250 } while (cont);
251
252 /* save state */
253 self->index = index;
254 *pvalue = accum;
255
256 return 0;
257}
258
259/* Unpack a string, which is encoded as a packed integer giving the
260 * length of the string, followed by the string data.
261 */
262static int
263unpack_string(LogReaderObject *self, PyObject **pvalue)
264{
265 int len;
266 int oldindex = self->index;
267 int err = unpack_packed_int(self, &len, 0);
268
269 if (!err) {
270 /* need at least len bytes in buffer */
271 if (len > (self->filled - self->index)) {
272 self->index = oldindex;
273 err = ERR_EOF;
274 }
275 else {
276 *pvalue = PyString_FromStringAndSize(self->buffer + self->index,
277 len);
278 if (*pvalue == NULL) {
279 self->index = oldindex;
280 err = ERR_EXCEPTION;
281 }
282 else
283 self->index += len;
284 }
285 }
286 return err;
287}
288
289
290static PyObject *
291logreader_tp_iternext(LogReaderObject *self)
292{
293 int what, oldindex;
294 int err = ERR_NONE;
295 int lineno = -1;
296 int fileno = -1;
297 int tdelta = -1;
298 PyObject *s1 = NULL, *s2 = NULL;
299 PyObject *result = NULL;
300#if 0
301 unsigned char b0, b1;
302#endif
303
304 if (self->logfp == NULL) {
305 PyErr_SetString(ProfilerError,
306 "cannot iterate over closed LogReader object");
307 return NULL;
308 }
309 restart:
310 if ((self->filled - self->index) < MAXEVENTSIZE) {
311 /* add a little to the buffer */
312 int needed;
313 size_t res;
314 refill:
315 if (self->index) {
316 memmove(self->buffer, &self->buffer[self->index],
317 self->filled - self->index);
318 self->filled = self->filled - self->index;
319 self->index = 0;
320 }
321 needed = BUFFERSIZE - self->filled;
322 res = fread(&self->buffer[self->filled], 1, needed, self->logfp);
323 self->filled += res;
324 }
325 /* end of input */
326 if (self->filled == 0)
327 return NULL;
328
329 oldindex = self->index;
330
331 /* decode the record type */
332 what = self->buffer[self->index] & WHAT_OTHER;
333 if (what == WHAT_OTHER) {
334 what = self->buffer[self->index];
335 self->index++;
336 }
337 switch (what) {
338 case WHAT_ENTER:
339 err = unpack_packed_int(self, &fileno, 2);
340 if (!err) {
341 err = unpack_packed_int(self, &tdelta, 0);
342 if (!err)
343 err = unpack_packed_int(self, &lineno, 0);
344 }
345 break;
346 case WHAT_EXIT:
347 err = unpack_packed_int(self, &tdelta, 2);
348 break;
349 case WHAT_LINENO:
350 err = unpack_packed_int(self, &lineno, 2);
351 if (self->linetimings && !err)
352 err = unpack_packed_int(self, &tdelta, 0);
353 break;
354 case WHAT_ADD_INFO:
355 err = unpack_string(self, &s1);
356 if (!err) {
357 err = unpack_string(self, &s2);
358 if (err) {
359 Py_DECREF(s1);
360 s1 = NULL;
361 }
362 }
363 break;
364 case WHAT_DEFINE_FILE:
365 err = unpack_packed_int(self, &fileno, 0);
366 if (!err) {
367 err = unpack_string(self, &s1);
368 if (!err) {
369 Py_INCREF(Py_None);
370 s2 = Py_None;
371 }
372 }
373 break;
374 case WHAT_LINE_TIMES:
375 if (self->index >= self->filled)
376 err = ERR_EOF;
377 else {
378 self->linetimings = self->buffer[self->index] ? 1 : 0;
379 self->index++;
380 goto restart;
381 }
382 default:
Tim Peters1566a172001-10-12 22:08:39 +0000383 ;
Fred Drake8c081a12001-10-12 20:57:55 +0000384 }
385 if (err == ERR_EOF && oldindex != 0) {
386 /* It looks like we ran out of data before we had it all; this
387 * could easily happen with large packed integers or string
388 * data. Try forcing the buffer to be re-filled before failing.
389 */
390 err = ERR_NONE;
391 goto refill;
392 }
393 if (err == ERR_EOF) {
394 /* Could not avoid end-of-buffer error. */
395 PyErr_SetString(PyExc_EOFError,
396 "end of file with incomplete profile record");
397 }
398 else if (!err) {
399 result = PyTuple_New(4);
400 PyTuple_SET_ITEM(result, 0, PyInt_FromLong(what));
401 PyTuple_SET_ITEM(result, 2, PyInt_FromLong(fileno));
402 if (s1 == NULL) {
403 PyTuple_SET_ITEM(result, 1, PyInt_FromLong(tdelta));
404 PyTuple_SET_ITEM(result, 3, PyInt_FromLong(lineno));
405 }
406 else {
407 PyTuple_SET_ITEM(result, 1, s1);
408 PyTuple_SET_ITEM(result, 3, s2);
409 }
410 }
411 /* The only other case is err == ERR_EXCEPTION, in which case the
412 * exception is already set.
413 */
414#if 0
415 b0 = self->buffer[self->index];
416 b1 = self->buffer[self->index + 1];
417 if (b0 & 1) {
418 /* This is a line-number event. */
419 what = PyTrace_LINE;
420 lineno = ((b0 & ~1) << 7) + b1;
421 self->index += 2;
422 }
423 else {
424 what = (b0 & 0x0E) >> 1;
425 tdelta = ((b0 & 0xF0) << 4) + b1;
426 if (what == PyTrace_CALL) {
427 /* we know there's a 2-byte file ID & 2-byte line number */
428 fileno = ((self->buffer[self->index + 2] << 8)
429 + self->buffer[self->index + 3]);
430 lineno = ((self->buffer[self->index + 4] << 8)
431 + self->buffer[self->index + 5]);
432 self->index += 6;
433 }
434 else
435 self->index += 2;
436 }
437#endif
438 return result;
439}
440
441static void
442logreader_dealloc(LogReaderObject *self)
443{
444 if (self->logfp != NULL) {
445 fclose(self->logfp);
446 self->logfp = NULL;
447 }
448 PyObject_Del(self);
449}
450
451static PyObject *
452logreader_sq_item(LogReaderObject *self, int index)
453{
454 PyObject *result = logreader_tp_iternext(self);
455 if (result == NULL && !PyErr_Occurred()) {
456 PyErr_SetString(PyExc_IndexError, "no more events in log");
457 return NULL;
458 }
459 return result;
460}
461
Tim Petersfeab23f2001-10-13 00:11:10 +0000462static char next__doc__[] =
463"next() -> event-info\n"
464"Return the next event record from the log file.";
Fred Drake8c081a12001-10-12 20:57:55 +0000465
466static PyObject *
467logreader_next(LogReaderObject *self, PyObject *args)
468{
469 PyObject *result = NULL;
470
471 if (PyArg_ParseTuple(args, ":next")) {
472 result = logreader_tp_iternext(self);
473 /* XXX return None if there's nothing left */
474 /* tp_iternext does the right thing, though */
475 if (result == NULL && !PyErr_Occurred()) {
476 result = Py_None;
477 Py_INCREF(result);
478 }
479 }
480 return result;
481}
482
483
484static int
485flush_data(ProfilerObject *self)
486{
487 /* Need to dump data to the log file... */
488 size_t written = fwrite(self->buffer, 1, self->index, self->logfp);
Tim Peters1566a172001-10-12 22:08:39 +0000489 if (written == (size_t)self->index)
Fred Drake8c081a12001-10-12 20:57:55 +0000490 self->index = 0;
491 else {
492 memmove(self->buffer, &self->buffer[written],
493 self->index - written);
494 self->index -= written;
495 if (written == 0) {
496 char *s = PyString_AsString(self->logfilename);
497 PyErr_SetFromErrnoWithFilename(PyExc_IOError, s);
498 return -1;
499 }
500 }
501 if (written > 0) {
502 if (fflush(self->logfp)) {
503 char *s = PyString_AsString(self->logfilename);
504 PyErr_SetFromErrnoWithFilename(PyExc_IOError, s);
505 return -1;
506 }
507 }
508 return 0;
509}
510
511static inline void
512pack_packed_int(ProfilerObject *self, int value)
513{
514 unsigned char partial;
515
516 do {
517 partial = value & 0x7F;
518 value >>= 7;
519 if (value)
520 partial |= 0x80;
521 self->buffer[self->index] = partial;
522 self->index++;
523 } while (value);
524}
525
526/* Encode a modified packed integer, with a subfield of modsize bits
527 * containing the value "subfield". The value of subfield is not
528 * checked to ensure it actually fits in modsize bits.
529 */
530static inline void
531pack_modified_packed_int(ProfilerObject *self, int value,
532 int modsize, int subfield)
533{
534 const int maxvalues[] = {-1, 1, 3, 7, 15, 31, 63, 127};
535
536 int bits = 7 - modsize;
537 int partial = value & maxvalues[bits];
538 unsigned char b = subfield | (partial << modsize);
539
540 if (partial != value) {
541 b |= 0x80;
542 self->buffer[self->index] = b;
543 self->index++;
544 pack_packed_int(self, value >> bits);
545 }
546 else {
547 self->buffer[self->index] = b;
548 self->index++;
549 }
550}
551
552static void
553pack_string(ProfilerObject *self, const char *s)
554{
555 int len = strlen(s);
556
557 pack_packed_int(self, len);
558 if (len + self->index >= BUFFERSIZE)
559 (void) flush_data(self);
560 memcpy(self->buffer + self->index, s, len);
561 self->index += len;
562}
563
564static void
565pack_add_info(ProfilerObject *self, const char *s1, const char *s2)
566{
567 int len1 = strlen(s1);
568 int len2 = strlen(s2);
569
570 if (len1 + len2 + PISIZE*2 + 1 + self->index >= BUFFERSIZE)
571 (void) flush_data(self);
572 self->buffer[self->index] = WHAT_ADD_INFO;
573 self->index++;
574 pack_string(self, s1);
575 pack_string(self, s2);
576}
577
578static void
579pack_define_file(ProfilerObject *self, int fileno, const char *filename)
580{
581 int len = strlen(filename);
582
583 if (len + PISIZE*2 + 1 + self->index >= BUFFERSIZE)
584 (void) flush_data(self);
585 self->buffer[self->index] = WHAT_DEFINE_FILE;
586 self->index++;
587 pack_packed_int(self, fileno);
588 pack_string(self, filename);
589}
590
591static void
592pack_line_times(ProfilerObject *self)
593{
594 if (2 + self->index >= BUFFERSIZE)
595 (void) flush_data(self);
596 self->buffer[self->index] = WHAT_LINE_TIMES;
597 self->buffer[self->index + 1] = self->linetimings ? 1 : 0;
598 self->index += 2;
599}
600
601static inline void
602pack_enter(ProfilerObject *self, int fileno, int tdelta, int lineno)
603{
604 if (MPISIZE + PISIZE*2 + self->index >= BUFFERSIZE)
605 (void) flush_data(self);
606 pack_modified_packed_int(self, fileno, 2, WHAT_ENTER);
607 pack_packed_int(self, tdelta);
608 pack_packed_int(self, lineno);
609}
610
611static inline void
612pack_exit(ProfilerObject *self, int tdelta)
613{
614 if (MPISIZE + self->index >= BUFFERSIZE)
615 (void) flush_data(self);
616 pack_modified_packed_int(self, tdelta, 2, WHAT_EXIT);
617}
618
619static inline void
620pack_lineno(ProfilerObject *self, int lineno)
621{
622 if (MPISIZE + self->index >= BUFFERSIZE)
623 (void) flush_data(self);
624 pack_modified_packed_int(self, lineno, 2, WHAT_LINENO);
625}
626
627static inline void
628pack_lineno_tdelta(ProfilerObject *self, int lineno, int tdelta)
629{
630 if (MPISIZE + PISIZE + self->index >= BUFFERSIZE)
631 (void) flush_data(self);
632 pack_modified_packed_int(self, lineno, 2, WHAT_LINENO);
633 pack_packed_int(self, tdelta);
634}
635
636static inline int
637get_fileno(ProfilerObject *self, PyCodeObject *fcode)
638{
639 PyObject *idobj;
640 int fileno;
641
642 idobj = PyDict_GetItem(self->filemap, fcode->co_filename);
643 if (idobj == NULL) {
644 /* first sighting of this file */
645 fileno = self->next_fileno;
646 idobj = PyInt_FromLong(fileno);
647 if (idobj == NULL) {
648 return -1;
649 }
650 if (PyDict_SetItem(self->filemap, fcode->co_filename, idobj)) {
651 Py_DECREF(idobj);
652 return -1;
653 }
654 self->next_fileno++;
655 Py_DECREF(idobj);
656 pack_define_file(self, fileno, PyString_AS_STRING(fcode->co_filename));
657 }
658 else {
659 /* already know this ID */
660 fileno = PyInt_AS_LONG(idobj);
661 }
662 return fileno;
663}
664
665static inline int
666get_tdelta(ProfilerObject *self)
667{
668 int tdelta;
669#ifdef MS_WIN32
670 hs_time tv;
Tim Peters7d99ff22001-10-13 07:37:52 +0000671 hs_time diff;
Fred Drake8c081a12001-10-12 20:57:55 +0000672
Tim Peters7d99ff22001-10-13 07:37:52 +0000673 GETTIMEOFDAY(&tv);
674 diff = tv - self->prev_timeofday;
675 tdelta = (int)diff;
Fred Drake8c081a12001-10-12 20:57:55 +0000676#else
677 struct timeval tv;
678
679 GETTIMEOFDAY(&tv);
680
681 if (tv.tv_sec == self->prev_timeofday.tv_sec)
682 tdelta = tv.tv_usec - self->prev_timeofday.tv_usec;
683 else
684 tdelta = ((tv.tv_sec - self->prev_timeofday.tv_sec) * 1000000
685 + tv.tv_usec);
686#endif
687 self->prev_timeofday = tv;
688 return tdelta;
689}
690
691
692/* The workhorse: the profiler callback function. */
693
694static int
695profiler_callback(ProfilerObject *self, PyFrameObject *frame, int what,
696 PyObject *arg)
697{
698 int tdelta = get_tdelta(self);
699 int fileno;
700
701 self->callcount++;
702 switch (what) {
703 case PyTrace_CALL:
704 fileno = get_fileno(self, frame->f_code);
705 if (fileno < 0)
706 return -1;
707 pack_enter(self, fileno, tdelta,
708 frame->f_code->co_firstlineno);
709 break;
710 case PyTrace_RETURN:
711 pack_exit(self, tdelta);
712 break;
713 default:
714 /* should never get here */
715 break;
716 }
717 return 0;
718}
719
720
721/* Alternate callback when we want PyTrace_LINE events */
722
723static int
724tracer_callback(ProfilerObject *self, PyFrameObject *frame, int what,
725 PyObject *arg)
726{
727 int fileno;
728
729 self->callcount++;
730 switch (what) {
731 case PyTrace_CALL:
732 fileno = get_fileno(self, frame->f_code);
733 if (fileno < 0)
734 return -1;
735 pack_enter(self, fileno, get_tdelta(self),
736 frame->f_code->co_firstlineno);
737 break;
738 case PyTrace_RETURN:
739 pack_exit(self, get_tdelta(self));
740 break;
Tim Peters1566a172001-10-12 22:08:39 +0000741 case PyTrace_LINE:
Fred Drake8c081a12001-10-12 20:57:55 +0000742 if (self->linetimings)
743 pack_lineno_tdelta(self, frame->f_lineno, get_tdelta(self));
744 else
745 pack_lineno(self, frame->f_lineno);
746 break;
747 default:
748 /* ignore PyTrace_EXCEPTION */
749 break;
750 }
751 return 0;
752}
753
754
755/* A couple of useful helper functions. */
756
757#ifdef MS_WIN32
Tim Petersfeab23f2001-10-13 00:11:10 +0000758static LARGE_INTEGER frequency = {0, 0};
Fred Drake8c081a12001-10-12 20:57:55 +0000759#endif
760
761static unsigned long timeofday_diff = 0;
762static unsigned long rusage_diff = 0;
763
764static void
765calibrate(void)
766{
767 hs_time tv1, tv2;
768
769#ifdef MS_WIN32
Tim Peters7d99ff22001-10-13 07:37:52 +0000770 hs_time diff;
Fred Drake8c081a12001-10-12 20:57:55 +0000771 QueryPerformanceFrequency(&frequency);
772#endif
773
774 GETTIMEOFDAY(&tv1);
775 while (1) {
776 GETTIMEOFDAY(&tv2);
777#ifdef MS_WIN32
Tim Peters7d99ff22001-10-13 07:37:52 +0000778 diff = tv2 - tv1;
779 if (diff != 0) {
780 timeofday_diff = (unsigned long)diff;
Fred Drake8c081a12001-10-12 20:57:55 +0000781 break;
782 }
783#else
784 if (tv1.tv_sec != tv2.tv_sec || tv1.tv_usec != tv2.tv_usec) {
785 if (tv1.tv_sec == tv2.tv_sec)
786 timeofday_diff = tv2.tv_usec - tv1.tv_usec;
787 else
788 timeofday_diff = (1000000 - tv1.tv_usec) + tv2.tv_usec;
789 break;
790 }
791#endif
792 }
793#ifdef MS_WIN32
794 rusage_diff = -1;
795#else
796 {
797 struct rusage ru1, ru2;
798
799 getrusage(RUSAGE_SELF, &ru1);
800 while (1) {
801 getrusage(RUSAGE_SELF, &ru2);
802 if (ru1.ru_utime.tv_sec != ru2.ru_utime.tv_sec) {
803 rusage_diff = ((1000000 - ru1.ru_utime.tv_usec)
804 + ru2.ru_utime.tv_usec);
805 break;
806 }
807 else if (ru1.ru_utime.tv_usec != ru2.ru_utime.tv_usec) {
808 rusage_diff = ru2.ru_utime.tv_usec - ru1.ru_utime.tv_usec;
809 break;
810 }
811 else if (ru1.ru_stime.tv_sec != ru2.ru_stime.tv_sec) {
812 rusage_diff = ((1000000 - ru1.ru_stime.tv_usec)
813 + ru2.ru_stime.tv_usec);
814 break;
815 }
816 else if (ru1.ru_stime.tv_usec != ru2.ru_stime.tv_usec) {
817 rusage_diff = ru2.ru_stime.tv_usec - ru1.ru_stime.tv_usec;
818 break;
819 }
820 }
821 }
822#endif
823}
824
825static void
826do_start(ProfilerObject *self)
827{
828 self->active = 1;
829 GETTIMEOFDAY(&self->prev_timeofday);
830 if (self->lineevents)
831 PyEval_SetTrace((Py_tracefunc) tracer_callback, (PyObject *)self);
832 else
833 PyEval_SetProfile((Py_tracefunc) profiler_callback, (PyObject *)self);
834}
835
836static void
837do_stop(ProfilerObject *self)
838{
839 if (self->active) {
840 self->active = 0;
841 if (self->lineevents)
842 PyEval_SetTrace(NULL, NULL);
843 else
844 PyEval_SetProfile(NULL, NULL);
845 }
846 if (self->index > 0) {
847 /* Best effort to dump out any remaining data. */
848 flush_data(self);
849 }
850}
851
852static int
853is_available(ProfilerObject *self)
854{
855 if (self->active) {
856 PyErr_SetString(ProfilerError, "profiler already active");
857 return 0;
858 }
859 if (self->logfp == NULL) {
860 PyErr_SetString(ProfilerError, "profiler already closed");
861 return 0;
862 }
863 return 1;
864}
865
866
867/* Profiler object interface methods. */
868
Tim Petersfeab23f2001-10-13 00:11:10 +0000869static char close__doc__[] =
870"close()\n"
871"Shut down this profiler and close the log files, even if its active.";
Fred Drake8c081a12001-10-12 20:57:55 +0000872
873static PyObject *
874profiler_close(ProfilerObject *self, PyObject *args)
875{
876 PyObject *result = NULL;
877
878 if (PyArg_ParseTuple(args, ":close")) {
879 do_stop(self);
880 if (self->logfp != NULL) {
881 fclose(self->logfp);
882 self->logfp = NULL;
883 }
884 Py_INCREF(Py_None);
885 result = Py_None;
886 }
887 return result;
888}
889
Tim Petersfeab23f2001-10-13 00:11:10 +0000890static char runcall__doc__[] =
891"runcall(callable[, args[, kw]]) -> callable()\n"
892"Profile a specific function call, returning the result of that call.";
Fred Drake8c081a12001-10-12 20:57:55 +0000893
894static PyObject *
895profiler_runcall(ProfilerObject *self, PyObject *args)
896{
897 PyObject *result = NULL;
898 PyObject *callargs = NULL;
899 PyObject *callkw = NULL;
900 PyObject *callable;
901
902 if (PyArg_ParseTuple(args, "O|OO:runcall",
903 &callable, &callargs, &callkw)) {
904 if (is_available(self)) {
905 do_start(self);
906 result = PyEval_CallObjectWithKeywords(callable, callargs, callkw);
907 do_stop(self);
908 }
909 }
910 return result;
911}
912
Tim Petersfeab23f2001-10-13 00:11:10 +0000913static char runcode__doc__[] =
914"runcode(code, globals[, locals])\n"
915"Execute a code object while collecting profile data. If locals is\n"
916"omitted, globals is used for the locals as well.";
Fred Drake8c081a12001-10-12 20:57:55 +0000917
918static PyObject *
919profiler_runcode(ProfilerObject *self, PyObject *args)
920{
921 PyObject *result = NULL;
922 PyCodeObject *code;
923 PyObject *globals;
924 PyObject *locals = NULL;
925
926 if (PyArg_ParseTuple(args, "O!O!|O:runcode",
927 &PyCode_Type, &code,
928 &PyDict_Type, &globals,
929 &locals)) {
930 if (is_available(self)) {
931 if (locals == NULL || locals == Py_None)
932 locals = globals;
933 else if (!PyDict_Check(locals)) {
934 PyErr_SetString(PyExc_TypeError,
935 "locals must be a dictionary or None");
936 return NULL;
937 }
938 do_start(self);
939 result = PyEval_EvalCode(code, globals, locals);
940 do_stop(self);
941#if 0
942 if (!PyErr_Occurred()) {
943 result = Py_None;
944 Py_INCREF(result);
945 }
946#endif
947 }
948 }
949 return result;
950}
951
Tim Petersfeab23f2001-10-13 00:11:10 +0000952static char start__doc__[] =
953"start()\n"
954"Install this profiler for the current thread.";
Fred Drake8c081a12001-10-12 20:57:55 +0000955
956static PyObject *
957profiler_start(ProfilerObject *self, PyObject *args)
958{
959 PyObject *result = NULL;
960
961 if (PyArg_ParseTuple(args, ":start")) {
962 if (is_available(self))
963 do_start(self);
964 }
965 return result;
966}
967
Tim Petersfeab23f2001-10-13 00:11:10 +0000968static char stop__doc__[] =
969"stop()\n"
970"Remove this profiler from the current thread.";
Fred Drake8c081a12001-10-12 20:57:55 +0000971
972static PyObject *
973profiler_stop(ProfilerObject *self, PyObject *args)
974{
975 PyObject *result = NULL;
976
977 if (PyArg_ParseTuple(args, ":stop")) {
978 if (!self->active)
979 PyErr_SetString(ProfilerError, "profiler not active");
980 else
981 do_stop(self);
982 }
983 return result;
984}
985
986
987/* Python API support. */
988
989static void
990profiler_dealloc(ProfilerObject *self)
991{
992 do_stop(self);
993 if (self->logfp != NULL)
994 fclose(self->logfp);
995 Py_XDECREF(self->filemap);
996 Py_XDECREF(self->logfilename);
997 PyObject_Del((PyObject *)self);
998}
999
1000/* Always use METH_VARARGS even though some of these could be METH_NOARGS;
1001 * this allows us to maintain compatibility with Python versions < 2.2
1002 * more easily, requiring only the changes to the dispatcher to be made.
1003 */
1004static PyMethodDef profiler_methods[] = {
1005 {"close", (PyCFunction)profiler_close, METH_VARARGS, close__doc__},
1006 {"runcall", (PyCFunction)profiler_runcall, METH_VARARGS, runcall__doc__},
1007 {"runcode", (PyCFunction)profiler_runcode, METH_VARARGS, runcode__doc__},
1008 {"start", (PyCFunction)profiler_start, METH_VARARGS, start__doc__},
1009 {"stop", (PyCFunction)profiler_stop, METH_VARARGS, stop__doc__},
1010 {NULL, NULL}
1011};
1012
1013/* Use a table even though there's only one "simple" member; this allows
1014 * __members__ and therefore dir() to work.
1015 */
1016static struct memberlist profiler_members[] = {
1017 {"callcount", T_LONG, offsetof(ProfilerObject, callcount), READONLY},
1018 {"closed", T_INT, -1, READONLY},
1019 {"lineevents", T_LONG, offsetof(ProfilerObject, lineevents), READONLY},
1020 {"linetimings", T_LONG, offsetof(ProfilerObject, linetimings), READONLY},
1021 {NULL}
1022};
1023
1024static PyObject *
1025profiler_getattr(ProfilerObject *self, char *name)
1026{
1027 PyObject *result;
1028 if (strcmp(name, "closed") == 0) {
1029 result = (self->logfp == NULL) ? Py_True : Py_False;
1030 Py_INCREF(result);
1031 }
1032 else {
1033 result = PyMember_Get((char *)self, profiler_members, name);
1034 if (result == NULL) {
1035 PyErr_Clear();
1036 result = Py_FindMethod(profiler_methods, (PyObject *)self, name);
1037 }
1038 }
1039 return result;
1040}
1041
1042
Tim Petersfeab23f2001-10-13 00:11:10 +00001043static char profiler_object__doc__[] =
1044"High-performance profiler object.\n"
1045"\n"
1046"Methods:\n"
1047"\n"
1048"close(): Stop the profiler and close the log files.\n"
1049"runcall(): Run a single function call with profiling enabled.\n"
1050"runcode(): Execute a code object with profiling enabled.\n"
1051"start(): Install the profiler and return.\n"
1052"stop(): Remove the profiler.\n"
1053"\n"
1054"Attributes (read-only):\n"
1055"\n"
1056"callcount: The number of low-level calls to the profiler.\n"
1057"closed: True if the profiler has already been closed.\n"
1058"lineevents: True if SET_LINENO events are reported to the profiler.\n"
1059"linetimings: True if SET_LINENO events collect timing information.";
Fred Drake8c081a12001-10-12 20:57:55 +00001060
1061static PyTypeObject ProfilerType = {
1062 PyObject_HEAD_INIT(NULL)
1063 0, /* ob_size */
1064 "HotShot-profiler", /* tp_name */
1065 (int) sizeof(ProfilerObject), /* tp_basicsize */
1066 0, /* tp_itemsize */
1067 (destructor)profiler_dealloc, /* tp_dealloc */
1068 0, /* tp_print */
1069 (getattrfunc)profiler_getattr, /* tp_getattr */
1070 0, /* tp_setattr */
1071 0, /* tp_compare */
1072 0, /* tp_repr */
1073 0, /* tp_as_number */
1074 0, /* tp_as_sequence */
1075 0, /* tp_as_mapping */
1076 0, /* tp_hash */
1077 0, /* tp_call */
1078 0, /* tp_str */
1079 0, /* tp_getattro */
1080 0, /* tp_setattro */
1081 0, /* tp_as_buffer */
1082 0, /* tp_flags */
1083 profiler_object__doc__, /* tp_doc */
1084};
1085
1086
1087static PyMethodDef logreader_methods[] = {
1088 {"close", (PyCFunction)logreader_close, METH_VARARGS,
1089 logreader_close__doc__},
1090 {"next", (PyCFunction)logreader_next, METH_VARARGS,
1091 next__doc__},
1092 {NULL, NULL}
1093};
1094
1095static PyObject *
1096logreader_getattr(ProfilerObject *self, char *name)
1097{
1098 return Py_FindMethod(logreader_methods, (PyObject *)self, name);
1099}
1100
1101
1102static char logreader__doc__[] = "\
1103logreader(filename) --> log-iterator\n\
1104Create a log-reader for the timing information file.";
1105
1106static PySequenceMethods logreader_as_sequence = {
1107 0, /* sq_length */
1108 0, /* sq_concat */
1109 0, /* sq_repeat */
1110 (intargfunc)logreader_sq_item, /* sq_item */
1111 0, /* sq_slice */
1112 0, /* sq_ass_item */
1113 0, /* sq_ass_slice */
1114 0, /* sq_contains */
1115 0, /* sq_inplace_concat */
1116 0, /* sq_inplace_repeat */
1117};
1118
1119static PyTypeObject LogReaderType = {
1120 PyObject_HEAD_INIT(NULL)
1121 0, /* ob_size */
1122 "HotShot-logreader", /* tp_name */
1123 (int) sizeof(LogReaderObject), /* tp_basicsize */
1124 0, /* tp_itemsize */
1125 (destructor)logreader_dealloc, /* tp_dealloc */
1126 0, /* tp_print */
1127 (getattrfunc)logreader_getattr, /* tp_getattr */
1128 0, /* tp_setattr */
1129 0, /* tp_compare */
1130 0, /* tp_repr */
1131 0, /* tp_as_number */
1132 &logreader_as_sequence, /* tp_as_sequence */
1133 0, /* tp_as_mapping */
1134 0, /* tp_hash */
1135 0, /* tp_call */
1136 0, /* tp_str */
1137 0, /* tp_getattro */
1138 0, /* tp_setattro */
1139 0, /* tp_as_buffer */
1140 0, /* tp_flags */
1141 logreader__doc__, /* tp_doc */
1142#if Py_TPFLAGS_HAVE_ITER
1143 0, /* tp_traverse */
1144 0, /* tp_clear */
1145 0, /* tp_richcompare */
1146 0, /* tp_weaklistoffset */
1147 (getiterfunc)logreader_tp_iter, /* tp_iter */
1148 (iternextfunc)logreader_tp_iternext,/* tp_iternext */
1149#endif
1150};
1151
1152static PyObject *
1153hotshot_logreader(PyObject *unused, PyObject *args)
1154{
1155 LogReaderObject *self = NULL;
1156 char *filename;
1157
1158 if (PyArg_ParseTuple(args, "s:logreader", &filename)) {
1159 self = PyObject_New(LogReaderObject, &LogReaderType);
1160 if (self != NULL) {
1161 self->filled = 0;
1162 self->index = 0;
1163 self->linetimings = 0;
1164 self->logfp = fopen(filename, "rb");
1165 if (self->logfp == NULL) {
1166 PyErr_SetFromErrnoWithFilename(PyExc_IOError, filename);
1167 Py_DECREF(self);
1168 self = NULL;
1169 }
1170 }
1171 }
1172 return (PyObject *) self;
1173}
1174
1175
1176/* Return a Python string that represents the version number without the
1177 * extra cruft added by revision control, even if the right options were
1178 * given to the "cvs export" command to make it not include the extra
1179 * cruft.
1180 */
1181static char *
1182get_version_string(void)
1183{
1184 static char *rcsid = "$Revision$";
1185 char *rev = rcsid;
1186 char *buffer;
1187 int i = 0;
1188
1189 while (*rev && !isdigit(*rev))
1190 ++rev;
1191 while (rev[i] != ' ' && rev[i] != '\0')
1192 ++i;
1193 buffer = malloc(i + 1);
1194 if (buffer != NULL) {
1195 memmove(buffer, rev, i);
1196 buffer[i] = '\0';
1197 }
1198 return buffer;
1199}
1200
1201/* Write out a RFC 822-style header with various useful bits of
1202 * information to make the output easier to manage.
1203 */
1204static int
1205write_header(ProfilerObject *self)
1206{
1207 char *buffer;
1208 char cwdbuffer[PATH_MAX];
1209 PyObject *temp;
1210 int i, len;
1211
1212 buffer = get_version_string();
1213 if (buffer == NULL) {
1214 PyErr_NoMemory();
1215 return -1;
1216 }
1217 pack_add_info(self, "HotShot-Version", buffer);
1218 pack_add_info(self, "Requested-Line-Events",
1219 (self->lineevents ? "yes" : "no"));
1220 pack_add_info(self, "Platform", Py_GetPlatform());
1221 pack_add_info(self, "Executable", Py_GetProgramFullPath());
1222 buffer = (char *) Py_GetVersion();
1223 if (buffer == NULL)
1224 PyErr_Clear();
1225 else
1226 pack_add_info(self, "Executable-Version", buffer);
1227
1228#ifdef MS_WIN32
1229 sprintf(cwdbuffer, "%I64d", frequency.QuadPart);
1230 pack_add_info(self, "Reported-Performance-Frequency", cwdbuffer);
1231#else
1232 sprintf(cwdbuffer, "%lu", rusage_diff);
1233 pack_add_info(self, "Observed-Interval-getrusage", cwdbuffer);
1234 sprintf(cwdbuffer, "%lu", timeofday_diff);
1235 pack_add_info(self, "Observed-Interval-gettimeofday", cwdbuffer);
1236#endif
1237 pack_line_times(self);
1238
1239 pack_add_info(self, "Current-Directory",
1240 getcwd(cwdbuffer, sizeof cwdbuffer));
1241
1242 temp = PySys_GetObject("path");
1243 len = PyList_GET_SIZE(temp);
1244 for (i = 0; i < len; ++i) {
1245 PyObject *item = PyList_GET_ITEM(temp, i);
1246 buffer = PyString_AsString(item);
1247 if (buffer == NULL)
1248 return -1;
1249 pack_add_info(self, "Sys-Path-Entry", buffer);
1250 }
1251 return 0;
1252}
1253
1254static char profiler__doc__[] = "\
1255profiler(logfilename[, lineevents[, linetimes]]) -> profiler\n\
1256Create a new profiler object.";
1257
1258static PyObject *
1259hotshot_profiler(PyObject *unused, PyObject *args)
1260{
1261 char *logfilename;
1262 ProfilerObject *self = NULL;
1263 int lineevents = 0;
1264 int linetimings = 1;
1265
1266 if (PyArg_ParseTuple(args, "s|ii:profiler", &logfilename,
1267 &lineevents, &linetimings)) {
1268 self = PyObject_New(ProfilerObject, &ProfilerType);
1269 if (self == NULL)
1270 return NULL;
1271 self->callcount = 0;
1272 self->lineevents = lineevents ? 1 : 0;
1273 self->linetimings = (lineevents && linetimings) ? 1 : 0;
1274 self->index = 0;
1275 self->active = 0;
1276 self->next_fileno = 0;
Tim Peters1566a172001-10-12 22:08:39 +00001277 self->logfp = NULL;
Fred Drake8c081a12001-10-12 20:57:55 +00001278 self->logfilename = PyTuple_GET_ITEM(args, 0);
1279 Py_INCREF(self->logfilename);
1280 self->filemap = PyDict_New();
1281 if (self->filemap == NULL) {
1282 Py_DECREF(self);
1283 return NULL;
1284 }
1285 self->logfp = fopen(logfilename, "wb");
1286 if (self->logfp == NULL) {
1287 Py_DECREF(self);
1288 PyErr_SetFromErrnoWithFilename(PyExc_IOError, logfilename);
1289 return NULL;
1290 }
1291 if (timeofday_diff == 0) {
1292 /* Run this several times since sometimes the first
1293 * doesn't give the lowest values, and we're really trying
1294 * to determine the lowest.
1295 */
1296 calibrate();
1297 calibrate();
1298 calibrate();
1299 }
1300 if (write_header(self))
1301 /* some error occurred, exception has been set */
1302 self = NULL;
1303 }
1304 return (PyObject *) self;
1305}
1306
1307static char resolution__doc__[] =
1308#ifdef MS_WIN32
Tim Petersfeab23f2001-10-13 00:11:10 +00001309"resolution() -> (performance-counter-ticks, update-frequency)\n"
1310"Return the resolution of the timer provided by the QueryPerformanceCounter()\n"
1311"function. The first value is the smallest observed change, and the second\n"
1312"is the result of QueryPerformanceFrequency().";
Fred Drake8c081a12001-10-12 20:57:55 +00001313#else
Tim Petersfeab23f2001-10-13 00:11:10 +00001314"resolution() -> (gettimeofday-usecs, getrusage-usecs)\n"
1315"Return the resolution of the timers provided by the gettimeofday() and\n"
1316"getrusage() system calls, or -1 if the call is not supported.";
Fred Drake8c081a12001-10-12 20:57:55 +00001317#endif
1318
1319static PyObject *
1320hotshot_resolution(PyObject *unused, PyObject *args)
1321{
1322 PyObject *result = NULL;
1323
1324 if (PyArg_ParseTuple(args, ":resolution")) {
1325 if (timeofday_diff == 0) {
1326 calibrate();
1327 calibrate();
1328 calibrate();
1329 }
1330#ifdef MS_WIN32
1331 result = Py_BuildValue("ii", timeofday_diff, frequency.LowPart);
1332#else
1333 result = Py_BuildValue("ii", timeofday_diff, rusage_diff);
1334#endif
1335 }
1336 return result;
1337}
1338
1339
1340static PyMethodDef functions[] = {
1341 {"profiler", hotshot_profiler, METH_VARARGS, profiler__doc__},
1342 {"logreader", hotshot_logreader, METH_VARARGS, logreader__doc__},
1343 {"resolution", hotshot_resolution, METH_VARARGS, resolution__doc__},
1344 {NULL, NULL}
1345};
1346
1347
1348void
1349init_hotshot(void)
1350{
1351 PyObject *module;
1352
1353 LogReaderType.ob_type = &PyType_Type;
1354 ProfilerType.ob_type = &PyType_Type;
1355 module = Py_InitModule("_hotshot", functions);
1356 if (module != NULL) {
1357 char *s = get_version_string();
1358
1359 PyModule_AddStringConstant(module, "__version__", s);
1360 free(s);
1361 Py_INCREF(&LogReaderType);
1362 PyModule_AddObject(module, "LogReaderType",
1363 (PyObject *)&LogReaderType);
1364 Py_INCREF(&ProfilerType);
1365 PyModule_AddObject(module, "ProfilerType",
1366 (PyObject *)&ProfilerType);
1367
1368 if (ProfilerError == NULL)
1369 ProfilerError = PyErr_NewException("hotshot.ProfilerError",
1370 NULL, NULL);
1371 if (ProfilerError != NULL) {
1372 Py_INCREF(ProfilerError);
1373 PyModule_AddObject(module, "ProfilerError", ProfilerError);
1374 }
1375 PyModule_AddIntConstant(module, "WHAT_ENTER", WHAT_ENTER);
1376 PyModule_AddIntConstant(module, "WHAT_EXIT", WHAT_EXIT);
1377 PyModule_AddIntConstant(module, "WHAT_LINENO", WHAT_LINENO);
1378 PyModule_AddIntConstant(module, "WHAT_OTHER", WHAT_OTHER);
1379 PyModule_AddIntConstant(module, "WHAT_ADD_INFO", WHAT_ADD_INFO);
1380 PyModule_AddIntConstant(module, "WHAT_DEFINE_FILE", WHAT_DEFINE_FILE);
1381 PyModule_AddIntConstant(module, "WHAT_LINE_TIMES", WHAT_LINE_TIMES);
1382 }
1383}