1
0
Fork 0
forked from wry/wry

Merge pull request #302 from mahkoh/jorth/edition-2024

warn on unsafe-op-in-unsafe-fn
This commit is contained in:
mahkoh 2024-10-20 18:41:50 +02:00 committed by GitHub
commit 5b7ad4b060
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
27 changed files with 457 additions and 355 deletions

View file

@ -155,12 +155,14 @@ fn write_egl_procs<W: Write>(f: &mut W) -> anyhow::Result<()> {
writeln!(f, " if self.{}.is_null() {{", name)?; writeln!(f, " if self.{}.is_null() {{", name)?;
writeln!(f, " panic!(\"Could not load `{}`\");", name)?; writeln!(f, " panic!(\"Could not load `{}`\");", name)?;
writeln!(f, " }}")?; writeln!(f, " }}")?;
writeln!(f, " unsafe {{")?;
writeln!( writeln!(
f, f,
" ptr::read(&self.{} as *const *mut u8 as *const unsafe extern fn({}) -> {})({})", " ptr::read(&self.{} as *const *mut u8 as *const unsafe extern fn({}) -> {})({})",
name, args_tys, ret, args_names name, args_tys, ret, args_names
)?; )?;
writeln!(f, " }}")?; writeln!(f, " }}")?;
writeln!(f, " }}")?;
} }
writeln!(f, "}}")?; writeln!(f, "}}")?;
Ok(()) Ok(())

View file

