py-spy 0.4.1

Sampling profiler for Python programs
Documentation
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
/* This code abstracts over different python interpreters by providing
traits for the classes/methods we need and implementations on the bindings objects
from bindgen.

Note this code is unaware of copying memory from the target process, so the
pointer addresses here refer to locations in the target process memory space.
This means we can't dereference them directly.
*/

#![allow(clippy::unnecessary_cast)]

// these bindings are automatically generated by rust bindgen
// using the generate_bindings.py script
use crate::python_bindings::{
    v2_7_15, v3_10_0, v3_11_0, v3_12_0, v3_13_0, v3_3_7, v3_5_5, v3_6_6, v3_7_0, v3_8_0, v3_9_5,
};
use crate::utils::offset_of;

pub trait InterpreterState: Copy {
    type ThreadState: ThreadState;
    type Object: Object;
    type StringObject: StringObject;
    type ListObject: ListObject;
    type TupleObject: TupleObject;
    const HAS_GIL_RUNTIME_STATE: bool = false;

    /// Get a remote pointer to a pointer to PyThreadState.
    fn threadstate_ptr_ptr(interpreter_address: usize) -> *const *const Self::ThreadState;
    /// Get a remote pointer to a pointer to PyObject being the modules dict.
    fn modules_ptr_ptr(interpreter_address: usize) -> *const *const Self::Object;
}

pub trait ThreadState: Copy {
    type FrameObject: FrameObject;
    type InterpreterState: InterpreterState;

    fn interp(&self) -> *mut Self::InterpreterState;

    // starting in python 3.11, there is an extra level of indirection
    // in getting the frame. this returns the address
    fn frame_address(&self) -> Option<usize>;

    fn frame(&self, offset: Option<usize>) -> *mut Self::FrameObject;
    fn thread_id(&self) -> u64;
    fn native_thread_id(&self) -> Option<u64>;
    fn next(&self) -> *mut Self;
}

pub trait FrameObject: Copy {
    type CodeObject: CodeObject;

    fn code(&self) -> *mut Self::CodeObject;
    fn lasti(&self) -> i32;
    fn back(&self) -> *mut Self;
    fn is_entry(&self) -> bool;
}

pub trait CodeObject: Copy {
    type StringObject: StringObject;
    type BytesObject: BytesObject;
    type TupleObject: TupleObject;

    fn name(&self) -> *mut Self::StringObject;
    fn filename(&self) -> *mut Self::StringObject;
    fn line_table(&self) -> *mut Self::BytesObject;
    fn first_lineno(&self) -> i32;
    fn nlocals(&self) -> i32;
    fn argcount(&self) -> i32;
    fn varnames(&self) -> *mut Self::TupleObject;

    fn get_line_number(&self, lasti: i32, table: &[u8]) -> i32;
}

pub trait BytesObject: Copy {
    fn size(&self) -> usize;
    fn address(&self, base: usize) -> usize;
}

pub trait StringObject: Copy {
    fn ascii(&self) -> bool;
    fn kind(&self) -> u32;
    fn size(&self) -> usize;
    fn address(&self, base: usize) -> usize;
}

pub trait TupleObject: Copy {
    fn size(&self) -> usize;
    fn address(&self, base: usize, index: usize) -> usize;
}

pub trait ListObject: Copy {
    type Object: Object;
    fn size(&self) -> usize;
    fn item(&self) -> *mut *mut Self::Object;
}

pub trait Object: Copy {
    type TypeObject: TypeObject;
    fn ob_type(&self) -> *mut Self::TypeObject;
}

pub trait TypeObject: Copy {
    fn name(&self) -> *const ::std::os::raw::c_char;
    fn dictoffset(&self) -> isize;
    fn flags(&self) -> usize;
}

