xous: mark MemoryRange::as_slice and friends as unsafe

Mark `MemoryRange::as_slice()` and `MemoryRange::as_slice_mut()` as
unsafe.

This is due to the fact that not all representable types can be cast to
an arbitrary value. For example, if Process A sends random values to
Process B, then Process B casts the memory to a slice of `bool`, then
any values that are not 0 or 1 are undefined.

Because these functions can leak UB into the program, they are marked as
unsafe.

This patch adds `unsafe {}` blocks to all instances where this function
is called. Additionally, all instances have been checked to verify that
they do not cast to any invalid types -- most use `u8` or `u32`.

Additionally, the long-deprecated `MemoryRange::from_parts()` call was
removed, since that causes UB without being marked as unsafe.

Signed-off-by: Sean Cross <sean@xobs.io>
This commit is contained in:
Sean Cross 2023-09-12 10:03:01 +08:00
parent f17ce555f7
commit 5dfad296ae
24 changed files with 245 additions and 206 deletions

View file

@ -25,8 +25,9 @@ impl FlashDrive {
) )
.unwrap(); .unwrap();
// initialize backing slice with bogus data // initialize backing slice with bogus data. Safety: all `[u32]`
let backing_slice: &mut [u32] = backing.as_slice_mut(); // values are valid
let backing_slice: &mut [u32] = unsafe { backing.as_slice_mut() };
for (index, d) in backing_slice.iter_mut().enumerate() { for (index, d) in backing_slice.iter_mut().enumerate() {
*d = index as u32; *d = index as u32;
} }
@ -44,7 +45,8 @@ impl FlashDrive {
.memory_message_mut() .memory_message_mut()
.expect("incorrect message type received"); .expect("incorrect message type received");
let lba = body.offset.map(|v| v.get()).unwrap_or_default(); let lba = body.offset.map(|v| v.get()).unwrap_or_default();
let data = body.buf.as_slice_mut::<u8>(); // Safety: all values of `[u32]` are valid
let data = unsafe { body.buf.as_slice_mut::<u8>() };
self.read_inner(lba, data); self.read_inner(lba, data);
} }
@ -55,7 +57,8 @@ impl FlashDrive {
.memory_message_mut() .memory_message_mut()
.expect("incorrect message type received"); .expect("incorrect message type received");
let lba = body.offset.map(|v| v.get()).unwrap_or_default(); let lba = body.offset.map(|v| v.get()).unwrap_or_default();
let data = body.buf.as_slice_mut::<u8>(); // Safety: all values of `[u32]` are valid
let data = unsafe { body.buf.as_slice_mut::<u8>() };
self.write_inner(lba, data); self.write_inner(lba, data);
} }
@ -67,7 +70,8 @@ impl FlashDrive {
impl FlashDrive { impl FlashDrive {
fn read_inner(&mut self, lba: usize, data: &mut [u8]) { fn read_inner(&mut self, lba: usize, data: &mut [u8]) {
let backing_slice: &[u8] = self.memory.as_slice(); // Safety: all values of `[u8]` are valid
let backing_slice: &[u8] = unsafe { self.memory.as_slice() };
let rawdata = &backing_slice[lba * self.block_size..(lba + 1) * self.block_size]; let rawdata = &backing_slice[lba * self.block_size..(lba + 1) * self.block_size];
@ -75,7 +79,8 @@ impl FlashDrive {
} }
fn write_inner(&mut self, lba: usize, data: &mut [u8]) { fn write_inner(&mut self, lba: usize, data: &mut [u8]) {
let backing_slice: &mut [u8] = self.memory.as_slice_mut(); // Safety: all values of `[u8]` are valid
let backing_slice: &mut [u8] = unsafe { self.memory.as_slice_mut() };
backing_slice[lba * self.block_size..(lba + 1) * self.block_size] backing_slice[lba * self.block_size..(lba + 1) * self.block_size]
.copy_from_slice(&data[..self.block_size]); .copy_from_slice(&data[..self.block_size]);
} }

View file

@ -1645,7 +1645,7 @@ impl SystemServices {
// buf: MemoryRange, // buf: MemoryRange,
) -> Result<*mut usize, xous_kernel::Error> { ) -> Result<*mut usize, xous_kernel::Error> {
let buf = unsafe { MemoryRange::new(src_virt as usize, len) }?; let buf = unsafe { MemoryRange::new(src_virt as usize, len) }?;
let buf = buf.as_slice(); let buf = unsafe { buf.as_slice() };
let current_pid = self.current_pid(); let current_pid = self.current_pid();
{ {
let target_process = self.get_process(dest_pid)?; let target_process = self.get_process(dest_pid)?;

View file

@ -427,7 +427,7 @@ fn name_from_msg(env: &xous::MessageEnvelope) -> Result<&str, NameConversionErro
fn fill_response(mut env: xous::MessageEnvelope, entries: &HashMap<IpAddr, u32>) -> Option<()> { fn fill_response(mut env: xous::MessageEnvelope, entries: &HashMap<IpAddr, u32>) -> Option<()> {
let mem = env.body.memory_message_mut()?; let mem = env.body.memory_message_mut()?;
let s: &mut [u8] = mem.buf.as_slice_mut(); let s: &mut [u8] = unsafe { mem.buf.as_slice_mut() };
let mut i = s.iter_mut(); let mut i = s.iter_mut();
// First tag = 1 for "Error" -- we'll fill this in at the end when it's successful // First tag = 1 for "Error" -- we'll fill this in at the end when it's successful
@ -472,7 +472,7 @@ fn fill_response(mut env: xous::MessageEnvelope, entries: &HashMap<IpAddr, u32>)
fn fill_error(mut env: xous::MessageEnvelope, code: DnsResponseCode) -> Option<()> { fn fill_error(mut env: xous::MessageEnvelope, code: DnsResponseCode) -> Option<()> {
let mem = env.body.memory_message_mut()?; let mem = env.body.memory_message_mut()?;
let s: &mut [u8] = mem.buf.as_slice_mut(); let s: &mut [u8] = unsafe { mem.buf.as_slice_mut() };
let mut i = s.iter_mut(); let mut i = s.iter_mut();
*i.next()? = 1; *i.next()? = 1;

View file

@ -43,7 +43,8 @@ impl State {
None => return, None => return,
}; };
let settings: &[u8] = settings.as_slice(); // Safety: all values of `[u8]` are valid
let settings: &[u8] = unsafe { settings.as_slice() };
let new_data_u32 = u32::from_le_bytes(data.try_into().unwrap()); let new_data_u32 = u32::from_le_bytes(data.try_into().unwrap());
@ -62,7 +63,8 @@ impl State {
None => return 0, None => return 0,
}; };
let settings: &[u8] = settings.as_slice(); // Safety: all values of `[u8]` are valid
let settings: &[u8] = unsafe { settings.as_slice() };
u32::from_le_bytes(settings[slot.range()].try_into().unwrap()) u32::from_le_bytes(settings[slot.range()].try_into().unwrap())
} }

View file

@ -123,7 +123,8 @@ impl XousDisplay {
} }
} }
pub fn pop(&mut self) { pub fn pop(&mut self) {
let fb: &mut [u32] = self.fb.as_slice_mut(); // Safety: `u32` contains no undefined values
let fb: &mut [u32] = unsafe { self.fb.as_slice_mut() };
// skip copying the status bar, so that the status info is not overwritten by the pop. // skip copying the status bar, so that the status info is not overwritten by the pop.
// this is "fixed" at 32 pixels high (2 * Cjk glyph height hint) per line 79 in gam/src/main.rs // this is "fixed" at 32 pixels high (2 * Cjk glyph height hint) per line 79 in gam/src/main.rs
fb[FB_WIDTH_WORDS * 32..FB_SIZE].copy_from_slice(&self.srfb[FB_WIDTH_WORDS * 32..FB_SIZE]); fb[FB_WIDTH_WORDS * 32..FB_SIZE].copy_from_slice(&self.srfb[FB_WIDTH_WORDS * 32..FB_SIZE]);
@ -184,7 +185,8 @@ impl XousDisplay {
} }
pub fn resume(&mut self) { pub fn resume(&mut self) {
self.susres.resume(); self.susres.resume();
let fb: &mut [u32] = self.fb.as_slice_mut(); // Safety: `u32` contains no undefined values
let fb: &mut [u32] = unsafe { self.fb.as_slice_mut() };
fb[..FB_SIZE].copy_from_slice(&self.srfb); fb[..FB_SIZE].copy_from_slice(&self.srfb);
self.redraw(); self.redraw();
@ -241,7 +243,8 @@ impl XousDisplay {
} }
pub fn as_slice(&self) -> &[u32] { pub fn as_slice(&self) -> &[u32] {
&self.fb.as_slice::<u32>()[..FB_SIZE] // Safety: all values of `[u32]` are valid
unsafe { &self.fb.as_slice::<u32>()[..FB_SIZE] }
} }
/// Beneath this line are pure-HAL layer, and should not be user-visible /// Beneath this line are pure-HAL layer, and should not be user-visible

View file

@ -488,7 +488,8 @@ fn wrapped_main(main_thread_token: backend::MainThreadToken) -> ! {
Buffer::from_memory_message_mut(msg.body.memory_message_mut().unwrap()) Buffer::from_memory_message_mut(msg.body.memory_message_mut().unwrap())
}; };
//let mut bulkread = buf.as_flat::<BulkRead, _>().unwrap(); // try to skip the copy/init step by using a persistent structure //let mut bulkread = buf.as_flat::<BulkRead, _>().unwrap(); // try to skip the copy/init step by using a persistent structure
let fontslice = fontregion.as_slice::<u8>(); // Safety: `u8` contains no undefined values
let fontslice = unsafe { fontregion.as_slice::<u8>() };
assert!(fontlen <= fontslice.len() as u32); assert!(fontlen <= fontslice.len() as u32);
if bulkread.from_offset >= fontlen { if bulkread.from_offset >= fontlen {
log::error!( log::error!(
@ -520,7 +521,8 @@ fn wrapped_main(main_thread_token: backend::MainThreadToken) -> ! {
((backend::FB_SIZE * 4) + 4096) & !4095, ((backend::FB_SIZE * 4) + 4096) & !4095,
xous::MemoryFlags::R | xous::MemoryFlags::W, xous::MemoryFlags::R | xous::MemoryFlags::W,
).expect("couldn't map stash frame buffer"); ).expect("couldn't map stash frame buffer");
let stash = &mut stashmem.as_slice_mut()[..backend::FB_SIZE]; // Safety: `u8` contains no undefined values
let stash = unsafe { &mut stashmem.as_slice_mut()[..backend::FB_SIZE] };
for (&src, dst) in display.as_slice().iter().zip(stash.iter_mut()) { for (&src, dst) in display.as_slice().iter().zip(stash.iter_mut()) {
*dst = src; *dst = src;
} }
@ -535,7 +537,8 @@ fn wrapped_main(main_thread_token: backend::MainThreadToken) -> ! {
((backend::FB_SIZE * 4) + 4096) & !4095, ((backend::FB_SIZE * 4) + 4096) & !4095,
xous::MemoryFlags::R | xous::MemoryFlags::W, xous::MemoryFlags::R | xous::MemoryFlags::W,
).expect("couldn't map stash frame buffer"); ).expect("couldn't map stash frame buffer");
let testpat = &mut testmem.as_slice_mut()[..backend::FB_SIZE]; // Safety: `u8` contains no undefined values
let testpat = unsafe { &mut testmem.as_slice_mut()[..backend::FB_SIZE] };
const DWELL: usize = 1000; const DWELL: usize = 1000;
while ticktimer.elapsed_ms() - start_time < duration as u64 { while ticktimer.elapsed_ms() - start_time < duration as u64 {
// all black // all black

View file

@ -813,7 +813,7 @@ fn main() -> ! {
Some(body) => { Some(body) => {
// u32::MAX indicates a zero-length receive // u32::MAX indicates a zero-length receive
body.valid = xous::MemorySize::new(u32::MAX as usize); body.valid = xous::MemorySize::new(u32::MAX as usize);
let response_data = body.buf.as_slice_mut::<u32>(); let response_data = unsafe { body.buf.as_slice_mut::<u32>() };
response_data[0] = 0; response_data[0] = 0;
response_data[1] = 0; response_data[1] = 0;
}, },
@ -894,7 +894,7 @@ fn main() -> ! {
{ {
let socket = iface.get_socket::<TcpSocket>(*connection); let socket = iface.get_socket::<TcpSocket>(*connection);
body.valid = xous::MemorySize::new( body.valid = xous::MemorySize::new(
write_address(socket.local_endpoint().addr, body.buf.as_slice_mut()) write_address(socket.local_endpoint().addr, unsafe { body.buf.as_slice_mut() })
.unwrap_or_default(), .unwrap_or_default(),
); );
} else { } else {
@ -1089,7 +1089,7 @@ fn main() -> ! {
iface.get_socket::<UdpSocket>(handle).close(); iface.get_socket::<UdpSocket>(handle).close();
iface.remove_socket(handle); iface.remove_socket(handle);
if let Some(response) = msg.body.memory_message_mut() { if let Some(response) = msg.body.memory_message_mut() {
response.buf.as_slice_mut::<u8>()[0] = 0; unsafe { response.buf.as_slice_mut::<u8>()[0] = 0 };
} else if !msg.body.has_memory() && msg.body.is_blocking() { } else if !msg.body.has_memory() && msg.body.is_blocking() {
xous::return_scalar(msg.sender, 0).ok(); xous::return_scalar(msg.sender, 0).ok();
} }
@ -1411,7 +1411,7 @@ fn main() -> ! {
} else { } else {
0 0
}; };
match socket.recv_slice(&mut body.buf.as_slice_mut()[..buflen]) { match socket.recv_slice(unsafe { &mut body.buf.as_slice_mut()[..buflen] }) {
Ok(count) => { Ok(count) => {
log::debug!("rxrcv of {}", count); log::debug!("rxrcv of {}", count);
body.valid = xous::MemorySize::new(count); body.valid = xous::MemorySize::new(count);
@ -1484,7 +1484,7 @@ fn main() -> ! {
} else { } else {
0 0
}; };
match socket.peek_slice(&mut body.buf.as_slice_mut()[..buflen]) { match socket.peek_slice(unsafe { &mut body.buf.as_slice_mut()[..buflen] }) {
Ok(count) => { Ok(count) => {
log::debug!("peekrcv of {}", count); log::debug!("peekrcv of {}", count);
body.valid = xous::MemorySize::new(count); body.valid = xous::MemorySize::new(count);
@ -1538,7 +1538,7 @@ fn main() -> ! {
let body = env.body.memory_message_mut().unwrap(); let body = env.body.memory_message_mut().unwrap();
// Perform the transfer // Perform the transfer
let sent_octets = { let sent_octets = {
let data = body.buf.as_slice::<u8>(); let data = unsafe { body.buf.as_slice::<u8>() };
let length = body let length = body
.valid .valid
.map(|v| { .map(|v| {
@ -1561,7 +1561,7 @@ fn main() -> ! {
}; };
log::trace!("sent {}", sent_octets); log::trace!("sent {}", sent_octets);
let response_data = body.buf.as_slice_mut::<u32>(); let response_data = unsafe { body.buf.as_slice_mut::<u32>() };
response_data[0] = 0; response_data[0] = 0;
response_data[1] = sent_octets as u32; response_data[1] = sent_octets as u32;
} }
@ -1588,7 +1588,7 @@ fn main() -> ! {
} }
}; };
let body = env.body.memory_message_mut().unwrap(); let body = env.body.memory_message_mut().unwrap();
let buf = body.buf.as_slice_mut::<u8>(); let buf = unsafe { body.buf.as_slice_mut::<u8>() };
tcp_accept_success(buf, fd as u16, ep); tcp_accept_success(buf, fd as u16, ep);
} }
@ -1636,7 +1636,7 @@ fn main() -> ! {
Ok((data, endpoint)) => { Ok((data, endpoint)) => {
udp_rx_success( udp_rx_success(
// unwrap is safe here because the message was type-checked prior to insertion into the waiting queue // unwrap is safe here because the message was type-checked prior to insertion into the waiting queue
msg.body.memory_message_mut().unwrap().buf.as_slice_mut(), unsafe { msg.body.memory_message_mut().unwrap().buf.as_slice_mut() },
data, data,
*endpoint // have to duplicate the code between peek and recv because of this type difference *endpoint // have to duplicate the code between peek and recv because of this type difference
); );
@ -1652,7 +1652,7 @@ fn main() -> ! {
log::debug!("netpump udp rx"); log::debug!("netpump udp rx");
udp_rx_success( udp_rx_success(
// unwrap is safe here because the message was type-checked prior to insertion into the waiting queue // unwrap is safe here because the message was type-checked prior to insertion into the waiting queue
msg.body.memory_message_mut().unwrap().buf.as_slice_mut(), unsafe { msg.body.memory_message_mut().unwrap().buf.as_slice_mut() },
data, data,
endpoint endpoint
); );

View file

@ -61,7 +61,7 @@ pub(crate) fn respond_with_error(mut env: xous::MessageEnvelope, code: NetError)
}; };
body.valid = None; body.valid = None;
let s: &mut [u8] = body.buf.as_slice_mut(); let s: &mut [u8] = unsafe { body.buf.as_slice_mut() };
let mut i = s.iter_mut(); let mut i = s.iter_mut();
// Duplicate error to ensure it's seen as an error regardless of byte order/return type // Duplicate error to ensure it's seen as an error regardless of byte order/return type
@ -85,7 +85,7 @@ pub(crate) fn respond_with_connected(
remote_port: u16, remote_port: u16,
) { ) {
let body = env.body.memory_message_mut().unwrap(); let body = env.body.memory_message_mut().unwrap();
let bfr = body.buf.as_slice_mut::<u16>(); let bfr = unsafe { body.buf.as_slice_mut::<u16>() };
log::debug!("successfully connected: {}", idx); log::debug!("successfully connected: {}", idx);
bfr[0] = 0; bfr[0] = 0;

View file

@ -18,7 +18,7 @@ pub(crate) fn std_tcp_listen(
} }
}; };
let bytes = body.buf.as_slice::<u8>(); let bytes = unsafe { body.buf.as_slice::<u8>() };
let mut local_port = u16::from_le_bytes([bytes[0], bytes[1]]); let mut local_port = u16::from_le_bytes([bytes[0], bytes[1]]);
let mut retry_local_port = false; let mut retry_local_port = false;
if local_port == 0 { if local_port == 0 {
@ -83,7 +83,7 @@ pub(crate) fn std_tcp_listen(
let fd = insert_or_append(our_sockets, handle) as u8; let fd = insert_or_append(our_sockets, handle) as u8;
let body = msg.body.memory_message_mut().unwrap(); let body = msg.body.memory_message_mut().unwrap();
let bfr = body.buf.as_slice_mut::<u8>(); let bfr = unsafe { body.buf.as_slice_mut::<u8>() };
log::debug!("successfully connected: {} -> {:?}:{}", fd, address, local_port); log::debug!("successfully connected: {} -> {:?}:{}", fd, address, local_port);
bfr[0] = 0; bfr[0] = 0;
bfr[1] = fd; bfr[1] = fd;
@ -119,14 +119,14 @@ pub(crate) fn std_tcp_accept(
} }
}; };
let args = body.buf.as_slice::<u8>(); let args = unsafe { body.buf.as_slice::<u8>() };
let nonblocking = args[0] == 0; let nonblocking = args[0] == 0;
let socket = iface.get_socket::<TcpSocket>(*handle); let socket = iface.get_socket::<TcpSocket>(*handle);
if socket.is_active() { if socket.is_active() {
log::debug!("accept did not block; immediately returning TcpSocket"); log::debug!("accept did not block; immediately returning TcpSocket");
let buf = body.buf.as_slice_mut::<u8>(); let buf = unsafe { body.buf.as_slice_mut::<u8>() };
tcp_server_remote_close_poll.push(*handle); tcp_server_remote_close_poll.push(*handle);
tcp_accept_success(buf, fd as u16, socket.remote_endpoint()); tcp_accept_success(buf, fd as u16, socket.remote_endpoint());
return; return;

View file

@ -27,7 +27,7 @@ pub(crate) fn std_tcp_connect(
} }
}; };
let bytes = body.buf.as_slice::<u8>(); let bytes = unsafe { body.buf.as_slice::<u8>() };
let remote_port = u16::from_le_bytes([bytes[0], bytes[1]]); let remote_port = u16::from_le_bytes([bytes[0], bytes[1]]);
let timeout_ms = NonZeroU64::new(u64::from_le_bytes(bytes[2..10].try_into().unwrap())); let timeout_ms = NonZeroU64::new(u64::from_le_bytes(bytes[2..10].try_into().unwrap()));
let address = match parse_address(&bytes[10..]) { let address = match parse_address(&bytes[10..]) {
@ -120,7 +120,7 @@ pub(crate) fn std_tcp_tx(
// Perform the transfer // Perform the transfer
let sent_octets = { let sent_octets = {
let data = body.buf.as_slice::<u8>(); let data = unsafe { body.buf.as_slice::<u8>() };
let length = body let length = body
.valid .valid
.map(|v| { .map(|v| {
@ -142,7 +142,7 @@ pub(crate) fn std_tcp_tx(
}; };
log::trace!("sent {}", sent_octets); log::trace!("sent {}", sent_octets);
let response_data = body.buf.as_slice_mut::<u32>(); let response_data = unsafe { body.buf.as_slice_mut::<u32>() };
response_data[0] = 0; response_data[0] = 0;
response_data[1] = sent_octets as u32; response_data[1] = sent_octets as u32;
} }
@ -186,7 +186,7 @@ pub(crate) fn std_tcp_rx(
} else { } else {
0 0
}; };
match socket.recv_slice(&mut body.buf.as_slice_mut()[..buflen]) { match socket.recv_slice(unsafe { &mut body.buf.as_slice_mut()[..buflen] }) {
Ok(bytes) => { Ok(bytes) => {
// it's actually valid to receive 0 bytes, but the encoding of this field doesn't allow it. // it's actually valid to receive 0 bytes, but the encoding of this field doesn't allow it.
// so, `None` is abused to represent the value of "0" bytes, which is what is naturally returned // so, `None` is abused to represent the value of "0" bytes, which is what is naturally returned
@ -263,7 +263,7 @@ pub(crate) fn std_tcp_peek(
} else { } else {
0 0
}; };
match socket.peek_slice(&mut body.buf.as_slice_mut()[..buflen]) { match socket.peek_slice(unsafe { &mut body.buf.as_slice_mut()[..buflen] }) {
Ok(bytes) => { Ok(bytes) => {
// it's actually valid to receive 0 bytes, but the encoding of this field doesn't allow it. // it's actually valid to receive 0 bytes, but the encoding of this field doesn't allow it.
// so, `None` is abused to represent the value of "0" bytes, which is what is naturally returned // so, `None` is abused to represent the value of "0" bytes, which is what is naturally returned

View file

@ -25,7 +25,7 @@ pub(crate) fn std_udp_bind(
} }
}; };
let bytes = body.buf.as_slice::<u8>(); let bytes = unsafe { body.buf.as_slice::<u8>() };
let local_port = u16::from_le_bytes([bytes[0], bytes[1]]); let local_port = u16::from_le_bytes([bytes[0], bytes[1]]);
let address = match parse_address(&bytes[2..]) { let address = match parse_address(&bytes[2..]) {
Some(addr) => addr, Some(addr) => addr,
@ -62,7 +62,7 @@ pub(crate) fn std_udp_bind(
let idx = insert_or_append(our_sockets, handle) as u8; let idx = insert_or_append(our_sockets, handle) as u8;
let body = msg.body.memory_message_mut().unwrap(); let body = msg.body.memory_message_mut().unwrap();
let bfr = body.buf.as_slice_mut::<u8>(); let bfr = unsafe { body.buf.as_slice_mut::<u8>() };
log::trace!("successfully connected: {} -> {:?}:{}", idx, address, local_port); log::trace!("successfully connected: {} -> {:?}:{}", idx, address, local_port);
bfr[0] = 0; bfr[0] = 0;
bfr[1] = idx; bfr[1] = idx;
@ -95,7 +95,7 @@ pub(crate) fn std_udp_rx(
} }
}; };
let args = body.buf.as_slice::<u8>(); let args = unsafe { body.buf.as_slice::<u8>() };
let nonblocking = args[0] == 0; let nonblocking = args[0] == 0;
let expiry = if !nonblocking { let expiry = if !nonblocking {
let to = u64::from_le_bytes(args[1..9].try_into().unwrap()); let to = u64::from_le_bytes(args[1..9].try_into().unwrap());
@ -143,7 +143,7 @@ pub(crate) fn std_udp_rx(
// difference in types means you can't do a pattern match assign to a common variable. // difference in types means you can't do a pattern match assign to a common variable.
match socket.peek() { match socket.peek() {
Ok((data, endpoint)) => { Ok((data, endpoint)) => {
udp_rx_success(body.buf.as_slice_mut(), data, *endpoint); udp_rx_success(unsafe { body.buf.as_slice_mut() }, data, *endpoint);
} }
Err(e) => { Err(e) => {
log::error!("unable to receive: {:?}", e); log::error!("unable to receive: {:?}", e);
@ -154,7 +154,7 @@ pub(crate) fn std_udp_rx(
match socket.recv() { match socket.recv() {
Ok((data, endpoint)) => { Ok((data, endpoint)) => {
log::debug!("immediate udp rx"); log::debug!("immediate udp rx");
udp_rx_success(body.buf.as_slice_mut(), data, endpoint); udp_rx_success(unsafe { body.buf.as_slice_mut() }, data, endpoint);
} }
Err(e) => { Err(e) => {
log::error!("unable to receive: {:?}", e); log::error!("unable to receive: {:?}", e);
@ -206,7 +206,7 @@ pub(crate) fn std_udp_tx(
}; };
// unpack arguments // unpack arguments
let bytes = body.buf.as_slice::<u8>(); let bytes = unsafe { body.buf.as_slice::<u8>() };
let remote_port = u16::from_le_bytes([bytes[0], bytes[1]]); let remote_port = u16::from_le_bytes([bytes[0], bytes[1]]);
let address = match parse_address(&bytes[2..]) { let address = match parse_address(&bytes[2..]) {
Some(addr) => addr, Some(addr) => addr,
@ -247,7 +247,7 @@ pub(crate) fn std_udp_tx(
} }
} }
match socket.send_slice(&bytes[21..21 + len as usize], IpEndpoint::new(address, remote_port)) { match socket.send_slice(&bytes[21..21 + len as usize], IpEndpoint::new(address, remote_port)) {
Ok(_) => { Ok(_) => unsafe {
body.buf.as_slice_mut()[0] = 0; body.buf.as_slice_mut()[0] = 0;
} }
Err(_e) => { Err(_e) => {
@ -304,7 +304,7 @@ pub(crate) fn std_failure(mut env: xous::MessageEnvelope, code: NetError) -> Opt
}; };
body.valid = None; body.valid = None;
let s: &mut [u8] = body.buf.as_slice_mut(); let s: &mut [u8] = unsafe { body.buf.as_slice_mut() };
let mut i = s.iter_mut(); let mut i = s.iter_mut();
*i.next()? = 1; *i.next()? = 1;

View file

@ -78,15 +78,13 @@ impl EmuStorage {
EmuStorage { EmuStorage {
} }
} }
pub fn as_slice<T>(&self) -> &[T] { pub unsafe fn as_slice<T>(&self) -> &[T] {
unsafe {
core::slice::from_raw_parts( core::slice::from_raw_parts(
flashmem().memory.as_ptr() as *const T, flashmem().memory.as_ptr() as *const T,
flashmem().memory.len() / core::mem::size_of::<T>(), flashmem().memory.len() / core::mem::size_of::<T>(),
) )
} }
} pub unsafe fn as_mut_slice(&mut self) -> &mut [u8] {
pub fn as_mut_slice(&mut self) -> &mut [u8] {
flashmem().memory.as_mut_slice() flashmem().memory.as_mut_slice()
} }
/// used to reset the storage for repeated test case generation /// used to reset the storage for repeated test case generation

View file

@ -197,7 +197,8 @@ impl PddbOs {
) )
.expect("Couldn't map the PDDB memory range"); .expect("Couldn't map the PDDB memory range");
#[cfg(any(feature="precursor", feature="renode"))] #[cfg(any(feature="precursor", feature="renode"))]
log::info!("pddb slice len: {}, PDDB_A_LEN: {}, raw len: {}", pddb.as_slice::<u8>().len(), PDDB_A_LEN, pddb.len()); // sanity check the PDDB size on init // Safety: all u8 values are valid
log::info!("pddb slice len: {}, PDDB_A_LEN: {}, raw len: {}", unsafe { pddb.as_slice::<u8>().len() }, PDDB_A_LEN, pddb.len()); // sanity check the PDDB size on init
// the mbbb is located one page off from the Page Table // the mbbb is located one page off from the Page Table
let key_phys_base = PageAlignedPa::from(size_of::<PageTableInFlash>()); let key_phys_base = PageAlignedPa::from(size_of::<PageTableInFlash>());
@ -376,7 +377,7 @@ impl PddbOs {
// log::trace!("patch bef: {:x?}", &self.pddb_mr.as_slice::<u8>()[offset as usize + self.data_phys_base.as_usize()..offset as usize + self.data_phys_base.as_usize() + 48]); // log::trace!("patch bef: {:x?}", &self.pddb_mr.as_slice::<u8>()[offset as usize + self.data_phys_base.as_usize()..offset as usize + self.data_phys_base.as_usize() + 48]);
assert!(data.len() + offset as usize <= PDDB_A_LEN - self.data_phys_base.as_usize(), "attempt to store past disk boundary"); assert!(data.len() + offset as usize <= PDDB_A_LEN - self.data_phys_base.as_usize(), "attempt to store past disk boundary");
self.spinor.patch( self.spinor.patch(
self.pddb_mr.as_slice(), unsafe { self.pddb_mr.as_slice() },
xous::PDDB_LOC, xous::PDDB_LOC,
&data, &data,
offset + self.data_phys_base.as_u32(), offset + self.data_phys_base.as_u32(),
@ -391,7 +392,7 @@ impl PddbOs {
if let Some(mbbb) = self.mbbb_retrieve() { if let Some(mbbb) = self.mbbb_retrieve() {
if let Some(erased_offset) = self.pt_find_erased_slot() { if let Some(erased_offset) = self.pt_find_erased_slot() {
self.spinor.patch( self.spinor.patch(
self.pddb_mr.as_slice(), unsafe { self.pddb_mr.as_slice() },
xous::PDDB_LOC, xous::PDDB_LOC,
&mbbb, &mbbb,
self.pt_phys_base.as_u32() + erased_offset, self.pt_phys_base.as_u32() + erased_offset,
@ -407,7 +408,7 @@ impl PddbOs {
// 3. copy the data to a local buffer // 3. copy the data to a local buffer
let mut mbbb_page = [0u8; PAGE_SIZE]; let mut mbbb_page = [0u8; PAGE_SIZE];
for (&src, dst) in for (&src, dst) in
self.pddb_mr.as_slice()[self.pt_phys_base.as_usize() + base_page..self.pt_phys_base.as_usize() + base_page + PAGE_SIZE].iter() unsafe { self.pddb_mr.as_slice()[self.pt_phys_base.as_usize() + base_page..self.pt_phys_base.as_usize() + base_page + PAGE_SIZE].iter() }
.zip(mbbb_page.iter_mut()) { .zip(mbbb_page.iter_mut()) {
*dst = src; *dst = src;
} }
@ -423,7 +424,7 @@ impl PddbOs {
// 6. erase the original page area, thus making the MBBB the authorative location // 6. erase the original page area, thus making the MBBB the authorative location
let blank = [0xffu8; PAGE_SIZE]; let blank = [0xffu8; PAGE_SIZE];
self.spinor.patch( self.spinor.patch(
self.pddb_mr.as_slice(), unsafe { self.pddb_mr.as_slice() },
xous::PDDB_LOC, xous::PDDB_LOC,
&blank, &blank,
self.pt_phys_base.as_u32() + base_page as u32, self.pt_phys_base.as_u32() + base_page as u32,
@ -436,7 +437,7 @@ impl PddbOs {
fn patch_pagetable_raw(&self, data: &[u8], offset: u32) { fn patch_pagetable_raw(&self, data: &[u8], offset: u32) {
assert!(data.len() + offset as usize <= size_of::<PageTableInFlash>(), "attempt to patch past page table end"); assert!(data.len() + offset as usize <= size_of::<PageTableInFlash>(), "attempt to patch past page table end");
self.spinor.patch( self.spinor.patch(
self.pddb_mr.as_slice(), unsafe { self.pddb_mr.as_slice() },
xous::PDDB_LOC, xous::PDDB_LOC,
&data, &data,
self.pt_phys_base.as_u32() + offset, self.pt_phys_base.as_u32() + offset,
@ -446,7 +447,7 @@ impl PddbOs {
assert!(data.len() + offset as usize <= PAGE_SIZE, "attempt to burn key data that is outside the key region"); assert!(data.len() + offset as usize <= PAGE_SIZE, "attempt to burn key data that is outside the key region");
log::info!("patching keys area with {} bytes", data.len()); log::info!("patching keys area with {} bytes", data.len());
self.spinor.patch( self.spinor.patch(
self.pddb_mr.as_slice(), unsafe { self.pddb_mr.as_slice() },
xous::PDDB_LOC, xous::PDDB_LOC,
data, data,
self.key_phys_base.as_u32() + offset self.key_phys_base.as_u32() + offset
@ -455,7 +456,7 @@ impl PddbOs {
fn patch_mbbb(&self, data: &[u8], offset: u32) { fn patch_mbbb(&self, data: &[u8], offset: u32) {
assert!(data.len() + offset as usize <= PAGE_SIZE * MBBB_PAGES, "mbbb patch would go out of bounds"); assert!(data.len() + offset as usize <= PAGE_SIZE * MBBB_PAGES, "mbbb patch would go out of bounds");
self.spinor.patch( self.spinor.patch(
self.pddb_mr.as_slice(), unsafe { self.pddb_mr.as_slice() },
xous::PDDB_LOC, xous::PDDB_LOC,
data, data,
self.mbbb_phys_base.as_u32() + offset self.mbbb_phys_base.as_u32() + offset
@ -466,7 +467,7 @@ impl PddbOs {
fn patch_fscb(&self, data: &[u8], offset: u32) { fn patch_fscb(&self, data: &[u8], offset: u32) {
assert!(data.len() + offset as usize <= PAGE_SIZE * FSCB_PAGES, "fscb patch would go out of bounds"); assert!(data.len() + offset as usize <= PAGE_SIZE * FSCB_PAGES, "fscb patch would go out of bounds");
self.spinor.patch( self.spinor.patch(
self.pddb_mr.as_slice(), unsafe { self.pddb_mr.as_slice() },
xous::PDDB_LOC, xous::PDDB_LOC,
data, data,
self.fscb_phys_base.as_u32() + offset self.fscb_phys_base.as_u32() + offset
@ -497,7 +498,7 @@ impl PddbOs {
/// This would want to be optimized or cached for a much larger filesystem. /// This would want to be optimized or cached for a much larger filesystem.
/// Returns the physical address of the erased slot as an offset from the pt_phys_base() /// Returns the physical address of the erased slot as an offset from the pt_phys_base()
fn pt_find_erased_slot(&self) -> Option<PhysAddr> { fn pt_find_erased_slot(&self) -> Option<PhysAddr> {
let pt: &[u8] = &self.pddb_mr.as_slice()[self.pt_phys_base.as_usize()..self.pt_phys_base.as_usize() + size_of::<PageTableInFlash>()]; let pt: &[u8] = unsafe { &self.pddb_mr.as_slice()[self.pt_phys_base.as_usize()..self.pt_phys_base.as_usize() + size_of::<PageTableInFlash>()] };
let blank = [0xffu8; aes::BLOCK_SIZE]; let blank = [0xffu8; aes::BLOCK_SIZE];
for (index, page) in pt.chunks(PAGE_SIZE).enumerate() { for (index, page) in pt.chunks(PAGE_SIZE).enumerate() {
if page[..aes::BLOCK_SIZE] == blank { if page[..aes::BLOCK_SIZE] == blank {
@ -507,7 +508,7 @@ impl PddbOs {
None None
} }
fn pt_as_slice(&self) -> &[u8] { fn pt_as_slice(&self) -> &[u8] {
&self.pddb_mr.as_slice()[self.pt_phys_base.as_usize()..self.pt_phys_base.as_usize() + size_of::<PageTableInFlash>()] unsafe { &self.pddb_mr.as_slice()[self.pt_phys_base.as_usize()..self.pt_phys_base.as_usize() + size_of::<PageTableInFlash>()] }
} }
/// scans the page tables and returns all entries for a given basis /// scans the page tables and returns all entries for a given basis
@ -639,7 +640,7 @@ impl PddbOs {
/// maps a StaticCryptoData structure into the key area of the PDDB. /// maps a StaticCryptoData structure into the key area of the PDDB.
fn static_crypto_data_get(&self) -> &StaticCryptoData { fn static_crypto_data_get(&self) -> &StaticCryptoData {
let scd_ptr = self.pddb_mr.as_slice::<u8>()[self.key_phys_base.as_usize()..self.key_phys_base.as_usize() + PAGE_SIZE].as_ptr() as *const StaticCryptoData; let scd_ptr = unsafe { self.pddb_mr.as_slice::<u8>()[self.key_phys_base.as_usize()..self.key_phys_base.as_usize() + PAGE_SIZE].as_ptr() as *const StaticCryptoData };
let scd: &StaticCryptoData = unsafe{scd_ptr.as_ref().unwrap()}; let scd: &StaticCryptoData = unsafe{scd_ptr.as_ref().unwrap()};
scd scd
} }
@ -781,7 +782,7 @@ impl PddbOs {
} }
fn mbbb_as_slice(&self) -> &[u8] { fn mbbb_as_slice(&self) -> &[u8] {
&self.pddb_mr.as_slice()[self.mbbb_phys_base.as_usize()..self.mbbb_phys_base.as_usize() + MBBB_PAGES * PAGE_SIZE] unsafe { &self.pddb_mr.as_slice()[self.mbbb_phys_base.as_usize()..self.mbbb_phys_base.as_usize() + MBBB_PAGES * PAGE_SIZE] }
} }
fn mbbb_retrieve(&self) -> Option<&[u8]> { fn mbbb_retrieve(&self) -> Option<&[u8]> {
// Invariant: MBBB pages should be blank, unless a page is stashed there. So, just check the first // Invariant: MBBB pages should be blank, unless a page is stashed there. So, just check the first
@ -880,7 +881,7 @@ impl PddbOs {
// We could "paper over" this by re-reading the data, but really, this problem should be solved by the d-cache // We could "paper over" this by re-reading the data, but really, this problem should be solved by the d-cache
// flush in the SPINOR primitive. // flush in the SPINOR primitive.
let page_start = dest_page_start as usize * PAGE_SIZE; let page_start = dest_page_start as usize * PAGE_SIZE;
let fscb_slice = &self.pddb_mr.as_slice()[self.fscb_phys_base.as_usize()..self.fscb_phys_base.as_usize() + FSCB_PAGES * PAGE_SIZE]; let fscb_slice = &unsafe { self.pddb_mr.as_slice() }[self.fscb_phys_base.as_usize()..self.fscb_phys_base.as_usize() + FSCB_PAGES * PAGE_SIZE];
let mut fscb_buf = [0; FASTSPACE_PAGES * PAGE_SIZE - size_of::<Nonce>()]; let mut fscb_buf = [0; FASTSPACE_PAGES * PAGE_SIZE - size_of::<Nonce>()];
// copy the encrypted data to the decryption buffer // copy the encrypted data to the decryption buffer
fscb_buf.copy_from_slice(&fscb_slice[page_start + size_of::<Nonce>() .. page_start + FASTSPACE_PAGES * PAGE_SIZE]); fscb_buf.copy_from_slice(&fscb_slice[page_start + size_of::<Nonce>() .. page_start + FASTSPACE_PAGES * PAGE_SIZE]);
@ -1095,7 +1096,7 @@ impl PddbOs {
} }
fn fscb_deref(&self) -> &[u8] { fn fscb_deref(&self) -> &[u8] {
&self.pddb_mr.as_slice()[self.fscb_phys_base.as_usize()..self.fscb_phys_base.as_usize() + FSCB_PAGES * PAGE_SIZE] unsafe { &self.pddb_mr.as_slice()[self.fscb_phys_base.as_usize()..self.fscb_phys_base.as_usize() + FSCB_PAGES * PAGE_SIZE] }
} }
/// Reads the data structures in the FSCB, if any, and stores the results in the fspace_cache HashSet. /// Reads the data structures in the FSCB, if any, and stores the results in the fspace_cache HashSet.
/// Note the following convention on the fscb: if the first 128 bits of a page are all 1's, then that sector /// Note the following convention on the fscb: if the first 128 bits of a page are all 1's, then that sector
@ -1122,7 +1123,7 @@ impl PddbOs {
self.fspace_log_len = 0; self.fspace_log_len = 0;
// let fscb_slice = self.fscb_deref(); // can't use this line because it causse self to be immutably borrowed, so we write out the equivalent below. // let fscb_slice = self.fscb_deref(); // can't use this line because it causse self to be immutably borrowed, so we write out the equivalent below.
let fscb_slice = &self.pddb_mr.as_slice()[self.fscb_phys_base.as_usize()..self.fscb_phys_base.as_usize() + FSCB_PAGES * PAGE_SIZE]; let fscb_slice = unsafe { &self.pddb_mr.as_slice()[self.fscb_phys_base.as_usize()..self.fscb_phys_base.as_usize() + FSCB_PAGES * PAGE_SIZE] };
// 1. scan through the entire space, and look for the FastSpace record. It can be identified by the // 1. scan through the entire space, and look for the FastSpace record. It can be identified by the
// first 16 (aes::BLOCK_SIZE) bytes not being all 1's. // first 16 (aes::BLOCK_SIZE) bytes not being all 1's.
@ -1517,9 +1518,9 @@ impl PddbOs {
/// We don't clip it off because it would require re-allocating a vector, and it's cheaper (although less elegant) to later /// We don't clip it off because it would require re-allocating a vector, and it's cheaper (although less elegant) to later
/// just index past it. /// just index past it.
pub(crate) fn data_decrypt_page(&self, cipher: &Aes256GcmSiv, aad: &[u8], page: &PhysPage) -> Option<Vec::<u8>> { pub(crate) fn data_decrypt_page(&self, cipher: &Aes256GcmSiv, aad: &[u8], page: &PhysPage) -> Option<Vec::<u8>> {
let ct_slice = &self.pddb_mr.as_slice()[ let ct_slice = unsafe { &self.pddb_mr.as_slice()[
self.data_phys_base.as_usize() + page.page_number() as usize * PAGE_SIZE .. self.data_phys_base.as_usize() + page.page_number() as usize * PAGE_SIZE ..
self.data_phys_base.as_usize() + (page.page_number() as usize + 1) * PAGE_SIZE]; self.data_phys_base.as_usize() + (page.page_number() as usize + 1) * PAGE_SIZE] };
let nonce = &ct_slice[..size_of::<Nonce>()]; let nonce = &ct_slice[..size_of::<Nonce>()];
let ct = &ct_slice[size_of::<Nonce>()..]; let ct = &ct_slice[size_of::<Nonce>()..];
match cipher.decrypt( match cipher.decrypt(
@ -1557,9 +1558,9 @@ impl PddbOs {
const KCOM_NONCE_LEN: usize = 32; const KCOM_NONCE_LEN: usize = 32;
const KCOM_LEN: usize = 32; const KCOM_LEN: usize = 32;
const MAC_LEN: usize = 16; const MAC_LEN: usize = 16;
let ct_slice = &self.pddb_mr.as_slice()[ let ct_slice = unsafe { &self.pddb_mr.as_slice()[
self.data_phys_base.as_usize() + page.page_number() as usize * PAGE_SIZE .. self.data_phys_base.as_usize() + page.page_number() as usize * PAGE_SIZE ..
self.data_phys_base.as_usize() + (page.page_number() as usize + 1) * PAGE_SIZE]; self.data_phys_base.as_usize() + (page.page_number() as usize + 1) * PAGE_SIZE] };
log::debug!("commit data at 0x{:x}", self.data_phys_base.as_usize() + page.page_number() as usize * PAGE_SIZE); log::debug!("commit data at 0x{:x}", self.data_phys_base.as_usize() + page.page_number() as usize * PAGE_SIZE);
let nonce = &ct_slice[..size_of::<Nonce>()]; let nonce = &ct_slice[..size_of::<Nonce>()];
let ct_total = &ct_slice[size_of::<Nonce>()..]; let ct_total = &ct_slice[size_of::<Nonce>()..];
@ -1838,7 +1839,7 @@ impl PddbOs {
// do a blank check first to see if the sector really needs erasing // do a blank check first to see if the sector really needs erasing
let mut blank = true; let mut blank = true;
let slice_start = (offset - xous::PDDB_LOC) as usize / size_of::<u32>(); let slice_start = (offset - xous::PDDB_LOC) as usize / size_of::<u32>();
for word in self.pddb_mr.as_slice::<u32>()[slice_start..slice_start + SPINOR_BULK_ERASE_SIZE as usize / size_of::<u32>()].iter() { for word in unsafe { self.pddb_mr.as_slice::<u32>()[slice_start..slice_start + SPINOR_BULK_ERASE_SIZE as usize / size_of::<u32>()].iter() } {
if *word != 0xFFFF_FFFF { if *word != 0xFFFF_FFFF {
blank = false; blank = false;
break; break;
@ -2000,7 +2001,7 @@ impl PddbOs {
// session key, previous data should be undecipherable. You shouldn't do this for a production erase // session key, previous data should be undecipherable. You shouldn't do this for a production erase
// but this is good for speeding up testing. // but this is good for speeding up testing.
let mut is_blank = true; let mut is_blank = true;
let block: &[u8] = &self.pddb_mr.as_slice()[offset + aes::BLOCK_SIZE * 3..offset + aes::BLOCK_SIZE * 4]; let block: &[u8] = unsafe { &self.pddb_mr.as_slice()[offset + aes::BLOCK_SIZE * 3..offset + aes::BLOCK_SIZE * 4] };
for (&a, &b) in block.iter().zip(blank.iter()) { for (&a, &b) in block.iter().zip(blank.iter()) {
if a != b { if a != b {
is_blank = false; is_blank = false;
@ -2022,7 +2023,7 @@ impl PddbOs {
} }
} }
self.spinor.patch( self.spinor.patch(
self.pddb_mr.as_slice(), unsafe { self.pddb_mr.as_slice() },
xous::PDDB_LOC, xous::PDDB_LOC,
&temp, &temp,
offset as u32 offset as u32
@ -2184,7 +2185,7 @@ impl PddbOs {
if let Some(mbbb) = self.mbbb_retrieve() { if let Some(mbbb) = self.mbbb_retrieve() {
if let Some(erased_offset) = self.pt_find_erased_slot() { if let Some(erased_offset) = self.pt_find_erased_slot() {
self.spinor.patch( self.spinor.patch(
self.pddb_mr.as_slice(), unsafe { self.pddb_mr.as_slice() },
xous::PDDB_LOC, xous::PDDB_LOC,
&mbbb, &mbbb,
self.pt_phys_base.as_u32() + erased_offset, self.pt_phys_base.as_u32() + erased_offset,
@ -2255,7 +2256,7 @@ impl PddbOs {
// at the base of the `pddb_mr`. // at the base of the `pddb_mr`.
let pddb_data_len = PDDB_A_LEN - self.data_phys_base.as_usize(); let pddb_data_len = PDDB_A_LEN - self.data_phys_base.as_usize();
let pddb_data_pages = pddb_data_len / PAGE_SIZE; let pddb_data_pages = pddb_data_len / PAGE_SIZE;
let pagetable: &[u8] = &self.pddb_mr.as_slice()[..pddb_data_pages * size_of::<Pte>()]; let pagetable: &[u8] = unsafe { &self.pddb_mr.as_slice()[..pddb_data_pages * size_of::<Pte>()] };
log::info!("Derived page table of len 0x{:x}", pagetable.len()); log::info!("Derived page table of len 0x{:x}", pagetable.len());
let entries_per_page = PAGE_SIZE / size_of::<Pte>(); let entries_per_page = PAGE_SIZE / size_of::<Pte>();
modals.start_progress(t!("pddb.rekey.running", locales::LANG), 0, (pddb_data_pages * size_of::<Pte>()) as u32, 0).ok(); modals.start_progress(t!("pddb.rekey.running", locales::LANG), 0, (pddb_data_pages * size_of::<Pte>()) as u32, 0).ok();
@ -2633,7 +2634,7 @@ impl PddbOs {
pub(crate) fn checksums(&self, modals: Option::<&Modals>) -> root_keys::api::Checksums { pub(crate) fn checksums(&self, modals: Option::<&Modals>) -> root_keys::api::Checksums {
let mut checksums = root_keys::api::Checksums::default(); let mut checksums = root_keys::api::Checksums::default();
let pddb = self.pddb_mr.as_slice(); let pddb = unsafe { self.pddb_mr.as_slice() };
if let Some(m) = modals { if let Some(m) = modals {
m.start_progress( m.start_progress(
t!("pddb.checksums", locales::LANG), t!("pddb.checksums", locales::LANG),

View file

@ -997,7 +997,8 @@ impl Pddb {
let mut serializer = WriteSerializer::new(AlignedVec::new()); let mut serializer = WriteSerializer::new(AlignedVec::new());
let pos = serializer.serialize_value(&request).unwrap(); let pos = serializer.serialize_value(&request).unwrap();
let buf = serializer.into_inner(); let buf = serializer.into_inner();
msg_mem.as_slice_mut()[..buf.len()].copy_from_slice(buf.as_slice()); // Safety: `u8` contains no undefined values
unsafe { msg_mem.as_slice_mut()[..buf.len()].copy_from_slice(buf.as_slice()) };
// initiate the request: assemble a MemoryMessage // initiate the request: assemble a MemoryMessage
let msg = xous::MemoryMessage { let msg = xous::MemoryMessage {
id: Opcode::DictBulkRead.to_usize().unwrap(), id: Opcode::DictBulkRead.to_usize().unwrap(),
@ -1016,8 +1017,9 @@ impl Pddb {
// unpack the return code. The result is not a single rkyv struct, it's hand-packed binary data. Unpack it. // unpack the return code. The result is not a single rkyv struct, it's hand-packed binary data. Unpack it.
let mut index = 0; let mut index = 0;
let mut header = BulkReadHeader::default(); let mut header = BulkReadHeader::default();
// Safety: `u8` contains no undefined values
header.deref_mut().copy_from_slice( header.deref_mut().copy_from_slice(
&msg_mem.as_slice()[index..index + size_of::<BulkReadHeader>()] unsafe { &msg_mem.as_slice()[index..index + size_of::<BulkReadHeader>()] }
); );
index += size_of::<BulkReadHeader>(); index += size_of::<BulkReadHeader>();
match FromPrimitive::from_u32(header.code).unwrap_or(PddbBulkReadCode::InternalError) { match FromPrimitive::from_u32(header.code).unwrap_or(PddbBulkReadCode::InternalError) {
@ -1042,9 +1044,11 @@ impl Pddb {
// quit if we don't have enough space to decode at least another two indices // quit if we don't have enough space to decode at least another two indices
break; break;
} }
let size = u32::from_le_bytes(msg_mem.as_slice()[index..index + size_of::<u32>()].try_into().unwrap()); // Safety: `u32` contains no undefined values
let size = unsafe { u32::from_le_bytes(msg_mem.as_slice()[index..index + size_of::<u32>()].try_into().unwrap()) };
index += size_of::<u32>(); index += size_of::<u32>();
let pos = u32::from_le_bytes(msg_mem.as_slice()[index..index + size_of::<u32>()].try_into().unwrap()); // Safety: `u32` contains no undefined values
let pos = unsafe { u32::from_le_bytes(msg_mem.as_slice()[index..index + size_of::<u32>()].try_into().unwrap()) };
index += size_of::<u32>(); index += size_of::<u32>();
log::trace!("unpacking message at {}({})", size, pos); log::trace!("unpacking message at {}({})", size, pos);
if size != 0 && pos != 0 { if size != 0 && pos != 0 {

View file

@ -44,7 +44,8 @@ pub(crate) fn stat_path(
basis_cache: &mut BasisCache, basis_cache: &mut BasisCache,
) -> Result<(), crate::PddbRetcode> { ) -> Result<(), crate::PddbRetcode> {
// Convert the memory to a Senres buffer // Convert the memory to a Senres buffer
let mut backing = senres::Message::from_mut_slice(mem.buf.as_slice_mut()) // Safety: the memory message must be aligned, and we test for validity here
let mut backing = unsafe { senres::Message::from_mut_slice(mem.buf.as_slice_mut()) }
.or(Err(crate::PddbRetcode::InternalError))?; .or(Err(crate::PddbRetcode::InternalError))?;
let reader = backing let reader = backing
@ -148,7 +149,8 @@ pub(crate) fn list_path(
basis_cache: &mut BasisCache, basis_cache: &mut BasisCache,
) -> Result<(), crate::PddbRetcode> { ) -> Result<(), crate::PddbRetcode> {
// Convert the memory to a Senres buffer // Convert the memory to a Senres buffer
let mut backing = senres::Message::from_mut_slice(mem.buf.as_slice_mut()) // Safety: the memory message must be aligned, and we test for validity here
let mut backing = unsafe { senres::Message::from_mut_slice(mem.buf.as_slice_mut()) }
.or(Err(crate::PddbRetcode::InternalError))?; .or(Err(crate::PddbRetcode::InternalError))?;
let reader = backing let reader = backing
@ -242,7 +244,8 @@ pub(crate) fn list_basis(
let basis_list = basis_cache.basis_list(); let basis_list = basis_cache.basis_list();
// Convert the memory to a Senres buffer // Convert the memory to a Senres buffer
let mut backing = senres::Message::from_mut_slice(mem.buf.as_slice_mut()) // Safety: the memory message must be aligned, and we test for validity here
let mut backing = unsafe { senres::Message::from_mut_slice(mem.buf.as_slice_mut()) }
.or(Err(crate::PddbRetcode::InternalError))?; .or(Err(crate::PddbRetcode::InternalError))?;
{ {
@ -273,7 +276,8 @@ pub(crate) fn open_key(
fds: &mut Vec<Option<crate::FileHandle>>, fds: &mut Vec<Option<crate::FileHandle>>,
) -> Result<(), crate::PddbRetcode> { ) -> Result<(), crate::PddbRetcode> {
// Convert the memory to a Senres buffer // Convert the memory to a Senres buffer
let mut backing = senres::Message::from_mut_slice(mem.buf.as_slice_mut()) // Safety: the memory message must be aligned, and we test for validity here
let mut backing = unsafe { senres::Message::from_mut_slice(mem.buf.as_slice_mut()) }
.or(Err(crate::PddbRetcode::InternalError))?; .or(Err(crate::PddbRetcode::InternalError))?;
let create_file: bool; let create_file: bool;
@ -549,7 +553,8 @@ pub(crate) fn delete_key(
all_fds: &mut std::collections::HashMap<Option<xous::PID>, Vec<Option<FileHandle>>>, all_fds: &mut std::collections::HashMap<Option<xous::PID>, Vec<Option<FileHandle>>>,
) -> Result<(), crate::PddbRetcode> { ) -> Result<(), crate::PddbRetcode> {
// Convert the memory to a Senres buffer // Convert the memory to a Senres buffer
let backing = senres::Message::from_mut_slice(mem.buf.as_slice_mut()) // Safety: the memory message must be aligned, and we test for validity here
let backing = unsafe { senres::Message::from_mut_slice(mem.buf.as_slice_mut()) }
.or(Err(crate::PddbRetcode::InternalError))?; .or(Err(crate::PddbRetcode::InternalError))?;
let reader = backing let reader = backing
@ -618,12 +623,13 @@ pub(crate) fn write_key(
file.key file.key
); );
let length_to_write = mem.valid.map(|v| v.get()).unwrap_or_default(); let length_to_write = mem.valid.map(|v| v.get()).unwrap_or_default();
// Safety: all `u8` values are valid
if basis_cache if basis_cache
.key_update( .key_update(
pddb_os, pddb_os,
&file.dict, &file.dict,
&file.key, &file.key,
&mem.buf.as_slice_mut()[0..length_to_write], unsafe { &mem.buf.as_slice_mut()[0..length_to_write] },
// &mut pbuf.data[..pbuf.len as usize], // &mut pbuf.data[..pbuf.len as usize],
Some(file.offset as usize), Some(file.offset as usize),
file.alloc_hint, file.alloc_hint,
@ -712,12 +718,13 @@ pub(crate) fn read_key(
file.basis.as_ref().unwrap_or(basis), file.basis.as_ref().unwrap_or(basis),
file.key file.key
); );
// Safety: all u8 values are valid
if let Ok(readlen) = basis_cache if let Ok(readlen) = basis_cache
.key_read( .key_read(
pddb_os, pddb_os,
&file.dict, &file.dict,
&file.key, &file.key,
&mut mem.buf.as_slice_mut()[0..mem.valid.map(|v| v.get()).unwrap_or_default()], unsafe { &mut mem.buf.as_slice_mut()[0..mem.valid.map(|v| v.get()).unwrap_or_default()] },
Some(file.offset as usize), Some(file.offset as usize),
// this is a bit inefficient because if a specific basis is specified *and* the key does not exist, // this is a bit inefficient because if a specific basis is specified *and* the key does not exist,
// it'll retry the same basis for a number of times equal to the number of bases open. // it'll retry the same basis for a number of times equal to the number of bases open.
@ -756,7 +763,8 @@ pub(crate) fn list_dict(
pddb_os: &mut PddbOs, pddb_os: &mut PddbOs,
basis_cache: &mut BasisCache, basis_cache: &mut BasisCache,
) -> Result<(), crate::PddbRetcode> { ) -> Result<(), crate::PddbRetcode> {
let mut backing = senres::Message::from_mut_slice(mem.buf.as_slice_mut()) // Safety: the memory message must be aligned, and we test for validity here
let mut backing = unsafe { senres::Message::from_mut_slice(mem.buf.as_slice_mut()) }
.or(Err(crate::PddbRetcode::InternalError))?; .or(Err(crate::PddbRetcode::InternalError))?;
let bname; let bname;
{ {
@ -786,7 +794,8 @@ pub(crate) fn list_key(
pddb_os: &mut PddbOs, pddb_os: &mut PddbOs,
basis_cache: &mut BasisCache, basis_cache: &mut BasisCache,
) -> Result<(), crate::PddbRetcode> { ) -> Result<(), crate::PddbRetcode> {
let mut backing = senres::Message::from_mut_slice(mem.buf.as_slice_mut()) // Safety: the memory message must be aligned, and we test for validity here
let mut backing = unsafe { senres::Message::from_mut_slice(mem.buf.as_slice_mut()) }
.or(Err(crate::PddbRetcode::InternalError))?; .or(Err(crate::PddbRetcode::InternalError))?;
let bname; let bname;
let key; let key;
@ -832,7 +841,8 @@ pub(crate) fn delete_dict(
pddb_os: &mut PddbOs, pddb_os: &mut PddbOs,
basis_cache: &mut BasisCache, basis_cache: &mut BasisCache,
) -> Result<(), crate::PddbRetcode> { ) -> Result<(), crate::PddbRetcode> {
let backing = senres::Message::from_mut_slice(mem.buf.as_slice_mut()) // Safety: the memory message must be aligned, and we test for validity here
let backing = unsafe { senres::Message::from_mut_slice(mem.buf.as_slice_mut()) }
.or(Err(crate::PddbRetcode::InternalError))?; .or(Err(crate::PddbRetcode::InternalError))?;
let reader = backing let reader = backing
.reader(*b"RmDQ") .reader(*b"RmDQ")
@ -876,7 +886,8 @@ pub(crate) fn create_dict(
pddb_os: &mut PddbOs, pddb_os: &mut PddbOs,
basis_cache: &mut BasisCache, basis_cache: &mut BasisCache,
) -> Result<(), crate::PddbRetcode> { ) -> Result<(), crate::PddbRetcode> {
let backing = senres::Message::from_mut_slice(mem.buf.as_slice_mut()) // Safety: the memory message must be aligned, and we test for validity here
let backing = unsafe { senres::Message::from_mut_slice(mem.buf.as_slice_mut()) }
.or(Err(crate::PddbRetcode::InternalError))?; .or(Err(crate::PddbRetcode::InternalError))?;
let reader = backing let reader = backing
.reader(*b"NuDQ") .reader(*b"NuDQ")

View file

@ -812,7 +812,8 @@ fn wrapped_main() -> ! {
if let Some(mem) = msg.body.memory_message_mut() { if let Some(mem) = msg.body.memory_message_mut() {
mem.offset = None; mem.offset = None;
if let Some(name) = basis_cache.basis_latest() { if let Some(name) = basis_cache.basis_latest() {
for (src, dest) in name.as_bytes().iter().zip(mem.buf.as_slice_mut().iter_mut()) { // Safety: `u8` contains no undefined values
for (src, dest) in unsafe { name.as_bytes().iter().zip(mem.buf.as_slice_mut().iter_mut()) } {
*dest = *src; *dest = *src;
} }
mem.offset = xous::MemorySize::new(name.len().min(mem.buf.len())); mem.offset = xous::MemorySize::new(name.len().min(mem.buf.len()));

View file

@ -227,10 +227,10 @@ impl<'a> RootKeys {
xous::MemoryFlags::R | xous::MemoryFlags::W, xous::MemoryFlags::R | xous::MemoryFlags::W,
).expect("couldn't map sensitive data page"); ).expect("couldn't map sensitive data page");
// make sure the caches start out as zeros // make sure the caches start out as zeros
for w in pass_cache.as_slice_mut::<u32>().iter_mut() { for w in unsafe { pass_cache.as_slice_mut::<u32>().iter_mut() } {
*w = 0; *w = 0;
} }
for w in sensitive_data.as_slice_mut::<u32>().iter_mut() { for w in unsafe { sensitive_data.as_slice_mut::<u32>().iter_mut() } {
*w = 0; *w = 0;
} }
@ -282,19 +282,19 @@ impl<'a> RootKeys {
keys keys
} }
pub fn gateware(&self) -> &[u8] { pub fn gateware(&self) -> &[u8] {
self.gateware_mr.as_slice::<u8>() unsafe { self.gateware_mr.as_slice::<u8>() }
} }
pub fn gateware_base(&self) -> u32 { self.gateware_base } pub fn gateware_base(&self) -> u32 { self.gateware_base }
pub fn staging(&self) -> &[u8] { pub fn staging(&self) -> &[u8] {
self.staging_mr.as_slice::<u8>() unsafe { self.staging_mr.as_slice::<u8>() }
} }
pub fn staging_base(&self) -> u32 { self.staging_base } pub fn staging_base(&self) -> u32 { self.staging_base }
pub fn loader_code(&self) -> &[u8] { pub fn loader_code(&self) -> &[u8] {
self.loader_code_mr.as_slice::<u8>() unsafe { self.loader_code_mr.as_slice::<u8>() }
} }
pub fn loader_base(&self) -> u32 { self.loader_code_base } pub fn loader_base(&self) -> u32 { self.loader_code_base }
pub fn kernel(&self) -> &[u8] { pub fn kernel(&self) -> &[u8] {
self.kernel_mr.as_slice::<u8>() unsafe { self.kernel_mr.as_slice::<u8>() }
} }
pub fn kernel_base(&self) -> u32 { self.kernel_base } pub fn kernel_base(&self) -> u32 { self.kernel_base }
@ -634,13 +634,13 @@ impl<'a> RootKeys {
core::sync::atomic::compiler_fence(core::sync::atomic::Ordering::SeqCst); core::sync::atomic::compiler_fence(core::sync::atomic::Ordering::SeqCst);
} }
pub fn purge_sensitive_data(&mut self) { pub fn purge_sensitive_data(&mut self) {
for d in self.sensitive_data.borrow_mut().as_slice_mut::<u32>().iter_mut() { for d in unsafe { self.sensitive_data.borrow_mut().as_slice_mut::<u32>().iter_mut() } {
*d = 0; *d = 0;
} }
core::sync::atomic::compiler_fence(core::sync::atomic::Ordering::SeqCst); core::sync::atomic::compiler_fence(core::sync::atomic::Ordering::SeqCst);
} }
fn populate_sensitive_data(&mut self) { fn populate_sensitive_data(&mut self) {
for (addr, d) in self.sensitive_data.borrow_mut().as_slice_mut::<u32>().iter_mut().enumerate() { for (addr, d) in unsafe { self.sensitive_data.borrow_mut().as_slice_mut::<u32>().iter_mut().enumerate() } {
if addr > 255 { if addr > 255 {
break; break;
} }
@ -664,13 +664,13 @@ impl<'a> RootKeys {
// now encrypt the key, and store it into the sensitive_data for access later on by the patching routine // now encrypt the key, and store it into the sensitive_data for access later on by the patching routine
if self.is_initialized() { if self.is_initialized() {
for (dst, (key, pw)) in for (dst, (key, pw)) in
self.sensitive_data.borrow_mut().as_slice_mut::<u32>()[KeyRomLocs::FPGA_KEY as usize .. KeyRomLocs::FPGA_KEY as usize + 8].iter_mut().zip( unsafe { self.sensitive_data.borrow_mut().as_slice_mut::<u32>()[KeyRomLocs::FPGA_KEY as usize .. KeyRomLocs::FPGA_KEY as usize + 8].iter_mut() }.zip(
pcache.fpga_key.chunks(4).into_iter().zip(pcache.hashed_update_pw.chunks(4).into_iter())) { pcache.fpga_key.chunks(4).into_iter().zip(pcache.hashed_update_pw.chunks(4).into_iter())) {
*dst = u32::from_be_bytes(key[0..4].try_into().unwrap()) ^ u32::from_be_bytes(pw[0..4].try_into().unwrap()); *dst = u32::from_be_bytes(key[0..4].try_into().unwrap()) ^ u32::from_be_bytes(pw[0..4].try_into().unwrap());
} }
} else { } else {
for (dst, key) in for (dst, key) in
self.sensitive_data.borrow_mut().as_slice_mut::<u32>()[KeyRomLocs::FPGA_KEY as usize .. KeyRomLocs::FPGA_KEY as usize + 8].iter_mut().zip( unsafe { self.sensitive_data.borrow_mut().as_slice_mut::<u32>()[KeyRomLocs::FPGA_KEY as usize .. KeyRomLocs::FPGA_KEY as usize + 8].iter_mut() }.zip(
pcache.fpga_key.chunks(4).into_iter()) { pcache.fpga_key.chunks(4).into_iter()) {
*dst = u32::from_be_bytes(key[0..4].try_into().unwrap()); *dst = u32::from_be_bytes(key[0..4].try_into().unwrap());
} }
@ -830,7 +830,7 @@ impl<'a> RootKeys {
fn read_staged_key_256(&mut self, index: u8) -> [u8; 32] { fn read_staged_key_256(&mut self, index: u8) -> [u8; 32] {
let mut key: [u8; 32] = [0; 32]; let mut key: [u8; 32] = [0; 32];
for (addr, word) in key.chunks_mut(4).into_iter().enumerate() { for (addr, word) in key.chunks_mut(4).into_iter().enumerate() {
let keyword = self.sensitive_data.borrow().as_slice::<u32>()[index as usize + addr]; let keyword = unsafe { self.sensitive_data.borrow().as_slice::<u32>()[index as usize + addr] };
for (&byte, dst) in keyword.to_be_bytes().iter().zip(word.iter_mut()) { for (&byte, dst) in keyword.to_be_bytes().iter().zip(word.iter_mut()) {
*dst = byte; *dst = byte;
} }
@ -847,7 +847,7 @@ impl<'a> RootKeys {
// we're not initialized, use the salt that should already be in the staging area // we're not initialized, use the salt that should already be in the staging area
let mut key: [u8; 16] = [0; 16]; let mut key: [u8; 16] = [0; 16];
for (word, &keyword) in key.chunks_mut(4).into_iter() for (word, &keyword) in key.chunks_mut(4).into_iter()
.zip(self.sensitive_data.borrow_mut().as_slice::<u32>() // get the sensitive_data as a slice &mut[u32] .zip(unsafe { self.sensitive_data.borrow_mut().as_slice::<u32>() } // get the sensitive_data as a slice &mut[u32]
[KeyRomLocs::PEPPER as usize..KeyRomLocs::PEPPER as usize + 128/(size_of::<u32>()*8)].iter()) { [KeyRomLocs::PEPPER as usize..KeyRomLocs::PEPPER as usize + 128/(size_of::<u32>()*8)].iter()) {
for (&byte, dst) in keyword.to_be_bytes().iter().zip(word.iter_mut()) { for (&byte, dst) in keyword.to_be_bytes().iter().zip(word.iter_mut()) {
*dst = byte; *dst = byte;
@ -904,11 +904,11 @@ impl<'a> RootKeys {
// make a copy of the KEYROM to hold the new mods, in the sensitive data area // make a copy of the KEYROM to hold the new mods, in the sensitive data area
for addr in 0..256 { for addr in 0..256 {
self.keyrom.wfo(utra::keyrom::ADDRESS_ADDRESS, addr); self.keyrom.wfo(utra::keyrom::ADDRESS_ADDRESS, addr);
self.sensitive_data.borrow_mut().as_slice_mut::<u32>()[addr as usize] = self.keyrom.rf(utra::keyrom::DATA_DATA); unsafe { self.sensitive_data.borrow_mut().as_slice_mut::<u32>()[addr as usize] = self.keyrom.rf(utra::keyrom::DATA_DATA) };
} }
// provision the pepper // provision the pepper
for keyword in self.sensitive_data.borrow_mut().as_slice_mut::<u32>() for keyword in unsafe { self.sensitive_data.borrow_mut().as_slice_mut::<u32>() }
[KeyRomLocs::PEPPER as usize..KeyRomLocs::PEPPER as usize + 128/(size_of::<u32>()*8)].iter_mut() { [KeyRomLocs::PEPPER as usize..KeyRomLocs::PEPPER as usize + 128/(size_of::<u32>()*8)].iter_mut() {
*keyword = self.trng.get_u32().expect("couldn't get random number"); *keyword = self.trng.get_u32().expect("couldn't get random number");
} }
@ -919,8 +919,8 @@ impl<'a> RootKeys {
self.susres.set_suspendable(false).expect("couldn't block suspend/resume"); self.susres.set_suspendable(false).expect("couldn't block suspend/resume");
// populate the staging area, in particular we are interested in the "pepper" so passwords work correctly. // populate the staging area, in particular we are interested in the "pepper" so passwords work correctly.
self.sensitive_data.borrow_mut().as_slice_mut::<u32>()[..256] unsafe { self.sensitive_data.borrow_mut().as_slice_mut::<u32>()[..256]
.copy_from_slice(&rom.0); .copy_from_slice(&rom.0) };
let pcache: &mut PasswordCache = unsafe{&mut *(self.pass_cache.as_mut_ptr() as *mut PasswordCache)}; let pcache: &mut PasswordCache = unsafe{&mut *(self.pass_cache.as_mut_ptr() as *mut PasswordCache)};
// copy the plaintext FPGA key to the pcache // copy the plaintext FPGA key to the pcache
@ -928,8 +928,8 @@ impl<'a> RootKeys {
pcache.fpga_key_valid = 1; pcache.fpga_key_valid = 1;
// stage the plaintext FPGA key into the keyrom area for encryption by the key_init routine. // stage the plaintext FPGA key into the keyrom area for encryption by the key_init routine.
self.sensitive_data.borrow_mut().as_slice_mut::<u8>()[KeyRomLocs::FPGA_KEY as usize..KeyRomLocs::FPGA_KEY as usize + 32] unsafe { self.sensitive_data.borrow_mut().as_slice_mut::<u8>()[KeyRomLocs::FPGA_KEY as usize..KeyRomLocs::FPGA_KEY as usize + 32]
.copy_from_slice(&key.0); .copy_from_slice(&key.0) };
self.restore_running = true; self.restore_running = true;
} }
@ -1011,7 +1011,7 @@ impl<'a> RootKeys {
// get access to the pcache and generate a keypair // get access to the pcache and generate a keypair
let pcache: &mut PasswordCache = unsafe{&mut *(self.pass_cache.as_mut_ptr() as *mut PasswordCache)}; let pcache: &mut PasswordCache = unsafe{&mut *(self.pass_cache.as_mut_ptr() as *mut PasswordCache)};
// initialize the global rollback constant to 0 // initialize the global rollback constant to 0
self.sensitive_data.borrow_mut().as_slice_mut::<u32>()[KeyRomLocs::GLOBAL_ROLLBACK as usize] = 0; unsafe { self.sensitive_data.borrow_mut().as_slice_mut::<u32>()[KeyRomLocs::GLOBAL_ROLLBACK as usize] = 0 };
let mut root_sk = [0u8; ed25519_dalek::SECRET_KEY_LENGTH]; let mut root_sk = [0u8; ed25519_dalek::SECRET_KEY_LENGTH];
self.trng.fill_bytes(&mut root_sk); self.trng.fill_bytes(&mut root_sk);
#[cfg(feature = "hazardous-debug")] #[cfg(feature = "hazardous-debug")]
@ -1067,7 +1067,7 @@ impl<'a> RootKeys {
pcache.fpga_key_valid = 1; pcache.fpga_key_valid = 1;
// now encrypt it in the staging area // now encrypt it in the staging area
for (word, hashed_pass) in self.sensitive_data.borrow_mut().as_slice_mut::<u32>()[KeyRomLocs::FPGA_KEY as usize..KeyRomLocs::FPGA_KEY as usize + 256/(size_of::<u32>()*8)].iter_mut() for (word, hashed_pass) in unsafe { self.sensitive_data.borrow_mut().as_slice_mut::<u32>()[KeyRomLocs::FPGA_KEY as usize..KeyRomLocs::FPGA_KEY as usize + 256/(size_of::<u32>()*8)].iter_mut() }
.zip(pcache.hashed_update_pw.chunks(4).into_iter()) { .zip(pcache.hashed_update_pw.chunks(4).into_iter()) {
*word = *word ^ u32::from_be_bytes(hashed_pass.try_into().unwrap()); *word = *word ^ u32::from_be_bytes(hashed_pass.try_into().unwrap());
} }
@ -1088,7 +1088,7 @@ impl<'a> RootKeys {
// pub key is easy, no need to encrypt // pub key is easy, no need to encrypt
let public_key: [u8; ed25519_dalek::PUBLIC_KEY_LENGTH] = keypair.public.to_bytes(); let public_key: [u8; ed25519_dalek::PUBLIC_KEY_LENGTH] = keypair.public.to_bytes();
for (src, dst) in public_key.chunks(4).into_iter() for (src, dst) in public_key.chunks(4).into_iter()
.zip(self.sensitive_data.borrow_mut().as_slice_mut::<u32>()[KeyRomLocs::SELFSIGN_PUBKEY as usize..KeyRomLocs::SELFSIGN_PUBKEY as usize + 256/(size_of::<u32>()*8)].iter_mut()) { .zip(unsafe { self.sensitive_data.borrow_mut().as_slice_mut::<u32>()[KeyRomLocs::SELFSIGN_PUBKEY as usize..KeyRomLocs::SELFSIGN_PUBKEY as usize + 256/(size_of::<u32>()*8)].iter_mut() }) {
*dst = u32::from_be_bytes(src.try_into().unwrap()) *dst = u32::from_be_bytes(src.try_into().unwrap())
} }
log::debug!("public key as computed: {:x?}", public_key); log::debug!("public key as computed: {:x?}", public_key);
@ -1110,7 +1110,7 @@ impl<'a> RootKeys {
// store the private key to the keyrom staging area // store the private key to the keyrom staging area
for (src, dst) in private_key_enc.chunks(4).into_iter() for (src, dst) in private_key_enc.chunks(4).into_iter()
.zip(self.sensitive_data.borrow_mut().as_slice_mut::<u32>()[KeyRomLocs::SELFSIGN_PRIVKEY as usize..KeyRomLocs::SELFSIGN_PRIVKEY as usize + 256/(size_of::<u32>()*8)].iter_mut()) { .zip(unsafe { self.sensitive_data.borrow_mut().as_slice_mut::<u32>()[KeyRomLocs::SELFSIGN_PRIVKEY as usize..KeyRomLocs::SELFSIGN_PRIVKEY as usize + 256/(size_of::<u32>()*8)].iter_mut() }) {
*dst = u32::from_be_bytes(src.try_into().unwrap()) *dst = u32::from_be_bytes(src.try_into().unwrap())
} }
#[cfg(feature = "hazardous-debug")] #[cfg(feature = "hazardous-debug")]
@ -1135,7 +1135,7 @@ impl<'a> RootKeys {
// store the boot key to the keyrom staging area // store the boot key to the keyrom staging area
for (src, dst) in boot_key_enc.chunks(4).into_iter() for (src, dst) in boot_key_enc.chunks(4).into_iter()
.zip(self.sensitive_data.borrow_mut().as_slice_mut::<u32>()[KeyRomLocs::USER_KEY as usize..KeyRomLocs::USER_KEY as usize + 256/(size_of::<u32>()*8)].iter_mut()) { .zip(unsafe { self.sensitive_data.borrow_mut().as_slice_mut::<u32>()[KeyRomLocs::USER_KEY as usize..KeyRomLocs::USER_KEY as usize + 256/(size_of::<u32>()*8)].iter_mut() }) {
*dst = u32::from_be_bytes(src.try_into().unwrap()) *dst = u32::from_be_bytes(src.try_into().unwrap())
} }
@ -1152,7 +1152,7 @@ impl<'a> RootKeys {
log::debug!("loader len: {} bytes", loader_len); log::debug!("loader len: {} bytes", loader_len);
// set the "init" bit in the staging area // set the "init" bit in the staging area
self.sensitive_data.borrow_mut().as_slice_mut::<u32>()[KeyRomLocs::CONFIG as usize] |= keyrom_config::INITIALIZED.ms(1); unsafe { self.sensitive_data.borrow_mut().as_slice_mut::<u32>()[KeyRomLocs::CONFIG as usize] |= keyrom_config::INITIALIZED.ms(1) };
#[cfg(feature = "hazardous-debug")] #[cfg(feature = "hazardous-debug")]
{ {
@ -1354,7 +1354,7 @@ impl<'a> RootKeys {
old_key.copy_from_slice(&pcache.fpga_key); old_key.copy_from_slice(&pcache.fpga_key);
// now encrypt the FPGA key for the Keyrom in-place to the provided password // now encrypt the FPGA key for the Keyrom in-place to the provided password
for (word, hashed_pass) in self.sensitive_data.borrow_mut().as_slice_mut::<u32>()[KeyRomLocs::FPGA_KEY as usize..KeyRomLocs::FPGA_KEY as usize + 256/(size_of::<u32>()*8)].iter_mut() for (word, hashed_pass) in unsafe { self.sensitive_data.borrow_mut().as_slice_mut::<u32>()[KeyRomLocs::FPGA_KEY as usize..KeyRomLocs::FPGA_KEY as usize + 256/(size_of::<u32>()*8)].iter_mut() }
.zip(pcache.hashed_update_pw.chunks(4).into_iter()) { .zip(pcache.hashed_update_pw.chunks(4).into_iter()) {
*word = *word ^ u32::from_be_bytes(hashed_pass.try_into().unwrap()); *word = *word ^ u32::from_be_bytes(hashed_pass.try_into().unwrap());
} }
@ -2030,7 +2030,7 @@ impl<'a> RootKeys {
// wrap the patch call with a range check, because the patch lookup search is pretty expensive // wrap the patch call with a range check, because the patch lookup search is pretty expensive
if self.patch_in_range(src_oracle, from, from + spinor::SPINOR_ERASE_SIZE as u32) { if self.patch_in_range(src_oracle, from, from + spinor::SPINOR_ERASE_SIZE as u32) {
dummy_consume ^= self.patch_sector(src_oracle, from, &mut pt_sector, &self.sensitive_data.borrow_mut().as_slice_mut::<u32>()[0..256]); dummy_consume ^= self.patch_sector(src_oracle, from, &mut pt_sector, unsafe { &self.sensitive_data.borrow_mut().as_slice_mut::<u32>()[0..256] });
} }
let hash_len = if bytes_hashed + decrypt_len < hash_stop { let hash_len = if bytes_hashed + decrypt_len < hash_stop {

View file

@ -403,7 +403,7 @@ impl<'a> ShellCmdApi<'a> for Test {
).expect("couldn't allocate record buffer")); ).expect("couldn't allocate record buffer"));
} }
if let Some(recbuf) = self.recbuf { if let Some(recbuf) = self.recbuf {
let recslice = recbuf.as_slice::<u8>(); let recslice = unsafe { recbuf.as_slice::<u8>() };
const BUFLEN: usize = 512; const BUFLEN: usize = 512;
// serialize and send audio as b64 encoded data // serialize and send audio as b64 encoded data
for (i, sample) in recslice[recslice.len()-4096 * size_of::<u32>()..].chunks_exact(BUFLEN).enumerate() { for (i, sample) in recslice[recslice.len()-4096 * size_of::<u32>()..].chunks_exact(BUFLEN).enumerate() {
@ -822,7 +822,7 @@ impl<'a> ShellCmdApi<'a> for Test {
).expect("couldn't allocate record buffer")); ).expect("couldn't allocate record buffer"));
} }
if let Some(mut recbuf) = self.recbuf { if let Some(mut recbuf) = self.recbuf {
let rec_samples = recbuf.as_slice_mut::<u32>(); let rec_samples = unsafe { recbuf.as_slice_mut::<u32>() };
let rec_len = rec_samples.len(); let rec_len = rec_samples.len();
loop { loop {
if let Some(frame) = frames.dq_frame() { if let Some(frame) = frames.dq_frame() {

View file

@ -80,7 +80,7 @@ pub(crate) fn ecupdate_thread(sid: xous::SID) {
xous::MemoryFlags::R | xous::MemoryFlags::W, xous::MemoryFlags::R | xous::MemoryFlags::W,
).expect("couldn't map EC firmware package memory range"); ).expect("couldn't map EC firmware package memory range");
#[cfg(not(target_os = "xous"))] #[cfg(not(target_os = "xous"))]
for d in ec_package.as_slice_mut::<u8>().iter_mut() { *d = 0xFF } // simulate blank flash for d in unsafe { ec_package.as_slice_mut::<u8>().iter_mut() } { *d = 0xFF } // simulate blank flash
#[cfg(not(target_os = "xous"))] #[cfg(not(target_os = "xous"))]
let mut wf_package = xous::syscall::map_memory( let mut wf_package = xous::syscall::map_memory(
None, None,
@ -89,7 +89,7 @@ pub(crate) fn ecupdate_thread(sid: xous::SID) {
xous::MemoryFlags::R | xous::MemoryFlags::W, xous::MemoryFlags::R | xous::MemoryFlags::W,
).expect("couldn't map EC wf200 package memory range"); ).expect("couldn't map EC wf200 package memory range");
#[cfg(not(target_os = "xous"))] #[cfg(not(target_os = "xous"))]
for d in wf_package.as_slice_mut::<u8>().iter_mut() { *d = 0xFF } for d in unsafe { wf_package.as_slice_mut::<u8>().iter_mut() } { *d = 0xFF }
loop { loop {
let msg = xous::receive_message(sid).unwrap(); let msg = xous::receive_message(sid).unwrap();

View file

@ -246,7 +246,7 @@ fn read_next_syscall_result(
memory_message.buf, memory_message.buf,
) )
.expect("couldn't allocate range"); .expect("couldn't allocate range");
if let Err(e) = stream.read_exact(memory_message.buf.as_slice_mut()) { if let Err(e) = stream.read_exact(unsafe { memory_message.buf.as_slice_mut() }) {
eprintln!("Server shut down: {}", e); eprintln!("Server shut down: {}", e);
std::process::exit(0); std::process::exit(0);
} }

View file

@ -151,7 +151,7 @@ pub fn create_process_pre(args: &ProcessArgs) -> core::result::Result<ProcessIni
spawn_stub_rounded, spawn_stub_rounded,
crate::MemoryFlags::R | crate::MemoryFlags::W | crate::MemoryFlags::X, crate::MemoryFlags::R | crate::MemoryFlags::W | crate::MemoryFlags::X,
)?; )?;
for (dest, src) in spawn_memory.as_slice_mut().iter_mut().zip(args.stub) { for (dest, src) in unsafe { spawn_memory.as_slice_mut().iter_mut().zip(args.stub) } {
*dest = *src; *dest = *src;
} }
Ok(ProcessInit { Ok(ProcessInit {

View file

@ -73,6 +73,9 @@ pub use exceptions::*;
pub mod memoryflags; pub mod memoryflags;
pub use memoryflags::*; pub use memoryflags::*;
pub mod memoryrange;
pub use memoryrange::*;
pub mod messages; pub mod messages;
pub use messages::*; pub use messages::*;
@ -155,12 +158,6 @@ pub type TID = usize;
/// Equivalent to a RISC-V Hart ID /// Equivalent to a RISC-V Hart ID
pub type CpuID = usize; pub type CpuID = usize;
#[derive(Debug, PartialEq, Copy, Clone)]
pub struct MemoryRange {
pub(crate) addr: MemoryAddress,
pub(crate) size: MemorySize,
}
pub fn pid_from_usize(src: usize) -> core::result::Result<PID, Error> { pub fn pid_from_usize(src: usize) -> core::result::Result<PID, Error> {
if src > u8::MAX as _ { if src > u8::MAX as _ {
return Err(Error::InvalidPID); return Err(Error::InvalidPID);
@ -276,75 +273,6 @@ pub struct Context {
pid: PID, pid: PID,
} }
impl MemoryRange {
/// # Safety
///
/// This allows for creating a `MemoryRange` from any arbitrary pointer,
/// so it is imperitive that this only be used to point to valid, page-aligned
/// ranges.
pub unsafe fn new(addr: usize, size: usize) -> core::result::Result<MemoryRange, Error> {
Ok(MemoryRange {
addr: MemoryAddress::new(addr).ok_or(Error::BadAddress)?,
size: MemorySize::new(size).ok_or(Error::BadAddress)?,
})
}
#[deprecated(since = "0.8.4", note = "Please use `new(addr, size)` instead")]
pub fn from_parts(addr: MemoryAddress, size: MemorySize) -> MemoryRange {
MemoryRange { addr, size }
}
pub fn len(&self) -> usize {
self.size.get()
}
pub fn is_empty(&self) -> bool {
self.size.get() > 0
}
pub fn as_ptr(&self) -> *const u8 {
self.addr.get() as *const u8
}
pub fn as_mut_ptr(&self) -> *mut u8 {
self.addr.get() as *mut u8
}
/// Return this memory as a slice of values. The resulting slice
/// will cover the maximum number of elements given the size of `T`.
/// For example, if the allocation is 4096 bytes, then the resulting
/// `&[u8]` would have 4096 elements, `&[u16]` would have 2048, and
/// `&[u32]` would have 1024. Values are rounded down.
pub fn as_slice<T>(&self) -> &[T] {
// This is safe because the pointer and length are guaranteed to
// be valid, as long as the user hasn't already called `as_ptr()`
// and done something unsound with the resulting pointer.
unsafe {
core::slice::from_raw_parts(
self.as_ptr() as *const T,
self.len() / core::mem::size_of::<T>(),
)
}
}
/// Return this memory as a slice of mutable values. The resulting slice
/// will cover the maximum number of elements given the size of `T`.
/// For example, if the allocation is 4096 bytes, then the resulting
/// `&[u8]` would have 4096 elements, `&[u16]` would have 2048, and
/// `&[u32]` would have 1024. Values are rounded down.
pub fn as_slice_mut<T>(&mut self) -> &mut [T] {
// This is safe because the pointer and length are guaranteed to
// be valid, as long as the user hasn't already called `as_ptr()`
// and done something unsound with the resulting pointer.
unsafe {
core::slice::from_raw_parts_mut(
self.as_mut_ptr() as *mut T,
self.len() / core::mem::size_of::<T>(),
)
}
}
}
/// Which memory region the operation should affect. /// Which memory region the operation should affect.
#[derive(Debug, Copy, Clone, PartialEq)] #[derive(Debug, Copy, Clone, PartialEq)]
pub enum MemoryType { pub enum MemoryType {

View file

@ -0,0 +1,83 @@
use crate::definitions::{Error, MemoryAddress, MemorySize};
#[derive(Debug, PartialEq, Copy, Clone)]
pub struct MemoryRange {
pub(crate) addr: MemoryAddress,
pub(crate) size: MemorySize,
}
impl MemoryRange {
/// # Safety
///
/// This allows for creating a `MemoryRange` from any arbitrary pointer,
/// so it is imperitive that this only be used to point to valid, page-aligned
/// ranges.
pub unsafe fn new(addr: usize, size: usize) -> core::result::Result<MemoryRange, Error> {
Ok(MemoryRange {
addr: MemoryAddress::new(addr).ok_or(Error::BadAddress)?,
size: MemorySize::new(size).ok_or(Error::BadAddress)?,
})
}
pub fn len(&self) -> usize {
self.size.get()
}
pub fn is_empty(&self) -> bool {
self.size.get() > 0
}
pub fn as_ptr(&self) -> *const u8 {
self.addr.get() as *const u8
}
pub fn as_mut_ptr(&self) -> *mut u8 {
self.addr.get() as *mut u8
}
/// Return this memory as a slice of values. The resulting slice
/// will cover the maximum number of elements given the size of `T`.
/// For example, if the allocation is 4096 bytes, then the resulting
/// `&[u8]` would have 4096 elements, `&[u16]` would have 2048, and
/// `&[u32]` would have 1024. Values are rounded down.
///
/// # Safety
///
/// This is safe as long as the underlying memory is representable
/// on the target system. For example, you must ensure that `bool`
/// slices contain only `0` or `1`.
pub unsafe fn as_slice<T>(&self) -> &[T] {
// This is safe because the pointer and length are guaranteed to
// be valid, as long as the user hasn't already called `as_ptr()`
// and done something unsound with the resulting pointer.
unsafe {
core::slice::from_raw_parts(
self.as_ptr() as *const T,
self.len() / core::mem::size_of::<T>(),
)
}
}
/// Return this memory as a slice of mutable values. The resulting slice
/// will cover the maximum number of elements given the size of `T`.
/// For example, if the allocation is 4096 bytes, then the resulting
/// `&[u8]` would have 4096 elements, `&[u16]` would have 2048, and
/// `&[u32]` would have 1024. Values are rounded down.
///
/// # Safety
///
/// This is safe as long as the underlying memory is representable
/// on the target system. For example, you must ensure that `bool`
/// slices contain only `0` or `1`.
pub unsafe fn as_slice_mut<T>(&mut self) -> &mut [T] {
// This is safe because the pointer and length are guaranteed to
// be valid, as long as the user hasn't already called `as_ptr()`
// and done something unsound with the resulting pointer.
unsafe {
core::slice::from_raw_parts_mut(
self.as_mut_ptr() as *mut T,
self.len() / core::mem::size_of::<T>(),
)
}
}
}