blob: 6d9776f1e6580fcbe9d03298480ecaef8db78deb [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>
Martin v. Löwis0e8bd7e2006-06-10 12:23:46 +000017
18#ifdef HAVE_DIRECT_H
Tim Peters1566a172001-10-12 22:08:39 +000019#include <direct.h> /* for getcwd() */
Martin v. Löwis0e8bd7e2006-06-10 12:23:46 +000020#endif
21
Tim Peters7d99ff22001-10-13 07:37:52 +000022typedef __int64 hs_time;
23#define GETTIMEOFDAY(P_HS_TIME) \
24 { LARGE_INTEGER _temp; \
25 QueryPerformanceCounter(&_temp); \
26 *(P_HS_TIME) = _temp.QuadPart; }
27
Tim Petersfeab23f2001-10-13 00:11:10 +000028
Fred Drake8c081a12001-10-12 20:57:55 +000029#else
30#ifndef HAVE_GETTIMEOFDAY
31#error "This module requires gettimeofday() on non-Windows platforms!"
32#endif
Martin v. Löwisf24de1e2006-04-14 15:07:46 +000033#if (defined(PYOS_OS2) && defined(PYCC_GCC)) || defined(__QNX__)
Jack Jansen963659a2001-10-23 22:26:16 +000034#include <sys/time.h>
35#else
Fred Drake8c081a12001-10-12 20:57:55 +000036#include <sys/resource.h>
37#include <sys/times.h>
Jack Jansen963659a2001-10-23 22:26:16 +000038#endif
Fred Drake8c081a12001-10-12 20:57:55 +000039typedef 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
Andrew MacIntyre7bf68332002-03-03 02:59:16 +000054#if defined(PYOS_OS2) && defined(PYCC_GCC)
55#define PATH_MAX 260
56#endif
57
Martin v. Löwis8eb92a02002-09-19 08:03:21 +000058#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
Tim Peters1566a172001-10-12 22:08:39 +000064#ifndef PATH_MAX
65# ifdef MAX_PATH
66# define PATH_MAX MAX_PATH
Martin v. Löwis21ee4092002-09-30 16:19:48 +000067# elif defined (_POSIX_PATH_MAX)
68# define PATH_MAX _POSIX_PATH_MAX
Tim Peters1566a172001-10-12 22:08:39 +000069# else
70# error "Need a defn. for PATH_MAX in _hotshot.c"
71# endif
72#endif
73
Fred Drake8c081a12001-10-12 20:57:55 +000074typedef struct {
75 PyObject_HEAD
76 PyObject *filemap;
77 PyObject *logfilename;
Martin v. Löwis18e16552006-02-15 17:27:45 +000078 Py_ssize_t index;
Fred Drake8c081a12001-10-12 20:57:55 +000079 unsigned char buffer[BUFFERSIZE];
80 FILE *logfp;
81 int lineevents;
82 int linetimings;
Fred Drake30d1c752001-10-15 22:11:02 +000083 int frametimings;
Fred Drake8c081a12001-10-12 20:57:55 +000084 /* size_t filled; */
85 int active;
86 int next_fileno;
Fred Drake8c081a12001-10-12 20:57:55 +000087 hs_time prev_timeofday;
88} ProfilerObject;
89
90typedef struct {
91 PyObject_HEAD
Fred Drake4c2e1af2001-10-29 20:45:57 +000092 PyObject *info;
Fred Drake8c081a12001-10-12 20:57:55 +000093 FILE *logfp;
Fred Drake8c081a12001-10-12 20:57:55 +000094 int linetimings;
Fred Drake30d1c752001-10-15 22:11:02 +000095 int frametimings;
Fred Drake8c081a12001-10-12 20:57:55 +000096} LogReaderObject;
97
98static PyObject * ProfilerError = NULL;
99
100
Martin v. Löwis6238d2b2002-06-30 15:26:10 +0000101#ifndef MS_WINDOWS
Fred Drake8c081a12001-10-12 20:57:55 +0000102#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
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000112PyDoc_STRVAR(logreader_close__doc__,
Tim Petersfeab23f2001-10-13 00:11:10 +0000113"close()\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000114"Close the log file, preventing additional records from being read.");
Fred Drake8c081a12001-10-12 20:57:55 +0000115
116static PyObject *
117logreader_close(LogReaderObject *self, PyObject *args)
118{
Fred Drake666bf522002-07-18 19:11:44 +0000119 if (self->logfp != NULL) {
120 fclose(self->logfp);
121 self->logfp = NULL;
Fred Drake8c081a12001-10-12 20:57:55 +0000122 }
Fred Drake666bf522002-07-18 19:11:44 +0000123 Py_INCREF(Py_None);
124
125 return Py_None;
126}
127
128PyDoc_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
133static PyObject *
134logreader_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));
Fred Drake8c081a12001-10-12 20:57:55 +0000142}
143
Fred Drake8c081a12001-10-12 20:57:55 +0000144
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
Michael W. Hudsondd32a912002-08-15 14:59:02 +0000156 * 0x02 LINENO execution moved onto a different line
Fred Drake8c081a12001-10-12 20:57:55 +0000157 * 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
Fred Drake30d1c752001-10-15 22:11:02 +0000171 * 0x43 DEFINE_FUNC define a (fileno,lineno)->funcname mapping
172 * 0x53 FRAME_TIMES indicates if ENTER/EXIT events have tdeltas
Fred Drake8c081a12001-10-12 20:57:55 +0000173 *
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
Fred Drake8c081a12001-10-12 20:57:55 +0000193 * PI lineno
Fred Drake30d1c752001-10-15 22:11:02 +0000194 * PI tdelta -- iff frame times are enabled
Fred Drake8c081a12001-10-12 20:57:55 +0000195 *
196 * EXIT records
197 *
Fred Drake30d1c752001-10-15 22:11:02 +0000198 * MPI(2,type) tdelta -- type is 0x01; tdelta will be 0
199 * if frame times are disabled
Fred Drake8c081a12001-10-12 20:57:55 +0000200 *
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 *
Fred Drake30d1c752001-10-15 22:11:02 +0000208 * BYTE type -- always 0x13
Fred Drake8c081a12001-10-12 20:57:55 +0000209 * 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 *
Fred Drake30d1c752001-10-15 22:11:02 +0000216 * BYTE type -- always 0x23
Fred Drake8c081a12001-10-12 20:57:55 +0000217 * PI fileno
218 * PI len -- length of filename
219 * BYTE filename[len] -- len bytes of string data
220 *
Fred Drake30d1c752001-10-15 22:11:02 +0000221 * 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 *
Fred Drake8c081a12001-10-12 20:57:55 +0000229 * LINE_TIMES records
Fred Drake30d1c752001-10-15 22:11:02 +0000230 *
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
Fred Drake8c081a12001-10-12 20:57:55 +0000237 * BYTE have_tdelta -- 0 if LINENO does *not* have
238 * timing information
Fred Drake30d1c752001-10-15 22:11:02 +0000239 * 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
Fred Drake8c081a12001-10-12 20:57:55 +0000250 */
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
Fred Drake30d1c752001-10-15 22:11:02 +0000259#define WHAT_DEFINE_FUNC 0x43
260#define WHAT_FRAME_TIMES 0x53
Fred Drake8c081a12001-10-12 20:57:55 +0000261
262#define ERR_NONE 0
263#define ERR_EOF -1
264#define ERR_EXCEPTION -2
Fred Drake4c2e1af2001-10-29 20:45:57 +0000265#define ERR_BAD_RECTYPE -3
Fred Drake8c081a12001-10-12 20:57:55 +0000266
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 */
277static int
278unpack_packed_int(LogReaderObject *self, int *pvalue, int discard)
279{
Neil Schemenauer8b6b4912002-05-29 18:19:14 +0000280 int c;
Fred Drake8c081a12001-10-12 20:57:55 +0000281 int accum = 0;
282 int bits = 0;
Fred Drake8c081a12001-10-12 20:57:55 +0000283 int cont;
284
285 do {
Fred Drake8c081a12001-10-12 20:57:55 +0000286 /* read byte */
Neil Schemenauer8b6b4912002-05-29 18:19:14 +0000287 if ((c = fgetc(self->logfp)) == EOF)
288 return ERR_EOF;
289 accum |= ((c & 0x7F) >> discard) << bits;
Fred Drake8c081a12001-10-12 20:57:55 +0000290 bits += (7 - discard);
Neil Schemenauer8b6b4912002-05-29 18:19:14 +0000291 cont = c & 0x80;
Fred Drake8c081a12001-10-12 20:57:55 +0000292 discard = 0;
Fred Drake8c081a12001-10-12 20:57:55 +0000293 } while (cont);
294
Fred Drake8c081a12001-10-12 20:57:55 +0000295 *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 */
303static int
304unpack_string(LogReaderObject *self, PyObject **pvalue)
305{
Neil Schemenauer8b6b4912002-05-29 18:19:14 +0000306 int i;
Fred Drake8c081a12001-10-12 20:57:55 +0000307 int len;
Neil Schemenauer8b6b4912002-05-29 18:19:14 +0000308 int err;
Guido van Rossum0b624f62002-07-20 00:38:01 +0000309 int ch;
Neil Schemenauer8b6b4912002-05-29 18:19:14 +0000310 char *buf;
311
312 if ((err = unpack_packed_int(self, &len, 0)))
313 return err;
Fred Drake8c081a12001-10-12 20:57:55 +0000314
Anthony Baxter7cbc0f52006-04-13 07:19:01 +0000315 buf = (char *)malloc(len);
Neil Schemenauer8b6b4912002-05-29 18:19:14 +0000316 for (i=0; i < len; i++) {
Guido van Rossum0b624f62002-07-20 00:38:01 +0000317 ch = fgetc(self->logfp);
318 buf[i] = ch;
319 if (ch == EOF) {
Neil Schemenauer8b6b4912002-05-29 18:19:14 +0000320 free(buf);
321 return ERR_EOF;
Fred Drake8c081a12001-10-12 20:57:55 +0000322 }
323 }
Neil Schemenauer8b6b4912002-05-29 18:19:14 +0000324 *pvalue = PyString_FromStringAndSize(buf, len);
325 free(buf);
326 if (*pvalue == NULL) {
327 return ERR_EXCEPTION;
328 }
329 return 0;
Fred Drake8c081a12001-10-12 20:57:55 +0000330}
331
332
Fred Drake4c2e1af2001-10-29 20:45:57 +0000333static int
Neil Schemenauer8b6b4912002-05-29 18:19:14 +0000334unpack_add_info(LogReaderObject *self)
Fred Drake4c2e1af2001-10-29 20:45:57 +0000335{
336 PyObject *key;
337 PyObject *value = NULL;
338 int err;
339
Fred Drake4c2e1af2001-10-29 20:45:57 +0000340 err = unpack_string(self, &key);
341 if (!err) {
342 err = unpack_string(self, &value);
343 if (err)
344 Py_DECREF(key);
345 else {
346 PyObject *list = PyDict_GetItem(self->info, key);
347 if (list == NULL) {
348 list = PyList_New(0);
349 if (list == NULL) {
350 err = ERR_EXCEPTION;
351 goto finally;
352 }
353 if (PyDict_SetItem(self->info, key, list)) {
Armin Rigoa4127692004-08-03 08:33:55 +0000354 Py_DECREF(list);
Fred Drake4c2e1af2001-10-29 20:45:57 +0000355 err = ERR_EXCEPTION;
356 goto finally;
357 }
Armin Rigoa4127692004-08-03 08:33:55 +0000358 Py_DECREF(list);
Fred Drake4c2e1af2001-10-29 20:45:57 +0000359 }
360 if (PyList_Append(list, value))
361 err = ERR_EXCEPTION;
362 }
363 }
364 finally:
365 Py_XDECREF(key);
366 Py_XDECREF(value);
367 return err;
368}
369
370
371static void
Fred Drake666bf522002-07-18 19:11:44 +0000372eof_error(LogReaderObject *self)
Fred Drake4c2e1af2001-10-29 20:45:57 +0000373{
Fred Drake666bf522002-07-18 19:11:44 +0000374 fclose(self->logfp);
375 self->logfp = NULL;
Fred Drake4c2e1af2001-10-29 20:45:57 +0000376 PyErr_SetString(PyExc_EOFError,
377 "end of file with incomplete profile record");
378}
379
Fred Drake8c081a12001-10-12 20:57:55 +0000380static PyObject *
381logreader_tp_iternext(LogReaderObject *self)
382{
Neil Schemenauer8b6b4912002-05-29 18:19:14 +0000383 int c;
384 int what;
Fred Drake8c081a12001-10-12 20:57:55 +0000385 int err = ERR_NONE;
386 int lineno = -1;
387 int fileno = -1;
388 int tdelta = -1;
389 PyObject *s1 = NULL, *s2 = NULL;
390 PyObject *result = NULL;
391#if 0
392 unsigned char b0, b1;
393#endif
394
395 if (self->logfp == NULL) {
396 PyErr_SetString(ProfilerError,
397 "cannot iterate over closed LogReader object");
398 return NULL;
399 }
Fred Drake4c2e1af2001-10-29 20:45:57 +0000400
Neil Schemenauer8b6b4912002-05-29 18:19:14 +0000401restart:
402 /* decode the record type */
Fred Drake666bf522002-07-18 19:11:44 +0000403 if ((c = fgetc(self->logfp)) == EOF) {
404 fclose(self->logfp);
405 self->logfp = NULL;
Fred Drake8c081a12001-10-12 20:57:55 +0000406 return NULL;
Fred Drake666bf522002-07-18 19:11:44 +0000407 }
Neil Schemenauer8b6b4912002-05-29 18:19:14 +0000408 what = c & WHAT_OTHER;
409 if (what == WHAT_OTHER)
410 what = c; /* need all the bits for type */
411 else
412 ungetc(c, self->logfp); /* type byte includes packed int */
Fred Drake8c081a12001-10-12 20:57:55 +0000413
Fred Drake8c081a12001-10-12 20:57:55 +0000414 switch (what) {
415 case WHAT_ENTER:
416 err = unpack_packed_int(self, &fileno, 2);
417 if (!err) {
Fred Drake30d1c752001-10-15 22:11:02 +0000418 err = unpack_packed_int(self, &lineno, 0);
419 if (self->frametimings && !err)
420 err = unpack_packed_int(self, &tdelta, 0);
Fred Drake8c081a12001-10-12 20:57:55 +0000421 }
422 break;
423 case WHAT_EXIT:
424 err = unpack_packed_int(self, &tdelta, 2);
425 break;
426 case WHAT_LINENO:
427 err = unpack_packed_int(self, &lineno, 2);
428 if (self->linetimings && !err)
429 err = unpack_packed_int(self, &tdelta, 0);
430 break;
431 case WHAT_ADD_INFO:
Neil Schemenauer8b6b4912002-05-29 18:19:14 +0000432 err = unpack_add_info(self);
Fred Drake8c081a12001-10-12 20:57:55 +0000433 break;
434 case WHAT_DEFINE_FILE:
435 err = unpack_packed_int(self, &fileno, 0);
436 if (!err) {
437 err = unpack_string(self, &s1);
438 if (!err) {
439 Py_INCREF(Py_None);
440 s2 = Py_None;
441 }
442 }
443 break;
Fred Drake30d1c752001-10-15 22:11:02 +0000444 case WHAT_DEFINE_FUNC:
445 err = unpack_packed_int(self, &fileno, 0);
446 if (!err) {
447 err = unpack_packed_int(self, &lineno, 0);
448 if (!err)
449 err = unpack_string(self, &s1);
450 }
451 break;
Fred Drake8c081a12001-10-12 20:57:55 +0000452 case WHAT_LINE_TIMES:
Neil Schemenauer8b6b4912002-05-29 18:19:14 +0000453 if ((c = fgetc(self->logfp)) == EOF)
Fred Drake8c081a12001-10-12 20:57:55 +0000454 err = ERR_EOF;
455 else {
Neil Schemenauer8b6b4912002-05-29 18:19:14 +0000456 self->linetimings = c ? 1 : 0;
457 goto restart;
458 }
Fred Drake4c2e1af2001-10-29 20:45:57 +0000459 break;
Fred Drake30d1c752001-10-15 22:11:02 +0000460 case WHAT_FRAME_TIMES:
Neil Schemenauer8b6b4912002-05-29 18:19:14 +0000461 if ((c = fgetc(self->logfp)) == EOF)
Fred Drake30d1c752001-10-15 22:11:02 +0000462 err = ERR_EOF;
463 else {
Neil Schemenauer8b6b4912002-05-29 18:19:14 +0000464 self->frametimings = c ? 1 : 0;
465 goto restart;
466 }
Fred Drake4c2e1af2001-10-29 20:45:57 +0000467 break;
Fred Drake8c081a12001-10-12 20:57:55 +0000468 default:
Fred Drake4c2e1af2001-10-29 20:45:57 +0000469 err = ERR_BAD_RECTYPE;
Fred Drake8c081a12001-10-12 20:57:55 +0000470 }
Fred Drake4c2e1af2001-10-29 20:45:57 +0000471 if (err == ERR_BAD_RECTYPE) {
472 PyErr_SetString(PyExc_ValueError,
473 "unknown record type in log file");
474 }
475 else if (err == ERR_EOF) {
Fred Drake666bf522002-07-18 19:11:44 +0000476 eof_error(self);
Fred Drake8c081a12001-10-12 20:57:55 +0000477 }
478 else if (!err) {
479 result = PyTuple_New(4);
Neal Norwitz60da3162006-03-07 04:48:24 +0000480 if (result == NULL)
481 return NULL;
Fred Drake8c081a12001-10-12 20:57:55 +0000482 PyTuple_SET_ITEM(result, 0, PyInt_FromLong(what));
483 PyTuple_SET_ITEM(result, 2, PyInt_FromLong(fileno));
Fred Drake30d1c752001-10-15 22:11:02 +0000484 if (s1 == NULL)
Fred Drake8c081a12001-10-12 20:57:55 +0000485 PyTuple_SET_ITEM(result, 1, PyInt_FromLong(tdelta));
Fred Drake30d1c752001-10-15 22:11:02 +0000486 else
Fred Drake8c081a12001-10-12 20:57:55 +0000487 PyTuple_SET_ITEM(result, 1, s1);
Fred Drake30d1c752001-10-15 22:11:02 +0000488 if (s2 == NULL)
489 PyTuple_SET_ITEM(result, 3, PyInt_FromLong(lineno));
490 else
Fred Drake8c081a12001-10-12 20:57:55 +0000491 PyTuple_SET_ITEM(result, 3, s2);
Fred Drake8c081a12001-10-12 20:57:55 +0000492 }
493 /* The only other case is err == ERR_EXCEPTION, in which case the
494 * exception is already set.
495 */
496#if 0
497 b0 = self->buffer[self->index];
498 b1 = self->buffer[self->index + 1];
499 if (b0 & 1) {
500 /* This is a line-number event. */
501 what = PyTrace_LINE;
502 lineno = ((b0 & ~1) << 7) + b1;
503 self->index += 2;
504 }
505 else {
506 what = (b0 & 0x0E) >> 1;
507 tdelta = ((b0 & 0xF0) << 4) + b1;
508 if (what == PyTrace_CALL) {
509 /* we know there's a 2-byte file ID & 2-byte line number */
510 fileno = ((self->buffer[self->index + 2] << 8)
511 + self->buffer[self->index + 3]);
512 lineno = ((self->buffer[self->index + 4] << 8)
513 + self->buffer[self->index + 5]);
514 self->index += 6;
515 }
516 else
517 self->index += 2;
518 }
519#endif
520 return result;
521}
522
523static void
524logreader_dealloc(LogReaderObject *self)
525{
526 if (self->logfp != NULL) {
527 fclose(self->logfp);
528 self->logfp = NULL;
529 }
Armin Rigoa4127692004-08-03 08:33:55 +0000530 Py_XDECREF(self->info);
Fred Drake8c081a12001-10-12 20:57:55 +0000531 PyObject_Del(self);
532}
533
534static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000535logreader_sq_item(LogReaderObject *self, Py_ssize_t index)
Fred Drake8c081a12001-10-12 20:57:55 +0000536{
537 PyObject *result = logreader_tp_iternext(self);
538 if (result == NULL && !PyErr_Occurred()) {
539 PyErr_SetString(PyExc_IndexError, "no more events in log");
540 return NULL;
541 }
542 return result;
543}
544
Fred Drake62c1e3c2001-12-04 21:40:53 +0000545static void
546do_stop(ProfilerObject *self);
Fred Drake8c081a12001-10-12 20:57:55 +0000547
548static int
549flush_data(ProfilerObject *self)
550{
551 /* Need to dump data to the log file... */
552 size_t written = fwrite(self->buffer, 1, self->index, self->logfp);
Tim Peters1566a172001-10-12 22:08:39 +0000553 if (written == (size_t)self->index)
Fred Drake8c081a12001-10-12 20:57:55 +0000554 self->index = 0;
555 else {
556 memmove(self->buffer, &self->buffer[written],
557 self->index - written);
558 self->index -= written;
559 if (written == 0) {
560 char *s = PyString_AsString(self->logfilename);
561 PyErr_SetFromErrnoWithFilename(PyExc_IOError, s);
Fred Drake62c1e3c2001-12-04 21:40:53 +0000562 do_stop(self);
Fred Drake8c081a12001-10-12 20:57:55 +0000563 return -1;
564 }
565 }
566 if (written > 0) {
567 if (fflush(self->logfp)) {
568 char *s = PyString_AsString(self->logfilename);
569 PyErr_SetFromErrnoWithFilename(PyExc_IOError, s);
Fred Drake62c1e3c2001-12-04 21:40:53 +0000570 do_stop(self);
Fred Drake8c081a12001-10-12 20:57:55 +0000571 return -1;
572 }
573 }
574 return 0;
575}
576
Fred Drake62c1e3c2001-12-04 21:40:53 +0000577static inline int
Fred Drake8c081a12001-10-12 20:57:55 +0000578pack_packed_int(ProfilerObject *self, int value)
579{
580 unsigned char partial;
581
582 do {
583 partial = value & 0x7F;
584 value >>= 7;
585 if (value)
586 partial |= 0x80;
587 self->buffer[self->index] = partial;
588 self->index++;
589 } while (value);
Fred Drake62c1e3c2001-12-04 21:40:53 +0000590 return 0;
Fred Drake8c081a12001-10-12 20:57:55 +0000591}
592
593/* Encode a modified packed integer, with a subfield of modsize bits
594 * containing the value "subfield". The value of subfield is not
595 * checked to ensure it actually fits in modsize bits.
596 */
Fred Drake62c1e3c2001-12-04 21:40:53 +0000597static inline int
Fred Drake8c081a12001-10-12 20:57:55 +0000598pack_modified_packed_int(ProfilerObject *self, int value,
599 int modsize, int subfield)
600{
601 const int maxvalues[] = {-1, 1, 3, 7, 15, 31, 63, 127};
602
603 int bits = 7 - modsize;
604 int partial = value & maxvalues[bits];
605 unsigned char b = subfield | (partial << modsize);
606
607 if (partial != value) {
608 b |= 0x80;
609 self->buffer[self->index] = b;
610 self->index++;
Fred Drake62c1e3c2001-12-04 21:40:53 +0000611 return pack_packed_int(self, value >> bits);
Fred Drake8c081a12001-10-12 20:57:55 +0000612 }
Fred Drake62c1e3c2001-12-04 21:40:53 +0000613 self->buffer[self->index] = b;
614 self->index++;
615 return 0;
Fred Drake8c081a12001-10-12 20:57:55 +0000616}
617
Fred Drake62c1e3c2001-12-04 21:40:53 +0000618static int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000619pack_string(ProfilerObject *self, const char *s, Py_ssize_t len)
Fred Drake8c081a12001-10-12 20:57:55 +0000620{
Fred Drake62c1e3c2001-12-04 21:40:53 +0000621 if (len + PISIZE + self->index >= BUFFERSIZE) {
622 if (flush_data(self) < 0)
623 return -1;
624 }
Martin v. Löwis18e16552006-02-15 17:27:45 +0000625 assert(len < INT_MAX);
626 if (pack_packed_int(self, (int)len) < 0)
Fred Drake62c1e3c2001-12-04 21:40:53 +0000627 return -1;
Fred Drake8c081a12001-10-12 20:57:55 +0000628 memcpy(self->buffer + self->index, s, len);
629 self->index += len;
Fred Drake62c1e3c2001-12-04 21:40:53 +0000630 return 0;
Fred Drake8c081a12001-10-12 20:57:55 +0000631}
632
Fred Drake62c1e3c2001-12-04 21:40:53 +0000633static int
Fred Drake8c081a12001-10-12 20:57:55 +0000634pack_add_info(ProfilerObject *self, const char *s1, const char *s2)
635{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000636 Py_ssize_t len1 = strlen(s1);
637 Py_ssize_t len2 = strlen(s2);
Fred Drake8c081a12001-10-12 20:57:55 +0000638
Fred Drake62c1e3c2001-12-04 21:40:53 +0000639 if (len1 + len2 + PISIZE*2 + 1 + self->index >= BUFFERSIZE) {
640 if (flush_data(self) < 0)
641 return -1;
642 }
Fred Drake8c081a12001-10-12 20:57:55 +0000643 self->buffer[self->index] = WHAT_ADD_INFO;
644 self->index++;
Fred Drake62c1e3c2001-12-04 21:40:53 +0000645 if (pack_string(self, s1, len1) < 0)
646 return -1;
647 return pack_string(self, s2, len2);
Fred Drake8c081a12001-10-12 20:57:55 +0000648}
649
Fred Drake62c1e3c2001-12-04 21:40:53 +0000650static int
Fred Drake8c081a12001-10-12 20:57:55 +0000651pack_define_file(ProfilerObject *self, int fileno, const char *filename)
652{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000653 Py_ssize_t len = strlen(filename);
Fred Drake8c081a12001-10-12 20:57:55 +0000654
Fred Drake62c1e3c2001-12-04 21:40:53 +0000655 if (len + PISIZE*2 + 1 + self->index >= BUFFERSIZE) {
656 if (flush_data(self) < 0)
657 return -1;
658 }
Fred Drake8c081a12001-10-12 20:57:55 +0000659 self->buffer[self->index] = WHAT_DEFINE_FILE;
660 self->index++;
Fred Drake62c1e3c2001-12-04 21:40:53 +0000661 if (pack_packed_int(self, fileno) < 0)
662 return -1;
663 return pack_string(self, filename, len);
Fred Drake30d1c752001-10-15 22:11:02 +0000664}
665
Fred Drake62c1e3c2001-12-04 21:40:53 +0000666static int
Fred Drake30d1c752001-10-15 22:11:02 +0000667pack_define_func(ProfilerObject *self, int fileno, int lineno,
668 const char *funcname)
669{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000670 Py_ssize_t len = strlen(funcname);
Fred Drake30d1c752001-10-15 22:11:02 +0000671
Fred Drake62c1e3c2001-12-04 21:40:53 +0000672 if (len + PISIZE*3 + 1 + self->index >= BUFFERSIZE) {
673 if (flush_data(self) < 0)
674 return -1;
675 }
Fred Drake30d1c752001-10-15 22:11:02 +0000676 self->buffer[self->index] = WHAT_DEFINE_FUNC;
677 self->index++;
Fred Drake62c1e3c2001-12-04 21:40:53 +0000678 if (pack_packed_int(self, fileno) < 0)
679 return -1;
680 if (pack_packed_int(self, lineno) < 0)
681 return -1;
682 return pack_string(self, funcname, len);
Fred Drake8c081a12001-10-12 20:57:55 +0000683}
684
Fred Drake62c1e3c2001-12-04 21:40:53 +0000685static int
Fred Drake8c081a12001-10-12 20:57:55 +0000686pack_line_times(ProfilerObject *self)
687{
Fred Drake62c1e3c2001-12-04 21:40:53 +0000688 if (2 + self->index >= BUFFERSIZE) {
689 if (flush_data(self) < 0)
690 return -1;
691 }
Fred Drake8c081a12001-10-12 20:57:55 +0000692 self->buffer[self->index] = WHAT_LINE_TIMES;
693 self->buffer[self->index + 1] = self->linetimings ? 1 : 0;
694 self->index += 2;
Fred Drake62c1e3c2001-12-04 21:40:53 +0000695 return 0;
Fred Drake8c081a12001-10-12 20:57:55 +0000696}
697
Fred Drake62c1e3c2001-12-04 21:40:53 +0000698static int
Fred Drake30d1c752001-10-15 22:11:02 +0000699pack_frame_times(ProfilerObject *self)
700{
Fred Drake62c1e3c2001-12-04 21:40:53 +0000701 if (2 + self->index >= BUFFERSIZE) {
702 if (flush_data(self) < 0)
703 return -1;
704 }
Fred Drake30d1c752001-10-15 22:11:02 +0000705 self->buffer[self->index] = WHAT_FRAME_TIMES;
706 self->buffer[self->index + 1] = self->frametimings ? 1 : 0;
707 self->index += 2;
Fred Drake62c1e3c2001-12-04 21:40:53 +0000708 return 0;
Fred Drake30d1c752001-10-15 22:11:02 +0000709}
710
Fred Drake62c1e3c2001-12-04 21:40:53 +0000711static inline int
Fred Drake8c081a12001-10-12 20:57:55 +0000712pack_enter(ProfilerObject *self, int fileno, int tdelta, int lineno)
713{
Fred Drake62c1e3c2001-12-04 21:40:53 +0000714 if (MPISIZE + PISIZE*2 + self->index >= BUFFERSIZE) {
715 if (flush_data(self) < 0)
716 return -1;
717 }
Fred Drake8c081a12001-10-12 20:57:55 +0000718 pack_modified_packed_int(self, fileno, 2, WHAT_ENTER);
Fred Drake8c081a12001-10-12 20:57:55 +0000719 pack_packed_int(self, lineno);
Fred Drake30d1c752001-10-15 22:11:02 +0000720 if (self->frametimings)
Fred Drake62c1e3c2001-12-04 21:40:53 +0000721 return pack_packed_int(self, tdelta);
722 else
723 return 0;
Fred Drake8c081a12001-10-12 20:57:55 +0000724}
725
Fred Drake62c1e3c2001-12-04 21:40:53 +0000726static inline int
Fred Drake8c081a12001-10-12 20:57:55 +0000727pack_exit(ProfilerObject *self, int tdelta)
728{
Fred Drake62c1e3c2001-12-04 21:40:53 +0000729 if (MPISIZE + self->index >= BUFFERSIZE) {
730 if (flush_data(self) < 0)
731 return -1;
Fred Drake30d1c752001-10-15 22:11:02 +0000732 }
Fred Drake62c1e3c2001-12-04 21:40:53 +0000733 if (self->frametimings)
734 return pack_modified_packed_int(self, tdelta, 2, WHAT_EXIT);
735 self->buffer[self->index] = WHAT_EXIT;
736 self->index++;
737 return 0;
Fred Drake8c081a12001-10-12 20:57:55 +0000738}
739
Fred Drake62c1e3c2001-12-04 21:40:53 +0000740static inline int
Fred Drake8c081a12001-10-12 20:57:55 +0000741pack_lineno(ProfilerObject *self, int lineno)
742{
Fred Drake62c1e3c2001-12-04 21:40:53 +0000743 if (MPISIZE + self->index >= BUFFERSIZE) {
744 if (flush_data(self) < 0)
745 return -1;
746 }
747 return pack_modified_packed_int(self, lineno, 2, WHAT_LINENO);
Fred Drake8c081a12001-10-12 20:57:55 +0000748}
749
Fred Drake62c1e3c2001-12-04 21:40:53 +0000750static inline int
Fred Drake8c081a12001-10-12 20:57:55 +0000751pack_lineno_tdelta(ProfilerObject *self, int lineno, int tdelta)
752{
Fred Drake62c1e3c2001-12-04 21:40:53 +0000753 if (MPISIZE + PISIZE + self->index >= BUFFERSIZE) {
754 if (flush_data(self) < 0)
755 return 0;
756 }
757 if (pack_modified_packed_int(self, lineno, 2, WHAT_LINENO) < 0)
758 return -1;
759 return pack_packed_int(self, tdelta);
Fred Drake8c081a12001-10-12 20:57:55 +0000760}
761
762static inline int
763get_fileno(ProfilerObject *self, PyCodeObject *fcode)
764{
Fred Drake30d1c752001-10-15 22:11:02 +0000765 /* This is only used for ENTER events. */
766
767 PyObject *obj;
768 PyObject *dict;
Fred Drake8c081a12001-10-12 20:57:55 +0000769 int fileno;
770
Fred Drake30d1c752001-10-15 22:11:02 +0000771 obj = PyDict_GetItem(self->filemap, fcode->co_filename);
772 if (obj == NULL) {
Fred Drake8c081a12001-10-12 20:57:55 +0000773 /* first sighting of this file */
Fred Drake30d1c752001-10-15 22:11:02 +0000774 dict = PyDict_New();
775 if (dict == NULL) {
Fred Drake8c081a12001-10-12 20:57:55 +0000776 return -1;
777 }
Fred Drake30d1c752001-10-15 22:11:02 +0000778 fileno = self->next_fileno;
779 obj = Py_BuildValue("iN", fileno, dict);
780 if (obj == NULL) {
781 return -1;
782 }
783 if (PyDict_SetItem(self->filemap, fcode->co_filename, obj)) {
784 Py_DECREF(obj);
Fred Drake8c081a12001-10-12 20:57:55 +0000785 return -1;
786 }
787 self->next_fileno++;
Fred Drake30d1c752001-10-15 22:11:02 +0000788 Py_DECREF(obj);
Fred Drake62c1e3c2001-12-04 21:40:53 +0000789 if (pack_define_file(self, fileno,
790 PyString_AS_STRING(fcode->co_filename)) < 0)
791 return -1;
Fred Drake8c081a12001-10-12 20:57:55 +0000792 }
793 else {
794 /* already know this ID */
Fred Drake30d1c752001-10-15 22:11:02 +0000795 fileno = PyInt_AS_LONG(PyTuple_GET_ITEM(obj, 0));
796 dict = PyTuple_GET_ITEM(obj, 1);
797 }
798 /* make sure we save a function name for this (fileno, lineno) */
799 obj = PyInt_FromLong(fcode->co_firstlineno);
800 if (obj == NULL) {
801 /* We just won't have it saved; too bad. */
802 PyErr_Clear();
803 }
804 else {
805 PyObject *name = PyDict_GetItem(dict, obj);
806 if (name == NULL) {
Fred Drake62c1e3c2001-12-04 21:40:53 +0000807 if (pack_define_func(self, fileno, fcode->co_firstlineno,
Armin Rigoa4127692004-08-03 08:33:55 +0000808 PyString_AS_STRING(fcode->co_name)) < 0) {
809 Py_DECREF(obj);
Fred Drake62c1e3c2001-12-04 21:40:53 +0000810 return -1;
Armin Rigoa4127692004-08-03 08:33:55 +0000811 }
812 if (PyDict_SetItem(dict, obj, fcode->co_name)) {
813 Py_DECREF(obj);
Fred Drake30d1c752001-10-15 22:11:02 +0000814 return -1;
Armin Rigoa4127692004-08-03 08:33:55 +0000815 }
Fred Drake30d1c752001-10-15 22:11:02 +0000816 }
Armin Rigoa4127692004-08-03 08:33:55 +0000817 Py_DECREF(obj);
Fred Drake8c081a12001-10-12 20:57:55 +0000818 }
819 return fileno;
820}
821
822static inline int
823get_tdelta(ProfilerObject *self)
824{
825 int tdelta;
Martin v. Löwis6238d2b2002-06-30 15:26:10 +0000826#ifdef MS_WINDOWS
Fred Drake8c081a12001-10-12 20:57:55 +0000827 hs_time tv;
Tim Peters7d99ff22001-10-13 07:37:52 +0000828 hs_time diff;
Fred Drake8c081a12001-10-12 20:57:55 +0000829
Tim Peters7d99ff22001-10-13 07:37:52 +0000830 GETTIMEOFDAY(&tv);
831 diff = tv - self->prev_timeofday;
832 tdelta = (int)diff;
Fred Drake8c081a12001-10-12 20:57:55 +0000833#else
834 struct timeval tv;
835
836 GETTIMEOFDAY(&tv);
837
Neal Norwitz7a135162004-06-13 20:45:11 +0000838 tdelta = tv.tv_usec - self->prev_timeofday.tv_usec;
839 if (tv.tv_sec != self->prev_timeofday.tv_sec)
840 tdelta += (tv.tv_sec - self->prev_timeofday.tv_sec) * 1000000;
Fred Drake8c081a12001-10-12 20:57:55 +0000841#endif
Neal Norwitz7a135162004-06-13 20:45:11 +0000842 /* time can go backwards on some multiprocessor systems or by NTP */
843 if (tdelta < 0)
844 return 0;
845
Fred Drake8c081a12001-10-12 20:57:55 +0000846 self->prev_timeofday = tv;
847 return tdelta;
848}
849
850
851/* The workhorse: the profiler callback function. */
852
853static int
Fred Drake8c081a12001-10-12 20:57:55 +0000854tracer_callback(ProfilerObject *self, PyFrameObject *frame, int what,
855 PyObject *arg)
856{
857 int fileno;
858
Fred Drake8c081a12001-10-12 20:57:55 +0000859 switch (what) {
860 case PyTrace_CALL:
861 fileno = get_fileno(self, frame->f_code);
862 if (fileno < 0)
863 return -1;
Fred Drake62c1e3c2001-12-04 21:40:53 +0000864 return pack_enter(self, fileno,
865 self->frametimings ? get_tdelta(self) : -1,
866 frame->f_code->co_firstlineno);
867
Fred Drake8c081a12001-10-12 20:57:55 +0000868 case PyTrace_RETURN:
Fred Drake62c1e3c2001-12-04 21:40:53 +0000869 return pack_exit(self, get_tdelta(self));
870
Armin Rigode5f05f2005-12-06 14:07:39 +0000871 case PyTrace_LINE: /* we only get these events if we asked for them */
Fred Drake8c081a12001-10-12 20:57:55 +0000872 if (self->linetimings)
Michael W. Hudson806d1c82002-09-11 17:09:45 +0000873 return pack_lineno_tdelta(self, frame->f_lineno,
Michael W. Hudsondd32a912002-08-15 14:59:02 +0000874 get_tdelta(self));
Fred Drake8c081a12001-10-12 20:57:55 +0000875 else
Michael W. Hudson02ff6a92002-09-11 15:36:32 +0000876 return pack_lineno(self, frame->f_lineno);
Fred Drake62c1e3c2001-12-04 21:40:53 +0000877
Fred Drake8c081a12001-10-12 20:57:55 +0000878 default:
879 /* ignore PyTrace_EXCEPTION */
880 break;
881 }
882 return 0;
883}
884
885
886/* A couple of useful helper functions. */
887
Martin v. Löwis6238d2b2002-06-30 15:26:10 +0000888#ifdef MS_WINDOWS
Tim Petersfeab23f2001-10-13 00:11:10 +0000889static LARGE_INTEGER frequency = {0, 0};
Fred Drake8c081a12001-10-12 20:57:55 +0000890#endif
891
892static unsigned long timeofday_diff = 0;
893static unsigned long rusage_diff = 0;
894
895static void
896calibrate(void)
897{
898 hs_time tv1, tv2;
899
Martin v. Löwis6238d2b2002-06-30 15:26:10 +0000900#ifdef MS_WINDOWS
Tim Peters7d99ff22001-10-13 07:37:52 +0000901 hs_time diff;
Fred Drake8c081a12001-10-12 20:57:55 +0000902 QueryPerformanceFrequency(&frequency);
903#endif
904
905 GETTIMEOFDAY(&tv1);
906 while (1) {
907 GETTIMEOFDAY(&tv2);
Martin v. Löwis6238d2b2002-06-30 15:26:10 +0000908#ifdef MS_WINDOWS
Tim Peters7d99ff22001-10-13 07:37:52 +0000909 diff = tv2 - tv1;
910 if (diff != 0) {
911 timeofday_diff = (unsigned long)diff;
Fred Drake8c081a12001-10-12 20:57:55 +0000912 break;
913 }
914#else
915 if (tv1.tv_sec != tv2.tv_sec || tv1.tv_usec != tv2.tv_usec) {
916 if (tv1.tv_sec == tv2.tv_sec)
917 timeofday_diff = tv2.tv_usec - tv1.tv_usec;
918 else
919 timeofday_diff = (1000000 - tv1.tv_usec) + tv2.tv_usec;
920 break;
921 }
922#endif
923 }
Jack Janseneddc1442003-11-20 01:44:59 +0000924#if defined(MS_WINDOWS) || defined(PYOS_OS2) || \
Martin v. Löwisf24de1e2006-04-14 15:07:46 +0000925 defined(__VMS) || defined (__QNX__)
Fred Drake8c081a12001-10-12 20:57:55 +0000926 rusage_diff = -1;
927#else
928 {
929 struct rusage ru1, ru2;
930
931 getrusage(RUSAGE_SELF, &ru1);
932 while (1) {
933 getrusage(RUSAGE_SELF, &ru2);
934 if (ru1.ru_utime.tv_sec != ru2.ru_utime.tv_sec) {
935 rusage_diff = ((1000000 - ru1.ru_utime.tv_usec)
936 + ru2.ru_utime.tv_usec);
937 break;
938 }
939 else if (ru1.ru_utime.tv_usec != ru2.ru_utime.tv_usec) {
940 rusage_diff = ru2.ru_utime.tv_usec - ru1.ru_utime.tv_usec;
941 break;
942 }
943 else if (ru1.ru_stime.tv_sec != ru2.ru_stime.tv_sec) {
944 rusage_diff = ((1000000 - ru1.ru_stime.tv_usec)
945 + ru2.ru_stime.tv_usec);
946 break;
947 }
948 else if (ru1.ru_stime.tv_usec != ru2.ru_stime.tv_usec) {
949 rusage_diff = ru2.ru_stime.tv_usec - ru1.ru_stime.tv_usec;
950 break;
951 }
952 }
953 }
954#endif
955}
956
957static void
958do_start(ProfilerObject *self)
959{
960 self->active = 1;
961 GETTIMEOFDAY(&self->prev_timeofday);
962 if (self->lineevents)
963 PyEval_SetTrace((Py_tracefunc) tracer_callback, (PyObject *)self);
964 else
Armin Rigode5f05f2005-12-06 14:07:39 +0000965 PyEval_SetProfile((Py_tracefunc) tracer_callback, (PyObject *)self);
Fred Drake8c081a12001-10-12 20:57:55 +0000966}
967
968static void
969do_stop(ProfilerObject *self)
970{
971 if (self->active) {
972 self->active = 0;
973 if (self->lineevents)
974 PyEval_SetTrace(NULL, NULL);
975 else
976 PyEval_SetProfile(NULL, NULL);
977 }
978 if (self->index > 0) {
979 /* Best effort to dump out any remaining data. */
980 flush_data(self);
981 }
982}
983
984static int
985is_available(ProfilerObject *self)
986{
987 if (self->active) {
988 PyErr_SetString(ProfilerError, "profiler already active");
989 return 0;
990 }
991 if (self->logfp == NULL) {
992 PyErr_SetString(ProfilerError, "profiler already closed");
993 return 0;
994 }
995 return 1;
996}
997
998
999/* Profiler object interface methods. */
1000
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001001PyDoc_STRVAR(addinfo__doc__,
Fred Drake4c2e1af2001-10-29 20:45:57 +00001002"addinfo(key, value)\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001003"Insert an ADD_INFO record into the log.");
Fred Drake4c2e1af2001-10-29 20:45:57 +00001004
1005static PyObject *
1006profiler_addinfo(ProfilerObject *self, PyObject *args)
1007{
1008 PyObject *result = NULL;
1009 char *key, *value;
1010
1011 if (PyArg_ParseTuple(args, "ss:addinfo", &key, &value)) {
1012 if (self->logfp == NULL)
1013 PyErr_SetString(ProfilerError, "profiler already closed");
1014 else {
Fred Drake62c1e3c2001-12-04 21:40:53 +00001015 if (pack_add_info(self, key, value) == 0) {
1016 result = Py_None;
1017 Py_INCREF(result);
1018 }
Fred Drake4c2e1af2001-10-29 20:45:57 +00001019 }
1020 }
1021 return result;
1022}
1023
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001024PyDoc_STRVAR(close__doc__,
Tim Petersfeab23f2001-10-13 00:11:10 +00001025"close()\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001026"Shut down this profiler and close the log files, even if its active.");
Fred Drake8c081a12001-10-12 20:57:55 +00001027
1028static PyObject *
Fred Drake666bf522002-07-18 19:11:44 +00001029profiler_close(ProfilerObject *self)
Fred Drake8c081a12001-10-12 20:57:55 +00001030{
Fred Drake666bf522002-07-18 19:11:44 +00001031 do_stop(self);
1032 if (self->logfp != NULL) {
1033 fclose(self->logfp);
1034 self->logfp = NULL;
Fred Drake8c081a12001-10-12 20:57:55 +00001035 }
Fred Drake666bf522002-07-18 19:11:44 +00001036 Py_INCREF(Py_None);
1037 return Py_None;
1038}
1039
1040#define fileno__doc__ logreader_fileno__doc__
1041
1042static PyObject *
1043profiler_fileno(ProfilerObject *self)
1044{
1045 if (self->logfp == NULL) {
1046 PyErr_SetString(PyExc_ValueError,
1047 "profiler's file object already closed");
1048 return NULL;
1049 }
1050 return PyInt_FromLong(fileno(self->logfp));
Fred Drake8c081a12001-10-12 20:57:55 +00001051}
1052
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001053PyDoc_STRVAR(runcall__doc__,
Tim Petersfeab23f2001-10-13 00:11:10 +00001054"runcall(callable[, args[, kw]]) -> callable()\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001055"Profile a specific function call, returning the result of that call.");
Fred Drake8c081a12001-10-12 20:57:55 +00001056
1057static PyObject *
1058profiler_runcall(ProfilerObject *self, PyObject *args)
1059{
1060 PyObject *result = NULL;
1061 PyObject *callargs = NULL;
1062 PyObject *callkw = NULL;
1063 PyObject *callable;
1064
Georg Brandl96a8c392006-05-29 21:04:52 +00001065 if (PyArg_UnpackTuple(args, "runcall", 1, 3,
Fred Drake8c081a12001-10-12 20:57:55 +00001066 &callable, &callargs, &callkw)) {
1067 if (is_available(self)) {
1068 do_start(self);
1069 result = PyEval_CallObjectWithKeywords(callable, callargs, callkw);
1070 do_stop(self);
1071 }
1072 }
1073 return result;
1074}
1075
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001076PyDoc_STRVAR(runcode__doc__,
Tim Petersfeab23f2001-10-13 00:11:10 +00001077"runcode(code, globals[, locals])\n"
1078"Execute a code object while collecting profile data. If locals is\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001079"omitted, globals is used for the locals as well.");
Fred Drake8c081a12001-10-12 20:57:55 +00001080
1081static PyObject *
1082profiler_runcode(ProfilerObject *self, PyObject *args)
1083{
1084 PyObject *result = NULL;
1085 PyCodeObject *code;
1086 PyObject *globals;
1087 PyObject *locals = NULL;
1088
1089 if (PyArg_ParseTuple(args, "O!O!|O:runcode",
1090 &PyCode_Type, &code,
1091 &PyDict_Type, &globals,
1092 &locals)) {
1093 if (is_available(self)) {
1094 if (locals == NULL || locals == Py_None)
1095 locals = globals;
1096 else if (!PyDict_Check(locals)) {
1097 PyErr_SetString(PyExc_TypeError,
1098 "locals must be a dictionary or None");
1099 return NULL;
1100 }
1101 do_start(self);
1102 result = PyEval_EvalCode(code, globals, locals);
1103 do_stop(self);
1104#if 0
1105 if (!PyErr_Occurred()) {
1106 result = Py_None;
1107 Py_INCREF(result);
1108 }
1109#endif
1110 }
1111 }
1112 return result;
1113}
1114
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001115PyDoc_STRVAR(start__doc__,
Tim Petersfeab23f2001-10-13 00:11:10 +00001116"start()\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001117"Install this profiler for the current thread.");
Fred Drake8c081a12001-10-12 20:57:55 +00001118
1119static PyObject *
1120profiler_start(ProfilerObject *self, PyObject *args)
1121{
1122 PyObject *result = NULL;
1123
Fred Drake666bf522002-07-18 19:11:44 +00001124 if (is_available(self)) {
1125 do_start(self);
1126 result = Py_None;
1127 Py_INCREF(result);
Fred Drake8c081a12001-10-12 20:57:55 +00001128 }
1129 return result;
1130}
1131
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001132PyDoc_STRVAR(stop__doc__,
Tim Petersfeab23f2001-10-13 00:11:10 +00001133"stop()\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001134"Remove this profiler from the current thread.");
Fred Drake8c081a12001-10-12 20:57:55 +00001135
1136static PyObject *
1137profiler_stop(ProfilerObject *self, PyObject *args)
1138{
1139 PyObject *result = NULL;
1140
Fred Drake666bf522002-07-18 19:11:44 +00001141 if (!self->active)
1142 PyErr_SetString(ProfilerError, "profiler not active");
1143 else {
1144 do_stop(self);
1145 result = Py_None;
1146 Py_INCREF(result);
Fred Drake8c081a12001-10-12 20:57:55 +00001147 }
1148 return result;
1149}
1150
1151
1152/* Python API support. */
1153
1154static void
1155profiler_dealloc(ProfilerObject *self)
1156{
1157 do_stop(self);
1158 if (self->logfp != NULL)
1159 fclose(self->logfp);
1160 Py_XDECREF(self->filemap);
1161 Py_XDECREF(self->logfilename);
1162 PyObject_Del((PyObject *)self);
1163}
1164
Fred Drake8c081a12001-10-12 20:57:55 +00001165static PyMethodDef profiler_methods[] = {
Fred Drake4c2e1af2001-10-29 20:45:57 +00001166 {"addinfo", (PyCFunction)profiler_addinfo, METH_VARARGS, addinfo__doc__},
Fred Drake666bf522002-07-18 19:11:44 +00001167 {"close", (PyCFunction)profiler_close, METH_NOARGS, close__doc__},
1168 {"fileno", (PyCFunction)profiler_fileno, METH_NOARGS, fileno__doc__},
Fred Drake8c081a12001-10-12 20:57:55 +00001169 {"runcall", (PyCFunction)profiler_runcall, METH_VARARGS, runcall__doc__},
1170 {"runcode", (PyCFunction)profiler_runcode, METH_VARARGS, runcode__doc__},
Fred Drake666bf522002-07-18 19:11:44 +00001171 {"start", (PyCFunction)profiler_start, METH_NOARGS, start__doc__},
1172 {"stop", (PyCFunction)profiler_stop, METH_NOARGS, stop__doc__},
Fred Drake8c081a12001-10-12 20:57:55 +00001173 {NULL, NULL}
1174};
1175
Guido van Rossum9cb64b92002-07-17 16:15:35 +00001176static PyMemberDef profiler_members[] = {
Fred Drake30d1c752001-10-15 22:11:02 +00001177 {"frametimings", T_LONG, offsetof(ProfilerObject, linetimings), READONLY},
1178 {"lineevents", T_LONG, offsetof(ProfilerObject, lineevents), READONLY},
1179 {"linetimings", T_LONG, offsetof(ProfilerObject, linetimings), READONLY},
Fred Drake8c081a12001-10-12 20:57:55 +00001180 {NULL}
1181};
1182
1183static PyObject *
Guido van Rossum9cb64b92002-07-17 16:15:35 +00001184profiler_get_closed(ProfilerObject *self, void *closure)
Fred Drake8c081a12001-10-12 20:57:55 +00001185{
Guido van Rossum9cb64b92002-07-17 16:15:35 +00001186 PyObject *result = (self->logfp == NULL) ? Py_True : Py_False;
1187 Py_INCREF(result);
Fred Drake8c081a12001-10-12 20:57:55 +00001188 return result;
1189}
1190
Guido van Rossum9cb64b92002-07-17 16:15:35 +00001191static PyGetSetDef profiler_getsets[] = {
Fred Draked1eb8b62002-07-17 18:54:20 +00001192 {"closed", (getter)profiler_get_closed, NULL,
Fred Drake5c3ed3d2002-07-17 19:38:05 +00001193 PyDoc_STR("True if the profiler's output file has already been closed.")},
Guido van Rossum9cb64b92002-07-17 16:15:35 +00001194 {NULL}
1195};
1196
Fred Drake8c081a12001-10-12 20:57:55 +00001197
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001198PyDoc_STRVAR(profiler_object__doc__,
Tim Petersfeab23f2001-10-13 00:11:10 +00001199"High-performance profiler object.\n"
1200"\n"
1201"Methods:\n"
1202"\n"
Fred Drake30d1c752001-10-15 22:11:02 +00001203"close(): Stop the profiler and close the log files.\n"
Fred Drake666bf522002-07-18 19:11:44 +00001204"fileno(): Returns the file descriptor of the log file.\n"
Fred Drake30d1c752001-10-15 22:11:02 +00001205"runcall(): Run a single function call with profiling enabled.\n"
1206"runcode(): Execute a code object with profiling enabled.\n"
1207"start(): Install the profiler and return.\n"
1208"stop(): Remove the profiler.\n"
Tim Petersfeab23f2001-10-13 00:11:10 +00001209"\n"
1210"Attributes (read-only):\n"
1211"\n"
Fred Drake30d1c752001-10-15 22:11:02 +00001212"closed: True if the profiler has already been closed.\n"
1213"frametimings: True if ENTER/EXIT events collect timing information.\n"
Michael W. Hudsondd32a912002-08-15 14:59:02 +00001214"lineevents: True if line events are reported to the profiler.\n"
1215"linetimings: True if line events collect timing information.");
Fred Drake8c081a12001-10-12 20:57:55 +00001216
1217static PyTypeObject ProfilerType = {
1218 PyObject_HEAD_INIT(NULL)
1219 0, /* ob_size */
Fred Drake4c2e1af2001-10-29 20:45:57 +00001220 "_hotshot.ProfilerType", /* tp_name */
Fred Drake8c081a12001-10-12 20:57:55 +00001221 (int) sizeof(ProfilerObject), /* tp_basicsize */
1222 0, /* tp_itemsize */
1223 (destructor)profiler_dealloc, /* tp_dealloc */
1224 0, /* tp_print */
Guido van Rossum9cb64b92002-07-17 16:15:35 +00001225 0, /* tp_getattr */
Fred Drake8c081a12001-10-12 20:57:55 +00001226 0, /* tp_setattr */
1227 0, /* tp_compare */
1228 0, /* tp_repr */
1229 0, /* tp_as_number */
1230 0, /* tp_as_sequence */
1231 0, /* tp_as_mapping */
1232 0, /* tp_hash */
1233 0, /* tp_call */
1234 0, /* tp_str */
Jason Tishlerfb8595d2003-01-06 12:41:26 +00001235 PyObject_GenericGetAttr, /* tp_getattro */
Fred Drake8c081a12001-10-12 20:57:55 +00001236 0, /* tp_setattro */
1237 0, /* tp_as_buffer */
Fred Drake4c2e1af2001-10-29 20:45:57 +00001238 Py_TPFLAGS_DEFAULT, /* tp_flags */
Fred Drake8c081a12001-10-12 20:57:55 +00001239 profiler_object__doc__, /* tp_doc */
Guido van Rossum9cb64b92002-07-17 16:15:35 +00001240 0, /* tp_traverse */
1241 0, /* tp_clear */
1242 0, /* tp_richcompare */
1243 0, /* tp_weaklistoffset */
1244 0, /* tp_iter */
1245 0, /* tp_iternext */
1246 profiler_methods, /* tp_methods */
1247 profiler_members, /* tp_members */
1248 profiler_getsets, /* tp_getset */
1249 0, /* tp_base */
1250 0, /* tp_dict */
1251 0, /* tp_descr_get */
1252 0, /* tp_descr_set */
Fred Drake8c081a12001-10-12 20:57:55 +00001253};
1254
1255
1256static PyMethodDef logreader_methods[] = {
Fred Drake666bf522002-07-18 19:11:44 +00001257 {"close", (PyCFunction)logreader_close, METH_NOARGS,
Fred Drake8c081a12001-10-12 20:57:55 +00001258 logreader_close__doc__},
Fred Drake666bf522002-07-18 19:11:44 +00001259 {"fileno", (PyCFunction)logreader_fileno, METH_NOARGS,
1260 logreader_fileno__doc__},
Fred Drake8c081a12001-10-12 20:57:55 +00001261 {NULL, NULL}
1262};
1263
Guido van Rossum9cb64b92002-07-17 16:15:35 +00001264static PyMemberDef logreader_members[] = {
Fred Drake5c3ed3d2002-07-17 19:38:05 +00001265 {"info", T_OBJECT, offsetof(LogReaderObject, info), RO,
1266 PyDoc_STR("Dictionary mapping informational keys to lists of values.")},
Guido van Rossum9cb64b92002-07-17 16:15:35 +00001267 {NULL}
1268};
Fred Drake8c081a12001-10-12 20:57:55 +00001269
1270
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001271PyDoc_STRVAR(logreader__doc__,
1272"logreader(filename) --> log-iterator\n\
1273Create a log-reader for the timing information file.");
Fred Drake8c081a12001-10-12 20:57:55 +00001274
1275static PySequenceMethods logreader_as_sequence = {
1276 0, /* sq_length */
1277 0, /* sq_concat */
1278 0, /* sq_repeat */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001279 (ssizeargfunc)logreader_sq_item, /* sq_item */
Fred Drake8c081a12001-10-12 20:57:55 +00001280 0, /* sq_slice */
1281 0, /* sq_ass_item */
1282 0, /* sq_ass_slice */
1283 0, /* sq_contains */
1284 0, /* sq_inplace_concat */
1285 0, /* sq_inplace_repeat */
1286};
1287
Fred Drake666bf522002-07-18 19:11:44 +00001288static PyObject *
1289logreader_get_closed(LogReaderObject *self, void *closure)
1290{
1291 PyObject *result = (self->logfp == NULL) ? Py_True : Py_False;
1292 Py_INCREF(result);
1293 return result;
1294}
1295
1296static PyGetSetDef logreader_getsets[] = {
1297 {"closed", (getter)logreader_get_closed, NULL,
1298 PyDoc_STR("True if the logreader's input file has already been closed.")},
1299 {NULL}
1300};
1301
Fred Drake8c081a12001-10-12 20:57:55 +00001302static PyTypeObject LogReaderType = {
1303 PyObject_HEAD_INIT(NULL)
1304 0, /* ob_size */
Fred Drake4c2e1af2001-10-29 20:45:57 +00001305 "_hotshot.LogReaderType", /* tp_name */
Fred Drake8c081a12001-10-12 20:57:55 +00001306 (int) sizeof(LogReaderObject), /* tp_basicsize */
1307 0, /* tp_itemsize */
1308 (destructor)logreader_dealloc, /* tp_dealloc */
1309 0, /* tp_print */
Guido van Rossum9cb64b92002-07-17 16:15:35 +00001310 0, /* tp_getattr */
Fred Drake8c081a12001-10-12 20:57:55 +00001311 0, /* tp_setattr */
1312 0, /* tp_compare */
1313 0, /* tp_repr */
1314 0, /* tp_as_number */
1315 &logreader_as_sequence, /* tp_as_sequence */
1316 0, /* tp_as_mapping */
1317 0, /* tp_hash */
1318 0, /* tp_call */
1319 0, /* tp_str */
Jason Tishlerfb8595d2003-01-06 12:41:26 +00001320 PyObject_GenericGetAttr, /* tp_getattro */
Fred Drake8c081a12001-10-12 20:57:55 +00001321 0, /* tp_setattro */
1322 0, /* tp_as_buffer */
Fred Drake4c2e1af2001-10-29 20:45:57 +00001323 Py_TPFLAGS_DEFAULT, /* tp_flags */
Fred Drake8c081a12001-10-12 20:57:55 +00001324 logreader__doc__, /* tp_doc */
Fred Drake8c081a12001-10-12 20:57:55 +00001325 0, /* tp_traverse */
1326 0, /* tp_clear */
1327 0, /* tp_richcompare */
1328 0, /* tp_weaklistoffset */
Raymond Hettinger1da1dbf2003-03-17 19:46:11 +00001329 PyObject_SelfIter, /* tp_iter */
Fred Drake8c081a12001-10-12 20:57:55 +00001330 (iternextfunc)logreader_tp_iternext,/* tp_iternext */
Guido van Rossum9cb64b92002-07-17 16:15:35 +00001331 logreader_methods, /* tp_methods */
1332 logreader_members, /* tp_members */
Fred Drake666bf522002-07-18 19:11:44 +00001333 logreader_getsets, /* tp_getset */
Guido van Rossum9cb64b92002-07-17 16:15:35 +00001334 0, /* tp_base */
1335 0, /* tp_dict */
1336 0, /* tp_descr_get */
1337 0, /* tp_descr_set */
Fred Drake8c081a12001-10-12 20:57:55 +00001338};
1339
1340static PyObject *
1341hotshot_logreader(PyObject *unused, PyObject *args)
1342{
1343 LogReaderObject *self = NULL;
1344 char *filename;
Neil Schemenauer8b6b4912002-05-29 18:19:14 +00001345 int c;
1346 int err = 0;
Fred Drake8c081a12001-10-12 20:57:55 +00001347
1348 if (PyArg_ParseTuple(args, "s:logreader", &filename)) {
1349 self = PyObject_New(LogReaderObject, &LogReaderType);
1350 if (self != NULL) {
Fred Drake30d1c752001-10-15 22:11:02 +00001351 self->frametimings = 1;
Fred Drake8c081a12001-10-12 20:57:55 +00001352 self->linetimings = 0;
Fred Drake4c2e1af2001-10-29 20:45:57 +00001353 self->info = NULL;
Fred Drake8c081a12001-10-12 20:57:55 +00001354 self->logfp = fopen(filename, "rb");
1355 if (self->logfp == NULL) {
1356 PyErr_SetFromErrnoWithFilename(PyExc_IOError, filename);
1357 Py_DECREF(self);
1358 self = NULL;
Fred Drake4c2e1af2001-10-29 20:45:57 +00001359 goto finally;
1360 }
1361 self->info = PyDict_New();
1362 if (self->info == NULL) {
1363 Py_DECREF(self);
1364 goto finally;
1365 }
Neil Schemenauer8b6b4912002-05-29 18:19:14 +00001366 /* read initial info */
1367 for (;;) {
1368 if ((c = fgetc(self->logfp)) == EOF) {
Fred Drake666bf522002-07-18 19:11:44 +00001369 eof_error(self);
Neil Schemenauer8b6b4912002-05-29 18:19:14 +00001370 break;
1371 }
1372 if (c != WHAT_ADD_INFO) {
1373 ungetc(c, self->logfp);
1374 break;
1375 }
1376 err = unpack_add_info(self);
Fred Drake4c2e1af2001-10-29 20:45:57 +00001377 if (err) {
1378 if (err == ERR_EOF)
Fred Drake666bf522002-07-18 19:11:44 +00001379 eof_error(self);
Fred Drake4c2e1af2001-10-29 20:45:57 +00001380 else
1381 PyErr_SetString(PyExc_RuntimeError,
1382 "unexpected error");
1383 break;
1384 }
Fred Drake8c081a12001-10-12 20:57:55 +00001385 }
1386 }
1387 }
Fred Drake4c2e1af2001-10-29 20:45:57 +00001388 finally:
Fred Drake8c081a12001-10-12 20:57:55 +00001389 return (PyObject *) self;
1390}
1391
1392
1393/* Return a Python string that represents the version number without the
1394 * extra cruft added by revision control, even if the right options were
1395 * given to the "cvs export" command to make it not include the extra
1396 * cruft.
1397 */
1398static char *
1399get_version_string(void)
1400{
1401 static char *rcsid = "$Revision$";
1402 char *rev = rcsid;
1403 char *buffer;
1404 int i = 0;
1405
Neal Norwitz30b5c5d2005-12-19 06:05:18 +00001406 while (*rev && !isdigit(Py_CHARMASK(*rev)))
Fred Drake8c081a12001-10-12 20:57:55 +00001407 ++rev;
1408 while (rev[i] != ' ' && rev[i] != '\0')
1409 ++i;
Anthony Baxter7cbc0f52006-04-13 07:19:01 +00001410 buffer = (char *)malloc(i + 1);
Fred Drake8c081a12001-10-12 20:57:55 +00001411 if (buffer != NULL) {
1412 memmove(buffer, rev, i);
1413 buffer[i] = '\0';
1414 }
1415 return buffer;
1416}
1417
1418/* Write out a RFC 822-style header with various useful bits of
1419 * information to make the output easier to manage.
1420 */
1421static int
1422write_header(ProfilerObject *self)
1423{
1424 char *buffer;
1425 char cwdbuffer[PATH_MAX];
1426 PyObject *temp;
Martin v. Löwis66851282006-04-22 11:40:03 +00001427 Py_ssize_t i, len;
Fred Drake8c081a12001-10-12 20:57:55 +00001428
1429 buffer = get_version_string();
1430 if (buffer == NULL) {
1431 PyErr_NoMemory();
1432 return -1;
1433 }
Fred Drake4c2e1af2001-10-29 20:45:57 +00001434 pack_add_info(self, "hotshot-version", buffer);
1435 pack_add_info(self, "requested-frame-timings",
1436 (self->frametimings ? "yes" : "no"));
1437 pack_add_info(self, "requested-line-events",
Fred Drake8c081a12001-10-12 20:57:55 +00001438 (self->lineevents ? "yes" : "no"));
Fred Drake4c2e1af2001-10-29 20:45:57 +00001439 pack_add_info(self, "requested-line-timings",
1440 (self->linetimings ? "yes" : "no"));
1441 pack_add_info(self, "platform", Py_GetPlatform());
1442 pack_add_info(self, "executable", Py_GetProgramFullPath());
Fred Drakef12a68c2001-11-09 15:59:36 +00001443 free(buffer);
Fred Drake8c081a12001-10-12 20:57:55 +00001444 buffer = (char *) Py_GetVersion();
1445 if (buffer == NULL)
1446 PyErr_Clear();
1447 else
Fred Drake4c2e1af2001-10-29 20:45:57 +00001448 pack_add_info(self, "executable-version", buffer);
Fred Drake8c081a12001-10-12 20:57:55 +00001449
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00001450#ifdef MS_WINDOWS
Tim Peters885d4572001-11-28 20:27:42 +00001451 PyOS_snprintf(cwdbuffer, sizeof(cwdbuffer), "%I64d", frequency.QuadPart);
Fred Drake4c2e1af2001-10-29 20:45:57 +00001452 pack_add_info(self, "reported-performance-frequency", cwdbuffer);
Fred Drake8c081a12001-10-12 20:57:55 +00001453#else
Tim Peters885d4572001-11-28 20:27:42 +00001454 PyOS_snprintf(cwdbuffer, sizeof(cwdbuffer), "%lu", rusage_diff);
Fred Drake4c2e1af2001-10-29 20:45:57 +00001455 pack_add_info(self, "observed-interval-getrusage", cwdbuffer);
Tim Peters885d4572001-11-28 20:27:42 +00001456 PyOS_snprintf(cwdbuffer, sizeof(cwdbuffer), "%lu", timeofday_diff);
Fred Drake4c2e1af2001-10-29 20:45:57 +00001457 pack_add_info(self, "observed-interval-gettimeofday", cwdbuffer);
Fred Drake8c081a12001-10-12 20:57:55 +00001458#endif
Fred Drake8c081a12001-10-12 20:57:55 +00001459
Fred Drake4c2e1af2001-10-29 20:45:57 +00001460 pack_add_info(self, "current-directory",
Fred Drake8c081a12001-10-12 20:57:55 +00001461 getcwd(cwdbuffer, sizeof cwdbuffer));
1462
1463 temp = PySys_GetObject("path");
Neal Norwitz60da3162006-03-07 04:48:24 +00001464 if (temp == NULL || !PyList_Check(temp)) {
1465 PyErr_SetString(PyExc_RuntimeError, "sys.path must be a list");
1466 return -1;
1467 }
Fred Drake8c081a12001-10-12 20:57:55 +00001468 len = PyList_GET_SIZE(temp);
1469 for (i = 0; i < len; ++i) {
1470 PyObject *item = PyList_GET_ITEM(temp, i);
1471 buffer = PyString_AsString(item);
Fred Draked1eb8b62002-07-17 18:54:20 +00001472 if (buffer == NULL) {
1473 pack_add_info(self, "sys-path-entry", "<non-string-path-entry>");
1474 PyErr_Clear();
1475 }
1476 else {
1477 pack_add_info(self, "sys-path-entry", buffer);
1478 }
Fred Drake8c081a12001-10-12 20:57:55 +00001479 }
Fred Drake4c2e1af2001-10-29 20:45:57 +00001480 pack_frame_times(self);
1481 pack_line_times(self);
1482
Fred Drake8c081a12001-10-12 20:57:55 +00001483 return 0;
1484}
1485
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001486PyDoc_STRVAR(profiler__doc__,
1487"profiler(logfilename[, lineevents[, linetimes]]) -> profiler\n\
1488Create a new profiler object.");
Fred Drake8c081a12001-10-12 20:57:55 +00001489
1490static PyObject *
1491hotshot_profiler(PyObject *unused, PyObject *args)
1492{
1493 char *logfilename;
1494 ProfilerObject *self = NULL;
1495 int lineevents = 0;
1496 int linetimings = 1;
1497
1498 if (PyArg_ParseTuple(args, "s|ii:profiler", &logfilename,
1499 &lineevents, &linetimings)) {
1500 self = PyObject_New(ProfilerObject, &ProfilerType);
1501 if (self == NULL)
1502 return NULL;
Fred Drake30d1c752001-10-15 22:11:02 +00001503 self->frametimings = 1;
Fred Drake8c081a12001-10-12 20:57:55 +00001504 self->lineevents = lineevents ? 1 : 0;
1505 self->linetimings = (lineevents && linetimings) ? 1 : 0;
1506 self->index = 0;
1507 self->active = 0;
1508 self->next_fileno = 0;
Tim Peters1566a172001-10-12 22:08:39 +00001509 self->logfp = NULL;
Fred Drake8c081a12001-10-12 20:57:55 +00001510 self->logfilename = PyTuple_GET_ITEM(args, 0);
1511 Py_INCREF(self->logfilename);
1512 self->filemap = PyDict_New();
1513 if (self->filemap == NULL) {
1514 Py_DECREF(self);
1515 return NULL;
1516 }
1517 self->logfp = fopen(logfilename, "wb");
1518 if (self->logfp == NULL) {
1519 Py_DECREF(self);
1520 PyErr_SetFromErrnoWithFilename(PyExc_IOError, logfilename);
1521 return NULL;
1522 }
1523 if (timeofday_diff == 0) {
1524 /* Run this several times since sometimes the first
1525 * doesn't give the lowest values, and we're really trying
1526 * to determine the lowest.
1527 */
1528 calibrate();
1529 calibrate();
1530 calibrate();
1531 }
Tim Petersdf44ab72006-03-07 23:53:32 +00001532 if (write_header(self)) {
Fred Drake8c081a12001-10-12 20:57:55 +00001533 /* some error occurred, exception has been set */
Tim Petersdf44ab72006-03-07 23:53:32 +00001534 Py_DECREF(self);
Fred Drake8c081a12001-10-12 20:57:55 +00001535 self = NULL;
Tim Petersdf44ab72006-03-07 23:53:32 +00001536 }
Fred Drake8c081a12001-10-12 20:57:55 +00001537 }
1538 return (PyObject *) self;
1539}
1540
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001541PyDoc_STRVAR(coverage__doc__,
1542"coverage(logfilename) -> profiler\n\
Fred Drake30d1c752001-10-15 22:11:02 +00001543Returns a profiler that doesn't collect any timing information, which is\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001544useful in building a coverage analysis tool.");
Fred Drake30d1c752001-10-15 22:11:02 +00001545
1546static PyObject *
1547hotshot_coverage(PyObject *unused, PyObject *args)
1548{
1549 char *logfilename;
1550 PyObject *result = NULL;
1551
1552 if (PyArg_ParseTuple(args, "s:coverage", &logfilename)) {
1553 result = hotshot_profiler(unused, args);
1554 if (result != NULL) {
1555 ProfilerObject *self = (ProfilerObject *) result;
1556 self->frametimings = 0;
1557 self->linetimings = 0;
1558 self->lineevents = 1;
1559 }
1560 }
1561 return result;
1562}
1563
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001564PyDoc_VAR(resolution__doc__) =
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00001565#ifdef MS_WINDOWS
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001566PyDoc_STR(
Tim Petersfeab23f2001-10-13 00:11:10 +00001567"resolution() -> (performance-counter-ticks, update-frequency)\n"
1568"Return the resolution of the timer provided by the QueryPerformanceCounter()\n"
1569"function. The first value is the smallest observed change, and the second\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001570"is the result of QueryPerformanceFrequency()."
1571)
Fred Drake8c081a12001-10-12 20:57:55 +00001572#else
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001573PyDoc_STR(
Tim Petersfeab23f2001-10-13 00:11:10 +00001574"resolution() -> (gettimeofday-usecs, getrusage-usecs)\n"
1575"Return the resolution of the timers provided by the gettimeofday() and\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001576"getrusage() system calls, or -1 if the call is not supported."
1577)
Fred Drake8c081a12001-10-12 20:57:55 +00001578#endif
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001579;
Fred Drake8c081a12001-10-12 20:57:55 +00001580
1581static PyObject *
Georg Brandl96a8c392006-05-29 21:04:52 +00001582hotshot_resolution(PyObject *self, PyObject *unused)
Fred Drake8c081a12001-10-12 20:57:55 +00001583{
Georg Brandl96a8c392006-05-29 21:04:52 +00001584 if (timeofday_diff == 0) {
1585 calibrate();
1586 calibrate();
1587 calibrate();
Fred Drake8c081a12001-10-12 20:57:55 +00001588 }
Georg Brandl96a8c392006-05-29 21:04:52 +00001589#ifdef MS_WINDOWS
1590 return Py_BuildValue("ii", timeofday_diff, frequency.LowPart);
1591#else
1592 return Py_BuildValue("ii", timeofday_diff, rusage_diff);
1593#endif
Fred Drake8c081a12001-10-12 20:57:55 +00001594}
1595
1596
1597static PyMethodDef functions[] = {
Fred Drake30d1c752001-10-15 22:11:02 +00001598 {"coverage", hotshot_coverage, METH_VARARGS, coverage__doc__},
Fred Drake8c081a12001-10-12 20:57:55 +00001599 {"profiler", hotshot_profiler, METH_VARARGS, profiler__doc__},
1600 {"logreader", hotshot_logreader, METH_VARARGS, logreader__doc__},
Georg Brandl96a8c392006-05-29 21:04:52 +00001601 {"resolution", hotshot_resolution, METH_NOARGS, resolution__doc__},
Fred Drake8c081a12001-10-12 20:57:55 +00001602 {NULL, NULL}
1603};
1604
1605
1606void
1607init_hotshot(void)
1608{
1609 PyObject *module;
1610
1611 LogReaderType.ob_type = &PyType_Type;
1612 ProfilerType.ob_type = &PyType_Type;
1613 module = Py_InitModule("_hotshot", functions);
1614 if (module != NULL) {
1615 char *s = get_version_string();
1616
1617 PyModule_AddStringConstant(module, "__version__", s);
1618 free(s);
1619 Py_INCREF(&LogReaderType);
1620 PyModule_AddObject(module, "LogReaderType",
1621 (PyObject *)&LogReaderType);
1622 Py_INCREF(&ProfilerType);
1623 PyModule_AddObject(module, "ProfilerType",
1624 (PyObject *)&ProfilerType);
1625
1626 if (ProfilerError == NULL)
1627 ProfilerError = PyErr_NewException("hotshot.ProfilerError",
1628 NULL, NULL);
1629 if (ProfilerError != NULL) {
1630 Py_INCREF(ProfilerError);
1631 PyModule_AddObject(module, "ProfilerError", ProfilerError);
1632 }
1633 PyModule_AddIntConstant(module, "WHAT_ENTER", WHAT_ENTER);
1634 PyModule_AddIntConstant(module, "WHAT_EXIT", WHAT_EXIT);
1635 PyModule_AddIntConstant(module, "WHAT_LINENO", WHAT_LINENO);
1636 PyModule_AddIntConstant(module, "WHAT_OTHER", WHAT_OTHER);
1637 PyModule_AddIntConstant(module, "WHAT_ADD_INFO", WHAT_ADD_INFO);
1638 PyModule_AddIntConstant(module, "WHAT_DEFINE_FILE", WHAT_DEFINE_FILE);
Fred Drake30d1c752001-10-15 22:11:02 +00001639 PyModule_AddIntConstant(module, "WHAT_DEFINE_FUNC", WHAT_DEFINE_FUNC);
Fred Drake8c081a12001-10-12 20:57:55 +00001640 PyModule_AddIntConstant(module, "WHAT_LINE_TIMES", WHAT_LINE_TIMES);
1641 }
1642}