/// This macro provides a common impl for PyThreadState/PyFrameObject/PyCodeObject traits
/// (this code is identical across python versions, we are only abstracting the struct layouts here).
/// String handling changes substantially between python versions, and is handled separately.
macro_rules! PythonCommonImpl {
    ($py: ident, $stringobject: ident) => {
        impl InterpreterState for $py::PyInterpreterState {
            type ThreadState = $py::PyThreadState;
            type Object = $py::PyObject;
            type StringObject = $py::$stringobject;
            type ListObject = $py::PyListObject;
            type TupleObject = $py::PyTupleObject;

            fn threadstate_ptr_ptr(interpreter_address: usize) -> *const *const Self::ThreadState {
                (interpreter_address + std::mem::offset_of!(Self, tstate_head))
                    as *const *const Self::ThreadState
            }
            fn modules_ptr_ptr(interpreter_address: usize) -> *const *const Self::Object {
                (interpreter_address + std::mem::offset_of!(Self, modules))
                    as *const *const Self::Object
            }
        }

        impl ThreadState for $py::PyThreadState {
            type FrameObject = $py::PyFrameObject;
            type InterpreterState = $py::PyInterpreterState;
            fn frame_address(&self) -> Option<usize> {
                None
            }
            fn frame(&self, _: Option<usize>) -> *mut Self::FrameObject {
                self.frame
            }
            fn thread_id(&self) -> u64 {
                self.thread_id as u64
            }
            fn native_thread_id(&self) -> Option<u64> {
                None
            }
            fn next(&self) -> *mut Self {
                self.next
            }
            fn interp(&self) -> *mut Self::InterpreterState {
                self.interp
            }
        }

        impl FrameObject for $py::PyFrameObject {
            type CodeObject = $py::PyCodeObject;

            fn code(&self) -> *mut Self::CodeObject {
                self.f_code
            }
            fn lasti(&self) -> i32 {
                self.f_lasti as i32
            }
            fn back(&self) -> *mut Self {
                self.f_back
            }
            fn is_entry(&self) -> bool {
                true
            }
        }

        impl Object for $py::PyObject {
            type TypeObject = $py::PyTypeObject;
            fn ob_type(&self) -> *mut Self::TypeObject {
                self.ob_type as *mut Self::TypeObject
            }
        }

        impl TypeObject for $py::PyTypeObject {
            fn name(&self) -> *const ::std::os::raw::c_char {
                self.tp_name
            }
            fn dictoffset(&self) -> isize {
                self.tp_dictoffset
            }
            fn flags(&self) -> usize {
                self.tp_flags as usize
            }
        }
    };
}

// We can use this up until python3.10 - where code object lnotab attribute is deprecated
macro_rules! PythonCodeObjectImpl {
    ($py: ident, $bytesobject: ident, $stringobject: ident) => {
        impl CodeObject for $py::PyCodeObject {
            type BytesObject = $py::$bytesobject;
            type StringObject = $py::$stringobject;
            type TupleObject = $py::PyTupleObject;

            fn name(&self) -> *mut Self::StringObject {
                self.co_name as *mut Self::StringObject
            }
            fn filename(&self) -> *mut Self::StringObject {
                self.co_filename as *mut Self::StringObject
            }
            fn line_table(&self) -> *mut Self::BytesObject {
                self.co_lnotab as *mut Self::BytesObject
            }
            fn first_lineno(&self) -> i32 {
                self.co_firstlineno
            }
            fn nlocals(&self) -> i32 {
                self.co_nlocals
            }
            fn argcount(&self) -> i32 {
                self.co_argcount
            }
            fn varnames(&self) -> *mut Self::TupleObject {
                self.co_varnames as *mut Self::TupleObject
            }

            fn get_line_number(&self, lasti: i32, table: &[u8]) -> i32 {
                let lasti = lasti as i32;

                // unpack the line table. format is specified here:
                // https://github.com/python/cpython/blob/3.9/Objects/lnotab_notes.txt
                let size = table.len();
                let mut i = 0;
                let mut line_number: i32 = self.first_lineno();
                let mut bytecode_address: i32 = 0;
                while (i + 1) < size {
                    bytecode_address += i32::from(table[i]);
                    if bytecode_address > lasti {
                        break;
                    }

                    let mut increment = i32::from(table[i + 1]);
                    // Handle negative line increments in the line number table - as shown here:
                    // https://github.com/python/cpython/blob/143a97f6/Objects/lnotab_notes.txt#L48-L49
                    if increment >= 0x80 {
                        increment -= 0x100;
                    }
                    line_number += increment;
                    i += 2;
                }
                line_number
            }
        }
    };
}

