-
Notifications
You must be signed in to change notification settings - Fork 24
Expand file tree
/
Copy pathpython.c
More file actions
3330 lines (2936 loc) · 109 KB
/
python.c
File metadata and controls
3330 lines (2936 loc) · 109 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// SPDX-License-Identifier: GPL-2.0
/*
* python - Python scripting profiler for perf-prof
*
* Convert perf events to Python objects and process them with Python scripts.
*
* Usage: perf-prof python -e EVENT script.py [script-args...]
* perf-prof python -e EVENT -- script.py --script-option
*/
/* Python.h must be included first */
#include <Python.h>
#include <structmember.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <libgen.h>
#include <monitor.h>
#include <dlfcn.h>
#include <tep.h>
#include <trace_helpers.h>
#include <stack_helpers.h>
#include <event-parse-local.h>
#include <linux/bitmap.h>
#include <linux/stringify.h>
#include <asm/perf_regs.h>
/*
* Register name tables for PERF_SAMPLE_REGS_USER / PERF_SAMPLE_REGS_INTR.
* Indexed by bit position in sample_regs_user / sample_regs_intr mask.
*/
#if defined(__x86_64__)
static const char *perf_reg_names[] = {
[PERF_REG_X86_AX] = "ax",
[PERF_REG_X86_BX] = "bx",
[PERF_REG_X86_CX] = "cx",
[PERF_REG_X86_DX] = "dx",
[PERF_REG_X86_SI] = "si",
[PERF_REG_X86_DI] = "di",
[PERF_REG_X86_BP] = "bp",
[PERF_REG_X86_SP] = "sp",
[PERF_REG_X86_IP] = "ip",
[PERF_REG_X86_FLAGS] = "flags",
[PERF_REG_X86_CS] = "cs",
[PERF_REG_X86_SS] = "ss",
[PERF_REG_X86_DS] = "ds",
[PERF_REG_X86_ES] = "es",
[PERF_REG_X86_FS] = "fs",
[PERF_REG_X86_GS] = "gs",
[PERF_REG_X86_R8] = "r8",
[PERF_REG_X86_R9] = "r9",
[PERF_REG_X86_R10] = "r10",
[PERF_REG_X86_R11] = "r11",
[PERF_REG_X86_R12] = "r12",
[PERF_REG_X86_R13] = "r13",
[PERF_REG_X86_R14] = "r14",
[PERF_REG_X86_R15] = "r15",
};
#define PERF_REG_MAX PERF_REG_X86_64_MAX
#elif defined(__i386__)
static const char *perf_reg_names[] = {
[PERF_REG_X86_AX] = "ax",
[PERF_REG_X86_BX] = "bx",
[PERF_REG_X86_CX] = "cx",
[PERF_REG_X86_DX] = "dx",
[PERF_REG_X86_SI] = "si",
[PERF_REG_X86_DI] = "di",
[PERF_REG_X86_BP] = "bp",
[PERF_REG_X86_SP] = "sp",
[PERF_REG_X86_IP] = "ip",
[PERF_REG_X86_FLAGS] = "flags",
[PERF_REG_X86_CS] = "cs",
[PERF_REG_X86_SS] = "ss",
[PERF_REG_X86_DS] = "ds",
[PERF_REG_X86_ES] = "es",
[PERF_REG_X86_FS] = "fs",
[PERF_REG_X86_GS] = "gs",
};
#define PERF_REG_MAX PERF_REG_X86_32_MAX
#elif defined(__aarch64__)
static const char *perf_reg_names[] = {
[PERF_REG_ARM64_X0] = "x0",
[PERF_REG_ARM64_X1] = "x1",
[PERF_REG_ARM64_X2] = "x2",
[PERF_REG_ARM64_X3] = "x3",
[PERF_REG_ARM64_X4] = "x4",
[PERF_REG_ARM64_X5] = "x5",
[PERF_REG_ARM64_X6] = "x6",
[PERF_REG_ARM64_X7] = "x7",
[PERF_REG_ARM64_X8] = "x8",
[PERF_REG_ARM64_X9] = "x9",
[PERF_REG_ARM64_X10] = "x10",
[PERF_REG_ARM64_X11] = "x11",
[PERF_REG_ARM64_X12] = "x12",
[PERF_REG_ARM64_X13] = "x13",
[PERF_REG_ARM64_X14] = "x14",
[PERF_REG_ARM64_X15] = "x15",
[PERF_REG_ARM64_X16] = "x16",
[PERF_REG_ARM64_X17] = "x17",
[PERF_REG_ARM64_X18] = "x18",
[PERF_REG_ARM64_X19] = "x19",
[PERF_REG_ARM64_X20] = "x20",
[PERF_REG_ARM64_X21] = "x21",
[PERF_REG_ARM64_X22] = "x22",
[PERF_REG_ARM64_X23] = "x23",
[PERF_REG_ARM64_X24] = "x24",
[PERF_REG_ARM64_X25] = "x25",
[PERF_REG_ARM64_X26] = "x26",
[PERF_REG_ARM64_X27] = "x27",
[PERF_REG_ARM64_X28] = "x28",
[PERF_REG_ARM64_X29] = "x29",
[PERF_REG_ARM64_LR] = "lr",
[PERF_REG_ARM64_SP] = "sp",
[PERF_REG_ARM64_PC] = "pc",
};
#define PERF_REG_MAX PERF_REG_ARM64_MAX
#else
static const char *perf_reg_names[] = {};
#define PERF_REG_MAX 0
#endif
#define PERF_REG_NAMES_SIZE (sizeof(perf_reg_names) / sizeof(perf_reg_names[0]))
/* Interned Python string keys for register names, initialized by init_perf_interned_keys() */
static PyObject *perf_reg_keys[PERF_REG_MAX > 0 ? PERF_REG_MAX : 1];
static PyObject *perf_reg_key_abi; /* interned "abi" key */
/* Interned Python string keys for PERF_SAMPLE_READ fields */
static PyObject *perf_read_key_value;
static PyObject *perf_read_key_time_enabled;
static PyObject *perf_read_key_time_running;
static PyObject *perf_read_key_id;
static PyObject *perf_read_key_lost;
static PyObject *perf_read_key_nr;
static PyObject *perf_read_key_cntr;
static int register_perf_prof_module(void);
/* Global script path and arguments, set by argc_init before init */
static char *script_path = NULL;
static int script_argc = 0;
static char **script_argv = NULL;
/*
* Sample type for Python profiler (no callchain support in initial version)
* PERF_SAMPLE_TID | PERF_SAMPLE_TIME | PERF_SAMPLE_ID | PERF_SAMPLE_CPU |
* PERF_SAMPLE_PERIOD | PERF_SAMPLE_RAW
*
* Same layout as struct sql_sample_type in sqlite/ext.h
*/
struct python_sample_type {
struct {
u32 pid;
u32 tid;
} tid_entry;
u64 time;
u64 id;
struct {
u32 cpu;
u32 reserved;
} cpu_entry;
u64 period;
struct {
u32 size;
union {
u8 data[0];
struct trace_entry common;
};
} raw;
};
/*
* Cached Python string objects for common dict keys.
* Using interned strings avoids repeated string hashing in PyDict_SetItem.
* Access via dev->private->key_cache.
*/
struct python_key_cache {
/* Common sample fields - for PerfEventObject */
PyObject *key_pid; /* "_pid" */
PyObject *key_tid; /* "_tid" */
PyObject *key_time; /* "_time" */
PyObject *key_cpu; /* "_cpu" */
PyObject *key_period; /* "_period" */
/* Common trace_entry fields */
PyObject *key_common_type; /* "common_type" */
PyObject *key_common_flags; /* "common_flags" */
PyObject *key_common_preempt_count; /* "common_preempt_count" */
PyObject *key_common_pid; /* "common_pid" */
/* Lazy computed fields */
PyObject *key_realtime; /* "_realtime" - wall clock time (ns) */
PyObject *key_callchain; /* "_callchain" */
PyObject *key_event; /* "_event" */
};
/*
* Per-event data: handler, fields, and cached Python strings.
* Access via tp->private.
*/
struct python_event_data {
PyObject *handler; /* sys__event_name handler */
PyObject *event_name; /* Cached "sys:name" or "sys:alias" string for _event field */
struct tep_format_field **fields; /* Event fields from tep */
PyObject **field_keys; /* Cached PyUnicode for each field name */
int nr_fields;
};
struct python_ctx {
struct tp_list *tp_list;
char *script_path;
PyObject *perf_prof_module; /* perf_prof built-in module (keeps types alive) */
PyObject *module;
PyObject *func_init;
PyObject *func_exit;
PyObject *func_print_stat;
PyObject *func_interval;
PyObject *func_lost;
PyObject *func_sample; /* default __sample__ handler */
/* Cached common key strings */
struct python_key_cache key_cache;
/* Per-event data array */
struct python_event_data *events;
int nr_events;
/* Callchain support */
int callchain_flags; /* CALLCHAIN_KERNEL | CALLCHAIN_USER flags */
struct callchain_ctx *cc; /* Callchain context for printing */
/* minevtime tracking: rb tree of live PerfEventObjects sorted by _time */
struct rb_root live_events;
unsigned long nr_live_events; /* Number of events in live_events tree */
};
/*
* ============================================================================
* PerfEvent Type
*
* A Python type that represents a perf event with lazy field evaluation.
* Direct access to common fields, lazy computation for derived fields,
* and lazy parsing for event-specific fields with caching.
* ============================================================================
*/
/* Forward declarations */
static PyTypeObject PerfEventType;
static PyTypeObject PerfEventIterType;
/*
* PerfEventObject - Python object representing a perf event
*
* Memory layout optimized for fast direct field access while supporting
* lazy evaluation for computed and event-specific fields.
*
* Key design:
* - event: Pointer to union perf_event (borrowed or owned)
* - tp: Borrowed reference to tracepoint info (valid during sample processing)
* - dev: Borrowed reference to prof_dev (for accessing key_cache and time conversion)
*
* Event ownership (determined by rb_node state):
* - Initially, event points to the original perf_event (borrowed)
* - If Python script keeps a reference (refcnt > 1 after handler returns),
* live_events_insert() copies the event and inserts into rb tree
* - RB_EMPTY_NODE(&rb_node) means borrowed; in tree means we own the copy
* - This optimization avoids copying for events that are processed and discarded
*/
typedef struct {
PyObject_HEAD
/* Core pointers */
struct prof_dev *dev; /* Prof dev - borrowed reference */
struct tp *tp; /* Tracepoint info - borrowed reference */
union perf_event *event; /* Entire perf event - borrowed or owned copy */
/* minevtime tracking: node in python_ctx->live_events rb tree */
struct rb_node rb_node;
/* Direct access fields (via PyMemberDef) - extracted from event */
int _pid; /* Process ID */
int _tid; /* Thread ID */
unsigned long long _time; /* Event timestamp (ns) */
int _cpu; /* CPU number */
int instance; /* Instance number */
unsigned long long _period; /* Sample period (tracepoint only) */
/* Lazy computed fields (via PyGetSetDef) - cached when first accessed */
PyObject *_realtime; /* Wall clock time - lazy computed */
PyObject *_callchain_list; /* Callchain as Python list (tracepoint only) - lazy computed */
/* Event-specific field cache (dict for lazy parsed fields) */
PyObject *field_cache; /* Dict caching event-specific field values */
} PerfEventObject;
/*
* Iterator object for PerfEvent
*/
typedef struct {
PyObject_HEAD
PerfEventObject *event;
PyObject *keys;
Py_ssize_t index;
} PerfEventIterObject;
static PyObject *PerfEvent_get_callchain(PerfEventObject *self, void *closure);
/* Helper to get raw data from PerfEventObject */
static inline void perfevent_get_raw(PerfEventObject *self, void **raw, int *raw_size,
struct callchain **callchain)
{
struct python_sample_type *data = (void *)self->event->sample.array;
bool has_callchain = self->tp->stack;
if (has_callchain) {
struct callchain *cc = (struct callchain *)&data->raw;
struct {
__u32 size;
__u8 data[0];
} *raw_data = (void *)cc->ips + cc->nr * sizeof(__u64);
if (callchain) *callchain = cc;
*raw = raw_data->data;
*raw_size = raw_data->size;
} else {
if (callchain) *callchain = NULL;
*raw = data->raw.data;
*raw_size = data->raw.size;
}
}
/*
* Common field names for tracepoint events.
* Tracepoint events have: _pid,_tid,_time,_cpu,_period,common_type,common_flags,
* common_preempt_count,common_pid,_realtime,_callchain,_event + tep fields
*/
static const char *tp_common_field_names[] = {
"_pid", "_tid", "_time", "_cpu", "_period",
"common_type", "common_flags", "common_preempt_count", "common_pid",
"_realtime", "_callchain", "_event",
NULL
};
/*
* Common field names for profiler (dev_tp) events.
* Profiler events have: _pid,_tid,_time,_cpu,_realtime,_event + member_cache fields
*/
static const char *dev_common_field_names[] = {
"_pid", "_tid", "_time", "_cpu", "_realtime", "_event",
NULL
};
/* Check if a field name is a common field for the given tp type */
static int is_common_field(const char *name, int is_dev)
{
const char **p;
const char **fields = is_dev ? dev_common_field_names : tp_common_field_names;
for (p = fields; *p; p++) {
if (strcmp(name, *p) == 0)
return 1;
}
return 0;
}
/* Parse a single event-specific field */
static PyObject *parse_event_field(void *raw_data, struct tep_format_field *field)
{
PyObject *value = NULL;
void *base = raw_data;
void *ptr;
int len;
if (field->flags & TEP_FIELD_IS_STRING) {
/* String field */
if (field->flags & TEP_FIELD_IS_DYNAMIC) {
ptr = base + *(unsigned short *)(base + field->offset);
len = *(unsigned short *)(base + field->offset + sizeof(unsigned short));
if (len > 0)
value = PyUnicode_FromStringAndSize((char *)ptr, len - 1);
else
value = PyUnicode_FromString("");
} else {
ptr = base + field->offset;
value = PyUnicode_FromString((char *)ptr);
}
} else if (field->flags & TEP_FIELD_IS_ARRAY) {
/* Array field -> bytes */
if (field->flags & TEP_FIELD_IS_DYNAMIC) {
ptr = base + *(unsigned short *)(base + field->offset);
len = *(unsigned short *)(base + field->offset + sizeof(unsigned short));
} else {
ptr = base + field->offset;
len = field->size;
}
value = PyBytes_FromStringAndSize((char *)ptr, len);
} else {
/* Numeric field */
bool is_signed = field->flags & TEP_FIELD_IS_SIGNED;
long long val = 0;
if (field->size == 1)
val = is_signed ? *(char *)(base + field->offset)
: *(unsigned char *)(base + field->offset);
else if (field->size == 2)
val = is_signed ? *(short *)(base + field->offset)
: *(unsigned short *)(base + field->offset);
else if (field->size == 4)
val = is_signed ? *(int *)(base + field->offset)
: *(unsigned int *)(base + field->offset);
else if (field->size == 8)
val = is_signed ? *(long long *)(base + field->offset)
: *(unsigned long long *)(base + field->offset);
if (field->size <= 8)
value = PyLong_FromLongLong(val);
}
return value;
}
/* Get all field names (common + event-specific) */
static PyObject *perfevent_get_all_field_names(PerfEventObject *self)
{
struct python_ctx *ctx = self->dev->private;
struct python_key_cache *kc = &ctx->key_cache;
struct python_event_data *ev = self->tp->private;
PyObject *list;
int i;
list = PyList_New(0);
if (!list)
return NULL;
/* Add common field names from key_cache */
#define APPEND_KEY(key) do { \
if (kc->key && PyList_Append(list, kc->key) < 0) { \
Py_DECREF(list); \
return NULL; \
} \
} while (0)
/*
* Field layout:
* - Tracepoint events: _pid,_tid,_time,_cpu,_period,common_type,common_flags,
* common_preempt_count,common_pid,_realtime,_callchain,_event + tep fields
* - Profiler events: _pid,_tid,_time,_cpu,_realtime,_event + member_cache fields
*/
APPEND_KEY(key_pid);
APPEND_KEY(key_tid);
APPEND_KEY(key_time);
APPEND_KEY(key_cpu);
if (tp_is_dev(self->tp)) {
/* Profiler event: _pid,_tid,_time,_cpu,_realtime,_event + member_cache fields */
struct prof_dev *source_dev = self->tp->source_dev;
struct perf_evsel *evsel;
struct perf_event_member_cache *cache;
APPEND_KEY(key_realtime);
APPEND_KEY(key_event);
/* Add member_cache fields */
evsel = perf_event_evsel(source_dev, self->event);
if (evsel) {
cache = perf_evsel_member_cache(evsel);
if (cache) {
for (i = 0; i < cache->nr_members; i++) {
PyObject *key = cache->members[i].private;
if (key && PyList_Append(list, key) < 0) {
Py_DECREF(list);
return NULL;
}
}
}
}
} else {
/* Tracepoint event: full field set */
APPEND_KEY(key_period);
APPEND_KEY(key_common_type);
APPEND_KEY(key_common_flags);
APPEND_KEY(key_common_preempt_count);
APPEND_KEY(key_common_pid);
APPEND_KEY(key_realtime);
APPEND_KEY(key_callchain);
APPEND_KEY(key_event);
/* Add tep event-specific fields */
for (i = 0; i < ev->nr_fields; i++) {
if (ev->field_keys[i]) {
if (PyList_Append(list, ev->field_keys[i]) < 0) {
Py_DECREF(list);
return NULL;
}
}
}
}
#undef APPEND_KEY
return list;
}
/*
* Initialize interned Python string keys for register names.
* Called once after Py_Initialize().
*/
static int init_perf_interned_keys(void)
{
int i;
perf_reg_key_abi = PyUnicode_InternFromString("abi");
if (!perf_reg_key_abi)
return -1;
for (i = 0; i < PERF_REG_MAX; i++) {
if (i < (int)PERF_REG_NAMES_SIZE && perf_reg_names[i]) {
perf_reg_keys[i] = PyUnicode_InternFromString(perf_reg_names[i]);
if (!perf_reg_keys[i])
return -1;
}
}
/* Intern PERF_SAMPLE_READ field keys */
perf_read_key_value = PyUnicode_InternFromString("value");
perf_read_key_time_enabled = PyUnicode_InternFromString("time_enabled");
perf_read_key_time_running = PyUnicode_InternFromString("time_running");
perf_read_key_id = PyUnicode_InternFromString("id");
perf_read_key_lost = PyUnicode_InternFromString("lost");
perf_read_key_nr = PyUnicode_InternFromString("nr");
perf_read_key_cntr = PyUnicode_InternFromString("cntr");
if (!perf_read_key_value || !perf_read_key_time_enabled ||
!perf_read_key_time_running || !perf_read_key_id ||
!perf_read_key_lost || !perf_read_key_nr || !perf_read_key_cntr)
return -1;
return 0;
}
static void free_perf_interned_keys(void)
{
int i;
Py_XDECREF(perf_reg_key_abi);
perf_reg_key_abi = NULL;
for (i = 0; i < PERF_REG_MAX; i++) {
Py_XDECREF(perf_reg_keys[i]);
perf_reg_keys[i] = NULL;
}
Py_XDECREF(perf_read_key_value); perf_read_key_value = NULL;
Py_XDECREF(perf_read_key_time_enabled); perf_read_key_time_enabled = NULL;
Py_XDECREF(perf_read_key_time_running); perf_read_key_time_running = NULL;
Py_XDECREF(perf_read_key_id); perf_read_key_id = NULL;
Py_XDECREF(perf_read_key_lost); perf_read_key_lost = NULL;
Py_XDECREF(perf_read_key_nr); perf_read_key_nr = NULL;
Py_XDECREF(perf_read_key_cntr); perf_read_key_cntr = NULL;
}
/*
* Convert { u64 abi; u64 regs[hweight64(mask)]; } to Python dict {'reg': value}.
* The mask indicates which registers were sampled. Each set bit corresponds to
* a register, and the regs array contains values in set-bit order.
* Uses interned string keys from perf_reg_keys[] for fast dict construction.
*/
static PyObject *perf_regs_to_pydict(void *data, u64 mask)
{
PyObject *dict;
PyObject *abi_val;
u64 abi = *(u64 *)data;
u64 *regs = (u64 *)(data + sizeof(u64));
unsigned long m = (unsigned long)mask;
int bit, idx = 0;
dict = PyDict_New();
if (!dict)
return NULL;
/* Add abi field using interned key */
abi_val = PyLong_FromUnsignedLongLong(abi);
if (abi_val) {
PyDict_SetItem(dict, perf_reg_key_abi, abi_val);
Py_DECREF(abi_val);
}
for_each_set_bit(bit, &m, PERF_REG_MAX) {
PyObject *key;
PyObject *val;
key = perf_reg_keys[bit];
val = PyLong_FromUnsignedLongLong(regs[idx]);
if (val) {
if (key)
PyDict_SetItem(dict, key, val);
else {
/* Unknown register bit, use "regN" as key */
char buf[16];
snprintf(buf, sizeof(buf), "reg%d", bit);
PyDict_SetItemString(dict, buf, val);
}
Py_DECREF(val);
}
idx++;
}
return dict;
}
/*
* Decode PERF_SAMPLE_READ data based on attr->read_format into a Python dict.
*
* !PERF_FORMAT_GROUP:
* { u64 value; u64 time_enabled; u64 time_running; u64 id; u64 lost; }
* -> {'value': int, 'time_enabled': int, 'time_running': int, 'id': int, 'lost': int}
*
* PERF_FORMAT_GROUP:
* { u64 nr; u64 time_enabled; u64 time_running; { u64 value; u64 id; u64 lost; } cntr[nr]; }
* -> {'nr': int, 'time_enabled': int, 'time_running': int,
* 'cntr': [{'value': int, 'id': int, 'lost': int}, ...]}
*/
static inline void dict_set_u64(PyObject *dict, PyObject *key, u64 val)
{
PyObject *v = PyLong_FromUnsignedLongLong(val);
PyDict_SetItem(dict, key, v);
Py_DECREF(v);
}
static PyObject *perf_read_to_pydict(void *data, struct perf_evsel *evsel)
{
u64 read_format = perf_evsel__attr(evsel)->read_format;
u64 *ptr = data;
PyObject *dict;
dict = PyDict_New();
if (!dict)
return NULL;
if (!(read_format & PERF_FORMAT_GROUP)) {
/* Non-group: value, [time_enabled], [time_running], [id], [lost] */
dict_set_u64(dict, perf_read_key_value, *ptr++);
if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED)
dict_set_u64(dict, perf_read_key_time_enabled, *ptr++);
if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING)
dict_set_u64(dict, perf_read_key_time_running, *ptr++);
if (read_format & PERF_FORMAT_ID)
dict_set_u64(dict, perf_read_key_id, *ptr++);
if (read_format & PERF_FORMAT_LOST)
dict_set_u64(dict, perf_read_key_lost, *ptr++);
} else {
/* Group: nr, [time_enabled], [time_running], cntr[nr] */
u64 nr = *ptr++;
u64 i;
PyObject *cntr_list;
dict_set_u64(dict, perf_read_key_nr, nr);
if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED)
dict_set_u64(dict, perf_read_key_time_enabled, *ptr++);
if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING)
dict_set_u64(dict, perf_read_key_time_running, *ptr++);
cntr_list = PyList_New(nr);
if (!cntr_list) {
Py_DECREF(dict);
return NULL;
}
for (i = 0; i < nr; i++) {
PyObject *entry = PyDict_New();
if (!entry) {
Py_DECREF(cntr_list);
Py_DECREF(dict);
return NULL;
}
dict_set_u64(entry, perf_read_key_value, *ptr++);
if (read_format & PERF_FORMAT_ID)
dict_set_u64(entry, perf_read_key_id, *ptr++);
if (read_format & PERF_FORMAT_LOST)
dict_set_u64(entry, perf_read_key_lost, *ptr++);
PyList_SET_ITEM(cntr_list, i, entry); /* steals ref */
}
PyDict_SetItem(dict, perf_read_key_cntr, cntr_list);
Py_DECREF(cntr_list);
}
return dict;
}
/*
* Get profiler event field by name (with caching).
* For profiler events (tp_is_dev), fields are defined in perf_event_member_cache.
*/
static PyObject *perfevent_get_dev_field(PerfEventObject *self, PyObject *field_name)
{
struct prof_dev *source_dev = self->tp->source_dev;
struct perf_evsel *evsel;
struct perf_event_member_cache *cache;
struct perf_event_member *member = NULL;
PyObject *value = NULL;
int i, offset;
void *data;
/* Check cache first */
value = PyDict_GetItem(self->field_cache, field_name);
if (value) {
Py_INCREF(value);
return value;
}
/* Find evsel for the event */
evsel = perf_event_evsel(source_dev, self->event);
if (!evsel)
return NULL;
cache = perf_evsel_member_cache(evsel);
if (!cache)
return NULL;
/* Find the member by comparing cached Python string keys */
for (i = 0; i < cache->nr_members; i++) {
if (cache->members[i].private == field_name) {
member = &cache->members[i];
break;
}
}
if (!member)
return NULL;
/* Calculate offset in the sample data */
offset = perf_event_member_offset(cache, member, self->event);
data = (void *)self->event->sample.array + offset;
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wswitch-enum"
/* Convert member value to Python object based on format */
switch (member->format) {
case PERF_SAMPLE_CALLCHAIN:
/* Callchain is handled separately via _callchain attribute */
value = PerfEvent_get_callchain(self, NULL);
break;
case PERF_SAMPLE_RAW:
/* Raw data as bytes */
{
u32 size = *(u32 *)data;
void *raw = data + sizeof(u32);
value = PyBytes_FromStringAndSize((char *)raw, size);
}
break;
case PERF_SAMPLE_READ:
/* Read format values -> dict */
value = perf_read_to_pydict(data, evsel);
break;
case PERF_SAMPLE_REGS_USER:
/* { u64 abi; u64 regs[hweight64(mask)]; } -> dict {'reg': value} */
{
struct perf_event_attr *attr = perf_evsel__attr(evsel);
value = perf_regs_to_pydict(data, attr->sample_regs_user);
}
break;
case PERF_SAMPLE_REGS_INTR:
/* { u64 abi; u64 regs[hweight64(mask)]; } -> dict {'reg': value} */
{
struct perf_event_attr *attr = perf_evsel__attr(evsel);
value = perf_regs_to_pydict(data, attr->sample_regs_intr);
}
break;
case PERF_SAMPLE_BRANCH_STACK:
/* { u64 nr; struct perf_branch_entry lbr[nr]; } -> bytes */
{
u64 nr = *(u64 *)data;
u64 total = sizeof(u64) + nr * sizeof(struct perf_branch_entry);
value = PyBytes_FromStringAndSize((char *)data, total);
}
break;
case PERF_SAMPLE_STACK_USER:
/* { u64 size; char data[size]; u64 dyn_size; } -> bytes (data part) */
{
u64 sz = *(u64 *)data;
void *stack_data = data + sizeof(u64);
value = PyBytes_FromStringAndSize((char *)stack_data, sz);
}
break;
case PERF_SAMPLE_AUX:
/* { u64 size; char data[size]; } -> bytes (data part) */
{
u64 sz = *(u64 *)data;
void *aux_data = data + sizeof(u64);
value = PyBytes_FromStringAndSize((char *)aux_data, sz);
}
break;
default:
/* Numeric fields */
if (member->size == 8) {
value = PyLong_FromUnsignedLongLong(*(u64 *)data);
} else if (member->size == 4) {
value = PyLong_FromLong(*(u32 *)data);
} else if (member->size == 2) {
value = PyLong_FromLong(*(u16 *)data);
} else if (member->size == 1) {
value = PyLong_FromLong(*(u8 *)data);
} else {
/* Unknown size, return as bytes */
value = PyBytes_FromStringAndSize((char *)data, member->size);
}
break;
}
#pragma GCC diagnostic pop
if (value) {
/* Cache the value */
PyDict_SetItem(self->field_cache, field_name, value);
}
return value;
}
/* Get event-specific field by name (with caching) */
static PyObject *perfevent_get_field(PerfEventObject *self, PyObject *field_name)
{
PyObject *value;
struct python_event_data *ev;
void *raw;
int raw_size;
int i;
/* Check cache first */
value = PyDict_GetItem(self->field_cache, field_name);
if (value) {
Py_INCREF(value);
return value;
}
/* For profiler events, use separate path */
if (tp_is_dev(self->tp)) {
return perfevent_get_dev_field(self, field_name);
}
/* Look up field in cached event data */
ev = (struct python_event_data *)self->tp->private;
for (i = 0; i < ev->nr_fields; i++) {
if (ev->field_keys[i] == field_name)
break;
}
if (i >= ev->nr_fields)
return NULL;
/* Parse field value */
perfevent_get_raw(self, &raw, &raw_size, NULL);
value = parse_event_field(raw, ev->fields[i]);
if (value) {
/* Cache the value using the cached key */
PyDict_SetItem(self->field_cache, ev->field_keys[i], value);
}
return value;
}
/*
* Insert PerfEventObject into live_events rb tree (sorted by _time, then by pointer)
* This is called when Python script keeps a reference to the event (refcnt > 1).
* We copy the event here since the original event buffer will be reused.
*/
static void live_events_insert(struct python_ctx *ctx, PerfEventObject *obj)
{
struct rb_node **p = &ctx->live_events.rb_node;
struct rb_node *parent = NULL;
PerfEventObject *entry;
size_t event_size;
union perf_event *event_copy;
/* Copy event since original buffer will be reused */
event_size = obj->event->header.size;
event_copy = malloc(event_size);
if (!event_copy) {
/* Memory allocation failed, cannot track this event */
PyErr_NoMemory();
return;
}
memcpy(event_copy, obj->event, event_size);
obj->event = event_copy;
while (*p) {
parent = *p;
entry = rb_entry(parent, PerfEventObject, rb_node);
if (obj->_time < entry->_time)
p = &parent->rb_left;
else if (obj->_time > entry->_time)
p = &parent->rb_right;
else if (obj < entry)
p = &parent->rb_left;
else
p = &parent->rb_right;
}
rb_link_node(&obj->rb_node, parent, p);
rb_insert_color(&obj->rb_node, &ctx->live_events);
ctx->nr_live_events++;
}
/*
* Remove PerfEventObject from live_events rb tree and free the copied event.
* Objects in the tree own their event copy; objects not in tree have borrowed event.
*/
static void live_events_remove(struct python_ctx *ctx, PerfEventObject *obj)
{
if (!RB_EMPTY_NODE(&obj->rb_node)) {
rb_erase(&obj->rb_node, &ctx->live_events);
RB_CLEAR_NODE(&obj->rb_node);
ctx->nr_live_events--;
/* Free the copied event (objects in tree own their event) */
free(obj->event);
obj->event = NULL;
}
}
/*
* Create a new PerfEventObject (internal use)
* This is called from python_sample() to create event objects.
*
* Initially, event points to the original perf_event buffer (borrowed reference).
* If the Python script keeps a reference (refcnt > 1 after handler returns),
* live_events_insert() will copy the event. This avoids copying for most events
* that are processed and immediately discarded.
*/
static PerfEventObject *PerfEvent_create(struct prof_dev *dev, struct tp *tp,
union perf_event *event, int instance)
{
PerfEventObject *self;
struct python_sample_type *data;
self = PyObject_New(PerfEventObject, &PerfEventType);
if (!self)
return NULL;
/* Store borrowed references */
self->dev = dev;
self->tp = tp;
/* Initially use borrowed reference to event (no copy) */
self->event = event;
/* Extract header fields */
data = (void *)self->event->sample.array;
self->_pid = data->tid_entry.pid;
self->_tid = data->tid_entry.tid;
self->_time = data->time;
self->_cpu = data->cpu_entry.cpu;
self->instance = instance;
self->_period = data->period;
/* Initialize lazy computed fields to NULL */
self->_realtime = NULL;
self->_callchain_list = NULL;
/* Initialize field cache */
self->field_cache = PyDict_New();
if (!self->field_cache) {
Py_DECREF(self);
return NULL;
}
/* Initialize rb_node for minevtime tracking (not inserted yet) */
RB_CLEAR_NODE(&self->rb_node);
return self;
}
/*
* Create a PerfEventObject from a forwarded profiler event (PERF_RECORD_DEV).
*
* For profiler events, the data format is defined by perf_event_member_cache
* rather than tep event fields. The header fields (pid, tid, time, cpu) come
* from perf_record_dev.
*
* self->event stores the inner event (&event_dev->event), not the wrapper.
* The source device can be accessed via tp->source_dev.
*
* Profiler events have: _pid, _tid, _time, _cpu, _realtime, _event +
* member_cache fields
*
* @dev: The python device receiving the event
* @tp: The tp representing the profiler source (tp_is_dev(tp) == true)
* @event: The PERF_RECORD_DEV wrapper event
*/
static PerfEventObject *PerfEvent_create_from_dev(struct prof_dev *dev, struct tp *tp,
union perf_event *event)
{
PerfEventObject *self;
struct perf_record_dev *event_dev = (void *)event;
self = PyObject_New(PerfEventObject, &PerfEventType);
if (!self)
return NULL;
/* Store borrowed references */
self->dev = dev;
self->tp = tp;