@ -164,7 +164,7 @@ unsafe fn with_client<T, F: FnOnce(&Client) -> T>(data: *const u8, f: F) -> T {
self.cell.set(self.val); self.cell.set(self.val);
} }
} }
CLIENT.with(|cell| { CLIENT.with(|cell| unsafe {
let client = data as *const Client; let client = data as *const Client;
Rc::increment_strong_count(client); Rc::increment_strong_count(client);
let client = Rc::from_raw(client); let client = Rc::from_raw(client);
@ -190,6 +190,7 @@ impl<T: Config> ConfigEntryGen<T> {
size: usize, size: usize,
) -> *const u8 { ) -> *const u8 {
logging::init(); logging::init();
unsafe {
init( init(
srv_data, srv_data,
srv_unref, srv_unref,
@ -200,6 +201,7 @@ impl<T: Config> ConfigEntryGen<T> {
) )
} }
} }
}
pub unsafe extern "C" fn init( pub unsafe extern "C" fn init(
srv_data: *const u8, srv_data: *const u8,
@ -239,22 +241,26 @@ pub unsafe extern "C" fn init(
pressed_keysym: Cell::new(None), pressed_keysym: Cell::new(None),
feat_mod_mask: Cell::new(false), feat_mod_mask: Cell::new(false),
}); });
let init = slice::from_raw_parts(init, size); let init = unsafe { slice::from_raw_parts(init, size) };
client.handle_init_msg(init); client.handle_init_msg(init);
Rc::into_raw(client) as *const u8 Rc::into_raw(client) as *const u8
} }
pub unsafe extern "C" fn unref(data: *const u8) { pub unsafe extern "C" fn unref(data: *const u8) {
let client = data as *const Client; let client = data as *const Client;
unsafe {
drop(Rc::from_raw(client)); drop(Rc::from_raw(client));
} }
}
pub unsafe extern "C" fn handle_msg(data: *const u8, msg: *const u8, size: usize) { pub unsafe extern "C" fn handle_msg(data: *const u8, msg: *const u8, size: usize) {
unsafe {
with_client(data, |client| { with_client(data, |client| {
let msg = slice::from_raw_parts(msg, size); let msg = slice::from_raw_parts(msg, size);
client.handle_msg(msg); client.handle_msg(msg);
}); });
} }
}
macro_rules! get_response { macro_rules! get_response {
($res:expr, $def:expr, $ty:ident { $($field:ident),+ }) => { ($res:expr, $def:expr, $ty:ident { $($field:ident),+ }) => {

View file

@ -41,6 +41,7 @@
clippy::single_char_add_str, clippy::single_char_add_str,
clippy::single_match clippy::single_match
)] )]
#![warn(unsafe_op_in_unsafe_fn)]
use { use {
crate::{_private::ipc::WorkspaceSource, keyboard::ModifiedKeySym, video::Connector}, crate::{_private::ipc::WorkspaceSource, keyboard::ModifiedKeySym, video::Connector},

View file

@ -49,6 +49,7 @@ impl<T: 'static, F: Future<Output = T>> SpawnedFutureVTableProxy<T, F> {
}; };
unsafe fn poll(data: *mut u8, ctx: &mut Context<'_>) -> Poll<T> { unsafe fn poll(data: *mut u8, ctx: &mut Context<'_>) -> Poll<T> {
unsafe {
let task = (data as *const Task<T, F>).deref(); let task = (data as *const Task<T, F>).deref();
if &task.state & COMPLETED == 0 { if &task.state & COMPLETED == 0 {
task.waker.set(Some(ctx.waker().clone())); task.waker.set(Some(ctx.waker().clone()));
@ -60,8 +61,10 @@ impl<T: 'static, F: Future<Output = T>> SpawnedFutureVTableProxy<T, F> {
panic!("Future polled after it has already been emptied"); panic!("Future polled after it has already been emptied");
} }
} }
}
unsafe fn drop(data: *mut u8) { unsafe fn drop(data: *mut u8) {
unsafe {
{ {
let task = (data as *const Task<T, F>).deref(); let task = (data as *const Task<T, F>).deref();
task.state.or_assign(CANCELLED); task.state.or_assign(CANCELLED);
@ -72,6 +75,7 @@ impl<T: 'static, F: Future<Output = T>> SpawnedFutureVTableProxy<T, F> {
Task::<T, F>::dec_ref_count(data as _); Task::<T, F>::dec_ref_count(data as _);
} }
} }
}
struct SpawnedFutureVtable<T> { struct SpawnedFutureVtable<T> {
poll: unsafe fn(data: *mut u8, ctx: &mut Context<'_>) -> Poll<T>, poll: unsafe fn(data: *mut u8, ctx: &mut Context<'_>) -> Poll<T>,
@ -160,6 +164,7 @@ impl<T, F: Future<Output = T>> Task<T, F> {
); );
unsafe fn run_proxy(data: *const u8, run: bool) { unsafe fn run_proxy(data: *const u8, run: bool) {
unsafe {
let task = data as *const Self; let task = data as *const Self;
if run { if run {
task.deref().run(); task.deref().run();
@ -168,46 +173,58 @@ impl<T, F: Future<Output = T>> Task<T, F> {
} }
Self::dec_ref_count(task); Self::dec_ref_count(task);
} }
}
#[cold] #[cold]
unsafe fn task_runnable_dropped(task: *const Self) { unsafe fn task_runnable_dropped(task: *const Self) {
unsafe {
let task = task.deref(); let task = task.deref();
task.state.and_assign(!RUNNING); task.state.and_assign(!RUNNING);
if task.state.get() & CANCELLED != 0 { if task.state.get() & CANCELLED != 0 {
task.drop_data(); task.drop_data();
} }
} }
}
unsafe fn dec_ref_count(slf: *const Self) { unsafe fn dec_ref_count(slf: *const Self) {
unsafe {
if slf.deref().ref_count.fetch_sub(1) == 1 { if slf.deref().ref_count.fetch_sub(1) == 1 {
drop(Box::from_raw(slf as *mut Self)); drop(Box::from_raw(slf as *mut Self));
} }
} }
}
unsafe fn inc_ref_count(&self) { unsafe fn inc_ref_count(&self) {
self.ref_count.fetch_add(1); self.ref_count.fetch_add(1);
} }
unsafe fn waker_clone(data: *const ()) -> RawWaker { unsafe fn waker_clone(data: *const ()) -> RawWaker {
unsafe {
let task = &mut *(data as *mut Self); let task = &mut *(data as *mut Self);
task.inc_ref_count(); task.inc_ref_count();
RawWaker::new(data, Self::VTABLE) RawWaker::new(data, Self::VTABLE)
} }
}
unsafe fn waker_wake(data: *const ()) { unsafe fn waker_wake(data: *const ()) {
unsafe {
Self::waker_wake_by_ref(data); Self::waker_wake_by_ref(data);
Self::waker_drop(data); Self::waker_drop(data);
} }
}
unsafe fn waker_wake_by_ref(data: *const ()) { unsafe fn waker_wake_by_ref(data: *const ()) {
unsafe {
(data as *const Self).deref().schedule_run(); (data as *const Self).deref().schedule_run();
} }
}
unsafe fn waker_drop(data: *const ()) { unsafe fn waker_drop(data: *const ()) {
Self::dec_ref_count(data as _) unsafe { Self::dec_ref_count(data as _) }
} }
unsafe fn schedule_run(&self) { unsafe fn schedule_run(&self) {
unsafe {
if &self.state & (COMPLETED | CANCELLED) == 0 { if &self.state & (COMPLETED | CANCELLED) == 0 {
if &self.state & RUNNING == 0 { if &self.state & RUNNING == 0 {
self.state.or_assign(RUNNING); self.state.or_assign(RUNNING);
@ -225,8 +242,10 @@ impl<T, F: Future<Output = T>> Task<T, F> {
} }
} }
} }
}
unsafe fn run(&self) { unsafe fn run(&self) {
unsafe {
if &self.state & CANCELLED == 0 { if &self.state & CANCELLED == 0 {
let data = self.data.get().deref_mut(); let data = self.data.get().deref_mut();
self.inc_ref_count(); self.inc_ref_count();
@ -257,8 +276,10 @@ impl<T, F: Future<Output = T>> Task<T, F> {
self.schedule_run() self.schedule_run()
} }
} }
}
unsafe fn drop_data(&self) { unsafe fn drop_data(&self) {
unsafe {
if &self.state & COMPLETED == 0 { if &self.state & COMPLETED == 0 {
ManuallyDrop::drop(&mut self.data.get().deref_mut().future); ManuallyDrop::drop(&mut self.data.get().deref_mut().future);
} else if &self.state & EMPTIED == 0 { } else if &self.state & EMPTIED == 0 {
@ -266,3 +287,4 @@ impl<T, F: Future<Output = T>> Task<T, F> {
} }
} }
} }
}

View file

@ -194,12 +194,15 @@ thread_local! {
} }
unsafe fn kill() -> ! { unsafe fn kill() -> ! {
unsafe {
c::signal(c::SIGBUS, c::SIG_DFL); c::signal(c::SIGBUS, c::SIG_DFL);
raise(c::SIGBUS); raise(c::SIGBUS);
}
unreachable!(); unreachable!();
} }
unsafe extern "C" fn sigbus(sig: i32, info: &c::siginfo_t, _ucontext: *mut c::c_void) { unsafe extern "C" fn sigbus(sig: i32, info: &c::siginfo_t, _ucontext: *mut c::c_void) {
unsafe {
assert_eq!(sig, c::SIGBUS); assert_eq!(sig, c::SIGBUS);
let mut memr_ptr = MEM.get(); let mut memr_ptr = MEM.get();
while !memr_ptr.is_null() { while !memr_ptr.is_null() {
@ -228,6 +231,7 @@ unsafe extern "C" fn sigbus(sig: i32, info: &c::siginfo_t, _ucontext: *mut c::c_
} }
kill(); kill();
} }
}
pub fn init() -> Result<(), ClientMemError> { pub fn init() -> Result<(), ClientMemError> {
unsafe { unsafe {

View file

@ -170,8 +170,10 @@ unsafe extern "C" fn default_client_init(
extern "C" fn configure() { extern "C" fn configure() {
jay_toml_config::configure(); jay_toml_config::configure();
} }
unsafe {
jay_config::_private::client::init(srv_data, srv_unref, srv_handler, msg, size, configure) jay_config::_private::client::init(srv_data, srv_unref, srv_handler, msg, size, configure)
} }
}
impl ConfigProxy { impl ConfigProxy {
fn new( fn new(
@ -279,11 +281,11 @@ impl ConfigProxy {
return Err(ConfigError::CopyConfigFile(e)); return Err(ConfigError::CopyConfigFile(e));
} }
let unlink = UnlinkOnDrop(&copy); let unlink = UnlinkOnDrop(&copy);
let lib = match Library::new(&copy) { let lib = match unsafe { Library::new(&copy) } {
Ok(l) => l, Ok(l) => l,
Err(e) => return Err(ConfigError::CouldNotLoadLibrary(e)), Err(e) => return Err(ConfigError::CouldNotLoadLibrary(e)),
}; };
let entry = lib.get::<&'static ConfigEntry>(b"JAY_CONFIG_ENTRY_V1\0"); let entry = unsafe { lib.get::<&'static ConfigEntry>(b"JAY_CONFIG_ENTRY_V1\0") };
let entry = match entry { let entry = match entry {
Ok(e) => *e, Ok(e) => *e,
Err(e) => return Err(ConfigError::LibraryDoesNotContainEntry(e)), Err(e) => return Err(ConfigError::LibraryDoesNotContainEntry(e)),
@ -295,10 +297,13 @@ impl ConfigProxy {
unsafe extern "C" fn unref(data: *const u8) { unsafe extern "C" fn unref(data: *const u8) {
let server = data as *const ConfigProxyHandler; let server = data as *const ConfigProxyHandler;
unsafe {
drop(Rc::from_raw(server)); drop(Rc::from_raw(server));
} }
}
unsafe extern "C" fn handle_msg(data: *const u8, msg: *const u8, size: usize) { unsafe extern "C" fn handle_msg(data: *const u8, msg: *const u8, size: usize) {
unsafe {
let server = (data as *const ConfigProxyHandler).deref(); let server = (data as *const ConfigProxyHandler).deref();
if server.dropped.get() { if server.dropped.get() {
return; return;
@ -308,6 +313,7 @@ unsafe extern "C" fn handle_msg(data: *const u8, msg: *const u8, size: usize) {
rc.handle_request(msg); rc.handle_request(msg);
mem::forget(rc); mem::forget(rc);
} }
}
pub struct InvokedShortcut { pub struct InvokedShortcut {
pub unmasked_mods: Modifiers, pub unmasked_mods: Modifiers,

View file

@ -83,12 +83,12 @@ unsafe extern "C" fn egl_log(
_ => Level::Warn, _ => Level::Warn,
}; };
let command = if !command.is_null() { let command = if !command.is_null() {
CStr::from_ptr(command).to_bytes() unsafe { CStr::from_ptr(command).to_bytes() }
} else { } else {
b"none" b"none"
}; };
let message = if !message.is_null() { let message = if !message.is_null() {
CStr::from_ptr(message).to_bytes() unsafe { CStr::from_ptr(message).to_bytes() }
} else { } else {
b"none" b"none"
}; };

View file

@ -76,6 +76,7 @@ impl EglContext {
&self, &self,
f: F, f: F,
) -> Result<T, RenderError> { ) -> Result<T, RenderError> {
unsafe {
if (self.dpy.egl.eglMakeCurrent)( if (self.dpy.egl.eglMakeCurrent)(
self.dpy.dpy, self.dpy.dpy,
EGLSurface::none(), EGLSurface::none(),
@ -88,8 +89,12 @@ impl EglContext {
let prev = CURRENT.get(); let prev = CURRENT.get();
CURRENT.set(self.ctx); CURRENT.set(self.ctx);
let res = f(); let res = f();
if (self.dpy.egl.eglMakeCurrent)(self.dpy.dpy, EGLSurface::none(), EGLSurface::none(), prev) if (self.dpy.egl.eglMakeCurrent)(
== EGL_FALSE self.dpy.dpy,
EGLSurface::none(),
EGLSurface::none(),
prev,
) == EGL_FALSE
{ {
panic!("Could not restore EGLContext"); panic!("Could not restore EGLContext");
} }
@ -97,3 +102,4 @@ impl EglContext {
res res
} }
} }
}

View file

@ -312,21 +312,23 @@ unsafe fn query_formats(
) -> Result<AHashMap<u32, EglFormat>, RenderError> { ) -> Result<AHashMap<u32, EglFormat>, RenderError> {
let mut vec = vec![]; let mut vec = vec![];
let mut num = 0; let mut num = 0;
let res = procs.eglQueryDmaBufFormatsEXT(dpy, num, ptr::null_mut(), &mut num); let res = unsafe { procs.eglQueryDmaBufFormatsEXT(dpy, num, ptr::null_mut(), &mut num) };
if res != EGL_TRUE { if res != EGL_TRUE {
return Err(RenderError::QueryDmaBufFormats); return Err(RenderError::QueryDmaBufFormats);
} }
vec.reserve_exact(num as usize); vec.reserve_exact(num as usize);
let res = procs.eglQueryDmaBufFormatsEXT(dpy, num, vec.as_mut_ptr(), &mut num); let res = unsafe { procs.eglQueryDmaBufFormatsEXT(dpy, num, vec.as_mut_ptr(), &mut num) };
if res != EGL_TRUE { if res != EGL_TRUE {
return Err(RenderError::QueryDmaBufFormats); return Err(RenderError::QueryDmaBufFormats);
} }
unsafe {
vec.set_len(num as usize); vec.set_len(num as usize);
}
let mut res = AHashMap::new(); let mut res = AHashMap::new();
let formats = formats(); let formats = formats();
for fmt in vec { for fmt in vec {
if let Some(format) = formats.get(&(fmt as u32)) { if let Some(format) = formats.get(&(fmt as u32)) {
let (modifiers, external_only) = query_modifiers(procs, dpy, fmt, format)?; let (modifiers, external_only) = unsafe { query_modifiers(procs, dpy, fmt, format)? };
res.insert( res.insert(
format.drm, format.drm,
EglFormat { EglFormat {
@ -349,32 +351,38 @@ unsafe fn query_modifiers(
let mut mods = vec![]; let mut mods = vec![];
let mut ext_only = vec![]; let mut ext_only = vec![];
let mut num = 0; let mut num = 0;
let res = procs.eglQueryDmaBufModifiersEXT( let res = unsafe {
procs.eglQueryDmaBufModifiersEXT(
dpy, dpy,
gl_format, gl_format,
num, num,
ptr::null_mut(), ptr::null_mut(),
ptr::null_mut(), ptr::null_mut(),
&mut num, &mut num,
); )
};
if res != EGL_TRUE { if res != EGL_TRUE {
return Err(RenderError::QueryDmaBufModifiers); return Err(RenderError::QueryDmaBufModifiers);
} }
mods.reserve_exact(num as usize); mods.reserve_exact(num as usize);
ext_only.reserve_exact(num as usize); ext_only.reserve_exact(num as usize);
let res = procs.eglQueryDmaBufModifiersEXT( let res = unsafe {
procs.eglQueryDmaBufModifiersEXT(
dpy, dpy,
gl_format, gl_format,
num, num,
mods.as_mut_ptr(), mods.as_mut_ptr(),
ext_only.as_mut_ptr(), ext_only.as_mut_ptr(),
&mut num, &mut num,
); )
};
if res != EGL_TRUE { if res != EGL_TRUE {
return Err(RenderError::QueryDmaBufModifiers); return Err(RenderError::QueryDmaBufModifiers);
} }
unsafe {
mods.set_len(num as usize); mods.set_len(num as usize);
ext_only.set_len(num as usize); ext_only.set_len(num as usize);
}
let mut res = IndexMap::new(); let mut res = IndexMap::new();
for (modifier, ext_only) in mods.iter().copied().zip(ext_only.iter().copied()) { for (modifier, ext_only) in mods.iter().copied().zip(ext_only.iter().copied()) {
res.insert( res.insert(

View file

@ -19,7 +19,7 @@ unsafe fn get_extensions(ext: *const c::c_char) -> Option<AHashSet<String>> {
return None; return None;
} }
let mut res = AHashSet::new(); let mut res = AHashSet::new();
let ext = CStr::from_ptr(ext).to_bytes(); let ext = unsafe { CStr::from_ptr(ext).to_bytes() };
for part in ext.split_str(" ") { for part in ext.split_str(" ") {
let name = part.trim(); let name = part.trim();
if name.len() > 0 { if name.len() > 0 {
@ -32,9 +32,11 @@ unsafe fn get_extensions(ext: *const c::c_char) -> Option<AHashSet<String>> {
} }
unsafe fn get_dpy_extensions(dpy: EGLDisplay) -> Option<AHashSet<String>> { unsafe fn get_dpy_extensions(dpy: EGLDisplay) -> Option<AHashSet<String>> {
unsafe {
let ext = (EGL.as_ref()?.eglQueryString)(dpy, EGL_EXTENSIONS); let ext = (EGL.as_ref()?.eglQueryString)(dpy, EGL_EXTENSIONS);
get_extensions(ext) get_extensions(ext)
} }
}
fn get_typed_ext<T>(exts: &AHashSet<String>, mut base: T, map: &[(&str, T)]) -> T fn get_typed_ext<T>(exts: &AHashSet<String>, mut base: T, map: &[(&str, T)]) -> T
where where
@ -103,7 +105,7 @@ pub(crate) unsafe fn get_display_ext(dpy: EGLDisplay) -> DisplayExt {
("EGL_KHR_wait_sync", KHR_WAIT_SYNC), ("EGL_KHR_wait_sync", KHR_WAIT_SYNC),
("EGL_ANDROID_native_fence_sync", ANDROID_NATIVE_FENCE_SYNC), ("EGL_ANDROID_native_fence_sync", ANDROID_NATIVE_FENCE_SYNC),
]; ];
match get_dpy_extensions(dpy) { match unsafe { get_dpy_extensions(dpy) } {
Some(exts) => get_typed_ext(&exts, DisplayExt::none(), &map), Some(exts) => get_typed_ext(&exts, DisplayExt::none(), &map),
_ => DisplayExt::none(), _ => DisplayExt::none(),
} }

View file

@ -21,15 +21,18 @@ impl GlProgram {
vert: &str, vert: &str,
frag: &str, frag: &str,
) -> Result<Self, RenderError> { ) -> Result<Self, RenderError> {
unsafe {
let vert = GlShader::compile(ctx, GL_VERTEX_SHADER, vert)?; let vert = GlShader::compile(ctx, GL_VERTEX_SHADER, vert)?;
let frag = GlShader::compile(ctx, GL_FRAGMENT_SHADER, frag)?; let frag = GlShader::compile(ctx, GL_FRAGMENT_SHADER, frag)?;
Self::link(&vert, &frag) Self::link(&vert, &frag)
} }
}
pub(in crate::gfx_apis::gl) unsafe fn link( pub(in crate::gfx_apis::gl) unsafe fn link(
vert: &GlShader, vert: &GlShader,
frag: &GlShader, frag: &GlShader,
) -> Result<Self, RenderError> { ) -> Result<Self, RenderError> {
unsafe {
let gles = vert.ctx.dpy.gles; let gles = vert.ctx.dpy.gles;
let res = GlProgram { let res = GlProgram {
ctx: vert.ctx.clone(), ctx: vert.ctx.clone(),
@ -49,13 +52,14 @@ impl GlProgram {
Ok(res) Ok(res)
} }
}
pub unsafe fn get_uniform_location(&self, name: &CStr) -> GLint { pub unsafe fn get_uniform_location(&self, name: &CStr) -> GLint {
(self.ctx.dpy.gles.glGetUniformLocation)(self.prog, name.as_ptr() as _) unsafe { (self.ctx.dpy.gles.glGetUniformLocation)(self.prog, name.as_ptr() as _) }
} }
pub unsafe fn get_attrib_location(&self, name: &CStr) -> GLint { pub unsafe fn get_attrib_location(&self, name: &CStr) -> GLint {
(self.ctx.dpy.gles.glGetAttribLocation)(self.prog, name.as_ptr() as _) unsafe { (self.ctx.dpy.gles.glGetAttribLocation)(self.prog, name.as_ptr() as _) }
} }
} }

View file

@ -39,10 +39,17 @@ impl GlRenderBuffer {
}; };
let gles = &ctx.dpy.gles; let gles = &ctx.dpy.gles;
let mut rbo = 0; let mut rbo = 0;
unsafe {
(gles.glGenRenderbuffers)(1, &mut rbo); (gles.glGenRenderbuffers)(1, &mut rbo);
(gles.glBindRenderbuffer)(GL_RENDERBUFFER, rbo); (gles.glBindRenderbuffer)(GL_RENDERBUFFER, rbo);
(gles.glRenderbufferStorage)(GL_RENDERBUFFER, shm_info.gl_internal_format, width, height); (gles.glRenderbufferStorage)(
GL_RENDERBUFFER,
shm_info.gl_internal_format,
width,
height,
);
(gles.glBindRenderbuffer)(GL_RENDERBUFFER, 0); (gles.glBindRenderbuffer)(GL_RENDERBUFFER, 0);
}
Ok(Rc::new(GlRenderBuffer { Ok(Rc::new(GlRenderBuffer {
_img: None, _img: None,
ctx: ctx.clone(), ctx: ctx.clone(),
@ -63,12 +70,14 @@ impl GlRenderBuffer {
} }
let gles = ctx.dpy.gles; let gles = ctx.dpy.gles;
let mut rbo = 0; let mut rbo = 0;
unsafe {
(gles.glGenRenderbuffers)(1, &mut rbo); (gles.glGenRenderbuffers)(1, &mut rbo);
(gles.glBindRenderbuffer)(GL_RENDERBUFFER, rbo); (gles.glBindRenderbuffer)(GL_RENDERBUFFER, rbo);
ctx.dpy ctx.dpy
.procs .procs
.glEGLImageTargetRenderbufferStorageOES(GL_RENDERBUFFER, GLeglImageOES(img.img.0)); .glEGLImageTargetRenderbufferStorageOES(GL_RENDERBUFFER, GLeglImageOES(img.img.0));
(gles.glBindRenderbuffer)(GL_RENDERBUFFER, 0); (gles.glBindRenderbuffer)(GL_RENDERBUFFER, 0);
}
Ok(Rc::new(GlRenderBuffer { Ok(Rc::new(GlRenderBuffer {
_img: Some(img.clone()), _img: Some(img.clone()),
ctx: ctx.clone(), ctx: ctx.clone(),
@ -85,6 +94,7 @@ impl GlRenderBuffer {
) -> Result<GlFrameBuffer, RenderError> { ) -> Result<GlFrameBuffer, RenderError> {
let gles = self.ctx.dpy.gles; let gles = self.ctx.dpy.gles;
let mut fbo = 0; let mut fbo = 0;
unsafe {
(gles.glGenFramebuffers)(1, &mut fbo); (gles.glGenFramebuffers)(1, &mut fbo);
(gles.glBindFramebuffer)(GL_FRAMEBUFFER, fbo); (gles.glBindFramebuffer)(GL_FRAMEBUFFER, fbo);
(gles.glFramebufferRenderbuffer)( (gles.glFramebufferRenderbuffer)(
@ -109,6 +119,7 @@ impl GlRenderBuffer {
Ok(fb) Ok(fb)
} }
} }
}
impl Drop for GlRenderBuffer { impl Drop for GlRenderBuffer {
fn drop(&mut self) { fn drop(&mut self) {

View file

@ -20,17 +20,21 @@ impl GlShader {
src: &str, src: &str,
) -> Result<Self, RenderError> { ) -> Result<Self, RenderError> {
let gles = ctx.dpy.gles; let gles = ctx.dpy.gles;
let shader = (gles.glCreateShader)(ty); let shader = unsafe { (gles.glCreateShader)(ty) };
let res = GlShader { let res = GlShader {
ctx: ctx.clone(), ctx: ctx.clone(),
shader, shader,
}; };
let len = src.len() as _; let len = src.len() as _;
unsafe {
(gles.glShaderSource)(shader, 1, &(src.as_ptr() as _), &len); (gles.glShaderSource)(shader, 1, &(src.as_ptr() as _), &len);
(gles.glCompileShader)(shader); (gles.glCompileShader)(shader);
}
let mut ok = 0; let mut ok = 0;
unsafe {
(gles.glGetShaderiv)(shader, GL_COMPILE_STATUS, &mut ok); (gles.glGetShaderiv)(shader, GL_COMPILE_STATUS, &mut ok);
}
if ok == GL_FALSE as GLint { if ok == GL_FALSE as GLint {
return Err(RenderError::ShaderCompileFailed); return Err(RenderError::ShaderCompileFailed);
} }

View file

@ -44,6 +44,7 @@ pub(crate) struct TexProg {
impl TexProg { impl TexProg {
unsafe fn from(prog: GlProgram, alpha_multiplier: bool) -> Self { unsafe fn from(prog: GlProgram, alpha_multiplier: bool) -> Self {
unsafe {
let alpha = match alpha_multiplier { let alpha = match alpha_multiplier {
true => prog.get_uniform_location(c"alpha"), true => prog.get_uniform_location(c"alpha"),
false => 0, false => 0,
@ -57,6 +58,7 @@ impl TexProg {
} }
} }
} }
}
#[derive(Copy, Clone, PartialEq, Enum)] #[derive(Copy, Clone, PartialEq, Enum)]
pub(in crate::gfx_apis::gl) enum TexCopyType { pub(in crate::gfx_apis::gl) enum TexCopyType {
@ -129,8 +131,10 @@ impl GlRenderContext {
tex_frac_src.push_str("#define ALPHA\n"); tex_frac_src.push_str("#define ALPHA\n");
} }
tex_frac_src.push_str(tex_frag); tex_frac_src.push_str(tex_frag);
unsafe {
let prog = GlProgram::from_shaders(ctx, tex_vert, &tex_frac_src)?; let prog = GlProgram::from_shaders(ctx, tex_vert, &tex_frac_src)?;
Ok::<_, RenderError>(TexProg::from(prog, alpha_multiplier)) Ok::<_, RenderError>(TexProg::from(prog, alpha_multiplier))
}
}; };
Ok::<_, RenderError>(enum_map! { Ok::<_, RenderError>(enum_map! {
TexCopyType::Identity => enum_map! { TexCopyType::Identity => enum_map! {
@ -149,11 +153,13 @@ impl GlRenderContext {
} else { } else {
None None
}; };
let fill_prog = GlProgram::from_shaders( let fill_prog = unsafe {
GlProgram::from_shaders(
ctx, ctx,
include_str!("../shaders/fill.vert.glsl"), include_str!("../shaders/fill.vert.glsl"),
include_str!("../shaders/fill.frag.glsl"), include_str!("../shaders/fill.frag.glsl"),
)?; )?
};
Ok(Self { Ok(Self {
ctx: ctx.clone(), ctx: ctx.clone(),
gbm: ctx.dpy.gbm.clone(), gbm: ctx.dpy.gbm.clone(),
@ -164,8 +170,8 @@ impl GlRenderContext {
tex_internal, tex_internal,
tex_external, tex_external,
fill_prog_pos: fill_prog.get_attrib_location(c"pos"), fill_prog_pos: unsafe { fill_prog.get_attrib_location(c"pos") },
fill_prog_color: fill_prog.get_uniform_location(c"color"), fill_prog_color: unsafe { fill_prog.get_uniform_location(c"color") },
fill_prog, fill_prog,
gl_state: Default::default(), gl_state: Default::default(),

View file

@ -67,9 +67,11 @@ impl VulkanAllocation {
) { ) {
allocator.total.fetch_sub(self.size); allocator.total.fetch_sub(self.size);
let block = self.block.take().unwrap(); let block = self.block.take().unwrap();
unsafe {
do_free(gpu, &device.device, block, self.mem); do_free(gpu, &device.device, block, self.mem);
} }
} }
}
impl Drop for VulkanAllocation { impl Drop for VulkanAllocation {
fn drop(&mut self) { fn drop(&mut self) {
@ -363,6 +365,7 @@ unsafe fn do_free(
mut block: MemoryBlock<DeviceMemory>, mut block: MemoryBlock<DeviceMemory>,
ptr: Option<*mut u8>, ptr: Option<*mut u8>,
) { ) {
unsafe {
let device = AshMemoryDevice::wrap(device); let device = AshMemoryDevice::wrap(device);
if let Some(_ptr) = ptr { if let Some(_ptr) = ptr {
// log::info!("free = {:?} - {:?} ({})", ptr, ptr.add(block.size() as usize), block.size()); // log::info!("free = {:?} - {:?} ({})", ptr, ptr.add(block.size() as usize), block.size());
@ -370,6 +373,7 @@ unsafe fn do_free(
} }
gpu.dealloc(device, block); gpu.dealloc(device, block);
} }
}
impl Drop for UnsyncAllocatorStorage { impl Drop for UnsyncAllocatorStorage {
fn drop(&mut self) { fn drop(&mut self) {

View file

@ -671,7 +671,7 @@ impl Drop for VulkanBoMapping {
impl MappedBuffer for VulkanBoMapping { impl MappedBuffer for VulkanBoMapping {
unsafe fn data(&self) -> &[u8] { unsafe fn data(&self) -> &[u8] {
&*self.data unsafe { &*self.data }
} }
fn data_ptr(&self) -> *mut u8 { fn data_ptr(&self) -> *mut u8 {

View file

@ -190,12 +190,12 @@ unsafe extern "system" fn debug_callback(
DebugUtilsMessageSeverityFlagsEXT::VERBOSE => Level::Trace, DebugUtilsMessageSeverityFlagsEXT::VERBOSE => Level::Trace,
_ => Level::Warn, _ => Level::Warn,
}; };
let data = &*p_callback_data; let data = unsafe { &*p_callback_data };
let message = Ustr::from_ptr(data.p_message); let message = unsafe { Ustr::from_ptr(data.p_message) };
let message_id_name = if data.p_message_id_name.is_null() { let message_id_name = if data.p_message_id_name.is_null() {
ustr!("<null>") ustr!("<null>")
} else { } else {
Ustr::from_ptr(data.p_message_id_name) unsafe { Ustr::from_ptr(data.p_message_id_name) }
}; };
log::log!( log::log!(
Level::Info, Level::Info,

View file

@ -41,6 +41,7 @@ unsafe extern "C" fn open_restricted(
_flags: c::c_int, _flags: c::c_int,
user_data: *mut c::c_void, user_data: *mut c::c_void,
) -> c::c_int { ) -> c::c_int {
unsafe {
let ud = (user_data as *const UserData).deref(); let ud = (user_data as *const UserData).deref();
match ud.adapter.open(CStr::from_ptr(path)) { match ud.adapter.open(CStr::from_ptr(path)) {
Ok(f) => f.unwrap(), Ok(f) => f.unwrap(),
@ -50,6 +51,7 @@ unsafe extern "C" fn open_restricted(
} }
} }
} }
}
unsafe extern "C" fn close_restricted(fd: c::c_int, _user_data: *mut c::c_void) { unsafe extern "C" fn close_restricted(fd: c::c_int, _user_data: *mut c::c_void) {
drop(OwnedFd::new(fd)); drop(OwnedFd::new(fd));
@ -173,7 +175,7 @@ unsafe extern "C" fn jay_libinput_log_handler(
line: *const c::c_char, line: *const c::c_char,
) { ) {
assert!(line.is_not_null()); assert!(line.is_not_null());
let str = CStr::from_ptr(line); let str = unsafe { CStr::from_ptr(line) };
let priority = match LogPriority(priority as _) { let priority = match LogPriority(priority as _) {
LIBINPUT_LOG_PRIORITY_DEBUG => log::Level::Debug, LIBINPUT_LOG_PRIORITY_DEBUG => log::Level::Debug,
LIBINPUT_LOG_PRIORITY_INFO => log::Level::Info, LIBINPUT_LOG_PRIORITY_INFO => log::Level::Info,

View file

@ -37,7 +37,7 @@
clippy::unnecessary_cast, clippy::unnecessary_cast,
clippy::manual_flatten clippy::manual_flatten
)] )]
#![warn(clippy::allow_attributes)] #![warn(clippy::allow_attributes, unsafe_op_in_unsafe_fn)]
#[macro_use] #[macro_use]
mod macros; mod macros;

View file

@ -88,22 +88,24 @@ impl PwMemMap {
#[expect(dead_code)] #[expect(dead_code)]
pub unsafe fn read<T: Pod>(&self) -> &T { pub unsafe fn read<T: Pod>(&self) -> &T {
self.check::<T>(0); self.check::<T>(0);
(self.map.ptr.cast::<u8>().add(self.range.start) as *const T).deref() unsafe { (self.map.ptr.cast::<u8>().add(self.range.start) as *const T).deref() }
} }
#[expect(dead_code)] #[expect(dead_code)]
pub unsafe fn write<T: Pod>(&self) -> &mut T { pub unsafe fn write<T: Pod>(&self) -> &mut T {
self.check::<T>(0); self.check::<T>(0);
(self.map.ptr.cast::<u8>().add(self.range.start) as *mut T).deref_mut() unsafe { (self.map.ptr.cast::<u8>().add(self.range.start) as *mut T).deref_mut() }
} }
#[expect(dead_code)] #[expect(dead_code)]
pub unsafe fn bytes_mut(&self) -> &mut [u8] { pub unsafe fn bytes_mut(&self) -> &mut [u8] {
unsafe {
std::slice::from_raw_parts_mut( std::slice::from_raw_parts_mut(
self.map.ptr.cast::<u8>().add(self.range.start) as _, self.map.ptr.cast::<u8>().add(self.range.start) as _,
self.range.len(), self.range.len(),
) )
} }
}
fn check<T>(&self, offset: usize) { fn check<T>(&self, offset: usize) {
assert!(offset <= self.range.len()); assert!(offset <= self.range.len());
@ -136,11 +138,11 @@ impl PwMemMap {
impl<T: Pod> PwMemTyped<T> { impl<T: Pod> PwMemTyped<T> {
pub unsafe fn read(&self) -> &T { pub unsafe fn read(&self) -> &T {
(self.mem.map.ptr.cast::<u8>().add(self.offset) as *const T).deref() unsafe { (self.mem.map.ptr.cast::<u8>().add(self.offset) as *const T).deref() }
} }
pub unsafe fn write(&self) -> &mut T { pub unsafe fn write(&self) -> &mut T {
(self.mem.map.ptr.cast::<u8>().add(self.offset) as *mut T).deref_mut() unsafe { (self.mem.map.ptr.cast::<u8>().add(self.offset) as *mut T).deref_mut() }
} }
} }

View file

@ -241,7 +241,7 @@ impl Drop for UdmabufMap {
impl MappedBuffer for UdmabufMap { impl MappedBuffer for UdmabufMap {
unsafe fn data(&self) -> &[u8] { unsafe fn data(&self) -> &[u8] {
&*self.data unsafe { &*self.data }
} }
fn data_ptr(&self) -> *mut u8 { fn data_ptr(&self) -> *mut u8 {

View file

@ -296,10 +296,12 @@ struct NodeData<T> {
} }
unsafe fn dec_ref_count<T>(slf: NonNull<NodeData<T>>, n: usize) { unsafe fn dec_ref_count<T>(slf: NonNull<NodeData<T>>, n: usize) {
unsafe {
if slf.as_ref().rc.fetch_sub(n) == n { if slf.as_ref().rc.fetch_sub(n) == n {
drop(Box::from_raw(slf.as_ptr())); drop(Box::from_raw(slf.as_ptr()));
} }
} }
}
impl<T> Drop for LinkedNode<T> { impl<T> Drop for LinkedNode<T> {
fn drop(&mut self) { fn drop(&mut self) {
@ -337,6 +339,7 @@ impl<T> LinkedNode<T> {
} }
unsafe fn prepend_existing<T>(data: NonNull<NodeData<T>>, t: &NodeRef<T>) { unsafe fn prepend_existing<T>(data: NonNull<NodeData<T>>, t: &NodeRef<T>) {
unsafe {
let dref = data.as_ref(); let dref = data.as_ref();
let tref = t.data.as_ref(); let tref = t.data.as_ref();
if tref.rc.get() < LINKED_NODE_REF_COUNT { if tref.rc.get() < LINKED_NODE_REF_COUNT {
@ -349,8 +352,10 @@ unsafe fn prepend_existing<T>(data: NonNull<NodeData<T>>, t: &NodeRef<T>) {
dref.prev.get().as_ref().next.set(t.data); dref.prev.get().as_ref().next.set(t.data);
dref.prev.set(t.data); dref.prev.set(t.data);
} }
}
unsafe fn prepend<T>(data: NonNull<NodeData<T>>, t: T) -> LinkedNode<T> { unsafe fn prepend<T>(data: NonNull<NodeData<T>>, t: T) -> LinkedNode<T> {
unsafe {
let dref = data.as_ref(); let dref = data.as_ref();
let node = NonNull::new_unchecked(Box::into_raw(Box::new(NodeData { let node = NonNull::new_unchecked(Box::into_raw(Box::new(NodeData {
rc: NumCell::new(LINKED_NODE_REF_COUNT), rc: NumCell::new(LINKED_NODE_REF_COUNT),
@ -362,8 +367,10 @@ unsafe fn prepend<T>(data: NonNull<NodeData<T>>, t: T) -> LinkedNode<T> {
dref.prev.set(node); dref.prev.set(node);
LinkedNode { data: node } LinkedNode { data: node }
} }
}
unsafe fn append_existing<T>(data: NonNull<NodeData<T>>, t: &NodeRef<T>) { unsafe fn append_existing<T>(data: NonNull<NodeData<T>>, t: &NodeRef<T>) {
unsafe {
let dref = data.as_ref(); let dref = data.as_ref();
let tref = t.data.as_ref(); let tref = t.data.as_ref();
if tref.rc.get() < LINKED_NODE_REF_COUNT { if tref.rc.get() < LINKED_NODE_REF_COUNT {
@ -376,8 +383,10 @@ unsafe fn append_existing<T>(data: NonNull<NodeData<T>>, t: &NodeRef<T>) {
dref.next.get().as_ref().prev.set(t.data); dref.next.get().as_ref().prev.set(t.data);
dref.next.set(t.data); dref.next.set(t.data);
} }
}
unsafe fn append<T>(data: NonNull<NodeData<T>>, t: T) -> LinkedNode<T> { unsafe fn append<T>(data: NonNull<NodeData<T>>, t: T) -> LinkedNode<T> {
unsafe {
let dref = data.as_ref(); let dref = data.as_ref();
let node = NonNull::new_unchecked(Box::into_raw(Box::new(NodeData { let node = NonNull::new_unchecked(Box::into_raw(Box::new(NodeData {
rc: NumCell::new(LINKED_NODE_REF_COUNT), rc: NumCell::new(LINKED_NODE_REF_COUNT),
@ -389,3 +398,4 @@ unsafe fn append<T>(data: NonNull<NodeData<T>>, t: T) -> LinkedNode<T> {
dref.next.set(node); dref.next.set(node);
LinkedNode { data: node } LinkedNode { data: node }
} }
}

View file

@ -9,20 +9,20 @@ pub trait MutPtrExt<T: ?Sized> {
impl<T: ?Sized> PtrExt<T> for *const T { impl<T: ?Sized> PtrExt<T> for *const T {
#[inline(always)] #[inline(always)]
unsafe fn deref<'a>(self) -> &'a T { unsafe fn deref<'a>(self) -> &'a T {
&*self unsafe { &*self }
} }
} }
impl<T: ?Sized> PtrExt<T> for *mut T { impl<T: ?Sized> PtrExt<T> for *mut T {
#[inline(always)] #[inline(always)]
unsafe fn deref<'a>(self) -> &'a T { unsafe fn deref<'a>(self) -> &'a T {
&*self unsafe { &*self }
} }
} }
impl<T: ?Sized> MutPtrExt<T> for *mut T { impl<T: ?Sized> MutPtrExt<T> for *mut T {
#[inline(always)] #[inline(always)]
unsafe fn deref_mut<'a>(self) -> &'a mut T { unsafe fn deref_mut<'a>(self) -> &'a mut T {
&mut *self unsafe { &mut *self }
} }
} }

View file

@ -35,7 +35,7 @@ impl<T> VecStorage<T> {
} }
unsafe fn to_vector<U>(&mut self) -> Vec<U> { unsafe fn to_vector<U>(&mut self) -> Vec<U> {
Vec::from_raw_parts(self.ptr as _, 0, self.cap) unsafe { Vec::from_raw_parts(self.ptr as _, 0, self.cap) }
} }
} }

View file

@ -23,7 +23,7 @@ use {
pub unsafe fn ioctl<T>(fd: c::c_int, request: c::c_ulong, t: &mut T) -> Result<c::c_int, OsError> { pub unsafe fn ioctl<T>(fd: c::c_int, request: c::c_ulong, t: &mut T) -> Result<c::c_int, OsError> {
let mut ret; let mut ret;
loop { loop {
ret = c::ioctl(fd, request, &mut *t); ret = unsafe { c::ioctl(fd, request, &mut *t) };
if ret != -1 { if ret != -1 {
return Ok(ret); return Ok(ret);
} }

View file

@ -158,7 +158,7 @@ pub struct GbmBoMap {
impl MappedBuffer for GbmBoMap { impl MappedBuffer for GbmBoMap {
unsafe fn data(&self) -> &[u8] { unsafe fn data(&self) -> &[u8] {
&*self.data unsafe { &*self.data }
} }
fn data_ptr(&self) -> *mut u8 { fn data_ptr(&self) -> *mut u8 {
@ -171,6 +171,7 @@ impl MappedBuffer for GbmBoMap {
} }
unsafe fn export_bo(dmabuf_ids: &DmaBufIds, bo: *mut Bo) -> Result<DmaBuf, GbmError> { unsafe fn export_bo(dmabuf_ids: &DmaBufIds, bo: *mut Bo) -> Result<DmaBuf, GbmError> {
unsafe {
Ok(DmaBuf { Ok(DmaBuf {
id: dmabuf_ids.next(), id: dmabuf_ids.next(),
width: gbm_bo_get_width(bo) as _, width: gbm_bo_get_width(bo) as _,
@ -202,6 +203,7 @@ unsafe fn export_bo(dmabuf_ids: &DmaBufIds, bo: *mut Bo) -> Result<DmaBuf, GbmEr
}, },
}) })
} }
}
impl GbmDevice { impl GbmDevice {
pub fn new(drm: &Drm) -> Result<Self, GbmError> { pub fn new(drm: &Drm) -> Result<Self, GbmError> {

View file

@ -415,7 +415,7 @@ unsafe extern "C" fn jay_xkbcommon_log_handler(
line: *const c::c_char, line: *const c::c_char,
) { ) {
assert!(line.is_not_null()); assert!(line.is_not_null());
let buf = CStr::from_ptr(line); let buf = unsafe { CStr::from_ptr(line) };
let level = match XkbLogLevel(level) { let level = match XkbLogLevel(level) {
XKB_LOG_LEVEL_CRITICAL | XKB_LOG_LEVEL_ERROR => log::Level::Error, XKB_LOG_LEVEL_CRITICAL | XKB_LOG_LEVEL_ERROR => log::Level::Error,
XKB_LOG_LEVEL_WARNING => log::Level::Warn, XKB_LOG_LEVEL_WARNING => log::Level::Warn,