fn read_varint(index: &mut usize, table: &[u8]) -> Option<usize> {
    if *index >= table.len() {
        return None;
    }
    let mut ret: usize;
    let mut byte = table[*index];
    let mut shift = 0;
    *index += 1;
    ret = (byte & 63) as usize;

    while byte & 64 != 0 {
        if *index >= table.len() {
            return None;
        }
        byte = table[*index];
        *index += 1;
        shift += 6;
        ret += ((byte & 63) as usize) << shift;
    }
    Some(ret)
}

fn read_signed_varint(index: &mut usize, table: &[u8]) -> Option<isize> {
    let unsigned_val = read_varint(index, table)?;
    if unsigned_val & 1 != 0 {
        Some(-((unsigned_val >> 1) as isize))
    } else {
        Some((unsigned_val >> 1) as isize)
    }
}

// Use for 3.11 and 3.12
macro_rules! CompactCodeObjectImpl {
    ($py: ident, $bytesobject: ident, $stringobject: ident) => {
        impl CodeObject for $py::PyCodeObject {
            type BytesObject = $py::$bytesobject;
            type StringObject = $py::$stringobject;
            type TupleObject = $py::PyTupleObject;

            fn name(&self) -> *mut Self::StringObject {
                self.co_name as *mut Self::StringObject
            }
            fn filename(&self) -> *mut Self::StringObject {
                self.co_filename as *mut Self::StringObject
            }
            fn line_table(&self) -> *mut Self::BytesObject {
                self.co_linetable as *mut Self::BytesObject
            }
            fn first_lineno(&self) -> i32 {
                self.co_firstlineno
            }
            fn nlocals(&self) -> i32 {
                self.co_nlocals
            }
            fn argcount(&self) -> i32 {
                self.co_argcount
            }
            fn varnames(&self) -> *mut Self::TupleObject {
                self.co_localsplusnames as *mut Self::TupleObject
            }

            fn get_line_number(&self, lasti: i32, table: &[u8]) -> i32 {
                // unpack compressed table format from python 3.11
                // https://github.com/python/cpython/pull/91666/files
                let lasti = lasti - offset_of(self, &self.co_code_adaptive) as i32;
                let mut line_number: i32 = self.first_lineno();
                let mut bytecode_address: i32 = 0;

                let mut index: usize = 0;
                loop {
                    if index >= table.len() {
                        break;
                    }
                    let byte = table[index];
                    index += 1;

                    let delta = ((byte & 7) as i32) + 1;
                    bytecode_address += delta * 2;
                    let code = (byte >> 3) & 15;
                    let line_delta = match code {
                        15 => 0,
                        14 => {
                            let delta = read_signed_varint(&mut index, table).unwrap_or(0);
                            read_varint(&mut index, table); // end line
                            read_varint(&mut index, table); // start column
                            read_varint(&mut index, table); // end column
                            delta
                        }
                        13 => read_signed_varint(&mut index, table).unwrap_or(0),
                        10..=12 => {
                            index += 2; // start column / end column
                            (code - 10).into()
                        }
                        _ => {
                            index += 1; // column
                            0
                        }
                    };
                    line_number += line_delta as i32;
                    if bytecode_address >= lasti {
                        break;
                    }
                }
                line_number
            }
        }
    };
}

