interplane.Get Omega
Read in your language

aienux

Aienux, the AienOS kernel: boot, scheduling, IPC and capability boundaries. Pre-alpha; host, emulator and physical evidence are labelled separately.

Brought by drakestapleton

branch main Branches Tags History

aienux / crates / aienos-kernel / src / abi.rs

1069 lines · 34381 bytes Raw Blame History
1// SPDX-License-Identifier: Apache-2.0
2// Copyright 2026 Drake Stapleton (AIEN / aien-dev)
3//
4// Licensed under the Apache License, Version 2.0 (the "License");
5// you may not use this file except in compliance with the License.
6// You may obtain a copy of the License at
7//
8// http://www.apache.org/licenses/LICENSE-2.0
9//
10// Unless required by applicable law or agreed to in writing, software
11// distributed under the License is distributed on an "AS IS" BASIS,
12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13// See the License for the specific language governing permissions and
14// limitations under the License.
15
16//! AIENOS ABI v1: the frozen wire contract for handles, rights, capabilities,
17//! memory regions and messages (ADR 0013).
18//!
19//! Every type here has an explicit little-endian byte encoding that does not
20//! depend on Rust's in-memory layout, the host architecture, or pointer width.
21//! Decoding fails closed: short or long input, reserved bits or fields that
22//! are not zero, unknown discriminants, unknown versions and generation-zero
23//! handles are all rejected with a distinct [`AbiError`].
24//!
25//! The in-memory structs are also `repr(C)` with explicit reserved fields so
26//! their layout matches the wire layout on little-endian targets; `const`
27//! assertions below pin sizes, alignments and field offsets. The byte
28//! encoding, not the struct layout, is the contract.
29//!
30//! No allocation, no `usize` or pointer fields, no implicit enum layout.
31
32use crate::caps;
33use core::mem::{align_of, offset_of, size_of};
34
35/// ABI version carried in every envelope. Decoders reject every other value.
36pub const ABI_VERSION: u16 = 1;
37
38/// Size in bytes of the envelope header that precedes a persisted or
39/// transported payload: tag u16, version u16, payload length u32.
40pub const ENVELOPE_HEADER_SIZE: usize = 8;
41
42/// Why an ABI value failed to encode or decode. Each failure has its own
43/// variant so callers and tests can tell them apart.
44#[derive(Clone, Copy, Debug, PartialEq, Eq)]
45pub enum AbiError {
46 /// Input is shorter than the encoding requires.
47 Truncated,
48 /// Input is longer than the encoding, or an envelope length field does
49 /// not match the payload size for its tag.
50 WrongLength,
51 /// Envelope version is not [`ABI_VERSION`].
52 UnknownVersion,
53 /// Envelope tag is not a known [`EnvelopeTag`].
54 UnknownTag,
55 /// Envelope tag is known but names a different type than requested.
56 TagMismatch,
57 /// A reserved field is not zero.
58 ReservedNonZero,
59 /// A reserved rights bit (6 through 31) is set.
60 ReservedBits,
61 /// An enum discriminant (for example a resource kind) is not defined.
62 UnknownDiscriminant,
63 /// A handle has generation 0, which is never issued.
64 InvalidHandle,
65 /// The output buffer is too small for the encoding.
66 BufferTooSmall,
67}
68
69/// A type with a fixed-size v1 wire encoding.
70pub trait Wire: Sized {
71 /// Envelope tag identifying this type when it is persisted or transported.
72 const TAG: EnvelopeTag;
73 /// Exact encoded size in bytes.
74 const SIZE: usize;
75
76 /// Write exactly [`Self::SIZE`] bytes to the front of `out`.
77 fn encode_into(&self, out: &mut [u8]) -> Result<usize, AbiError>;
78
79 /// Decode from a buffer of exactly [`Self::SIZE`] bytes.
80 fn decode(bytes: &[u8]) -> Result<Self, AbiError>;
81}
82
83// Little-endian field helpers. Callers pass fixed arrays whose size is checked
84// by the type, so the offsets are always in range.
85
86const fn get_u16(b: &[u8], at: usize) -> u16 {
87 u16::from_le_bytes([b[at], b[at + 1]])
88}
89
90const fn get_u32(b: &[u8], at: usize) -> u32 {
91 u32::from_le_bytes([b[at], b[at + 1], b[at + 2], b[at + 3]])
92}
93
94const fn get_u64(b: &[u8], at: usize) -> u64 {
95 u64::from_le_bytes([
96 b[at],
97 b[at + 1],
98 b[at + 2],
99 b[at + 3],
100 b[at + 4],
101 b[at + 5],
102 b[at + 6],
103 b[at + 7],
104 ])
105}
106
107fn put(out: &mut [u8], at: usize, bytes: &[u8]) {
108 out[at..at + bytes.len()].copy_from_slice(bytes);
109}
110
111/// Check that `bytes` is exactly `size` long.
112const fn exact(bytes: &[u8], size: usize) -> Result<(), AbiError> {
113 if bytes.len() < size {
114 Err(AbiError::Truncated)
115 } else if bytes.len() > size {
116 Err(AbiError::WrongLength)
117 } else {
118 Ok(())
119 }
120}
121
122macro_rules! wire_impl {
123 ($ty:ty, $tag:expr, $size:expr) => {
124 impl Wire for $ty {
125 const TAG: EnvelopeTag = $tag;
126 const SIZE: usize = $size;
127
128 fn encode_into(&self, out: &mut [u8]) -> Result<usize, AbiError> {
129 let dst = out.get_mut(..$size).ok_or(AbiError::BufferTooSmall)?;
130 dst.copy_from_slice(&self.to_bytes());
131 Ok($size)
132 }
133
134 fn decode(bytes: &[u8]) -> Result<Self, AbiError> {
135 exact(bytes, $size)?;
136 let mut array = [0u8; $size];
137 array.copy_from_slice(bytes);
138 Self::from_bytes(&array)
139 }
140 }
141 };
142}
143
144// ---------------------------------------------------------------------------
145// Handle
146
147/// A 64-bit generational capability handle: slot index plus the slot's
148/// generation at issue time. Generation 0 is never issued, so it is invalid.
149///
150/// Wire: index u32 LE, then generation u32 LE (8 bytes). Register form:
151/// `(generation << 32) | index`, the packing the syscall path already uses.
152#[repr(C)]
153#[derive(Clone, Copy, Debug, PartialEq, Eq)]
154pub struct Handle {
155 pub index: u32,
156 pub generation: u32,
157}
158
159impl Handle {
160 pub const SIZE: usize = 8;
161
162 /// Build a handle. Fails with [`AbiError::InvalidHandle`] on generation 0.
163 pub const fn new(index: u32, generation: u32) -> Result<Self, AbiError> {
164 if generation == 0 {
165 Err(AbiError::InvalidHandle)
166 } else {
167 Ok(Self { index, generation })
168 }
169 }
170
171 pub const fn index(self) -> u32 {
172 self.index
173 }
174
175 pub const fn generation(self) -> u32 {
176 self.generation
177 }
178
179 /// Register form: `(generation << 32) | index`.
180 pub const fn to_raw(self) -> u64 {
181 ((self.generation as u64) << 32) | self.index as u64
182 }
183
184 /// Parse the register form. Fails closed on generation 0.
185 pub const fn from_raw(raw: u64) -> Result<Self, AbiError> {
186 Self::new(raw as u32, (raw >> 32) as u32)
187 }
188
189 pub fn to_bytes(&self) -> [u8; 8] {
190 let mut out = [0u8; 8];
191 put(&mut out, 0, &self.index.to_le_bytes());
192 put(&mut out, 4, &self.generation.to_le_bytes());
193 out
194 }
195
196 pub const fn from_bytes(bytes: &[u8; 8]) -> Result<Self, AbiError> {
197 Self::new(get_u32(bytes, 0), get_u32(bytes, 4))
198 }
199}
200
201wire_impl!(Handle, EnvelopeTag::Handle, 8);
202
203// caps::Handle is a direct re-export of crate::abi::Handle
204
205// ---------------------------------------------------------------------------
206// Plain identifiers
207
208macro_rules! id_type {
209 ($(#[$doc:meta])* $name:ident, $int:ty, $size:expr, $tag:expr, $get:ident) => {
210 $(#[$doc])*
211 #[repr(transparent)]
212 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
213 pub struct $name(pub $int);
214
215 impl $name {
216 pub const SIZE: usize = $size;
217
218 pub const fn to_bytes(&self) -> [u8; $size] {
219 self.0.to_le_bytes()
220 }
221
222 pub const fn from_bytes(bytes: &[u8; $size]) -> Result<Self, AbiError> {
223 Ok(Self($get(bytes, 0)))
224 }
225 }
226
227 wire_impl!($name, $tag, $size);
228 };
229}
230
231id_type!(
232 /// Identity of a task. Wire: u32 LE. Every value is well formed.
233 TaskId, u32, 4, EnvelopeTag::TaskId, get_u32
234);
235id_type!(
236 /// Identity of a kernel object. Wire: u64 LE. Every value is well formed.
237 ObjectId, u64, 8, EnvelopeTag::ObjectId, get_u64
238);
239id_type!(
240 /// Identity of a kernel message channel. Wire: u32 LE.
241 ChannelId, u32, 4, EnvelopeTag::ChannelId, get_u32
242);
243id_type!(
244 /// Identity of a device. Wire: u32 LE.
245 DeviceId, u32, 4, EnvelopeTag::DeviceId, get_u32
246);
247
248// ---------------------------------------------------------------------------
249// ResourceId
250
251/// What kind of resource a capability names. Discriminants are frozen and
252/// never reused; 0 is invalid.
253#[repr(u16)]
254#[derive(Clone, Copy, Debug, PartialEq, Eq)]
255pub enum ResourceKind {
256 Console = 1,
257 Channel = 2,
258 Object = 3,
259 Device = 4,
260 MemoryRegion = 5,
261}
262
263impl ResourceKind {
264 pub const fn from_u16(value: u16) -> Result<Self, AbiError> {
265 match value {
266 1 => Ok(Self::Console),
267 2 => Ok(Self::Channel),
268 3 => Ok(Self::Object),
269 4 => Ok(Self::Device),
270 5 => Ok(Self::MemoryRegion),
271 _ => Err(AbiError::UnknownDiscriminant),
272 }
273 }
274
275 pub const fn to_u16(self) -> u16 {
276 self as u16
277 }
278}
279
280/// A typed resource reference. Wire: kind u16 LE, reserved u16 (zero),
281/// id u32 LE (8 bytes). `id` is the kernel's resource number for that kind.
282#[repr(C)]
283#[derive(Clone, Copy, Debug, PartialEq, Eq)]
284pub struct ResourceId {
285 kind: ResourceKind,
286 reserved: u16,
287 id: u32,
288}
289
290impl ResourceId {
291 pub const SIZE: usize = 8;
292
293 pub const fn new(kind: ResourceKind, id: u32) -> Self {
294 Self {
295 kind,
296 reserved: 0,
297 id,
298 }
299 }
300
301 pub const fn kind(self) -> ResourceKind {
302 self.kind
303 }
304
305 pub const fn id(self) -> u32 {
306 self.id
307 }
308
309 pub fn to_bytes(&self) -> [u8; 8] {
310 let mut out = [0u8; 8];
311 put(&mut out, 0, &self.kind.to_u16().to_le_bytes());
312 // Bytes 2..4 reserved, written as zero.
313 put(&mut out, 4, &self.id.to_le_bytes());
314 out
315 }
316
317 pub const fn from_bytes(bytes: &[u8; 8]) -> Result<Self, AbiError> {
318 let kind = match ResourceKind::from_u16(get_u16(bytes, 0)) {
319 Ok(kind) => kind,
320 Err(e) => return Err(e),
321 };
322 if get_u16(bytes, 2) != 0 {
323 return Err(AbiError::ReservedNonZero);
324 }
325 Ok(Self::new(kind, get_u32(bytes, 4)))
326 }
327}
328
329wire_impl!(ResourceId, EnvelopeTag::ResourceId, 8);
330
331// ---------------------------------------------------------------------------
332// Rights
333
334/// Capability rights. Wire: u32 LE. Bits 0 to 5 are defined; bits 6 to 31
335/// are reserved and must be zero.
336#[repr(transparent)]
337#[derive(Clone, Copy, Debug, PartialEq, Eq)]
338pub struct Rights(u32);
339
340impl Rights {
341 pub const SIZE: usize = 4;
342 pub const NONE: Self = Self(0);
343 pub const READ: Self = Self(1 << 0);
344 pub const WRITE: Self = Self(1 << 1);
345 pub const MAP: Self = Self(1 << 2);
346 pub const GRANT: Self = Self(1 << 3);
347 pub const DERIVE: Self = Self(1 << 4);
348 pub const REVOKE: Self = Self(1 << 5);
349 /// Mask of every bit defined in v1.
350 pub const DEFINED_MASK: u32 = (1 << 6) - 1;
351
352 /// Fails with [`AbiError::ReservedBits`] if any bit 6 to 31 is set.
353 pub const fn from_bits(bits: u32) -> Result<Self, AbiError> {
354 if bits & !Self::DEFINED_MASK == 0 {
355 Ok(Self(bits))
356 } else {
357 Err(AbiError::ReservedBits)
358 }
359 }
360
361 pub const fn bits(self) -> u32 {
362 self.0
363 }
364
365 pub const fn union(self, other: Self) -> Self {
366 Self(self.0 | other.0)
367 }
368
369 pub const fn to_bytes(&self) -> [u8; 4] {
370 self.0.to_le_bytes()
371 }
372
373 pub const fn from_bytes(bytes: &[u8; 4]) -> Result<Self, AbiError> {
374 Self::from_bits(get_u32(bytes, 0))
375 }
376}
377
378wire_impl!(Rights, EnvelopeTag::Rights, 4);
379
380impl From<caps::Rights> for Rights {
381 fn from(rights: caps::Rights) -> Self {
382 Self(rights.bits() as u32)
383 }
384}
385
386impl TryFrom<Rights> for caps::Rights {
387 type Error = AbiError;
388 fn try_from(rights: Rights) -> Result<Self, AbiError> {
389 let bits = u8::try_from(rights.0).map_err(|_| AbiError::ReservedBits)?;
390 caps::Rights::from_bits(bits).ok_or(AbiError::ReservedBits)
391 }
392}
393
394// ---------------------------------------------------------------------------
395// Capability
396
397/// A capability as data: which resource and which rights. Wire: resource
398/// (8 bytes), rights u32 LE, reserved u32 (zero); 16 bytes.
399#[repr(C)]
400#[derive(Clone, Copy, Debug, PartialEq, Eq)]
401pub struct Capability {
402 resource: ResourceId,
403 rights: Rights,
404 reserved: u32,
405}
406
407impl Capability {
408 pub const SIZE: usize = 16;
409
410 pub const fn new(resource: ResourceId, rights: Rights) -> Self {
411 Self {
412 resource,
413 rights,
414 reserved: 0,
415 }
416 }
417
418 pub const fn resource(self) -> ResourceId {
419 self.resource
420 }
421
422 pub const fn rights(self) -> Rights {
423 self.rights
424 }
425
426 pub fn to_bytes(&self) -> [u8; 16] {
427 let mut out = [0u8; 16];
428 put(&mut out, 0, &self.resource.to_bytes());
429 put(&mut out, 8, &self.rights.to_bytes());
430 // Bytes 12..16 reserved, written as zero.
431 out
432 }
433
434 pub const fn from_bytes(bytes: &[u8; 16]) -> Result<Self, AbiError> {
435 let resource = match ResourceId::from_bytes(&[
436 bytes[0], bytes[1], bytes[2], bytes[3], bytes[4], bytes[5], bytes[6], bytes[7],
437 ]) {
438 Ok(resource) => resource,
439 Err(e) => return Err(e),
440 };
441 let rights = match Rights::from_bits(get_u32(bytes, 8)) {
442 Ok(rights) => rights,
443 Err(e) => return Err(e),
444 };
445 if get_u32(bytes, 12) != 0 {
446 return Err(AbiError::ReservedNonZero);
447 }
448 Ok(Self::new(resource, rights))
449 }
450}
451
452wire_impl!(Capability, EnvelopeTag::Capability, 16);
453
454// ---------------------------------------------------------------------------
455// MemoryRegion
456
457/// A bounded memory extent in pages. Wire: base u64 LE, pages u32 LE,
458/// reserved u32 (zero); 16 bytes.
459#[repr(C)]
460#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
461pub struct MemoryRegion {
462 pub base: u64,
463 pub pages: u32,
464 pub reserved: u32,
465}
466
467impl MemoryRegion {
468 pub const SIZE: usize = 16;
469 pub const EMPTY: Self = Self {
470 base: 0,
471 pages: 0,
472 reserved: 0,
473 };
474
475 pub const fn new(base: u64, pages: u32) -> Self {
476 Self {
477 base,
478 pages,
479 reserved: 0,
480 }
481 }
482
483 pub const fn base(self) -> u64 {
484 self.base
485 }
486
487 pub const fn pages(self) -> u32 {
488 self.pages
489 }
490
491 pub fn to_bytes(&self) -> [u8; 16] {
492 let mut out = [0u8; 16];
493 put(&mut out, 0, &self.base.to_le_bytes());
494 put(&mut out, 8, &self.pages.to_le_bytes());
495 // Bytes 12..16 reserved, written as zero.
496 out
497 }
498
499 pub const fn from_bytes(bytes: &[u8; 16]) -> Result<Self, AbiError> {
500 if get_u32(bytes, 12) != 0 {
501 return Err(AbiError::ReservedNonZero);
502 }
503 Ok(Self::new(get_u64(bytes, 0), get_u32(bytes, 8)))
504 }
505}
506
507wire_impl!(MemoryRegion, EnvelopeTag::MemoryRegion, 16);
508
509// ---------------------------------------------------------------------------
510// Message
511
512/// Fixed-size typed IPC message. Wire (56 bytes): kind u32 LE at 0,
513/// reserved u32 (zero) at 4, payload 3 x u64 LE at 8, region at 32,
514/// object u64 LE at 48. Field order matches the typed IPC message.
515#[repr(C)]
516#[derive(Clone, Copy, Debug, PartialEq, Eq)]
517pub struct Message {
518 pub kind: u32,
519 pub reserved: u32,
520 pub payload: [u64; 3],
521 pub region: MemoryRegion,
522 pub object: ObjectId,
523}
524
525impl Message {
526 pub const SIZE: usize = 56;
527 pub const NEW: Self = Self {
528 kind: 0,
529 reserved: 0,
530 payload: [0; 3],
531 region: MemoryRegion::EMPTY,
532 object: ObjectId(0),
533 };
534
535 pub const fn new(kind: u32, payload: [u64; 3], region: MemoryRegion, object: ObjectId) -> Self {
536 Self {
537 kind,
538 reserved: 0,
539 payload,
540 region,
541 object,
542 }
543 }
544
545 pub const fn kind(self) -> u32 {
546 self.kind
547 }
548
549 pub const fn payload(self) -> [u64; 3] {
550 self.payload
551 }
552
553 pub const fn region(self) -> MemoryRegion {
554 self.region
555 }
556
557 pub const fn object(self) -> ObjectId {
558 self.object
559 }
560
561 pub fn to_bytes(&self) -> [u8; 56] {
562 let mut out = [0u8; 56];
563 put(&mut out, 0, &self.kind.to_le_bytes());
564 // Bytes 4..8 reserved, written as zero.
565 put(&mut out, 8, &self.payload[0].to_le_bytes());
566 put(&mut out, 16, &self.payload[1].to_le_bytes());
567 put(&mut out, 24, &self.payload[2].to_le_bytes());
568 put(&mut out, 32, &self.region.to_bytes());
569 put(&mut out, 48, &self.object.to_bytes());
570 out
571 }
572
573 pub fn from_bytes(bytes: &[u8; 56]) -> Result<Self, AbiError> {
574 if get_u32(bytes, 4) != 0 {
575 return Err(AbiError::ReservedNonZero);
576 }
577 let region = MemoryRegion::decode(&bytes[32..48])?;
578 Ok(Self::new(
579 get_u32(bytes, 0),
580 [get_u64(bytes, 8), get_u64(bytes, 16), get_u64(bytes, 24)],
581 region,
582 ObjectId(get_u64(bytes, 48)),
583 ))
584 }
585}
586
587wire_impl!(Message, EnvelopeTag::Message, 56);
588
589// ---------------------------------------------------------------------------
590// Envelope
591
592/// Type tag in an envelope header. Discriminants are frozen and never reused;
593/// 0 is invalid.
594#[repr(u16)]
595#[derive(Clone, Copy, Debug, PartialEq, Eq)]
596pub enum EnvelopeTag {
597 Handle = 1,
598 TaskId = 2,
599 ObjectId = 3,
600 ChannelId = 4,
601 DeviceId = 5,
602 ResourceId = 6,
603 Rights = 7,
604 Capability = 8,
605 MemoryRegion = 9,
606 Message = 10,
607}
608
609impl EnvelopeTag {
610 pub const fn from_u16(value: u16) -> Result<Self, AbiError> {
611 match value {
612 1 => Ok(Self::Handle),
613 2 => Ok(Self::TaskId),
614 3 => Ok(Self::ObjectId),
615 4 => Ok(Self::ChannelId),
616 5 => Ok(Self::DeviceId),
617 6 => Ok(Self::ResourceId),
618 7 => Ok(Self::Rights),
619 8 => Ok(Self::Capability),
620 9 => Ok(Self::MemoryRegion),
621 10 => Ok(Self::Message),
622 _ => Err(AbiError::UnknownTag),
623 }
624 }
625
626 pub const fn to_u16(self) -> u16 {
627 self as u16
628 }
629}
630
631/// Write `value` as header (tag, [`ABI_VERSION`], payload length) followed by
632/// its payload. Returns the number of bytes written.
633pub fn encode_enveloped<T: Wire>(value: &T, out: &mut [u8]) -> Result<usize, AbiError> {
634 let total = ENVELOPE_HEADER_SIZE + T::SIZE;
635 let dst = out.get_mut(..total).ok_or(AbiError::BufferTooSmall)?;
636 put(dst, 0, &T::TAG.to_u16().to_le_bytes());
637 put(dst, 2, &ABI_VERSION.to_le_bytes());
638 put(dst, 4, &(T::SIZE as u32).to_le_bytes());
639 value.encode_into(&mut dst[ENVELOPE_HEADER_SIZE..])?;
640 Ok(total)
641}
642
643/// Decode an enveloped `T`. Checks, in order: header present, version,
644/// tag known, tag matches `T`, length field equals `T::SIZE`, buffer holds
645/// exactly header plus payload, payload decodes.
646pub fn decode_enveloped<T: Wire>(bytes: &[u8]) -> Result<T, AbiError> {
647 if bytes.len() < ENVELOPE_HEADER_SIZE {
648 return Err(AbiError::Truncated);
649 }
650 if get_u16(bytes, 2) != ABI_VERSION {
651 return Err(AbiError::UnknownVersion);
652 }
653 if EnvelopeTag::from_u16(get_u16(bytes, 0))? != T::TAG {
654 return Err(AbiError::TagMismatch);
655 }
656 if get_u32(bytes, 4) as usize != T::SIZE {
657 return Err(AbiError::WrongLength);
658 }
659 T::decode(&bytes[ENVELOPE_HEADER_SIZE..])
660}
661
662// ---------------------------------------------------------------------------
663// Layout assertions. The wire encoding is the contract; these pin the
664// in-memory mirror so it cannot drift silently.
665
666const _: () = {
667 assert!(size_of::<Handle>() == Handle::SIZE);
668 assert!(align_of::<Handle>() == 4);
669 assert!(offset_of!(Handle, index) == 0);
670 assert!(offset_of!(Handle, generation) == 4);
671
672 assert!(size_of::<TaskId>() == TaskId::SIZE);
673 assert!(size_of::<ObjectId>() == ObjectId::SIZE);
674 assert!(size_of::<ChannelId>() == ChannelId::SIZE);
675 assert!(size_of::<DeviceId>() == DeviceId::SIZE);
676
677 assert!(size_of::<ResourceKind>() == 2);
678 assert!(size_of::<ResourceId>() == ResourceId::SIZE);
679 assert!(align_of::<ResourceId>() == 4);
680 assert!(offset_of!(ResourceId, kind) == 0);
681 assert!(offset_of!(ResourceId, reserved) == 2);
682 assert!(offset_of!(ResourceId, id) == 4);
683
684 assert!(size_of::<Rights>() == Rights::SIZE);
685
686 assert!(size_of::<Capability>() == Capability::SIZE);
687 assert!(align_of::<Capability>() == 4);
688 assert!(offset_of!(Capability, resource) == 0);
689 assert!(offset_of!(Capability, rights) == 8);
690 assert!(offset_of!(Capability, reserved) == 12);
691
692 assert!(size_of::<MemoryRegion>() == MemoryRegion::SIZE);
693 assert!(align_of::<MemoryRegion>() == 8);
694 assert!(offset_of!(MemoryRegion, base) == 0);
695 assert!(offset_of!(MemoryRegion, pages) == 8);
696 assert!(offset_of!(MemoryRegion, reserved) == 12);
697
698 assert!(size_of::<Message>() == Message::SIZE);
699 assert!(align_of::<Message>() == 8);
700 assert!(offset_of!(Message, kind) == 0);
701 assert!(offset_of!(Message, reserved) == 4);
702 assert!(offset_of!(Message, payload) == 8);
703 assert!(offset_of!(Message, region) == 32);
704 assert!(offset_of!(Message, object) == 48);
705
706 assert!(size_of::<EnvelopeTag>() == 2);
707};
708
709#[cfg(test)]
710mod tests {
711 use super::*;
712
713 /// Golden round trip: encode gives exactly `golden`, decoding `golden`
714 /// gives `value`, and re-encoding gives `golden` again. Also covers the
715 /// envelope form and every truncation and one-byte extension.
716 fn golden<T: Wire + Copy + PartialEq + core::fmt::Debug>(value: T, golden: &[u8]) {
717 assert_eq!(golden.len(), T::SIZE);
718 let mut buf = [0xAAu8; 64];
719 assert_eq!(value.encode_into(&mut buf), Ok(T::SIZE));
720 assert_eq!(&buf[..T::SIZE], golden);
721 let decoded = T::decode(golden).expect("golden bytes decode");
722 assert_eq!(decoded, value);
723 let mut again = [0x55u8; 64];
724 decoded.encode_into(&mut again).unwrap();
725 assert_eq!(&again[..T::SIZE], golden);
726
727 for len in 0..T::SIZE {
728 assert_eq!(T::decode(&golden[..len]), Err(AbiError::Truncated));
729 }
730 let mut long = [0u8; 65];
731 long[..T::SIZE].copy_from_slice(golden);
732 assert_eq!(T::decode(&long[..T::SIZE + 1]), Err(AbiError::WrongLength));
733 let mut small = [0u8; 64];
734 assert_eq!(
735 value.encode_into(&mut small[..T::SIZE - 1]),
736 Err(AbiError::BufferTooSmall)
737 );
738
739 // Envelope: header golden bytes, then payload golden bytes.
740 let mut env = [0u8; 72];
741 let n = encode_enveloped(&value, &mut env).unwrap();
742 assert_eq!(n, ENVELOPE_HEADER_SIZE + T::SIZE);
743 assert_eq!(&env[0..2], &T::TAG.to_u16().to_le_bytes());
744 assert_eq!(&env[2..4], &[1, 0]);
745 assert_eq!(&env[4..8], &(T::SIZE as u32).to_le_bytes());
746 assert_eq!(&env[8..n], golden);
747 assert_eq!(decode_enveloped::<T>(&env[..n]), Ok(value));
748 for len in 0..n {
749 assert_eq!(
750 decode_enveloped::<T>(&env[..len]),
751 Err(AbiError::Truncated),
752 "envelope truncated to {len}"
753 );
754 }
755 assert_eq!(
756 decode_enveloped::<T>(&env[..n + 1]),
757 Err(AbiError::WrongLength)
758 );
759 assert_eq!(
760 encode_enveloped(&value, &mut env[..n - 1]),
761 Err(AbiError::BufferTooSmall)
762 );
763 }
764
765 #[test]
766 fn handle_golden() {
767 let h = Handle::new(7, 0x0102_0304).unwrap();
768 golden(h, &[0x07, 0, 0, 0, 0x04, 0x03, 0x02, 0x01]);
769 assert_eq!(h.to_raw(), 0x0102_0304_0000_0007);
770 assert_eq!(Handle::from_raw(0x0102_0304_0000_0007), Ok(h));
771 }
772
773 #[test]
774 fn handle_raw_matches_syscall_packing() {
775 // user.rs packs (generation << 32) | index into x0.
776 let h = Handle::new(u32::MAX, u32::MAX).unwrap();
777 assert_eq!(h.to_raw(), u64::MAX);
778 let h = Handle::new(0, 1).unwrap();
779 assert_eq!(h.to_raw(), 1 << 32);
780 assert_eq!(Handle::from_raw(1 << 32), Ok(h));
781 }
782
783 #[test]
784 fn handle_generation_zero_fails_closed() {
785 assert_eq!(Handle::new(3, 0), Err(AbiError::InvalidHandle));
786 assert_eq!(Handle::from_raw(0), Err(AbiError::InvalidHandle));
787 assert_eq!(
788 Handle::from_raw(0x0000_0000_FFFF_FFFF),
789 Err(AbiError::InvalidHandle)
790 );
791 assert_eq!(
792 Handle::decode(&[1, 0, 0, 0, 0, 0, 0, 0]),
793 Err(AbiError::InvalidHandle)
794 );
795 let env = [1, 0, 1, 0, 8, 0, 0, 0, 5, 0, 0, 0, 0, 0, 0, 0];
796 assert_eq!(
797 decode_enveloped::<Handle>(&env),
798 Err(AbiError::InvalidHandle)
799 );
800 let forged = Handle {
801 index: 0,
802 generation: 0,
803 };
804 assert_eq!(
805 Handle::from_raw(forged.to_raw()),
806 Err(AbiError::InvalidHandle)
807 );
808 }
809
810 #[test]
811 fn handle_raw_register_encoding() {
812 let mut table = caps::CapTable::<4>::new(1);
813 let issued = table.insert(9, caps::Rights::READ).unwrap();
814 let raw = issued.to_raw();
815 assert_eq!(Handle::from_raw(raw), Ok(issued));
816 assert_eq!(Handle::from_raw(0), Err(AbiError::InvalidHandle));
817 }
818
819 #[test]
820 fn id_goldens() {
821 golden(TaskId(0x1122_3344), &[0x44, 0x33, 0x22, 0x11]);
822 golden(
823 ObjectId(0x0102_0304_0506_0708),
824 &[0x08, 0x07, 0x06, 0x05, 0x04, 0x03, 0x02, 0x01],
825 );
826 golden(ChannelId(0xA1B2_C3D4), &[0xD4, 0xC3, 0xB2, 0xA1]);
827 golden(DeviceId(0x42), &[0x42, 0, 0, 0]);
828 }
829
830 #[test]
831 fn resource_id_golden() {
832 golden(
833 ResourceId::new(ResourceKind::Channel, 0xBEEF),
834 &[0x02, 0x00, 0x00, 0x00, 0xEF, 0xBE, 0x00, 0x00],
835 );
836 let kinds = [
837 (ResourceKind::Console, 1u16),
838 (ResourceKind::Channel, 2),
839 (ResourceKind::Object, 3),
840 (ResourceKind::Device, 4),
841 (ResourceKind::MemoryRegion, 5),
842 ];
843 for (kind, value) in kinds {
844 assert_eq!(kind.to_u16(), value);
845 assert_eq!(ResourceKind::from_u16(value), Ok(kind));
846 }
847 }
848
849 #[test]
850 fn resource_id_rejects_unknown_kind_and_reserved() {
851 for kind in [0u16, 6, 0x00FF, 0xFFFF] {
852 let [a, b] = kind.to_le_bytes();
853 assert_eq!(
854 ResourceId::decode(&[a, b, 0, 0, 1, 0, 0, 0]),
855 Err(AbiError::UnknownDiscriminant)
856 );
857 }
858 assert_eq!(
859 ResourceId::decode(&[1, 0, 1, 0, 1, 0, 0, 0]),
860 Err(AbiError::ReservedNonZero)
861 );
862 assert_eq!(
863 ResourceId::decode(&[1, 0, 0, 0x80, 1, 0, 0, 0]),
864 Err(AbiError::ReservedNonZero)
865 );
866 }
867
868 #[test]
869 fn rights_golden() {
870 let rights = Rights::READ.union(Rights::WRITE).union(Rights::GRANT);
871 golden(rights, &[0x0B, 0, 0, 0]);
872 golden(Rights::NONE, &[0, 0, 0, 0]);
873 golden(Rights::from_bits(0x3F).unwrap(), &[0x3F, 0, 0, 0]);
874 assert_eq!(Rights::READ.bits(), caps::Rights::READ.bits() as u32);
875 assert_eq!(Rights::WRITE.bits(), caps::Rights::WRITE.bits() as u32);
876 assert_eq!(Rights::MAP.bits(), caps::Rights::MAP.bits() as u32);
877 assert_eq!(Rights::GRANT.bits(), caps::Rights::GRANT.bits() as u32);
878 assert_eq!(Rights::DERIVE.bits(), caps::Rights::DERIVE.bits() as u32);
879 assert_eq!(Rights::REVOKE.bits(), caps::Rights::REVOKE.bits() as u32);
880 }
881
882 #[test]
883 fn rights_reserved_bits_fail_closed() {
884 for bit in 6..32 {
885 let bits = 1u32 << bit;
886 assert_eq!(Rights::from_bits(bits), Err(AbiError::ReservedBits));
887 assert_eq!(
888 Rights::decode(&bits.to_le_bytes()),
889 Err(AbiError::ReservedBits)
890 );
891 }
892 }
893
894 #[test]
895 fn rights_convert_with_caps_rights() {
896 let kernel = caps::Rights::READ | caps::Rights::DERIVE;
897 let wire = Rights::from(kernel);
898 assert_eq!(wire.bits(), 0x11);
899 assert_eq!(caps::Rights::try_from(wire), Ok(kernel));
900 }
901
902 #[test]
903 fn capability_golden() {
904 let cap = Capability::new(
905 ResourceId::new(ResourceKind::Device, 0x1234_5678),
906 Rights::READ.union(Rights::MAP).union(Rights::REVOKE),
907 );
908 golden(
909 cap,
910 &[
911 0x04, 0x00, 0x00, 0x00, 0x78, 0x56, 0x34, 0x12, // resource
912 0x25, 0x00, 0x00, 0x00, // rights
913 0x00, 0x00, 0x00, 0x00, // reserved
914 ],
915 );
916 }
917
918 #[test]
919 fn capability_fails_closed() {
920 let good = [4u8, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0];
921 assert!(Capability::decode(&good).is_ok());
922 let mut bad = good;
923 bad[15] = 1;
924 assert_eq!(Capability::decode(&bad), Err(AbiError::ReservedNonZero));
925 let mut bad = good;
926 bad[8] = 0x40;
927 assert_eq!(Capability::decode(&bad), Err(AbiError::ReservedBits));
928 let mut bad = good;
929 bad[11] = 0x80;
930 assert_eq!(Capability::decode(&bad), Err(AbiError::ReservedBits));
931 let mut bad = good;
932 bad[0] = 0;
933 assert_eq!(Capability::decode(&bad), Err(AbiError::UnknownDiscriminant));
934 let mut bad = good;
935 bad[3] = 1;
936 assert_eq!(Capability::decode(&bad), Err(AbiError::ReservedNonZero));
937 }
938
939 #[test]
940 fn memory_region_golden() {
941 golden(
942 MemoryRegion::new(0x4000_0000, 16),
943 &[
944 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, 0x00, // base
945 0x10, 0x00, 0x00, 0x00, // pages
946 0x00, 0x00, 0x00, 0x00, // reserved
947 ],
948 );
949 let mut bad = MemoryRegion::new(1, 1).to_bytes();
950 bad[12] = 1;
951 assert_eq!(MemoryRegion::decode(&bad), Err(AbiError::ReservedNonZero));
952 }
953
954 fn sample_message() -> Message {
955 Message::new(
956 3,
957 [1, 0x2222, u64::MAX],
958 MemoryRegion::new(0x8000_1000, 2),
959 ObjectId(0x0A0B_0C0D_0E0F_1011),
960 )
961 }
962
963 const MESSAGE_GOLDEN: [u8; 56] = [
964 0x03, 0x00, 0x00, 0x00, // kind
965 0x00, 0x00, 0x00, 0x00, // reserved
966 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // payload[0]
967 0x22, 0x22, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // payload[1]
968 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, // payload[2]
969 0x00, 0x10, 0x00, 0x80, 0x00, 0x00, 0x00, 0x00, // region.base
970 0x02, 0x00, 0x00, 0x00, // region.pages
971 0x00, 0x00, 0x00, 0x00, // region reserved
972 0x11, 0x10, 0x0F, 0x0E, 0x0D, 0x0C, 0x0B, 0x0A, // object
973 ];
974
975 #[test]
976 fn message_golden() {
977 golden(sample_message(), &MESSAGE_GOLDEN);
978 }
979
980 #[test]
981 fn message_reserved_fields_fail_closed() {
982 for at in [4usize, 7, 44, 47] {
983 let mut bad = MESSAGE_GOLDEN;
984 bad[at] = 1;
985 assert_eq!(
986 Message::decode(&bad),
987 Err(AbiError::ReservedNonZero),
988 "byte {at}"
989 );
990 }
991 }
992
993 #[test]
994 fn envelope_golden() {
995 let cap = Capability::new(ResourceId::new(ResourceKind::Console, 1), Rights::WRITE);
996 let mut out = [0u8; 24];
997 assert_eq!(encode_enveloped(&cap, &mut out), Ok(24));
998 let expected = [
999 0x08, 0x00, // tag: Capability
1000 0x01, 0x00, // version 1
1001 0x10, 0x00, 0x00, 0x00, // payload length 16
1002 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, // resource
1003 0x02, 0x00, 0x00, 0x00, // rights
1004 0x00, 0x00, 0x00, 0x00, // reserved
1005 ];
1006 assert_eq!(out, expected);
1007 assert_eq!(decode_enveloped::<Capability>(&expected), Ok(cap));
1008 }
1009
1010 #[test]
1011 fn envelope_fails_closed() {
1012 let mut good = [0u8; 16];
1013 encode_enveloped(&Handle::new(2, 5).unwrap(), &mut good).unwrap();
1014 assert!(decode_enveloped::<Handle>(&good).is_ok());
1015
1016 for version in [0u16, 2, 0x0100, 0xFFFF] {
1017 let mut bad = good;
1018 bad[2..4].copy_from_slice(&version.to_le_bytes());
1019 assert_eq!(
1020 decode_enveloped::<Handle>(&bad),
1021 Err(AbiError::UnknownVersion)
1022 );
1023 }
1024 for tag in [0u16, 11, 0xFFFF] {
1025 let mut bad = good;
1026 bad[0..2].copy_from_slice(&tag.to_le_bytes());
1027 assert_eq!(decode_enveloped::<Handle>(&bad), Err(AbiError::UnknownTag));
1028 }
1029 // A known tag for an 8-byte type that is not Handle.
1030 let mut bad = good;
1031 bad[0] = EnvelopeTag::ObjectId.to_u16() as u8;
1032 assert_eq!(decode_enveloped::<Handle>(&bad), Err(AbiError::TagMismatch));
1033 for len in [0u32, 7, 9, 16, u32::MAX] {
1034 let mut bad = good;
1035 bad[4..8].copy_from_slice(&len.to_le_bytes());
1036 assert_eq!(decode_enveloped::<Handle>(&bad), Err(AbiError::WrongLength));
1037 }
1038 let mut bad = good;
1039 bad[12] = 0;
1040 bad[13] = 0;
1041 bad[14] = 0;
1042 bad[15] = 0;
1043 assert_eq!(
1044 decode_enveloped::<Handle>(&bad),
1045 Err(AbiError::InvalidHandle)
1046 );
1047 }
1048
1049 #[test]
1050 fn tags_are_distinct_and_round_trip() {
1051 let tags = [
1052 (EnvelopeTag::Handle, <Handle as Wire>::TAG),
1053 (EnvelopeTag::TaskId, <TaskId as Wire>::TAG),
1054 (EnvelopeTag::ObjectId, <ObjectId as Wire>::TAG),
1055 (EnvelopeTag::ChannelId, <ChannelId as Wire>::TAG),
1056 (EnvelopeTag::DeviceId, <DeviceId as Wire>::TAG),
1057 (EnvelopeTag::ResourceId, <ResourceId as Wire>::TAG),
1058 (EnvelopeTag::Rights, <Rights as Wire>::TAG),
1059 (EnvelopeTag::Capability, <Capability as Wire>::TAG),
1060 (EnvelopeTag::MemoryRegion, <MemoryRegion as Wire>::TAG),
1061 (EnvelopeTag::Message, <Message as Wire>::TAG),
1062 ];
1063 for (i, (tag, wire_tag)) in tags.iter().enumerate() {
1064 assert_eq!(tag, wire_tag);
1065 assert_eq!(tag.to_u16(), i as u16 + 1);
1066 assert_eq!(EnvelopeTag::from_u16(tag.to_u16()), Ok(*tag));
1067 }
1068 }
1069}