diff --git a/.rustfmt.toml b/.rustfmt.toml new file mode 100644 index 0000000..7e41aae --- /dev/null +++ b/.rustfmt.toml @@ -0,0 +1,11 @@ +error_on_line_overflow = false +fn_args_density = "Compressed" +fn_args_layout = "Visual" +fn_arg_intent = "Tabbed" +reorder_imports = true +reorder_imported_names = true +report_todo = "Always" +report_fixme = "Always" +normalize_comments = true +use_try_shorthand = true +max_width = 110 diff --git a/.travis.yml b/.travis.yml index c184699..cb938e1 100644 --- a/.travis.yml +++ b/.travis.yml @@ -24,17 +24,17 @@ branches: - master before_script: - - | - pip install 'travis-cargo<0.2' --user && - export PATH=$HOME/.local/bin:$PATH - - | - mkdir $(pwd)/socket && - export XDG_RUNTIME_DIR="$(pwd)/socket" + - export PATH=$HOME/.local/bin:$HOME/.cargo/bin:$PATH + - which rustfmt || cargo install rustfmt + - pip install 'travis-cargo<0.2' --user + - mkdir $(pwd)/socket + - export XDG_RUNTIME_DIR="$(pwd)/socket" script: - - | - travis-cargo build && - travis-cargo --only stable doc -- --no-deps + - cargo fmt -- --write-mode=diff + - travis-cargo --skip nightly build + - travis-cargo --only nightly build -- --features "clippy" + - travis-cargo --only stable doc -- --no-deps after_success: - travis-cargo --only stable doc-upload diff --git a/Cargo.toml b/Cargo.toml index 47eeab4..025a343 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -8,6 +8,7 @@ wayland-server = "0.8.4" nix = "0.7.0" slog = { version = "~1.5.2", features = ["max_level_trace", "release_max_level_info"] } slog-stdlog = "~1.1.0" +clippy = { version = "*", optional = true } [dev-dependencies] slog-term = "~1.5" diff --git a/src/lib.rs b/src/lib.rs index 3a7d7aa..b4eed74 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1,5 +1,8 @@ #![warn(missing_docs)] +#![cfg_attr(feature = "clippy", feature(plugin))] +#![cfg_attr(feature = "clippy", plugin(clippy))] + #[macro_use] extern crate wayland_server; extern crate nix; diff --git a/src/shm/mod.rs b/src/shm/mod.rs index 61d1ef9..2a2bcc6 100644 --- a/src/shm/mod.rs +++ b/src/shm/mod.rs @@ -61,13 +61,13 @@ //! //! If you are already using an handler for this signal, you probably don't want to use this handler. + +use self::pool::{Pool, ResizeError}; use std::os::unix::io::RawFd; use std::sync::Arc; -use wayland_server::{GlobalHandler, EventLoopHandle, Client, Init, Resource, Destroy, resource_is_registered}; -use wayland_server::protocol::{wl_shm, wl_shm_pool, wl_buffer}; - -use self::pool::{Pool, ResizeError}; +use wayland_server::{Client, Destroy, EventLoopHandle, GlobalHandler, Init, Resource, resource_is_registered}; +use wayland_server::protocol::{wl_buffer, wl_shm, wl_shm_pool}; mod pool; @@ -78,7 +78,7 @@ mod pool; pub struct ShmGlobal { formats: Vec, handler_id: Option, - log: ::slog::Logger + log: ::slog::Logger, } impl ShmGlobal { @@ -94,7 +94,7 @@ impl ShmGlobal { where L: Into> { use slog::DrainExt; - let log = logger.into().unwrap_or(::slog::Logger::root(::slog_stdlog::StdLog.fuse(), o!())); + let log = logger.into().unwrap_or_else(|| ::slog::Logger::root(::slog_stdlog::StdLog.fuse(), o!())); // always add the mandatory formats formats.push(wl_shm::Format::Argb8888); @@ -102,7 +102,7 @@ impl ShmGlobal { ShmGlobal { formats: formats, handler_id: None, - log: log.new(o!("smithay_module" => "shm_handler")) + log: log.new(o!("smithay_module" => "shm_handler")), } } @@ -113,18 +113,16 @@ impl ShmGlobal { /// /// This is needed to retrieve the contents of the shm pools and buffers. pub fn get_token(&self) -> ShmGlobalToken { - ShmGlobalToken { - hid: self.handler_id.clone().expect("ShmGlobal was not initialized."), - } + ShmGlobalToken { hid: self.handler_id.expect("ShmGlobal was not initialized.") } } } /// An SHM global token /// /// It is needed to access the contents of the buffers & pools managed by the -/// associated ShmGlobal. +/// associated `ShmGlobal`. pub struct ShmGlobalToken { - hid: usize + hid: usize, } /// Error that can occur when accessing an SHM buffer @@ -137,7 +135,7 @@ pub enum BufferAccessError { /// for the memory map. /// /// If this error occurs, the client has been killed as a result. - BadMap + BadMap, } impl ShmGlobalToken { @@ -155,14 +153,14 @@ impl ShmGlobalToken { where F: FnOnce(&[u8], BufferData) { if !resource_is_registered::<_, ShmHandler>(buffer, self.hid) { - return Err(BufferAccessError::NotManaged) + return Err(BufferAccessError::NotManaged); } - let data = unsafe { &* (buffer.get_user_data() as *mut InternalBufferData) }; + let data = unsafe { &*(buffer.get_user_data() as *mut InternalBufferData) }; - if data.pool.with_data_slice(|slice| f(slice, data.data.clone())).is_err() { + if data.pool.with_data_slice(|slice| f(slice, data.data)).is_err() { // SIGBUS error occured buffer.post_error(wl_shm::Error::InvalidFd as u32, "Bad pool size.".into()); - return Err(BufferAccessError::BadMap) + return Err(BufferAccessError::BadMap); } Ok(()) } @@ -171,17 +169,17 @@ impl ShmGlobalToken { impl Init for ShmGlobal { fn init(&mut self, evqh: &mut EventLoopHandle, _index: usize) { let id = evqh.add_handler_with_init(ShmHandler { - my_id: ::std::usize::MAX, - valid_formats: self.formats.clone(), - log: self.log.clone() - }); + my_id: ::std::usize::MAX, + valid_formats: self.formats.clone(), + log: self.log.clone(), + }); self.handler_id = Some(id); } } impl GlobalHandler for ShmGlobal { fn bind(&mut self, evqh: &mut EventLoopHandle, _: &Client, global: wl_shm::WlShm) { - let hid = self.handler_id.clone().expect("ShmGlobal was not initialized."); + let hid = self.handler_id.expect("ShmGlobal was not initialized."); // register an handler for this shm evqh.register::<_, ShmHandler>(&global, hid); // and then the custom formats @@ -194,7 +192,7 @@ impl GlobalHandler for ShmGlobal { struct ShmHandler { my_id: usize, valid_formats: Vec, - log: ::slog::Logger + log: ::slog::Logger, } impl Init for ShmHandler { @@ -208,8 +206,9 @@ impl wl_shm::Handler for ShmHandler { fn create_pool(&mut self, evqh: &mut EventLoopHandle, _client: &Client, shm: &wl_shm::WlShm, pool: wl_shm_pool::WlShmPool, fd: RawFd, size: i32) { if size <= 0 { - shm.post_error(wl_shm::Error::InvalidFd as u32, "Invalid size for a new wl_shm_pool.".into()); - return + shm.post_error(wl_shm::Error::InvalidFd as u32, + "Invalid size for a new wl_shm_pool.".into()); + return; } let mmap_pool = match Pool::new(fd, size as usize, self.log.clone()) { Ok(p) => p, @@ -245,47 +244,46 @@ pub struct BufferData { /// Stride of the buffer in bytes pub stride: i32, /// Format used by this buffer - pub format: wl_shm::Format + pub format: wl_shm::Format, } struct InternalBufferData { pool: Arc, - data: BufferData + data: BufferData, } impl wl_shm_pool::Handler for ShmHandler { fn create_buffer(&mut self, evqh: &mut EventLoopHandle, _client: &Client, - pool: &wl_shm_pool::WlShmPool, buffer: wl_buffer::WlBuffer, offset: i32, - width: i32, height: i32, stride: i32, format: wl_shm::Format) - { + pool: &wl_shm_pool::WlShmPool, buffer: wl_buffer::WlBuffer, offset: i32, width: i32, + height: i32, stride: i32, format: wl_shm::Format) { if !self.valid_formats.contains(&format) { buffer.post_error(wl_shm::Error::InvalidFormat as u32, String::new()); - return + return; } let arc_pool = unsafe { &*(pool.get_user_data() as *mut Arc) }; let data = Box::into_raw(Box::new(InternalBufferData { - pool: arc_pool.clone(), - data: BufferData { - offset: offset, - width: width, - height: height, - stride: stride, - format: format - } - })); + pool: arc_pool.clone(), + data: BufferData { + offset: offset, + width: width, + height: height, + stride: stride, + format: format, + }, + })); evqh.register_with_destructor::<_, ShmHandler, ShmHandler>(&buffer, self.my_id); buffer.set_user_data(data as *mut ()); } - fn resize(&mut self, _evqh: &mut EventLoopHandle, _client: &Client, - pool: &wl_shm_pool::WlShmPool, size: i32) - { + fn resize(&mut self, _evqh: &mut EventLoopHandle, _client: &Client, pool: &wl_shm_pool::WlShmPool, + size: i32) { let arc_pool = unsafe { &*(pool.get_user_data() as *mut Arc) }; match arc_pool.resize(size) { - Ok(()) => {}, + Ok(()) => {} Err(ResizeError::InvalidSize) => { - pool.post_error(wl_shm::Error::InvalidFd as u32, "Invalid new size for a wl_shm_pool.".into()); - }, + pool.post_error(wl_shm::Error::InvalidFd as u32, + "Invalid new size for a wl_shm_pool.".into()); + } Err(ResizeError::MremapFailed) => { pool.post_error(wl_shm::Error::InvalidFd as u32, "mremap failed.".into()); } @@ -302,7 +300,6 @@ impl Destroy for ShmHandler { declare_handler!(ShmHandler, wl_shm_pool::Handler, wl_shm_pool::WlShmPool); -impl wl_buffer::Handler for ShmHandler { -} +impl wl_buffer::Handler for ShmHandler {} declare_handler!(ShmHandler, wl_buffer::Handler, wl_buffer::WlBuffer); diff --git a/src/shm/pool.rs b/src/shm/pool.rs index 886007c..08321db 100644 --- a/src/shm/pool.rs +++ b/src/shm/pool.rs @@ -1,11 +1,12 @@ -use std::cell::Cell; -use std::os::unix::io::RawFd; -use std::sync::{RwLock, Once, ONCE_INIT}; -use std::ptr; + use nix::{c_int, c_void, libc, unistd}; use nix::sys::mman; -use nix::sys::signal::{self, SigAction, Signal, SigHandler}; +use nix::sys::signal::{self, SigAction, SigHandler, Signal}; +use std::cell::Cell; +use std::os::unix::io::RawFd; +use std::ptr; +use std::sync::{ONCE_INIT, Once, RwLock}; thread_local!(static SIGBUS_GUARD: Cell<(*const MemMap, bool)> = Cell::new((ptr::null_mut(), false))); @@ -15,30 +16,30 @@ static mut OLD_SIGBUS_HANDLER: *mut SigAction = 0 as *mut SigAction; pub struct Pool { map: RwLock, fd: RawFd, - log: ::slog::Logger + log: ::slog::Logger, } pub enum ResizeError { InvalidSize, - MremapFailed + MremapFailed, } impl Pool { - pub fn new(fd: RawFd, size: usize, log: ::slog::Logger) -> Result { + pub fn new(fd: RawFd, size: usize, log: ::slog::Logger) -> Result { let memmap = MemMap::new(fd, size)?; trace!(log, "Creating new shm pool"; "fd" => fd as i32, "size" => size); Ok(Pool { - map: RwLock::new(memmap), - fd: fd, - log: log - }) + map: RwLock::new(memmap), + fd: fd, + log: log, + }) } - pub fn resize(&self, newsize: i32) -> Result<(),ResizeError> { + pub fn resize(&self, newsize: i32) -> Result<(), ResizeError> { let mut guard = self.map.write().unwrap(); let oldsize = guard.size(); if newsize <= 0 || oldsize > (newsize as usize) { - return Err(ResizeError::InvalidSize) + return Err(ResizeError::InvalidSize); } trace!(self.log, "Resizing shm pool"; "fd" => self.fd as i32, "oldsize" => oldsize, "newsize" => newsize); guard.remap(newsize as usize).map_err(|()| { @@ -46,12 +47,12 @@ impl Pool { ResizeError::MremapFailed }) } - - pub fn with_data_slice(&self, f: F) -> Result<(),()> { + + pub fn with_data_slice(&self, f: F) -> Result<(), ()> { // Place the sigbus handler - SIGBUS_INIT.call_once(|| { - unsafe { place_sigbus_handler(); } - }); + SIGBUS_INIT.call_once(|| unsafe { + place_sigbus_handler(); + }); let pool_guard = self.map.read().unwrap(); @@ -59,7 +60,7 @@ impl Pool { // Prepare the access SIGBUS_GUARD.with(|guard| { - let (p,_) = guard.get(); + let (p, _) = guard.get(); if !p.is_null() { // Recursive call of this method is not supported panic!("Recursive access to a SHM pool content is not supported."); @@ -87,28 +88,28 @@ impl Pool { impl Drop for Pool { fn drop(&mut self) { trace!(self.log, "Deleting SHM pool"; "fd" => self.fd); - let _ = unsafe { unistd::close(self.fd) }; + let _ = unistd::close(self.fd); } } struct MemMap { ptr: *mut u8, fd: RawFd, - size: usize + size: usize, } impl MemMap { - fn new(fd: RawFd, size: usize) -> Result { + fn new(fd: RawFd, size: usize) -> Result { Ok(MemMap { - ptr: unsafe { map(fd, size) }?, - fd: fd, - size: size - }) + ptr: unsafe { map(fd, size) }?, + fd: fd, + size: size, + }) } - fn remap(&mut self, newsize: usize) -> Result<(),()> { + fn remap(&mut self, newsize: usize) -> Result<(), ()> { if self.ptr.is_null() { - return Err(()) + return Err(()); } // memunmap cannot fail, as we are unmapping a pre-existing map let _ = unsafe { unmap(self.ptr, self.size) }; @@ -119,7 +120,7 @@ impl MemMap { self.ptr = ptr; self.size = newsize; Ok(()) - }, + } Err(()) => { // set ourselves in an empty state self.ptr = ptr::null_mut(); @@ -144,7 +145,7 @@ impl MemMap { ptr >= self.ptr && ptr < unsafe { self.ptr.offset(self.size as isize) } } - fn nullify(&self) -> Result<(),()> { + fn nullify(&self) -> Result<(), ()> { unsafe { nullify_map(self.ptr, self.size) } } } @@ -159,49 +160,41 @@ impl Drop for MemMap { // mman::mmap should really be unsafe... why isn't it? unsafe fn map(fd: RawFd, size: usize) -> Result<*mut u8, ()> { - let ret = mman::mmap( - ptr::null_mut(), - size, - mman::PROT_READ, - mman::MAP_SHARED, - fd, - 0 - ); + let ret = mman::mmap(ptr::null_mut(), + size, + mman::PROT_READ, + mman::MAP_SHARED, + fd, + 0); ret.map(|p| p as *mut u8).map_err(|_| ()) } // mman::munmap should really be unsafe... why isn't it? -unsafe fn unmap(ptr: *mut u8, size: usize) -> Result<(),()> { +unsafe fn unmap(ptr: *mut u8, size: usize) -> Result<(), ()> { let ret = mman::munmap(ptr as *mut _, size); ret.map_err(|_| ()) } unsafe fn nullify_map(ptr: *mut u8, size: usize) -> Result<(), ()> { - let ret = mman::mmap( - ptr as *mut _, - size, - mman::PROT_READ, - mman::MAP_ANONYMOUS | mman::MAP_PRIVATE | mman::MAP_FIXED, - -1, - 0 - ); + let ret = mman::mmap(ptr as *mut _, + size, + mman::PROT_READ, + mman::MAP_ANONYMOUS | mman::MAP_PRIVATE | mman::MAP_FIXED, + -1, + 0); ret.map(|_| ()).map_err(|_| ()) } unsafe fn place_sigbus_handler() { // create our sigbus handler - let action = SigAction::new( - SigHandler::SigAction(sigbus_handler), - signal::SA_NODEFER, - signal::SigSet::empty() - ); + let action = SigAction::new(SigHandler::SigAction(sigbus_handler), + signal::SA_NODEFER, + signal::SigSet::empty()); match signal::sigaction(Signal::SIGBUS, &action) { Ok(old_signal) => { OLD_SIGBUS_HANDLER = Box::into_raw(Box::new(old_signal)); - }, - Err(e) => { - panic!("sigaction failed sor SIGBUS handler: {:?}", e) } + Err(e) => panic!("sigaction failed sor SIGBUS handler: {:?}", e), } } @@ -225,7 +218,7 @@ extern "C" fn sigbus_handler(_signum: c_int, info: *mut libc::siginfo_t, _contex // something terrible occured ! unsafe { reraise_sigbus() } } - }, + } _ => { // something else occured, let's die honorably unsafe { reraise_sigbus() } @@ -240,16 +233,16 @@ extern "C" fn sigbus_handler(_signum: c_int, info: *mut libc::siginfo_t, _contex #[cfg(any(target_os = "linux", target_os = "android"))] unsafe fn siginfo_si_addr(info: *mut libc::siginfo_t) -> *mut c_void { - #[repr(C)] - struct siginfo_t { - a: [libc::c_int; 3], // si_signo, si_errno, si_code - si_addr: *mut libc::c_void, - } + #[repr(C)] + struct siginfo_t { + a: [libc::c_int; 3], // si_signo, si_errno, si_code + si_addr: *mut libc::c_void, + } - (*(info as *const siginfo_t)).si_addr + (*(info as *const siginfo_t)).si_addr } #[cfg(not(any(target_os = "linux", target_os = "android")))] unsafe fn siginfo_si_addr(info: *mut libc::siginfo_t) -> *mut c_void { - (*info).si_addr + (*info).si_addr }