// String/Byte/List/Tuple handling for Python 3.3+
macro_rules! Python3Impl {
    ($py: ident) => {
        impl BytesObject for $py::PyBytesObject {
            fn size(&self) -> usize {
                self.ob_base.ob_size as usize
            }
            fn address(&self, base: usize) -> usize {
                base + offset_of(self, &self.ob_sval)
            }
        }

        impl StringObject for $py::PyUnicodeObject {
            fn ascii(&self) -> bool {
                self._base._base.state.ascii() != 0
            }
            fn size(&self) -> usize {
                self._base._base.length as usize
            }
            fn kind(&self) -> u32 {
                self._base._base.state.kind()
            }

            fn address(&self, base: usize) -> usize {
                if self._base._base.state.compact() == 0 {
                    return unsafe { self.data.any as usize };
                }

                if self._base._base.state.ascii() == 1 {
                    base + std::mem::size_of::<$py::PyASCIIObject>()
                } else {
                    base + std::mem::size_of::<$py::PyCompactUnicodeObject>()
                }
            }
        }

        impl ListObject for $py::PyListObject {
            type Object = $py::PyObject;
            fn size(&self) -> usize {
                self.ob_base.ob_size as usize
            }
            fn item(&self) -> *mut *mut Self::Object {
                self.ob_item
            }
        }

        impl TupleObject for $py::PyTupleObject {
            fn size(&self) -> usize {
                self.ob_base.ob_size as usize
            }
            fn address(&self, base: usize, index: usize) -> usize {
                base + offset_of(self, &self.ob_item)
                    + index * std::mem::size_of::<*mut $py::PyObject>()
            }
        }
    };
}

// Python 3.13
Python3Impl!(v3_13_0);

impl InterpreterState for v3_13_0::PyInterpreterState {
    type ThreadState = v3_13_0::PyThreadState;
    type Object = v3_13_0::PyObject;
    type StringObject = v3_13_0::PyUnicodeObject;
    type ListObject = v3_13_0::PyListObject;
    type TupleObject = v3_13_0::PyTupleObject;
    const HAS_GIL_RUNTIME_STATE: bool = true;

    fn threadstate_ptr_ptr(interpreter_address: usize) -> *const *const Self::ThreadState {
        (interpreter_address + std::mem::offset_of!(Self, threads.head))
            as *const *const Self::ThreadState
    }
    fn modules_ptr_ptr(interpreter_address: usize) -> *const *const Self::Object {
        (interpreter_address + std::mem::offset_of!(Self, imports.modules))
            as *const *const Self::Object
    }
}

impl ThreadState for v3_13_0::PyThreadState {
    type FrameObject = v3_13_0::_PyInterpreterFrame;
    type InterpreterState = v3_13_0::PyInterpreterState;
    fn frame_address(&self) -> Option<usize> {
        None
    }
    fn frame(&self, _addr: Option<usize>) -> *mut Self::FrameObject {
        self.current_frame
    }
    fn thread_id(&self) -> u64 {
        self.thread_id as u64
    }
    fn native_thread_id(&self) -> Option<u64> {
        Some(self.native_thread_id as u64)
    }
    fn next(&self) -> *mut Self {
        self.next
    }
    fn interp(&self) -> *mut Self::InterpreterState {
        self.interp
    }
}

impl FrameObject for v3_13_0::_PyInterpreterFrame {
    type CodeObject = v3_13_0::PyCodeObject;
    fn code(&self) -> *mut Self::CodeObject {
        self.f_executable as *mut v3_13_0::PyCodeObject
    }
    fn lasti(&self) -> i32 {
        let co_code = self.f_executable as *const _ as *const u8;
        unsafe { (self.instr_ptr as *const u8).offset_from(co_code) as i32 }
    }
    fn back(&self) -> *mut Self {
        self.previous
    }
    fn is_entry(&self) -> bool {
        // https://github.com/python/cpython/pull/108036#issuecomment-1684458828
        const FRAME_OWNED_BY_CSTACK: ::std::os::raw::c_char = 3;
        self.owner == FRAME_OWNED_BY_CSTACK
    }
}

impl Object for v3_13_0::PyObject {
    type TypeObject = v3_13_0::PyTypeObject;
    fn ob_type(&self) -> *mut Self::TypeObject {
        self.ob_type as *mut Self::TypeObject
    }
}

impl TypeObject for v3_13_0::PyTypeObject {
    fn name(&self) -> *const ::std::os::raw::c_char {
        self.tp_name
    }
    fn dictoffset(&self) -> isize {
        self.tp_dictoffset
    }
    fn flags(&self) -> usize {
        self.tp_flags as usize
    }
}

CompactCodeObjectImpl!(v3_13_0, PyBytesObject, PyUnicodeObject);

