blob: 16af56f89420b39f993beb310c3f5247f0ef29d4 [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;
Fred Drake30d1c752001-10-15 22:11:02 +000068 int frametimings;
Fred Drake8c081a12001-10-12 20:57:55 +000069 /* size_t filled; */
70 int active;
71 int next_fileno;
Fred Drake8c081a12001-10-12 20:57:55 +000072 hs_time prev_timeofday;
73} ProfilerObject;
74
75typedef struct {
76 PyObject_HEAD
77 FILE *logfp;
78 int filled;
79 int index;
80 int linetimings;
Fred Drake30d1c752001-10-15 22:11:02 +000081 int frametimings;
Fred Drake8c081a12001-10-12 20:57:55 +000082 unsigned char buffer[BUFFERSIZE];
83} LogReaderObject;
84
85static PyObject * ProfilerError = NULL;
86
87
88#ifndef MS_WIN32
89#ifdef GETTIMEOFDAY_NO_TZ
90#define GETTIMEOFDAY(ptv) gettimeofday((ptv))
91#else
92#define GETTIMEOFDAY(ptv) gettimeofday((ptv), (struct timezone *)NULL)
93#endif
94#endif
95
96
97/* The log reader... */
98
Tim Petersfeab23f2001-10-13 00:11:10 +000099static char logreader_close__doc__[] =
100"close()\n"
101"Close the log file, preventing additional records from being read.";
Fred Drake8c081a12001-10-12 20:57:55 +0000102
103static PyObject *
104logreader_close(LogReaderObject *self, PyObject *args)
105{
106 PyObject *result = NULL;
107 if (PyArg_ParseTuple(args, ":close")) {
108 if (self->logfp != NULL) {
109 fclose(self->logfp);
110 self->logfp = NULL;
111 }
112 result = Py_None;
113 Py_INCREF(result);
114 }
115 return result;
116}
117
118#if Py_TPFLAGS_HAVE_ITER
119/* This is only used if the interpreter has iterator support; the
120 * iternext handler is also used as a helper for other functions, so
121 * does not need to be included in this conditional section.
122 */
123static PyObject *
124logreader_tp_iter(LogReaderObject *self)
125{
126 Py_INCREF(self);
127 return (PyObject *) self;
128}
129#endif
130
131
132/* Log File Format
133 * ---------------
134 *
135 * The log file consists of a sequence of variable-length records.
136 * Each record is identified with a record type identifier in two
137 * bits of the first byte. The two bits are the "least significant"
138 * bits of the byte.
139 *
140 * Low bits: Opcode: Meaning:
141 * 0x00 ENTER enter a frame
142 * 0x01 EXIT exit a frame
143 * 0x02 LINENO SET_LINENO instruction was executed
144 * 0x03 OTHER more bits are needed to deecode
145 *
146 * If the type is OTHER, the record is not packed so tightly, and the
147 * remaining bits are used to disambiguate the record type. These
148 * records are not used as frequently so compaction is not an issue.
149 * Each of the first three record types has a highly tailored
150 * structure that allows it to be packed tightly.
151 *
152 * The OTHER records have the following identifiers:
153 *
154 * First byte: Opcode: Meaning:
155 * 0x13 ADD_INFO define a key/value pair
156 * 0x23 DEFINE_FILE define an int->filename mapping
157 * 0x33 LINE_TIMES indicates if LINENO events have tdeltas
Fred Drake30d1c752001-10-15 22:11:02 +0000158 * 0x43 DEFINE_FUNC define a (fileno,lineno)->funcname mapping
159 * 0x53 FRAME_TIMES indicates if ENTER/EXIT events have tdeltas
Fred Drake8c081a12001-10-12 20:57:55 +0000160 *
161 * Packed Integers
162 *
163 * "Packed integers" are non-negative integer values encoded as a
164 * sequence of bytes. Each byte is encoded such that the most
165 * significant bit is set if the next byte is also part of the
166 * integer. Each byte provides bits to the least-significant end of
167 * the result; the accumulated value must be shifted up to place the
168 * new bits into the result.
169 *
170 * "Modified packed integers" are packed integers where only a portion
171 * of the first byte is used. In the rest of the specification, these
172 * are referred to as "MPI(n,name)", where "n" is the number of bits
173 * discarded from the least-signicant positions of the byte, and
174 * "name" is a name being given to those "discarded" bits, since they
175 * are a field themselves.
176 *
177 * ENTER records:
178 *
179 * MPI(2,type) fileno -- type is 0x00
Fred Drake8c081a12001-10-12 20:57:55 +0000180 * PI lineno
Fred Drake30d1c752001-10-15 22:11:02 +0000181 * PI tdelta -- iff frame times are enabled
Fred Drake8c081a12001-10-12 20:57:55 +0000182 *
183 * EXIT records
184 *
Fred Drake30d1c752001-10-15 22:11:02 +0000185 * MPI(2,type) tdelta -- type is 0x01; tdelta will be 0
186 * if frame times are disabled
Fred Drake8c081a12001-10-12 20:57:55 +0000187 *
188 * LINENO records
189 *
190 * MPI(2,type) lineno -- type is 0x02
191 * PI tdelta -- iff LINENO includes it
192 *
193 * ADD_INFO records
194 *
Fred Drake30d1c752001-10-15 22:11:02 +0000195 * BYTE type -- always 0x13
Fred Drake8c081a12001-10-12 20:57:55 +0000196 * PI len1 -- length of first string
197 * BYTE string1[len1] -- len1 bytes of string data
198 * PI len2 -- length of second string
199 * BYTE string2[len2] -- len2 bytes of string data
200 *
201 * DEFINE_FILE records
202 *
Fred Drake30d1c752001-10-15 22:11:02 +0000203 * BYTE type -- always 0x23
Fred Drake8c081a12001-10-12 20:57:55 +0000204 * PI fileno
205 * PI len -- length of filename
206 * BYTE filename[len] -- len bytes of string data
207 *
Fred Drake30d1c752001-10-15 22:11:02 +0000208 * DEFINE_FUNC records
209 *
210 * BYTE type -- always 0x43
211 * PI fileno
212 * PI lineno
213 * PI len -- length of funcname
214 * BYTE funcname[len] -- len bytes of string data
215 *
Fred Drake8c081a12001-10-12 20:57:55 +0000216 * LINE_TIMES records
Fred Drake30d1c752001-10-15 22:11:02 +0000217 *
218 * This record can be used only before the start of ENTER/EXIT/LINENO
219 * records. If have_tdelta is true, LINENO records will include the
220 * tdelta field, otherwise it will be omitted. If this record is not
221 * given, LINENO records will not contain the tdelta field.
222 *
223 * BYTE type -- always 0x33
Fred Drake8c081a12001-10-12 20:57:55 +0000224 * BYTE have_tdelta -- 0 if LINENO does *not* have
225 * timing information
Fred Drake30d1c752001-10-15 22:11:02 +0000226 * FRAME_TIMES records
227 *
228 * This record can be used only before the start of ENTER/EXIT/LINENO
229 * records. If have_tdelta is true, ENTER and EXIT records will
230 * include the tdelta field, otherwise it will be omitted. If this
231 * record is not given, ENTER and EXIT records will contain the tdelta
232 * field.
233 *
234 * BYTE type -- always 0x53
235 * BYTE have_tdelta -- 0 if ENTER/EXIT do *not* have
236 * timing information
Fred Drake8c081a12001-10-12 20:57:55 +0000237 */
238
239#define WHAT_ENTER 0x00
240#define WHAT_EXIT 0x01
241#define WHAT_LINENO 0x02
242#define WHAT_OTHER 0x03 /* only used in decoding */
243#define WHAT_ADD_INFO 0x13
244#define WHAT_DEFINE_FILE 0x23
245#define WHAT_LINE_TIMES 0x33
Fred Drake30d1c752001-10-15 22:11:02 +0000246#define WHAT_DEFINE_FUNC 0x43
247#define WHAT_FRAME_TIMES 0x53
Fred Drake8c081a12001-10-12 20:57:55 +0000248
249#define ERR_NONE 0
250#define ERR_EOF -1
251#define ERR_EXCEPTION -2
252
253#define PISIZE (sizeof(int) + 1)
254#define MPISIZE (PISIZE + 1)
255
256/* Maximum size of "normal" events -- nothing that contains string data */
257#define MAXEVENTSIZE (MPISIZE + PISIZE*2)
258
259
260/* Unpack a packed integer; if "discard" is non-zero, unpack a modified
261 * packed integer with "discard" discarded bits.
262 */
263static int
264unpack_packed_int(LogReaderObject *self, int *pvalue, int discard)
265{
266 int accum = 0;
267 int bits = 0;
268 int index = self->index;
269 int cont;
270
271 do {
272 if (index >= self->filled)
273 return ERR_EOF;
274 /* read byte */
275 accum |= ((self->buffer[index] & 0x7F) >> discard) << bits;
276 bits += (7 - discard);
277 cont = self->buffer[index] & 0x80;
278 /* move to next */
279 discard = 0;
280 index++;
281 } while (cont);
282
283 /* save state */
284 self->index = index;
285 *pvalue = accum;
286
287 return 0;
288}
289
290/* Unpack a string, which is encoded as a packed integer giving the
291 * length of the string, followed by the string data.
292 */
293static int
294unpack_string(LogReaderObject *self, PyObject **pvalue)
295{
296 int len;
297 int oldindex = self->index;
298 int err = unpack_packed_int(self, &len, 0);
299
300 if (!err) {
301 /* need at least len bytes in buffer */
302 if (len > (self->filled - self->index)) {
303 self->index = oldindex;
304 err = ERR_EOF;
305 }
306 else {
307 *pvalue = PyString_FromStringAndSize(self->buffer + self->index,
308 len);
309 if (*pvalue == NULL) {
310 self->index = oldindex;
311 err = ERR_EXCEPTION;
312 }
313 else
314 self->index += len;
315 }
316 }
317 return err;
318}
319
320
321static PyObject *
322logreader_tp_iternext(LogReaderObject *self)
323{
324 int what, oldindex;
325 int err = ERR_NONE;
326 int lineno = -1;
327 int fileno = -1;
328 int tdelta = -1;
329 PyObject *s1 = NULL, *s2 = NULL;
330 PyObject *result = NULL;
331#if 0
332 unsigned char b0, b1;
333#endif
334
335 if (self->logfp == NULL) {
336 PyErr_SetString(ProfilerError,
337 "cannot iterate over closed LogReader object");
338 return NULL;
339 }
340 restart:
341 if ((self->filled - self->index) < MAXEVENTSIZE) {
342 /* add a little to the buffer */
343 int needed;
344 size_t res;
345 refill:
346 if (self->index) {
347 memmove(self->buffer, &self->buffer[self->index],
348 self->filled - self->index);
349 self->filled = self->filled - self->index;
350 self->index = 0;
351 }
352 needed = BUFFERSIZE - self->filled;
353 res = fread(&self->buffer[self->filled], 1, needed, self->logfp);
354 self->filled += res;
355 }
356 /* end of input */
357 if (self->filled == 0)
358 return NULL;
359
360 oldindex = self->index;
361
362 /* decode the record type */
363 what = self->buffer[self->index] & WHAT_OTHER;
364 if (what == WHAT_OTHER) {
365 what = self->buffer[self->index];
366 self->index++;
367 }
368 switch (what) {
369 case WHAT_ENTER:
370 err = unpack_packed_int(self, &fileno, 2);
371 if (!err) {
Fred Drake30d1c752001-10-15 22:11:02 +0000372 err = unpack_packed_int(self, &lineno, 0);
373 if (self->frametimings && !err)
374 err = unpack_packed_int(self, &tdelta, 0);
Fred Drake8c081a12001-10-12 20:57:55 +0000375 }
376 break;
377 case WHAT_EXIT:
378 err = unpack_packed_int(self, &tdelta, 2);
379 break;
380 case WHAT_LINENO:
381 err = unpack_packed_int(self, &lineno, 2);
382 if (self->linetimings && !err)
383 err = unpack_packed_int(self, &tdelta, 0);
384 break;
385 case WHAT_ADD_INFO:
386 err = unpack_string(self, &s1);
387 if (!err) {
388 err = unpack_string(self, &s2);
389 if (err) {
390 Py_DECREF(s1);
391 s1 = NULL;
392 }
393 }
394 break;
395 case WHAT_DEFINE_FILE:
396 err = unpack_packed_int(self, &fileno, 0);
397 if (!err) {
398 err = unpack_string(self, &s1);
399 if (!err) {
400 Py_INCREF(Py_None);
401 s2 = Py_None;
402 }
403 }
404 break;
Fred Drake30d1c752001-10-15 22:11:02 +0000405 case WHAT_DEFINE_FUNC:
406 err = unpack_packed_int(self, &fileno, 0);
407 if (!err) {
408 err = unpack_packed_int(self, &lineno, 0);
409 if (!err)
410 err = unpack_string(self, &s1);
411 }
412 break;
Fred Drake8c081a12001-10-12 20:57:55 +0000413 case WHAT_LINE_TIMES:
414 if (self->index >= self->filled)
415 err = ERR_EOF;
416 else {
417 self->linetimings = self->buffer[self->index] ? 1 : 0;
418 self->index++;
419 goto restart;
420 }
Fred Drake30d1c752001-10-15 22:11:02 +0000421 case WHAT_FRAME_TIMES:
422 if (self->index >= self->filled)
423 err = ERR_EOF;
424 else {
425 self->frametimings = self->buffer[self->index] ? 1 : 0;
426 self->index++;
427 goto restart;
428 }
Fred Drake8c081a12001-10-12 20:57:55 +0000429 default:
Tim Peters1566a172001-10-12 22:08:39 +0000430 ;
Fred Drake8c081a12001-10-12 20:57:55 +0000431 }
432 if (err == ERR_EOF && oldindex != 0) {
433 /* It looks like we ran out of data before we had it all; this
434 * could easily happen with large packed integers or string
435 * data. Try forcing the buffer to be re-filled before failing.
436 */
437 err = ERR_NONE;
438 goto refill;
439 }
440 if (err == ERR_EOF) {
441 /* Could not avoid end-of-buffer error. */
442 PyErr_SetString(PyExc_EOFError,
443 "end of file with incomplete profile record");
444 }
445 else if (!err) {
446 result = PyTuple_New(4);
447 PyTuple_SET_ITEM(result, 0, PyInt_FromLong(what));
448 PyTuple_SET_ITEM(result, 2, PyInt_FromLong(fileno));
Fred Drake30d1c752001-10-15 22:11:02 +0000449 if (s1 == NULL)
Fred Drake8c081a12001-10-12 20:57:55 +0000450 PyTuple_SET_ITEM(result, 1, PyInt_FromLong(tdelta));
Fred Drake30d1c752001-10-15 22:11:02 +0000451 else
Fred Drake8c081a12001-10-12 20:57:55 +0000452 PyTuple_SET_ITEM(result, 1, s1);
Fred Drake30d1c752001-10-15 22:11:02 +0000453 if (s2 == NULL)
454 PyTuple_SET_ITEM(result, 3, PyInt_FromLong(lineno));
455 else
Fred Drake8c081a12001-10-12 20:57:55 +0000456 PyTuple_SET_ITEM(result, 3, s2);
Fred Drake8c081a12001-10-12 20:57:55 +0000457 }
458 /* The only other case is err == ERR_EXCEPTION, in which case the
459 * exception is already set.
460 */
461#if 0
462 b0 = self->buffer[self->index];
463 b1 = self->buffer[self->index + 1];
464 if (b0 & 1) {
465 /* This is a line-number event. */
466 what = PyTrace_LINE;
467 lineno = ((b0 & ~1) << 7) + b1;
468 self->index += 2;
469 }
470 else {
471 what = (b0 & 0x0E) >> 1;
472 tdelta = ((b0 & 0xF0) << 4) + b1;
473 if (what == PyTrace_CALL) {
474 /* we know there's a 2-byte file ID & 2-byte line number */
475 fileno = ((self->buffer[self->index + 2] << 8)
476 + self->buffer[self->index + 3]);
477 lineno = ((self->buffer[self->index + 4] << 8)
478 + self->buffer[self->index + 5]);
479 self->index += 6;
480 }
481 else
482 self->index += 2;
483 }
484#endif
485 return result;
486}
487
488static void
489logreader_dealloc(LogReaderObject *self)
490{
491 if (self->logfp != NULL) {
492 fclose(self->logfp);
493 self->logfp = NULL;
494 }
495 PyObject_Del(self);
496}
497
498static PyObject *
499logreader_sq_item(LogReaderObject *self, int index)
500{
501 PyObject *result = logreader_tp_iternext(self);
502 if (result == NULL && !PyErr_Occurred()) {
503 PyErr_SetString(PyExc_IndexError, "no more events in log");
504 return NULL;
505 }
506 return result;
507}
508
Tim Petersfeab23f2001-10-13 00:11:10 +0000509static char next__doc__[] =
510"next() -> event-info\n"
511"Return the next event record from the log file.";
Fred Drake8c081a12001-10-12 20:57:55 +0000512
513static PyObject *
514logreader_next(LogReaderObject *self, PyObject *args)
515{
516 PyObject *result = NULL;
517
518 if (PyArg_ParseTuple(args, ":next")) {
519 result = logreader_tp_iternext(self);
520 /* XXX return None if there's nothing left */
521 /* tp_iternext does the right thing, though */
522 if (result == NULL && !PyErr_Occurred()) {
523 result = Py_None;
524 Py_INCREF(result);
525 }
526 }
527 return result;
528}
529
530
531static int
532flush_data(ProfilerObject *self)
533{
534 /* Need to dump data to the log file... */
535 size_t written = fwrite(self->buffer, 1, self->index, self->logfp);
Tim Peters1566a172001-10-12 22:08:39 +0000536 if (written == (size_t)self->index)
Fred Drake8c081a12001-10-12 20:57:55 +0000537 self->index = 0;
538 else {
539 memmove(self->buffer, &self->buffer[written],
540 self->index - written);
541 self->index -= written;
542 if (written == 0) {
543 char *s = PyString_AsString(self->logfilename);
544 PyErr_SetFromErrnoWithFilename(PyExc_IOError, s);
545 return -1;
546 }
547 }
548 if (written > 0) {
549 if (fflush(self->logfp)) {
550 char *s = PyString_AsString(self->logfilename);
551 PyErr_SetFromErrnoWithFilename(PyExc_IOError, s);
552 return -1;
553 }
554 }
555 return 0;
556}
557
558static inline void
559pack_packed_int(ProfilerObject *self, int value)
560{
561 unsigned char partial;
562
563 do {
564 partial = value & 0x7F;
565 value >>= 7;
566 if (value)
567 partial |= 0x80;
568 self->buffer[self->index] = partial;
569 self->index++;
570 } while (value);
571}
572
573/* Encode a modified packed integer, with a subfield of modsize bits
574 * containing the value "subfield". The value of subfield is not
575 * checked to ensure it actually fits in modsize bits.
576 */
577static inline void
578pack_modified_packed_int(ProfilerObject *self, int value,
579 int modsize, int subfield)
580{
581 const int maxvalues[] = {-1, 1, 3, 7, 15, 31, 63, 127};
582
583 int bits = 7 - modsize;
584 int partial = value & maxvalues[bits];
585 unsigned char b = subfield | (partial << modsize);
586
587 if (partial != value) {
588 b |= 0x80;
589 self->buffer[self->index] = b;
590 self->index++;
591 pack_packed_int(self, value >> bits);
592 }
593 else {
594 self->buffer[self->index] = b;
595 self->index++;
596 }
597}
598
599static void
Fred Drake30d1c752001-10-15 22:11:02 +0000600pack_string(ProfilerObject *self, const char *s, int len)
Fred Drake8c081a12001-10-12 20:57:55 +0000601{
Fred Drake30d1c752001-10-15 22:11:02 +0000602 if (len + PISIZE + self->index >= BUFFERSIZE)
Fred Drake8c081a12001-10-12 20:57:55 +0000603 (void) flush_data(self);
Fred Drake30d1c752001-10-15 22:11:02 +0000604 pack_packed_int(self, len);
Fred Drake8c081a12001-10-12 20:57:55 +0000605 memcpy(self->buffer + self->index, s, len);
606 self->index += len;
607}
608
609static void
610pack_add_info(ProfilerObject *self, const char *s1, const char *s2)
611{
612 int len1 = strlen(s1);
613 int len2 = strlen(s2);
614
615 if (len1 + len2 + PISIZE*2 + 1 + self->index >= BUFFERSIZE)
616 (void) flush_data(self);
617 self->buffer[self->index] = WHAT_ADD_INFO;
618 self->index++;
Fred Drake30d1c752001-10-15 22:11:02 +0000619 pack_string(self, s1, len1);
620 pack_string(self, s2, len2);
Fred Drake8c081a12001-10-12 20:57:55 +0000621}
622
623static void
624pack_define_file(ProfilerObject *self, int fileno, const char *filename)
625{
626 int len = strlen(filename);
627
628 if (len + PISIZE*2 + 1 + self->index >= BUFFERSIZE)
629 (void) flush_data(self);
630 self->buffer[self->index] = WHAT_DEFINE_FILE;
631 self->index++;
632 pack_packed_int(self, fileno);
Fred Drake30d1c752001-10-15 22:11:02 +0000633 pack_string(self, filename, len);
634}
635
636static void
637pack_define_func(ProfilerObject *self, int fileno, int lineno,
638 const char *funcname)
639{
640 int len = strlen(funcname);
641
642 if (len + PISIZE*3 + 1 + self->index >= BUFFERSIZE)
643 (void) flush_data(self);
644 self->buffer[self->index] = WHAT_DEFINE_FUNC;
645 self->index++;
646 pack_packed_int(self, fileno);
647 pack_packed_int(self, lineno);
648 pack_string(self, funcname, len);
Fred Drake8c081a12001-10-12 20:57:55 +0000649}
650
651static void
652pack_line_times(ProfilerObject *self)
653{
654 if (2 + self->index >= BUFFERSIZE)
655 (void) flush_data(self);
656 self->buffer[self->index] = WHAT_LINE_TIMES;
657 self->buffer[self->index + 1] = self->linetimings ? 1 : 0;
658 self->index += 2;
659}
660
Fred Drake30d1c752001-10-15 22:11:02 +0000661static void
662pack_frame_times(ProfilerObject *self)
663{
664 if (2 + self->index >= BUFFERSIZE)
665 (void) flush_data(self);
666 self->buffer[self->index] = WHAT_FRAME_TIMES;
667 self->buffer[self->index + 1] = self->frametimings ? 1 : 0;
668 self->index += 2;
669}
670
Fred Drake8c081a12001-10-12 20:57:55 +0000671static inline void
672pack_enter(ProfilerObject *self, int fileno, int tdelta, int lineno)
673{
674 if (MPISIZE + PISIZE*2 + self->index >= BUFFERSIZE)
675 (void) flush_data(self);
676 pack_modified_packed_int(self, fileno, 2, WHAT_ENTER);
Fred Drake8c081a12001-10-12 20:57:55 +0000677 pack_packed_int(self, lineno);
Fred Drake30d1c752001-10-15 22:11:02 +0000678 if (self->frametimings)
679 pack_packed_int(self, tdelta);
Fred Drake8c081a12001-10-12 20:57:55 +0000680}
681
682static inline void
683pack_exit(ProfilerObject *self, int tdelta)
684{
685 if (MPISIZE + self->index >= BUFFERSIZE)
686 (void) flush_data(self);
Fred Drake30d1c752001-10-15 22:11:02 +0000687 if (self->frametimings)
688 pack_modified_packed_int(self, tdelta, 2, WHAT_EXIT);
689 else {
690 self->buffer[self->index] = WHAT_EXIT;
691 self->index++;
692 }
Fred Drake8c081a12001-10-12 20:57:55 +0000693}
694
695static inline void
696pack_lineno(ProfilerObject *self, int lineno)
697{
698 if (MPISIZE + self->index >= BUFFERSIZE)
699 (void) flush_data(self);
700 pack_modified_packed_int(self, lineno, 2, WHAT_LINENO);
701}
702
703static inline void
704pack_lineno_tdelta(ProfilerObject *self, int lineno, int tdelta)
705{
706 if (MPISIZE + PISIZE + self->index >= BUFFERSIZE)
707 (void) flush_data(self);
708 pack_modified_packed_int(self, lineno, 2, WHAT_LINENO);
709 pack_packed_int(self, tdelta);
710}
711
712static inline int
713get_fileno(ProfilerObject *self, PyCodeObject *fcode)
714{
Fred Drake30d1c752001-10-15 22:11:02 +0000715 /* This is only used for ENTER events. */
716
717 PyObject *obj;
718 PyObject *dict;
Fred Drake8c081a12001-10-12 20:57:55 +0000719 int fileno;
720
Fred Drake30d1c752001-10-15 22:11:02 +0000721 obj = PyDict_GetItem(self->filemap, fcode->co_filename);
722 if (obj == NULL) {
Fred Drake8c081a12001-10-12 20:57:55 +0000723 /* first sighting of this file */
Fred Drake30d1c752001-10-15 22:11:02 +0000724 dict = PyDict_New();
725 if (dict == NULL) {
Fred Drake8c081a12001-10-12 20:57:55 +0000726 return -1;
727 }
Fred Drake30d1c752001-10-15 22:11:02 +0000728 fileno = self->next_fileno;
729 obj = Py_BuildValue("iN", fileno, dict);
730 if (obj == NULL) {
731 return -1;
732 }
733 if (PyDict_SetItem(self->filemap, fcode->co_filename, obj)) {
734 Py_DECREF(obj);
Fred Drake8c081a12001-10-12 20:57:55 +0000735 return -1;
736 }
737 self->next_fileno++;
Fred Drake30d1c752001-10-15 22:11:02 +0000738 Py_DECREF(obj);
Fred Drake8c081a12001-10-12 20:57:55 +0000739 pack_define_file(self, fileno, PyString_AS_STRING(fcode->co_filename));
740 }
741 else {
742 /* already know this ID */
Fred Drake30d1c752001-10-15 22:11:02 +0000743 fileno = PyInt_AS_LONG(PyTuple_GET_ITEM(obj, 0));
744 dict = PyTuple_GET_ITEM(obj, 1);
745 }
746 /* make sure we save a function name for this (fileno, lineno) */
747 obj = PyInt_FromLong(fcode->co_firstlineno);
748 if (obj == NULL) {
749 /* We just won't have it saved; too bad. */
750 PyErr_Clear();
751 }
752 else {
753 PyObject *name = PyDict_GetItem(dict, obj);
754 if (name == NULL) {
755 pack_define_func(self, fileno, fcode->co_firstlineno,
756 PyString_AS_STRING(fcode->co_name));
757 if (PyDict_SetItem(dict, obj, fcode->co_name))
758 return -1;
759 }
Fred Drake8c081a12001-10-12 20:57:55 +0000760 }
761 return fileno;
762}
763
764static inline int
765get_tdelta(ProfilerObject *self)
766{
767 int tdelta;
768#ifdef MS_WIN32
769 hs_time tv;
Tim Peters7d99ff22001-10-13 07:37:52 +0000770 hs_time diff;
Fred Drake8c081a12001-10-12 20:57:55 +0000771
Tim Peters7d99ff22001-10-13 07:37:52 +0000772 GETTIMEOFDAY(&tv);
773 diff = tv - self->prev_timeofday;
774 tdelta = (int)diff;
Fred Drake8c081a12001-10-12 20:57:55 +0000775#else
776 struct timeval tv;
777
778 GETTIMEOFDAY(&tv);
779
780 if (tv.tv_sec == self->prev_timeofday.tv_sec)
781 tdelta = tv.tv_usec - self->prev_timeofday.tv_usec;
782 else
783 tdelta = ((tv.tv_sec - self->prev_timeofday.tv_sec) * 1000000
784 + tv.tv_usec);
785#endif
786 self->prev_timeofday = tv;
787 return tdelta;
788}
789
790
791/* The workhorse: the profiler callback function. */
792
793static int
794profiler_callback(ProfilerObject *self, PyFrameObject *frame, int what,
795 PyObject *arg)
796{
Fred Drake30d1c752001-10-15 22:11:02 +0000797 int tdelta = -1;
Fred Drake8c081a12001-10-12 20:57:55 +0000798 int fileno;
799
Fred Drake30d1c752001-10-15 22:11:02 +0000800 if (self->frametimings)
801 tdelta = get_tdelta(self);
Fred Drake8c081a12001-10-12 20:57:55 +0000802 switch (what) {
803 case PyTrace_CALL:
804 fileno = get_fileno(self, frame->f_code);
805 if (fileno < 0)
806 return -1;
807 pack_enter(self, fileno, tdelta,
808 frame->f_code->co_firstlineno);
809 break;
810 case PyTrace_RETURN:
811 pack_exit(self, tdelta);
812 break;
813 default:
814 /* should never get here */
815 break;
816 }
817 return 0;
818}
819
820
821/* Alternate callback when we want PyTrace_LINE events */
822
823static int
824tracer_callback(ProfilerObject *self, PyFrameObject *frame, int what,
825 PyObject *arg)
826{
827 int fileno;
828
Fred Drake8c081a12001-10-12 20:57:55 +0000829 switch (what) {
830 case PyTrace_CALL:
831 fileno = get_fileno(self, frame->f_code);
832 if (fileno < 0)
833 return -1;
Fred Drake30d1c752001-10-15 22:11:02 +0000834 pack_enter(self, fileno, self->frametimings ? get_tdelta(self) : -1,
Fred Drake8c081a12001-10-12 20:57:55 +0000835 frame->f_code->co_firstlineno);
836 break;
837 case PyTrace_RETURN:
838 pack_exit(self, get_tdelta(self));
839 break;
Tim Peters1566a172001-10-12 22:08:39 +0000840 case PyTrace_LINE:
Fred Drake8c081a12001-10-12 20:57:55 +0000841 if (self->linetimings)
842 pack_lineno_tdelta(self, frame->f_lineno, get_tdelta(self));
843 else
844 pack_lineno(self, frame->f_lineno);
845 break;
846 default:
847 /* ignore PyTrace_EXCEPTION */
848 break;
849 }
850 return 0;
851}
852
853
854/* A couple of useful helper functions. */
855
856#ifdef MS_WIN32
Tim Petersfeab23f2001-10-13 00:11:10 +0000857static LARGE_INTEGER frequency = {0, 0};
Fred Drake8c081a12001-10-12 20:57:55 +0000858#endif
859
860static unsigned long timeofday_diff = 0;
861static unsigned long rusage_diff = 0;
862
863static void
864calibrate(void)
865{
866 hs_time tv1, tv2;
867
868#ifdef MS_WIN32
Tim Peters7d99ff22001-10-13 07:37:52 +0000869 hs_time diff;
Fred Drake8c081a12001-10-12 20:57:55 +0000870 QueryPerformanceFrequency(&frequency);
871#endif
872
873 GETTIMEOFDAY(&tv1);
874 while (1) {
875 GETTIMEOFDAY(&tv2);
876#ifdef MS_WIN32
Tim Peters7d99ff22001-10-13 07:37:52 +0000877 diff = tv2 - tv1;
878 if (diff != 0) {
879 timeofday_diff = (unsigned long)diff;
Fred Drake8c081a12001-10-12 20:57:55 +0000880 break;
881 }
882#else
883 if (tv1.tv_sec != tv2.tv_sec || tv1.tv_usec != tv2.tv_usec) {
884 if (tv1.tv_sec == tv2.tv_sec)
885 timeofday_diff = tv2.tv_usec - tv1.tv_usec;
886 else
887 timeofday_diff = (1000000 - tv1.tv_usec) + tv2.tv_usec;
888 break;
889 }
890#endif
891 }
892#ifdef MS_WIN32
893 rusage_diff = -1;
894#else
895 {
896 struct rusage ru1, ru2;
897
898 getrusage(RUSAGE_SELF, &ru1);
899 while (1) {
900 getrusage(RUSAGE_SELF, &ru2);
901 if (ru1.ru_utime.tv_sec != ru2.ru_utime.tv_sec) {
902 rusage_diff = ((1000000 - ru1.ru_utime.tv_usec)
903 + ru2.ru_utime.tv_usec);
904 break;
905 }
906 else if (ru1.ru_utime.tv_usec != ru2.ru_utime.tv_usec) {
907 rusage_diff = ru2.ru_utime.tv_usec - ru1.ru_utime.tv_usec;
908 break;
909 }
910 else if (ru1.ru_stime.tv_sec != ru2.ru_stime.tv_sec) {
911 rusage_diff = ((1000000 - ru1.ru_stime.tv_usec)
912 + ru2.ru_stime.tv_usec);
913 break;
914 }
915 else if (ru1.ru_stime.tv_usec != ru2.ru_stime.tv_usec) {
916 rusage_diff = ru2.ru_stime.tv_usec - ru1.ru_stime.tv_usec;
917 break;
918 }
919 }
920 }
921#endif
922}
923
924static void
925do_start(ProfilerObject *self)
926{
927 self->active = 1;
928 GETTIMEOFDAY(&self->prev_timeofday);
929 if (self->lineevents)
930 PyEval_SetTrace((Py_tracefunc) tracer_callback, (PyObject *)self);
931 else
932 PyEval_SetProfile((Py_tracefunc) profiler_callback, (PyObject *)self);
933}
934
935static void
936do_stop(ProfilerObject *self)
937{
938 if (self->active) {
939 self->active = 0;
940 if (self->lineevents)
941 PyEval_SetTrace(NULL, NULL);
942 else
943 PyEval_SetProfile(NULL, NULL);
944 }
945 if (self->index > 0) {
946 /* Best effort to dump out any remaining data. */
947 flush_data(self);
948 }
949}
950
951static int
952is_available(ProfilerObject *self)
953{
954 if (self->active) {
955 PyErr_SetString(ProfilerError, "profiler already active");
956 return 0;
957 }
958 if (self->logfp == NULL) {
959 PyErr_SetString(ProfilerError, "profiler already closed");
960 return 0;
961 }
962 return 1;
963}
964
965
966/* Profiler object interface methods. */
967
Tim Petersfeab23f2001-10-13 00:11:10 +0000968static char close__doc__[] =
969"close()\n"
970"Shut down this profiler and close the log files, even if its active.";
Fred Drake8c081a12001-10-12 20:57:55 +0000971
972static PyObject *
973profiler_close(ProfilerObject *self, PyObject *args)
974{
975 PyObject *result = NULL;
976
977 if (PyArg_ParseTuple(args, ":close")) {
978 do_stop(self);
979 if (self->logfp != NULL) {
980 fclose(self->logfp);
981 self->logfp = NULL;
982 }
983 Py_INCREF(Py_None);
984 result = Py_None;
985 }
986 return result;
987}
988
Tim Petersfeab23f2001-10-13 00:11:10 +0000989static char runcall__doc__[] =
990"runcall(callable[, args[, kw]]) -> callable()\n"
991"Profile a specific function call, returning the result of that call.";
Fred Drake8c081a12001-10-12 20:57:55 +0000992
993static PyObject *
994profiler_runcall(ProfilerObject *self, PyObject *args)
995{
996 PyObject *result = NULL;
997 PyObject *callargs = NULL;
998 PyObject *callkw = NULL;
999 PyObject *callable;
1000
1001 if (PyArg_ParseTuple(args, "O|OO:runcall",
1002 &callable, &callargs, &callkw)) {
1003 if (is_available(self)) {
1004 do_start(self);
1005 result = PyEval_CallObjectWithKeywords(callable, callargs, callkw);
1006 do_stop(self);
1007 }
1008 }
1009 return result;
1010}
1011
Tim Petersfeab23f2001-10-13 00:11:10 +00001012static char runcode__doc__[] =
1013"runcode(code, globals[, locals])\n"
1014"Execute a code object while collecting profile data. If locals is\n"
1015"omitted, globals is used for the locals as well.";
Fred Drake8c081a12001-10-12 20:57:55 +00001016
1017static PyObject *
1018profiler_runcode(ProfilerObject *self, PyObject *args)
1019{
1020 PyObject *result = NULL;
1021 PyCodeObject *code;
1022 PyObject *globals;
1023 PyObject *locals = NULL;
1024
1025 if (PyArg_ParseTuple(args, "O!O!|O:runcode",
1026 &PyCode_Type, &code,
1027 &PyDict_Type, &globals,
1028 &locals)) {
1029 if (is_available(self)) {
1030 if (locals == NULL || locals == Py_None)
1031 locals = globals;
1032 else if (!PyDict_Check(locals)) {
1033 PyErr_SetString(PyExc_TypeError,
1034 "locals must be a dictionary or None");
1035 return NULL;
1036 }
1037 do_start(self);
1038 result = PyEval_EvalCode(code, globals, locals);
1039 do_stop(self);
1040#if 0
1041 if (!PyErr_Occurred()) {
1042 result = Py_None;
1043 Py_INCREF(result);
1044 }
1045#endif
1046 }
1047 }
1048 return result;
1049}
1050
Tim Petersfeab23f2001-10-13 00:11:10 +00001051static char start__doc__[] =
1052"start()\n"
1053"Install this profiler for the current thread.";
Fred Drake8c081a12001-10-12 20:57:55 +00001054
1055static PyObject *
1056profiler_start(ProfilerObject *self, PyObject *args)
1057{
1058 PyObject *result = NULL;
1059
1060 if (PyArg_ParseTuple(args, ":start")) {
1061 if (is_available(self))
1062 do_start(self);
1063 }
1064 return result;
1065}
1066
Tim Petersfeab23f2001-10-13 00:11:10 +00001067static char stop__doc__[] =
1068"stop()\n"
1069"Remove this profiler from the current thread.";
Fred Drake8c081a12001-10-12 20:57:55 +00001070
1071static PyObject *
1072profiler_stop(ProfilerObject *self, PyObject *args)
1073{
1074 PyObject *result = NULL;
1075
1076 if (PyArg_ParseTuple(args, ":stop")) {
1077 if (!self->active)
1078 PyErr_SetString(ProfilerError, "profiler not active");
1079 else
1080 do_stop(self);
1081 }
1082 return result;
1083}
1084
1085
1086/* Python API support. */
1087
1088static void
1089profiler_dealloc(ProfilerObject *self)
1090{
1091 do_stop(self);
1092 if (self->logfp != NULL)
1093 fclose(self->logfp);
1094 Py_XDECREF(self->filemap);
1095 Py_XDECREF(self->logfilename);
1096 PyObject_Del((PyObject *)self);
1097}
1098
1099/* Always use METH_VARARGS even though some of these could be METH_NOARGS;
1100 * this allows us to maintain compatibility with Python versions < 2.2
1101 * more easily, requiring only the changes to the dispatcher to be made.
1102 */
1103static PyMethodDef profiler_methods[] = {
1104 {"close", (PyCFunction)profiler_close, METH_VARARGS, close__doc__},
1105 {"runcall", (PyCFunction)profiler_runcall, METH_VARARGS, runcall__doc__},
1106 {"runcode", (PyCFunction)profiler_runcode, METH_VARARGS, runcode__doc__},
1107 {"start", (PyCFunction)profiler_start, METH_VARARGS, start__doc__},
1108 {"stop", (PyCFunction)profiler_stop, METH_VARARGS, stop__doc__},
1109 {NULL, NULL}
1110};
1111
1112/* Use a table even though there's only one "simple" member; this allows
1113 * __members__ and therefore dir() to work.
1114 */
1115static struct memberlist profiler_members[] = {
Fred Drake30d1c752001-10-15 22:11:02 +00001116 {"closed", T_INT, -1, READONLY},
1117 {"frametimings", T_LONG, offsetof(ProfilerObject, linetimings), READONLY},
1118 {"lineevents", T_LONG, offsetof(ProfilerObject, lineevents), READONLY},
1119 {"linetimings", T_LONG, offsetof(ProfilerObject, linetimings), READONLY},
Fred Drake8c081a12001-10-12 20:57:55 +00001120 {NULL}
1121};
1122
1123static PyObject *
1124profiler_getattr(ProfilerObject *self, char *name)
1125{
1126 PyObject *result;
1127 if (strcmp(name, "closed") == 0) {
1128 result = (self->logfp == NULL) ? Py_True : Py_False;
1129 Py_INCREF(result);
1130 }
1131 else {
1132 result = PyMember_Get((char *)self, profiler_members, name);
1133 if (result == NULL) {
1134 PyErr_Clear();
1135 result = Py_FindMethod(profiler_methods, (PyObject *)self, name);
1136 }
1137 }
1138 return result;
1139}
1140
1141
Tim Petersfeab23f2001-10-13 00:11:10 +00001142static char profiler_object__doc__[] =
1143"High-performance profiler object.\n"
1144"\n"
1145"Methods:\n"
1146"\n"
Fred Drake30d1c752001-10-15 22:11:02 +00001147"close(): Stop the profiler and close the log files.\n"
1148"runcall(): Run a single function call with profiling enabled.\n"
1149"runcode(): Execute a code object with profiling enabled.\n"
1150"start(): Install the profiler and return.\n"
1151"stop(): Remove the profiler.\n"
Tim Petersfeab23f2001-10-13 00:11:10 +00001152"\n"
1153"Attributes (read-only):\n"
1154"\n"
Fred Drake30d1c752001-10-15 22:11:02 +00001155"closed: True if the profiler has already been closed.\n"
1156"frametimings: True if ENTER/EXIT events collect timing information.\n"
1157"lineevents: True if SET_LINENO events are reported to the profiler.\n"
1158"linetimings: True if SET_LINENO events collect timing information.";
Fred Drake8c081a12001-10-12 20:57:55 +00001159
1160static PyTypeObject ProfilerType = {
1161 PyObject_HEAD_INIT(NULL)
1162 0, /* ob_size */
1163 "HotShot-profiler", /* tp_name */
1164 (int) sizeof(ProfilerObject), /* tp_basicsize */
1165 0, /* tp_itemsize */
1166 (destructor)profiler_dealloc, /* tp_dealloc */
1167 0, /* tp_print */
1168 (getattrfunc)profiler_getattr, /* tp_getattr */
1169 0, /* tp_setattr */
1170 0, /* tp_compare */
1171 0, /* tp_repr */
1172 0, /* tp_as_number */
1173 0, /* tp_as_sequence */
1174 0, /* tp_as_mapping */
1175 0, /* tp_hash */
1176 0, /* tp_call */
1177 0, /* tp_str */
1178 0, /* tp_getattro */
1179 0, /* tp_setattro */
1180 0, /* tp_as_buffer */
1181 0, /* tp_flags */
1182 profiler_object__doc__, /* tp_doc */
1183};
1184
1185
1186static PyMethodDef logreader_methods[] = {
1187 {"close", (PyCFunction)logreader_close, METH_VARARGS,
1188 logreader_close__doc__},
1189 {"next", (PyCFunction)logreader_next, METH_VARARGS,
1190 next__doc__},
1191 {NULL, NULL}
1192};
1193
1194static PyObject *
1195logreader_getattr(ProfilerObject *self, char *name)
1196{
1197 return Py_FindMethod(logreader_methods, (PyObject *)self, name);
1198}
1199
1200
1201static char logreader__doc__[] = "\
1202logreader(filename) --> log-iterator\n\
1203Create a log-reader for the timing information file.";
1204
1205static PySequenceMethods logreader_as_sequence = {
1206 0, /* sq_length */
1207 0, /* sq_concat */
1208 0, /* sq_repeat */
1209 (intargfunc)logreader_sq_item, /* sq_item */
1210 0, /* sq_slice */
1211 0, /* sq_ass_item */
1212 0, /* sq_ass_slice */
1213 0, /* sq_contains */
1214 0, /* sq_inplace_concat */
1215 0, /* sq_inplace_repeat */
1216};
1217
1218static PyTypeObject LogReaderType = {
1219 PyObject_HEAD_INIT(NULL)
1220 0, /* ob_size */
1221 "HotShot-logreader", /* tp_name */
1222 (int) sizeof(LogReaderObject), /* tp_basicsize */
1223 0, /* tp_itemsize */
1224 (destructor)logreader_dealloc, /* tp_dealloc */
1225 0, /* tp_print */
1226 (getattrfunc)logreader_getattr, /* tp_getattr */
1227 0, /* tp_setattr */
1228 0, /* tp_compare */
1229 0, /* tp_repr */
1230 0, /* tp_as_number */
1231 &logreader_as_sequence, /* tp_as_sequence */
1232 0, /* tp_as_mapping */
1233 0, /* tp_hash */
1234 0, /* tp_call */
1235 0, /* tp_str */
1236 0, /* tp_getattro */
1237 0, /* tp_setattro */
1238 0, /* tp_as_buffer */
1239 0, /* tp_flags */
1240 logreader__doc__, /* tp_doc */
1241#if Py_TPFLAGS_HAVE_ITER
1242 0, /* tp_traverse */
1243 0, /* tp_clear */
1244 0, /* tp_richcompare */
1245 0, /* tp_weaklistoffset */
1246 (getiterfunc)logreader_tp_iter, /* tp_iter */
1247 (iternextfunc)logreader_tp_iternext,/* tp_iternext */
1248#endif
1249};
1250
1251static PyObject *
1252hotshot_logreader(PyObject *unused, PyObject *args)
1253{
1254 LogReaderObject *self = NULL;
1255 char *filename;
1256
1257 if (PyArg_ParseTuple(args, "s:logreader", &filename)) {
1258 self = PyObject_New(LogReaderObject, &LogReaderType);
1259 if (self != NULL) {
1260 self->filled = 0;
1261 self->index = 0;
Fred Drake30d1c752001-10-15 22:11:02 +00001262 self->frametimings = 1;
Fred Drake8c081a12001-10-12 20:57:55 +00001263 self->linetimings = 0;
1264 self->logfp = fopen(filename, "rb");
1265 if (self->logfp == NULL) {
1266 PyErr_SetFromErrnoWithFilename(PyExc_IOError, filename);
1267 Py_DECREF(self);
1268 self = NULL;
1269 }
1270 }
1271 }
1272 return (PyObject *) self;
1273}
1274
1275
1276/* Return a Python string that represents the version number without the
1277 * extra cruft added by revision control, even if the right options were
1278 * given to the "cvs export" command to make it not include the extra
1279 * cruft.
1280 */
1281static char *
1282get_version_string(void)
1283{
1284 static char *rcsid = "$Revision$";
1285 char *rev = rcsid;
1286 char *buffer;
1287 int i = 0;
1288
1289 while (*rev && !isdigit(*rev))
1290 ++rev;
1291 while (rev[i] != ' ' && rev[i] != '\0')
1292 ++i;
1293 buffer = malloc(i + 1);
1294 if (buffer != NULL) {
1295 memmove(buffer, rev, i);
1296 buffer[i] = '\0';
1297 }
1298 return buffer;
1299}
1300
1301/* Write out a RFC 822-style header with various useful bits of
1302 * information to make the output easier to manage.
1303 */
1304static int
1305write_header(ProfilerObject *self)
1306{
1307 char *buffer;
1308 char cwdbuffer[PATH_MAX];
1309 PyObject *temp;
1310 int i, len;
1311
1312 buffer = get_version_string();
1313 if (buffer == NULL) {
1314 PyErr_NoMemory();
1315 return -1;
1316 }
1317 pack_add_info(self, "HotShot-Version", buffer);
1318 pack_add_info(self, "Requested-Line-Events",
1319 (self->lineevents ? "yes" : "no"));
1320 pack_add_info(self, "Platform", Py_GetPlatform());
1321 pack_add_info(self, "Executable", Py_GetProgramFullPath());
1322 buffer = (char *) Py_GetVersion();
1323 if (buffer == NULL)
1324 PyErr_Clear();
1325 else
1326 pack_add_info(self, "Executable-Version", buffer);
1327
1328#ifdef MS_WIN32
1329 sprintf(cwdbuffer, "%I64d", frequency.QuadPart);
1330 pack_add_info(self, "Reported-Performance-Frequency", cwdbuffer);
1331#else
1332 sprintf(cwdbuffer, "%lu", rusage_diff);
1333 pack_add_info(self, "Observed-Interval-getrusage", cwdbuffer);
1334 sprintf(cwdbuffer, "%lu", timeofday_diff);
1335 pack_add_info(self, "Observed-Interval-gettimeofday", cwdbuffer);
1336#endif
Fred Drake30d1c752001-10-15 22:11:02 +00001337 pack_frame_times(self);
Fred Drake8c081a12001-10-12 20:57:55 +00001338 pack_line_times(self);
1339
1340 pack_add_info(self, "Current-Directory",
1341 getcwd(cwdbuffer, sizeof cwdbuffer));
1342
1343 temp = PySys_GetObject("path");
1344 len = PyList_GET_SIZE(temp);
1345 for (i = 0; i < len; ++i) {
1346 PyObject *item = PyList_GET_ITEM(temp, i);
1347 buffer = PyString_AsString(item);
1348 if (buffer == NULL)
1349 return -1;
1350 pack_add_info(self, "Sys-Path-Entry", buffer);
1351 }
1352 return 0;
1353}
1354
1355static char profiler__doc__[] = "\
1356profiler(logfilename[, lineevents[, linetimes]]) -> profiler\n\
1357Create a new profiler object.";
1358
1359static PyObject *
1360hotshot_profiler(PyObject *unused, PyObject *args)
1361{
1362 char *logfilename;
1363 ProfilerObject *self = NULL;
1364 int lineevents = 0;
1365 int linetimings = 1;
1366
1367 if (PyArg_ParseTuple(args, "s|ii:profiler", &logfilename,
1368 &lineevents, &linetimings)) {
1369 self = PyObject_New(ProfilerObject, &ProfilerType);
1370 if (self == NULL)
1371 return NULL;
Fred Drake30d1c752001-10-15 22:11:02 +00001372 self->frametimings = 1;
Fred Drake8c081a12001-10-12 20:57:55 +00001373 self->lineevents = lineevents ? 1 : 0;
1374 self->linetimings = (lineevents && linetimings) ? 1 : 0;
1375 self->index = 0;
1376 self->active = 0;
1377 self->next_fileno = 0;
Tim Peters1566a172001-10-12 22:08:39 +00001378 self->logfp = NULL;
Fred Drake8c081a12001-10-12 20:57:55 +00001379 self->logfilename = PyTuple_GET_ITEM(args, 0);
1380 Py_INCREF(self->logfilename);
1381 self->filemap = PyDict_New();
1382 if (self->filemap == NULL) {
1383 Py_DECREF(self);
1384 return NULL;
1385 }
1386 self->logfp = fopen(logfilename, "wb");
1387 if (self->logfp == NULL) {
1388 Py_DECREF(self);
1389 PyErr_SetFromErrnoWithFilename(PyExc_IOError, logfilename);
1390 return NULL;
1391 }
1392 if (timeofday_diff == 0) {
1393 /* Run this several times since sometimes the first
1394 * doesn't give the lowest values, and we're really trying
1395 * to determine the lowest.
1396 */
1397 calibrate();
1398 calibrate();
1399 calibrate();
1400 }
1401 if (write_header(self))
1402 /* some error occurred, exception has been set */
1403 self = NULL;
1404 }
1405 return (PyObject *) self;
1406}
1407
Fred Drake30d1c752001-10-15 22:11:02 +00001408static char coverage__doc__[] = "\
1409coverage(logfilename) -> profiler\n\
1410Returns a profiler that doesn't collect any timing information, which is\n\
1411useful in building a coverage analysis tool.";
1412
1413static PyObject *
1414hotshot_coverage(PyObject *unused, PyObject *args)
1415{
1416 char *logfilename;
1417 PyObject *result = NULL;
1418
1419 if (PyArg_ParseTuple(args, "s:coverage", &logfilename)) {
1420 result = hotshot_profiler(unused, args);
1421 if (result != NULL) {
1422 ProfilerObject *self = (ProfilerObject *) result;
1423 self->frametimings = 0;
1424 self->linetimings = 0;
1425 self->lineevents = 1;
1426 }
1427 }
1428 return result;
1429}
1430
Fred Drake8c081a12001-10-12 20:57:55 +00001431static char resolution__doc__[] =
1432#ifdef MS_WIN32
Tim Petersfeab23f2001-10-13 00:11:10 +00001433"resolution() -> (performance-counter-ticks, update-frequency)\n"
1434"Return the resolution of the timer provided by the QueryPerformanceCounter()\n"
1435"function. The first value is the smallest observed change, and the second\n"
1436"is the result of QueryPerformanceFrequency().";
Fred Drake8c081a12001-10-12 20:57:55 +00001437#else
Tim Petersfeab23f2001-10-13 00:11:10 +00001438"resolution() -> (gettimeofday-usecs, getrusage-usecs)\n"
1439"Return the resolution of the timers provided by the gettimeofday() and\n"
1440"getrusage() system calls, or -1 if the call is not supported.";
Fred Drake8c081a12001-10-12 20:57:55 +00001441#endif
1442
1443static PyObject *
1444hotshot_resolution(PyObject *unused, PyObject *args)
1445{
1446 PyObject *result = NULL;
1447
1448 if (PyArg_ParseTuple(args, ":resolution")) {
1449 if (timeofday_diff == 0) {
1450 calibrate();
1451 calibrate();
1452 calibrate();
1453 }
1454#ifdef MS_WIN32
1455 result = Py_BuildValue("ii", timeofday_diff, frequency.LowPart);
1456#else
1457 result = Py_BuildValue("ii", timeofday_diff, rusage_diff);
1458#endif
1459 }
1460 return result;
1461}
1462
1463
1464static PyMethodDef functions[] = {
Fred Drake30d1c752001-10-15 22:11:02 +00001465 {"coverage", hotshot_coverage, METH_VARARGS, coverage__doc__},
Fred Drake8c081a12001-10-12 20:57:55 +00001466 {"profiler", hotshot_profiler, METH_VARARGS, profiler__doc__},
1467 {"logreader", hotshot_logreader, METH_VARARGS, logreader__doc__},
1468 {"resolution", hotshot_resolution, METH_VARARGS, resolution__doc__},
1469 {NULL, NULL}
1470};
1471
1472
1473void
1474init_hotshot(void)
1475{
1476 PyObject *module;
1477
1478 LogReaderType.ob_type = &PyType_Type;
1479 ProfilerType.ob_type = &PyType_Type;
1480 module = Py_InitModule("_hotshot", functions);
1481 if (module != NULL) {
1482 char *s = get_version_string();
1483
1484 PyModule_AddStringConstant(module, "__version__", s);
1485 free(s);
1486 Py_INCREF(&LogReaderType);
1487 PyModule_AddObject(module, "LogReaderType",
1488 (PyObject *)&LogReaderType);
1489 Py_INCREF(&ProfilerType);
1490 PyModule_AddObject(module, "ProfilerType",
1491 (PyObject *)&ProfilerType);
1492
1493 if (ProfilerError == NULL)
1494 ProfilerError = PyErr_NewException("hotshot.ProfilerError",
1495 NULL, NULL);
1496 if (ProfilerError != NULL) {
1497 Py_INCREF(ProfilerError);
1498 PyModule_AddObject(module, "ProfilerError", ProfilerError);
1499 }
1500 PyModule_AddIntConstant(module, "WHAT_ENTER", WHAT_ENTER);
1501 PyModule_AddIntConstant(module, "WHAT_EXIT", WHAT_EXIT);
1502 PyModule_AddIntConstant(module, "WHAT_LINENO", WHAT_LINENO);
1503 PyModule_AddIntConstant(module, "WHAT_OTHER", WHAT_OTHER);
1504 PyModule_AddIntConstant(module, "WHAT_ADD_INFO", WHAT_ADD_INFO);
1505 PyModule_AddIntConstant(module, "WHAT_DEFINE_FILE", WHAT_DEFINE_FILE);
Fred Drake30d1c752001-10-15 22:11:02 +00001506 PyModule_AddIntConstant(module, "WHAT_DEFINE_FUNC", WHAT_DEFINE_FUNC);
Fred Drake8c081a12001-10-12 20:57:55 +00001507 PyModule_AddIntConstant(module, "WHAT_LINE_TIMES", WHAT_LINE_TIMES);
1508 }
1509}