mirror of
https://github.com/QuixiAI/nvdriver.git
synced 2026-12-06 14:38:47 +00:00
Mechanical, behavior-neutral: edition/resolver keys, unsafe extern blocks, unsafe(no_mangle)/unsafe(export_name), unsafe blocks inside unsafe fn, r#gen renames, --edition flags in Makefiles/tools, rustfmt style_edition pinned to 2021 so formatting stays edition-independent, and clippy collapsible_if allowed workspace-wide (let-chain churn). Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
56 lines
5.7 KiB
Python
56 lines
5.7 KiB
Python
#!/usr/bin/env python3
|
|
"""Generate safe byte codecs; layout oracle remains independent C evidence."""
|
|
from pathlib import Path
|
|
p=Path(__file__).resolve().parents[1]/'src/common/abi/src/lib.rs'
|
|
# field name, Rust type, wire offset. u8 flags deliberately preserve unknown values.
|
|
S=[('PciInfo',12,[('domain','u32',0),('bus','u8',4),('slot','u8',5),('function','u8',6),('vendor_id','u16',8),('device_id','u16',10)]),('IoctlXfer',16,[('cmd','u32',0),('size','u32',4),('ptr','u64',8)]),('CardInfo',72,[('valid','u8',0),('pci_info','PciInfo',4),('gpu_id','u32',16),('interrupt_line','u16',20),('reg_address','u64',24),('reg_size','u64',32),('fb_address','u64',40),('fb_size','u64',48),('minor_number','u32',56),('dev_name','[u8; 10]',60)]),('AllocOsEvent',16,[('h_client','u32',0),('h_device','u32',4),('fd','u32',8),('status','u32',12)]),('FreeOsEvent',16,[('h_client','u32',0),('h_device','u32',4),('fd','u32',8),('status','u32',12)]),('StatusCode',12,[('domain','u32',0),('bus','u8',4),('slot','u8',5),('status','u32',8)]),('RmApiVersion',72,[('cmd','u32',0),('reply','u32',4),('version_string','[u8; 64]',8)]),('QueryDeviceIntr',8,[('intr_status','u32',0),('status','u32',4)]),('SysParams',8,[('memblock_size','u64',0)]),('RegisterFd',4,[('ctl_fd','i32',0)]),('ExportDmaBuf',2608,[('fd','i32',0),('h_client','u32',4),('total_objects','u32',8),('num_objects','u32',12),('index','u32',16),('total_size','u64',24),('mapping_type','u8',32),('allow_mmap','u8',33),('handles','[u32; 128]',36),('offsets','[u64; 128]',552),('sizes','[u64; 128]',1576),('status','u32',2600)]),('WaitOpenComplete',8,[('rc','i32',0),('adapter_status','u32',4)]),('RmControl',32,[('h_client','u32',0),('h_object','u32',4),('cmd','u32',8),('flags','u32',12),('params','u64',16),('params_size','u32',24),('status','u32',28)]),('RmAlloc',48,[('h_root','u32',0),('h_parent','u32',4),('h_new','u32',8),('class','u32',12),('params','u64',16),('rights','u64',24),('params_size','u32',32),('flags','u32',36),('status','u32',40)])]
|
|
S.append(('RmFree',16,[('h_root','u32',0),('h_parent','u32',4),('h_object','u32',8),('status','u32',12)]))
|
|
head='''//! NVIDIA 580.178.04 native x86_64 wire layouts. Generated by tools/generate_abi.py.
|
|
//! Pointer-shaped fields are opaque integers. Codecs never access caller addresses.
|
|
#![no_std]
|
|
#![forbid(unsafe_code)]
|
|
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
|
pub enum WireError { Length { expected: usize, actual: usize } }
|
|
pub trait Wire: Sized { const SIZE: usize; fn decode(bytes: &[u8]) -> Result<Self, WireError>; fn encode(&self, bytes: &mut [u8]) -> Result<(), WireError>; }
|
|
fn check(bytes: &[u8], expected: usize) -> Result<(), WireError> { if bytes.len() == expected { Ok(()) } else { Err(WireError::Length { expected, actual: bytes.len() }) } }
|
|
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
|
#[repr(transparent)]
|
|
pub struct NvStatus(pub u32);
|
|
impl NvStatus { pub const OK: Self = Self(0); pub const INVALID_ARGUMENT: Self = Self(0x1f); pub const INVALID_CLASS: Self = Self(0x22); pub const INVALID_LOCK_STATE: Self = Self(0x2f); pub const INSUFFICIENT_RESOURCES: Self = Self(0x1a); pub const NOT_SUPPORTED: Self = Self(0x56); pub const STATE_IN_USE: Self = Self(0x63); }
|
|
pub const RM_CONTROL_IOCTL: u32 = 0xc020462a;
|
|
pub const RM_ALLOC_IOCTL: u32 = 0xc030462b;
|
|
pub const RM_FREE_IOCTL: u32 = 0xc0104629;
|
|
pub const DRIVER_VERSION: &[u8] = b"580.178.04";
|
|
'''
|
|
import re
|
|
size={'u8':1,'u16':2,'u32':4,'i32':4,'u64':8,'PciInfo':12}
|
|
code=[head]
|
|
for name,n,fields in S:
|
|
code+=['#[derive(Clone, Copy, Debug, PartialEq, Eq)]','#[repr(C)]',f'pub struct {name} {{']+[f' pub {f}: {t},'for f,t,o in fields]+['}',f'impl Wire for {name} {{',f'const SIZE: usize = {n};','fn decode(bytes: &[u8]) -> Result<Self, WireError> { check(bytes, Self::SIZE)?;']
|
|
for f,t,o in fields:
|
|
a=re.fullmatch(r'\[(\w+); (\d+)\]',t)
|
|
if a:
|
|
base,count=a[1],int(a[2]);w=size[base];code.append(f'let mut {f} = [0; {count}]; for (i, value) in {f}.iter_mut().enumerate() {{ *value = {base}::from_le_bytes(bytes[{o}+i*{w}..{o}+(i+1)*{w}].try_into().unwrap()); }}')
|
|
elif t=='PciInfo':code.append(f'let {f} = PciInfo::decode(&bytes[{o}..{o+12}])?;')
|
|
else:code.append(f'let {f} = {t}::from_le_bytes(bytes[{o}..{o+size[t]}].try_into().unwrap());')
|
|
code+=['Ok(Self {'+','.join(f for f,t,o in fields)+'})','}','fn encode(&self, bytes: &mut [u8]) -> Result<(), WireError> { check(bytes, Self::SIZE)?; bytes.fill(0);']
|
|
for f,t,o in fields:
|
|
a=re.fullmatch(r'\[(\w+); (\d+)\]',t)
|
|
if a:
|
|
w=size[a[1]];code.append(f'for (i,value) in self.{f}.iter().enumerate() {{ bytes[{o}+i*{w}..{o}+(i+1)*{w}].copy_from_slice(&value.to_le_bytes()); }}')
|
|
elif t=='PciInfo':code.append(f'self.{f}.encode(&mut bytes[{o}..{o+12}])?;')
|
|
else:code.append(f'bytes[{o}..{o+size[t]}].copy_from_slice(&self.{f}.to_le_bytes());')
|
|
code+=['Ok(())','}','}']
|
|
# Verify every C field offset independently fixed above, not merely total size.
|
|
code+=['#[cfg(test)] mod tests { use super::*; use core::mem::{size_of,align_of,offset_of};','#[test] fn native_layouts() {']
|
|
for name,n,fields in S:
|
|
code.append(f'assert_eq!(size_of::<{name}>(),{n});'); code.append(f'assert_eq!(align_of::<{name}>(),{8 if any(t=="u64" or t.startswith("[u64") for f,t,o in fields) else 4});')
|
|
for f,t,o in fields:code.append(f'assert_eq!(offset_of!({name},{f}),{o});')
|
|
code+=['}','#[test] fn malformed_lengths_and_roundtrip() {']
|
|
for name,n,fields in S:
|
|
code.append(f'assert!({name}::decode(&[0; {n-1}]).is_err()); let value={name}::decode(&[0xa5; {n}]).unwrap(); let mut out=[0;{n}]; value.encode(&mut out).unwrap(); assert_eq!({name}::decode(&out).unwrap(),value);')
|
|
code+=['}','}'];p.write_text(re.sub(r'\*1(?!\d)', '', '\n'.join(code))+'\n')
|
|
|
|
import subprocess
|
|
subprocess.run([str(Path.home()/".cargo/bin/rustfmt"),"--edition","2024",str(Path(__file__).resolve().parents[1]/"src/common/abi/src/lib.rs")],check=True)
|