Back to home page

OSCL-LXR

 
 

    


0001 // SPDX-License-Identifier: GPL-2.0
0002 #include <Python.h>
0003 #include <structmember.h>
0004 #include <inttypes.h>
0005 #include <poll.h>
0006 #include <linux/err.h>
0007 #include <perf/cpumap.h>
0008 #include <traceevent/event-parse.h>
0009 #include <perf/mmap.h>
0010 #include "evlist.h"
0011 #include "callchain.h"
0012 #include "evsel.h"
0013 #include "event.h"
0014 #include "print_binary.h"
0015 #include "thread_map.h"
0016 #include "trace-event.h"
0017 #include "mmap.h"
0018 #include "stat.h"
0019 #include "metricgroup.h"
0020 #include "util/env.h"
0021 #include <internal/lib.h>
0022 #include "util.h"
0023 
0024 #if PY_MAJOR_VERSION < 3
0025 #define _PyUnicode_FromString(arg) \
0026   PyString_FromString(arg)
0027 #define _PyUnicode_AsString(arg) \
0028   PyString_AsString(arg)
0029 #define _PyUnicode_FromFormat(...) \
0030   PyString_FromFormat(__VA_ARGS__)
0031 #define _PyLong_FromLong(arg) \
0032   PyInt_FromLong(arg)
0033 
0034 #else
0035 
0036 #define _PyUnicode_FromString(arg) \
0037   PyUnicode_FromString(arg)
0038 #define _PyUnicode_FromFormat(...) \
0039   PyUnicode_FromFormat(__VA_ARGS__)
0040 #define _PyLong_FromLong(arg) \
0041   PyLong_FromLong(arg)
0042 #endif
0043 
0044 #ifndef Py_TYPE
0045 #define Py_TYPE(ob) (((PyObject*)(ob))->ob_type)
0046 #endif
0047 
0048 /*
0049  * Provide these two so that we don't have to link against callchain.c and
0050  * start dragging hist.c, etc.
0051  */
0052 struct callchain_param callchain_param;
0053 
0054 int parse_callchain_record(const char *arg __maybe_unused,
0055                struct callchain_param *param __maybe_unused)
0056 {
0057     return 0;
0058 }
0059 
0060 /*
0061  * Add these not to drag util/env.c
0062  */
0063 struct perf_env perf_env;
0064 
0065 const char *perf_env__cpuid(struct perf_env *env __maybe_unused)
0066 {
0067     return NULL;
0068 }
0069 
0070 // This one is a bit easier, wouldn't drag too much, but leave it as a stub we need it here
0071 const char *perf_env__arch(struct perf_env *env __maybe_unused)
0072 {
0073     return NULL;
0074 }
0075 
0076 /*
0077  * Add this one here not to drag util/stat-shadow.c
0078  */
0079 void perf_stat__collect_metric_expr(struct evlist *evsel_list)
0080 {
0081 }
0082 
0083 /*
0084  * This one is needed not to drag the PMU bandwagon, jevents generated
0085  * pmu_sys_event_tables, etc and evsel__find_pmu() is used so far just for
0086  * doing per PMU perf_event_attr.exclude_guest handling, not really needed, so
0087  * far, for the perf python binding known usecases, revisit if this become
0088  * necessary.
0089  */
0090 struct perf_pmu *evsel__find_pmu(struct evsel *evsel __maybe_unused)
0091 {
0092     return NULL;
0093 }
0094 
0095 /*
0096  * Add this one here not to drag util/metricgroup.c
0097  */
0098 int metricgroup__copy_metric_events(struct evlist *evlist, struct cgroup *cgrp,
0099                     struct rblist *new_metric_events,
0100                     struct rblist *old_metric_events)
0101 {
0102     return 0;
0103 }
0104 
0105 /*
0106  * XXX: All these evsel destructors need some better mechanism, like a linked
0107  * list of destructors registered when the relevant code indeed is used instead
0108  * of having more and more calls in perf_evsel__delete(). -- acme
0109  *
0110  * For now, add some more:
0111  *
0112  * Not to drag the BPF bandwagon...
0113  */
0114 void bpf_counter__destroy(struct evsel *evsel);
0115 int bpf_counter__install_pe(struct evsel *evsel, int cpu, int fd);
0116 int bpf_counter__disable(struct evsel *evsel);
0117 
0118 void bpf_counter__destroy(struct evsel *evsel __maybe_unused)
0119 {
0120 }
0121 
0122 int bpf_counter__install_pe(struct evsel *evsel __maybe_unused, int cpu __maybe_unused, int fd __maybe_unused)
0123 {
0124     return 0;
0125 }
0126 
0127 int bpf_counter__disable(struct evsel *evsel __maybe_unused)
0128 {
0129     return 0;
0130 }
0131 
0132 /*
0133  * Support debug printing even though util/debug.c is not linked.  That means
0134  * implementing 'verbose' and 'eprintf'.
0135  */
0136 int verbose;
0137 int debug_peo_args;
0138 
0139 int eprintf(int level, int var, const char *fmt, ...);
0140 
0141 int eprintf(int level, int var, const char *fmt, ...)
0142 {
0143     va_list args;
0144     int ret = 0;
0145 
0146     if (var >= level) {
0147         va_start(args, fmt);
0148         ret = vfprintf(stderr, fmt, args);
0149         va_end(args);
0150     }
0151 
0152     return ret;
0153 }
0154 
0155 /* Define PyVarObject_HEAD_INIT for python 2.5 */
0156 #ifndef PyVarObject_HEAD_INIT
0157 # define PyVarObject_HEAD_INIT(type, size) PyObject_HEAD_INIT(type) size,
0158 #endif
0159 
0160 #if PY_MAJOR_VERSION < 3
0161 PyMODINIT_FUNC initperf(void);
0162 #else
0163 PyMODINIT_FUNC PyInit_perf(void);
0164 #endif
0165 
0166 #define member_def(type, member, ptype, help) \
0167     { #member, ptype, \
0168       offsetof(struct pyrf_event, event) + offsetof(struct type, member), \
0169       0, help }
0170 
0171 #define sample_member_def(name, member, ptype, help) \
0172     { #name, ptype, \
0173       offsetof(struct pyrf_event, sample) + offsetof(struct perf_sample, member), \
0174       0, help }
0175 
0176 struct pyrf_event {
0177     PyObject_HEAD
0178     struct evsel *evsel;
0179     struct perf_sample sample;
0180     union perf_event   event;
0181 };
0182 
0183 #define sample_members \
0184     sample_member_def(sample_ip, ip, T_ULONGLONG, "event type"),             \
0185     sample_member_def(sample_pid, pid, T_INT, "event pid"),          \
0186     sample_member_def(sample_tid, tid, T_INT, "event tid"),          \
0187     sample_member_def(sample_time, time, T_ULONGLONG, "event timestamp"),        \
0188     sample_member_def(sample_addr, addr, T_ULONGLONG, "event addr"),         \
0189     sample_member_def(sample_id, id, T_ULONGLONG, "event id"),           \
0190     sample_member_def(sample_stream_id, stream_id, T_ULONGLONG, "event stream id"), \
0191     sample_member_def(sample_period, period, T_ULONGLONG, "event period"),       \
0192     sample_member_def(sample_cpu, cpu, T_UINT, "event cpu"),
0193 
0194 static char pyrf_mmap_event__doc[] = PyDoc_STR("perf mmap event object.");
0195 
0196 static PyMemberDef pyrf_mmap_event__members[] = {
0197     sample_members
0198     member_def(perf_event_header, type, T_UINT, "event type"),
0199     member_def(perf_event_header, misc, T_UINT, "event misc"),
0200     member_def(perf_record_mmap, pid, T_UINT, "event pid"),
0201     member_def(perf_record_mmap, tid, T_UINT, "event tid"),
0202     member_def(perf_record_mmap, start, T_ULONGLONG, "start of the map"),
0203     member_def(perf_record_mmap, len, T_ULONGLONG, "map length"),
0204     member_def(perf_record_mmap, pgoff, T_ULONGLONG, "page offset"),
0205     member_def(perf_record_mmap, filename, T_STRING_INPLACE, "backing store"),
0206     { .name = NULL, },
0207 };
0208 
0209 static PyObject *pyrf_mmap_event__repr(struct pyrf_event *pevent)
0210 {
0211     PyObject *ret;
0212     char *s;
0213 
0214     if (asprintf(&s, "{ type: mmap, pid: %u, tid: %u, start: %#" PRI_lx64 ", "
0215              "length: %#" PRI_lx64 ", offset: %#" PRI_lx64 ", "
0216              "filename: %s }",
0217              pevent->event.mmap.pid, pevent->event.mmap.tid,
0218              pevent->event.mmap.start, pevent->event.mmap.len,
0219              pevent->event.mmap.pgoff, pevent->event.mmap.filename) < 0) {
0220         ret = PyErr_NoMemory();
0221     } else {
0222         ret = _PyUnicode_FromString(s);
0223         free(s);
0224     }
0225     return ret;
0226 }
0227 
0228 static PyTypeObject pyrf_mmap_event__type = {
0229     PyVarObject_HEAD_INIT(NULL, 0)
0230     .tp_name    = "perf.mmap_event",
0231     .tp_basicsize   = sizeof(struct pyrf_event),
0232     .tp_flags   = Py_TPFLAGS_DEFAULT|Py_TPFLAGS_BASETYPE,
0233     .tp_doc     = pyrf_mmap_event__doc,
0234     .tp_members = pyrf_mmap_event__members,
0235     .tp_repr    = (reprfunc)pyrf_mmap_event__repr,
0236 };
0237 
0238 static char pyrf_task_event__doc[] = PyDoc_STR("perf task (fork/exit) event object.");
0239 
0240 static PyMemberDef pyrf_task_event__members[] = {
0241     sample_members
0242     member_def(perf_event_header, type, T_UINT, "event type"),
0243     member_def(perf_record_fork, pid, T_UINT, "event pid"),
0244     member_def(perf_record_fork, ppid, T_UINT, "event ppid"),
0245     member_def(perf_record_fork, tid, T_UINT, "event tid"),
0246     member_def(perf_record_fork, ptid, T_UINT, "event ptid"),
0247     member_def(perf_record_fork, time, T_ULONGLONG, "timestamp"),
0248     { .name = NULL, },
0249 };
0250 
0251 static PyObject *pyrf_task_event__repr(struct pyrf_event *pevent)
0252 {
0253     return _PyUnicode_FromFormat("{ type: %s, pid: %u, ppid: %u, tid: %u, "
0254                    "ptid: %u, time: %" PRI_lu64 "}",
0255                    pevent->event.header.type == PERF_RECORD_FORK ? "fork" : "exit",
0256                    pevent->event.fork.pid,
0257                    pevent->event.fork.ppid,
0258                    pevent->event.fork.tid,
0259                    pevent->event.fork.ptid,
0260                    pevent->event.fork.time);
0261 }
0262 
0263 static PyTypeObject pyrf_task_event__type = {
0264     PyVarObject_HEAD_INIT(NULL, 0)
0265     .tp_name    = "perf.task_event",
0266     .tp_basicsize   = sizeof(struct pyrf_event),
0267     .tp_flags   = Py_TPFLAGS_DEFAULT|Py_TPFLAGS_BASETYPE,
0268     .tp_doc     = pyrf_task_event__doc,
0269     .tp_members = pyrf_task_event__members,
0270     .tp_repr    = (reprfunc)pyrf_task_event__repr,
0271 };
0272 
0273 static char pyrf_comm_event__doc[] = PyDoc_STR("perf comm event object.");
0274 
0275 static PyMemberDef pyrf_comm_event__members[] = {
0276     sample_members
0277     member_def(perf_event_header, type, T_UINT, "event type"),
0278     member_def(perf_record_comm, pid, T_UINT, "event pid"),
0279     member_def(perf_record_comm, tid, T_UINT, "event tid"),
0280     member_def(perf_record_comm, comm, T_STRING_INPLACE, "process name"),
0281     { .name = NULL, },
0282 };
0283 
0284 static PyObject *pyrf_comm_event__repr(struct pyrf_event *pevent)
0285 {
0286     return _PyUnicode_FromFormat("{ type: comm, pid: %u, tid: %u, comm: %s }",
0287                    pevent->event.comm.pid,
0288                    pevent->event.comm.tid,
0289                    pevent->event.comm.comm);
0290 }
0291 
0292 static PyTypeObject pyrf_comm_event__type = {
0293     PyVarObject_HEAD_INIT(NULL, 0)
0294     .tp_name    = "perf.comm_event",
0295     .tp_basicsize   = sizeof(struct pyrf_event),
0296     .tp_flags   = Py_TPFLAGS_DEFAULT|Py_TPFLAGS_BASETYPE,
0297     .tp_doc     = pyrf_comm_event__doc,
0298     .tp_members = pyrf_comm_event__members,
0299     .tp_repr    = (reprfunc)pyrf_comm_event__repr,
0300 };
0301 
0302 static char pyrf_throttle_event__doc[] = PyDoc_STR("perf throttle event object.");
0303 
0304 static PyMemberDef pyrf_throttle_event__members[] = {
0305     sample_members
0306     member_def(perf_event_header, type, T_UINT, "event type"),
0307     member_def(perf_record_throttle, time, T_ULONGLONG, "timestamp"),
0308     member_def(perf_record_throttle, id, T_ULONGLONG, "event id"),
0309     member_def(perf_record_throttle, stream_id, T_ULONGLONG, "event stream id"),
0310     { .name = NULL, },
0311 };
0312 
0313 static PyObject *pyrf_throttle_event__repr(struct pyrf_event *pevent)
0314 {
0315     struct perf_record_throttle *te = (struct perf_record_throttle *)(&pevent->event.header + 1);
0316 
0317     return _PyUnicode_FromFormat("{ type: %sthrottle, time: %" PRI_lu64 ", id: %" PRI_lu64
0318                    ", stream_id: %" PRI_lu64 " }",
0319                    pevent->event.header.type == PERF_RECORD_THROTTLE ? "" : "un",
0320                    te->time, te->id, te->stream_id);
0321 }
0322 
0323 static PyTypeObject pyrf_throttle_event__type = {
0324     PyVarObject_HEAD_INIT(NULL, 0)
0325     .tp_name    = "perf.throttle_event",
0326     .tp_basicsize   = sizeof(struct pyrf_event),
0327     .tp_flags   = Py_TPFLAGS_DEFAULT|Py_TPFLAGS_BASETYPE,
0328     .tp_doc     = pyrf_throttle_event__doc,
0329     .tp_members = pyrf_throttle_event__members,
0330     .tp_repr    = (reprfunc)pyrf_throttle_event__repr,
0331 };
0332 
0333 static char pyrf_lost_event__doc[] = PyDoc_STR("perf lost event object.");
0334 
0335 static PyMemberDef pyrf_lost_event__members[] = {
0336     sample_members
0337     member_def(perf_record_lost, id, T_ULONGLONG, "event id"),
0338     member_def(perf_record_lost, lost, T_ULONGLONG, "number of lost events"),
0339     { .name = NULL, },
0340 };
0341 
0342 static PyObject *pyrf_lost_event__repr(struct pyrf_event *pevent)
0343 {
0344     PyObject *ret;
0345     char *s;
0346 
0347     if (asprintf(&s, "{ type: lost, id: %#" PRI_lx64 ", "
0348              "lost: %#" PRI_lx64 " }",
0349              pevent->event.lost.id, pevent->event.lost.lost) < 0) {
0350         ret = PyErr_NoMemory();
0351     } else {
0352         ret = _PyUnicode_FromString(s);
0353         free(s);
0354     }
0355     return ret;
0356 }
0357 
0358 static PyTypeObject pyrf_lost_event__type = {
0359     PyVarObject_HEAD_INIT(NULL, 0)
0360     .tp_name    = "perf.lost_event",
0361     .tp_basicsize   = sizeof(struct pyrf_event),
0362     .tp_flags   = Py_TPFLAGS_DEFAULT|Py_TPFLAGS_BASETYPE,
0363     .tp_doc     = pyrf_lost_event__doc,
0364     .tp_members = pyrf_lost_event__members,
0365     .tp_repr    = (reprfunc)pyrf_lost_event__repr,
0366 };
0367 
0368 static char pyrf_read_event__doc[] = PyDoc_STR("perf read event object.");
0369 
0370 static PyMemberDef pyrf_read_event__members[] = {
0371     sample_members
0372     member_def(perf_record_read, pid, T_UINT, "event pid"),
0373     member_def(perf_record_read, tid, T_UINT, "event tid"),
0374     { .name = NULL, },
0375 };
0376 
0377 static PyObject *pyrf_read_event__repr(struct pyrf_event *pevent)
0378 {
0379     return _PyUnicode_FromFormat("{ type: read, pid: %u, tid: %u }",
0380                    pevent->event.read.pid,
0381                    pevent->event.read.tid);
0382     /*
0383      * FIXME: return the array of read values,
0384      * making this method useful ;-)
0385      */
0386 }
0387 
0388 static PyTypeObject pyrf_read_event__type = {
0389     PyVarObject_HEAD_INIT(NULL, 0)
0390     .tp_name    = "perf.read_event",
0391     .tp_basicsize   = sizeof(struct pyrf_event),
0392     .tp_flags   = Py_TPFLAGS_DEFAULT|Py_TPFLAGS_BASETYPE,
0393     .tp_doc     = pyrf_read_event__doc,
0394     .tp_members = pyrf_read_event__members,
0395     .tp_repr    = (reprfunc)pyrf_read_event__repr,
0396 };
0397 
0398 static char pyrf_sample_event__doc[] = PyDoc_STR("perf sample event object.");
0399 
0400 static PyMemberDef pyrf_sample_event__members[] = {
0401     sample_members
0402     member_def(perf_event_header, type, T_UINT, "event type"),
0403     { .name = NULL, },
0404 };
0405 
0406 static PyObject *pyrf_sample_event__repr(struct pyrf_event *pevent)
0407 {
0408     PyObject *ret;
0409     char *s;
0410 
0411     if (asprintf(&s, "{ type: sample }") < 0) {
0412         ret = PyErr_NoMemory();
0413     } else {
0414         ret = _PyUnicode_FromString(s);
0415         free(s);
0416     }
0417     return ret;
0418 }
0419 
0420 static bool is_tracepoint(struct pyrf_event *pevent)
0421 {
0422     return pevent->evsel->core.attr.type == PERF_TYPE_TRACEPOINT;
0423 }
0424 
0425 static PyObject*
0426 tracepoint_field(struct pyrf_event *pe, struct tep_format_field *field)
0427 {
0428     struct tep_handle *pevent = field->event->tep;
0429     void *data = pe->sample.raw_data;
0430     PyObject *ret = NULL;
0431     unsigned long long val;
0432     unsigned int offset, len;
0433 
0434     if (field->flags & TEP_FIELD_IS_ARRAY) {
0435         offset = field->offset;
0436         len    = field->size;
0437         if (field->flags & TEP_FIELD_IS_DYNAMIC) {
0438             val     = tep_read_number(pevent, data + offset, len);
0439             offset  = val;
0440             len     = offset >> 16;
0441             offset &= 0xffff;
0442             if (field->flags & TEP_FIELD_IS_RELATIVE)
0443                 offset += field->offset + field->size;
0444         }
0445         if (field->flags & TEP_FIELD_IS_STRING &&
0446             is_printable_array(data + offset, len)) {
0447             ret = _PyUnicode_FromString((char *)data + offset);
0448         } else {
0449             ret = PyByteArray_FromStringAndSize((const char *) data + offset, len);
0450             field->flags &= ~TEP_FIELD_IS_STRING;
0451         }
0452     } else {
0453         val = tep_read_number(pevent, data + field->offset,
0454                       field->size);
0455         if (field->flags & TEP_FIELD_IS_POINTER)
0456             ret = PyLong_FromUnsignedLong((unsigned long) val);
0457         else if (field->flags & TEP_FIELD_IS_SIGNED)
0458             ret = PyLong_FromLong((long) val);
0459         else
0460             ret = PyLong_FromUnsignedLong((unsigned long) val);
0461     }
0462 
0463     return ret;
0464 }
0465 
0466 static PyObject*
0467 get_tracepoint_field(struct pyrf_event *pevent, PyObject *attr_name)
0468 {
0469     const char *str = _PyUnicode_AsString(PyObject_Str(attr_name));
0470     struct evsel *evsel = pevent->evsel;
0471     struct tep_format_field *field;
0472 
0473     if (!evsel->tp_format) {
0474         struct tep_event *tp_format;
0475 
0476         tp_format = trace_event__tp_format_id(evsel->core.attr.config);
0477         if (IS_ERR_OR_NULL(tp_format))
0478             return NULL;
0479 
0480         evsel->tp_format = tp_format;
0481     }
0482 
0483     field = tep_find_any_field(evsel->tp_format, str);
0484     if (!field)
0485         return NULL;
0486 
0487     return tracepoint_field(pevent, field);
0488 }
0489 
0490 static PyObject*
0491 pyrf_sample_event__getattro(struct pyrf_event *pevent, PyObject *attr_name)
0492 {
0493     PyObject *obj = NULL;
0494 
0495     if (is_tracepoint(pevent))
0496         obj = get_tracepoint_field(pevent, attr_name);
0497 
0498     return obj ?: PyObject_GenericGetAttr((PyObject *) pevent, attr_name);
0499 }
0500 
0501 static PyTypeObject pyrf_sample_event__type = {
0502     PyVarObject_HEAD_INIT(NULL, 0)
0503     .tp_name    = "perf.sample_event",
0504     .tp_basicsize   = sizeof(struct pyrf_event),
0505     .tp_flags   = Py_TPFLAGS_DEFAULT|Py_TPFLAGS_BASETYPE,
0506     .tp_doc     = pyrf_sample_event__doc,
0507     .tp_members = pyrf_sample_event__members,
0508     .tp_repr    = (reprfunc)pyrf_sample_event__repr,
0509     .tp_getattro    = (getattrofunc) pyrf_sample_event__getattro,
0510 };
0511 
0512 static char pyrf_context_switch_event__doc[] = PyDoc_STR("perf context_switch event object.");
0513 
0514 static PyMemberDef pyrf_context_switch_event__members[] = {
0515     sample_members
0516     member_def(perf_event_header, type, T_UINT, "event type"),
0517     member_def(perf_record_switch, next_prev_pid, T_UINT, "next/prev pid"),
0518     member_def(perf_record_switch, next_prev_tid, T_UINT, "next/prev tid"),
0519     { .name = NULL, },
0520 };
0521 
0522 static PyObject *pyrf_context_switch_event__repr(struct pyrf_event *pevent)
0523 {
0524     PyObject *ret;
0525     char *s;
0526 
0527     if (asprintf(&s, "{ type: context_switch, next_prev_pid: %u, next_prev_tid: %u, switch_out: %u }",
0528              pevent->event.context_switch.next_prev_pid,
0529              pevent->event.context_switch.next_prev_tid,
0530              !!(pevent->event.header.misc & PERF_RECORD_MISC_SWITCH_OUT)) < 0) {
0531         ret = PyErr_NoMemory();
0532     } else {
0533         ret = _PyUnicode_FromString(s);
0534         free(s);
0535     }
0536     return ret;
0537 }
0538 
0539 static PyTypeObject pyrf_context_switch_event__type = {
0540     PyVarObject_HEAD_INIT(NULL, 0)
0541     .tp_name    = "perf.context_switch_event",
0542     .tp_basicsize   = sizeof(struct pyrf_event),
0543     .tp_flags   = Py_TPFLAGS_DEFAULT|Py_TPFLAGS_BASETYPE,
0544     .tp_doc     = pyrf_context_switch_event__doc,
0545     .tp_members = pyrf_context_switch_event__members,
0546     .tp_repr    = (reprfunc)pyrf_context_switch_event__repr,
0547 };
0548 
0549 static int pyrf_event__setup_types(void)
0550 {
0551     int err;
0552     pyrf_mmap_event__type.tp_new =
0553     pyrf_task_event__type.tp_new =
0554     pyrf_comm_event__type.tp_new =
0555     pyrf_lost_event__type.tp_new =
0556     pyrf_read_event__type.tp_new =
0557     pyrf_sample_event__type.tp_new =
0558     pyrf_context_switch_event__type.tp_new =
0559     pyrf_throttle_event__type.tp_new = PyType_GenericNew;
0560     err = PyType_Ready(&pyrf_mmap_event__type);
0561     if (err < 0)
0562         goto out;
0563     err = PyType_Ready(&pyrf_lost_event__type);
0564     if (err < 0)
0565         goto out;
0566     err = PyType_Ready(&pyrf_task_event__type);
0567     if (err < 0)
0568         goto out;
0569     err = PyType_Ready(&pyrf_comm_event__type);
0570     if (err < 0)
0571         goto out;
0572     err = PyType_Ready(&pyrf_throttle_event__type);
0573     if (err < 0)
0574         goto out;
0575     err = PyType_Ready(&pyrf_read_event__type);
0576     if (err < 0)
0577         goto out;
0578     err = PyType_Ready(&pyrf_sample_event__type);
0579     if (err < 0)
0580         goto out;
0581     err = PyType_Ready(&pyrf_context_switch_event__type);
0582     if (err < 0)
0583         goto out;
0584 out:
0585     return err;
0586 }
0587 
0588 static PyTypeObject *pyrf_event__type[] = {
0589     [PERF_RECORD_MMAP]   = &pyrf_mmap_event__type,
0590     [PERF_RECORD_LOST]   = &pyrf_lost_event__type,
0591     [PERF_RECORD_COMM]   = &pyrf_comm_event__type,
0592     [PERF_RECORD_EXIT]   = &pyrf_task_event__type,
0593     [PERF_RECORD_THROTTLE]   = &pyrf_throttle_event__type,
0594     [PERF_RECORD_UNTHROTTLE] = &pyrf_throttle_event__type,
0595     [PERF_RECORD_FORK]   = &pyrf_task_event__type,
0596     [PERF_RECORD_READ]   = &pyrf_read_event__type,
0597     [PERF_RECORD_SAMPLE]     = &pyrf_sample_event__type,
0598     [PERF_RECORD_SWITCH]     = &pyrf_context_switch_event__type,
0599     [PERF_RECORD_SWITCH_CPU_WIDE]  = &pyrf_context_switch_event__type,
0600 };
0601 
0602 static PyObject *pyrf_event__new(union perf_event *event)
0603 {
0604     struct pyrf_event *pevent;
0605     PyTypeObject *ptype;
0606 
0607     if ((event->header.type < PERF_RECORD_MMAP ||
0608          event->header.type > PERF_RECORD_SAMPLE) &&
0609         !(event->header.type == PERF_RECORD_SWITCH ||
0610           event->header.type == PERF_RECORD_SWITCH_CPU_WIDE))
0611         return NULL;
0612 
0613     ptype = pyrf_event__type[event->header.type];
0614     pevent = PyObject_New(struct pyrf_event, ptype);
0615     if (pevent != NULL)
0616         memcpy(&pevent->event, event, event->header.size);
0617     return (PyObject *)pevent;
0618 }
0619 
0620 struct pyrf_cpu_map {
0621     PyObject_HEAD
0622 
0623     struct perf_cpu_map *cpus;
0624 };
0625 
0626 static int pyrf_cpu_map__init(struct pyrf_cpu_map *pcpus,
0627                   PyObject *args, PyObject *kwargs)
0628 {
0629     static char *kwlist[] = { "cpustr", NULL };
0630     char *cpustr = NULL;
0631 
0632     if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|s",
0633                      kwlist, &cpustr))
0634         return -1;
0635 
0636     pcpus->cpus = perf_cpu_map__new(cpustr);
0637     if (pcpus->cpus == NULL)
0638         return -1;
0639     return 0;
0640 }
0641 
0642 static void pyrf_cpu_map__delete(struct pyrf_cpu_map *pcpus)
0643 {
0644     perf_cpu_map__put(pcpus->cpus);
0645     Py_TYPE(pcpus)->tp_free((PyObject*)pcpus);
0646 }
0647 
0648 static Py_ssize_t pyrf_cpu_map__length(PyObject *obj)
0649 {
0650     struct pyrf_cpu_map *pcpus = (void *)obj;
0651 
0652     return perf_cpu_map__nr(pcpus->cpus);
0653 }
0654 
0655 static PyObject *pyrf_cpu_map__item(PyObject *obj, Py_ssize_t i)
0656 {
0657     struct pyrf_cpu_map *pcpus = (void *)obj;
0658 
0659     if (i >= perf_cpu_map__nr(pcpus->cpus))
0660         return NULL;
0661 
0662     return Py_BuildValue("i", perf_cpu_map__cpu(pcpus->cpus, i).cpu);
0663 }
0664 
0665 static PySequenceMethods pyrf_cpu_map__sequence_methods = {
0666     .sq_length = pyrf_cpu_map__length,
0667     .sq_item   = pyrf_cpu_map__item,
0668 };
0669 
0670 static char pyrf_cpu_map__doc[] = PyDoc_STR("cpu map object.");
0671 
0672 static PyTypeObject pyrf_cpu_map__type = {
0673     PyVarObject_HEAD_INIT(NULL, 0)
0674     .tp_name    = "perf.cpu_map",
0675     .tp_basicsize   = sizeof(struct pyrf_cpu_map),
0676     .tp_dealloc = (destructor)pyrf_cpu_map__delete,
0677     .tp_flags   = Py_TPFLAGS_DEFAULT|Py_TPFLAGS_BASETYPE,
0678     .tp_doc     = pyrf_cpu_map__doc,
0679     .tp_as_sequence = &pyrf_cpu_map__sequence_methods,
0680     .tp_init    = (initproc)pyrf_cpu_map__init,
0681 };
0682 
0683 static int pyrf_cpu_map__setup_types(void)
0684 {
0685     pyrf_cpu_map__type.tp_new = PyType_GenericNew;
0686     return PyType_Ready(&pyrf_cpu_map__type);
0687 }
0688 
0689 struct pyrf_thread_map {
0690     PyObject_HEAD
0691 
0692     struct perf_thread_map *threads;
0693 };
0694 
0695 static int pyrf_thread_map__init(struct pyrf_thread_map *pthreads,
0696                  PyObject *args, PyObject *kwargs)
0697 {
0698     static char *kwlist[] = { "pid", "tid", "uid", NULL };
0699     int pid = -1, tid = -1, uid = UINT_MAX;
0700 
0701     if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|iii",
0702                      kwlist, &pid, &tid, &uid))
0703         return -1;
0704 
0705     pthreads->threads = thread_map__new(pid, tid, uid);
0706     if (pthreads->threads == NULL)
0707         return -1;
0708     return 0;
0709 }
0710 
0711 static void pyrf_thread_map__delete(struct pyrf_thread_map *pthreads)
0712 {
0713     perf_thread_map__put(pthreads->threads);
0714     Py_TYPE(pthreads)->tp_free((PyObject*)pthreads);
0715 }
0716 
0717 static Py_ssize_t pyrf_thread_map__length(PyObject *obj)
0718 {
0719     struct pyrf_thread_map *pthreads = (void *)obj;
0720 
0721     return pthreads->threads->nr;
0722 }
0723 
0724 static PyObject *pyrf_thread_map__item(PyObject *obj, Py_ssize_t i)
0725 {
0726     struct pyrf_thread_map *pthreads = (void *)obj;
0727 
0728     if (i >= pthreads->threads->nr)
0729         return NULL;
0730 
0731     return Py_BuildValue("i", pthreads->threads->map[i]);
0732 }
0733 
0734 static PySequenceMethods pyrf_thread_map__sequence_methods = {
0735     .sq_length = pyrf_thread_map__length,
0736     .sq_item   = pyrf_thread_map__item,
0737 };
0738 
0739 static char pyrf_thread_map__doc[] = PyDoc_STR("thread map object.");
0740 
0741 static PyTypeObject pyrf_thread_map__type = {
0742     PyVarObject_HEAD_INIT(NULL, 0)
0743     .tp_name    = "perf.thread_map",
0744     .tp_basicsize   = sizeof(struct pyrf_thread_map),
0745     .tp_dealloc = (destructor)pyrf_thread_map__delete,
0746     .tp_flags   = Py_TPFLAGS_DEFAULT|Py_TPFLAGS_BASETYPE,
0747     .tp_doc     = pyrf_thread_map__doc,
0748     .tp_as_sequence = &pyrf_thread_map__sequence_methods,
0749     .tp_init    = (initproc)pyrf_thread_map__init,
0750 };
0751 
0752 static int pyrf_thread_map__setup_types(void)
0753 {
0754     pyrf_thread_map__type.tp_new = PyType_GenericNew;
0755     return PyType_Ready(&pyrf_thread_map__type);
0756 }
0757 
0758 struct pyrf_evsel {
0759     PyObject_HEAD
0760 
0761     struct evsel evsel;
0762 };
0763 
0764 static int pyrf_evsel__init(struct pyrf_evsel *pevsel,
0765                 PyObject *args, PyObject *kwargs)
0766 {
0767     struct perf_event_attr attr = {
0768         .type = PERF_TYPE_HARDWARE,
0769         .config = PERF_COUNT_HW_CPU_CYCLES,
0770         .sample_type = PERF_SAMPLE_PERIOD | PERF_SAMPLE_TID,
0771     };
0772     static char *kwlist[] = {
0773         "type",
0774         "config",
0775         "sample_freq",
0776         "sample_period",
0777         "sample_type",
0778         "read_format",
0779         "disabled",
0780         "inherit",
0781         "pinned",
0782         "exclusive",
0783         "exclude_user",
0784         "exclude_kernel",
0785         "exclude_hv",
0786         "exclude_idle",
0787         "mmap",
0788         "context_switch",
0789         "comm",
0790         "freq",
0791         "inherit_stat",
0792         "enable_on_exec",
0793         "task",
0794         "watermark",
0795         "precise_ip",
0796         "mmap_data",
0797         "sample_id_all",
0798         "wakeup_events",
0799         "bp_type",
0800         "bp_addr",
0801         "bp_len",
0802          NULL
0803     };
0804     u64 sample_period = 0;
0805     u32 disabled = 0,
0806         inherit = 0,
0807         pinned = 0,
0808         exclusive = 0,
0809         exclude_user = 0,
0810         exclude_kernel = 0,
0811         exclude_hv = 0,
0812         exclude_idle = 0,
0813         mmap = 0,
0814         context_switch = 0,
0815         comm = 0,
0816         freq = 1,
0817         inherit_stat = 0,
0818         enable_on_exec = 0,
0819         task = 0,
0820         watermark = 0,
0821         precise_ip = 0,
0822         mmap_data = 0,
0823         sample_id_all = 1;
0824     int idx = 0;
0825 
0826     if (!PyArg_ParseTupleAndKeywords(args, kwargs,
0827                      "|iKiKKiiiiiiiiiiiiiiiiiiiiiiKK", kwlist,
0828                      &attr.type, &attr.config, &attr.sample_freq,
0829                      &sample_period, &attr.sample_type,
0830                      &attr.read_format, &disabled, &inherit,
0831                      &pinned, &exclusive, &exclude_user,
0832                      &exclude_kernel, &exclude_hv, &exclude_idle,
0833                      &mmap, &context_switch, &comm, &freq, &inherit_stat,
0834                      &enable_on_exec, &task, &watermark,
0835                      &precise_ip, &mmap_data, &sample_id_all,
0836                      &attr.wakeup_events, &attr.bp_type,
0837                      &attr.bp_addr, &attr.bp_len, &idx))
0838         return -1;
0839 
0840     /* union... */
0841     if (sample_period != 0) {
0842         if (attr.sample_freq != 0)
0843             return -1; /* FIXME: throw right exception */
0844         attr.sample_period = sample_period;
0845     }
0846 
0847     /* Bitfields */
0848     attr.disabled       = disabled;
0849     attr.inherit        = inherit;
0850     attr.pinned     = pinned;
0851     attr.exclusive      = exclusive;
0852     attr.exclude_user   = exclude_user;
0853     attr.exclude_kernel = exclude_kernel;
0854     attr.exclude_hv     = exclude_hv;
0855     attr.exclude_idle   = exclude_idle;
0856     attr.mmap       = mmap;
0857     attr.context_switch = context_switch;
0858     attr.comm       = comm;
0859     attr.freq       = freq;
0860     attr.inherit_stat   = inherit_stat;
0861     attr.enable_on_exec = enable_on_exec;
0862     attr.task       = task;
0863     attr.watermark      = watermark;
0864     attr.precise_ip     = precise_ip;
0865     attr.mmap_data      = mmap_data;
0866     attr.sample_id_all  = sample_id_all;
0867     attr.size       = sizeof(attr);
0868 
0869     evsel__init(&pevsel->evsel, &attr, idx);
0870     return 0;
0871 }
0872 
0873 static void pyrf_evsel__delete(struct pyrf_evsel *pevsel)
0874 {
0875     evsel__exit(&pevsel->evsel);
0876     Py_TYPE(pevsel)->tp_free((PyObject*)pevsel);
0877 }
0878 
0879 static PyObject *pyrf_evsel__open(struct pyrf_evsel *pevsel,
0880                   PyObject *args, PyObject *kwargs)
0881 {
0882     struct evsel *evsel = &pevsel->evsel;
0883     struct perf_cpu_map *cpus = NULL;
0884     struct perf_thread_map *threads = NULL;
0885     PyObject *pcpus = NULL, *pthreads = NULL;
0886     int group = 0, inherit = 0;
0887     static char *kwlist[] = { "cpus", "threads", "group", "inherit", NULL };
0888 
0889     if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|OOii", kwlist,
0890                      &pcpus, &pthreads, &group, &inherit))
0891         return NULL;
0892 
0893     if (pthreads != NULL)
0894         threads = ((struct pyrf_thread_map *)pthreads)->threads;
0895 
0896     if (pcpus != NULL)
0897         cpus = ((struct pyrf_cpu_map *)pcpus)->cpus;
0898 
0899     evsel->core.attr.inherit = inherit;
0900     /*
0901      * This will group just the fds for this single evsel, to group
0902      * multiple events, use evlist.open().
0903      */
0904     if (evsel__open(evsel, cpus, threads) < 0) {
0905         PyErr_SetFromErrno(PyExc_OSError);
0906         return NULL;
0907     }
0908 
0909     Py_INCREF(Py_None);
0910     return Py_None;
0911 }
0912 
0913 static PyMethodDef pyrf_evsel__methods[] = {
0914     {
0915         .ml_name  = "open",
0916         .ml_meth  = (PyCFunction)pyrf_evsel__open,
0917         .ml_flags = METH_VARARGS | METH_KEYWORDS,
0918         .ml_doc   = PyDoc_STR("open the event selector file descriptor table.")
0919     },
0920     { .ml_name = NULL, }
0921 };
0922 
0923 static char pyrf_evsel__doc[] = PyDoc_STR("perf event selector list object.");
0924 
0925 static PyTypeObject pyrf_evsel__type = {
0926     PyVarObject_HEAD_INIT(NULL, 0)
0927     .tp_name    = "perf.evsel",
0928     .tp_basicsize   = sizeof(struct pyrf_evsel),
0929     .tp_dealloc = (destructor)pyrf_evsel__delete,
0930     .tp_flags   = Py_TPFLAGS_DEFAULT|Py_TPFLAGS_BASETYPE,
0931     .tp_doc     = pyrf_evsel__doc,
0932     .tp_methods = pyrf_evsel__methods,
0933     .tp_init    = (initproc)pyrf_evsel__init,
0934 };
0935 
0936 static int pyrf_evsel__setup_types(void)
0937 {
0938     pyrf_evsel__type.tp_new = PyType_GenericNew;
0939     return PyType_Ready(&pyrf_evsel__type);
0940 }
0941 
0942 struct pyrf_evlist {
0943     PyObject_HEAD
0944 
0945     struct evlist evlist;
0946 };
0947 
0948 static int pyrf_evlist__init(struct pyrf_evlist *pevlist,
0949                  PyObject *args, PyObject *kwargs __maybe_unused)
0950 {
0951     PyObject *pcpus = NULL, *pthreads = NULL;
0952     struct perf_cpu_map *cpus;
0953     struct perf_thread_map *threads;
0954 
0955     if (!PyArg_ParseTuple(args, "OO", &pcpus, &pthreads))
0956         return -1;
0957 
0958     threads = ((struct pyrf_thread_map *)pthreads)->threads;
0959     cpus = ((struct pyrf_cpu_map *)pcpus)->cpus;
0960     evlist__init(&pevlist->evlist, cpus, threads);
0961     return 0;
0962 }
0963 
0964 static void pyrf_evlist__delete(struct pyrf_evlist *pevlist)
0965 {
0966     evlist__exit(&pevlist->evlist);
0967     Py_TYPE(pevlist)->tp_free((PyObject*)pevlist);
0968 }
0969 
0970 static PyObject *pyrf_evlist__mmap(struct pyrf_evlist *pevlist,
0971                    PyObject *args, PyObject *kwargs)
0972 {
0973     struct evlist *evlist = &pevlist->evlist;
0974     static char *kwlist[] = { "pages", "overwrite", NULL };
0975     int pages = 128, overwrite = false;
0976 
0977     if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|ii", kwlist,
0978                      &pages, &overwrite))
0979         return NULL;
0980 
0981     if (evlist__mmap(evlist, pages) < 0) {
0982         PyErr_SetFromErrno(PyExc_OSError);
0983         return NULL;
0984     }
0985 
0986     Py_INCREF(Py_None);
0987     return Py_None;
0988 }
0989 
0990 static PyObject *pyrf_evlist__poll(struct pyrf_evlist *pevlist,
0991                    PyObject *args, PyObject *kwargs)
0992 {
0993     struct evlist *evlist = &pevlist->evlist;
0994     static char *kwlist[] = { "timeout", NULL };
0995     int timeout = -1, n;
0996 
0997     if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|i", kwlist, &timeout))
0998         return NULL;
0999 
1000     n = evlist__poll(evlist, timeout);
1001     if (n < 0) {
1002         PyErr_SetFromErrno(PyExc_OSError);
1003         return NULL;
1004     }
1005 
1006     return Py_BuildValue("i", n);
1007 }
1008 
1009 static PyObject *pyrf_evlist__get_pollfd(struct pyrf_evlist *pevlist,
1010                      PyObject *args __maybe_unused,
1011                      PyObject *kwargs __maybe_unused)
1012 {
1013     struct evlist *evlist = &pevlist->evlist;
1014         PyObject *list = PyList_New(0);
1015     int i;
1016 
1017     for (i = 0; i < evlist->core.pollfd.nr; ++i) {
1018         PyObject *file;
1019 #if PY_MAJOR_VERSION < 3
1020         FILE *fp = fdopen(evlist->core.pollfd.entries[i].fd, "r");
1021 
1022         if (fp == NULL)
1023             goto free_list;
1024 
1025         file = PyFile_FromFile(fp, "perf", "r", NULL);
1026 #else
1027         file = PyFile_FromFd(evlist->core.pollfd.entries[i].fd, "perf", "r", -1,
1028                      NULL, NULL, NULL, 0);
1029 #endif
1030         if (file == NULL)
1031             goto free_list;
1032 
1033         if (PyList_Append(list, file) != 0) {
1034             Py_DECREF(file);
1035             goto free_list;
1036         }
1037 
1038         Py_DECREF(file);
1039     }
1040 
1041     return list;
1042 free_list:
1043     return PyErr_NoMemory();
1044 }
1045 
1046 
1047 static PyObject *pyrf_evlist__add(struct pyrf_evlist *pevlist,
1048                   PyObject *args,
1049                   PyObject *kwargs __maybe_unused)
1050 {
1051     struct evlist *evlist = &pevlist->evlist;
1052     PyObject *pevsel;
1053     struct evsel *evsel;
1054 
1055     if (!PyArg_ParseTuple(args, "O", &pevsel))
1056         return NULL;
1057 
1058     Py_INCREF(pevsel);
1059     evsel = &((struct pyrf_evsel *)pevsel)->evsel;
1060     evsel->core.idx = evlist->core.nr_entries;
1061     evlist__add(evlist, evsel);
1062 
1063     return Py_BuildValue("i", evlist->core.nr_entries);
1064 }
1065 
1066 static struct mmap *get_md(struct evlist *evlist, int cpu)
1067 {
1068     int i;
1069 
1070     for (i = 0; i < evlist->core.nr_mmaps; i++) {
1071         struct mmap *md = &evlist->mmap[i];
1072 
1073         if (md->core.cpu.cpu == cpu)
1074             return md;
1075     }
1076 
1077     return NULL;
1078 }
1079 
1080 static PyObject *pyrf_evlist__read_on_cpu(struct pyrf_evlist *pevlist,
1081                       PyObject *args, PyObject *kwargs)
1082 {
1083     struct evlist *evlist = &pevlist->evlist;
1084     union perf_event *event;
1085     int sample_id_all = 1, cpu;
1086     static char *kwlist[] = { "cpu", "sample_id_all", NULL };
1087     struct mmap *md;
1088     int err;
1089 
1090     if (!PyArg_ParseTupleAndKeywords(args, kwargs, "i|i", kwlist,
1091                      &cpu, &sample_id_all))
1092         return NULL;
1093 
1094     md = get_md(evlist, cpu);
1095     if (!md)
1096         return NULL;
1097 
1098     if (perf_mmap__read_init(&md->core) < 0)
1099         goto end;
1100 
1101     event = perf_mmap__read_event(&md->core);
1102     if (event != NULL) {
1103         PyObject *pyevent = pyrf_event__new(event);
1104         struct pyrf_event *pevent = (struct pyrf_event *)pyevent;
1105         struct evsel *evsel;
1106 
1107         if (pyevent == NULL)
1108             return PyErr_NoMemory();
1109 
1110         evsel = evlist__event2evsel(evlist, event);
1111         if (!evsel) {
1112             Py_INCREF(Py_None);
1113             return Py_None;
1114         }
1115 
1116         pevent->evsel = evsel;
1117 
1118         err = evsel__parse_sample(evsel, event, &pevent->sample);
1119 
1120         /* Consume the even only after we parsed it out. */
1121         perf_mmap__consume(&md->core);
1122 
1123         if (err)
1124             return PyErr_Format(PyExc_OSError,
1125                         "perf: can't parse sample, err=%d", err);
1126         return pyevent;
1127     }
1128 end:
1129     Py_INCREF(Py_None);
1130     return Py_None;
1131 }
1132 
1133 static PyObject *pyrf_evlist__open(struct pyrf_evlist *pevlist,
1134                    PyObject *args, PyObject *kwargs)
1135 {
1136     struct evlist *evlist = &pevlist->evlist;
1137     int group = 0;
1138     static char *kwlist[] = { "group", NULL };
1139 
1140     if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|OOii", kwlist, &group))
1141         return NULL;
1142 
1143     if (group)
1144         evlist__set_leader(evlist);
1145 
1146     if (evlist__open(evlist) < 0) {
1147         PyErr_SetFromErrno(PyExc_OSError);
1148         return NULL;
1149     }
1150 
1151     Py_INCREF(Py_None);
1152     return Py_None;
1153 }
1154 
1155 static PyMethodDef pyrf_evlist__methods[] = {
1156     {
1157         .ml_name  = "mmap",
1158         .ml_meth  = (PyCFunction)pyrf_evlist__mmap,
1159         .ml_flags = METH_VARARGS | METH_KEYWORDS,
1160         .ml_doc   = PyDoc_STR("mmap the file descriptor table.")
1161     },
1162     {
1163         .ml_name  = "open",
1164         .ml_meth  = (PyCFunction)pyrf_evlist__open,
1165         .ml_flags = METH_VARARGS | METH_KEYWORDS,
1166         .ml_doc   = PyDoc_STR("open the file descriptors.")
1167     },
1168     {
1169         .ml_name  = "poll",
1170         .ml_meth  = (PyCFunction)pyrf_evlist__poll,
1171         .ml_flags = METH_VARARGS | METH_KEYWORDS,
1172         .ml_doc   = PyDoc_STR("poll the file descriptor table.")
1173     },
1174     {
1175         .ml_name  = "get_pollfd",
1176         .ml_meth  = (PyCFunction)pyrf_evlist__get_pollfd,
1177         .ml_flags = METH_VARARGS | METH_KEYWORDS,
1178         .ml_doc   = PyDoc_STR("get the poll file descriptor table.")
1179     },
1180     {
1181         .ml_name  = "add",
1182         .ml_meth  = (PyCFunction)pyrf_evlist__add,
1183         .ml_flags = METH_VARARGS | METH_KEYWORDS,
1184         .ml_doc   = PyDoc_STR("adds an event selector to the list.")
1185     },
1186     {
1187         .ml_name  = "read_on_cpu",
1188         .ml_meth  = (PyCFunction)pyrf_evlist__read_on_cpu,
1189         .ml_flags = METH_VARARGS | METH_KEYWORDS,
1190         .ml_doc   = PyDoc_STR("reads an event.")
1191     },
1192     { .ml_name = NULL, }
1193 };
1194 
1195 static Py_ssize_t pyrf_evlist__length(PyObject *obj)
1196 {
1197     struct pyrf_evlist *pevlist = (void *)obj;
1198 
1199     return pevlist->evlist.core.nr_entries;
1200 }
1201 
1202 static PyObject *pyrf_evlist__item(PyObject *obj, Py_ssize_t i)
1203 {
1204     struct pyrf_evlist *pevlist = (void *)obj;
1205     struct evsel *pos;
1206 
1207     if (i >= pevlist->evlist.core.nr_entries)
1208         return NULL;
1209 
1210     evlist__for_each_entry(&pevlist->evlist, pos) {
1211         if (i-- == 0)
1212             break;
1213     }
1214 
1215     return Py_BuildValue("O", container_of(pos, struct pyrf_evsel, evsel));
1216 }
1217 
1218 static PySequenceMethods pyrf_evlist__sequence_methods = {
1219     .sq_length = pyrf_evlist__length,
1220     .sq_item   = pyrf_evlist__item,
1221 };
1222 
1223 static char pyrf_evlist__doc[] = PyDoc_STR("perf event selector list object.");
1224 
1225 static PyTypeObject pyrf_evlist__type = {
1226     PyVarObject_HEAD_INIT(NULL, 0)
1227     .tp_name    = "perf.evlist",
1228     .tp_basicsize   = sizeof(struct pyrf_evlist),
1229     .tp_dealloc = (destructor)pyrf_evlist__delete,
1230     .tp_flags   = Py_TPFLAGS_DEFAULT|Py_TPFLAGS_BASETYPE,
1231     .tp_as_sequence = &pyrf_evlist__sequence_methods,
1232     .tp_doc     = pyrf_evlist__doc,
1233     .tp_methods = pyrf_evlist__methods,
1234     .tp_init    = (initproc)pyrf_evlist__init,
1235 };
1236 
1237 static int pyrf_evlist__setup_types(void)
1238 {
1239     pyrf_evlist__type.tp_new = PyType_GenericNew;
1240     return PyType_Ready(&pyrf_evlist__type);
1241 }
1242 
1243 #define PERF_CONST(name) { #name, PERF_##name }
1244 
1245 static struct {
1246     const char *name;
1247     int     value;
1248 } perf__constants[] = {
1249     PERF_CONST(TYPE_HARDWARE),
1250     PERF_CONST(TYPE_SOFTWARE),
1251     PERF_CONST(TYPE_TRACEPOINT),
1252     PERF_CONST(TYPE_HW_CACHE),
1253     PERF_CONST(TYPE_RAW),
1254     PERF_CONST(TYPE_BREAKPOINT),
1255 
1256     PERF_CONST(COUNT_HW_CPU_CYCLES),
1257     PERF_CONST(COUNT_HW_INSTRUCTIONS),
1258     PERF_CONST(COUNT_HW_CACHE_REFERENCES),
1259     PERF_CONST(COUNT_HW_CACHE_MISSES),
1260     PERF_CONST(COUNT_HW_BRANCH_INSTRUCTIONS),
1261     PERF_CONST(COUNT_HW_BRANCH_MISSES),
1262     PERF_CONST(COUNT_HW_BUS_CYCLES),
1263     PERF_CONST(COUNT_HW_CACHE_L1D),
1264     PERF_CONST(COUNT_HW_CACHE_L1I),
1265     PERF_CONST(COUNT_HW_CACHE_LL),
1266     PERF_CONST(COUNT_HW_CACHE_DTLB),
1267     PERF_CONST(COUNT_HW_CACHE_ITLB),
1268     PERF_CONST(COUNT_HW_CACHE_BPU),
1269     PERF_CONST(COUNT_HW_CACHE_OP_READ),
1270     PERF_CONST(COUNT_HW_CACHE_OP_WRITE),
1271     PERF_CONST(COUNT_HW_CACHE_OP_PREFETCH),
1272     PERF_CONST(COUNT_HW_CACHE_RESULT_ACCESS),
1273     PERF_CONST(COUNT_HW_CACHE_RESULT_MISS),
1274 
1275     PERF_CONST(COUNT_HW_STALLED_CYCLES_FRONTEND),
1276     PERF_CONST(COUNT_HW_STALLED_CYCLES_BACKEND),
1277 
1278     PERF_CONST(COUNT_SW_CPU_CLOCK),
1279     PERF_CONST(COUNT_SW_TASK_CLOCK),
1280     PERF_CONST(COUNT_SW_PAGE_FAULTS),
1281     PERF_CONST(COUNT_SW_CONTEXT_SWITCHES),
1282     PERF_CONST(COUNT_SW_CPU_MIGRATIONS),
1283     PERF_CONST(COUNT_SW_PAGE_FAULTS_MIN),
1284     PERF_CONST(COUNT_SW_PAGE_FAULTS_MAJ),
1285     PERF_CONST(COUNT_SW_ALIGNMENT_FAULTS),
1286     PERF_CONST(COUNT_SW_EMULATION_FAULTS),
1287     PERF_CONST(COUNT_SW_DUMMY),
1288 
1289     PERF_CONST(SAMPLE_IP),
1290     PERF_CONST(SAMPLE_TID),
1291     PERF_CONST(SAMPLE_TIME),
1292     PERF_CONST(SAMPLE_ADDR),
1293     PERF_CONST(SAMPLE_READ),
1294     PERF_CONST(SAMPLE_CALLCHAIN),
1295     PERF_CONST(SAMPLE_ID),
1296     PERF_CONST(SAMPLE_CPU),
1297     PERF_CONST(SAMPLE_PERIOD),
1298     PERF_CONST(SAMPLE_STREAM_ID),
1299     PERF_CONST(SAMPLE_RAW),
1300 
1301     PERF_CONST(FORMAT_TOTAL_TIME_ENABLED),
1302     PERF_CONST(FORMAT_TOTAL_TIME_RUNNING),
1303     PERF_CONST(FORMAT_ID),
1304     PERF_CONST(FORMAT_GROUP),
1305 
1306     PERF_CONST(RECORD_MMAP),
1307     PERF_CONST(RECORD_LOST),
1308     PERF_CONST(RECORD_COMM),
1309     PERF_CONST(RECORD_EXIT),
1310     PERF_CONST(RECORD_THROTTLE),
1311     PERF_CONST(RECORD_UNTHROTTLE),
1312     PERF_CONST(RECORD_FORK),
1313     PERF_CONST(RECORD_READ),
1314     PERF_CONST(RECORD_SAMPLE),
1315     PERF_CONST(RECORD_MMAP2),
1316     PERF_CONST(RECORD_AUX),
1317     PERF_CONST(RECORD_ITRACE_START),
1318     PERF_CONST(RECORD_LOST_SAMPLES),
1319     PERF_CONST(RECORD_SWITCH),
1320     PERF_CONST(RECORD_SWITCH_CPU_WIDE),
1321 
1322     PERF_CONST(RECORD_MISC_SWITCH_OUT),
1323     { .name = NULL, },
1324 };
1325 
1326 static PyObject *pyrf__tracepoint(struct pyrf_evsel *pevsel,
1327                   PyObject *args, PyObject *kwargs)
1328 {
1329     struct tep_event *tp_format;
1330     static char *kwlist[] = { "sys", "name", NULL };
1331     char *sys  = NULL;
1332     char *name = NULL;
1333 
1334     if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|ss", kwlist,
1335                      &sys, &name))
1336         return NULL;
1337 
1338     tp_format = trace_event__tp_format(sys, name);
1339     if (IS_ERR(tp_format))
1340         return _PyLong_FromLong(-1);
1341 
1342     return _PyLong_FromLong(tp_format->id);
1343 }
1344 
1345 static PyMethodDef perf__methods[] = {
1346     {
1347         .ml_name  = "tracepoint",
1348         .ml_meth  = (PyCFunction) pyrf__tracepoint,
1349         .ml_flags = METH_VARARGS | METH_KEYWORDS,
1350         .ml_doc   = PyDoc_STR("Get tracepoint config.")
1351     },
1352     { .ml_name = NULL, }
1353 };
1354 
1355 #if PY_MAJOR_VERSION < 3
1356 PyMODINIT_FUNC initperf(void)
1357 #else
1358 PyMODINIT_FUNC PyInit_perf(void)
1359 #endif
1360 {
1361     PyObject *obj;
1362     int i;
1363     PyObject *dict;
1364 #if PY_MAJOR_VERSION < 3
1365     PyObject *module = Py_InitModule("perf", perf__methods);
1366 #else
1367     static struct PyModuleDef moduledef = {
1368         PyModuleDef_HEAD_INIT,
1369         "perf",         /* m_name */
1370         "",         /* m_doc */
1371         -1,         /* m_size */
1372         perf__methods,      /* m_methods */
1373         NULL,           /* m_reload */
1374         NULL,           /* m_traverse */
1375         NULL,           /* m_clear */
1376         NULL,           /* m_free */
1377     };
1378     PyObject *module = PyModule_Create(&moduledef);
1379 #endif
1380 
1381     if (module == NULL ||
1382         pyrf_event__setup_types() < 0 ||
1383         pyrf_evlist__setup_types() < 0 ||
1384         pyrf_evsel__setup_types() < 0 ||
1385         pyrf_thread_map__setup_types() < 0 ||
1386         pyrf_cpu_map__setup_types() < 0)
1387 #if PY_MAJOR_VERSION < 3
1388         return;
1389 #else
1390         return module;
1391 #endif
1392 
1393     /* The page_size is placed in util object. */
1394     page_size = sysconf(_SC_PAGE_SIZE);
1395 
1396     Py_INCREF(&pyrf_evlist__type);
1397     PyModule_AddObject(module, "evlist", (PyObject*)&pyrf_evlist__type);
1398 
1399     Py_INCREF(&pyrf_evsel__type);
1400     PyModule_AddObject(module, "evsel", (PyObject*)&pyrf_evsel__type);
1401 
1402     Py_INCREF(&pyrf_mmap_event__type);
1403     PyModule_AddObject(module, "mmap_event", (PyObject *)&pyrf_mmap_event__type);
1404 
1405     Py_INCREF(&pyrf_lost_event__type);
1406     PyModule_AddObject(module, "lost_event", (PyObject *)&pyrf_lost_event__type);
1407 
1408     Py_INCREF(&pyrf_comm_event__type);
1409     PyModule_AddObject(module, "comm_event", (PyObject *)&pyrf_comm_event__type);
1410 
1411     Py_INCREF(&pyrf_task_event__type);
1412     PyModule_AddObject(module, "task_event", (PyObject *)&pyrf_task_event__type);
1413 
1414     Py_INCREF(&pyrf_throttle_event__type);
1415     PyModule_AddObject(module, "throttle_event", (PyObject *)&pyrf_throttle_event__type);
1416 
1417     Py_INCREF(&pyrf_task_event__type);
1418     PyModule_AddObject(module, "task_event", (PyObject *)&pyrf_task_event__type);
1419 
1420     Py_INCREF(&pyrf_read_event__type);
1421     PyModule_AddObject(module, "read_event", (PyObject *)&pyrf_read_event__type);
1422 
1423     Py_INCREF(&pyrf_sample_event__type);
1424     PyModule_AddObject(module, "sample_event", (PyObject *)&pyrf_sample_event__type);
1425 
1426     Py_INCREF(&pyrf_context_switch_event__type);
1427     PyModule_AddObject(module, "switch_event", (PyObject *)&pyrf_context_switch_event__type);
1428 
1429     Py_INCREF(&pyrf_thread_map__type);
1430     PyModule_AddObject(module, "thread_map", (PyObject*)&pyrf_thread_map__type);
1431 
1432     Py_INCREF(&pyrf_cpu_map__type);
1433     PyModule_AddObject(module, "cpu_map", (PyObject*)&pyrf_cpu_map__type);
1434 
1435     dict = PyModule_GetDict(module);
1436     if (dict == NULL)
1437         goto error;
1438 
1439     for (i = 0; perf__constants[i].name != NULL; i++) {
1440         obj = _PyLong_FromLong(perf__constants[i].value);
1441         if (obj == NULL)
1442             goto error;
1443         PyDict_SetItemString(dict, perf__constants[i].name, obj);
1444         Py_DECREF(obj);
1445     }
1446 
1447 error:
1448     if (PyErr_Occurred())
1449         PyErr_SetString(PyExc_ImportError, "perf: Init failed!");
1450 #if PY_MAJOR_VERSION >= 3
1451     return module;
1452 #endif
1453 }
1454 
1455 /*
1456  * Dummy, to avoid dragging all the test_attr infrastructure in the python
1457  * binding.
1458  */
1459 void test_attr__open(struct perf_event_attr *attr, pid_t pid, struct perf_cpu cpu,
1460                      int fd, int group_fd, unsigned long flags)
1461 {
1462 }