firmware: use ? instead of try! everywhere.

This commit is contained in:
whitequark 2017-01-31 22:18:59 +00:00
parent ee1b2fa3ea
commit 680a7067a8
10 changed files with 177 additions and 177 deletions

View File

@ -156,7 +156,7 @@ extern fn send_async_rpc(service: u32, tag: *const u8, data: *const *const ()) {
rpc_queue::enqueue(|mut slice| { rpc_queue::enqueue(|mut slice| {
let length = { let length = {
let mut writer = Cursor::new(&mut slice[4..]); let mut writer = Cursor::new(&mut slice[4..]);
try!(rpc_proto::send_args(&mut writer, service, tag, data)); rpc_proto::send_args(&mut writer, service, tag, data)?;
writer.position() writer.position()
}; };
proto::write_u32(&mut slice, length as u32) proto::write_u32(&mut slice, length as u32)

View File

@ -56,12 +56,12 @@ fn worker(stream: &mut TcpStream) -> io::Result<()> {
}; };
trace!("{:?}", header); trace!("{:?}", header);
try!(header.write_to(stream)); header.write_to(stream)?;
if wraparound { if wraparound {
try!(stream.write_all(&data[pointer..])); stream.write_all(&data[pointer..])?;
try!(stream.write_all(&data[..pointer])); stream.write_all(&data[..pointer])?;
} else { } else {
try!(stream.write_all(&data[..pointer])); stream.write_all(&data[..pointer])?;
} }
Ok(()) Ok(())

View File

@ -12,11 +12,11 @@ pub struct Header {
impl Header { impl Header {
pub fn write_to(&self, writer: &mut Write) -> io::Result<()> { pub fn write_to(&self, writer: &mut Write) -> io::Result<()> {
try!(write_u32(writer, self.sent_bytes)); write_u32(writer, self.sent_bytes)?;
try!(write_u64(writer, self.total_byte_count)); write_u64(writer, self.total_byte_count)?;
try!(write_u8(writer, self.overflow_occurred as u8)); write_u8(writer, self.overflow_occurred as u8)?;
try!(write_u8(writer, self.log_channel)); write_u8(writer, self.log_channel)?;
try!(write_u8(writer, self.dds_onehot_sel as u8)); write_u8(writer, self.dds_onehot_sel as u8)?;
Ok(()) Ok(())
} }
} }

View File

@ -10,8 +10,8 @@ const MONINJ_TTL_OVERRIDE_OE: u8 = 2;
fn worker(socket: &mut UdpSocket) -> io::Result<()> { fn worker(socket: &mut UdpSocket) -> io::Result<()> {
let mut buf = vec![0; 512]; let mut buf = vec![0; 512];
loop { loop {
let (size, addr) = try!(socket.recv_from(&mut buf)); let (size, addr) = socket.recv_from(&mut buf)?;
let request = try!(Request::read_from(&mut io::Cursor::new(&buf[..size]))); let request = Request::read_from(&mut io::Cursor::new(&buf[..size]))?;
trace!("{} -> {:?}", addr, request); trace!("{} -> {:?}", addr, request);
match request { match request {
@ -64,8 +64,8 @@ fn worker(socket: &mut UdpSocket) -> io::Result<()> {
trace!("{} <- {:?}", addr, reply); trace!("{} <- {:?}", addr, reply);
buf.clear(); buf.clear();
try!(reply.write_to(&mut buf)); reply.write_to(&mut buf)?;
try!(socket.send_to(&buf, addr)); socket.send_to(&buf, addr)?;
}, },
Request::TtlSet { channel, mode: TtlMode::Experiment } => { Request::TtlSet { channel, mode: TtlMode::Experiment } => {

View File

@ -11,7 +11,7 @@ pub enum TtlMode {
impl TtlMode { impl TtlMode {
pub fn read_from(reader: &mut Read) -> io::Result<TtlMode> { pub fn read_from(reader: &mut Read) -> io::Result<TtlMode> {
Ok(match try!(read_u8(reader)) { Ok(match read_u8(reader)? {
0 => TtlMode::Experiment, 0 => TtlMode::Experiment,
1 => TtlMode::High, 1 => TtlMode::High,
2 => TtlMode::Low, 2 => TtlMode::Low,
@ -29,11 +29,11 @@ pub enum Request {
impl Request { impl Request {
pub fn read_from(reader: &mut Read) -> io::Result<Request> { pub fn read_from(reader: &mut Read) -> io::Result<Request> {
Ok(match try!(read_u8(reader)) { Ok(match read_u8(reader)? {
1 => Request::Monitor, 1 => Request::Monitor,
2 => Request::TtlSet { 2 => Request::TtlSet {
channel: try!(read_u8(reader)), channel: read_u8(reader)?,
mode: try!(TtlMode::read_from(reader)) mode: TtlMode::read_from(reader)?
}, },
_ => return Err(io::Error::new(io::ErrorKind::InvalidData, "unknown request type")) _ => return Err(io::Error::new(io::ErrorKind::InvalidData, "unknown request type"))
}) })
@ -52,13 +52,13 @@ pub struct Reply<'a> {
impl<'a> Reply<'a> { impl<'a> Reply<'a> {
pub fn write_to(&self, writer: &mut Write) -> io::Result<()> { pub fn write_to(&self, writer: &mut Write) -> io::Result<()> {
try!(write_u64(writer, self.ttl_levels)); write_u64(writer, self.ttl_levels)?;
try!(write_u64(writer, self.ttl_oes)); write_u64(writer, self.ttl_oes)?;
try!(write_u64(writer, self.ttl_overrides)); write_u64(writer, self.ttl_overrides)?;
try!(write_u16(writer, self.dds_rtio_first_channel)); write_u16(writer, self.dds_rtio_first_channel)?;
try!(write_u16(writer, self.dds_channels_per_bus)); write_u16(writer, self.dds_channels_per_bus)?;
for dds_ftw in self.dds_ftws { for dds_ftw in self.dds_ftws {
try!(write_u32(writer, *dds_ftw)); write_u32(writer, *dds_ftw)?;
} }
Ok(()) Ok(())
} }

View File

@ -8,7 +8,7 @@ use byteorder::{ByteOrder, NetworkEndian};
// FIXME: replace these with byteorder core io traits once those are in // FIXME: replace these with byteorder core io traits once those are in
pub fn read_u8(reader: &mut Read) -> io::Result<u8> { pub fn read_u8(reader: &mut Read) -> io::Result<u8> {
let mut bytes = [0; 1]; let mut bytes = [0; 1];
try!(reader.read_exact(&mut bytes)); reader.read_exact(&mut bytes)?;
Ok(bytes[0]) Ok(bytes[0])
} }
@ -19,7 +19,7 @@ pub fn write_u8(writer: &mut Write, value: u8) -> io::Result<()> {
pub fn read_u16(reader: &mut Read) -> io::Result<u16> { pub fn read_u16(reader: &mut Read) -> io::Result<u16> {
let mut bytes = [0; 2]; let mut bytes = [0; 2];
try!(reader.read_exact(&mut bytes)); reader.read_exact(&mut bytes)?;
Ok(NetworkEndian::read_u16(&bytes)) Ok(NetworkEndian::read_u16(&bytes))
} }
@ -31,7 +31,7 @@ pub fn write_u16(writer: &mut Write, value: u16) -> io::Result<()> {
pub fn read_u32(reader: &mut Read) -> io::Result<u32> { pub fn read_u32(reader: &mut Read) -> io::Result<u32> {
let mut bytes = [0; 4]; let mut bytes = [0; 4];
try!(reader.read_exact(&mut bytes)); reader.read_exact(&mut bytes)?;
Ok(NetworkEndian::read_u32(&bytes)) Ok(NetworkEndian::read_u32(&bytes))
} }
@ -43,7 +43,7 @@ pub fn write_u32(writer: &mut Write, value: u32) -> io::Result<()> {
pub fn read_u64(reader: &mut Read) -> io::Result<u64> { pub fn read_u64(reader: &mut Read) -> io::Result<u64> {
let mut bytes = [0; 8]; let mut bytes = [0; 8];
try!(reader.read_exact(&mut bytes)); reader.read_exact(&mut bytes)?;
Ok(NetworkEndian::read_u64(&bytes)) Ok(NetworkEndian::read_u64(&bytes))
} }
@ -54,19 +54,19 @@ pub fn write_u64(writer: &mut Write, value: u64) -> io::Result<()> {
} }
pub fn read_bytes(reader: &mut Read) -> io::Result<Vec<u8>> { pub fn read_bytes(reader: &mut Read) -> io::Result<Vec<u8>> {
let length = try!(read_u32(reader)); let length = read_u32(reader)?;
let mut value = vec![0; length as usize]; let mut value = vec![0; length as usize];
try!(reader.read_exact(&mut value)); reader.read_exact(&mut value)?;
Ok(value) Ok(value)
} }
pub fn write_bytes(writer: &mut Write, value: &[u8]) -> io::Result<()> { pub fn write_bytes(writer: &mut Write, value: &[u8]) -> io::Result<()> {
try!(write_u32(writer, value.len() as u32)); write_u32(writer, value.len() as u32)?;
writer.write_all(value) writer.write_all(value)
} }
pub fn read_string(reader: &mut Read) -> io::Result<String> { pub fn read_string(reader: &mut Read) -> io::Result<String> {
let bytes = try!(read_bytes(reader)); let bytes = read_bytes(reader)?;
String::from_utf8(bytes) String::from_utf8(bytes)
.map_err(|_| io::Error::new(io::ErrorKind::InvalidData, "invalid UTF-8")) .map_err(|_| io::Error::new(io::ErrorKind::InvalidData, "invalid UTF-8"))
} }

View File

@ -19,22 +19,22 @@ unsafe fn recv_value(reader: &mut Read, tag: Tag, data: &mut *mut (),
Tag::None => Ok(()), Tag::None => Ok(()),
Tag::Bool => Tag::Bool =>
consume_value!(u8, |ptr| { consume_value!(u8, |ptr| {
*ptr = try!(read_u8(reader)); Ok(()) *ptr = read_u8(reader)?; Ok(())
}), }),
Tag::Int32 => Tag::Int32 =>
consume_value!(u32, |ptr| { consume_value!(u32, |ptr| {
*ptr = try!(read_u32(reader)); Ok(()) *ptr = read_u32(reader)?; Ok(())
}), }),
Tag::Int64 | Tag::Float64 => Tag::Int64 | Tag::Float64 =>
consume_value!(u64, |ptr| { consume_value!(u64, |ptr| {
*ptr = try!(read_u64(reader)); Ok(()) *ptr = read_u64(reader)?; Ok(())
}), }),
Tag::String => { Tag::String => {
consume_value!(*mut u8, |ptr| { consume_value!(*mut u8, |ptr| {
let length = try!(read_u32(reader)); let length = read_u32(reader)?;
// NB: the received string includes a trailing \0 // NB: the received string includes a trailing \0
*ptr = try!(alloc(length as usize)) as *mut u8; *ptr = alloc(length as usize)? as *mut u8;
try!(reader.read_exact(slice::from_raw_parts_mut(*ptr, length as usize))); reader.read_exact(slice::from_raw_parts_mut(*ptr, length as usize))?;
Ok(()) Ok(())
}) })
} }
@ -42,30 +42,30 @@ unsafe fn recv_value(reader: &mut Read, tag: Tag, data: &mut *mut (),
let mut it = it.clone(); let mut it = it.clone();
for _ in 0..arity { for _ in 0..arity {
let tag = it.next().expect("truncated tag"); let tag = it.next().expect("truncated tag");
try!(recv_value(reader, tag, data, alloc)) recv_value(reader, tag, data, alloc)?
} }
Ok(()) Ok(())
} }
Tag::List(it) | Tag::Array(it) => { Tag::List(it) | Tag::Array(it) => {
struct List { elements: *mut (), length: u32 }; struct List { elements: *mut (), length: u32 };
consume_value!(List, |ptr| { consume_value!(List, |ptr| {
(*ptr).length = try!(read_u32(reader)); (*ptr).length = read_u32(reader)?;
let tag = it.clone().next().expect("truncated tag"); let tag = it.clone().next().expect("truncated tag");
(*ptr).elements = try!(alloc(tag.size() * (*ptr).length as usize)); (*ptr).elements = alloc(tag.size() * (*ptr).length as usize)?;
let mut data = (*ptr).elements; let mut data = (*ptr).elements;
for _ in 0..(*ptr).length as usize { for _ in 0..(*ptr).length as usize {
try!(recv_value(reader, tag, &mut data, alloc)); recv_value(reader, tag, &mut data, alloc)?
} }
Ok(()) Ok(())
}) })
} }
Tag::Range(it) => { Tag::Range(it) => {
let tag = it.clone().next().expect("truncated tag"); let tag = it.clone().next().expect("truncated tag");
try!(recv_value(reader, tag, data, alloc)); recv_value(reader, tag, data, alloc)?;
try!(recv_value(reader, tag, data, alloc)); recv_value(reader, tag, data, alloc)?;
try!(recv_value(reader, tag, data, alloc)); recv_value(reader, tag, data, alloc)?;
Ok(()) Ok(())
} }
Tag::Keyword(_) => unreachable!(), Tag::Keyword(_) => unreachable!(),
@ -81,7 +81,7 @@ pub fn recv_return(reader: &mut Read, tag_bytes: &[u8], data: *mut (),
let tag = it.next().expect("truncated tag"); let tag = it.next().expect("truncated tag");
let mut data = data; let mut data = data;
try!(unsafe { recv_value(reader, tag, &mut data, alloc) }); unsafe { recv_value(reader, tag, &mut data, alloc)? };
Ok(()) Ok(())
} }
@ -101,7 +101,7 @@ unsafe fn send_value(writer: &mut Write, tag: Tag, data: &mut *const ()) -> io::
}) })
} }
try!(write_u8(writer, tag.as_u8())); write_u8(writer, tag.as_u8())?;
match tag { match tag {
Tag::None => Ok(()), Tag::None => Ok(()),
Tag::Bool => Tag::Bool =>
@ -118,36 +118,36 @@ unsafe fn send_value(writer: &mut Write, tag: Tag, data: &mut *const ()) -> io::
write_string(writer, from_c_str(*ptr))), write_string(writer, from_c_str(*ptr))),
Tag::Tuple(it, arity) => { Tag::Tuple(it, arity) => {
let mut it = it.clone(); let mut it = it.clone();
try!(write_u8(writer, arity)); write_u8(writer, arity)?;
for _ in 0..arity { for _ in 0..arity {
let tag = it.next().expect("truncated tag"); let tag = it.next().expect("truncated tag");
try!(send_value(writer, tag, data)) send_value(writer, tag, data)?
} }
Ok(()) Ok(())
} }
Tag::List(it) | Tag::Array(it) => { Tag::List(it) | Tag::Array(it) => {
struct List { elements: *const (), length: u32 }; struct List { elements: *const (), length: u32 };
consume_value!(List, |ptr| { consume_value!(List, |ptr| {
try!(write_u32(writer, (*ptr).length)); write_u32(writer, (*ptr).length)?;
let tag = it.clone().next().expect("truncated tag"); let tag = it.clone().next().expect("truncated tag");
let mut data = (*ptr).elements; let mut data = (*ptr).elements;
for _ in 0..(*ptr).length as usize { for _ in 0..(*ptr).length as usize {
try!(send_value(writer, tag, &mut data)); send_value(writer, tag, &mut data)?;
} }
Ok(()) Ok(())
}) })
} }
Tag::Range(it) => { Tag::Range(it) => {
let tag = it.clone().next().expect("truncated tag"); let tag = it.clone().next().expect("truncated tag");
try!(send_value(writer, tag, data)); send_value(writer, tag, data)?;
try!(send_value(writer, tag, data)); send_value(writer, tag, data)?;
try!(send_value(writer, tag, data)); send_value(writer, tag, data)?;
Ok(()) Ok(())
} }
Tag::Keyword(it) => { Tag::Keyword(it) => {
struct Keyword { name: *const u8, contents: () }; struct Keyword { name: *const u8, contents: () };
consume_value!(Keyword, |ptr| { consume_value!(Keyword, |ptr| {
try!(write_string(writer, from_c_str((*ptr).name))); write_string(writer, from_c_str((*ptr).name))?;
let tag = it.clone().next().expect("truncated tag"); let tag = it.clone().next().expect("truncated tag");
let mut data = &(*ptr).contents as *const (); let mut data = &(*ptr).contents as *const ();
send_value(writer, tag, &mut data) send_value(writer, tag, &mut data)
@ -172,17 +172,17 @@ pub fn send_args(writer: &mut Write, service: u32, tag_bytes: &[u8],
#[cfg(not(ksupport))] #[cfg(not(ksupport))]
trace!("send<{}>({})->{}", service, args_it, return_it); trace!("send<{}>({})->{}", service, args_it, return_it);
try!(write_u32(writer, service)); write_u32(writer, service)?;
for index in 0.. { for index in 0.. {
if let Some(arg_tag) = args_it.next() { if let Some(arg_tag) = args_it.next() {
let mut data = unsafe { *data.offset(index) }; let mut data = unsafe { *data.offset(index) };
try!(unsafe { send_value(writer, arg_tag, &mut data) }); unsafe { send_value(writer, arg_tag, &mut data)? };
} else { } else {
break break
} }
} }
try!(write_u8(writer, 0)); write_u8(writer, 0)?;
try!(write_bytes(writer, return_tag_bytes)); write_bytes(writer, return_tag_bytes)?;
Ok(()) Ok(())
} }
@ -317,49 +317,49 @@ mod tag {
if first { if first {
first = false first = false
} else { } else {
try!(write!(f, ", ")) write!(f, ", ")?
} }
match tag { match tag {
Tag::None => Tag::None =>
try!(write!(f, "None")), write!(f, "None")?,
Tag::Bool => Tag::Bool =>
try!(write!(f, "Bool")), write!(f, "Bool")?,
Tag::Int32 => Tag::Int32 =>
try!(write!(f, "Int32")), write!(f, "Int32")?,
Tag::Int64 => Tag::Int64 =>
try!(write!(f, "Int64")), write!(f, "Int64")?,
Tag::Float64 => Tag::Float64 =>
try!(write!(f, "Float64")), write!(f, "Float64")?,
Tag::String => Tag::String =>
try!(write!(f, "String")), write!(f, "String")?,
Tag::Tuple(it, _) => { Tag::Tuple(it, _) => {
try!(write!(f, "Tuple(")); write!(f, "Tuple(")?;
try!(it.fmt(f)); it.fmt(f)?;
try!(write!(f, ")")) write!(f, ")")?;
} }
Tag::List(it) => { Tag::List(it) => {
try!(write!(f, "List(")); write!(f, "List(")?;
try!(it.fmt(f)); it.fmt(f)?;
try!(write!(f, ")")) write!(f, ")")?;
} }
Tag::Array(it) => { Tag::Array(it) => {
try!(write!(f, "Array(")); write!(f, "Array(")?;
try!(it.fmt(f)); it.fmt(f)?;
try!(write!(f, ")")) write!(f, ")")?;
} }
Tag::Range(it) => { Tag::Range(it) => {
try!(write!(f, "Range(")); write!(f, "Range(")?;
try!(it.fmt(f)); it.fmt(f)?;
try!(write!(f, ")")) write!(f, ")")?;
} }
Tag::Keyword(it) => { Tag::Keyword(it) => {
try!(write!(f, "Keyword(")); write!(f, "Keyword(")?;
try!(it.fmt(f)); it.fmt(f)?;
try!(write!(f, ")")) write!(f, ")")?;
} }
Tag::Object => Tag::Object =>
try!(write!(f, "Object")) write!(f, "Object")?,
} }
} }

View File

@ -285,7 +285,7 @@ impl<'a> UdpSocket<'a> {
} }
pub fn recv_from(&self, buf: &mut [u8]) -> Result<(usize, IpEndpoint)> { pub fn recv_from(&self, buf: &mut [u8]) -> Result<(usize, IpEndpoint)> {
try!(until!(self, UdpSocketLower, |s| s.can_recv())); until!(self, UdpSocketLower, |s| s.can_recv())?;
match self.as_lower().recv_slice(buf) { match self.as_lower().recv_slice(buf) {
Ok(r) => Ok(r), Ok(r) => Ok(r),
Err(()) => { Err(()) => {
@ -296,7 +296,7 @@ impl<'a> UdpSocket<'a> {
} }
pub fn send_to(&self, buf: &[u8], addr: IpEndpoint) -> Result<usize> { pub fn send_to(&self, buf: &[u8], addr: IpEndpoint) -> Result<usize> {
try!(until!(self, UdpSocketLower, |s| s.can_send())); until!(self, UdpSocketLower, |s| s.can_send())?;
match self.as_lower().send_slice(buf, addr) { match self.as_lower().send_slice(buf, addr) {
Ok(r) => Ok(r), Ok(r) => Ok(r),
Err(()) => { Err(()) => {
@ -363,9 +363,9 @@ impl<'a> TcpListener<'a> {
pub fn listen<T: Into<IpEndpoint>>(&self, endpoint: T) -> Result<()> { pub fn listen<T: Into<IpEndpoint>>(&self, endpoint: T) -> Result<()> {
let endpoint = endpoint.into(); let endpoint = endpoint.into();
try!(self.as_lower().listen(endpoint) self.as_lower().listen(endpoint)
.map_err(|()| Error::new(ErrorKind::Other, .map_err(|()| Error::new(ErrorKind::Other,
"cannot listen: already connected"))); "cannot listen: already connected"))?;
self.endpoint.set(endpoint); self.endpoint.set(endpoint);
Ok(()) Ok(())
} }
@ -375,11 +375,11 @@ impl<'a> TcpListener<'a> {
// This handles the case where a remote socket immediately sends a FIN-- // This handles the case where a remote socket immediately sends a FIN--
// that still counts as accepting even though nothing may be sent. // that still counts as accepting even though nothing may be sent.
let (sockets, handle) = (self.io.sockets.clone(), self.handle.get()); let (sockets, handle) = (self.io.sockets.clone(), self.handle.get());
try!(self.io.until(move || { self.io.until(move || {
let mut sockets = borrow_mut!(sockets); let mut sockets = borrow_mut!(sockets);
let socket: &mut TcpSocketLower = sockets.get_mut(handle).as_socket(); let socket: &mut TcpSocketLower = sockets.get_mut(handle).as_socket();
socket.may_send() || socket.may_recv() socket.may_send() || socket.may_recv()
})); })?;
let accepted = self.handle.get(); let accepted = self.handle.get();
self.handle.set(Self::new_lower(self.io, self.buffer_size.get())); self.handle.set(Self::new_lower(self.io, self.buffer_size.get()));
@ -456,7 +456,7 @@ impl<'a> TcpStream<'a> {
pub fn close(&self) -> Result<()> { pub fn close(&self) -> Result<()> {
self.as_lower().close(); self.as_lower().close();
try!(until!(self, TcpSocketLower, |s| !s.is_open())); until!(self, TcpSocketLower, |s| !s.is_open())?;
// right now the socket may be in TIME-WAIT state. if we don't give it a chance to send // right now the socket may be in TIME-WAIT state. if we don't give it a chance to send
// a packet, and the user code executes a loop { s.listen(); s.read(); s.close(); } // a packet, and the user code executes a loop { s.listen(); s.read(); s.close(); }
// then the last ACK will never be sent. // then the last ACK will never be sent.
@ -472,7 +472,7 @@ impl<'a> Read for TcpStream<'a> {
Ok(0) | Err(()) => { Ok(0) | Err(()) => {
// slow path // slow path
if !self.as_lower().may_recv() { return Ok(0) } if !self.as_lower().may_recv() { return Ok(0) }
try!(until!(self, TcpSocketLower, |s| s.can_recv())); until!(self, TcpSocketLower, |s| s.can_recv())?;
Ok(self.as_lower().recv_slice(buf) Ok(self.as_lower().recv_slice(buf)
.expect("may_recv implies that data was available")) .expect("may_recv implies that data was available"))
} }
@ -489,7 +489,7 @@ impl<'a> Write for TcpStream<'a> {
Ok(0) | Err(()) => { Ok(0) | Err(()) => {
// slow path // slow path
if !self.as_lower().may_send() { return Ok(0) } if !self.as_lower().may_send() { return Ok(0) }
try!(until!(self, TcpSocketLower, |s| s.can_send())); until!(self, TcpSocketLower, |s| s.can_send())?;
Ok(self.as_lower().send_slice(buf) Ok(self.as_lower().send_slice(buf)
.expect("may_send implies that data was available")) .expect("may_send implies that data was available"))
} }

View File

@ -102,7 +102,7 @@ fn check_magic(stream: &mut TcpStream) -> io::Result<()> {
const MAGIC: &'static [u8] = b"ARTIQ coredev\n"; const MAGIC: &'static [u8] = b"ARTIQ coredev\n";
let mut magic: [u8; 14] = [0; 14]; let mut magic: [u8; 14] = [0; 14];
try!(stream.read_exact(&mut magic)); stream.read_exact(&mut magic)?;
if magic != MAGIC { if magic != MAGIC {
Err(io::Error::new(io::ErrorKind::InvalidData, "unrecognized magic")) Err(io::Error::new(io::ErrorKind::InvalidData, "unrecognized magic"))
} else { } else {
@ -111,7 +111,7 @@ fn check_magic(stream: &mut TcpStream) -> io::Result<()> {
} }
fn host_read(stream: &mut TcpStream) -> io::Result<host::Request> { fn host_read(stream: &mut TcpStream) -> io::Result<host::Request> {
let request = try!(host::Request::read_from(stream)); let request = host::Request::read_from(stream)?;
match &request { match &request {
&host::Request::LoadKernel(_) => trace!("comm<-host LoadLibrary(...)"), &host::Request::LoadKernel(_) => trace!("comm<-host LoadLibrary(...)"),
_ => trace!("comm<-host {:?}", request) _ => trace!("comm<-host {:?}", request)
@ -135,7 +135,7 @@ fn kern_send(io: &Io, request: &kern::Message) -> io::Result<()> {
fn kern_recv_notrace<R, F>(io: &Io, f: F) -> io::Result<R> fn kern_recv_notrace<R, F>(io: &Io, f: F) -> io::Result<R>
where F: FnOnce(&kern::Message) -> io::Result<R> { where F: FnOnce(&kern::Message) -> io::Result<R> {
try!(io.until(|| mailbox::receive() != 0)); io.until(|| mailbox::receive() != 0)?;
if !kernel::validate(mailbox::receive()) { if !kernel::validate(mailbox::receive()) {
let message = format!("invalid kernel CPU pointer 0x{:x}", mailbox::receive()); let message = format!("invalid kernel CPU pointer 0x{:x}", mailbox::receive());
return Err(io::Error::new(io::ErrorKind::InvalidData, message)) return Err(io::Error::new(io::ErrorKind::InvalidData, message))
@ -173,7 +173,7 @@ unsafe fn kern_load(io: &Io, session: &mut Session, library: &[u8]) -> io::Resul
kernel::start(); kernel::start();
try!(kern_send(io, &kern::LoadRequest(&library))); kern_send(io, &kern::LoadRequest(&library))?;
kern_recv(io, |reply| { kern_recv(io, |reply| {
match reply { match reply {
&kern::LoadReply(Ok(())) => { &kern::LoadReply(Ok(())) => {
@ -203,7 +203,7 @@ fn kern_run(session: &mut Session) -> io::Result<()> {
fn process_host_message(io: &Io, fn process_host_message(io: &Io,
stream: &mut TcpStream, stream: &mut TcpStream,
session: &mut Session) -> io::Result<()> { session: &mut Session) -> io::Result<()> {
match try!(host_read(stream)) { match host_read(stream)? {
host::Request::Ident => host::Request::Ident =>
host_write(stream, host::Reply::Ident(board::ident(&mut [0; 64]))), host_write(stream, host::Reply::Ident(board::ident(&mut [0; 64]))),
@ -263,7 +263,7 @@ fn process_host_message(io: &Io,
match unsafe { kern_load(io, session, &kernel) } { match unsafe { kern_load(io, session, &kernel) } {
Ok(()) => host_write(stream, host::Reply::LoadCompleted), Ok(()) => host_write(stream, host::Reply::LoadCompleted),
Err(error) => { Err(error) => {
try!(host_write(stream, host::Reply::LoadFailed(error.description()))); host_write(stream, host::Reply::LoadFailed(error.description()))?;
kern_acknowledge() kern_acknowledge()
} }
}, },
@ -279,22 +279,22 @@ fn process_host_message(io: &Io,
unexpected!("unsolicited RPC reply") unexpected!("unsolicited RPC reply")
} }
let slot = try!(kern_recv(io, |reply| { let slot = kern_recv(io, |reply| {
match reply { match reply {
&kern::RpcRecvRequest(slot) => Ok(slot), &kern::RpcRecvRequest(slot) => Ok(slot),
other => unexpected!("unexpected reply from kernel CPU: {:?}", other) other => unexpected!("unexpected reply from kernel CPU: {:?}", other)
} }
})); })?;
try!(rpc::recv_return(stream, &tag, slot, &|size| { rpc::recv_return(stream, &tag, slot, &|size| {
try!(kern_send(io, &kern::RpcRecvReply(Ok(size)))); kern_send(io, &kern::RpcRecvReply(Ok(size)))?;
kern_recv(io, |reply| { kern_recv(io, |reply| {
match reply { match reply {
&kern::RpcRecvRequest(slot) => Ok(slot), &kern::RpcRecvRequest(slot) => Ok(slot),
other => unexpected!("unexpected reply from kernel CPU: {:?}", other) other => unexpected!("unexpected reply from kernel CPU: {:?}", other)
} }
}) })
})); })?;
try!(kern_send(io, &kern::RpcRecvReply(Ok(0)))); kern_send(io, &kern::RpcRecvReply(Ok(0)))?;
session.kernel_state = KernelState::Running; session.kernel_state = KernelState::Running;
Ok(()) Ok(())
@ -307,13 +307,13 @@ fn process_host_message(io: &Io,
unexpected!("unsolicited RPC reply") unexpected!("unsolicited RPC reply")
} }
try!(kern_recv(io, |reply| { kern_recv(io, |reply| {
match reply { match reply {
&kern::RpcRecvRequest(_) => Ok(()), &kern::RpcRecvRequest(_) => Ok(()),
other => other =>
unexpected!("unexpected reply from kernel CPU: {:?}", other) unexpected!("unexpected reply from kernel CPU: {:?}", other)
} }
})); })?;
// FIXME: gross. // FIXME: gross.
fn into_c_str(interner: &mut BTreeSet<String>, s: String) -> *const u8 { fn into_c_str(interner: &mut BTreeSet<String>, s: String) -> *const u8 {
@ -332,7 +332,7 @@ fn process_host_message(io: &Io,
function: into_c_str(&mut session.interner, function), function: into_c_str(&mut session.interner, function),
phantom: ::core::marker::PhantomData phantom: ::core::marker::PhantomData
}; };
try!(kern_send(io, &kern::RpcRecvReply(Err(exn)))); kern_send(io, &kern::RpcRecvReply(Err(exn)))?;
session.kernel_state = KernelState::Running; session.kernel_state = KernelState::Running;
Ok(()) Ok(())
@ -361,8 +361,8 @@ fn process_kern_message(io: &Io,
match request { match request {
&kern::Log(args) => { &kern::Log(args) => {
use std::fmt::Write; use std::fmt::Write;
try!(session.log_buffer.write_fmt(args) session.log_buffer.write_fmt(args)
.map_err(|_| io_error("cannot append to session log buffer"))); .map_err(|_| io_error("cannot append to session log buffer"))?;
session.flush_log_buffer(); session.flush_log_buffer();
kern_acknowledge() kern_acknowledge()
} }
@ -410,8 +410,8 @@ fn process_kern_message(io: &Io,
} }
&kern::WatchdogSetRequest { ms } => { &kern::WatchdogSetRequest { ms } => {
let id = try!(session.watchdog_set.set_ms(ms) let id = session.watchdog_set.set_ms(ms)
.map_err(|()| io_error("out of watchdogs"))); .map_err(|()| io_error("out of watchdogs"))?;
kern_send(io, &kern::WatchdogSetReply { id: id }) kern_send(io, &kern::WatchdogSetReply { id: id })
} }
@ -424,8 +424,8 @@ fn process_kern_message(io: &Io,
match stream { match stream {
None => unexpected!("unexpected RPC in flash kernel"), None => unexpected!("unexpected RPC in flash kernel"),
Some(ref mut stream) => { Some(ref mut stream) => {
try!(host_write(stream, host::Reply::RpcRequest { async: async })); host_write(stream, host::Reply::RpcRequest { async: async })?;
try!(rpc::send_args(stream, service, tag, data)); rpc::send_args(stream, service, tag, data)?;
if !async { if !async {
session.kernel_state = KernelState::RpcWait session.kernel_state = KernelState::RpcWait
} }
@ -543,9 +543,9 @@ fn process_kern_queued_rpc(stream: &mut TcpStream,
rpc_queue::dequeue(|slice| { rpc_queue::dequeue(|slice| {
trace!("comm<-kern (async RPC)"); trace!("comm<-kern (async RPC)");
let length = NetworkEndian::read_u32(slice) as usize; let length = NetworkEndian::read_u32(slice) as usize;
try!(host_write(stream, host::Reply::RpcRequest { async: true })); host_write(stream, host::Reply::RpcRequest { async: true })?;
trace!("{:?}" ,&slice[4..][..length]); trace!("{:?}" ,&slice[4..][..length]);
try!(stream.write(&slice[4..][..length])); stream.write(&slice[4..][..length])?;
Ok(()) Ok(())
}) })
} }
@ -557,32 +557,32 @@ fn host_kernel_worker(io: &Io,
loop { loop {
while !rpc_queue::empty() { while !rpc_queue::empty() {
try!(process_kern_queued_rpc(stream, &mut session)) process_kern_queued_rpc(stream, &mut session)?
} }
if stream.can_recv() { if stream.can_recv() {
try!(process_host_message(io, stream, &mut session)) process_host_message(io, stream, &mut session)?
} else if !stream.may_recv() { } else if !stream.may_recv() {
return Ok(()) return Ok(())
} }
if mailbox::receive() != 0 { if mailbox::receive() != 0 {
try!(process_kern_message(io, Some(stream), &mut session)); process_kern_message(io, Some(stream), &mut session)?;
} }
if session.kernel_state == KernelState::Running { if session.kernel_state == KernelState::Running {
if session.watchdog_set.expired() { if session.watchdog_set.expired() {
try!(host_write(stream, host::Reply::WatchdogExpired)); host_write(stream, host::Reply::WatchdogExpired)?;
return Err(io_error("watchdog expired")) return Err(io_error("watchdog expired"))
} }
if !rtio_mgt::crg::check() { if !rtio_mgt::crg::check() {
try!(host_write(stream, host::Reply::ClockFailure)); host_write(stream, host::Reply::ClockFailure)?;
return Err(io_error("RTIO clock failure")) return Err(io_error("RTIO clock failure"))
} }
} }
try!(io.relinquish()) io.relinquish()?
} }
} }
@ -596,8 +596,8 @@ fn flash_kernel_worker(io: &Io,
return Err(io::Error::new(io::ErrorKind::NotFound, "kernel not found")) return Err(io::Error::new(io::ErrorKind::NotFound, "kernel not found"))
} }
try!(unsafe { kern_load(io, &mut session, &kernel) }); unsafe { kern_load(io, &mut session, &kernel)? };
try!(kern_run(&mut session)); kern_run(&mut session)?;
loop { loop {
if !rpc_queue::empty() { if !rpc_queue::empty() {
@ -605,7 +605,7 @@ fn flash_kernel_worker(io: &Io,
} }
if mailbox::receive() != 0 { if mailbox::receive() != 0 {
if try!(process_kern_message(io, None, &mut session)) { if process_kern_message(io, None, &mut session)? {
return Ok(()) return Ok(())
} }
} }
@ -618,7 +618,7 @@ fn flash_kernel_worker(io: &Io,
return Err(io_error("RTIO clock failure")) return Err(io_error("RTIO clock failure"))
} }
try!(io.relinquish()) io.relinquish()?
} }
} }

View File

@ -5,7 +5,7 @@ use proto::*;
fn read_sync(reader: &mut Read) -> io::Result<()> { fn read_sync(reader: &mut Read) -> io::Result<()> {
let mut sync = [0; 4]; let mut sync = [0; 4];
for i in 0.. { for i in 0.. {
sync[i % 4] = try!(read_u8(reader)); sync[i % 4] = read_u8(reader)?;
if sync == [0x5a; 4] { break } if sync == [0x5a; 4] { break }
} }
Ok(()) Ok(())
@ -45,38 +45,38 @@ pub enum Request {
impl Request { impl Request {
pub fn read_from(reader: &mut Read) -> io::Result<Request> { pub fn read_from(reader: &mut Read) -> io::Result<Request> {
try!(read_sync(reader)); read_sync(reader)?;
Ok(match try!(read_u8(reader)) { Ok(match read_u8(reader)? {
1 => Request::Log, 1 => Request::Log,
2 => Request::LogClear, 2 => Request::LogClear,
3 => Request::Ident, 3 => Request::Ident,
4 => Request::SwitchClock(try!(read_u8(reader))), 4 => Request::SwitchClock(read_u8(reader)?),
5 => Request::LoadKernel(try!(read_bytes(reader))), 5 => Request::LoadKernel(read_bytes(reader)?),
6 => Request::RunKernel, 6 => Request::RunKernel,
7 => Request::RpcReply { 7 => Request::RpcReply {
tag: try!(read_bytes(reader)) tag: read_bytes(reader)?
}, },
8 => Request::RpcException { 8 => Request::RpcException {
name: try!(read_string(reader)), name: read_string(reader)?,
message: try!(read_string(reader)), message: read_string(reader)?,
param: [try!(read_u64(reader).map(|x| x as i64)), param: [read_u64(reader)? as i64,
try!(read_u64(reader).map(|x| x as i64)), read_u64(reader)? as i64,
try!(read_u64(reader).map(|x| x as i64))], read_u64(reader)? as i64],
file: try!(read_string(reader)), file: read_string(reader)?,
line: try!(read_u32(reader)), line: read_u32(reader)?,
column: try!(read_u32(reader)), column: read_u32(reader)?,
function: try!(read_string(reader)) function: read_string(reader)?
}, },
9 => Request::FlashRead { 9 => Request::FlashRead {
key: try!(read_string(reader)) key: read_string(reader)?
}, },
10 => Request::FlashWrite { 10 => Request::FlashWrite {
key: try!(read_string(reader)), key: read_string(reader)?,
value: try!(read_bytes(reader)) value: read_bytes(reader)?
}, },
11 => Request::FlashErase, 11 => Request::FlashErase,
12 => Request::FlashRemove { 12 => Request::FlashRemove {
key: try!(read_string(reader)) key: read_string(reader)?
}, },
_ => return Err(io::Error::new(io::ErrorKind::InvalidData, "unknown request type")) _ => return Err(io::Error::new(io::ErrorKind::InvalidData, "unknown request type"))
}) })
@ -119,79 +119,79 @@ pub enum Reply<'a> {
impl<'a> Reply<'a> { impl<'a> Reply<'a> {
pub fn write_to(&self, writer: &mut Write) -> io::Result<()> { pub fn write_to(&self, writer: &mut Write) -> io::Result<()> {
try!(write_sync(writer)); write_sync(writer)?;
match *self { match *self {
Reply::Log(ref log) => { Reply::Log(ref log) => {
try!(write_u8(writer, 1)); write_u8(writer, 1)?;
try!(write_string(writer, log)); write_string(writer, log)?;
}, },
Reply::Ident(ident) => { Reply::Ident(ident) => {
try!(write_u8(writer, 2)); write_u8(writer, 2)?;
try!(writer.write(b"AROR")); writer.write(b"AROR")?;
try!(write_string(writer, ident)); write_string(writer, ident)?;
}, },
Reply::ClockSwitchCompleted => { Reply::ClockSwitchCompleted => {
try!(write_u8(writer, 3)); write_u8(writer, 3)?;
}, },
Reply::ClockSwitchFailed => { Reply::ClockSwitchFailed => {
try!(write_u8(writer, 4)); write_u8(writer, 4)?;
}, },
Reply::LoadCompleted => { Reply::LoadCompleted => {
try!(write_u8(writer, 5)); write_u8(writer, 5)?;
}, },
Reply::LoadFailed(reason) => { Reply::LoadFailed(reason) => {
try!(write_u8(writer, 6)); write_u8(writer, 6)?;
try!(write_string(writer, reason)); write_string(writer, reason)?;
}, },
Reply::KernelFinished => { Reply::KernelFinished => {
try!(write_u8(writer, 7)); write_u8(writer, 7)?;
}, },
Reply::KernelStartupFailed => { Reply::KernelStartupFailed => {
try!(write_u8(writer, 8)); write_u8(writer, 8)?;
}, },
Reply::KernelException { Reply::KernelException {
name, message, param, file, line, column, function, backtrace name, message, param, file, line, column, function, backtrace
} => { } => {
try!(write_u8(writer, 9)); write_u8(writer, 9)?;
try!(write_string(writer, name)); write_string(writer, name)?;
try!(write_string(writer, message)); write_string(writer, message)?;
try!(write_u64(writer, param[0] as u64)); write_u64(writer, param[0] as u64)?;
try!(write_u64(writer, param[1] as u64)); write_u64(writer, param[1] as u64)?;
try!(write_u64(writer, param[2] as u64)); write_u64(writer, param[2] as u64)?;
try!(write_string(writer, file)); write_string(writer, file)?;
try!(write_u32(writer, line)); write_u32(writer, line)?;
try!(write_u32(writer, column)); write_u32(writer, column)?;
try!(write_string(writer, function)); write_string(writer, function)?;
try!(write_u32(writer, backtrace.len() as u32)); write_u32(writer, backtrace.len() as u32)?;
for &addr in backtrace { for &addr in backtrace {
try!(write_u32(writer, addr as u32)) write_u32(writer, addr as u32)?
} }
}, },
Reply::RpcRequest { async } => { Reply::RpcRequest { async } => {
try!(write_u8(writer, 10)); write_u8(writer, 10)?;
try!(write_u8(writer, async as u8)); write_u8(writer, async as u8)?;
}, },
Reply::FlashRead(ref bytes) => { Reply::FlashRead(ref bytes) => {
try!(write_u8(writer, 11)); write_u8(writer, 11)?;
try!(write_bytes(writer, bytes)); write_bytes(writer, bytes)?;
}, },
Reply::FlashOk => { Reply::FlashOk => {
try!(write_u8(writer, 12)); write_u8(writer, 12)?;
}, },
Reply::FlashError => { Reply::FlashError => {
try!(write_u8(writer, 13)); write_u8(writer, 13)?;
}, },
Reply::WatchdogExpired => { Reply::WatchdogExpired => {
try!(write_u8(writer, 14)); write_u8(writer, 14)?;
}, },
Reply::ClockFailure => { Reply::ClockFailure => {
try!(write_u8(writer, 15)); write_u8(writer, 15)?;
}, },
} }
Ok(()) Ok(())