blob: 3ad0a9ef36937a3ad688d56d61e74f9fe3304328 [file] [log] [blame]
Fred Drake8c081a12001-10-12 20:57:55 +00001/*
2 * This is the High Performance Python Profiler portion of HotShot.
3 */
4
Tim Peters885d4572001-11-28 20:27:42 +00005#include "Python.h"
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00006#include "code.h"
Tim Peters885d4572001-11-28 20:27:42 +00007#include "eval.h"
8#include "frameobject.h"
9#include "structmember.h"
Fred Drake8c081a12001-10-12 20:57:55 +000010
Fred Drake8c081a12001-10-12 20:57:55 +000011/*
12 * Which timer to use should be made more configurable, but that should not
Tim Petersfeab23f2001-10-13 00:11:10 +000013 * be difficult. This will do for now.
Fred Drake8c081a12001-10-12 20:57:55 +000014 */
Martin v. Löwis6238d2b2002-06-30 15:26:10 +000015#ifdef MS_WINDOWS
Fred Drake8c081a12001-10-12 20:57:55 +000016#include <windows.h>
Tim Peters1566a172001-10-12 22:08:39 +000017#include <direct.h> /* for getcwd() */
Tim Peters7d99ff22001-10-13 07:37:52 +000018typedef __int64 hs_time;
19#define GETTIMEOFDAY(P_HS_TIME) \
20 { LARGE_INTEGER _temp; \
21 QueryPerformanceCounter(&_temp); \
22 *(P_HS_TIME) = _temp.QuadPart; }
23
Tim Petersfeab23f2001-10-13 00:11:10 +000024
Fred Drake8c081a12001-10-12 20:57:55 +000025#else
26#ifndef HAVE_GETTIMEOFDAY
27#error "This module requires gettimeofday() on non-Windows platforms!"
28#endif
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000029#if (defined(PYOS_OS2) && defined(PYCC_GCC)) || defined(__QNX__)
Jack Jansen963659a2001-10-23 22:26:16 +000030#include <sys/time.h>
31#else
Fred Drake8c081a12001-10-12 20:57:55 +000032#include <sys/resource.h>
33#include <sys/times.h>
Jack Jansen963659a2001-10-23 22:26:16 +000034#endif
Fred Drake8c081a12001-10-12 20:57:55 +000035typedef struct timeval hs_time;
36#endif
37
38#if !defined(__cplusplus) && !defined(inline)
39#ifdef __GNUC__
40#define inline __inline
41#endif
42#endif
43
44#ifndef inline
45#define inline
46#endif
47
48#define BUFFERSIZE 10240
49
Andrew MacIntyre7bf68332002-03-03 02:59:16 +000050#if defined(PYOS_OS2) && defined(PYCC_GCC)
51#define PATH_MAX 260
52#endif
53
Martin v. Löwis8eb92a02002-09-19 08:03:21 +000054#if defined(__sgi) && _COMPILER_VERSION>700 && !defined(PATH_MAX)
55/* fix PATH_MAX not being defined with MIPSPro 7.x
56 if mode is ANSI C (default) */
57#define PATH_MAX 1024
58#endif
59
Tim Peters1566a172001-10-12 22:08:39 +000060#ifndef PATH_MAX
61# ifdef MAX_PATH
62# define PATH_MAX MAX_PATH
Martin v. Löwis21ee4092002-09-30 16:19:48 +000063# elif defined (_POSIX_PATH_MAX)
64# define PATH_MAX _POSIX_PATH_MAX
Tim Peters1566a172001-10-12 22:08:39 +000065# else
66# error "Need a defn. for PATH_MAX in _hotshot.c"
67# endif
68#endif
69
Fred Drake8c081a12001-10-12 20:57:55 +000070typedef struct {
71 PyObject_HEAD
72 PyObject *filemap;
73 PyObject *logfilename;
Martin v. Löwis18e16552006-02-15 17:27:45 +000074 Py_ssize_t index;
Fred Drake8c081a12001-10-12 20:57:55 +000075 unsigned char buffer[BUFFERSIZE];
76 FILE *logfp;
77 int lineevents;
78 int linetimings;
Fred Drake30d1c752001-10-15 22:11:02 +000079 int frametimings;
Fred Drake8c081a12001-10-12 20:57:55 +000080 /* size_t filled; */
81 int active;
82 int next_fileno;
Fred Drake8c081a12001-10-12 20:57:55 +000083 hs_time prev_timeofday;
84} ProfilerObject;
85
86typedef struct {
87 PyObject_HEAD
Fred Drake4c2e1af2001-10-29 20:45:57 +000088 PyObject *info;
Fred Drake8c081a12001-10-12 20:57:55 +000089 FILE *logfp;
Fred Drake8c081a12001-10-12 20:57:55 +000090 int linetimings;
Fred Drake30d1c752001-10-15 22:11:02 +000091 int frametimings;
Fred Drake8c081a12001-10-12 20:57:55 +000092} LogReaderObject;
93
94static PyObject * ProfilerError = NULL;
95
96
Martin v. Löwis6238d2b2002-06-30 15:26:10 +000097#ifndef MS_WINDOWS
Fred Drake8c081a12001-10-12 20:57:55 +000098#ifdef GETTIMEOFDAY_NO_TZ
99#define GETTIMEOFDAY(ptv) gettimeofday((ptv))
100#else
101#define GETTIMEOFDAY(ptv) gettimeofday((ptv), (struct timezone *)NULL)
102#endif
103#endif
104
105
106/* The log reader... */
107
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000108PyDoc_STRVAR(logreader_close__doc__,
Tim Petersfeab23f2001-10-13 00:11:10 +0000109"close()\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000110"Close the log file, preventing additional records from being read.");
Fred Drake8c081a12001-10-12 20:57:55 +0000111
112static PyObject *
113logreader_close(LogReaderObject *self, PyObject *args)
114{
Fred Drake666bf522002-07-18 19:11:44 +0000115 if (self->logfp != NULL) {
116 fclose(self->logfp);
117 self->logfp = NULL;
Fred Drake8c081a12001-10-12 20:57:55 +0000118 }
Fred Drake666bf522002-07-18 19:11:44 +0000119 Py_INCREF(Py_None);
120
121 return Py_None;
122}
123
124PyDoc_STRVAR(logreader_fileno__doc__,
125"fileno() -> file descriptor\n"
126"Returns the file descriptor for the log file, if open.\n"
127"Raises ValueError if the log file is closed.");
128
129static PyObject *
130logreader_fileno(LogReaderObject *self)
131{
132 if (self->logfp == NULL) {
133 PyErr_SetString(PyExc_ValueError,
134 "logreader's file object already closed");
135 return NULL;
136 }
137 return PyInt_FromLong(fileno(self->logfp));
Fred Drake8c081a12001-10-12 20:57:55 +0000138}
139
Fred Drake8c081a12001-10-12 20:57:55 +0000140
141/* Log File Format
142 * ---------------
143 *
144 * The log file consists of a sequence of variable-length records.
145 * Each record is identified with a record type identifier in two
146 * bits of the first byte. The two bits are the "least significant"
147 * bits of the byte.
148 *
149 * Low bits: Opcode: Meaning:
150 * 0x00 ENTER enter a frame
151 * 0x01 EXIT exit a frame
Michael W. Hudsondd32a912002-08-15 14:59:02 +0000152 * 0x02 LINENO execution moved onto a different line
Fred Drake8c081a12001-10-12 20:57:55 +0000153 * 0x03 OTHER more bits are needed to deecode
154 *
155 * If the type is OTHER, the record is not packed so tightly, and the
156 * remaining bits are used to disambiguate the record type. These
157 * records are not used as frequently so compaction is not an issue.
158 * Each of the first three record types has a highly tailored
159 * structure that allows it to be packed tightly.
160 *
161 * The OTHER records have the following identifiers:
162 *
163 * First byte: Opcode: Meaning:
164 * 0x13 ADD_INFO define a key/value pair
165 * 0x23 DEFINE_FILE define an int->filename mapping
166 * 0x33 LINE_TIMES indicates if LINENO events have tdeltas
Fred Drake30d1c752001-10-15 22:11:02 +0000167 * 0x43 DEFINE_FUNC define a (fileno,lineno)->funcname mapping
168 * 0x53 FRAME_TIMES indicates if ENTER/EXIT events have tdeltas
Fred Drake8c081a12001-10-12 20:57:55 +0000169 *
170 * Packed Integers
171 *
172 * "Packed integers" are non-negative integer values encoded as a
173 * sequence of bytes. Each byte is encoded such that the most
174 * significant bit is set if the next byte is also part of the
175 * integer. Each byte provides bits to the least-significant end of
176 * the result; the accumulated value must be shifted up to place the
177 * new bits into the result.
178 *
179 * "Modified packed integers" are packed integers where only a portion
180 * of the first byte is used. In the rest of the specification, these
181 * are referred to as "MPI(n,name)", where "n" is the number of bits
182 * discarded from the least-signicant positions of the byte, and
183 * "name" is a name being given to those "discarded" bits, since they
184 * are a field themselves.
185 *
186 * ENTER records:
187 *
188 * MPI(2,type) fileno -- type is 0x00
Fred Drake8c081a12001-10-12 20:57:55 +0000189 * PI lineno
Fred Drake30d1c752001-10-15 22:11:02 +0000190 * PI tdelta -- iff frame times are enabled
Fred Drake8c081a12001-10-12 20:57:55 +0000191 *
192 * EXIT records
193 *
Fred Drake30d1c752001-10-15 22:11:02 +0000194 * MPI(2,type) tdelta -- type is 0x01; tdelta will be 0
195 * if frame times are disabled
Fred Drake8c081a12001-10-12 20:57:55 +0000196 *
197 * LINENO records
198 *
199 * MPI(2,type) lineno -- type is 0x02
200 * PI tdelta -- iff LINENO includes it
201 *
202 * ADD_INFO records
203 *
Fred Drake30d1c752001-10-15 22:11:02 +0000204 * BYTE type -- always 0x13
Fred Drake8c081a12001-10-12 20:57:55 +0000205 * PI len1 -- length of first string
206 * BYTE string1[len1] -- len1 bytes of string data
207 * PI len2 -- length of second string
208 * BYTE string2[len2] -- len2 bytes of string data
209 *
210 * DEFINE_FILE records
211 *
Fred Drake30d1c752001-10-15 22:11:02 +0000212 * BYTE type -- always 0x23
Fred Drake8c081a12001-10-12 20:57:55 +0000213 * PI fileno
214 * PI len -- length of filename
215 * BYTE filename[len] -- len bytes of string data
216 *
Fred Drake30d1c752001-10-15 22:11:02 +0000217 * DEFINE_FUNC records
218 *
219 * BYTE type -- always 0x43
220 * PI fileno
221 * PI lineno
222 * PI len -- length of funcname
223 * BYTE funcname[len] -- len bytes of string data
224 *
Fred Drake8c081a12001-10-12 20:57:55 +0000225 * LINE_TIMES records
Fred Drake30d1c752001-10-15 22:11:02 +0000226 *
227 * This record can be used only before the start of ENTER/EXIT/LINENO
228 * records. If have_tdelta is true, LINENO records will include the
229 * tdelta field, otherwise it will be omitted. If this record is not
230 * given, LINENO records will not contain the tdelta field.
231 *
232 * BYTE type -- always 0x33
Fred Drake8c081a12001-10-12 20:57:55 +0000233 * BYTE have_tdelta -- 0 if LINENO does *not* have
234 * timing information
Fred Drake30d1c752001-10-15 22:11:02 +0000235 * FRAME_TIMES records
236 *
237 * This record can be used only before the start of ENTER/EXIT/LINENO
238 * records. If have_tdelta is true, ENTER and EXIT records will
239 * include the tdelta field, otherwise it will be omitted. If this
240 * record is not given, ENTER and EXIT records will contain the tdelta
241 * field.
242 *
243 * BYTE type -- always 0x53
244 * BYTE have_tdelta -- 0 if ENTER/EXIT do *not* have
245 * timing information
Fred Drake8c081a12001-10-12 20:57:55 +0000246 */
247
248#define WHAT_ENTER 0x00
249#define WHAT_EXIT 0x01
250#define WHAT_LINENO 0x02
251#define WHAT_OTHER 0x03 /* only used in decoding */
252#define WHAT_ADD_INFO 0x13
253#define WHAT_DEFINE_FILE 0x23
254#define WHAT_LINE_TIMES 0x33
Fred Drake30d1c752001-10-15 22:11:02 +0000255#define WHAT_DEFINE_FUNC 0x43
256#define WHAT_FRAME_TIMES 0x53
Fred Drake8c081a12001-10-12 20:57:55 +0000257
258#define ERR_NONE 0
259#define ERR_EOF -1
260#define ERR_EXCEPTION -2
Fred Drake4c2e1af2001-10-29 20:45:57 +0000261#define ERR_BAD_RECTYPE -3
Fred Drake8c081a12001-10-12 20:57:55 +0000262
263#define PISIZE (sizeof(int) + 1)
264#define MPISIZE (PISIZE + 1)
265
266/* Maximum size of "normal" events -- nothing that contains string data */
267#define MAXEVENTSIZE (MPISIZE + PISIZE*2)
268
269
270/* Unpack a packed integer; if "discard" is non-zero, unpack a modified
271 * packed integer with "discard" discarded bits.
272 */
273static int
274unpack_packed_int(LogReaderObject *self, int *pvalue, int discard)
275{
Neil Schemenauer8b6b4912002-05-29 18:19:14 +0000276 int c;
Fred Drake8c081a12001-10-12 20:57:55 +0000277 int accum = 0;
278 int bits = 0;
Fred Drake8c081a12001-10-12 20:57:55 +0000279 int cont;
280
281 do {
Fred Drake8c081a12001-10-12 20:57:55 +0000282 /* read byte */
Neil Schemenauer8b6b4912002-05-29 18:19:14 +0000283 if ((c = fgetc(self->logfp)) == EOF)
284 return ERR_EOF;
285 accum |= ((c & 0x7F) >> discard) << bits;
Fred Drake8c081a12001-10-12 20:57:55 +0000286 bits += (7 - discard);
Neil Schemenauer8b6b4912002-05-29 18:19:14 +0000287 cont = c & 0x80;
Fred Drake8c081a12001-10-12 20:57:55 +0000288 discard = 0;
Fred Drake8c081a12001-10-12 20:57:55 +0000289 } while (cont);
290
Fred Drake8c081a12001-10-12 20:57:55 +0000291 *pvalue = accum;
292
293 return 0;
294}
295
296/* Unpack a string, which is encoded as a packed integer giving the
297 * length of the string, followed by the string data.
298 */
299static int
300unpack_string(LogReaderObject *self, PyObject **pvalue)
301{
Neil Schemenauer8b6b4912002-05-29 18:19:14 +0000302 int i;
Fred Drake8c081a12001-10-12 20:57:55 +0000303 int len;
Neil Schemenauer8b6b4912002-05-29 18:19:14 +0000304 int err;
Guido van Rossum0b624f62002-07-20 00:38:01 +0000305 int ch;
Neil Schemenauer8b6b4912002-05-29 18:19:14 +0000306 char *buf;
307
308 if ((err = unpack_packed_int(self, &len, 0)))
309 return err;
Fred Drake8c081a12001-10-12 20:57:55 +0000310
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000311 buf = (char *)malloc(len);
Neil Schemenauer8b6b4912002-05-29 18:19:14 +0000312 for (i=0; i < len; i++) {
Guido van Rossum0b624f62002-07-20 00:38:01 +0000313 ch = fgetc(self->logfp);
314 buf[i] = ch;
315 if (ch == EOF) {
Neil Schemenauer8b6b4912002-05-29 18:19:14 +0000316 free(buf);
317 return ERR_EOF;
Fred Drake8c081a12001-10-12 20:57:55 +0000318 }
319 }
Neil Schemenauer8b6b4912002-05-29 18:19:14 +0000320 *pvalue = PyString_FromStringAndSize(buf, len);
321 free(buf);
322 if (*pvalue == NULL) {
323 return ERR_EXCEPTION;
324 }
325 return 0;
Fred Drake8c081a12001-10-12 20:57:55 +0000326}
327
328
Fred Drake4c2e1af2001-10-29 20:45:57 +0000329static int
Neil Schemenauer8b6b4912002-05-29 18:19:14 +0000330unpack_add_info(LogReaderObject *self)
Fred Drake4c2e1af2001-10-29 20:45:57 +0000331{
332 PyObject *key;
333 PyObject *value = NULL;
334 int err;
335
Fred Drake4c2e1af2001-10-29 20:45:57 +0000336 err = unpack_string(self, &key);
337 if (!err) {
338 err = unpack_string(self, &value);
339 if (err)
340 Py_DECREF(key);
341 else {
342 PyObject *list = PyDict_GetItem(self->info, key);
343 if (list == NULL) {
344 list = PyList_New(0);
345 if (list == NULL) {
346 err = ERR_EXCEPTION;
347 goto finally;
348 }
349 if (PyDict_SetItem(self->info, key, list)) {
Armin Rigoa4127692004-08-03 08:33:55 +0000350 Py_DECREF(list);
Fred Drake4c2e1af2001-10-29 20:45:57 +0000351 err = ERR_EXCEPTION;
352 goto finally;
353 }
Armin Rigoa4127692004-08-03 08:33:55 +0000354 Py_DECREF(list);
Fred Drake4c2e1af2001-10-29 20:45:57 +0000355 }
356 if (PyList_Append(list, value))
357 err = ERR_EXCEPTION;
358 }
359 }
360 finally:
361 Py_XDECREF(key);
362 Py_XDECREF(value);
363 return err;
364}
365
366
367static void
Fred Drake666bf522002-07-18 19:11:44 +0000368eof_error(LogReaderObject *self)
Fred Drake4c2e1af2001-10-29 20:45:57 +0000369{
Fred Drake666bf522002-07-18 19:11:44 +0000370 fclose(self->logfp);
371 self->logfp = NULL;
Fred Drake4c2e1af2001-10-29 20:45:57 +0000372 PyErr_SetString(PyExc_EOFError,
373 "end of file with incomplete profile record");
374}
375
Fred Drake8c081a12001-10-12 20:57:55 +0000376static PyObject *
377logreader_tp_iternext(LogReaderObject *self)
378{
Neil Schemenauer8b6b4912002-05-29 18:19:14 +0000379 int c;
380 int what;
Fred Drake8c081a12001-10-12 20:57:55 +0000381 int err = ERR_NONE;
382 int lineno = -1;
383 int fileno = -1;
384 int tdelta = -1;
385 PyObject *s1 = NULL, *s2 = NULL;
386 PyObject *result = NULL;
387#if 0
388 unsigned char b0, b1;
389#endif
390
391 if (self->logfp == NULL) {
392 PyErr_SetString(ProfilerError,
393 "cannot iterate over closed LogReader object");
394 return NULL;
395 }
Fred Drake4c2e1af2001-10-29 20:45:57 +0000396
Neil Schemenauer8b6b4912002-05-29 18:19:14 +0000397restart:
398 /* decode the record type */
Fred Drake666bf522002-07-18 19:11:44 +0000399 if ((c = fgetc(self->logfp)) == EOF) {
400 fclose(self->logfp);
401 self->logfp = NULL;
Fred Drake8c081a12001-10-12 20:57:55 +0000402 return NULL;
Fred Drake666bf522002-07-18 19:11:44 +0000403 }
Neil Schemenauer8b6b4912002-05-29 18:19:14 +0000404 what = c & WHAT_OTHER;
405 if (what == WHAT_OTHER)
406 what = c; /* need all the bits for type */
407 else
408 ungetc(c, self->logfp); /* type byte includes packed int */
Fred Drake8c081a12001-10-12 20:57:55 +0000409
Fred Drake8c081a12001-10-12 20:57:55 +0000410 switch (what) {
411 case WHAT_ENTER:
412 err = unpack_packed_int(self, &fileno, 2);
413 if (!err) {
Fred Drake30d1c752001-10-15 22:11:02 +0000414 err = unpack_packed_int(self, &lineno, 0);
415 if (self->frametimings && !err)
416 err = unpack_packed_int(self, &tdelta, 0);
Fred Drake8c081a12001-10-12 20:57:55 +0000417 }
418 break;
419 case WHAT_EXIT:
420 err = unpack_packed_int(self, &tdelta, 2);
421 break;
422 case WHAT_LINENO:
423 err = unpack_packed_int(self, &lineno, 2);
424 if (self->linetimings && !err)
425 err = unpack_packed_int(self, &tdelta, 0);
426 break;
427 case WHAT_ADD_INFO:
Neil Schemenauer8b6b4912002-05-29 18:19:14 +0000428 err = unpack_add_info(self);
Fred Drake8c081a12001-10-12 20:57:55 +0000429 break;
430 case WHAT_DEFINE_FILE:
431 err = unpack_packed_int(self, &fileno, 0);
432 if (!err) {
433 err = unpack_string(self, &s1);
434 if (!err) {
435 Py_INCREF(Py_None);
436 s2 = Py_None;
437 }
438 }
439 break;
Fred Drake30d1c752001-10-15 22:11:02 +0000440 case WHAT_DEFINE_FUNC:
441 err = unpack_packed_int(self, &fileno, 0);
442 if (!err) {
443 err = unpack_packed_int(self, &lineno, 0);
444 if (!err)
445 err = unpack_string(self, &s1);
446 }
447 break;
Fred Drake8c081a12001-10-12 20:57:55 +0000448 case WHAT_LINE_TIMES:
Neil Schemenauer8b6b4912002-05-29 18:19:14 +0000449 if ((c = fgetc(self->logfp)) == EOF)
Fred Drake8c081a12001-10-12 20:57:55 +0000450 err = ERR_EOF;
451 else {
Neil Schemenauer8b6b4912002-05-29 18:19:14 +0000452 self->linetimings = c ? 1 : 0;
453 goto restart;
454 }
Fred Drake4c2e1af2001-10-29 20:45:57 +0000455 break;
Fred Drake30d1c752001-10-15 22:11:02 +0000456 case WHAT_FRAME_TIMES:
Neil Schemenauer8b6b4912002-05-29 18:19:14 +0000457 if ((c = fgetc(self->logfp)) == EOF)
Fred Drake30d1c752001-10-15 22:11:02 +0000458 err = ERR_EOF;
459 else {
Neil Schemenauer8b6b4912002-05-29 18:19:14 +0000460 self->frametimings = c ? 1 : 0;
461 goto restart;
462 }
Fred Drake4c2e1af2001-10-29 20:45:57 +0000463 break;
Fred Drake8c081a12001-10-12 20:57:55 +0000464 default:
Fred Drake4c2e1af2001-10-29 20:45:57 +0000465 err = ERR_BAD_RECTYPE;
Fred Drake8c081a12001-10-12 20:57:55 +0000466 }
Fred Drake4c2e1af2001-10-29 20:45:57 +0000467 if (err == ERR_BAD_RECTYPE) {
468 PyErr_SetString(PyExc_ValueError,
469 "unknown record type in log file");
470 }
471 else if (err == ERR_EOF) {
Fred Drake666bf522002-07-18 19:11:44 +0000472 eof_error(self);
Fred Drake8c081a12001-10-12 20:57:55 +0000473 }
474 else if (!err) {
475 result = PyTuple_New(4);
Neal Norwitz60da3162006-03-07 04:48:24 +0000476 if (result == NULL)
477 return NULL;
Fred Drake8c081a12001-10-12 20:57:55 +0000478 PyTuple_SET_ITEM(result, 0, PyInt_FromLong(what));
479 PyTuple_SET_ITEM(result, 2, PyInt_FromLong(fileno));
Fred Drake30d1c752001-10-15 22:11:02 +0000480 if (s1 == NULL)
Fred Drake8c081a12001-10-12 20:57:55 +0000481 PyTuple_SET_ITEM(result, 1, PyInt_FromLong(tdelta));
Fred Drake30d1c752001-10-15 22:11:02 +0000482 else
Fred Drake8c081a12001-10-12 20:57:55 +0000483 PyTuple_SET_ITEM(result, 1, s1);
Fred Drake30d1c752001-10-15 22:11:02 +0000484 if (s2 == NULL)
485 PyTuple_SET_ITEM(result, 3, PyInt_FromLong(lineno));
486 else
Fred Drake8c081a12001-10-12 20:57:55 +0000487 PyTuple_SET_ITEM(result, 3, s2);
Fred Drake8c081a12001-10-12 20:57:55 +0000488 }
489 /* The only other case is err == ERR_EXCEPTION, in which case the
490 * exception is already set.
491 */
492#if 0
493 b0 = self->buffer[self->index];
494 b1 = self->buffer[self->index + 1];
495 if (b0 & 1) {
496 /* This is a line-number event. */
497 what = PyTrace_LINE;
498 lineno = ((b0 & ~1) << 7) + b1;
499 self->index += 2;
500 }
501 else {
502 what = (b0 & 0x0E) >> 1;
503 tdelta = ((b0 & 0xF0) << 4) + b1;
504 if (what == PyTrace_CALL) {
505 /* we know there's a 2-byte file ID & 2-byte line number */
506 fileno = ((self->buffer[self->index + 2] << 8)
507 + self->buffer[self->index + 3]);
508 lineno = ((self->buffer[self->index + 4] << 8)
509 + self->buffer[self->index + 5]);
510 self->index += 6;
511 }
512 else
513 self->index += 2;
514 }
515#endif
516 return result;
517}
518
519static void
520logreader_dealloc(LogReaderObject *self)
521{
522 if (self->logfp != NULL) {
523 fclose(self->logfp);
524 self->logfp = NULL;
525 }
Armin Rigoa4127692004-08-03 08:33:55 +0000526 Py_XDECREF(self->info);
Fred Drake8c081a12001-10-12 20:57:55 +0000527 PyObject_Del(self);
528}
529
530static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000531logreader_sq_item(LogReaderObject *self, Py_ssize_t index)
Fred Drake8c081a12001-10-12 20:57:55 +0000532{
533 PyObject *result = logreader_tp_iternext(self);
534 if (result == NULL && !PyErr_Occurred()) {
535 PyErr_SetString(PyExc_IndexError, "no more events in log");
536 return NULL;
537 }
538 return result;
539}
540
Fred Drake62c1e3c2001-12-04 21:40:53 +0000541static void
542do_stop(ProfilerObject *self);
Fred Drake8c081a12001-10-12 20:57:55 +0000543
544static int
545flush_data(ProfilerObject *self)
546{
547 /* Need to dump data to the log file... */
548 size_t written = fwrite(self->buffer, 1, self->index, self->logfp);
Tim Peters1566a172001-10-12 22:08:39 +0000549 if (written == (size_t)self->index)
Fred Drake8c081a12001-10-12 20:57:55 +0000550 self->index = 0;
551 else {
552 memmove(self->buffer, &self->buffer[written],
553 self->index - written);
554 self->index -= written;
555 if (written == 0) {
556 char *s = PyString_AsString(self->logfilename);
557 PyErr_SetFromErrnoWithFilename(PyExc_IOError, s);
Fred Drake62c1e3c2001-12-04 21:40:53 +0000558 do_stop(self);
Fred Drake8c081a12001-10-12 20:57:55 +0000559 return -1;
560 }
561 }
562 if (written > 0) {
563 if (fflush(self->logfp)) {
564 char *s = PyString_AsString(self->logfilename);
565 PyErr_SetFromErrnoWithFilename(PyExc_IOError, s);
Fred Drake62c1e3c2001-12-04 21:40:53 +0000566 do_stop(self);
Fred Drake8c081a12001-10-12 20:57:55 +0000567 return -1;
568 }
569 }
570 return 0;
571}
572
Fred Drake62c1e3c2001-12-04 21:40:53 +0000573static inline int
Fred Drake8c081a12001-10-12 20:57:55 +0000574pack_packed_int(ProfilerObject *self, int value)
575{
576 unsigned char partial;
577
578 do {
579 partial = value & 0x7F;
580 value >>= 7;
581 if (value)
582 partial |= 0x80;
583 self->buffer[self->index] = partial;
584 self->index++;
585 } while (value);
Fred Drake62c1e3c2001-12-04 21:40:53 +0000586 return 0;
Fred Drake8c081a12001-10-12 20:57:55 +0000587}
588
589/* Encode a modified packed integer, with a subfield of modsize bits
590 * containing the value "subfield". The value of subfield is not
591 * checked to ensure it actually fits in modsize bits.
592 */
Fred Drake62c1e3c2001-12-04 21:40:53 +0000593static inline int
Fred Drake8c081a12001-10-12 20:57:55 +0000594pack_modified_packed_int(ProfilerObject *self, int value,
595 int modsize, int subfield)
596{
597 const int maxvalues[] = {-1, 1, 3, 7, 15, 31, 63, 127};
598
599 int bits = 7 - modsize;
600 int partial = value & maxvalues[bits];
601 unsigned char b = subfield | (partial << modsize);
602
603 if (partial != value) {
604 b |= 0x80;
605 self->buffer[self->index] = b;
606 self->index++;
Fred Drake62c1e3c2001-12-04 21:40:53 +0000607 return pack_packed_int(self, value >> bits);
Fred Drake8c081a12001-10-12 20:57:55 +0000608 }
Fred Drake62c1e3c2001-12-04 21:40:53 +0000609 self->buffer[self->index] = b;
610 self->index++;
611 return 0;
Fred Drake8c081a12001-10-12 20:57:55 +0000612}
613
Fred Drake62c1e3c2001-12-04 21:40:53 +0000614static int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000615pack_string(ProfilerObject *self, const char *s, Py_ssize_t len)
Fred Drake8c081a12001-10-12 20:57:55 +0000616{
Fred Drake62c1e3c2001-12-04 21:40:53 +0000617 if (len + PISIZE + self->index >= BUFFERSIZE) {
618 if (flush_data(self) < 0)
619 return -1;
620 }
Martin v. Löwis18e16552006-02-15 17:27:45 +0000621 assert(len < INT_MAX);
622 if (pack_packed_int(self, (int)len) < 0)
Fred Drake62c1e3c2001-12-04 21:40:53 +0000623 return -1;
Fred Drake8c081a12001-10-12 20:57:55 +0000624 memcpy(self->buffer + self->index, s, len);
625 self->index += len;
Fred Drake62c1e3c2001-12-04 21:40:53 +0000626 return 0;
Fred Drake8c081a12001-10-12 20:57:55 +0000627}
628
Fred Drake62c1e3c2001-12-04 21:40:53 +0000629static int
Fred Drake8c081a12001-10-12 20:57:55 +0000630pack_add_info(ProfilerObject *self, const char *s1, const char *s2)
631{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000632 Py_ssize_t len1 = strlen(s1);
633 Py_ssize_t len2 = strlen(s2);
Fred Drake8c081a12001-10-12 20:57:55 +0000634
Fred Drake62c1e3c2001-12-04 21:40:53 +0000635 if (len1 + len2 + PISIZE*2 + 1 + self->index >= BUFFERSIZE) {
636 if (flush_data(self) < 0)
637 return -1;
638 }
Fred Drake8c081a12001-10-12 20:57:55 +0000639 self->buffer[self->index] = WHAT_ADD_INFO;
640 self->index++;
Fred Drake62c1e3c2001-12-04 21:40:53 +0000641 if (pack_string(self, s1, len1) < 0)
642 return -1;
643 return pack_string(self, s2, len2);
Fred Drake8c081a12001-10-12 20:57:55 +0000644}
645
Fred Drake62c1e3c2001-12-04 21:40:53 +0000646static int
Fred Drake8c081a12001-10-12 20:57:55 +0000647pack_define_file(ProfilerObject *self, int fileno, const char *filename)
648{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000649 Py_ssize_t len = strlen(filename);
Fred Drake8c081a12001-10-12 20:57:55 +0000650
Fred Drake62c1e3c2001-12-04 21:40:53 +0000651 if (len + PISIZE*2 + 1 + self->index >= BUFFERSIZE) {
652 if (flush_data(self) < 0)
653 return -1;
654 }
Fred Drake8c081a12001-10-12 20:57:55 +0000655 self->buffer[self->index] = WHAT_DEFINE_FILE;
656 self->index++;
Fred Drake62c1e3c2001-12-04 21:40:53 +0000657 if (pack_packed_int(self, fileno) < 0)
658 return -1;
659 return pack_string(self, filename, len);
Fred Drake30d1c752001-10-15 22:11:02 +0000660}
661
Fred Drake62c1e3c2001-12-04 21:40:53 +0000662static int
Fred Drake30d1c752001-10-15 22:11:02 +0000663pack_define_func(ProfilerObject *self, int fileno, int lineno,
664 const char *funcname)
665{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000666 Py_ssize_t len = strlen(funcname);
Fred Drake30d1c752001-10-15 22:11:02 +0000667
Fred Drake62c1e3c2001-12-04 21:40:53 +0000668 if (len + PISIZE*3 + 1 + self->index >= BUFFERSIZE) {
669 if (flush_data(self) < 0)
670 return -1;
671 }
Fred Drake30d1c752001-10-15 22:11:02 +0000672 self->buffer[self->index] = WHAT_DEFINE_FUNC;
673 self->index++;
Fred Drake62c1e3c2001-12-04 21:40:53 +0000674 if (pack_packed_int(self, fileno) < 0)
675 return -1;
676 if (pack_packed_int(self, lineno) < 0)
677 return -1;
678 return pack_string(self, funcname, len);
Fred Drake8c081a12001-10-12 20:57:55 +0000679}
680
Fred Drake62c1e3c2001-12-04 21:40:53 +0000681static int
Fred Drake8c081a12001-10-12 20:57:55 +0000682pack_line_times(ProfilerObject *self)
683{
Fred Drake62c1e3c2001-12-04 21:40:53 +0000684 if (2 + self->index >= BUFFERSIZE) {
685 if (flush_data(self) < 0)
686 return -1;
687 }
Fred Drake8c081a12001-10-12 20:57:55 +0000688 self->buffer[self->index] = WHAT_LINE_TIMES;
689 self->buffer[self->index + 1] = self->linetimings ? 1 : 0;
690 self->index += 2;
Fred Drake62c1e3c2001-12-04 21:40:53 +0000691 return 0;
Fred Drake8c081a12001-10-12 20:57:55 +0000692}
693
Fred Drake62c1e3c2001-12-04 21:40:53 +0000694static int
Fred Drake30d1c752001-10-15 22:11:02 +0000695pack_frame_times(ProfilerObject *self)
696{
Fred Drake62c1e3c2001-12-04 21:40:53 +0000697 if (2 + self->index >= BUFFERSIZE) {
698 if (flush_data(self) < 0)
699 return -1;
700 }
Fred Drake30d1c752001-10-15 22:11:02 +0000701 self->buffer[self->index] = WHAT_FRAME_TIMES;
702 self->buffer[self->index + 1] = self->frametimings ? 1 : 0;
703 self->index += 2;
Fred Drake62c1e3c2001-12-04 21:40:53 +0000704 return 0;
Fred Drake30d1c752001-10-15 22:11:02 +0000705}
706
Fred Drake62c1e3c2001-12-04 21:40:53 +0000707static inline int
Fred Drake8c081a12001-10-12 20:57:55 +0000708pack_enter(ProfilerObject *self, int fileno, int tdelta, int lineno)
709{
Fred Drake62c1e3c2001-12-04 21:40:53 +0000710 if (MPISIZE + PISIZE*2 + self->index >= BUFFERSIZE) {
711 if (flush_data(self) < 0)
712 return -1;
713 }
Fred Drake8c081a12001-10-12 20:57:55 +0000714 pack_modified_packed_int(self, fileno, 2, WHAT_ENTER);
Fred Drake8c081a12001-10-12 20:57:55 +0000715 pack_packed_int(self, lineno);
Fred Drake30d1c752001-10-15 22:11:02 +0000716 if (self->frametimings)
Fred Drake62c1e3c2001-12-04 21:40:53 +0000717 return pack_packed_int(self, tdelta);
718 else
719 return 0;
Fred Drake8c081a12001-10-12 20:57:55 +0000720}
721
Fred Drake62c1e3c2001-12-04 21:40:53 +0000722static inline int
Fred Drake8c081a12001-10-12 20:57:55 +0000723pack_exit(ProfilerObject *self, int tdelta)
724{
Fred Drake62c1e3c2001-12-04 21:40:53 +0000725 if (MPISIZE + self->index >= BUFFERSIZE) {
726 if (flush_data(self) < 0)
727 return -1;
Fred Drake30d1c752001-10-15 22:11:02 +0000728 }
Fred Drake62c1e3c2001-12-04 21:40:53 +0000729 if (self->frametimings)
730 return pack_modified_packed_int(self, tdelta, 2, WHAT_EXIT);
731 self->buffer[self->index] = WHAT_EXIT;
732 self->index++;
733 return 0;
Fred Drake8c081a12001-10-12 20:57:55 +0000734}
735
Fred Drake62c1e3c2001-12-04 21:40:53 +0000736static inline int
Fred Drake8c081a12001-10-12 20:57:55 +0000737pack_lineno(ProfilerObject *self, int lineno)
738{
Fred Drake62c1e3c2001-12-04 21:40:53 +0000739 if (MPISIZE + self->index >= BUFFERSIZE) {
740 if (flush_data(self) < 0)
741 return -1;
742 }
743 return pack_modified_packed_int(self, lineno, 2, WHAT_LINENO);
Fred Drake8c081a12001-10-12 20:57:55 +0000744}
745
Fred Drake62c1e3c2001-12-04 21:40:53 +0000746static inline int
Fred Drake8c081a12001-10-12 20:57:55 +0000747pack_lineno_tdelta(ProfilerObject *self, int lineno, int tdelta)
748{
Fred Drake62c1e3c2001-12-04 21:40:53 +0000749 if (MPISIZE + PISIZE + self->index >= BUFFERSIZE) {
750 if (flush_data(self) < 0)
751 return 0;
752 }
753 if (pack_modified_packed_int(self, lineno, 2, WHAT_LINENO) < 0)
754 return -1;
755 return pack_packed_int(self, tdelta);
Fred Drake8c081a12001-10-12 20:57:55 +0000756}
757
758static inline int
759get_fileno(ProfilerObject *self, PyCodeObject *fcode)
760{
Fred Drake30d1c752001-10-15 22:11:02 +0000761 /* This is only used for ENTER events. */
762
763 PyObject *obj;
764 PyObject *dict;
Fred Drake8c081a12001-10-12 20:57:55 +0000765 int fileno;
766
Fred Drake30d1c752001-10-15 22:11:02 +0000767 obj = PyDict_GetItem(self->filemap, fcode->co_filename);
768 if (obj == NULL) {
Fred Drake8c081a12001-10-12 20:57:55 +0000769 /* first sighting of this file */
Fred Drake30d1c752001-10-15 22:11:02 +0000770 dict = PyDict_New();
771 if (dict == NULL) {
Fred Drake8c081a12001-10-12 20:57:55 +0000772 return -1;
773 }
Fred Drake30d1c752001-10-15 22:11:02 +0000774 fileno = self->next_fileno;
775 obj = Py_BuildValue("iN", fileno, dict);
776 if (obj == NULL) {
777 return -1;
778 }
779 if (PyDict_SetItem(self->filemap, fcode->co_filename, obj)) {
780 Py_DECREF(obj);
Fred Drake8c081a12001-10-12 20:57:55 +0000781 return -1;
782 }
783 self->next_fileno++;
Fred Drake30d1c752001-10-15 22:11:02 +0000784 Py_DECREF(obj);
Fred Drake62c1e3c2001-12-04 21:40:53 +0000785 if (pack_define_file(self, fileno,
786 PyString_AS_STRING(fcode->co_filename)) < 0)
787 return -1;
Fred Drake8c081a12001-10-12 20:57:55 +0000788 }
789 else {
790 /* already know this ID */
Fred Drake30d1c752001-10-15 22:11:02 +0000791 fileno = PyInt_AS_LONG(PyTuple_GET_ITEM(obj, 0));
792 dict = PyTuple_GET_ITEM(obj, 1);
793 }
794 /* make sure we save a function name for this (fileno, lineno) */
795 obj = PyInt_FromLong(fcode->co_firstlineno);
796 if (obj == NULL) {
797 /* We just won't have it saved; too bad. */
798 PyErr_Clear();
799 }
800 else {
801 PyObject *name = PyDict_GetItem(dict, obj);
802 if (name == NULL) {
Fred Drake62c1e3c2001-12-04 21:40:53 +0000803 if (pack_define_func(self, fileno, fcode->co_firstlineno,
Armin Rigoa4127692004-08-03 08:33:55 +0000804 PyString_AS_STRING(fcode->co_name)) < 0) {
805 Py_DECREF(obj);
Fred Drake62c1e3c2001-12-04 21:40:53 +0000806 return -1;
Armin Rigoa4127692004-08-03 08:33:55 +0000807 }
808 if (PyDict_SetItem(dict, obj, fcode->co_name)) {
809 Py_DECREF(obj);
Fred Drake30d1c752001-10-15 22:11:02 +0000810 return -1;
Armin Rigoa4127692004-08-03 08:33:55 +0000811 }
Fred Drake30d1c752001-10-15 22:11:02 +0000812 }
Armin Rigoa4127692004-08-03 08:33:55 +0000813 Py_DECREF(obj);
Fred Drake8c081a12001-10-12 20:57:55 +0000814 }
815 return fileno;
816}
817
818static inline int
819get_tdelta(ProfilerObject *self)
820{
821 int tdelta;
Martin v. Löwis6238d2b2002-06-30 15:26:10 +0000822#ifdef MS_WINDOWS
Fred Drake8c081a12001-10-12 20:57:55 +0000823 hs_time tv;
Tim Peters7d99ff22001-10-13 07:37:52 +0000824 hs_time diff;
Fred Drake8c081a12001-10-12 20:57:55 +0000825
Tim Peters7d99ff22001-10-13 07:37:52 +0000826 GETTIMEOFDAY(&tv);
827 diff = tv - self->prev_timeofday;
828 tdelta = (int)diff;
Fred Drake8c081a12001-10-12 20:57:55 +0000829#else
830 struct timeval tv;
831
832 GETTIMEOFDAY(&tv);
833
Neal Norwitz7a135162004-06-13 20:45:11 +0000834 tdelta = tv.tv_usec - self->prev_timeofday.tv_usec;
835 if (tv.tv_sec != self->prev_timeofday.tv_sec)
836 tdelta += (tv.tv_sec - self->prev_timeofday.tv_sec) * 1000000;
Fred Drake8c081a12001-10-12 20:57:55 +0000837#endif
Neal Norwitz7a135162004-06-13 20:45:11 +0000838 /* time can go backwards on some multiprocessor systems or by NTP */
839 if (tdelta < 0)
840 return 0;
841
Fred Drake8c081a12001-10-12 20:57:55 +0000842 self->prev_timeofday = tv;
843 return tdelta;
844}
845
846
847/* The workhorse: the profiler callback function. */
848
849static int
Fred Drake8c081a12001-10-12 20:57:55 +0000850tracer_callback(ProfilerObject *self, PyFrameObject *frame, int what,
851 PyObject *arg)
852{
853 int fileno;
854
Fred Drake8c081a12001-10-12 20:57:55 +0000855 switch (what) {
856 case PyTrace_CALL:
857 fileno = get_fileno(self, frame->f_code);
858 if (fileno < 0)
859 return -1;
Fred Drake62c1e3c2001-12-04 21:40:53 +0000860 return pack_enter(self, fileno,
861 self->frametimings ? get_tdelta(self) : -1,
862 frame->f_code->co_firstlineno);
863
Fred Drake8c081a12001-10-12 20:57:55 +0000864 case PyTrace_RETURN:
Fred Drake62c1e3c2001-12-04 21:40:53 +0000865 return pack_exit(self, get_tdelta(self));
866
Armin Rigode5f05f2005-12-06 14:07:39 +0000867 case PyTrace_LINE: /* we only get these events if we asked for them */
Fred Drake8c081a12001-10-12 20:57:55 +0000868 if (self->linetimings)
Michael W. Hudson806d1c82002-09-11 17:09:45 +0000869 return pack_lineno_tdelta(self, frame->f_lineno,
Michael W. Hudsondd32a912002-08-15 14:59:02 +0000870 get_tdelta(self));
Fred Drake8c081a12001-10-12 20:57:55 +0000871 else
Michael W. Hudson02ff6a92002-09-11 15:36:32 +0000872 return pack_lineno(self, frame->f_lineno);
Fred Drake62c1e3c2001-12-04 21:40:53 +0000873
Fred Drake8c081a12001-10-12 20:57:55 +0000874 default:
875 /* ignore PyTrace_EXCEPTION */
876 break;
877 }
878 return 0;
879}
880
881
882/* A couple of useful helper functions. */
883
Martin v. Löwis6238d2b2002-06-30 15:26:10 +0000884#ifdef MS_WINDOWS
Tim Petersfeab23f2001-10-13 00:11:10 +0000885static LARGE_INTEGER frequency = {0, 0};
Fred Drake8c081a12001-10-12 20:57:55 +0000886#endif
887
888static unsigned long timeofday_diff = 0;
889static unsigned long rusage_diff = 0;
890
891static void
892calibrate(void)
893{
894 hs_time tv1, tv2;
895
Martin v. Löwis6238d2b2002-06-30 15:26:10 +0000896#ifdef MS_WINDOWS
Tim Peters7d99ff22001-10-13 07:37:52 +0000897 hs_time diff;
Fred Drake8c081a12001-10-12 20:57:55 +0000898 QueryPerformanceFrequency(&frequency);
899#endif
900
901 GETTIMEOFDAY(&tv1);
902 while (1) {
903 GETTIMEOFDAY(&tv2);
Martin v. Löwis6238d2b2002-06-30 15:26:10 +0000904#ifdef MS_WINDOWS
Tim Peters7d99ff22001-10-13 07:37:52 +0000905 diff = tv2 - tv1;
906 if (diff != 0) {
907 timeofday_diff = (unsigned long)diff;
Fred Drake8c081a12001-10-12 20:57:55 +0000908 break;
909 }
910#else
911 if (tv1.tv_sec != tv2.tv_sec || tv1.tv_usec != tv2.tv_usec) {
912 if (tv1.tv_sec == tv2.tv_sec)
913 timeofday_diff = tv2.tv_usec - tv1.tv_usec;
914 else
915 timeofday_diff = (1000000 - tv1.tv_usec) + tv2.tv_usec;
916 break;
917 }
918#endif
919 }
Jack Janseneddc1442003-11-20 01:44:59 +0000920#if defined(MS_WINDOWS) || defined(PYOS_OS2) || \
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000921 defined(__VMS) || defined (__QNX__)
Fred Drake8c081a12001-10-12 20:57:55 +0000922 rusage_diff = -1;
923#else
924 {
925 struct rusage ru1, ru2;
926
927 getrusage(RUSAGE_SELF, &ru1);
928 while (1) {
929 getrusage(RUSAGE_SELF, &ru2);
930 if (ru1.ru_utime.tv_sec != ru2.ru_utime.tv_sec) {
931 rusage_diff = ((1000000 - ru1.ru_utime.tv_usec)
932 + ru2.ru_utime.tv_usec);
933 break;
934 }
935 else if (ru1.ru_utime.tv_usec != ru2.ru_utime.tv_usec) {
936 rusage_diff = ru2.ru_utime.tv_usec - ru1.ru_utime.tv_usec;
937 break;
938 }
939 else if (ru1.ru_stime.tv_sec != ru2.ru_stime.tv_sec) {
940 rusage_diff = ((1000000 - ru1.ru_stime.tv_usec)
941 + ru2.ru_stime.tv_usec);
942 break;
943 }
944 else if (ru1.ru_stime.tv_usec != ru2.ru_stime.tv_usec) {
945 rusage_diff = ru2.ru_stime.tv_usec - ru1.ru_stime.tv_usec;
946 break;
947 }
948 }
949 }
950#endif
951}
952
953static void
954do_start(ProfilerObject *self)
955{
956 self->active = 1;
957 GETTIMEOFDAY(&self->prev_timeofday);
958 if (self->lineevents)
959 PyEval_SetTrace((Py_tracefunc) tracer_callback, (PyObject *)self);
960 else
Armin Rigode5f05f2005-12-06 14:07:39 +0000961 PyEval_SetProfile((Py_tracefunc) tracer_callback, (PyObject *)self);
Fred Drake8c081a12001-10-12 20:57:55 +0000962}
963
964static void
965do_stop(ProfilerObject *self)
966{
967 if (self->active) {
968 self->active = 0;
969 if (self->lineevents)
970 PyEval_SetTrace(NULL, NULL);
971 else
972 PyEval_SetProfile(NULL, NULL);
973 }
974 if (self->index > 0) {
975 /* Best effort to dump out any remaining data. */
976 flush_data(self);
977 }
978}
979
980static int
981is_available(ProfilerObject *self)
982{
983 if (self->active) {
984 PyErr_SetString(ProfilerError, "profiler already active");
985 return 0;
986 }
987 if (self->logfp == NULL) {
988 PyErr_SetString(ProfilerError, "profiler already closed");
989 return 0;
990 }
991 return 1;
992}
993
994
995/* Profiler object interface methods. */
996
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000997PyDoc_STRVAR(addinfo__doc__,
Fred Drake4c2e1af2001-10-29 20:45:57 +0000998"addinfo(key, value)\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000999"Insert an ADD_INFO record into the log.");
Fred Drake4c2e1af2001-10-29 20:45:57 +00001000
1001static PyObject *
1002profiler_addinfo(ProfilerObject *self, PyObject *args)
1003{
1004 PyObject *result = NULL;
1005 char *key, *value;
1006
1007 if (PyArg_ParseTuple(args, "ss:addinfo", &key, &value)) {
1008 if (self->logfp == NULL)
1009 PyErr_SetString(ProfilerError, "profiler already closed");
1010 else {
Fred Drake62c1e3c2001-12-04 21:40:53 +00001011 if (pack_add_info(self, key, value) == 0) {
1012 result = Py_None;
1013 Py_INCREF(result);
1014 }
Fred Drake4c2e1af2001-10-29 20:45:57 +00001015 }
1016 }
1017 return result;
1018}
1019
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001020PyDoc_STRVAR(close__doc__,
Tim Petersfeab23f2001-10-13 00:11:10 +00001021"close()\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001022"Shut down this profiler and close the log files, even if its active.");
Fred Drake8c081a12001-10-12 20:57:55 +00001023
1024static PyObject *
Fred Drake666bf522002-07-18 19:11:44 +00001025profiler_close(ProfilerObject *self)
Fred Drake8c081a12001-10-12 20:57:55 +00001026{
Fred Drake666bf522002-07-18 19:11:44 +00001027 do_stop(self);
1028 if (self->logfp != NULL) {
1029 fclose(self->logfp);
1030 self->logfp = NULL;
Fred Drake8c081a12001-10-12 20:57:55 +00001031 }
Fred Drake666bf522002-07-18 19:11:44 +00001032 Py_INCREF(Py_None);
1033 return Py_None;
1034}
1035
1036#define fileno__doc__ logreader_fileno__doc__
1037
1038static PyObject *
1039profiler_fileno(ProfilerObject *self)
1040{
1041 if (self->logfp == NULL) {
1042 PyErr_SetString(PyExc_ValueError,
1043 "profiler's file object already closed");
1044 return NULL;
1045 }
1046 return PyInt_FromLong(fileno(self->logfp));
Fred Drake8c081a12001-10-12 20:57:55 +00001047}
1048
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001049PyDoc_STRVAR(runcall__doc__,
Tim Petersfeab23f2001-10-13 00:11:10 +00001050"runcall(callable[, args[, kw]]) -> callable()\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001051"Profile a specific function call, returning the result of that call.");
Fred Drake8c081a12001-10-12 20:57:55 +00001052
1053static PyObject *
1054profiler_runcall(ProfilerObject *self, PyObject *args)
1055{
1056 PyObject *result = NULL;
1057 PyObject *callargs = NULL;
1058 PyObject *callkw = NULL;
1059 PyObject *callable;
1060
1061 if (PyArg_ParseTuple(args, "O|OO:runcall",
1062 &callable, &callargs, &callkw)) {
1063 if (is_available(self)) {
1064 do_start(self);
1065 result = PyEval_CallObjectWithKeywords(callable, callargs, callkw);
1066 do_stop(self);
1067 }
1068 }
1069 return result;
1070}
1071
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001072PyDoc_STRVAR(runcode__doc__,
Tim Petersfeab23f2001-10-13 00:11:10 +00001073"runcode(code, globals[, locals])\n"
1074"Execute a code object while collecting profile data. If locals is\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001075"omitted, globals is used for the locals as well.");
Fred Drake8c081a12001-10-12 20:57:55 +00001076
1077static PyObject *
1078profiler_runcode(ProfilerObject *self, PyObject *args)
1079{
1080 PyObject *result = NULL;
1081 PyCodeObject *code;
1082 PyObject *globals;
1083 PyObject *locals = NULL;
1084
1085 if (PyArg_ParseTuple(args, "O!O!|O:runcode",
1086 &PyCode_Type, &code,
1087 &PyDict_Type, &globals,
1088 &locals)) {
1089 if (is_available(self)) {
1090 if (locals == NULL || locals == Py_None)
1091 locals = globals;
1092 else if (!PyDict_Check(locals)) {
1093 PyErr_SetString(PyExc_TypeError,
1094 "locals must be a dictionary or None");
1095 return NULL;
1096 }
1097 do_start(self);
1098 result = PyEval_EvalCode(code, globals, locals);
1099 do_stop(self);
1100#if 0
1101 if (!PyErr_Occurred()) {
1102 result = Py_None;
1103 Py_INCREF(result);
1104 }
1105#endif
1106 }
1107 }
1108 return result;
1109}
1110
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001111PyDoc_STRVAR(start__doc__,
Tim Petersfeab23f2001-10-13 00:11:10 +00001112"start()\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001113"Install this profiler for the current thread.");
Fred Drake8c081a12001-10-12 20:57:55 +00001114
1115static PyObject *
1116profiler_start(ProfilerObject *self, PyObject *args)
1117{
1118 PyObject *result = NULL;
1119
Fred Drake666bf522002-07-18 19:11:44 +00001120 if (is_available(self)) {
1121 do_start(self);
1122 result = Py_None;
1123 Py_INCREF(result);
Fred Drake8c081a12001-10-12 20:57:55 +00001124 }
1125 return result;
1126}
1127
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001128PyDoc_STRVAR(stop__doc__,
Tim Petersfeab23f2001-10-13 00:11:10 +00001129"stop()\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001130"Remove this profiler from the current thread.");
Fred Drake8c081a12001-10-12 20:57:55 +00001131
1132static PyObject *
1133profiler_stop(ProfilerObject *self, PyObject *args)
1134{
1135 PyObject *result = NULL;
1136
Fred Drake666bf522002-07-18 19:11:44 +00001137 if (!self->active)
1138 PyErr_SetString(ProfilerError, "profiler not active");
1139 else {
1140 do_stop(self);
1141 result = Py_None;
1142 Py_INCREF(result);
Fred Drake8c081a12001-10-12 20:57:55 +00001143 }
1144 return result;
1145}
1146
1147
1148/* Python API support. */
1149
1150static void
1151profiler_dealloc(ProfilerObject *self)
1152{
1153 do_stop(self);
1154 if (self->logfp != NULL)
1155 fclose(self->logfp);
1156 Py_XDECREF(self->filemap);
1157 Py_XDECREF(self->logfilename);
1158 PyObject_Del((PyObject *)self);
1159}
1160
Fred Drake8c081a12001-10-12 20:57:55 +00001161static PyMethodDef profiler_methods[] = {
Fred Drake4c2e1af2001-10-29 20:45:57 +00001162 {"addinfo", (PyCFunction)profiler_addinfo, METH_VARARGS, addinfo__doc__},
Fred Drake666bf522002-07-18 19:11:44 +00001163 {"close", (PyCFunction)profiler_close, METH_NOARGS, close__doc__},
1164 {"fileno", (PyCFunction)profiler_fileno, METH_NOARGS, fileno__doc__},
Fred Drake8c081a12001-10-12 20:57:55 +00001165 {"runcall", (PyCFunction)profiler_runcall, METH_VARARGS, runcall__doc__},
1166 {"runcode", (PyCFunction)profiler_runcode, METH_VARARGS, runcode__doc__},
Fred Drake666bf522002-07-18 19:11:44 +00001167 {"start", (PyCFunction)profiler_start, METH_NOARGS, start__doc__},
1168 {"stop", (PyCFunction)profiler_stop, METH_NOARGS, stop__doc__},
Fred Drake8c081a12001-10-12 20:57:55 +00001169 {NULL, NULL}
1170};
1171
Guido van Rossum9cb64b92002-07-17 16:15:35 +00001172static PyMemberDef profiler_members[] = {
Fred Drake30d1c752001-10-15 22:11:02 +00001173 {"frametimings", T_LONG, offsetof(ProfilerObject, linetimings), READONLY},
1174 {"lineevents", T_LONG, offsetof(ProfilerObject, lineevents), READONLY},
1175 {"linetimings", T_LONG, offsetof(ProfilerObject, linetimings), READONLY},
Fred Drake8c081a12001-10-12 20:57:55 +00001176 {NULL}
1177};
1178
1179static PyObject *
Guido van Rossum9cb64b92002-07-17 16:15:35 +00001180profiler_get_closed(ProfilerObject *self, void *closure)
Fred Drake8c081a12001-10-12 20:57:55 +00001181{
Guido van Rossum9cb64b92002-07-17 16:15:35 +00001182 PyObject *result = (self->logfp == NULL) ? Py_True : Py_False;
1183 Py_INCREF(result);
Fred Drake8c081a12001-10-12 20:57:55 +00001184 return result;
1185}
1186
Guido van Rossum9cb64b92002-07-17 16:15:35 +00001187static PyGetSetDef profiler_getsets[] = {
Fred Draked1eb8b62002-07-17 18:54:20 +00001188 {"closed", (getter)profiler_get_closed, NULL,
Fred Drake5c3ed3d2002-07-17 19:38:05 +00001189 PyDoc_STR("True if the profiler's output file has already been closed.")},
Guido van Rossum9cb64b92002-07-17 16:15:35 +00001190 {NULL}
1191};
1192
Fred Drake8c081a12001-10-12 20:57:55 +00001193
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001194PyDoc_STRVAR(profiler_object__doc__,
Tim Petersfeab23f2001-10-13 00:11:10 +00001195"High-performance profiler object.\n"
1196"\n"
1197"Methods:\n"
1198"\n"
Fred Drake30d1c752001-10-15 22:11:02 +00001199"close(): Stop the profiler and close the log files.\n"
Fred Drake666bf522002-07-18 19:11:44 +00001200"fileno(): Returns the file descriptor of the log file.\n"
Fred Drake30d1c752001-10-15 22:11:02 +00001201"runcall(): Run a single function call with profiling enabled.\n"
1202"runcode(): Execute a code object with profiling enabled.\n"
1203"start(): Install the profiler and return.\n"
1204"stop(): Remove the profiler.\n"
Tim Petersfeab23f2001-10-13 00:11:10 +00001205"\n"
1206"Attributes (read-only):\n"
1207"\n"
Fred Drake30d1c752001-10-15 22:11:02 +00001208"closed: True if the profiler has already been closed.\n"
1209"frametimings: True if ENTER/EXIT events collect timing information.\n"
Michael W. Hudsondd32a912002-08-15 14:59:02 +00001210"lineevents: True if line events are reported to the profiler.\n"
1211"linetimings: True if line events collect timing information.");
Fred Drake8c081a12001-10-12 20:57:55 +00001212
1213static PyTypeObject ProfilerType = {
1214 PyObject_HEAD_INIT(NULL)
1215 0, /* ob_size */
Fred Drake4c2e1af2001-10-29 20:45:57 +00001216 "_hotshot.ProfilerType", /* tp_name */
Fred Drake8c081a12001-10-12 20:57:55 +00001217 (int) sizeof(ProfilerObject), /* tp_basicsize */
1218 0, /* tp_itemsize */
1219 (destructor)profiler_dealloc, /* tp_dealloc */
1220 0, /* tp_print */
Guido van Rossum9cb64b92002-07-17 16:15:35 +00001221 0, /* tp_getattr */
Fred Drake8c081a12001-10-12 20:57:55 +00001222 0, /* tp_setattr */
1223 0, /* tp_compare */
1224 0, /* tp_repr */
1225 0, /* tp_as_number */
1226 0, /* tp_as_sequence */
1227 0, /* tp_as_mapping */
1228 0, /* tp_hash */
1229 0, /* tp_call */
1230 0, /* tp_str */
Jason Tishlerfb8595d2003-01-06 12:41:26 +00001231 PyObject_GenericGetAttr, /* tp_getattro */
Fred Drake8c081a12001-10-12 20:57:55 +00001232 0, /* tp_setattro */
1233 0, /* tp_as_buffer */
Fred Drake4c2e1af2001-10-29 20:45:57 +00001234 Py_TPFLAGS_DEFAULT, /* tp_flags */
Fred Drake8c081a12001-10-12 20:57:55 +00001235 profiler_object__doc__, /* tp_doc */
Guido van Rossum9cb64b92002-07-17 16:15:35 +00001236 0, /* tp_traverse */
1237 0, /* tp_clear */
1238 0, /* tp_richcompare */
1239 0, /* tp_weaklistoffset */
1240 0, /* tp_iter */
1241 0, /* tp_iternext */
1242 profiler_methods, /* tp_methods */
1243 profiler_members, /* tp_members */
1244 profiler_getsets, /* tp_getset */
1245 0, /* tp_base */
1246 0, /* tp_dict */
1247 0, /* tp_descr_get */
1248 0, /* tp_descr_set */
Fred Drake8c081a12001-10-12 20:57:55 +00001249};
1250
1251
1252static PyMethodDef logreader_methods[] = {
Fred Drake666bf522002-07-18 19:11:44 +00001253 {"close", (PyCFunction)logreader_close, METH_NOARGS,
Fred Drake8c081a12001-10-12 20:57:55 +00001254 logreader_close__doc__},
Fred Drake666bf522002-07-18 19:11:44 +00001255 {"fileno", (PyCFunction)logreader_fileno, METH_NOARGS,
1256 logreader_fileno__doc__},
Fred Drake8c081a12001-10-12 20:57:55 +00001257 {NULL, NULL}
1258};
1259
Guido van Rossum9cb64b92002-07-17 16:15:35 +00001260static PyMemberDef logreader_members[] = {
Fred Drake5c3ed3d2002-07-17 19:38:05 +00001261 {"info", T_OBJECT, offsetof(LogReaderObject, info), RO,
1262 PyDoc_STR("Dictionary mapping informational keys to lists of values.")},
Guido van Rossum9cb64b92002-07-17 16:15:35 +00001263 {NULL}
1264};
Fred Drake8c081a12001-10-12 20:57:55 +00001265
1266
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001267PyDoc_STRVAR(logreader__doc__,
1268"logreader(filename) --> log-iterator\n\
1269Create a log-reader for the timing information file.");
Fred Drake8c081a12001-10-12 20:57:55 +00001270
1271static PySequenceMethods logreader_as_sequence = {
1272 0, /* sq_length */
1273 0, /* sq_concat */
1274 0, /* sq_repeat */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001275 (ssizeargfunc)logreader_sq_item, /* sq_item */
Fred Drake8c081a12001-10-12 20:57:55 +00001276 0, /* sq_slice */
1277 0, /* sq_ass_item */
1278 0, /* sq_ass_slice */
1279 0, /* sq_contains */
1280 0, /* sq_inplace_concat */
1281 0, /* sq_inplace_repeat */
1282};
1283
Fred Drake666bf522002-07-18 19:11:44 +00001284static PyObject *
1285logreader_get_closed(LogReaderObject *self, void *closure)
1286{
1287 PyObject *result = (self->logfp == NULL) ? Py_True : Py_False;
1288 Py_INCREF(result);
1289 return result;
1290}
1291
1292static PyGetSetDef logreader_getsets[] = {
1293 {"closed", (getter)logreader_get_closed, NULL,
1294 PyDoc_STR("True if the logreader's input file has already been closed.")},
1295 {NULL}
1296};
1297
Fred Drake8c081a12001-10-12 20:57:55 +00001298static PyTypeObject LogReaderType = {
1299 PyObject_HEAD_INIT(NULL)
1300 0, /* ob_size */
Fred Drake4c2e1af2001-10-29 20:45:57 +00001301 "_hotshot.LogReaderType", /* tp_name */
Fred Drake8c081a12001-10-12 20:57:55 +00001302 (int) sizeof(LogReaderObject), /* tp_basicsize */
1303 0, /* tp_itemsize */
1304 (destructor)logreader_dealloc, /* tp_dealloc */
1305 0, /* tp_print */
Guido van Rossum9cb64b92002-07-17 16:15:35 +00001306 0, /* tp_getattr */
Fred Drake8c081a12001-10-12 20:57:55 +00001307 0, /* tp_setattr */
1308 0, /* tp_compare */
1309 0, /* tp_repr */
1310 0, /* tp_as_number */
1311 &logreader_as_sequence, /* tp_as_sequence */
1312 0, /* tp_as_mapping */
1313 0, /* tp_hash */
1314 0, /* tp_call */
1315 0, /* tp_str */
Jason Tishlerfb8595d2003-01-06 12:41:26 +00001316 PyObject_GenericGetAttr, /* tp_getattro */
Fred Drake8c081a12001-10-12 20:57:55 +00001317 0, /* tp_setattro */
1318 0, /* tp_as_buffer */
Fred Drake4c2e1af2001-10-29 20:45:57 +00001319 Py_TPFLAGS_DEFAULT, /* tp_flags */
Fred Drake8c081a12001-10-12 20:57:55 +00001320 logreader__doc__, /* tp_doc */
Fred Drake8c081a12001-10-12 20:57:55 +00001321 0, /* tp_traverse */
1322 0, /* tp_clear */
1323 0, /* tp_richcompare */
1324 0, /* tp_weaklistoffset */
Raymond Hettinger1da1dbf2003-03-17 19:46:11 +00001325 PyObject_SelfIter, /* tp_iter */
Fred Drake8c081a12001-10-12 20:57:55 +00001326 (iternextfunc)logreader_tp_iternext,/* tp_iternext */
Guido van Rossum9cb64b92002-07-17 16:15:35 +00001327 logreader_methods, /* tp_methods */
1328 logreader_members, /* tp_members */
Fred Drake666bf522002-07-18 19:11:44 +00001329 logreader_getsets, /* tp_getset */
Guido van Rossum9cb64b92002-07-17 16:15:35 +00001330 0, /* tp_base */
1331 0, /* tp_dict */
1332 0, /* tp_descr_get */
1333 0, /* tp_descr_set */
Fred Drake8c081a12001-10-12 20:57:55 +00001334};
1335
1336static PyObject *
1337hotshot_logreader(PyObject *unused, PyObject *args)
1338{
1339 LogReaderObject *self = NULL;
1340 char *filename;
Neil Schemenauer8b6b4912002-05-29 18:19:14 +00001341 int c;
1342 int err = 0;
Fred Drake8c081a12001-10-12 20:57:55 +00001343
1344 if (PyArg_ParseTuple(args, "s:logreader", &filename)) {
1345 self = PyObject_New(LogReaderObject, &LogReaderType);
1346 if (self != NULL) {
Fred Drake30d1c752001-10-15 22:11:02 +00001347 self->frametimings = 1;
Fred Drake8c081a12001-10-12 20:57:55 +00001348 self->linetimings = 0;
Fred Drake4c2e1af2001-10-29 20:45:57 +00001349 self->info = NULL;
Fred Drake8c081a12001-10-12 20:57:55 +00001350 self->logfp = fopen(filename, "rb");
1351 if (self->logfp == NULL) {
1352 PyErr_SetFromErrnoWithFilename(PyExc_IOError, filename);
1353 Py_DECREF(self);
1354 self = NULL;
Fred Drake4c2e1af2001-10-29 20:45:57 +00001355 goto finally;
1356 }
1357 self->info = PyDict_New();
1358 if (self->info == NULL) {
1359 Py_DECREF(self);
1360 goto finally;
1361 }
Neil Schemenauer8b6b4912002-05-29 18:19:14 +00001362 /* read initial info */
1363 for (;;) {
1364 if ((c = fgetc(self->logfp)) == EOF) {
Fred Drake666bf522002-07-18 19:11:44 +00001365 eof_error(self);
Neil Schemenauer8b6b4912002-05-29 18:19:14 +00001366 break;
1367 }
1368 if (c != WHAT_ADD_INFO) {
1369 ungetc(c, self->logfp);
1370 break;
1371 }
1372 err = unpack_add_info(self);
Fred Drake4c2e1af2001-10-29 20:45:57 +00001373 if (err) {
1374 if (err == ERR_EOF)
Fred Drake666bf522002-07-18 19:11:44 +00001375 eof_error(self);
Fred Drake4c2e1af2001-10-29 20:45:57 +00001376 else
1377 PyErr_SetString(PyExc_RuntimeError,
1378 "unexpected error");
1379 break;
1380 }
Fred Drake8c081a12001-10-12 20:57:55 +00001381 }
1382 }
1383 }
Fred Drake4c2e1af2001-10-29 20:45:57 +00001384 finally:
Fred Drake8c081a12001-10-12 20:57:55 +00001385 return (PyObject *) self;
1386}
1387
1388
1389/* Return a Python string that represents the version number without the
1390 * extra cruft added by revision control, even if the right options were
1391 * given to the "cvs export" command to make it not include the extra
1392 * cruft.
1393 */
1394static char *
1395get_version_string(void)
1396{
1397 static char *rcsid = "$Revision$";
1398 char *rev = rcsid;
1399 char *buffer;
1400 int i = 0;
1401
Neal Norwitz30b5c5d2005-12-19 06:05:18 +00001402 while (*rev && !isdigit(Py_CHARMASK(*rev)))
Fred Drake8c081a12001-10-12 20:57:55 +00001403 ++rev;
1404 while (rev[i] != ' ' && rev[i] != '\0')
1405 ++i;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001406 buffer = (char *)malloc(i + 1);
Fred Drake8c081a12001-10-12 20:57:55 +00001407 if (buffer != NULL) {
1408 memmove(buffer, rev, i);
1409 buffer[i] = '\0';
1410 }
1411 return buffer;
1412}
1413
1414/* Write out a RFC 822-style header with various useful bits of
1415 * information to make the output easier to manage.
1416 */
1417static int
1418write_header(ProfilerObject *self)
1419{
1420 char *buffer;
1421 char cwdbuffer[PATH_MAX];
1422 PyObject *temp;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001423 Py_ssize_t i, len;
Fred Drake8c081a12001-10-12 20:57:55 +00001424
1425 buffer = get_version_string();
1426 if (buffer == NULL) {
1427 PyErr_NoMemory();
1428 return -1;
1429 }
Fred Drake4c2e1af2001-10-29 20:45:57 +00001430 pack_add_info(self, "hotshot-version", buffer);
1431 pack_add_info(self, "requested-frame-timings",
1432 (self->frametimings ? "yes" : "no"));
1433 pack_add_info(self, "requested-line-events",
Fred Drake8c081a12001-10-12 20:57:55 +00001434 (self->lineevents ? "yes" : "no"));
Fred Drake4c2e1af2001-10-29 20:45:57 +00001435 pack_add_info(self, "requested-line-timings",
1436 (self->linetimings ? "yes" : "no"));
1437 pack_add_info(self, "platform", Py_GetPlatform());
1438 pack_add_info(self, "executable", Py_GetProgramFullPath());
Fred Drakef12a68c2001-11-09 15:59:36 +00001439 free(buffer);
Fred Drake8c081a12001-10-12 20:57:55 +00001440 buffer = (char *) Py_GetVersion();
1441 if (buffer == NULL)
1442 PyErr_Clear();
1443 else
Fred Drake4c2e1af2001-10-29 20:45:57 +00001444 pack_add_info(self, "executable-version", buffer);
Fred Drake8c081a12001-10-12 20:57:55 +00001445
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00001446#ifdef MS_WINDOWS
Tim Peters885d4572001-11-28 20:27:42 +00001447 PyOS_snprintf(cwdbuffer, sizeof(cwdbuffer), "%I64d", frequency.QuadPart);
Fred Drake4c2e1af2001-10-29 20:45:57 +00001448 pack_add_info(self, "reported-performance-frequency", cwdbuffer);
Fred Drake8c081a12001-10-12 20:57:55 +00001449#else
Tim Peters885d4572001-11-28 20:27:42 +00001450 PyOS_snprintf(cwdbuffer, sizeof(cwdbuffer), "%lu", rusage_diff);
Fred Drake4c2e1af2001-10-29 20:45:57 +00001451 pack_add_info(self, "observed-interval-getrusage", cwdbuffer);
Tim Peters885d4572001-11-28 20:27:42 +00001452 PyOS_snprintf(cwdbuffer, sizeof(cwdbuffer), "%lu", timeofday_diff);
Fred Drake4c2e1af2001-10-29 20:45:57 +00001453 pack_add_info(self, "observed-interval-gettimeofday", cwdbuffer);
Fred Drake8c081a12001-10-12 20:57:55 +00001454#endif
Fred Drake8c081a12001-10-12 20:57:55 +00001455
Fred Drake4c2e1af2001-10-29 20:45:57 +00001456 pack_add_info(self, "current-directory",
Fred Drake8c081a12001-10-12 20:57:55 +00001457 getcwd(cwdbuffer, sizeof cwdbuffer));
1458
1459 temp = PySys_GetObject("path");
Neal Norwitz60da3162006-03-07 04:48:24 +00001460 if (temp == NULL || !PyList_Check(temp)) {
1461 PyErr_SetString(PyExc_RuntimeError, "sys.path must be a list");
1462 return -1;
1463 }
Fred Drake8c081a12001-10-12 20:57:55 +00001464 len = PyList_GET_SIZE(temp);
1465 for (i = 0; i < len; ++i) {
1466 PyObject *item = PyList_GET_ITEM(temp, i);
1467 buffer = PyString_AsString(item);
Fred Draked1eb8b62002-07-17 18:54:20 +00001468 if (buffer == NULL) {
1469 pack_add_info(self, "sys-path-entry", "<non-string-path-entry>");
1470 PyErr_Clear();
1471 }
1472 else {
1473 pack_add_info(self, "sys-path-entry", buffer);
1474 }
Fred Drake8c081a12001-10-12 20:57:55 +00001475 }
Fred Drake4c2e1af2001-10-29 20:45:57 +00001476 pack_frame_times(self);
1477 pack_line_times(self);
1478
Fred Drake8c081a12001-10-12 20:57:55 +00001479 return 0;
1480}
1481
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001482PyDoc_STRVAR(profiler__doc__,
1483"profiler(logfilename[, lineevents[, linetimes]]) -> profiler\n\
1484Create a new profiler object.");
Fred Drake8c081a12001-10-12 20:57:55 +00001485
1486static PyObject *
1487hotshot_profiler(PyObject *unused, PyObject *args)
1488{
1489 char *logfilename;
1490 ProfilerObject *self = NULL;
1491 int lineevents = 0;
1492 int linetimings = 1;
1493
1494 if (PyArg_ParseTuple(args, "s|ii:profiler", &logfilename,
1495 &lineevents, &linetimings)) {
1496 self = PyObject_New(ProfilerObject, &ProfilerType);
1497 if (self == NULL)
1498 return NULL;
Fred Drake30d1c752001-10-15 22:11:02 +00001499 self->frametimings = 1;
Fred Drake8c081a12001-10-12 20:57:55 +00001500 self->lineevents = lineevents ? 1 : 0;
1501 self->linetimings = (lineevents && linetimings) ? 1 : 0;
1502 self->index = 0;
1503 self->active = 0;
1504 self->next_fileno = 0;
Tim Peters1566a172001-10-12 22:08:39 +00001505 self->logfp = NULL;
Fred Drake8c081a12001-10-12 20:57:55 +00001506 self->logfilename = PyTuple_GET_ITEM(args, 0);
1507 Py_INCREF(self->logfilename);
1508 self->filemap = PyDict_New();
1509 if (self->filemap == NULL) {
1510 Py_DECREF(self);
1511 return NULL;
1512 }
1513 self->logfp = fopen(logfilename, "wb");
1514 if (self->logfp == NULL) {
1515 Py_DECREF(self);
1516 PyErr_SetFromErrnoWithFilename(PyExc_IOError, logfilename);
1517 return NULL;
1518 }
1519 if (timeofday_diff == 0) {
1520 /* Run this several times since sometimes the first
1521 * doesn't give the lowest values, and we're really trying
1522 * to determine the lowest.
1523 */
1524 calibrate();
1525 calibrate();
1526 calibrate();
1527 }
Tim Petersdf44ab72006-03-07 23:53:32 +00001528 if (write_header(self)) {
Fred Drake8c081a12001-10-12 20:57:55 +00001529 /* some error occurred, exception has been set */
Tim Petersdf44ab72006-03-07 23:53:32 +00001530 Py_DECREF(self);
Fred Drake8c081a12001-10-12 20:57:55 +00001531 self = NULL;
Tim Petersdf44ab72006-03-07 23:53:32 +00001532 }
Fred Drake8c081a12001-10-12 20:57:55 +00001533 }
1534 return (PyObject *) self;
1535}
1536
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001537PyDoc_STRVAR(coverage__doc__,
1538"coverage(logfilename) -> profiler\n\
Fred Drake30d1c752001-10-15 22:11:02 +00001539Returns a profiler that doesn't collect any timing information, which is\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001540useful in building a coverage analysis tool.");
Fred Drake30d1c752001-10-15 22:11:02 +00001541
1542static PyObject *
1543hotshot_coverage(PyObject *unused, PyObject *args)
1544{
1545 char *logfilename;
1546 PyObject *result = NULL;
1547
1548 if (PyArg_ParseTuple(args, "s:coverage", &logfilename)) {
1549 result = hotshot_profiler(unused, args);
1550 if (result != NULL) {
1551 ProfilerObject *self = (ProfilerObject *) result;
1552 self->frametimings = 0;
1553 self->linetimings = 0;
1554 self->lineevents = 1;
1555 }
1556 }
1557 return result;
1558}
1559
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001560PyDoc_VAR(resolution__doc__) =
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00001561#ifdef MS_WINDOWS
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001562PyDoc_STR(
Tim Petersfeab23f2001-10-13 00:11:10 +00001563"resolution() -> (performance-counter-ticks, update-frequency)\n"
1564"Return the resolution of the timer provided by the QueryPerformanceCounter()\n"
1565"function. The first value is the smallest observed change, and the second\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001566"is the result of QueryPerformanceFrequency()."
1567)
Fred Drake8c081a12001-10-12 20:57:55 +00001568#else
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001569PyDoc_STR(
Tim Petersfeab23f2001-10-13 00:11:10 +00001570"resolution() -> (gettimeofday-usecs, getrusage-usecs)\n"
1571"Return the resolution of the timers provided by the gettimeofday() and\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001572"getrusage() system calls, or -1 if the call is not supported."
1573)
Fred Drake8c081a12001-10-12 20:57:55 +00001574#endif
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001575;
Fred Drake8c081a12001-10-12 20:57:55 +00001576
1577static PyObject *
1578hotshot_resolution(PyObject *unused, PyObject *args)
1579{
1580 PyObject *result = NULL;
1581
1582 if (PyArg_ParseTuple(args, ":resolution")) {
1583 if (timeofday_diff == 0) {
1584 calibrate();
1585 calibrate();
1586 calibrate();
1587 }
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00001588#ifdef MS_WINDOWS
Fred Drake8c081a12001-10-12 20:57:55 +00001589 result = Py_BuildValue("ii", timeofday_diff, frequency.LowPart);
1590#else
1591 result = Py_BuildValue("ii", timeofday_diff, rusage_diff);
1592#endif
1593 }
1594 return result;
1595}
1596
1597
1598static PyMethodDef functions[] = {
Fred Drake30d1c752001-10-15 22:11:02 +00001599 {"coverage", hotshot_coverage, METH_VARARGS, coverage__doc__},
Fred Drake8c081a12001-10-12 20:57:55 +00001600 {"profiler", hotshot_profiler, METH_VARARGS, profiler__doc__},
1601 {"logreader", hotshot_logreader, METH_VARARGS, logreader__doc__},
1602 {"resolution", hotshot_resolution, METH_VARARGS, resolution__doc__},
1603 {NULL, NULL}
1604};
1605
1606
1607void
1608init_hotshot(void)
1609{
1610 PyObject *module;
1611
1612 LogReaderType.ob_type = &PyType_Type;
1613 ProfilerType.ob_type = &PyType_Type;
1614 module = Py_InitModule("_hotshot", functions);
1615 if (module != NULL) {
1616 char *s = get_version_string();
1617
1618 PyModule_AddStringConstant(module, "__version__", s);
1619 free(s);
1620 Py_INCREF(&LogReaderType);
1621 PyModule_AddObject(module, "LogReaderType",
1622 (PyObject *)&LogReaderType);
1623 Py_INCREF(&ProfilerType);
1624 PyModule_AddObject(module, "ProfilerType",
1625 (PyObject *)&ProfilerType);
1626
1627 if (ProfilerError == NULL)
1628 ProfilerError = PyErr_NewException("hotshot.ProfilerError",
1629 NULL, NULL);
1630 if (ProfilerError != NULL) {
1631 Py_INCREF(ProfilerError);
1632 PyModule_AddObject(module, "ProfilerError", ProfilerError);
1633 }
1634 PyModule_AddIntConstant(module, "WHAT_ENTER", WHAT_ENTER);
1635 PyModule_AddIntConstant(module, "WHAT_EXIT", WHAT_EXIT);
1636 PyModule_AddIntConstant(module, "WHAT_LINENO", WHAT_LINENO);
1637 PyModule_AddIntConstant(module, "WHAT_OTHER", WHAT_OTHER);
1638 PyModule_AddIntConstant(module, "WHAT_ADD_INFO", WHAT_ADD_INFO);
1639 PyModule_AddIntConstant(module, "WHAT_DEFINE_FILE", WHAT_DEFINE_FILE);
Fred Drake30d1c752001-10-15 22:11:02 +00001640 PyModule_AddIntConstant(module, "WHAT_DEFINE_FUNC", WHAT_DEFINE_FUNC);
Fred Drake8c081a12001-10-12 20:57:55 +00001641 PyModule_AddIntConstant(module, "WHAT_LINE_TIMES", WHAT_LINE_TIMES);
1642 }
1643}