// Python 3.12
// TODO: this shares some similarities with python 3.11, we should refactor to a common macro
Python3Impl!(v3_12_0);

impl InterpreterState for v3_12_0::PyInterpreterState {
    type ThreadState = v3_12_0::PyThreadState;
    type Object = v3_12_0::PyObject;
    type StringObject = v3_12_0::PyUnicodeObject;
    type ListObject = v3_12_0::PyListObject;
    type TupleObject = v3_12_0::PyTupleObject;
    const HAS_GIL_RUNTIME_STATE: bool = true;

    fn threadstate_ptr_ptr(interpreter_address: usize) -> *const *const Self::ThreadState {
        (interpreter_address + std::mem::offset_of!(Self, threads.head))
            as *const *const Self::ThreadState
    }
    fn modules_ptr_ptr(interpreter_address: usize) -> *const *const Self::Object {
        (interpreter_address + std::mem::offset_of!(Self, imports.modules))
            as *const *const Self::Object
    }
}

impl ThreadState for v3_12_0::PyThreadState {
    type FrameObject = v3_12_0::_PyInterpreterFrame;
    type InterpreterState = v3_12_0::PyInterpreterState;
    fn frame_address(&self) -> Option<usize> {
        // There must be a way to get the offset here without actually creating the object
        let cframe: v3_12_0::_PyCFrame = Default::default();
        let current_frame_offset = offset_of(&cframe, &cframe.current_frame);
        Some(self.cframe as usize + current_frame_offset)
    }
    fn frame(&self, addr: Option<usize>) -> *mut Self::FrameObject {
        addr.unwrap() as *mut Self::FrameObject
    }
    fn thread_id(&self) -> u64 {
        self.thread_id as u64
    }
    fn native_thread_id(&self) -> Option<u64> {
        Some(self.native_thread_id as u64)
    }
    fn next(&self) -> *mut Self {
        self.next
    }
    fn interp(&self) -> *mut Self::InterpreterState {
        self.interp
    }
}

impl FrameObject for v3_12_0::_PyInterpreterFrame {
    type CodeObject = v3_12_0::PyCodeObject;
    fn code(&self) -> *mut Self::CodeObject {
        self.f_code
    }
    fn lasti(&self) -> i32 {
        // this returns the delta from the co_code, but we need to adjust for the
        // offset from co_code.co_code_adaptive. This is slightly easier to do in the
        // get_line_number code, so will adjust there
        let co_code = self.f_code as *const _ as *const u8;
        unsafe { (self.prev_instr as *const u8).offset_from(co_code) as i32 }
    }
    fn back(&self) -> *mut Self {
        self.previous
    }
    fn is_entry(&self) -> bool {
        // https://github.com/python/cpython/pull/108036#issuecomment-1684458828
        const FRAME_OWNED_BY_CSTACK: ::std::os::raw::c_char = 3;
        self.owner == FRAME_OWNED_BY_CSTACK
    }
}

impl Object for v3_12_0::PyObject {
    type TypeObject = v3_12_0::PyTypeObject;
    fn ob_type(&self) -> *mut Self::TypeObject {
        self.ob_type as *mut Self::TypeObject
    }
}

impl TypeObject for v3_12_0::PyTypeObject {
    fn name(&self) -> *const ::std::os::raw::c_char {
        self.tp_name
    }
    fn dictoffset(&self) -> isize {
        self.tp_dictoffset
    }
    fn flags(&self) -> usize {
        self.tp_flags as usize
    }
}

CompactCodeObjectImpl!(v3_12_0, PyBytesObject, PyUnicodeObject);

// Python 3.11
// Python3.11 is sufficiently different from previous versions that we can't use the macros above
// to generate implementations of these traits.
Python3Impl!(v3_11_0);

impl InterpreterState for v3_11_0::PyInterpreterState {
    type ThreadState = v3_11_0::PyThreadState;
    type Object = v3_11_0::PyObject;
    type StringObject = v3_11_0::PyUnicodeObject;
    type ListObject = v3_11_0::PyListObject;
    type TupleObject = v3_11_0::PyTupleObject;

