blob: 2dbabccaaa5f1ddbd83f5e2232204cac6c1a2616 [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
Jack Jansen963659a2001-10-23 22:26:16 +000034#ifdef macintosh
35#include <sys/time.h>
36#else
Fred Drake8c081a12001-10-12 20:57:55 +000037#include <sys/resource.h>
38#include <sys/times.h>
Jack Jansen963659a2001-10-23 22:26:16 +000039#endif
Fred Drake8c081a12001-10-12 20:57:55 +000040typedef struct timeval hs_time;
41#endif
42
43#if !defined(__cplusplus) && !defined(inline)
44#ifdef __GNUC__
45#define inline __inline
46#endif
47#endif
48
49#ifndef inline
50#define inline
51#endif
52
53#define BUFFERSIZE 10240
54
Jack Jansen963659a2001-10-23 22:26:16 +000055#ifdef macintosh
56#define PATH_MAX 254
57#endif
58
Tim Peters1566a172001-10-12 22:08:39 +000059#ifndef PATH_MAX
60# ifdef MAX_PATH
61# define PATH_MAX MAX_PATH
62# else
63# error "Need a defn. for PATH_MAX in _hotshot.c"
64# endif
65#endif
66
Fred Drake8c081a12001-10-12 20:57:55 +000067typedef struct {
68 PyObject_HEAD
69 PyObject *filemap;
70 PyObject *logfilename;
71 int index;
72 unsigned char buffer[BUFFERSIZE];
73 FILE *logfp;
74 int lineevents;
75 int linetimings;
Fred Drake30d1c752001-10-15 22:11:02 +000076 int frametimings;
Fred Drake8c081a12001-10-12 20:57:55 +000077 /* size_t filled; */
78 int active;
79 int next_fileno;
Fred Drake8c081a12001-10-12 20:57:55 +000080 hs_time prev_timeofday;
81} ProfilerObject;
82
83typedef struct {
84 PyObject_HEAD
85 FILE *logfp;
86 int filled;
87 int index;
88 int linetimings;
Fred Drake30d1c752001-10-15 22:11:02 +000089 int frametimings;
Fred Drake8c081a12001-10-12 20:57:55 +000090 unsigned char buffer[BUFFERSIZE];
91} LogReaderObject;
92
93static PyObject * ProfilerError = NULL;
94
95
96#ifndef MS_WIN32
97#ifdef GETTIMEOFDAY_NO_TZ
98#define GETTIMEOFDAY(ptv) gettimeofday((ptv))
99#else
100#define GETTIMEOFDAY(ptv) gettimeofday((ptv), (struct timezone *)NULL)
101#endif
102#endif
103
104
105/* The log reader... */
106
Tim Petersfeab23f2001-10-13 00:11:10 +0000107static char logreader_close__doc__[] =
108"close()\n"
109"Close the log file, preventing additional records from being read.";
Fred Drake8c081a12001-10-12 20:57:55 +0000110
111static PyObject *
112logreader_close(LogReaderObject *self, PyObject *args)
113{
114 PyObject *result = NULL;
115 if (PyArg_ParseTuple(args, ":close")) {
116 if (self->logfp != NULL) {
117 fclose(self->logfp);
118 self->logfp = NULL;
119 }
120 result = Py_None;
121 Py_INCREF(result);
122 }
123 return result;
124}
125
126#if Py_TPFLAGS_HAVE_ITER
127/* This is only used if the interpreter has iterator support; the
128 * iternext handler is also used as a helper for other functions, so
129 * does not need to be included in this conditional section.
130 */
131static PyObject *
132logreader_tp_iter(LogReaderObject *self)
133{
134 Py_INCREF(self);
135 return (PyObject *) self;
136}
137#endif
138
139
140/* Log File Format
141 * ---------------
142 *
143 * The log file consists of a sequence of variable-length records.
144 * Each record is identified with a record type identifier in two
145 * bits of the first byte. The two bits are the "least significant"
146 * bits of the byte.
147 *
148 * Low bits: Opcode: Meaning:
149 * 0x00 ENTER enter a frame
150 * 0x01 EXIT exit a frame
151 * 0x02 LINENO SET_LINENO instruction was executed
152 * 0x03 OTHER more bits are needed to deecode
153 *
154 * If the type is OTHER, the record is not packed so tightly, and the
155 * remaining bits are used to disambiguate the record type. These
156 * records are not used as frequently so compaction is not an issue.
157 * Each of the first three record types has a highly tailored
158 * structure that allows it to be packed tightly.
159 *
160 * The OTHER records have the following identifiers:
161 *
162 * First byte: Opcode: Meaning:
163 * 0x13 ADD_INFO define a key/value pair
164 * 0x23 DEFINE_FILE define an int->filename mapping
165 * 0x33 LINE_TIMES indicates if LINENO events have tdeltas
Fred Drake30d1c752001-10-15 22:11:02 +0000166 * 0x43 DEFINE_FUNC define a (fileno,lineno)->funcname mapping
167 * 0x53 FRAME_TIMES indicates if ENTER/EXIT events have tdeltas
Fred Drake8c081a12001-10-12 20:57:55 +0000168 *
169 * Packed Integers
170 *
171 * "Packed integers" are non-negative integer values encoded as a
172 * sequence of bytes. Each byte is encoded such that the most
173 * significant bit is set if the next byte is also part of the
174 * integer. Each byte provides bits to the least-significant end of
175 * the result; the accumulated value must be shifted up to place the
176 * new bits into the result.
177 *
178 * "Modified packed integers" are packed integers where only a portion
179 * of the first byte is used. In the rest of the specification, these
180 * are referred to as "MPI(n,name)", where "n" is the number of bits
181 * discarded from the least-signicant positions of the byte, and
182 * "name" is a name being given to those "discarded" bits, since they
183 * are a field themselves.
184 *
185 * ENTER records:
186 *
187 * MPI(2,type) fileno -- type is 0x00
Fred Drake8c081a12001-10-12 20:57:55 +0000188 * PI lineno
Fred Drake30d1c752001-10-15 22:11:02 +0000189 * PI tdelta -- iff frame times are enabled
Fred Drake8c081a12001-10-12 20:57:55 +0000190 *
191 * EXIT records
192 *
Fred Drake30d1c752001-10-15 22:11:02 +0000193 * MPI(2,type) tdelta -- type is 0x01; tdelta will be 0
194 * if frame times are disabled
Fred Drake8c081a12001-10-12 20:57:55 +0000195 *
196 * LINENO records
197 *
198 * MPI(2,type) lineno -- type is 0x02
199 * PI tdelta -- iff LINENO includes it
200 *
201 * ADD_INFO records
202 *
Fred Drake30d1c752001-10-15 22:11:02 +0000203 * BYTE type -- always 0x13
Fred Drake8c081a12001-10-12 20:57:55 +0000204 * PI len1 -- length of first string
205 * BYTE string1[len1] -- len1 bytes of string data
206 * PI len2 -- length of second string
207 * BYTE string2[len2] -- len2 bytes of string data
208 *
209 * DEFINE_FILE records
210 *
Fred Drake30d1c752001-10-15 22:11:02 +0000211 * BYTE type -- always 0x23
Fred Drake8c081a12001-10-12 20:57:55 +0000212 * PI fileno
213 * PI len -- length of filename
214 * BYTE filename[len] -- len bytes of string data
215 *
Fred Drake30d1c752001-10-15 22:11:02 +0000216 * DEFINE_FUNC records
217 *
218 * BYTE type -- always 0x43
219 * PI fileno
220 * PI lineno
221 * PI len -- length of funcname
222 * BYTE funcname[len] -- len bytes of string data
223 *
Fred Drake8c081a12001-10-12 20:57:55 +0000224 * LINE_TIMES records
Fred Drake30d1c752001-10-15 22:11:02 +0000225 *
226 * This record can be used only before the start of ENTER/EXIT/LINENO
227 * records. If have_tdelta is true, LINENO records will include the
228 * tdelta field, otherwise it will be omitted. If this record is not
229 * given, LINENO records will not contain the tdelta field.
230 *
231 * BYTE type -- always 0x33
Fred Drake8c081a12001-10-12 20:57:55 +0000232 * BYTE have_tdelta -- 0 if LINENO does *not* have
233 * timing information
Fred Drake30d1c752001-10-15 22:11:02 +0000234 * FRAME_TIMES records
235 *
236 * This record can be used only before the start of ENTER/EXIT/LINENO
237 * records. If have_tdelta is true, ENTER and EXIT records will
238 * include the tdelta field, otherwise it will be omitted. If this
239 * record is not given, ENTER and EXIT records will contain the tdelta
240 * field.
241 *
242 * BYTE type -- always 0x53
243 * BYTE have_tdelta -- 0 if ENTER/EXIT do *not* have
244 * timing information
Fred Drake8c081a12001-10-12 20:57:55 +0000245 */
246
247#define WHAT_ENTER 0x00
248#define WHAT_EXIT 0x01
249#define WHAT_LINENO 0x02
250#define WHAT_OTHER 0x03 /* only used in decoding */
251#define WHAT_ADD_INFO 0x13
252#define WHAT_DEFINE_FILE 0x23
253#define WHAT_LINE_TIMES 0x33
Fred Drake30d1c752001-10-15 22:11:02 +0000254#define WHAT_DEFINE_FUNC 0x43
255#define WHAT_FRAME_TIMES 0x53
Fred Drake8c081a12001-10-12 20:57:55 +0000256
257#define ERR_NONE 0
258#define ERR_EOF -1
259#define ERR_EXCEPTION -2
260
261#define PISIZE (sizeof(int) + 1)
262#define MPISIZE (PISIZE + 1)
263
264/* Maximum size of "normal" events -- nothing that contains string data */
265#define MAXEVENTSIZE (MPISIZE + PISIZE*2)
266
267
268/* Unpack a packed integer; if "discard" is non-zero, unpack a modified
269 * packed integer with "discard" discarded bits.
270 */
271static int
272unpack_packed_int(LogReaderObject *self, int *pvalue, int discard)
273{
274 int accum = 0;
275 int bits = 0;
276 int index = self->index;
277 int cont;
278
279 do {
280 if (index >= self->filled)
281 return ERR_EOF;
282 /* read byte */
283 accum |= ((self->buffer[index] & 0x7F) >> discard) << bits;
284 bits += (7 - discard);
285 cont = self->buffer[index] & 0x80;
286 /* move to next */
287 discard = 0;
288 index++;
289 } while (cont);
290
291 /* save state */
292 self->index = index;
293 *pvalue = accum;
294
295 return 0;
296}
297
298/* Unpack a string, which is encoded as a packed integer giving the
299 * length of the string, followed by the string data.
300 */
301static int
302unpack_string(LogReaderObject *self, PyObject **pvalue)
303{
304 int len;
305 int oldindex = self->index;
306 int err = unpack_packed_int(self, &len, 0);
307
308 if (!err) {
309 /* need at least len bytes in buffer */
310 if (len > (self->filled - self->index)) {
311 self->index = oldindex;
312 err = ERR_EOF;
313 }
314 else {
Jack Jansen963659a2001-10-23 22:26:16 +0000315 *pvalue = PyString_FromStringAndSize((char *)self->buffer + self->index,
Fred Drake8c081a12001-10-12 20:57:55 +0000316 len);
317 if (*pvalue == NULL) {
318 self->index = oldindex;
319 err = ERR_EXCEPTION;
320 }
321 else
322 self->index += len;
323 }
324 }
325 return err;
326}
327
328
329static PyObject *
330logreader_tp_iternext(LogReaderObject *self)
331{
332 int what, oldindex;
333 int err = ERR_NONE;
334 int lineno = -1;
335 int fileno = -1;
336 int tdelta = -1;
337 PyObject *s1 = NULL, *s2 = NULL;
338 PyObject *result = NULL;
339#if 0
340 unsigned char b0, b1;
341#endif
342
343 if (self->logfp == NULL) {
344 PyErr_SetString(ProfilerError,
345 "cannot iterate over closed LogReader object");
346 return NULL;
347 }
348 restart:
349 if ((self->filled - self->index) < MAXEVENTSIZE) {
350 /* add a little to the buffer */
351 int needed;
352 size_t res;
353 refill:
354 if (self->index) {
355 memmove(self->buffer, &self->buffer[self->index],
356 self->filled - self->index);
357 self->filled = self->filled - self->index;
358 self->index = 0;
359 }
360 needed = BUFFERSIZE - self->filled;
361 res = fread(&self->buffer[self->filled], 1, needed, self->logfp);
362 self->filled += res;
363 }
364 /* end of input */
365 if (self->filled == 0)
366 return NULL;
367
368 oldindex = self->index;
369
370 /* decode the record type */
371 what = self->buffer[self->index] & WHAT_OTHER;
372 if (what == WHAT_OTHER) {
373 what = self->buffer[self->index];
374 self->index++;
375 }
376 switch (what) {
377 case WHAT_ENTER:
378 err = unpack_packed_int(self, &fileno, 2);
379 if (!err) {
Fred Drake30d1c752001-10-15 22:11:02 +0000380 err = unpack_packed_int(self, &lineno, 0);
381 if (self->frametimings && !err)
382 err = unpack_packed_int(self, &tdelta, 0);
Fred Drake8c081a12001-10-12 20:57:55 +0000383 }
384 break;
385 case WHAT_EXIT:
386 err = unpack_packed_int(self, &tdelta, 2);
387 break;
388 case WHAT_LINENO:
389 err = unpack_packed_int(self, &lineno, 2);
390 if (self->linetimings && !err)
391 err = unpack_packed_int(self, &tdelta, 0);
392 break;
393 case WHAT_ADD_INFO:
394 err = unpack_string(self, &s1);
395 if (!err) {
396 err = unpack_string(self, &s2);
397 if (err) {
398 Py_DECREF(s1);
399 s1 = NULL;
400 }
401 }
402 break;
403 case WHAT_DEFINE_FILE:
404 err = unpack_packed_int(self, &fileno, 0);
405 if (!err) {
406 err = unpack_string(self, &s1);
407 if (!err) {
408 Py_INCREF(Py_None);
409 s2 = Py_None;
410 }
411 }
412 break;
Fred Drake30d1c752001-10-15 22:11:02 +0000413 case WHAT_DEFINE_FUNC:
414 err = unpack_packed_int(self, &fileno, 0);
415 if (!err) {
416 err = unpack_packed_int(self, &lineno, 0);
417 if (!err)
418 err = unpack_string(self, &s1);
419 }
420 break;
Fred Drake8c081a12001-10-12 20:57:55 +0000421 case WHAT_LINE_TIMES:
422 if (self->index >= self->filled)
423 err = ERR_EOF;
424 else {
425 self->linetimings = self->buffer[self->index] ? 1 : 0;
426 self->index++;
427 goto restart;
428 }
Fred Drake30d1c752001-10-15 22:11:02 +0000429 case WHAT_FRAME_TIMES:
430 if (self->index >= self->filled)
431 err = ERR_EOF;
432 else {
433 self->frametimings = self->buffer[self->index] ? 1 : 0;
434 self->index++;
435 goto restart;
436 }
Fred Drake8c081a12001-10-12 20:57:55 +0000437 default:
Tim Peters1566a172001-10-12 22:08:39 +0000438 ;
Fred Drake8c081a12001-10-12 20:57:55 +0000439 }
440 if (err == ERR_EOF && oldindex != 0) {
441 /* It looks like we ran out of data before we had it all; this
442 * could easily happen with large packed integers or string
443 * data. Try forcing the buffer to be re-filled before failing.
444 */
445 err = ERR_NONE;
446 goto refill;
447 }
448 if (err == ERR_EOF) {
449 /* Could not avoid end-of-buffer error. */
450 PyErr_SetString(PyExc_EOFError,
451 "end of file with incomplete profile record");
452 }
453 else if (!err) {
454 result = PyTuple_New(4);
455 PyTuple_SET_ITEM(result, 0, PyInt_FromLong(what));
456 PyTuple_SET_ITEM(result, 2, PyInt_FromLong(fileno));
Fred Drake30d1c752001-10-15 22:11:02 +0000457 if (s1 == NULL)
Fred Drake8c081a12001-10-12 20:57:55 +0000458 PyTuple_SET_ITEM(result, 1, PyInt_FromLong(tdelta));
Fred Drake30d1c752001-10-15 22:11:02 +0000459 else
Fred Drake8c081a12001-10-12 20:57:55 +0000460 PyTuple_SET_ITEM(result, 1, s1);
Fred Drake30d1c752001-10-15 22:11:02 +0000461 if (s2 == NULL)
462 PyTuple_SET_ITEM(result, 3, PyInt_FromLong(lineno));
463 else
Fred Drake8c081a12001-10-12 20:57:55 +0000464 PyTuple_SET_ITEM(result, 3, s2);
Fred Drake8c081a12001-10-12 20:57:55 +0000465 }
466 /* The only other case is err == ERR_EXCEPTION, in which case the
467 * exception is already set.
468 */
469#if 0
470 b0 = self->buffer[self->index];
471 b1 = self->buffer[self->index + 1];
472 if (b0 & 1) {
473 /* This is a line-number event. */
474 what = PyTrace_LINE;
475 lineno = ((b0 & ~1) << 7) + b1;
476 self->index += 2;
477 }
478 else {
479 what = (b0 & 0x0E) >> 1;
480 tdelta = ((b0 & 0xF0) << 4) + b1;
481 if (what == PyTrace_CALL) {
482 /* we know there's a 2-byte file ID & 2-byte line number */
483 fileno = ((self->buffer[self->index + 2] << 8)
484 + self->buffer[self->index + 3]);
485 lineno = ((self->buffer[self->index + 4] << 8)
486 + self->buffer[self->index + 5]);
487 self->index += 6;
488 }
489 else
490 self->index += 2;
491 }
492#endif
493 return result;
494}
495
496static void
497logreader_dealloc(LogReaderObject *self)
498{
499 if (self->logfp != NULL) {
500 fclose(self->logfp);
501 self->logfp = NULL;
502 }
503 PyObject_Del(self);
504}
505
506static PyObject *
507logreader_sq_item(LogReaderObject *self, int index)
508{
509 PyObject *result = logreader_tp_iternext(self);
510 if (result == NULL && !PyErr_Occurred()) {
511 PyErr_SetString(PyExc_IndexError, "no more events in log");
512 return NULL;
513 }
514 return result;
515}
516
Tim Petersfeab23f2001-10-13 00:11:10 +0000517static char next__doc__[] =
518"next() -> event-info\n"
519"Return the next event record from the log file.";
Fred Drake8c081a12001-10-12 20:57:55 +0000520
521static PyObject *
522logreader_next(LogReaderObject *self, PyObject *args)
523{
524 PyObject *result = NULL;
525
526 if (PyArg_ParseTuple(args, ":next")) {
527 result = logreader_tp_iternext(self);
528 /* XXX return None if there's nothing left */
529 /* tp_iternext does the right thing, though */
530 if (result == NULL && !PyErr_Occurred()) {
531 result = Py_None;
532 Py_INCREF(result);
533 }
534 }
535 return result;
536}
537
538
539static int
540flush_data(ProfilerObject *self)
541{
542 /* Need to dump data to the log file... */
543 size_t written = fwrite(self->buffer, 1, self->index, self->logfp);
Tim Peters1566a172001-10-12 22:08:39 +0000544 if (written == (size_t)self->index)
Fred Drake8c081a12001-10-12 20:57:55 +0000545 self->index = 0;
546 else {
547 memmove(self->buffer, &self->buffer[written],
548 self->index - written);
549 self->index -= written;
550 if (written == 0) {
551 char *s = PyString_AsString(self->logfilename);
552 PyErr_SetFromErrnoWithFilename(PyExc_IOError, s);
553 return -1;
554 }
555 }
556 if (written > 0) {
557 if (fflush(self->logfp)) {
558 char *s = PyString_AsString(self->logfilename);
559 PyErr_SetFromErrnoWithFilename(PyExc_IOError, s);
560 return -1;
561 }
562 }
563 return 0;
564}
565
566static inline void
567pack_packed_int(ProfilerObject *self, int value)
568{
569 unsigned char partial;
570
571 do {
572 partial = value & 0x7F;
573 value >>= 7;
574 if (value)
575 partial |= 0x80;
576 self->buffer[self->index] = partial;
577 self->index++;
578 } while (value);
579}
580
581/* Encode a modified packed integer, with a subfield of modsize bits
582 * containing the value "subfield". The value of subfield is not
583 * checked to ensure it actually fits in modsize bits.
584 */
585static inline void
586pack_modified_packed_int(ProfilerObject *self, int value,
587 int modsize, int subfield)
588{
589 const int maxvalues[] = {-1, 1, 3, 7, 15, 31, 63, 127};
590
591 int bits = 7 - modsize;
592 int partial = value & maxvalues[bits];
593 unsigned char b = subfield | (partial << modsize);
594
595 if (partial != value) {
596 b |= 0x80;
597 self->buffer[self->index] = b;
598 self->index++;
599 pack_packed_int(self, value >> bits);
600 }
601 else {
602 self->buffer[self->index] = b;
603 self->index++;
604 }
605}
606
607static void
Fred Drake30d1c752001-10-15 22:11:02 +0000608pack_string(ProfilerObject *self, const char *s, int len)
Fred Drake8c081a12001-10-12 20:57:55 +0000609{
Fred Drake30d1c752001-10-15 22:11:02 +0000610 if (len + PISIZE + self->index >= BUFFERSIZE)
Fred Drake8c081a12001-10-12 20:57:55 +0000611 (void) flush_data(self);
Fred Drake30d1c752001-10-15 22:11:02 +0000612 pack_packed_int(self, len);
Fred Drake8c081a12001-10-12 20:57:55 +0000613 memcpy(self->buffer + self->index, s, len);
614 self->index += len;
615}
616
617static void
618pack_add_info(ProfilerObject *self, const char *s1, const char *s2)
619{
620 int len1 = strlen(s1);
621 int len2 = strlen(s2);
622
623 if (len1 + len2 + PISIZE*2 + 1 + self->index >= BUFFERSIZE)
624 (void) flush_data(self);
625 self->buffer[self->index] = WHAT_ADD_INFO;
626 self->index++;
Fred Drake30d1c752001-10-15 22:11:02 +0000627 pack_string(self, s1, len1);
628 pack_string(self, s2, len2);
Fred Drake8c081a12001-10-12 20:57:55 +0000629}
630
631static void
632pack_define_file(ProfilerObject *self, int fileno, const char *filename)
633{
634 int len = strlen(filename);
635
636 if (len + PISIZE*2 + 1 + self->index >= BUFFERSIZE)
637 (void) flush_data(self);
638 self->buffer[self->index] = WHAT_DEFINE_FILE;
639 self->index++;
640 pack_packed_int(self, fileno);
Fred Drake30d1c752001-10-15 22:11:02 +0000641 pack_string(self, filename, len);
642}
643
644static void
645pack_define_func(ProfilerObject *self, int fileno, int lineno,
646 const char *funcname)
647{
648 int len = strlen(funcname);
649
650 if (len + PISIZE*3 + 1 + self->index >= BUFFERSIZE)
651 (void) flush_data(self);
652 self->buffer[self->index] = WHAT_DEFINE_FUNC;
653 self->index++;
654 pack_packed_int(self, fileno);
655 pack_packed_int(self, lineno);
656 pack_string(self, funcname, len);
Fred Drake8c081a12001-10-12 20:57:55 +0000657}
658
659static void
660pack_line_times(ProfilerObject *self)
661{
662 if (2 + self->index >= BUFFERSIZE)
663 (void) flush_data(self);
664 self->buffer[self->index] = WHAT_LINE_TIMES;
665 self->buffer[self->index + 1] = self->linetimings ? 1 : 0;
666 self->index += 2;
667}
668
Fred Drake30d1c752001-10-15 22:11:02 +0000669static void
670pack_frame_times(ProfilerObject *self)
671{
672 if (2 + self->index >= BUFFERSIZE)
673 (void) flush_data(self);
674 self->buffer[self->index] = WHAT_FRAME_TIMES;
675 self->buffer[self->index + 1] = self->frametimings ? 1 : 0;
676 self->index += 2;
677}
678
Fred Drake8c081a12001-10-12 20:57:55 +0000679static inline void
680pack_enter(ProfilerObject *self, int fileno, int tdelta, int lineno)
681{
682 if (MPISIZE + PISIZE*2 + self->index >= BUFFERSIZE)
683 (void) flush_data(self);
684 pack_modified_packed_int(self, fileno, 2, WHAT_ENTER);
Fred Drake8c081a12001-10-12 20:57:55 +0000685 pack_packed_int(self, lineno);
Fred Drake30d1c752001-10-15 22:11:02 +0000686 if (self->frametimings)
687 pack_packed_int(self, tdelta);
Fred Drake8c081a12001-10-12 20:57:55 +0000688}
689
690static inline void
691pack_exit(ProfilerObject *self, int tdelta)
692{
693 if (MPISIZE + self->index >= BUFFERSIZE)
694 (void) flush_data(self);
Fred Drake30d1c752001-10-15 22:11:02 +0000695 if (self->frametimings)
696 pack_modified_packed_int(self, tdelta, 2, WHAT_EXIT);
697 else {
698 self->buffer[self->index] = WHAT_EXIT;
699 self->index++;
700 }
Fred Drake8c081a12001-10-12 20:57:55 +0000701}
702
703static inline void
704pack_lineno(ProfilerObject *self, int lineno)
705{
706 if (MPISIZE + self->index >= BUFFERSIZE)
707 (void) flush_data(self);
708 pack_modified_packed_int(self, lineno, 2, WHAT_LINENO);
709}
710
711static inline void
712pack_lineno_tdelta(ProfilerObject *self, int lineno, int tdelta)
713{
714 if (MPISIZE + PISIZE + self->index >= BUFFERSIZE)
715 (void) flush_data(self);
716 pack_modified_packed_int(self, lineno, 2, WHAT_LINENO);
717 pack_packed_int(self, tdelta);
718}
719
720static inline int
721get_fileno(ProfilerObject *self, PyCodeObject *fcode)
722{
Fred Drake30d1c752001-10-15 22:11:02 +0000723 /* This is only used for ENTER events. */
724
725 PyObject *obj;
726 PyObject *dict;
Fred Drake8c081a12001-10-12 20:57:55 +0000727 int fileno;
728
Fred Drake30d1c752001-10-15 22:11:02 +0000729 obj = PyDict_GetItem(self->filemap, fcode->co_filename);
730 if (obj == NULL) {
Fred Drake8c081a12001-10-12 20:57:55 +0000731 /* first sighting of this file */
Fred Drake30d1c752001-10-15 22:11:02 +0000732 dict = PyDict_New();
733 if (dict == NULL) {
Fred Drake8c081a12001-10-12 20:57:55 +0000734 return -1;
735 }
Fred Drake30d1c752001-10-15 22:11:02 +0000736 fileno = self->next_fileno;
737 obj = Py_BuildValue("iN", fileno, dict);
738 if (obj == NULL) {
739 return -1;
740 }
741 if (PyDict_SetItem(self->filemap, fcode->co_filename, obj)) {
742 Py_DECREF(obj);
Fred Drake8c081a12001-10-12 20:57:55 +0000743 return -1;
744 }
745 self->next_fileno++;
Fred Drake30d1c752001-10-15 22:11:02 +0000746 Py_DECREF(obj);
Fred Drake8c081a12001-10-12 20:57:55 +0000747 pack_define_file(self, fileno, PyString_AS_STRING(fcode->co_filename));
748 }
749 else {
750 /* already know this ID */
Fred Drake30d1c752001-10-15 22:11:02 +0000751 fileno = PyInt_AS_LONG(PyTuple_GET_ITEM(obj, 0));
752 dict = PyTuple_GET_ITEM(obj, 1);
753 }
754 /* make sure we save a function name for this (fileno, lineno) */
755 obj = PyInt_FromLong(fcode->co_firstlineno);
756 if (obj == NULL) {
757 /* We just won't have it saved; too bad. */
758 PyErr_Clear();
759 }
760 else {
761 PyObject *name = PyDict_GetItem(dict, obj);
762 if (name == NULL) {
763 pack_define_func(self, fileno, fcode->co_firstlineno,
764 PyString_AS_STRING(fcode->co_name));
765 if (PyDict_SetItem(dict, obj, fcode->co_name))
766 return -1;
767 }
Fred Drake8c081a12001-10-12 20:57:55 +0000768 }
769 return fileno;
770}
771
772static inline int
773get_tdelta(ProfilerObject *self)
774{
775 int tdelta;
776#ifdef MS_WIN32
777 hs_time tv;
Tim Peters7d99ff22001-10-13 07:37:52 +0000778 hs_time diff;
Fred Drake8c081a12001-10-12 20:57:55 +0000779
Tim Peters7d99ff22001-10-13 07:37:52 +0000780 GETTIMEOFDAY(&tv);
781 diff = tv - self->prev_timeofday;
782 tdelta = (int)diff;
Fred Drake8c081a12001-10-12 20:57:55 +0000783#else
784 struct timeval tv;
785
786 GETTIMEOFDAY(&tv);
787
788 if (tv.tv_sec == self->prev_timeofday.tv_sec)
789 tdelta = tv.tv_usec - self->prev_timeofday.tv_usec;
790 else
791 tdelta = ((tv.tv_sec - self->prev_timeofday.tv_sec) * 1000000
792 + tv.tv_usec);
793#endif
794 self->prev_timeofday = tv;
795 return tdelta;
796}
797
798
799/* The workhorse: the profiler callback function. */
800
801static int
802profiler_callback(ProfilerObject *self, PyFrameObject *frame, int what,
803 PyObject *arg)
804{
Fred Drake30d1c752001-10-15 22:11:02 +0000805 int tdelta = -1;
Fred Drake8c081a12001-10-12 20:57:55 +0000806 int fileno;
807
Fred Drake30d1c752001-10-15 22:11:02 +0000808 if (self->frametimings)
809 tdelta = get_tdelta(self);
Fred Drake8c081a12001-10-12 20:57:55 +0000810 switch (what) {
811 case PyTrace_CALL:
812 fileno = get_fileno(self, frame->f_code);
813 if (fileno < 0)
814 return -1;
815 pack_enter(self, fileno, tdelta,
816 frame->f_code->co_firstlineno);
817 break;
818 case PyTrace_RETURN:
819 pack_exit(self, tdelta);
820 break;
821 default:
822 /* should never get here */
823 break;
824 }
825 return 0;
826}
827
828
829/* Alternate callback when we want PyTrace_LINE events */
830
831static int
832tracer_callback(ProfilerObject *self, PyFrameObject *frame, int what,
833 PyObject *arg)
834{
835 int fileno;
836
Fred Drake8c081a12001-10-12 20:57:55 +0000837 switch (what) {
838 case PyTrace_CALL:
839 fileno = get_fileno(self, frame->f_code);
840 if (fileno < 0)
841 return -1;
Fred Drake30d1c752001-10-15 22:11:02 +0000842 pack_enter(self, fileno, self->frametimings ? get_tdelta(self) : -1,
Fred Drake8c081a12001-10-12 20:57:55 +0000843 frame->f_code->co_firstlineno);
844 break;
845 case PyTrace_RETURN:
846 pack_exit(self, get_tdelta(self));
847 break;
Tim Peters1566a172001-10-12 22:08:39 +0000848 case PyTrace_LINE:
Fred Drake8c081a12001-10-12 20:57:55 +0000849 if (self->linetimings)
850 pack_lineno_tdelta(self, frame->f_lineno, get_tdelta(self));
851 else
852 pack_lineno(self, frame->f_lineno);
853 break;
854 default:
855 /* ignore PyTrace_EXCEPTION */
856 break;
857 }
858 return 0;
859}
860
861
862/* A couple of useful helper functions. */
863
864#ifdef MS_WIN32
Tim Petersfeab23f2001-10-13 00:11:10 +0000865static LARGE_INTEGER frequency = {0, 0};
Fred Drake8c081a12001-10-12 20:57:55 +0000866#endif
867
868static unsigned long timeofday_diff = 0;
869static unsigned long rusage_diff = 0;
870
871static void
872calibrate(void)
873{
874 hs_time tv1, tv2;
875
876#ifdef MS_WIN32
Tim Peters7d99ff22001-10-13 07:37:52 +0000877 hs_time diff;
Fred Drake8c081a12001-10-12 20:57:55 +0000878 QueryPerformanceFrequency(&frequency);
879#endif
880
881 GETTIMEOFDAY(&tv1);
882 while (1) {
883 GETTIMEOFDAY(&tv2);
884#ifdef MS_WIN32
Tim Peters7d99ff22001-10-13 07:37:52 +0000885 diff = tv2 - tv1;
886 if (diff != 0) {
887 timeofday_diff = (unsigned long)diff;
Fred Drake8c081a12001-10-12 20:57:55 +0000888 break;
889 }
890#else
891 if (tv1.tv_sec != tv2.tv_sec || tv1.tv_usec != tv2.tv_usec) {
892 if (tv1.tv_sec == tv2.tv_sec)
893 timeofday_diff = tv2.tv_usec - tv1.tv_usec;
894 else
895 timeofday_diff = (1000000 - tv1.tv_usec) + tv2.tv_usec;
896 break;
897 }
898#endif
899 }
Jack Jansen963659a2001-10-23 22:26:16 +0000900#if defined(MS_WIN32) || defined(macintosh)
Fred Drake8c081a12001-10-12 20:57:55 +0000901 rusage_diff = -1;
902#else
903 {
904 struct rusage ru1, ru2;
905
906 getrusage(RUSAGE_SELF, &ru1);
907 while (1) {
908 getrusage(RUSAGE_SELF, &ru2);
909 if (ru1.ru_utime.tv_sec != ru2.ru_utime.tv_sec) {
910 rusage_diff = ((1000000 - ru1.ru_utime.tv_usec)
911 + ru2.ru_utime.tv_usec);
912 break;
913 }
914 else if (ru1.ru_utime.tv_usec != ru2.ru_utime.tv_usec) {
915 rusage_diff = ru2.ru_utime.tv_usec - ru1.ru_utime.tv_usec;
916 break;
917 }
918 else if (ru1.ru_stime.tv_sec != ru2.ru_stime.tv_sec) {
919 rusage_diff = ((1000000 - ru1.ru_stime.tv_usec)
920 + ru2.ru_stime.tv_usec);
921 break;
922 }
923 else if (ru1.ru_stime.tv_usec != ru2.ru_stime.tv_usec) {
924 rusage_diff = ru2.ru_stime.tv_usec - ru1.ru_stime.tv_usec;
925 break;
926 }
927 }
928 }
929#endif
930}
931
932static void
933do_start(ProfilerObject *self)
934{
935 self->active = 1;
936 GETTIMEOFDAY(&self->prev_timeofday);
937 if (self->lineevents)
938 PyEval_SetTrace((Py_tracefunc) tracer_callback, (PyObject *)self);
939 else
940 PyEval_SetProfile((Py_tracefunc) profiler_callback, (PyObject *)self);
941}
942
943static void
944do_stop(ProfilerObject *self)
945{
946 if (self->active) {
947 self->active = 0;
948 if (self->lineevents)
949 PyEval_SetTrace(NULL, NULL);
950 else
951 PyEval_SetProfile(NULL, NULL);
952 }
953 if (self->index > 0) {
954 /* Best effort to dump out any remaining data. */
955 flush_data(self);
956 }
957}
958
959static int
960is_available(ProfilerObject *self)
961{
962 if (self->active) {
963 PyErr_SetString(ProfilerError, "profiler already active");
964 return 0;
965 }
966 if (self->logfp == NULL) {
967 PyErr_SetString(ProfilerError, "profiler already closed");
968 return 0;
969 }
970 return 1;
971}
972
973
974/* Profiler object interface methods. */
975
Tim Petersfeab23f2001-10-13 00:11:10 +0000976static char close__doc__[] =
977"close()\n"
978"Shut down this profiler and close the log files, even if its active.";
Fred Drake8c081a12001-10-12 20:57:55 +0000979
980static PyObject *
981profiler_close(ProfilerObject *self, PyObject *args)
982{
983 PyObject *result = NULL;
984
985 if (PyArg_ParseTuple(args, ":close")) {
986 do_stop(self);
987 if (self->logfp != NULL) {
988 fclose(self->logfp);
989 self->logfp = NULL;
990 }
991 Py_INCREF(Py_None);
992 result = Py_None;
993 }
994 return result;
995}
996
Tim Petersfeab23f2001-10-13 00:11:10 +0000997static char runcall__doc__[] =
998"runcall(callable[, args[, kw]]) -> callable()\n"
999"Profile a specific function call, returning the result of that call.";
Fred Drake8c081a12001-10-12 20:57:55 +00001000
1001static PyObject *
1002profiler_runcall(ProfilerObject *self, PyObject *args)
1003{
1004 PyObject *result = NULL;
1005 PyObject *callargs = NULL;
1006 PyObject *callkw = NULL;
1007 PyObject *callable;
1008
1009 if (PyArg_ParseTuple(args, "O|OO:runcall",
1010 &callable, &callargs, &callkw)) {
1011 if (is_available(self)) {
1012 do_start(self);
1013 result = PyEval_CallObjectWithKeywords(callable, callargs, callkw);
1014 do_stop(self);
1015 }
1016 }
1017 return result;
1018}
1019
Tim Petersfeab23f2001-10-13 00:11:10 +00001020static char runcode__doc__[] =
1021"runcode(code, globals[, locals])\n"
1022"Execute a code object while collecting profile data. If locals is\n"
1023"omitted, globals is used for the locals as well.";
Fred Drake8c081a12001-10-12 20:57:55 +00001024
1025static PyObject *
1026profiler_runcode(ProfilerObject *self, PyObject *args)
1027{
1028 PyObject *result = NULL;
1029 PyCodeObject *code;
1030 PyObject *globals;
1031 PyObject *locals = NULL;
1032
1033 if (PyArg_ParseTuple(args, "O!O!|O:runcode",
1034 &PyCode_Type, &code,
1035 &PyDict_Type, &globals,
1036 &locals)) {
1037 if (is_available(self)) {
1038 if (locals == NULL || locals == Py_None)
1039 locals = globals;
1040 else if (!PyDict_Check(locals)) {
1041 PyErr_SetString(PyExc_TypeError,
1042 "locals must be a dictionary or None");
1043 return NULL;
1044 }
1045 do_start(self);
1046 result = PyEval_EvalCode(code, globals, locals);
1047 do_stop(self);
1048#if 0
1049 if (!PyErr_Occurred()) {
1050 result = Py_None;
1051 Py_INCREF(result);
1052 }
1053#endif
1054 }
1055 }
1056 return result;
1057}
1058
Tim Petersfeab23f2001-10-13 00:11:10 +00001059static char start__doc__[] =
1060"start()\n"
1061"Install this profiler for the current thread.";
Fred Drake8c081a12001-10-12 20:57:55 +00001062
1063static PyObject *
1064profiler_start(ProfilerObject *self, PyObject *args)
1065{
1066 PyObject *result = NULL;
1067
1068 if (PyArg_ParseTuple(args, ":start")) {
1069 if (is_available(self))
1070 do_start(self);
1071 }
1072 return result;
1073}
1074
Tim Petersfeab23f2001-10-13 00:11:10 +00001075static char stop__doc__[] =
1076"stop()\n"
1077"Remove this profiler from the current thread.";
Fred Drake8c081a12001-10-12 20:57:55 +00001078
1079static PyObject *
1080profiler_stop(ProfilerObject *self, PyObject *args)
1081{
1082 PyObject *result = NULL;
1083
1084 if (PyArg_ParseTuple(args, ":stop")) {
1085 if (!self->active)
1086 PyErr_SetString(ProfilerError, "profiler not active");
1087 else
1088 do_stop(self);
1089 }
1090 return result;
1091}
1092
1093
1094/* Python API support. */
1095
1096static void
1097profiler_dealloc(ProfilerObject *self)
1098{
1099 do_stop(self);
1100 if (self->logfp != NULL)
1101 fclose(self->logfp);
1102 Py_XDECREF(self->filemap);
1103 Py_XDECREF(self->logfilename);
1104 PyObject_Del((PyObject *)self);
1105}
1106
1107/* Always use METH_VARARGS even though some of these could be METH_NOARGS;
1108 * this allows us to maintain compatibility with Python versions < 2.2
1109 * more easily, requiring only the changes to the dispatcher to be made.
1110 */
1111static PyMethodDef profiler_methods[] = {
1112 {"close", (PyCFunction)profiler_close, METH_VARARGS, close__doc__},
1113 {"runcall", (PyCFunction)profiler_runcall, METH_VARARGS, runcall__doc__},
1114 {"runcode", (PyCFunction)profiler_runcode, METH_VARARGS, runcode__doc__},
1115 {"start", (PyCFunction)profiler_start, METH_VARARGS, start__doc__},
1116 {"stop", (PyCFunction)profiler_stop, METH_VARARGS, stop__doc__},
1117 {NULL, NULL}
1118};
1119
1120/* Use a table even though there's only one "simple" member; this allows
1121 * __members__ and therefore dir() to work.
1122 */
1123static struct memberlist profiler_members[] = {
Fred Drake30d1c752001-10-15 22:11:02 +00001124 {"closed", T_INT, -1, READONLY},
1125 {"frametimings", T_LONG, offsetof(ProfilerObject, linetimings), READONLY},
1126 {"lineevents", T_LONG, offsetof(ProfilerObject, lineevents), READONLY},
1127 {"linetimings", T_LONG, offsetof(ProfilerObject, linetimings), READONLY},
Fred Drake8c081a12001-10-12 20:57:55 +00001128 {NULL}
1129};
1130
1131static PyObject *
1132profiler_getattr(ProfilerObject *self, char *name)
1133{
1134 PyObject *result;
1135 if (strcmp(name, "closed") == 0) {
1136 result = (self->logfp == NULL) ? Py_True : Py_False;
1137 Py_INCREF(result);
1138 }
1139 else {
1140 result = PyMember_Get((char *)self, profiler_members, name);
1141 if (result == NULL) {
1142 PyErr_Clear();
1143 result = Py_FindMethod(profiler_methods, (PyObject *)self, name);
1144 }
1145 }
1146 return result;
1147}
1148
1149
Tim Petersfeab23f2001-10-13 00:11:10 +00001150static char profiler_object__doc__[] =
1151"High-performance profiler object.\n"
1152"\n"
1153"Methods:\n"
1154"\n"
Fred Drake30d1c752001-10-15 22:11:02 +00001155"close(): Stop the profiler and close the log files.\n"
1156"runcall(): Run a single function call with profiling enabled.\n"
1157"runcode(): Execute a code object with profiling enabled.\n"
1158"start(): Install the profiler and return.\n"
1159"stop(): Remove the profiler.\n"
Tim Petersfeab23f2001-10-13 00:11:10 +00001160"\n"
1161"Attributes (read-only):\n"
1162"\n"
Fred Drake30d1c752001-10-15 22:11:02 +00001163"closed: True if the profiler has already been closed.\n"
1164"frametimings: True if ENTER/EXIT events collect timing information.\n"
1165"lineevents: True if SET_LINENO events are reported to the profiler.\n"
1166"linetimings: True if SET_LINENO events collect timing information.";
Fred Drake8c081a12001-10-12 20:57:55 +00001167
1168static PyTypeObject ProfilerType = {
1169 PyObject_HEAD_INIT(NULL)
1170 0, /* ob_size */
1171 "HotShot-profiler", /* tp_name */
1172 (int) sizeof(ProfilerObject), /* tp_basicsize */
1173 0, /* tp_itemsize */
1174 (destructor)profiler_dealloc, /* tp_dealloc */
1175 0, /* tp_print */
1176 (getattrfunc)profiler_getattr, /* tp_getattr */
1177 0, /* tp_setattr */
1178 0, /* tp_compare */
1179 0, /* tp_repr */
1180 0, /* tp_as_number */
1181 0, /* tp_as_sequence */
1182 0, /* tp_as_mapping */
1183 0, /* tp_hash */
1184 0, /* tp_call */
1185 0, /* tp_str */
1186 0, /* tp_getattro */
1187 0, /* tp_setattro */
1188 0, /* tp_as_buffer */
1189 0, /* tp_flags */
1190 profiler_object__doc__, /* tp_doc */
1191};
1192
1193
1194static PyMethodDef logreader_methods[] = {
1195 {"close", (PyCFunction)logreader_close, METH_VARARGS,
1196 logreader_close__doc__},
1197 {"next", (PyCFunction)logreader_next, METH_VARARGS,
1198 next__doc__},
1199 {NULL, NULL}
1200};
1201
1202static PyObject *
1203logreader_getattr(ProfilerObject *self, char *name)
1204{
1205 return Py_FindMethod(logreader_methods, (PyObject *)self, name);
1206}
1207
1208
1209static char logreader__doc__[] = "\
1210logreader(filename) --> log-iterator\n\
1211Create a log-reader for the timing information file.";
1212
1213static PySequenceMethods logreader_as_sequence = {
1214 0, /* sq_length */
1215 0, /* sq_concat */
1216 0, /* sq_repeat */
1217 (intargfunc)logreader_sq_item, /* sq_item */
1218 0, /* sq_slice */
1219 0, /* sq_ass_item */
1220 0, /* sq_ass_slice */
1221 0, /* sq_contains */
1222 0, /* sq_inplace_concat */
1223 0, /* sq_inplace_repeat */
1224};
1225
1226static PyTypeObject LogReaderType = {
1227 PyObject_HEAD_INIT(NULL)
1228 0, /* ob_size */
1229 "HotShot-logreader", /* tp_name */
1230 (int) sizeof(LogReaderObject), /* tp_basicsize */
1231 0, /* tp_itemsize */
1232 (destructor)logreader_dealloc, /* tp_dealloc */
1233 0, /* tp_print */
1234 (getattrfunc)logreader_getattr, /* tp_getattr */
1235 0, /* tp_setattr */
1236 0, /* tp_compare */
1237 0, /* tp_repr */
1238 0, /* tp_as_number */
1239 &logreader_as_sequence, /* tp_as_sequence */
1240 0, /* tp_as_mapping */
1241 0, /* tp_hash */
1242 0, /* tp_call */
1243 0, /* tp_str */
1244 0, /* tp_getattro */
1245 0, /* tp_setattro */
1246 0, /* tp_as_buffer */
1247 0, /* tp_flags */
1248 logreader__doc__, /* tp_doc */
1249#if Py_TPFLAGS_HAVE_ITER
1250 0, /* tp_traverse */
1251 0, /* tp_clear */
1252 0, /* tp_richcompare */
1253 0, /* tp_weaklistoffset */
1254 (getiterfunc)logreader_tp_iter, /* tp_iter */
1255 (iternextfunc)logreader_tp_iternext,/* tp_iternext */
1256#endif
1257};
1258
1259static PyObject *
1260hotshot_logreader(PyObject *unused, PyObject *args)
1261{
1262 LogReaderObject *self = NULL;
1263 char *filename;
1264
1265 if (PyArg_ParseTuple(args, "s:logreader", &filename)) {
1266 self = PyObject_New(LogReaderObject, &LogReaderType);
1267 if (self != NULL) {
1268 self->filled = 0;
1269 self->index = 0;
Fred Drake30d1c752001-10-15 22:11:02 +00001270 self->frametimings = 1;
Fred Drake8c081a12001-10-12 20:57:55 +00001271 self->linetimings = 0;
1272 self->logfp = fopen(filename, "rb");
1273 if (self->logfp == NULL) {
1274 PyErr_SetFromErrnoWithFilename(PyExc_IOError, filename);
1275 Py_DECREF(self);
1276 self = NULL;
1277 }
1278 }
1279 }
1280 return (PyObject *) self;
1281}
1282
1283
1284/* Return a Python string that represents the version number without the
1285 * extra cruft added by revision control, even if the right options were
1286 * given to the "cvs export" command to make it not include the extra
1287 * cruft.
1288 */
1289static char *
1290get_version_string(void)
1291{
1292 static char *rcsid = "$Revision$";
1293 char *rev = rcsid;
1294 char *buffer;
1295 int i = 0;
1296
1297 while (*rev && !isdigit(*rev))
1298 ++rev;
1299 while (rev[i] != ' ' && rev[i] != '\0')
1300 ++i;
1301 buffer = malloc(i + 1);
1302 if (buffer != NULL) {
1303 memmove(buffer, rev, i);
1304 buffer[i] = '\0';
1305 }
1306 return buffer;
1307}
1308
1309/* Write out a RFC 822-style header with various useful bits of
1310 * information to make the output easier to manage.
1311 */
1312static int
1313write_header(ProfilerObject *self)
1314{
1315 char *buffer;
1316 char cwdbuffer[PATH_MAX];
1317 PyObject *temp;
1318 int i, len;
1319
1320 buffer = get_version_string();
1321 if (buffer == NULL) {
1322 PyErr_NoMemory();
1323 return -1;
1324 }
1325 pack_add_info(self, "HotShot-Version", buffer);
1326 pack_add_info(self, "Requested-Line-Events",
1327 (self->lineevents ? "yes" : "no"));
1328 pack_add_info(self, "Platform", Py_GetPlatform());
1329 pack_add_info(self, "Executable", Py_GetProgramFullPath());
1330 buffer = (char *) Py_GetVersion();
1331 if (buffer == NULL)
1332 PyErr_Clear();
1333 else
1334 pack_add_info(self, "Executable-Version", buffer);
1335
1336#ifdef MS_WIN32
1337 sprintf(cwdbuffer, "%I64d", frequency.QuadPart);
1338 pack_add_info(self, "Reported-Performance-Frequency", cwdbuffer);
1339#else
1340 sprintf(cwdbuffer, "%lu", rusage_diff);
1341 pack_add_info(self, "Observed-Interval-getrusage", cwdbuffer);
1342 sprintf(cwdbuffer, "%lu", timeofday_diff);
1343 pack_add_info(self, "Observed-Interval-gettimeofday", cwdbuffer);
1344#endif
Fred Drake30d1c752001-10-15 22:11:02 +00001345 pack_frame_times(self);
Fred Drake8c081a12001-10-12 20:57:55 +00001346 pack_line_times(self);
1347
1348 pack_add_info(self, "Current-Directory",
1349 getcwd(cwdbuffer, sizeof cwdbuffer));
1350
1351 temp = PySys_GetObject("path");
1352 len = PyList_GET_SIZE(temp);
1353 for (i = 0; i < len; ++i) {
1354 PyObject *item = PyList_GET_ITEM(temp, i);
1355 buffer = PyString_AsString(item);
1356 if (buffer == NULL)
1357 return -1;
1358 pack_add_info(self, "Sys-Path-Entry", buffer);
1359 }
1360 return 0;
1361}
1362
1363static char profiler__doc__[] = "\
1364profiler(logfilename[, lineevents[, linetimes]]) -> profiler\n\
1365Create a new profiler object.";
1366
1367static PyObject *
1368hotshot_profiler(PyObject *unused, PyObject *args)
1369{
1370 char *logfilename;
1371 ProfilerObject *self = NULL;
1372 int lineevents = 0;
1373 int linetimings = 1;
1374
1375 if (PyArg_ParseTuple(args, "s|ii:profiler", &logfilename,
1376 &lineevents, &linetimings)) {
1377 self = PyObject_New(ProfilerObject, &ProfilerType);
1378 if (self == NULL)
1379 return NULL;
Fred Drake30d1c752001-10-15 22:11:02 +00001380 self->frametimings = 1;
Fred Drake8c081a12001-10-12 20:57:55 +00001381 self->lineevents = lineevents ? 1 : 0;
1382 self->linetimings = (lineevents && linetimings) ? 1 : 0;
1383 self->index = 0;
1384 self->active = 0;
1385 self->next_fileno = 0;
Tim Peters1566a172001-10-12 22:08:39 +00001386 self->logfp = NULL;
Fred Drake8c081a12001-10-12 20:57:55 +00001387 self->logfilename = PyTuple_GET_ITEM(args, 0);
1388 Py_INCREF(self->logfilename);
1389 self->filemap = PyDict_New();
1390 if (self->filemap == NULL) {
1391 Py_DECREF(self);
1392 return NULL;
1393 }
1394 self->logfp = fopen(logfilename, "wb");
1395 if (self->logfp == NULL) {
1396 Py_DECREF(self);
1397 PyErr_SetFromErrnoWithFilename(PyExc_IOError, logfilename);
1398 return NULL;
1399 }
1400 if (timeofday_diff == 0) {
1401 /* Run this several times since sometimes the first
1402 * doesn't give the lowest values, and we're really trying
1403 * to determine the lowest.
1404 */
1405 calibrate();
1406 calibrate();
1407 calibrate();
1408 }
1409 if (write_header(self))
1410 /* some error occurred, exception has been set */
1411 self = NULL;
1412 }
1413 return (PyObject *) self;
1414}
1415
Fred Drake30d1c752001-10-15 22:11:02 +00001416static char coverage__doc__[] = "\
1417coverage(logfilename) -> profiler\n\
1418Returns a profiler that doesn't collect any timing information, which is\n\
1419useful in building a coverage analysis tool.";
1420
1421static PyObject *
1422hotshot_coverage(PyObject *unused, PyObject *args)
1423{
1424 char *logfilename;
1425 PyObject *result = NULL;
1426
1427 if (PyArg_ParseTuple(args, "s:coverage", &logfilename)) {
1428 result = hotshot_profiler(unused, args);
1429 if (result != NULL) {
1430 ProfilerObject *self = (ProfilerObject *) result;
1431 self->frametimings = 0;
1432 self->linetimings = 0;
1433 self->lineevents = 1;
1434 }
1435 }
1436 return result;
1437}
1438
Fred Drake8c081a12001-10-12 20:57:55 +00001439static char resolution__doc__[] =
1440#ifdef MS_WIN32
Tim Petersfeab23f2001-10-13 00:11:10 +00001441"resolution() -> (performance-counter-ticks, update-frequency)\n"
1442"Return the resolution of the timer provided by the QueryPerformanceCounter()\n"
1443"function. The first value is the smallest observed change, and the second\n"
1444"is the result of QueryPerformanceFrequency().";
Fred Drake8c081a12001-10-12 20:57:55 +00001445#else
Tim Petersfeab23f2001-10-13 00:11:10 +00001446"resolution() -> (gettimeofday-usecs, getrusage-usecs)\n"
1447"Return the resolution of the timers provided by the gettimeofday() and\n"
1448"getrusage() system calls, or -1 if the call is not supported.";
Fred Drake8c081a12001-10-12 20:57:55 +00001449#endif
1450
1451static PyObject *
1452hotshot_resolution(PyObject *unused, PyObject *args)
1453{
1454 PyObject *result = NULL;
1455
1456 if (PyArg_ParseTuple(args, ":resolution")) {
1457 if (timeofday_diff == 0) {
1458 calibrate();
1459 calibrate();
1460 calibrate();
1461 }
1462#ifdef MS_WIN32
1463 result = Py_BuildValue("ii", timeofday_diff, frequency.LowPart);
1464#else
1465 result = Py_BuildValue("ii", timeofday_diff, rusage_diff);
1466#endif
1467 }
1468 return result;
1469}
1470
1471
1472static PyMethodDef functions[] = {
Fred Drake30d1c752001-10-15 22:11:02 +00001473 {"coverage", hotshot_coverage, METH_VARARGS, coverage__doc__},
Fred Drake8c081a12001-10-12 20:57:55 +00001474 {"profiler", hotshot_profiler, METH_VARARGS, profiler__doc__},
1475 {"logreader", hotshot_logreader, METH_VARARGS, logreader__doc__},
1476 {"resolution", hotshot_resolution, METH_VARARGS, resolution__doc__},
1477 {NULL, NULL}
1478};
1479
1480
1481void
1482init_hotshot(void)
1483{
1484 PyObject *module;
1485
1486 LogReaderType.ob_type = &PyType_Type;
1487 ProfilerType.ob_type = &PyType_Type;
1488 module = Py_InitModule("_hotshot", functions);
1489 if (module != NULL) {
1490 char *s = get_version_string();
1491
1492 PyModule_AddStringConstant(module, "__version__", s);
1493 free(s);
1494 Py_INCREF(&LogReaderType);
1495 PyModule_AddObject(module, "LogReaderType",
1496 (PyObject *)&LogReaderType);
1497 Py_INCREF(&ProfilerType);
1498 PyModule_AddObject(module, "ProfilerType",
1499 (PyObject *)&ProfilerType);
1500
1501 if (ProfilerError == NULL)
1502 ProfilerError = PyErr_NewException("hotshot.ProfilerError",
1503 NULL, NULL);
1504 if (ProfilerError != NULL) {
1505 Py_INCREF(ProfilerError);
1506 PyModule_AddObject(module, "ProfilerError", ProfilerError);
1507 }
1508 PyModule_AddIntConstant(module, "WHAT_ENTER", WHAT_ENTER);
1509 PyModule_AddIntConstant(module, "WHAT_EXIT", WHAT_EXIT);
1510 PyModule_AddIntConstant(module, "WHAT_LINENO", WHAT_LINENO);
1511 PyModule_AddIntConstant(module, "WHAT_OTHER", WHAT_OTHER);
1512 PyModule_AddIntConstant(module, "WHAT_ADD_INFO", WHAT_ADD_INFO);
1513 PyModule_AddIntConstant(module, "WHAT_DEFINE_FILE", WHAT_DEFINE_FILE);
Fred Drake30d1c752001-10-15 22:11:02 +00001514 PyModule_AddIntConstant(module, "WHAT_DEFINE_FUNC", WHAT_DEFINE_FUNC);
Fred Drake8c081a12001-10-12 20:57:55 +00001515 PyModule_AddIntConstant(module, "WHAT_LINE_TIMES", WHAT_LINE_TIMES);
1516 }
1517}