342 lines
10 KiB
Rust
342 lines
10 KiB
Rust
//! Shared PBX v1 resource limits and structured validation failures.
|
|
//! Counters are deterministic; a failed reservation never changes usage.
|
|
use std::fmt;
|
|
|
|
const MIB: u64 = 1_048_576;
|
|
|
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
|
pub enum LoadCode {
|
|
InvalidFormat,
|
|
UnsupportedFormat,
|
|
InvalidReference,
|
|
InvalidRegistry,
|
|
InvalidCode,
|
|
ResourceLimit,
|
|
InvalidEntrypoint,
|
|
}
|
|
impl LoadCode {
|
|
pub const fn tag(self) -> &'static str {
|
|
match self {
|
|
Self::InvalidFormat => "LOAD_INVALID_FORMAT",
|
|
Self::UnsupportedFormat => "LOAD_UNSUPPORTED_FORMAT",
|
|
Self::InvalidReference => "LOAD_INVALID_REFERENCE",
|
|
Self::InvalidRegistry => "LOAD_INVALID_REGISTRY",
|
|
Self::InvalidCode => "LOAD_INVALID_CODE",
|
|
Self::ResourceLimit => "LOAD_RESOURCE_LIMIT",
|
|
Self::InvalidEntrypoint => "LOAD_INVALID_ENTRYPOINT",
|
|
}
|
|
}
|
|
}
|
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
|
pub enum LoadReason {
|
|
Magic,
|
|
Version,
|
|
Endianness,
|
|
Reserved,
|
|
SectionKind,
|
|
MissingSection,
|
|
DuplicateSection,
|
|
Overlap,
|
|
Truncated,
|
|
TrailingBytes,
|
|
InvalidFlag,
|
|
Utf8,
|
|
Category,
|
|
Builtin,
|
|
TypeId,
|
|
FunctionId,
|
|
OwnerCategory,
|
|
TraitCategory,
|
|
DuplicateBuiltin,
|
|
DuplicateArray,
|
|
ArrayCycle,
|
|
DuplicateImplementation,
|
|
MethodCount,
|
|
Signature,
|
|
CodeRange,
|
|
FrameSlots,
|
|
ReturnSlots,
|
|
Overflow,
|
|
Limit,
|
|
Allocation,
|
|
ConstantTag,
|
|
DebugRange,
|
|
DuplicateSyscall,
|
|
UnknownOpcode,
|
|
LocalSlot,
|
|
JumpTarget,
|
|
InstructionBoundary,
|
|
BooleanImmediate,
|
|
ConstantIndex,
|
|
NativeId,
|
|
UnpatchedHostcall,
|
|
}
|
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
|
#[repr(usize)]
|
|
pub enum LoadResource {
|
|
PbxBytes,
|
|
CodeBytes,
|
|
Types,
|
|
Functions,
|
|
Implementations,
|
|
NestedRecords,
|
|
NameBytes,
|
|
RegistryBytes,
|
|
TemporaryBytes,
|
|
Work,
|
|
ConstantEntries,
|
|
ConstantStringBytes,
|
|
}
|
|
const RESOURCE_COUNT: usize = 12;
|
|
|
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
|
pub enum IdDomain {
|
|
Type,
|
|
Function,
|
|
Implementation,
|
|
}
|
|
|
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
|
pub struct LoadFailure {
|
|
pub code: LoadCode,
|
|
pub reason: LoadReason,
|
|
pub section: Option<u32>,
|
|
pub offset: Option<usize>,
|
|
pub record: Option<u32>,
|
|
pub member: Option<u32>,
|
|
pub id_domain: Option<IdDomain>,
|
|
pub referenced_id: Option<u32>,
|
|
pub function: Option<u32>,
|
|
pub pc: Option<u32>,
|
|
pub resource: Option<LoadResource>,
|
|
pub requested: Option<u64>,
|
|
pub limit: Option<u64>,
|
|
}
|
|
impl LoadFailure {
|
|
pub fn new(code: LoadCode, reason: LoadReason) -> Self {
|
|
Self {
|
|
code,
|
|
reason,
|
|
section: None,
|
|
offset: None,
|
|
record: None,
|
|
member: None,
|
|
id_domain: None,
|
|
referenced_id: None,
|
|
function: None,
|
|
pc: None,
|
|
resource: None,
|
|
requested: None,
|
|
limit: None,
|
|
}
|
|
}
|
|
pub fn at(mut self, section: u32, offset: usize) -> Self {
|
|
self.section = Some(section);
|
|
self.offset = Some(offset);
|
|
self
|
|
}
|
|
pub fn record(mut self, record: u32) -> Self {
|
|
self.record = Some(record);
|
|
self
|
|
}
|
|
pub fn member(mut self, member: u32) -> Self {
|
|
self.member = Some(member);
|
|
self
|
|
}
|
|
pub fn in_section(mut self, section: u32) -> Self {
|
|
self.section = Some(section);
|
|
self
|
|
}
|
|
pub fn reference(mut self, domain: IdDomain, id: u32) -> Self {
|
|
self.id_domain = Some(domain);
|
|
self.referenced_id = Some(id);
|
|
self
|
|
}
|
|
pub fn in_function(mut self, function: u32, pc: Option<u32>) -> Self {
|
|
self.function = Some(function);
|
|
self.pc = pc;
|
|
self
|
|
}
|
|
pub fn resource(resource: LoadResource, requested: u64, limit: u64) -> Self {
|
|
Self {
|
|
resource: Some(resource),
|
|
requested: Some(requested),
|
|
limit: Some(limit),
|
|
..Self::new(LoadCode::ResourceLimit, LoadReason::Limit)
|
|
}
|
|
}
|
|
}
|
|
impl fmt::Display for LoadFailure {
|
|
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
|
write!(f, "{}: {:?}", self.code.tag(), self.reason)?;
|
|
if let Some(section) = self.section {
|
|
write!(f, " in section {section}")?;
|
|
}
|
|
if let Some(offset) = self.offset {
|
|
write!(f, " at byte {offset}")?;
|
|
}
|
|
if let Some(record) = self.record {
|
|
write!(f, " (record {record})")?;
|
|
}
|
|
if let Some(resource) = self.resource {
|
|
write!(f, " ({resource:?}: {:?} / {:?})", self.requested, self.limit)?;
|
|
}
|
|
Ok(())
|
|
}
|
|
}
|
|
impl std::error::Error for LoadFailure {}
|
|
|
|
/// Product maxima; callers may lower limits but cannot raise the accepted ceilings.
|
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
|
pub struct LoadLimits {
|
|
pub pbx_bytes: u64,
|
|
pub code_bytes: u64,
|
|
pub types: u64,
|
|
pub functions: u64,
|
|
pub implementations: u64,
|
|
pub nested_records: u64,
|
|
pub name_bytes: u64,
|
|
pub individual_name_bytes: u64,
|
|
pub registry_bytes: u64,
|
|
pub temporary_bytes: u64,
|
|
pub work: u64,
|
|
pub frame_slots: u64,
|
|
pub result_slots: u64,
|
|
pub constant_entries: u64,
|
|
pub constant_string_bytes: u64,
|
|
pub individual_string_bytes: u64,
|
|
}
|
|
impl Default for LoadLimits {
|
|
fn default() -> Self {
|
|
Self {
|
|
pbx_bytes: 64 * MIB,
|
|
code_bytes: 32 * MIB,
|
|
types: 65_536,
|
|
functions: 65_536,
|
|
implementations: 262_144,
|
|
nested_records: 1_048_576,
|
|
name_bytes: 4 * MIB,
|
|
individual_name_bytes: 4096,
|
|
registry_bytes: 64 * MIB,
|
|
temporary_bytes: 128 * MIB,
|
|
work: 268_435_456,
|
|
frame_slots: 16_384,
|
|
result_slots: 1024,
|
|
constant_entries: 1_048_576,
|
|
constant_string_bytes: 64 * MIB,
|
|
individual_string_bytes: 4 * MIB,
|
|
}
|
|
}
|
|
}
|
|
impl LoadLimits {
|
|
fn ceiling(self, r: LoadResource) -> u64 {
|
|
match r {
|
|
LoadResource::PbxBytes => self.pbx_bytes,
|
|
LoadResource::CodeBytes => self.code_bytes,
|
|
LoadResource::Types => self.types,
|
|
LoadResource::Functions => self.functions,
|
|
LoadResource::Implementations => self.implementations,
|
|
LoadResource::NestedRecords => self.nested_records,
|
|
LoadResource::NameBytes => self.name_bytes,
|
|
LoadResource::RegistryBytes => self.registry_bytes,
|
|
LoadResource::TemporaryBytes => self.temporary_bytes,
|
|
LoadResource::Work => self.work,
|
|
LoadResource::ConstantEntries => self.constant_entries,
|
|
LoadResource::ConstantStringBytes => self.constant_string_bytes,
|
|
}
|
|
}
|
|
}
|
|
/// One load attempt's counters. Successful retained allocations stay charged
|
|
/// for the remainder of this attempt; executable-image lifetime accounting is
|
|
/// a separate owner. Reuse a budget only when its earlier allocations still live.
|
|
#[derive(Debug)]
|
|
pub struct LoadBudget {
|
|
limits: LoadLimits,
|
|
used: [u64; RESOURCE_COUNT],
|
|
}
|
|
impl LoadBudget {
|
|
pub fn new(limits: LoadLimits) -> Self {
|
|
Self { limits, used: [0; RESOURCE_COUNT] }
|
|
}
|
|
pub fn limit(&self, r: LoadResource) -> u64 {
|
|
self.limits.ceiling(r).min(LoadLimits::default().ceiling(r))
|
|
}
|
|
pub fn individual_string_limit(&self) -> u64 {
|
|
self.limits.individual_string_bytes.min(4 * MIB)
|
|
}
|
|
pub fn individual_name_limit(&self) -> u64 {
|
|
self.limits.individual_name_bytes.min(4096)
|
|
}
|
|
pub fn frame_limit(&self) -> u64 {
|
|
self.limits.frame_slots.min(16_384)
|
|
}
|
|
pub fn result_limit(&self) -> u64 {
|
|
self.limits.result_slots.min(1024)
|
|
}
|
|
pub fn used(&self, r: LoadResource) -> u64 {
|
|
self.used[r as usize]
|
|
}
|
|
pub fn charge(&mut self, r: LoadResource, amount: u64) -> Result<(), LoadFailure> {
|
|
let next = self
|
|
.used(r)
|
|
.checked_add(amount)
|
|
.ok_or_else(|| LoadFailure::new(LoadCode::ResourceLimit, LoadReason::Overflow))?;
|
|
self.check(r, next)?;
|
|
self.used[r as usize] = next;
|
|
Ok(())
|
|
}
|
|
pub fn check(&self, r: LoadResource, amount: u64) -> Result<(), LoadFailure> {
|
|
if amount > self.limit(r) {
|
|
Err(LoadFailure::resource(r, amount, self.limit(r)))
|
|
} else {
|
|
Ok(())
|
|
}
|
|
}
|
|
pub fn refund(&mut self, r: LoadResource, amount: u64) {
|
|
self.used[r as usize] = self.used[r as usize]
|
|
.checked_sub(amount)
|
|
.expect("internal load budget accounting imbalance");
|
|
}
|
|
pub fn work(&mut self, amount: usize) -> Result<(), LoadFailure> {
|
|
self.charge(LoadResource::Work, amount as u64)
|
|
}
|
|
pub(crate) fn vector<T>(
|
|
&mut self,
|
|
count: usize,
|
|
r: LoadResource,
|
|
) -> Result<Vec<T>, LoadFailure> {
|
|
let bytes = count
|
|
.checked_mul(std::mem::size_of::<T>())
|
|
.ok_or_else(|| LoadFailure::new(LoadCode::ResourceLimit, LoadReason::Overflow))?
|
|
as u64;
|
|
self.charge(r, bytes)?;
|
|
let mut result = Vec::new();
|
|
if result.try_reserve_exact(count).is_err() {
|
|
self.refund(r, bytes);
|
|
return Err(LoadFailure::new(LoadCode::ResourceLimit, LoadReason::Allocation));
|
|
}
|
|
let actual = (result.capacity() as u64)
|
|
.checked_mul(std::mem::size_of::<T>() as u64)
|
|
.ok_or_else(|| LoadFailure::new(LoadCode::ResourceLimit, LoadReason::Overflow))?;
|
|
if let Err(err) = self.charge(r, actual - bytes) {
|
|
self.refund(r, bytes);
|
|
return Err(err);
|
|
}
|
|
Ok(result)
|
|
}
|
|
/// Roll back retained counters on failure; attempted work remains charged.
|
|
pub(crate) fn transaction<T>(
|
|
&mut self,
|
|
f: impl FnOnce(&mut Self) -> Result<T, LoadFailure>,
|
|
) -> Result<T, LoadFailure> {
|
|
let before = self.used;
|
|
let result = f(self);
|
|
if result.is_err() {
|
|
let work = self.used(LoadResource::Work);
|
|
self.used = before;
|
|
self.used[LoadResource::Work as usize] = work;
|
|
}
|
|
result
|
|
}
|
|
}
|