    fn threadstate_ptr_ptr(interpreter_address: usize) -> *const *const Self::ThreadState {
        (interpreter_address + std::mem::offset_of!(Self, threads.head))
            as *const *const Self::ThreadState
    }
    fn modules_ptr_ptr(interpreter_address: usize) -> *const *const Self::Object {
        (interpreter_address + std::mem::offset_of!(Self, modules)) as *const *const Self::Object
    }
}

impl ThreadState for v3_11_0::PyThreadState {
    type FrameObject = v3_11_0::_PyInterpreterFrame;
    type InterpreterState = v3_11_0::PyInterpreterState;
    fn frame_address(&self) -> Option<usize> {
        // There must be a way to get the offset here without actually creating the object
        let cframe: v3_11_0::_PyCFrame = Default::default();
        let current_frame_offset = offset_of(&cframe, &cframe.current_frame);
        Some(self.cframe as usize + current_frame_offset)
    }
    fn frame(&self, addr: Option<usize>) -> *mut Self::FrameObject {
        addr.unwrap() as *mut Self::FrameObject
    }
    fn thread_id(&self) -> u64 {
        self.thread_id as u64
    }
    fn native_thread_id(&self) -> Option<u64> {
        Some(self.native_thread_id as u64)
    }
    fn next(&self) -> *mut Self {
        self.next
    }
    fn interp(&self) -> *mut Self::InterpreterState {
        self.interp
    }
}

impl FrameObject for v3_11_0::_PyInterpreterFrame {
    type CodeObject = v3_11_0::PyCodeObject;
    fn code(&self) -> *mut Self::CodeObject {
        self.f_code
    }
    fn lasti(&self) -> i32 {
        // this returns the delta from the co_code, but we need to adjust for the
        // offset from co_code.co_code_adaptive. This is slightly easier to do in the
        // get_line_number code, so will adjust there
        let co_code = self.f_code as *const _ as *const u8;
        unsafe { (self.prev_instr as *const u8).offset_from(co_code) as i32 }
    }
    fn back(&self) -> *mut Self {
        self.previous
    }
    fn is_entry(&self) -> bool {
        self.is_entry
    }
}

impl Object for v3_11_0::PyObject {
    type TypeObject = v3_11_0::PyTypeObject;
    fn ob_type(&self) -> *mut Self::TypeObject {
        self.ob_type as *mut Self::TypeObject
    }
}

impl TypeObject for v3_11_0::PyTypeObject {
    fn name(&self) -> *const ::std::os::raw::c_char {
        self.tp_name
    }
    fn dictoffset(&self) -> isize {
        self.tp_dictoffset
    }
    fn flags(&self) -> usize {
        self.tp_flags as usize
    }
}

CompactCodeObjectImpl!(v3_11_0, PyBytesObject, PyUnicodeObject);

// Python 3.10
Python3Impl!(v3_10_0);
PythonCommonImpl!(v3_10_0, PyUnicodeObject);

impl CodeObject for v3_10_0::PyCodeObject {
    type BytesObject = v3_10_0::PyBytesObject;
    type StringObject = v3_10_0::PyUnicodeObject;
    type TupleObject = v3_10_0::PyTupleObject;

    fn name(&self) -> *mut Self::StringObject {
        self.co_name as *mut Self::StringObject
    }
    fn filename(&self) -> *mut Self::StringObject {
        self.co_filename as *mut Self::StringObject
    }
    fn line_table(&self) -> *mut Self::BytesObject {
        self.co_linetable as *mut Self::BytesObject
    }
    fn first_lineno(&self) -> i32 {
        self.co_firstlineno
    }
    fn nlocals(&self) -> i32 {
        self.co_nlocals
    }
    fn argcount(&self) -> i32 {
        self.co_argcount
    }
    fn varnames(&self) -> *mut Self::TupleObject {
        self.co_varnames as *mut Self::TupleObject
    }
    fn get_line_number(&self, lasti: i32, table: &[u8]) -> i32 {
        // in Python 3.10 we need to double the lasti instruction value here (and no I don't know why)
        // https://github.com/python/cpython/blob/7b88f63e1dd4006b1a08b9c9f087dd13449ecc76/Python/ceval.c#L5999
        // Whereas in python versions up to 3.9 we didn't.
        // https://github.com/python/cpython/blob/3.9/Python/ceval.c#L4713-L4714
        let lasti = 2 * lasti as i32;

        // unpack the line table. format is specified here:
        // https://github.com/python/cpython/blob/3.10/Objects/lnotab_notes.txt
        let size = table.len();
        let mut i = 0;
        let mut line_number: i32 = self.first_lineno();
        let mut bytecode_address: i32 = 0;
        while (i + 1) < size {
            let delta: u8 = table[i];
            let line_delta: i8 = unsafe { std::mem::transmute(table[i + 1]) };
            i += 2;

            if line_delta == -128 {
                continue;
            }

            line_number += i32::from(line_delta);
            bytecode_address += i32::from(delta);
            if bytecode_address > lasti {
                break;
            }
        }

        line_number
    }
}

