Skip to content

Commit eaa75b1

Browse files
committed
Preserve code construction provenance across execution storage
Extract the independent code-source, clone, co_code and fallible decoding foundation from #9439. Interpreter-local monitoring dispatch remains in the dependent original PR. Assisted-by: OpenAI Codex: model version unavailable
1 parent 84d7afc commit eaa75b1

7 files changed

Lines changed: 366 additions & 48 deletions

File tree

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

Lines changed: 234 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,50 @@ 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+
/// Parse external bytecode without accepting wrappers whose original
784+
/// operation requires monitoring metadata absent from the input.
785+
pub fn from_external_bytes(bytes: &[u8]) -> Result<Self, MarshalError> {
786+
let units = Self::try_from(bytes)?;
787+
if let CodeSourceLayout::Opaque { index } = units.source_layout
788+
&& matches!(
789+
units.source[index].op,
790+
Instruction::InstrumentedLine | Instruction::InstrumentedInstruction
791+
)
792+
{
793+
return Err(MarshalError::InvalidBytecode);
794+
}
795+
Ok(units)
796+
}
797+
739798
/// `fixup_getiter` applied to every `GET_ITER` by `_PyCode_Quicken`.
740799
///
741800
/// The compiler can't know if `types.coroutine()` will be called, so a
@@ -748,10 +807,18 @@ impl CodeUnits {
748807
};
749808
let mut i = 0;
750809
let units = self.units.get_mut();
751-
while i < units.len() {
752-
let unit = &mut units[i];
810+
let stop = match self.source_layout {
811+
CodeSourceLayout::Complete => self.source.len(),
812+
CodeSourceLayout::Opaque { index } => index,
813+
// Preserve the existing literal GET_ITER fixup even if the input
814+
// ends before that instruction's cache extent.
815+
CodeSourceLayout::Truncated { index } => index + 1,
816+
};
817+
while i < stop {
818+
let unit = &mut self.source[i];
753819
if matches!(unit.op, Instruction::GetIter { .. }) && u8::from(unit.arg) != 0 {
754820
unit.arg = (mode as u8).into();
821+
units[i].arg = unit.arg;
755822
}
756823
i += 1 + unit.op.cache_entries();
757824
}
@@ -969,12 +1036,13 @@ impl CodeUnits {
9691036
&self,
9701037
resolve: impl Fn(usize, Instruction) -> Instruction,
9711038
) -> Vec<u8> {
972-
let len = self.len();
1039+
let len = self.source.len();
9731040
let mut out = Vec::with_capacity(len * 2);
9741041
let mut i = 0;
9751042
while i < len {
976-
let op = resolve(i, self.read_op(i)).deoptimize();
977-
let arg = self.read_arg(i);
1043+
let unit = self.source[i];
1044+
let op = resolve(i, unit.op).deoptimize();
1045+
let arg = unit.arg;
9781046
let caches = op.cache_entries();
9791047
out.push(u8::from(op));
9801048
out.push(u8::from(arg));
@@ -1471,6 +1539,150 @@ impl<C: Constant> fmt::Debug for CodeObject<C> {
14711539

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

‎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)