Skip to content

Commit f8a7823

Browse files
committed
Keep monitoring dispatch in interpreter-local state
Use immutable source metadata and native code identity for virtual monitoring layers; preserve callback continuations and ordinary branch event sites. Assisted-by: OpenAI Codex: model version unavailable
1 parent c672599 commit f8a7823

16 files changed

Lines changed: 2256 additions & 1072 deletions

File tree

‎crates/compiler-core/src/bytecode.rs‎

Lines changed: 245 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -319,6 +319,10 @@ impl Constant for ConstantData {
319319
pub trait ConstantBag: Sized + Copy {
320320
type Constant: Constant;
321321

322+
fn code_units_from_bytes(&self, bytes: &[u8]) -> Result<CodeUnits, MarshalError> {
323+
CodeUnits::try_from(bytes)
324+
}
325+
322326
fn make_constant<C: Constant>(&self, constant: BorrowedConstant<'_, C>) -> Self::Constant;
323327

324328
fn make_int(&self, value: BigInt) -> Self::Constant;
@@ -627,6 +631,10 @@ impl TryFrom<[u8; 2]> for CodeUnit {
627631
}
628632

629633
pub struct CodeUnits {
634+
// Construction provenance, never updated by runtime specialization. Keep
635+
// original opcode identity: GET_ITER fixup does not apply to its specialized forms.
636+
source: Box<[CodeUnit]>,
637+
source_layout: CodeSourceLayout,
630638
units: UnsafeCell<Box<[CodeUnit]>>,
631639
adaptive_counters: Box<[AtomicU16]>,
632640
/// Pointer-sized cache entries for descriptor pointers.
@@ -635,6 +643,13 @@ pub struct CodeUnits {
635643
pointer_cache: Box<[AtomicUsize]>,
636644
}
637645

646+
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
647+
pub enum CodeSourceLayout {
648+
Complete,
649+
Opaque { index: usize },
650+
Truncated { index: usize },
651+
}
652+
638653
// SAFETY: All cache operations use atomic read/write instructions.
639654
// - replace_op / compare_exchange_op: AtomicU8 store/CAS (Release)
640655
// - cache read/write: AtomicU16 load/store (Relaxed)
@@ -646,24 +661,20 @@ unsafe impl Sync for CodeUnits {}
646661

647662
impl Clone for CodeUnits {
648663
fn clone(&self) -> Self {
649-
// SAFETY: No concurrent mutation during clone — cloning is only done
650-
// during code object construction or marshaling, not while instrumented.
651-
let units = unsafe { &*self.units.get() }.clone();
652-
let adaptive_counters = self
653-
.adaptive_counters
654-
.iter()
655-
.map(|c| AtomicU16::new(c.load(Ordering::Relaxed)))
656-
.collect();
657-
let pointer_cache = self
658-
.pointer_cache
659-
.iter()
660-
.map(|c| AtomicUsize::new(c.load(Ordering::Relaxed)))
661-
.collect();
662-
Self {
663-
units: UnsafeCell::new(units),
664-
adaptive_counters,
665-
pointer_cache,
664+
let mut cloned = Self::from(self.source.to_vec());
665+
if self.source_layout == CodeSourceLayout::Complete {
666+
let units = cloned.units.get_mut();
667+
let mut i = 0;
668+
while i < units.len() {
669+
units[i].op = units[i].op.deoptimize();
670+
let end = i + 1 + units[i].op.cache_entries();
671+
for cache in &mut units[i + 1..end] {
672+
*cache = CodeUnit::new(Instruction::Cache, 0.into());
673+
}
674+
i = end;
675+
}
666676
}
677+
cloned
667678
}
668679
}
669680

@@ -701,6 +712,8 @@ impl<const N: usize> From<[CodeUnit; N]> for CodeUnits {
701712
impl From<Vec<CodeUnit>> for CodeUnits {
702713
fn from(value: Vec<CodeUnit>) -> Self {
703714
let units = value.into_boxed_slice();
715+
let source = units.clone();
716+
let source_layout = Self::classify_source(&source);
704717
let len = units.len();
705718
let adaptive_counters = (0..len)
706719
.map(|_| AtomicU16::new(0))
@@ -711,6 +724,8 @@ impl From<Vec<CodeUnit>> for CodeUnits {
711724
.collect::<Vec<_>>()
712725
.into_boxed_slice();
713726
Self {
727+
source,
728+
source_layout,
714729
units: UnsafeCell::new(units),
715730
adaptive_counters,
716731
pointer_cache,
@@ -736,6 +751,61 @@ impl Deref for CodeUnits {
736751
}
737752

738753
impl CodeUnits {
754+
fn classify_source(units: &[CodeUnit]) -> CodeSourceLayout {
755+
let mut i = 0;
756+
while i < units.len() {
757+
if matches!(
758+
units[i].op,
759+
Instruction::InstrumentedLine
760+
| Instruction::InstrumentedInstruction
761+
| Instruction::EnterExecutor
762+
| Instruction::TraceRecord
763+
| Instruction::Reserved
764+
| Instruction::InterpreterExit
765+
) {
766+
return CodeSourceLayout::Opaque { index: i };
767+
}
768+
let Some(end) = i.checked_add(1 + units[i].op.cache_entries()) else {
769+
return CodeSourceLayout::Truncated { index: i };
770+
};
771+
if end > units.len() {
772+
return CodeSourceLayout::Truncated { index: i };
773+
}
774+
i = end;
775+
}
776+
CodeSourceLayout::Complete
777+
}
778+
779+
pub const fn source_layout(&self) -> CodeSourceLayout {
780+
self.source_layout
781+
}
782+
783+
/// Immutable source before the first opaque or truncated instruction start.
784+
/// This includes cache units: consumers must walk by proven opcode widths,
785+
/// not decode every unit as an instruction. It proves no branch validity.
786+
pub fn proven_source_prefix(&self) -> &[CodeUnit] {
787+
let end = match self.source_layout {
788+
CodeSourceLayout::Complete => self.source.len(),
789+
CodeSourceLayout::Opaque { index } | CodeSourceLayout::Truncated { index } => index,
790+
};
791+
&self.source[..end]
792+
}
793+
794+
/// Parse external bytecode without accepting wrappers whose original
795+
/// operation requires monitoring metadata absent from the input.
796+
pub fn from_external_bytes(bytes: &[u8]) -> Result<Self, MarshalError> {
797+
let units = Self::try_from(bytes)?;
798+
if let CodeSourceLayout::Opaque { index } = units.source_layout
799+
&& matches!(
800+
units.source[index].op,
801+
Instruction::InstrumentedLine | Instruction::InstrumentedInstruction
802+
)
803+
{
804+
return Err(MarshalError::InvalidBytecode);
805+
}
806+
Ok(units)
807+
}
808+
739809
/// `fixup_getiter` applied to every `GET_ITER` by `_PyCode_Quicken`.
740810
///
741811
/// The compiler can't know if `types.coroutine()` will be called, so a
@@ -748,10 +818,18 @@ impl CodeUnits {
748818
};
749819
let mut i = 0;
750820
let units = self.units.get_mut();
751-
while i < units.len() {
752-
let unit = &mut units[i];
821+
let stop = match self.source_layout {
822+
CodeSourceLayout::Complete => self.source.len(),
823+
CodeSourceLayout::Opaque { index } => index,
824+
// Preserve the existing literal GET_ITER fixup even if the input
825+
// ends before that instruction's cache extent.
826+
CodeSourceLayout::Truncated { index } => index + 1,
827+
};
828+
while i < stop {
829+
let unit = &mut self.source[i];
753830
if matches!(unit.op, Instruction::GetIter { .. }) && u8::from(unit.arg) != 0 {
754831
unit.arg = (mode as u8).into();
832+
units[i].arg = unit.arg;
755833
}
756834
i += 1 + unit.op.cache_entries();
757835
}
@@ -969,12 +1047,13 @@ impl CodeUnits {
9691047
&self,
9701048
resolve: impl Fn(usize, Instruction) -> Instruction,
9711049
) -> Vec<u8> {
972-
let len = self.len();
1050+
let len = self.source.len();
9731051
let mut out = Vec::with_capacity(len * 2);
9741052
let mut i = 0;
9751053
while i < len {
976-
let op = resolve(i, self.read_op(i)).deoptimize();
977-
let arg = self.read_arg(i);
1054+
let unit = self.source[i];
1055+
let op = resolve(i, unit.op).deoptimize();
1056+
let arg = unit.arg;
9781057
let caches = op.cache_entries();
9791058
out.push(u8::from(op));
9801059
out.push(u8::from(arg));
@@ -1471,6 +1550,150 @@ impl<C: Constant> fmt::Debug for CodeObject<C> {
14711550

14721551
#[cfg(test)]
14731552
mod tests {
1553+
#[test]
1554+
fn code_source_clone_ignores_runtime_storage() {
1555+
use super::*;
1556+
let code = CodeUnits::from([
1557+
CodeUnit::new(Opcode::LoadGlobal.as_instruction(), 7.into()),
1558+
CodeUnit::new(Instruction::Cache, 0.into()),
1559+
CodeUnit::new(Instruction::Cache, 0.into()),
1560+
CodeUnit::new(Instruction::Cache, 0.into()),
1561+
CodeUnit::new(Instruction::Cache, 0.into()),
1562+
]);
1563+
let original = code.original_bytes();
1564+
// These are bounded scalar storage writes, not bytecode execution.
1565+
unsafe {
1566+
code.replace_op(0, Instruction::LoadGlobalModule);
1567+
code.write_cache_u16(1, 123);
1568+
code.write_adaptive_counter(1, 456);
1569+
code.write_cache_ptr(1, 789);
1570+
}
1571+
let cloned = code.clone();
1572+
assert_eq!(code.original_bytes(), original);
1573+
assert_eq!(cloned.original_bytes(), original);
1574+
assert!(matches!(cloned.read_op(0), Instruction::LoadGlobal { .. }));
1575+
assert_eq!(cloned.read_cache_u16(1), 0);
1576+
assert_eq!(cloned.read_adaptive_counter(1), 0);
1577+
assert_eq!(cloned.read_cache_ptr(1), 0);
1578+
}
1579+
1580+
#[test]
1581+
fn code_source_normalization_preserves_family_layout() {
1582+
use super::*;
1583+
let mut count = 0;
1584+
for byte in 0..=u8::MAX {
1585+
let Ok(op) = Opcode::try_from(byte) else {
1586+
continue;
1587+
};
1588+
let Some(base) = op.deopt().or_else(|| op.to_base()) else {
1589+
continue;
1590+
};
1591+
assert_eq!(op.cache_entries(), base.cache_entries());
1592+
let mut units =
1593+
vec![CodeUnit::new(Instruction::Cache, 0.into()); 1 + op.cache_entries()];
1594+
units[0] = CodeUnit::new(op.as_instruction(), 7.into());
1595+
let code = CodeUnits::from(units);
1596+
assert_eq!(code.read_op(0).as_opcode(), op);
1597+
let cloned = code.clone();
1598+
assert_eq!(cloned.read_op(0).as_opcode(), base);
1599+
assert_eq!(u8::from(cloned.read_arg(0)), 7);
1600+
assert_eq!(code.original_bytes(), cloned.original_bytes());
1601+
count += 1;
1602+
}
1603+
assert_eq!(count, 110); // 91 specialized and 19 direct instrumented forms.
1604+
}
1605+
1606+
#[test]
1607+
fn code_source_get_iter_fixup_retains_origin() {
1608+
use super::*;
1609+
let mut specialized = CodeUnits::from([
1610+
CodeUnit::new(Instruction::GetIterSelf, 1.into()),
1611+
CodeUnit::new(Instruction::Cache, 0.into()),
1612+
]);
1613+
specialized.fixup_get_iter(CodeFlags::COROUTINE);
1614+
let original = specialized.original_bytes();
1615+
let mut cloned = specialized.clone();
1616+
cloned.fixup_get_iter(CodeFlags::empty());
1617+
assert_eq!(cloned.original_bytes(), original);
1618+
assert_eq!(u8::from(cloned.read_arg(0)), 1);
1619+
let mut literal = CodeUnits::from([
1620+
CodeUnit::new(Opcode::GetIter.as_instruction(), 1.into()),
1621+
CodeUnit::new(Instruction::Cache, 0.into()),
1622+
]);
1623+
literal.fixup_get_iter(CodeFlags::empty());
1624+
assert_eq!(
1625+
u8::from(literal.read_arg(0)),
1626+
oparg::GET_ITER_YIELD_FROM_CORO_CHECK as u8
1627+
);
1628+
let mut cloned = literal.clone();
1629+
cloned.fixup_get_iter(CodeFlags::COROUTINE);
1630+
assert_eq!(
1631+
u8::from(cloned.read_arg(0)),
1632+
oparg::GET_ITER_YIELD_FROM_NO_CHECK as u8
1633+
);
1634+
assert_eq!(
1635+
cloned.original_bytes()[1],
1636+
oparg::GET_ITER_YIELD_FROM_NO_CHECK as u8
1637+
);
1638+
}
1639+
1640+
#[test]
1641+
fn code_source_external_wrappers_are_not_cache_bytes() {
1642+
use super::*;
1643+
for wrapper in [
1644+
Instruction::InstrumentedLine,
1645+
Instruction::InstrumentedInstruction,
1646+
] {
1647+
let bytes = [u8::from(wrapper), 0];
1648+
assert!(CodeUnits::from_external_bytes(&bytes).is_err());
1649+
let trusted = CodeUnits::try_from(bytes.as_slice()).unwrap();
1650+
assert_eq!(
1651+
trusted.source_layout(),
1652+
CodeSourceLayout::Opaque { index: 0 }
1653+
);
1654+
assert_eq!(trusted.clone().read_op(0).as_opcode(), wrapper.as_opcode());
1655+
let cached = [u8::from(Opcode::GetIter), 0, u8::from(wrapper), 0];
1656+
assert_eq!(
1657+
CodeUnits::from_external_bytes(&cached)
1658+
.unwrap()
1659+
.source_layout(),
1660+
CodeSourceLayout::Complete
1661+
);
1662+
}
1663+
}
1664+
1665+
#[test]
1666+
fn code_source_unsupported_barriers_do_not_scan_suffix() {
1667+
for barrier in [Opcode::Reserved, Opcode::InterpreterExit] {
1668+
for wrapper in [Opcode::InstrumentedLine, Opcode::InstrumentedInstruction] {
1669+
let bytes = [u8::from(barrier), 7, u8::from(wrapper), 0];
1670+
let code = CodeUnits::from_external_bytes(&bytes).unwrap();
1671+
assert_eq!(code.source_layout(), CodeSourceLayout::Opaque { index: 0 });
1672+
assert_eq!(code.clone().source_layout(), code.source_layout());
1673+
}
1674+
}
1675+
}
1676+
1677+
#[test]
1678+
fn code_source_unavailable_layout_stops_without_rejection() {
1679+
use super::*;
1680+
let opaque = [
1681+
u8::from(Opcode::EnterExecutor),
1682+
0,
1683+
u8::from(Opcode::InstrumentedLine),
1684+
0,
1685+
];
1686+
let code = CodeUnits::from_external_bytes(&opaque).unwrap();
1687+
assert_eq!(code.source_layout(), CodeSourceLayout::Opaque { index: 0 });
1688+
let truncated = [u8::from(Opcode::LoadGlobal), 0];
1689+
let code = CodeUnits::from_external_bytes(&truncated).unwrap();
1690+
assert_eq!(
1691+
code.source_layout(),
1692+
CodeSourceLayout::Truncated { index: 0 }
1693+
);
1694+
assert_eq!(code.clone().source_layout(), code.source_layout());
1695+
}
1696+
14741697
use super::*;
14751698
use alloc::{vec, vec::Vec};
14761699

‎crates/compiler-core/src/frozen.rs‎

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,17 @@ pub struct FrozenCodeObject<B> {
1515
}
1616

1717
impl<B: AsRef<[u8]>> FrozenCodeObject<B> {
18-
/// Decode a frozen code object
18+
/// Decode externally supplied frozen bytes through a recoverable error path.
19+
pub fn try_decode<Bag: AsBag>(
20+
&self,
21+
bag: Bag,
22+
) -> Result<CodeObject<<Bag::Bag as ConstantBag>::Constant>, marshal::MarshalError> {
23+
let decompressed = lz4_flex::decompress_size_prepended(self.bytes.as_ref())
24+
.map_err(|_| marshal::MarshalError::InvalidBytecode)?;
25+
marshal::deserialize_code_external(&mut &decompressed[..], bag.as_bag())
26+
}
27+
28+
/// Decode trusted generated frozen code. External data must use `try_decode`.
1929
#[inline]
2030
pub fn decode<Bag: AsBag>(&self, bag: Bag) -> CodeObject<<Bag::Bag as ConstantBag>::Constant> {
2131
Self::_decode(self.bytes.as_ref(), bag.as_bag())

0 commit comments

Comments
 (0)