// Python 3.9
PythonCommonImpl!(v3_9_5, PyUnicodeObject);
PythonCodeObjectImpl!(v3_9_5, PyBytesObject, PyUnicodeObject);
Python3Impl!(v3_9_5);

// Python 3.8
PythonCommonImpl!(v3_8_0, PyUnicodeObject);
PythonCodeObjectImpl!(v3_8_0, PyBytesObject, PyUnicodeObject);
Python3Impl!(v3_8_0);

// Python 3.7
PythonCommonImpl!(v3_7_0, PyUnicodeObject);
PythonCodeObjectImpl!(v3_7_0, PyBytesObject, PyUnicodeObject);
Python3Impl!(v3_7_0);

// Python 3.6
PythonCommonImpl!(v3_6_6, PyUnicodeObject);
PythonCodeObjectImpl!(v3_6_6, PyBytesObject, PyUnicodeObject);
Python3Impl!(v3_6_6);

// python 3.5 and python 3.4
PythonCommonImpl!(v3_5_5, PyUnicodeObject);
PythonCodeObjectImpl!(v3_5_5, PyBytesObject, PyUnicodeObject);
Python3Impl!(v3_5_5);

// python 3.3
PythonCommonImpl!(v3_3_7, PyUnicodeObject);
PythonCodeObjectImpl!(v3_3_7, PyBytesObject, PyUnicodeObject);
Python3Impl!(v3_3_7);

// Python 2.7
PythonCommonImpl!(v2_7_15, PyStringObject);
PythonCodeObjectImpl!(v2_7_15, PyStringObject, PyStringObject);
impl BytesObject for v2_7_15::PyStringObject {
    fn size(&self) -> usize {
        self.ob_size as usize
    }
    fn address(&self, base: usize) -> usize {
        base + offset_of(self, &self.ob_sval)
    }
}

impl StringObject for v2_7_15::PyStringObject {
    fn ascii(&self) -> bool {
        true
    }
    fn kind(&self) -> u32 {
        1
    }
    fn size(&self) -> usize {
        self.ob_size as usize
    }
    fn address(&self, base: usize) -> usize {
        base + offset_of(self, &self.ob_sval)
    }
}

impl ListObject for v2_7_15::PyListObject {
    type Object = v2_7_15::PyObject;
    fn size(&self) -> usize {
        self.ob_size as usize
    }
    fn item(&self) -> *mut *mut Self::Object {
        self.ob_item
    }
}

impl TupleObject for v2_7_15::PyTupleObject {
    fn size(&self) -> usize {
        self.ob_size as usize
    }
    fn address(&self, base: usize, index: usize) -> usize {
        base + offset_of(self, &self.ob_item)
            + index * std::mem::size_of::<*mut v2_7_15::PyObject>()
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_py3_11_line_numbers() {
        use crate::python_bindings::v3_11_0::PyCodeObject;
        let code = PyCodeObject {
            co_firstlineno: 4,
            ..Default::default()
        };

        let table = [
            128_u8, 0, 221, 4, 8, 132, 74, 136, 118, 209, 4, 22, 212, 4, 22, 208, 4, 22, 208, 4,
            22, 208, 4, 22,
        ];
        assert_eq!(code.get_line_number(214, &table), 5);
    }
}