From b74219aafd6977a99de7e52bc47f956b0b45cb01 Mon Sep 17 00:00:00 2001 From: Martin Pitt Date: Fri, 27 Aug 2021 09:27:37 +0200 Subject: [PATCH] Implement the rest of c-mounts.c in Rust Use errno crate for human-readable error formatting. --- call-c-from-rust/Cargo.toml | 1 + call-c-from-rust/src/main.rs | 29 +++++++++++++++++++++++++++++ 2 files changed, 30 insertions(+) diff --git a/call-c-from-rust/Cargo.toml b/call-c-from-rust/Cargo.toml index 535c6b9..b01f48a 100644 --- a/call-c-from-rust/Cargo.toml +++ b/call-c-from-rust/Cargo.toml @@ -6,3 +6,4 @@ edition = "2018" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html [dependencies] +errno = "*" diff --git a/call-c-from-rust/src/main.rs b/call-c-from-rust/src/main.rs index b453d81..ee94586 100644 --- a/call-c-from-rust/src/main.rs +++ b/call-c-from-rust/src/main.rs @@ -1,10 +1,39 @@ mod libmount; use std::ffi::CStr; +use std::ptr; +use std::process; + +extern crate errno; + +fn check_call(error: i32, msg: &str) { + if error < 0 { + errno::set_errno(errno::Errno(-error)); + eprintln!("ERROR: {}: {}", msg, errno::errno()); + process::exit(1); + } +} fn main() { let fstab_path_cstr: &CStr = unsafe { CStr::from_ptr (libmount::mnt_get_fstab_path()) }; println!("fstab path C-String: {:?}", fstab_path_cstr); let fstab_path = fstab_path_cstr.to_str().unwrap(); // may cause UTF-8 decoding error println!("fstab path str: {}", fstab_path); + + let mut version = ptr::null(); + check_call(unsafe { libmount::mnt_get_library_version(ptr::addr_of_mut!(version)) }, + "Failed to get lib version"); + println!("libmount version: {:?}", unsafe { CStr::from_ptr(version) }); + + let table = unsafe { libmount::mnt_new_table() }; + check_call(unsafe {libmount::mnt_table_parse_mtab(table, ptr::null()) }, + "Failed to parse mtab"); + let mut fs = ptr::null_mut(); + check_call(unsafe { libmount::mnt_table_first_fs(table, &mut fs) }, + "Failed to find first fs"); + + println!("first fs type: {:?} source: {:?} target: {:?}", + unsafe { CStr::from_ptr (libmount::mnt_fs_get_fstype(fs)) }, + unsafe { CStr::from_ptr (libmount::mnt_fs_get_source(fs)) }, + unsafe { CStr::from_ptr (libmount::mnt_fs_get_target(fs)) }); } -- 2.39.5