Debian Codegraph @

cpython27/Modules/_hotshot.c

raw symbols SCIP
1 /*
2 * This is the High Performance Python Profiler portion of HotShot.
3 */
4
5 #include "Python.h"
6 #include "code.h"
7 #include "eval.h"
8 #include "frameobject.h"
9 #include "structmember.h"
10
11 /*
12 * Which timer to use should be made more configurable, but that should not
13 * be difficult. This will do for now.
14 */
15 #ifdef MS_WINDOWS
16 #include <windows.h>
17
18 #ifdef HAVE_DIRECT_H
19 #include <direct.h> /* for getcwd() */
20 #endif
21
22 typedef __int64 hs_time;
23 #define GETTIMEOFDAY(P_HS_TIME) \
24 { LARGE_INTEGER _temp; \
25 QueryPerformanceCounter(&_temp); \
26 *(P_HS_TIME) = _temp.QuadPart; }
27
28
29 #else
30 #ifndef HAVE_GETTIMEOFDAY
31 #error "This module requires gettimeofday() on non-Windows platforms!"
32 #endif
33 #if (defined(PYOS_OS2) && defined(PYCC_GCC)) || defined(__QNX__)
34 #include <sys/time.h>
35 #else
36 #include <sys/resource.h>
37 #include <sys/times.h>
38 #endif
39 typedef struct timeval hs_time;
40 #endif
41
42 #if !defined(__cplusplus) && !defined(inline)
43 #ifdef __GNUC__
44 #define inline __inline
45 #endif
46 #endif
47
48 #ifndef inline
49 #define inline
50 #endif
51
52 #define BUFFERSIZE 10240
53
54 #if defined(PYOS_OS2) && defined(PYCC_GCC)
55 #define PATH_MAX 260
56 #endif
57
58 #if defined(__sgi) && _COMPILER_VERSION>700 && !defined(PATH_MAX)
59 /* fix PATH_MAX not being defined with MIPSPro 7.x
60 if mode is ANSI C (default) */
61 #define PATH_MAX 1024
62 #endif
63
64 #ifndef PATH_MAX
65 # ifdef MAX_PATH
66 # define PATH_MAX MAX_PATH
67 # elif defined (_POSIX_PATH_MAX)
68 # define PATH_MAX _POSIX_PATH_MAX
69 # else
70 # error "Need a defn. for PATH_MAX in _hotshot.c"
71 # endif
72 #endif
73
74 typedef struct {
75 PyObject_HEAD
76 PyObject *filemap;
77 PyObject *logfilename;
78 Py_ssize_t index;
79 unsigned char buffer[BUFFERSIZE];
80 FILE *logfp;
81 int lineevents;
82 int linetimings;
83 int frametimings;
84 /* size_t filled; */
85 int active;
86 int next_fileno;
87 hs_time prev_timeofday;
88 } ProfilerObject;
89
90 typedef struct {
91 PyObject_HEAD
92 PyObject *info;
93 FILE *logfp;
94 int linetimings;
95 int frametimings;
96 } LogReaderObject;
97
98 static PyObject * ProfilerError = NULL;
99
100
101 #ifndef MS_WINDOWS
102 #ifdef GETTIMEOFDAY_NO_TZ
103 #define GETTIMEOFDAY(ptv) gettimeofday((ptv))
104 #else
105 #define GETTIMEOFDAY(ptv) gettimeofday((ptv), (struct timezone *)NULL)
106 #endif
107 #endif
108
109
110 /* The log reader... */
111
112 PyDoc_STRVAR(logreader_close__doc__,
113 "close()\n"
114 "Close the log file, preventing additional records from being read.");
115
116 static PyObject *
117 logreader_close(LogReaderObject *self, PyObject *args)
118 {
119 if (self->logfp != NULL) {
120 fclose(self->logfp);
121 self->logfp = NULL;
122 }
123 Py_INCREF(Py_None);
124
125 return Py_None;
126 }
127
128 PyDoc_STRVAR(logreader_fileno__doc__,
129 "fileno() -> file descriptor\n"
130 "Returns the file descriptor for the log file, if open.\n"
131 "Raises ValueError if the log file is closed.");
132
133 static PyObject *
134 logreader_fileno(LogReaderObject *self)
135 {
136 if (self->logfp == NULL) {
137 PyErr_SetString(PyExc_ValueError,
138 "logreader's file object already closed");
139 return NULL;
140 }
141 return PyInt_FromLong(fileno(self->logfp));
142 }
143
144
145 /* Log File Format
146 * ---------------
147 *
148 * The log file consists of a sequence of variable-length records.
149 * Each record is identified with a record type identifier in two
150 * bits of the first byte. The two bits are the "least significant"
151 * bits of the byte.
152 *
153 * Low bits: Opcode: Meaning:
154 * 0x00 ENTER enter a frame
155 * 0x01 EXIT exit a frame
156 * 0x02 LINENO execution moved onto a different line
157 * 0x03 OTHER more bits are needed to deecode
158 *
159 * If the type is OTHER, the record is not packed so tightly, and the
160 * remaining bits are used to disambiguate the record type. These
161 * records are not used as frequently so compaction is not an issue.
162 * Each of the first three record types has a highly tailored
163 * structure that allows it to be packed tightly.
164 *
165 * The OTHER records have the following identifiers:
166 *
167 * First byte: Opcode: Meaning:
168 * 0x13 ADD_INFO define a key/value pair
169 * 0x23 DEFINE_FILE define an int->filename mapping
170 * 0x33 LINE_TIMES indicates if LINENO events have tdeltas
171 * 0x43 DEFINE_FUNC define a (fileno,lineno)->funcname mapping
172 * 0x53 FRAME_TIMES indicates if ENTER/EXIT events have tdeltas
173 *
174 * Packed Integers
175 *
176 * "Packed integers" are non-negative integer values encoded as a
177 * sequence of bytes. Each byte is encoded such that the most
178 * significant bit is set if the next byte is also part of the
179 * integer. Each byte provides bits to the least-significant end of
180 * the result; the accumulated value must be shifted up to place the
181 * new bits into the result.
182 *
183 * "Modified packed integers" are packed integers where only a portion
184 * of the first byte is used. In the rest of the specification, these
185 * are referred to as "MPI(n,name)", where "n" is the number of bits
186 * discarded from the least-signicant positions of the byte, and
187 * "name" is a name being given to those "discarded" bits, since they
188 * are a field themselves.
189 *
190 * ENTER records:
191 *
192 * MPI(2,type) fileno -- type is 0x00
193 * PI lineno
194 * PI tdelta -- iff frame times are enabled
195 *
196 * EXIT records
197 *
198 * MPI(2,type) tdelta -- type is 0x01; tdelta will be 0
199 * if frame times are disabled
200 *
201 * LINENO records
202 *
203 * MPI(2,type) lineno -- type is 0x02
204 * PI tdelta -- iff LINENO includes it
205 *
206 * ADD_INFO records
207 *
208 * BYTE type -- always 0x13
209 * PI len1 -- length of first string
210 * BYTE string1[len1] -- len1 bytes of string data
211 * PI len2 -- length of second string
212 * BYTE string2[len2] -- len2 bytes of string data
213 *
214 * DEFINE_FILE records
215 *
216 * BYTE type -- always 0x23
217 * PI fileno
218 * PI len -- length of filename
219 * BYTE filename[len] -- len bytes of string data
220 *
221 * DEFINE_FUNC records
222 *
223 * BYTE type -- always 0x43
224 * PI fileno
225 * PI lineno
226 * PI len -- length of funcname
227 * BYTE funcname[len] -- len bytes of string data
228 *
229 * LINE_TIMES records
230 *
231 * This record can be used only before the start of ENTER/EXIT/LINENO
232 * records. If have_tdelta is true, LINENO records will include the
233 * tdelta field, otherwise it will be omitted. If this record is not
234 * given, LINENO records will not contain the tdelta field.
235 *
236 * BYTE type -- always 0x33
237 * BYTE have_tdelta -- 0 if LINENO does *not* have
238 * timing information
239 * FRAME_TIMES records
240 *
241 * This record can be used only before the start of ENTER/EXIT/LINENO
242 * records. If have_tdelta is true, ENTER and EXIT records will
243 * include the tdelta field, otherwise it will be omitted. If this
244 * record is not given, ENTER and EXIT records will contain the tdelta
245 * field.
246 *
247 * BYTE type -- always 0x53
248 * BYTE have_tdelta -- 0 if ENTER/EXIT do *not* have
249 * timing information
250 */
251
252 #define WHAT_ENTER 0x00
253 #define WHAT_EXIT 0x01
254 #define WHAT_LINENO 0x02
255 #define WHAT_OTHER 0x03 /* only used in decoding */
256 #define WHAT_ADD_INFO 0x13
257 #define WHAT_DEFINE_FILE 0x23
258 #define WHAT_LINE_TIMES 0x33
259 #define WHAT_DEFINE_FUNC 0x43
260 #define WHAT_FRAME_TIMES 0x53
261
262 #define ERR_NONE 0
263 #define ERR_EOF -1
264 #define ERR_EXCEPTION -2
265 #define ERR_BAD_RECTYPE -3
266
267 #define PISIZE (sizeof(int) + 1)
268 #define MPISIZE (PISIZE + 1)
269
270 /* Maximum size of "normal" events -- nothing that contains string data */
271 #define MAXEVENTSIZE (MPISIZE + PISIZE*2)
272
273
274 /* Unpack a packed integer; if "discard" is non-zero, unpack a modified
275 * packed integer with "discard" discarded bits.
276 */
277 static int
278 unpack_packed_int(LogReaderObject *self, int *pvalue, int discard)
279 {
280 int c;
281 int accum = 0;
282 int bits = 0;
283 int cont;
284
285 do {
286 /* read byte */
287 if ((c = fgetc(self->logfp)) == EOF)
288 return ERR_EOF;
289 accum |= ((c & 0x7F) >> discard) << bits;
290 bits += (7 - discard);
291 cont = c & 0x80;
292 discard = 0;
293 } while (cont);
294
295 *pvalue = accum;
296
297 return 0;
298 }
299
300 /* Unpack a string, which is encoded as a packed integer giving the
301 * length of the string, followed by the string data.
302 */
303 static int
304 unpack_string(LogReaderObject *self, PyObject **pvalue)
305 {
306 int i;
307 int len;
308 int err;
309 int ch;
310 char *buf;
311
312 if ((err = unpack_packed_int(self, &len, 0)))
313 return err;
314
315 buf = (char *)malloc(len);
316 if (!buf) {
317 PyErr_NoMemory();
318 return ERR_EXCEPTION;
319 }
320
321 for (i=0; i < len; i++) {
322 ch = fgetc(self->logfp);
323 buf[i] = ch;
324 if (ch == EOF) {
325 free(buf);
326 return ERR_EOF;
327 }
328 }
329 *pvalue = PyString_FromStringAndSize(buf, len);
330 free(buf);
331 if (*pvalue == NULL) {
332 return ERR_EXCEPTION;
333 }
334 return 0;
335 }
336
337
338 static int
339 unpack_add_info(LogReaderObject *self)
340 {
341 PyObject *key = NULL;
342 PyObject *value = NULL;
343 PyObject *list;
344 int err;
345
346 err = unpack_string(self, &key);
347 if (err)
348 goto finally;
349 err = unpack_string(self, &value);
350 if (err)
351 goto finally;
352 list = PyDict_GetItem(self->info, key);
353 if (list == NULL) {
354 list = PyList_New(0);
355 if (list == NULL) {
356 err = ERR_EXCEPTION;
357 goto finally;
358 }
359 if (PyDict_SetItem(self->info, key, list)) {
360 Py_DECREF(list);
361 err = ERR_EXCEPTION;
362 goto finally;
363 }
364 Py_DECREF(list);
365 }
366 if (PyList_Append(list, value))
367 err = ERR_EXCEPTION;
368
369 finally:
370 Py_XDECREF(key);
371 Py_XDECREF(value);
372 return err;
373 }
374
375
376 static void
377 eof_error(LogReaderObject *self)
378 {
379 fclose(self->logfp);
380 self->logfp = NULL;
381 PyErr_SetString(PyExc_EOFError,
382 "end of file with incomplete profile record");
383 }
384
385 static PyObject *
386 logreader_tp_iternext(LogReaderObject *self)
387 {
388 int c;
389 int what;
390 int err = ERR_NONE;
391 int lineno = -1;
392 int fileno = -1;
393 int tdelta = -1;
394 PyObject *s1 = NULL, *s2 = NULL;
395 PyObject *result = NULL;
396 #if 0
397 unsigned char b0, b1;
398 #endif
399
400 if (self->logfp == NULL) {
401 PyErr_SetString(ProfilerError,
402 "cannot iterate over closed LogReader object");
403 return NULL;
404 }
405
406 restart:
407 /* decode the record type */
408 if ((c = fgetc(self->logfp)) == EOF) {
409 fclose(self->logfp);
410 self->logfp = NULL;
411 return NULL;
412 }
413 what = c & WHAT_OTHER;
414 if (what == WHAT_OTHER)
415 what = c; /* need all the bits for type */
416 else
417 ungetc(c, self->logfp); /* type byte includes packed int */
418
419 switch (what) {
420 case WHAT_ENTER:
421 err = unpack_packed_int(self, &fileno, 2);
422 if (!err) {
423 err = unpack_packed_int(self, &lineno, 0);
424 if (self->frametimings && !err)
425 err = unpack_packed_int(self, &tdelta, 0);
426 }
427 break;
428 case WHAT_EXIT:
429 err = unpack_packed_int(self, &tdelta, 2);
430 break;
431 case WHAT_LINENO:
432 err = unpack_packed_int(self, &lineno, 2);
433 if (self->linetimings && !err)
434 err = unpack_packed_int(self, &tdelta, 0);
435 break;
436 case WHAT_ADD_INFO:
437 err = unpack_add_info(self);
438 break;
439 case WHAT_DEFINE_FILE:
440 err = unpack_packed_int(self, &fileno, 0);
441 if (!err) {
442 err = unpack_string(self, &s1);
443 if (!err) {
444 Py_INCREF(Py_None);
445 s2 = Py_None;
446 }
447 }
448 break;
449 case WHAT_DEFINE_FUNC:
450 err = unpack_packed_int(self, &fileno, 0);
451 if (!err) {
452 err = unpack_packed_int(self, &lineno, 0);
453 if (!err)
454 err = unpack_string(self, &s1);
455 }
456 break;
457 case WHAT_LINE_TIMES:
458 if ((c = fgetc(self->logfp)) == EOF)
459 err = ERR_EOF;
460 else {
461 self->linetimings = c ? 1 : 0;
462 goto restart;
463 }
464 break;
465 case WHAT_FRAME_TIMES:
466 if ((c = fgetc(self->logfp)) == EOF)
467 err = ERR_EOF;
468 else {
469 self->frametimings = c ? 1 : 0;
470 goto restart;
471 }
472 break;
473 default:
474 err = ERR_BAD_RECTYPE;
475 }
476 if (err == ERR_BAD_RECTYPE) {
477 PyErr_SetString(PyExc_ValueError,
478 "unknown record type in log file");
479 }
480 else if (err == ERR_EOF) {
481 eof_error(self);
482 }
483 else if (!err) {
484 result = PyTuple_New(4);
485 if (result == NULL) {
486 Py_XDECREF(s1);
487 Py_XDECREF(s2);
488 return NULL;
489 }
490 PyTuple_SET_ITEM(result, 0, PyInt_FromLong(what));
491 PyTuple_SET_ITEM(result, 2, PyInt_FromLong(fileno));
492 if (s1 == NULL)
493 PyTuple_SET_ITEM(result, 1, PyInt_FromLong(tdelta));
494 else
495 PyTuple_SET_ITEM(result, 1, s1);
496 if (s2 == NULL)
497 PyTuple_SET_ITEM(result, 3, PyInt_FromLong(lineno));
498 else
499 PyTuple_SET_ITEM(result, 3, s2);
500 }
501 /* The only other case is err == ERR_EXCEPTION, in which case the
502 * exception is already set.
503 */
504 #if 0
505 b0 = self->buffer[self->index];
506 b1 = self->buffer[self->index + 1];
507 if (b0 & 1) {
508 /* This is a line-number event. */
509 what = PyTrace_LINE;
510 lineno = ((b0 & ~1) << 7) + b1;
511 self->index += 2;
512 }
513 else {
514 what = (b0 & 0x0E) >> 1;
515 tdelta = ((b0 & 0xF0) << 4) + b1;
516 if (what == PyTrace_CALL) {
517 /* we know there's a 2-byte file ID & 2-byte line number */
518 fileno = ((self->buffer[self->index + 2] << 8)
519 + self->buffer[self->index + 3]);
520 lineno = ((self->buffer[self->index + 4] << 8)
521 + self->buffer[self->index + 5]);
522 self->index += 6;
523 }
524 else
525 self->index += 2;
526 }
527 #endif
528 return result;
529 }
530
531 static void
532 logreader_dealloc(LogReaderObject *self)
533 {
534 if (self->logfp != NULL) {
535 fclose(self->logfp);
536 self->logfp = NULL;
537 }
538 Py_XDECREF(self->info);
539 PyObject_Del(self);
540 }
541
542 static PyObject *
543 logreader_sq_item(LogReaderObject *self, Py_ssize_t index)
544 {
545 PyObject *result = logreader_tp_iternext(self);
546 if (result == NULL && !PyErr_Occurred()) {
547 PyErr_SetString(PyExc_IndexError, "no more events in log");
548 return NULL;
549 }
550 return result;
551 }
552
553 static void
554 do_stop(ProfilerObject *self);
555
556 static int
557 flush_data(ProfilerObject *self)
558 {
559 /* Need to dump data to the log file... */
560 size_t written = fwrite(self->buffer, 1, self->index, self->logfp);
561 if (written == (size_t)self->index)
562 self->index = 0;
563 else {
564 memmove(self->buffer, &self->buffer[written],
565 self->index - written);
566 self->index -= written;
567 if (written == 0) {
568 char *s = PyString_AsString(self->logfilename);
569 PyErr_SetFromErrnoWithFilename(PyExc_IOError, s);
570 do_stop(self);
571 return -1;
572 }
573 }
574 if (written > 0) {
575 if (fflush(self->logfp)) {
576 char *s = PyString_AsString(self->logfilename);
577 PyErr_SetFromErrnoWithFilename(PyExc_IOError, s);
578 do_stop(self);
579 return -1;
580 }
581 }
582 return 0;
583 }
584
585 static inline int
586 pack_packed_int(ProfilerObject *self, int value)
587 {
588 unsigned char partial;
589
590 do {
591 partial = value & 0x7F;
592 value >>= 7;
593 if (value)
594 partial |= 0x80;
595 self->buffer[self->index] = partial;
596 self->index++;
597 } while (value);
598 return 0;
599 }
600
601 /* Encode a modified packed integer, with a subfield of modsize bits
602 * containing the value "subfield". The value of subfield is not
603 * checked to ensure it actually fits in modsize bits.
604 */
605 static inline int
606 pack_modified_packed_int(ProfilerObject *self, int value,
607 int modsize, int subfield)
608 {
609 const int maxvalues[] = {-1, 1, 3, 7, 15, 31, 63, 127};
610
611 int bits = 7 - modsize;
612 int partial = value & maxvalues[bits];
613 unsigned char b = subfield | (partial << modsize);
614
615 if (partial != value) {
616 b |= 0x80;
617 self->buffer[self->index] = b;
618 self->index++;
619 return pack_packed_int(self, value >> bits);
620 }
621 self->buffer[self->index] = b;
622 self->index++;
623 return 0;
624 }
625
626 static int
627 pack_string(ProfilerObject *self, const char *s, Py_ssize_t len)
628 {
629 if (len + PISIZE + self->index >= BUFFERSIZE) {
630 if (flush_data(self) < 0)
631 return -1;
632 if (len + PISIZE + self->index >= BUFFERSIZE) {
633 PyErr_SetString(PyExc_ValueError, "string too large for internal buffer");
634 return -1;
635 }
636 }
637 assert(len < INT_MAX);
638 if (pack_packed_int(self, (int)len) < 0)
639 return -1;
640 memcpy(self->buffer + self->index, s, len);
641 self->index += len;
642 return 0;
643 }
644
645 static int
646 pack_add_info(ProfilerObject *self, const char *s1, const char *s2)
647 {
648 Py_ssize_t len1 = strlen(s1);
649 Py_ssize_t len2 = strlen(s2);
650
651 if (len1 + len2 + PISIZE*2 + 1 + self->index >= BUFFERSIZE) {
652 if (flush_data(self) < 0)
653 return -1;
654 }
655 self->buffer[self->index] = WHAT_ADD_INFO;
656 self->index++;
657 if (pack_string(self, s1, len1) < 0)
658 return -1;
659 return pack_string(self, s2, len2);
660 }
661
662 static int
663 pack_define_file(ProfilerObject *self, int fileno, const char *filename)
664 {
665 Py_ssize_t len = strlen(filename);
666
667 if (len + PISIZE*2 + 1 + self->index >= BUFFERSIZE) {
668 if (flush_data(self) < 0)
669 return -1;
670 }
671 self->buffer[self->index] = WHAT_DEFINE_FILE;
672 self->index++;
673 if (pack_packed_int(self, fileno) < 0)
674 return -1;
675 return pack_string(self, filename, len);
676 }
677
678 static int
679 pack_define_func(ProfilerObject *self, int fileno, int lineno,
680 const char *funcname)
681 {
682 Py_ssize_t len = strlen(funcname);
683
684 if (len + PISIZE*3 + 1 + self->index >= BUFFERSIZE) {
685 if (flush_data(self) < 0)
686 return -1;
687 }
688 self->buffer[self->index] = WHAT_DEFINE_FUNC;
689 self->index++;
690 if (pack_packed_int(self, fileno) < 0)
691 return -1;
692 if (pack_packed_int(self, lineno) < 0)
693 return -1;
694 return pack_string(self, funcname, len);
695 }
696
697 static int
698 pack_line_times(ProfilerObject *self)
699 {
700 if (2 + self->index >= BUFFERSIZE) {
701 if (flush_data(self) < 0)
702 return -1;
703 }
704 self->buffer[self->index] = WHAT_LINE_TIMES;
705 self->buffer[self->index + 1] = self->linetimings ? 1 : 0;
706 self->index += 2;
707 return 0;
708 }
709
710 static int
711 pack_frame_times(ProfilerObject *self)
712 {
713 if (2 + self->index >= BUFFERSIZE) {
714 if (flush_data(self) < 0)
715 return -1;
716 }
717 self->buffer[self->index] = WHAT_FRAME_TIMES;
718 self->buffer[self->index + 1] = self->frametimings ? 1 : 0;
719 self->index += 2;
720 return 0;
721 }
722
723 static inline int
724 pack_enter(ProfilerObject *self, int fileno, int tdelta, int lineno)
725 {
726 if (MPISIZE + PISIZE*2 + self->index >= BUFFERSIZE) {
727 if (flush_data(self) < 0)
728 return -1;
729 }
730 pack_modified_packed_int(self, fileno, 2, WHAT_ENTER);
731 pack_packed_int(self, lineno);
732 if (self->frametimings)
733 return pack_packed_int(self, tdelta);
734 else
735 return 0;
736 }
737
738 static inline int
739 pack_exit(ProfilerObject *self, int tdelta)
740 {
741 if (MPISIZE + self->index >= BUFFERSIZE) {
742 if (flush_data(self) < 0)
743 return -1;
744 }
745 if (self->frametimings)
746 return pack_modified_packed_int(self, tdelta, 2, WHAT_EXIT);
747 self->buffer[self->index] = WHAT_EXIT;
748 self->index++;
749 return 0;
750 }
751
752 static inline int
753 pack_lineno(ProfilerObject *self, int lineno)
754 {
755 if (MPISIZE + self->index >= BUFFERSIZE) {
756 if (flush_data(self) < 0)
757 return -1;
758 }
759 return pack_modified_packed_int(self, lineno, 2, WHAT_LINENO);
760 }
761
762 static inline int
763 pack_lineno_tdelta(ProfilerObject *self, int lineno, int tdelta)
764 {
765 if (MPISIZE + PISIZE + self->index >= BUFFERSIZE) {
766 if (flush_data(self) < 0)
767 return 0;
768 }
769 if (pack_modified_packed_int(self, lineno, 2, WHAT_LINENO) < 0)
770 return -1;
771 return pack_packed_int(self, tdelta);
772 }
773
774 static inline int
775 get_fileno(ProfilerObject *self, PyCodeObject *fcode)
776 {
777 /* This is only used for ENTER events. */
778
779 PyObject *obj;
780 PyObject *dict;
781 int fileno;
782
783 obj = PyDict_GetItem(self->filemap, fcode->co_filename);
784 if (obj == NULL) {
785 /* first sighting of this file */
786 dict = PyDict_New();
787 if (dict == NULL) {
788 return -1;
789 }
790 fileno = self->next_fileno;
791 obj = Py_BuildValue("iN", fileno, dict);
792 if (obj == NULL) {
793 return -1;
794 }
795 if (PyDict_SetItem(self->filemap, fcode->co_filename, obj)) {
796 Py_DECREF(obj);
797 return -1;
798 }
799 self->next_fileno++;
800 Py_DECREF(obj);
801 if (pack_define_file(self, fileno,
802 PyString_AS_STRING(fcode->co_filename)) < 0)
803 return -1;
804 }
805 else {
806 /* already know this ID */
807 fileno = PyInt_AS_LONG(PyTuple_GET_ITEM(obj, 0));
808 dict = PyTuple_GET_ITEM(obj, 1);
809 }
810 /* make sure we save a function name for this (fileno, lineno) */
811 obj = PyInt_FromLong(fcode->co_firstlineno);
812 if (obj == NULL) {
813 /* We just won't have it saved; too bad. */
814 PyErr_Clear();
815 }
816 else {
817 PyObject *name = PyDict_GetItem(dict, obj);
818 if (name == NULL) {
819 if (pack_define_func(self, fileno, fcode->co_firstlineno,
820 PyString_AS_STRING(fcode->co_name)) < 0) {
821 Py_DECREF(obj);
822 return -1;
823 }
824 if (PyDict_SetItem(dict, obj, fcode->co_name)) {
825 Py_DECREF(obj);
826 return -1;
827 }
828 }
829 Py_DECREF(obj);
830 }
831 return fileno;
832 }
833
834 static inline int
835 get_tdelta(ProfilerObject *self)
836 {
837 int tdelta;
838 #ifdef MS_WINDOWS
839 hs_time tv;
840 hs_time diff;
841
842 GETTIMEOFDAY(&tv);
843 diff = tv - self->prev_timeofday;
844 tdelta = (int)diff;
845 #else
846 struct timeval tv;
847
848 GETTIMEOFDAY(&tv);
849
850 tdelta = tv.tv_usec - self->prev_timeofday.tv_usec;
851 if (tv.tv_sec != self->prev_timeofday.tv_sec)
852 tdelta += (tv.tv_sec - self->prev_timeofday.tv_sec) * 1000000;
853 #endif
854 /* time can go backwards on some multiprocessor systems or by NTP */
855 if (tdelta < 0)
856 return 0;
857
858 self->prev_timeofday = tv;
859 return tdelta;
860 }
861
862
863 /* The workhorse: the profiler callback function. */
864
865 static int
866 tracer_callback(ProfilerObject *self, PyFrameObject *frame, int what,
867 PyObject *arg)
868 {
869 int fileno;
870
871 switch (what) {
872 case PyTrace_CALL:
873 fileno = get_fileno(self, frame->f_code);
874 if (fileno < 0)
875 return -1;
876 return pack_enter(self, fileno,
877 self->frametimings ? get_tdelta(self) : -1,
878 frame->f_code->co_firstlineno);
879
880 case PyTrace_RETURN:
881 return pack_exit(self, get_tdelta(self));
882
883 case PyTrace_LINE: /* we only get these events if we asked for them */
884 if (self->linetimings)
885 return pack_lineno_tdelta(self, frame->f_lineno,
886 get_tdelta(self));
887 else
888 return pack_lineno(self, frame->f_lineno);
889
890 default:
891 /* ignore PyTrace_EXCEPTION */
892 break;
893 }
894 return 0;
895 }
896
897
898 /* A couple of useful helper functions. */
899
900 #ifdef MS_WINDOWS
901 static LARGE_INTEGER frequency = {0, 0};
902 #endif
903
904 static unsigned long timeofday_diff = 0;
905 static unsigned long rusage_diff = 0;
906
907 static void
908 calibrate(void)
909 {
910 hs_time tv1, tv2;
911
912 #ifdef MS_WINDOWS
913 hs_time diff;
914 QueryPerformanceFrequency(&frequency);
915 #endif
916
917 GETTIMEOFDAY(&tv1);
918 while (1) {
919 GETTIMEOFDAY(&tv2);
920 #ifdef MS_WINDOWS
921 diff = tv2 - tv1;
922 if (diff != 0) {
923 timeofday_diff = (unsigned long)diff;
924 break;
925 }
926 #else
927 if (tv1.tv_sec != tv2.tv_sec || tv1.tv_usec != tv2.tv_usec) {
928 if (tv1.tv_sec == tv2.tv_sec)
929 timeofday_diff = tv2.tv_usec - tv1.tv_usec;
930 else
931 timeofday_diff = (1000000 - tv1.tv_usec) + tv2.tv_usec;
932 break;
933 }
934 #endif
935 }
936 #if defined(MS_WINDOWS) || defined(PYOS_OS2) || \
937 defined(__VMS) || defined (__QNX__)
938 rusage_diff = -1;
939 #else
940 {
941 struct rusage ru1, ru2;
942
943 getrusage(RUSAGE_SELF, &ru1);
944 while (1) {
945 getrusage(RUSAGE_SELF, &ru2);
946 if (ru1.ru_utime.tv_sec != ru2.ru_utime.tv_sec) {
947 rusage_diff = ((1000000 - ru1.ru_utime.tv_usec)
948 + ru2.ru_utime.tv_usec);
949 break;
950 }
951 else if (ru1.ru_utime.tv_usec != ru2.ru_utime.tv_usec) {
952 rusage_diff = ru2.ru_utime.tv_usec - ru1.ru_utime.tv_usec;
953 break;
954 }
955 else if (ru1.ru_stime.tv_sec != ru2.ru_stime.tv_sec) {
956 rusage_diff = ((1000000 - ru1.ru_stime.tv_usec)
957 + ru2.ru_stime.tv_usec);
958 break;
959 }
960 else if (ru1.ru_stime.tv_usec != ru2.ru_stime.tv_usec) {
961 rusage_diff = ru2.ru_stime.tv_usec - ru1.ru_stime.tv_usec;
962 break;
963 }
964 }
965 }
966 #endif
967 }
968
969 static void
970 do_start(ProfilerObject *self)
971 {
972 self->active = 1;
973 GETTIMEOFDAY(&self->prev_timeofday);
974 if (self->lineevents)
975 PyEval_SetTrace((Py_tracefunc) tracer_callback, (PyObject *)self);
976 else
977 PyEval_SetProfile((Py_tracefunc) tracer_callback, (PyObject *)self);
978 }
979
980 static void
981 do_stop(ProfilerObject *self)
982 {
983 if (self->active) {
984 self->active = 0;
985 if (self->lineevents)
986 PyEval_SetTrace(NULL, NULL);
987 else
988 PyEval_SetProfile(NULL, NULL);
989 }
990 if (self->index > 0) {
991 /* Best effort to dump out any remaining data. */
992 flush_data(self);
993 }
994 }
995
996 static int
997 is_available(ProfilerObject *self)
998 {
999 if (self->active) {
1000 PyErr_SetString(ProfilerError, "profiler already active");
1001 return 0;
1002 }
1003 if (self->logfp == NULL) {
1004 PyErr_SetString(ProfilerError, "profiler already closed");
1005 return 0;
1006 }
1007 return 1;
1008 }
1009
1010
1011 /* Profiler object interface methods. */
1012
1013 PyDoc_STRVAR(addinfo__doc__,
1014 "addinfo(key, value)\n"
1015 "Insert an ADD_INFO record into the log.");
1016
1017 static PyObject *
1018 profiler_addinfo(ProfilerObject *self, PyObject *args)
1019 {
1020 PyObject *result = NULL;
1021 char *key, *value;
1022
1023 if (PyArg_ParseTuple(args, "ss:addinfo", &key, &value)) {
1024 if (self->logfp == NULL)
1025 PyErr_SetString(ProfilerError, "profiler already closed");
1026 else {
1027 if (pack_add_info(self, key, value) == 0) {
1028 result = Py_None;
1029 Py_INCREF(result);
1030 }
1031 }
1032 }
1033 return result;
1034 }
1035
1036 PyDoc_STRVAR(close__doc__,
1037 "close()\n"
1038 "Shut down this profiler and close the log files, even if its active.");
1039
1040 static PyObject *
1041 profiler_close(ProfilerObject *self)
1042 {
1043 do_stop(self);
1044 if (self->logfp != NULL) {
1045 fclose(self->logfp);
1046 self->logfp = NULL;
1047 }
1048 Py_INCREF(Py_None);
1049 return Py_None;
1050 }
1051
1052 #define fileno__doc__ logreader_fileno__doc__
1053
1054 static PyObject *
1055 profiler_fileno(ProfilerObject *self)
1056 {
1057 if (self->logfp == NULL) {
1058 PyErr_SetString(PyExc_ValueError,
1059 "profiler's file object already closed");
1060 return NULL;
1061 }
1062 return PyInt_FromLong(fileno(self->logfp));
1063 }
1064
1065 PyDoc_STRVAR(runcall__doc__,
1066 "runcall(callable[, args[, kw]]) -> callable()\n"
1067 "Profile a specific function call, returning the result of that call.");
1068
1069 static PyObject *
1070 profiler_runcall(ProfilerObject *self, PyObject *args)
1071 {
1072 PyObject *result = NULL;
1073 PyObject *callargs = NULL;
1074 PyObject *callkw = NULL;
1075 PyObject *callable;
1076
1077 if (PyArg_UnpackTuple(args, "runcall", 1, 3,
1078 &callable, &callargs, &callkw)) {
1079 if (is_available(self)) {
1080 do_start(self);
1081 result = PyEval_CallObjectWithKeywords(callable, callargs, callkw);
1082 do_stop(self);
1083 }
1084 }
1085 return result;
1086 }
1087
1088 PyDoc_STRVAR(runcode__doc__,
1089 "runcode(code, globals[, locals])\n"
1090 "Execute a code object while collecting profile data. If locals is\n"
1091 "omitted, globals is used for the locals as well.");
1092
1093 static PyObject *
1094 profiler_runcode(ProfilerObject *self, PyObject *args)
1095 {
1096 PyObject *result = NULL;
1097 PyCodeObject *code;
1098 PyObject *globals;
1099 PyObject *locals = NULL;
1100
1101 if (PyArg_ParseTuple(args, "O!O!|O:runcode",
1102 &PyCode_Type, &code,
1103 &PyDict_Type, &globals,
1104 &locals)) {
1105 if (is_available(self)) {
1106 if (locals == NULL || locals == Py_None)
1107 locals = globals;
1108 else if (!PyDict_Check(locals)) {
1109 PyErr_SetString(PyExc_TypeError,
1110 "locals must be a dictionary or None");
1111 return NULL;
1112 }
1113 do_start(self);
1114 result = PyEval_EvalCode(code, globals, locals);
1115 do_stop(self);
1116 #if 0
1117 if (!PyErr_Occurred()) {
1118 result = Py_None;
1119 Py_INCREF(result);
1120 }
1121 #endif
1122 }
1123 }
1124 return result;
1125 }
1126
1127 PyDoc_STRVAR(start__doc__,
1128 "start()\n"
1129 "Install this profiler for the current thread.");
1130
1131 static PyObject *
1132 profiler_start(ProfilerObject *self, PyObject *args)
1133 {
1134 PyObject *result = NULL;
1135
1136 if (is_available(self)) {
1137 do_start(self);
1138 result = Py_None;
1139 Py_INCREF(result);
1140 }
1141 return result;
1142 }
1143
1144 PyDoc_STRVAR(stop__doc__,
1145 "stop()\n"
1146 "Remove this profiler from the current thread.");
1147
1148 static PyObject *
1149 profiler_stop(ProfilerObject *self, PyObject *args)
1150 {
1151 PyObject *result = NULL;
1152
1153 if (!self->active)
1154 PyErr_SetString(ProfilerError, "profiler not active");
1155 else {
1156 do_stop(self);
1157 result = Py_None;
1158 Py_INCREF(result);
1159 }
1160 return result;
1161 }
1162
1163
1164 /* Python API support. */
1165
1166 static void
1167 profiler_dealloc(ProfilerObject *self)
1168 {
1169 do_stop(self);
1170 if (self->logfp != NULL)
1171 fclose(self->logfp);
1172 Py_XDECREF(self->filemap);
1173 Py_XDECREF(self->logfilename);
1174 PyObject_Del((PyObject *)self);
1175 }
1176
1177 static PyMethodDef profiler_methods[] = {
1178 {"addinfo", (PyCFunction)profiler_addinfo, METH_VARARGS, addinfo__doc__},
1179 {"close", (PyCFunction)profiler_close, METH_NOARGS, close__doc__},
1180 {"fileno", (PyCFunction)profiler_fileno, METH_NOARGS, fileno__doc__},
1181 {"runcall", (PyCFunction)profiler_runcall, METH_VARARGS, runcall__doc__},
1182 {"runcode", (PyCFunction)profiler_runcode, METH_VARARGS, runcode__doc__},
1183 {"start", (PyCFunction)profiler_start, METH_NOARGS, start__doc__},
1184 {"stop", (PyCFunction)profiler_stop, METH_NOARGS, stop__doc__},
1185 {NULL, NULL}
1186 };
1187
1188 static PyMemberDef profiler_members[] = {
1189 {"frametimings", T_LONG, offsetof(ProfilerObject, linetimings), READONLY},
1190 {"lineevents", T_LONG, offsetof(ProfilerObject, lineevents), READONLY},
1191 {"linetimings", T_LONG, offsetof(ProfilerObject, linetimings), READONLY},
1192 {NULL}
1193 };
1194
1195 static PyObject *
1196 profiler_get_closed(ProfilerObject *self, void *closure)
1197 {
1198 PyObject *result = (self->logfp == NULL) ? Py_True : Py_False;
1199 Py_INCREF(result);
1200 return result;
1201 }
1202
1203 static PyGetSetDef profiler_getsets[] = {
1204 {"closed", (getter)profiler_get_closed, NULL,
1205 PyDoc_STR("True if the profiler's output file has already been closed.")},
1206 {NULL}
1207 };
1208
1209
1210 PyDoc_STRVAR(profiler_object__doc__,
1211 "High-performance profiler object.\n"
1212 "\n"
1213 "Methods:\n"
1214 "\n"
1215 "close(): Stop the profiler and close the log files.\n"
1216 "fileno(): Returns the file descriptor of the log file.\n"
1217 "runcall(): Run a single function call with profiling enabled.\n"
1218 "runcode(): Execute a code object with profiling enabled.\n"
1219 "start(): Install the profiler and return.\n"
1220 "stop(): Remove the profiler.\n"
1221 "\n"
1222 "Attributes (read-only):\n"
1223 "\n"
1224 "closed: True if the profiler has already been closed.\n"
1225 "frametimings: True if ENTER/EXIT events collect timing information.\n"
1226 "lineevents: True if line events are reported to the profiler.\n"
1227 "linetimings: True if line events collect timing information.");
1228
1229 static PyTypeObject ProfilerType = {
1230 PyVarObject_HEAD_INIT(NULL, 0)
1231 "_hotshot.ProfilerType", /* tp_name */
1232 (int) sizeof(ProfilerObject), /* tp_basicsize */
1233 0, /* tp_itemsize */
1234 (destructor)profiler_dealloc, /* tp_dealloc */
1235 0, /* tp_print */
1236 0, /* tp_getattr */
1237 0, /* tp_setattr */
1238 0, /* tp_compare */
1239 0, /* tp_repr */
1240 0, /* tp_as_number */
1241 0, /* tp_as_sequence */
1242 0, /* tp_as_mapping */
1243 0, /* tp_hash */
1244 0, /* tp_call */
1245 0, /* tp_str */
1246 PyObject_GenericGetAttr, /* tp_getattro */
1247 0, /* tp_setattro */
1248 0, /* tp_as_buffer */
1249 Py_TPFLAGS_DEFAULT, /* tp_flags */
1250 profiler_object__doc__, /* tp_doc */
1251 0, /* tp_traverse */
1252 0, /* tp_clear */
1253 0, /* tp_richcompare */
1254 0, /* tp_weaklistoffset */
1255 0, /* tp_iter */
1256 0, /* tp_iternext */
1257 profiler_methods, /* tp_methods */
1258 profiler_members, /* tp_members */
1259 profiler_getsets, /* tp_getset */
1260 0, /* tp_base */
1261 0, /* tp_dict */
1262 0, /* tp_descr_get */
1263 0, /* tp_descr_set */
1264 };
1265
1266
1267 static PyMethodDef logreader_methods[] = {
1268 {"close", (PyCFunction)logreader_close, METH_NOARGS,
1269 logreader_close__doc__},
1270 {"fileno", (PyCFunction)logreader_fileno, METH_NOARGS,
1271 logreader_fileno__doc__},
1272 {NULL, NULL}
1273 };
1274
1275 static PyMemberDef logreader_members[] = {
1276 {"info", T_OBJECT, offsetof(LogReaderObject, info), RO,
1277 PyDoc_STR("Dictionary mapping informational keys to lists of values.")},
1278 {NULL}
1279 };
1280
1281
1282 PyDoc_STRVAR(logreader__doc__,
1283 "logreader(filename) --> log-iterator\n\
1284 Create a log-reader for the timing information file.");
1285
1286 static PySequenceMethods logreader_as_sequence = {
1287 0, /* sq_length */
1288 0, /* sq_concat */
1289 0, /* sq_repeat */
1290 (ssizeargfunc)logreader_sq_item, /* sq_item */
1291 0, /* sq_slice */
1292 0, /* sq_ass_item */
1293 0, /* sq_ass_slice */
1294 0, /* sq_contains */
1295 0, /* sq_inplace_concat */
1296 0, /* sq_inplace_repeat */
1297 };
1298
1299 static PyObject *
1300 logreader_get_closed(LogReaderObject *self, void *closure)
1301 {
1302 PyObject *result = (self->logfp == NULL) ? Py_True : Py_False;
1303 Py_INCREF(result);
1304 return result;
1305 }
1306
1307 static PyGetSetDef logreader_getsets[] = {
1308 {"closed", (getter)logreader_get_closed, NULL,
1309 PyDoc_STR("True if the logreader's input file has already been closed.")},
1310 {NULL}
1311 };
1312
1313 static PyTypeObject LogReaderType = {
1314 PyVarObject_HEAD_INIT(NULL, 0)
1315 "_hotshot.LogReaderType", /* tp_name */
1316 (int) sizeof(LogReaderObject), /* tp_basicsize */
1317 0, /* tp_itemsize */
1318 (destructor)logreader_dealloc, /* tp_dealloc */
1319 0, /* tp_print */
1320 0, /* tp_getattr */
1321 0, /* tp_setattr */
1322 0, /* tp_compare */
1323 0, /* tp_repr */
1324 0, /* tp_as_number */
1325 &logreader_as_sequence, /* tp_as_sequence */
1326 0, /* tp_as_mapping */
1327 0, /* tp_hash */
1328 0, /* tp_call */
1329 0, /* tp_str */
1330 PyObject_GenericGetAttr, /* tp_getattro */
1331 0, /* tp_setattro */
1332 0, /* tp_as_buffer */
1333 Py_TPFLAGS_DEFAULT, /* tp_flags */
1334 logreader__doc__, /* tp_doc */
1335 0, /* tp_traverse */
1336 0, /* tp_clear */
1337 0, /* tp_richcompare */
1338 0, /* tp_weaklistoffset */
1339 PyObject_SelfIter, /* tp_iter */
1340 (iternextfunc)logreader_tp_iternext,/* tp_iternext */
1341 logreader_methods, /* tp_methods */
1342 logreader_members, /* tp_members */
1343 logreader_getsets, /* tp_getset */
1344 0, /* tp_base */
1345 0, /* tp_dict */
1346 0, /* tp_descr_get */
1347 0, /* tp_descr_set */
1348 };
1349
1350 static PyObject *
1351 hotshot_logreader(PyObject *unused, PyObject *args)
1352 {
1353 LogReaderObject *self = NULL;
1354 char *filename;
1355 int c;
1356 int err = 0;
1357
1358 if (PyArg_ParseTuple(args, "s:logreader", &filename)) {
1359 self = PyObject_New(LogReaderObject, &LogReaderType);
1360 if (self != NULL) {
1361 self->frametimings = 1;
1362 self->linetimings = 0;
1363 self->info = NULL;
1364 self->logfp = fopen(filename, "rb");
1365 if (self->logfp == NULL) {
1366 PyErr_SetFromErrnoWithFilename(PyExc_IOError, filename);
1367 goto error;
1368 }
1369 self->info = PyDict_New();
1370 if (self->info == NULL)
1371 goto error;
1372 /* read initial info */
1373 for (;;) {
1374 if ((c = fgetc(self->logfp)) == EOF) {
1375 eof_error(self);
1376 goto error;
1377 }
1378 if (c != WHAT_ADD_INFO) {
1379 ungetc(c, self->logfp);
1380 break;
1381 }
1382 err = unpack_add_info(self);
1383 if (err) {
1384 if (err == ERR_EOF)
1385 eof_error(self);
1386 else
1387 PyErr_SetString(PyExc_RuntimeError,
1388 "unexpected error");
1389 goto error;
1390 }
1391 }
1392 }
1393 }
1394 return (PyObject *) self;
1395 error:
1396 Py_DECREF(self);
1397 return NULL;
1398 }
1399
1400
1401 /* Return a Python string that represents the version number without the
1402 * extra cruft added by revision control, even if the right options were
1403 * given to the "cvs export" command to make it not include the extra
1404 * cruft.
1405 */
1406 static char *
1407 get_version_string(void)
1408 {
1409 static char *rcsid = "$Revision$";
1410 char *rev = rcsid;
1411 char *buffer;
1412 int i = 0;
1413
1414 while (*rev && !isdigit(Py_CHARMASK(*rev)))
1415 ++rev;
1416 while (rev[i] != ' ' && rev[i] != '\0')
1417 ++i;
1418 buffer = (char *)malloc(i + 1);
1419 if (buffer != NULL) {
1420 memmove(buffer, rev, i);
1421 buffer[i] = '\0';
1422 }
1423 return buffer;
1424 }
1425
1426 /* Write out a RFC 822-style header with various useful bits of
1427 * information to make the output easier to manage.
1428 */
1429 static int
1430 write_header(ProfilerObject *self)
1431 {
1432 char *buffer;
1433 char cwdbuffer[PATH_MAX];
1434 PyObject *temp;
1435 Py_ssize_t i, len;
1436
1437 buffer = get_version_string();
1438 if (buffer == NULL) {
1439 PyErr_NoMemory();
1440 return -1;
1441 }
1442 pack_add_info(self, "hotshot-version", buffer);
1443 pack_add_info(self, "requested-frame-timings",
1444 (self->frametimings ? "yes" : "no"));
1445 pack_add_info(self, "requested-line-events",
1446 (self->lineevents ? "yes" : "no"));
1447 pack_add_info(self, "requested-line-timings",
1448 (self->linetimings ? "yes" : "no"));
1449 pack_add_info(self, "platform", Py_GetPlatform());
1450 pack_add_info(self, "executable", Py_GetProgramFullPath());
1451 free(buffer);
1452 buffer = (char *) Py_GetVersion();
1453 if (buffer == NULL)
1454 PyErr_Clear();
1455 else
1456 pack_add_info(self, "executable-version", buffer);
1457
1458 #ifdef MS_WINDOWS
1459 PyOS_snprintf(cwdbuffer, sizeof(cwdbuffer), "%I64d", frequency.QuadPart);
1460 pack_add_info(self, "reported-performance-frequency", cwdbuffer);
1461 #else
1462 PyOS_snprintf(cwdbuffer, sizeof(cwdbuffer), "%lu", rusage_diff);
1463 pack_add_info(self, "observed-interval-getrusage", cwdbuffer);
1464 PyOS_snprintf(cwdbuffer, sizeof(cwdbuffer), "%lu", timeofday_diff);
1465 pack_add_info(self, "observed-interval-gettimeofday", cwdbuffer);
1466 #endif
1467
1468 pack_add_info(self, "current-directory",
1469 getcwd(cwdbuffer, sizeof cwdbuffer));
1470
1471 temp = PySys_GetObject("path");
1472 if (temp == NULL || !PyList_Check(temp)) {
1473 PyErr_SetString(PyExc_RuntimeError, "sys.path must be a list");
1474 return -1;
1475 }
1476 len = PyList_GET_SIZE(temp);
1477 for (i = 0; i < len; ++i) {
1478 PyObject *item = PyList_GET_ITEM(temp, i);
1479 buffer = PyString_AsString(item);
1480 if (buffer == NULL) {
1481 pack_add_info(self, "sys-path-entry", "<non-string-path-entry>");
1482 PyErr_Clear();
1483 }
1484 else {
1485 pack_add_info(self, "sys-path-entry", buffer);
1486 }
1487 }
1488 pack_frame_times(self);
1489 pack_line_times(self);
1490
1491 return 0;
1492 }
1493
1494 PyDoc_STRVAR(profiler__doc__,
1495 "profiler(logfilename[, lineevents[, linetimes]]) -> profiler\n\
1496 Create a new profiler object.");
1497
1498 static PyObject *
1499 hotshot_profiler(PyObject *unused, PyObject *args)
1500 {
1501 char *logfilename;
1502 ProfilerObject *self = NULL;
1503 int lineevents = 0;
1504 int linetimings = 1;
1505
1506 if (PyArg_ParseTuple(args, "s|ii:profiler", &logfilename,
1507 &lineevents, &linetimings)) {
1508 self = PyObject_New(ProfilerObject, &ProfilerType);
1509 if (self == NULL)
1510 return NULL;
1511 self->frametimings = 1;
1512 self->lineevents = lineevents ? 1 : 0;
1513 self->linetimings = (lineevents && linetimings) ? 1 : 0;
1514 self->index = 0;
1515 self->active = 0;
1516 self->next_fileno = 0;
1517 self->logfp = NULL;
1518 self->logfilename = PyTuple_GET_ITEM(args, 0);
1519 Py_INCREF(self->logfilename);
1520 self->filemap = PyDict_New();
1521 if (self->filemap == NULL) {
1522 Py_DECREF(self);
1523 return NULL;
1524 }
1525 self->logfp = fopen(logfilename, "wb");
1526 if (self->logfp == NULL) {
1527 Py_DECREF(self);
1528 PyErr_SetFromErrnoWithFilename(PyExc_IOError, logfilename);
1529 return NULL;
1530 }
1531 if (timeofday_diff == 0) {
1532 /* Run this several times since sometimes the first
1533 * doesn't give the lowest values, and we're really trying
1534 * to determine the lowest.
1535 */
1536 calibrate();
1537 calibrate();
1538 calibrate();
1539 }
1540 if (write_header(self)) {
1541 /* some error occurred, exception has been set */
1542 Py_DECREF(self);
1543 self = NULL;
1544 }
1545 }
1546 return (PyObject *) self;
1547 }
1548
1549 PyDoc_STRVAR(coverage__doc__,
1550 "coverage(logfilename) -> profiler\n\
1551 Returns a profiler that doesn't collect any timing information, which is\n\
1552 useful in building a coverage analysis tool.");
1553
1554 static PyObject *
1555 hotshot_coverage(PyObject *unused, PyObject *args)
1556 {
1557 char *logfilename;
1558 PyObject *result = NULL;
1559
1560 if (PyArg_ParseTuple(args, "s:coverage", &logfilename)) {
1561 result = hotshot_profiler(unused, args);
1562 if (result != NULL) {
1563 ProfilerObject *self = (ProfilerObject *) result;
1564 self->frametimings = 0;
1565 self->linetimings = 0;
1566 self->lineevents = 1;
1567 }
1568 }
1569 return result;
1570 }
1571
1572 PyDoc_VAR(resolution__doc__) =
1573 #ifdef MS_WINDOWS
1574 PyDoc_STR(
1575 "resolution() -> (performance-counter-ticks, update-frequency)\n"
1576 "Return the resolution of the timer provided by the QueryPerformanceCounter()\n"
1577 "function. The first value is the smallest observed change, and the second\n"
1578 "is the result of QueryPerformanceFrequency()."
1579 )
1580 #else
1581 PyDoc_STR(
1582 "resolution() -> (gettimeofday-usecs, getrusage-usecs)\n"
1583 "Return the resolution of the timers provided by the gettimeofday() and\n"
1584 "getrusage() system calls, or -1 if the call is not supported."
1585 )
1586 #endif
1587 ;
1588
1589 static PyObject *
1590 hotshot_resolution(PyObject *self, PyObject *unused)
1591 {
1592 if (timeofday_diff == 0) {
1593 calibrate();
1594 calibrate();
1595 calibrate();
1596 }
1597 #ifdef MS_WINDOWS
1598 return Py_BuildValue("ii", timeofday_diff, frequency.LowPart);
1599 #else
1600 return Py_BuildValue("ii", timeofday_diff, rusage_diff);
1601 #endif
1602 }
1603
1604
1605 static PyMethodDef functions[] = {
1606 {"coverage", hotshot_coverage, METH_VARARGS, coverage__doc__},
1607 {"profiler", hotshot_profiler, METH_VARARGS, profiler__doc__},
1608 {"logreader", hotshot_logreader, METH_VARARGS, logreader__doc__},
1609 {"resolution", hotshot_resolution, METH_NOARGS, resolution__doc__},
1610 {NULL, NULL}
1611 };
1612
1613
1614 void
1615 init_hotshot(void)
1616 {
1617 PyObject *module;
1618
1619 Py_TYPE(&LogReaderType) = &PyType_Type;
1620 Py_TYPE(&ProfilerType) = &PyType_Type;
1621 module = Py_InitModule("_hotshot", functions);
1622 if (module != NULL) {
1623 char *s = get_version_string();
1624
1625 PyModule_AddStringConstant(module, "__version__", s);
1626 free(s);
1627 Py_INCREF(&LogReaderType);
1628 PyModule_AddObject(module, "LogReaderType",
1629 (PyObject *)&LogReaderType);
1630 Py_INCREF(&ProfilerType);
1631 PyModule_AddObject(module, "ProfilerType",
1632 (PyObject *)&ProfilerType);
1633
1634 if (ProfilerError == NULL)
1635 ProfilerError = PyErr_NewException("hotshot.ProfilerError",
1636 NULL, NULL);
1637 if (ProfilerError != NULL) {
1638 Py_INCREF(ProfilerError);
1639 PyModule_AddObject(module, "ProfilerError", ProfilerError);
1640 }
1641 PyModule_AddIntConstant(module, "WHAT_ENTER", WHAT_ENTER);
1642 PyModule_AddIntConstant(module, "WHAT_EXIT", WHAT_EXIT);
1643 PyModule_AddIntConstant(module, "WHAT_LINENO", WHAT_LINENO);
1644 PyModule_AddIntConstant(module, "WHAT_OTHER", WHAT_OTHER);
1645 PyModule_AddIntConstant(module, "WHAT_ADD_INFO", WHAT_ADD_INFO);
1646 PyModule_AddIntConstant(module, "WHAT_DEFINE_FILE", WHAT_DEFINE_FILE);
1647 PyModule_AddIntConstant(module, "WHAT_DEFINE_FUNC", WHAT_DEFINE_FUNC);
1648 PyModule_AddIntConstant(module, "WHAT_LINE_TIMES", WHAT_LINE_TIMES);
1649 }
1650 }