Migration to Edition 2024

This commit is contained in:
topjohnwu 2025-03-06 23:04:02 -08:00 committed by John Wu
parent a43c1267d8
commit c90e73ccec
23 changed files with 568 additions and 437 deletions

View File

@ -5,7 +5,7 @@ resolver = "2"
[workspace.package] [workspace.package]
version = "0.0.0" version = "0.0.0"
edition = "2021" edition = "2024"
[workspace.dependencies] [workspace.dependencies]
cxx = { path = "external/cxx-rs" } cxx = { path = "external/cxx-rs" }

View File

@ -1,7 +1,7 @@
use crate::gen::gen_cxx_binding; use crate::codegen::gen_cxx_binding;
#[path = "../include/gen.rs"] #[path = "../include/codegen.rs"]
mod gen; mod codegen;
fn main() { fn main() {
gen_cxx_binding("base-rs"); gen_cxx_binding("base-rs");

View File

@ -62,7 +62,7 @@ pub mod cstr_buf {
#[inline(always)] #[inline(always)]
pub unsafe fn wrap_ptr<'a>(buf: *mut u8, len: usize) -> Utf8CStrBufRef<'a> { pub unsafe fn wrap_ptr<'a>(buf: *mut u8, len: usize) -> Utf8CStrBufRef<'a> {
Utf8CStrBufRef::from_ptr(buf, len) unsafe { Utf8CStrBufRef::from_ptr(buf, len) }
} }
} }
@ -232,7 +232,9 @@ impl Utf8CStrBuf for Utf8CString {
} }
unsafe fn set_len(&mut self, len: usize) { unsafe fn set_len(&mut self, len: usize) {
self.0.as_mut_vec().set_len(len); unsafe {
self.0.as_mut_vec().set_len(len);
}
} }
fn push_str(&mut self, s: &str) -> usize { fn push_str(&mut self, s: &str) -> usize {
@ -277,7 +279,7 @@ pub struct Utf8CStrBufRef<'a> {
impl<'a> Utf8CStrBufRef<'a> { impl<'a> Utf8CStrBufRef<'a> {
pub unsafe fn from_ptr(buf: *mut u8, len: usize) -> Utf8CStrBufRef<'a> { pub unsafe fn from_ptr(buf: *mut u8, len: usize) -> Utf8CStrBufRef<'a> {
Self::from(slice_from_ptr_mut(buf, len)) unsafe { Self::from(slice_from_ptr_mut(buf, len)) }
} }
} }
@ -366,12 +368,12 @@ impl Utf8CStr {
#[inline(always)] #[inline(always)]
pub const unsafe fn from_bytes_unchecked(buf: &[u8]) -> &Utf8CStr { pub const unsafe fn from_bytes_unchecked(buf: &[u8]) -> &Utf8CStr {
mem::transmute(buf) unsafe { mem::transmute(buf) }
} }
#[inline(always)] #[inline(always)]
unsafe fn from_bytes_unchecked_mut(buf: &mut [u8]) -> &mut Utf8CStr { unsafe fn from_bytes_unchecked_mut(buf: &mut [u8]) -> &mut Utf8CStr {
mem::transmute(buf) unsafe { mem::transmute(buf) }
} }
pub unsafe fn from_ptr<'a>(ptr: *const c_char) -> Result<&'a Utf8CStr, StrErr> { pub unsafe fn from_ptr<'a>(ptr: *const c_char) -> Result<&'a Utf8CStr, StrErr> {
@ -382,8 +384,10 @@ impl Utf8CStr {
} }
pub unsafe fn from_ptr_unchecked<'a>(ptr: *const c_char) -> &'a Utf8CStr { pub unsafe fn from_ptr_unchecked<'a>(ptr: *const c_char) -> &'a Utf8CStr {
let cstr = CStr::from_ptr(ptr); unsafe {
Self::from_bytes_unchecked(cstr.to_bytes_with_nul()) let cstr = CStr::from_ptr(ptr);
Self::from_bytes_unchecked(cstr.to_bytes_with_nul())
}
} }
#[inline(always)] #[inline(always)]

View File

@ -20,36 +20,42 @@ pub(crate) fn fd_path_for_cxx(fd: RawFd, buf: &mut [u8]) -> isize {
.map_or(-1_isize, |_| buf.len() as isize) .map_or(-1_isize, |_| buf.len() as isize)
} }
#[no_mangle] #[unsafe(no_mangle)]
unsafe extern "C" fn canonical_path(path: *const c_char, buf: *mut u8, bufsz: usize) -> isize { unsafe extern "C" fn canonical_path(path: *const c_char, buf: *mut u8, bufsz: usize) -> isize {
match Utf8CStr::from_ptr(path) { unsafe {
Ok(p) => { match Utf8CStr::from_ptr(path) {
let mut buf = cstr_buf::wrap_ptr(buf, bufsz); Ok(p) => {
FsPath::from(p) let mut buf = cstr_buf::wrap_ptr(buf, bufsz);
.realpath(&mut buf) FsPath::from(p)
.map_or(-1, |_| buf.len() as isize) .realpath(&mut buf)
.map_or(-1, |_| buf.len() as isize)
}
Err(_) => -1,
} }
Err(_) => -1,
} }
} }
#[export_name = "mkdirs"] #[unsafe(export_name = "mkdirs")]
unsafe extern "C" fn mkdirs_for_cxx(path: *const c_char, mode: mode_t) -> i32 { unsafe extern "C" fn mkdirs_for_cxx(path: *const c_char, mode: mode_t) -> i32 {
match Utf8CStr::from_ptr(path) { unsafe {
Ok(p) => FsPath::from(p).mkdirs(mode).map_or(-1, |_| 0), match Utf8CStr::from_ptr(path) {
Err(_) => -1, Ok(p) => FsPath::from(p).mkdirs(mode).map_or(-1, |_| 0),
Err(_) => -1,
}
} }
} }
#[export_name = "rm_rf"] #[unsafe(export_name = "rm_rf")]
unsafe extern "C" fn rm_rf_for_cxx(path: *const c_char) -> bool { unsafe extern "C" fn rm_rf_for_cxx(path: *const c_char) -> bool {
match Utf8CStr::from_ptr(path) { unsafe {
Ok(p) => FsPath::from(p).remove_all().is_ok(), match Utf8CStr::from_ptr(path) {
Err(_) => false, Ok(p) => FsPath::from(p).remove_all().is_ok(),
Err(_) => false,
}
} }
} }
#[no_mangle] #[unsafe(no_mangle)]
unsafe extern "C" fn frm_rf(fd: OwnedFd) -> bool { unsafe extern "C" fn frm_rf(fd: OwnedFd) -> bool {
fn inner(fd: OwnedFd) -> io::Result<()> { fn inner(fd: OwnedFd) -> io::Result<()> {
Directory::try_from(fd)?.remove_all() Directory::try_from(fd)?.remove_all()
@ -83,110 +89,122 @@ pub(crate) unsafe fn readlinkat_for_cxx(
buf: *mut u8, buf: *mut u8,
bufsz: usize, bufsz: usize,
) -> isize { ) -> isize {
// readlinkat() may fail on x86 platform, returning random value unsafe {
// instead of number of bytes placed in buf (length of link) // readlinkat() may fail on x86 platform, returning random value
cfg_if! { // instead of number of bytes placed in buf (length of link)
if #[cfg(any(target_arch = "x86", target_arch = "x86_64"))] { cfg_if! {
libc::memset(buf.cast(), 0, bufsz); if #[cfg(any(target_arch = "x86", target_arch = "x86_64"))] {
let mut r = libc::readlinkat(dirfd, path, buf.cast(), bufsz - 1); libc::memset(buf.cast(), 0, bufsz);
if r > 0 { let mut r = libc::readlinkat(dirfd, path, buf.cast(), bufsz - 1);
r = libc::strlen(buf.cast()) as isize; if r > 0 {
} r = libc::strlen(buf.cast()) as isize;
} else { }
let r = libc::readlinkat(dirfd, path, buf.cast(), bufsz - 1); } else {
if r >= 0 { let r = libc::readlinkat(dirfd, path, buf.cast(), bufsz - 1);
*buf.offset(r) = b'\0'; if r >= 0 {
*buf.offset(r) = b'\0';
}
} }
} }
r
} }
r
} }
#[export_name = "cp_afc"] #[unsafe(export_name = "cp_afc")]
unsafe extern "C" fn cp_afc_for_cxx(src: *const c_char, dest: *const c_char) -> bool { unsafe extern "C" fn cp_afc_for_cxx(src: *const c_char, dest: *const c_char) -> bool {
if let Ok(src) = Utf8CStr::from_ptr(src) { unsafe {
if let Ok(dest) = Utf8CStr::from_ptr(dest) { if let Ok(src) = Utf8CStr::from_ptr(src) {
let src = FsPath::from(src); if let Ok(dest) = Utf8CStr::from_ptr(dest) {
let dest = FsPath::from(dest); let src = FsPath::from(src);
return src let dest = FsPath::from(dest);
.copy_to(dest) return src
.log_cxx_with_msg(|w| { .copy_to(dest)
w.write_fmt(format_args!("cp_afc {} -> {} failed", src, dest)) .log_cxx_with_msg(|w| {
}) w.write_fmt(format_args!("cp_afc {} -> {} failed", src, dest))
.is_ok(); })
.is_ok();
}
} }
false
} }
false
} }
#[export_name = "mv_path"] #[unsafe(export_name = "mv_path")]
unsafe extern "C" fn mv_path_for_cxx(src: *const c_char, dest: *const c_char) -> bool { unsafe extern "C" fn mv_path_for_cxx(src: *const c_char, dest: *const c_char) -> bool {
if let Ok(src) = Utf8CStr::from_ptr(src) { unsafe {
if let Ok(dest) = Utf8CStr::from_ptr(dest) { if let Ok(src) = Utf8CStr::from_ptr(src) {
let src = FsPath::from(src); if let Ok(dest) = Utf8CStr::from_ptr(dest) {
let dest = FsPath::from(dest); let src = FsPath::from(src);
return src let dest = FsPath::from(dest);
.move_to(dest) return src
.log_cxx_with_msg(|w| { .move_to(dest)
w.write_fmt(format_args!("mv_path {} -> {} failed", src, dest)) .log_cxx_with_msg(|w| {
}) w.write_fmt(format_args!("mv_path {} -> {} failed", src, dest))
.is_ok(); })
.is_ok();
}
} }
false
} }
false
} }
#[export_name = "link_path"] #[unsafe(export_name = "link_path")]
unsafe extern "C" fn link_path_for_cxx(src: *const c_char, dest: *const c_char) -> bool { unsafe extern "C" fn link_path_for_cxx(src: *const c_char, dest: *const c_char) -> bool {
if let Ok(src) = Utf8CStr::from_ptr(src) { unsafe {
if let Ok(dest) = Utf8CStr::from_ptr(dest) { if let Ok(src) = Utf8CStr::from_ptr(src) {
let src = FsPath::from(src); if let Ok(dest) = Utf8CStr::from_ptr(dest) {
let dest = FsPath::from(dest); let src = FsPath::from(src);
return src let dest = FsPath::from(dest);
.link_to(dest) return src
.log_cxx_with_msg(|w| { .link_to(dest)
w.write_fmt(format_args!("link_path {} -> {} failed", src, dest)) .log_cxx_with_msg(|w| {
}) w.write_fmt(format_args!("link_path {} -> {} failed", src, dest))
.is_ok(); })
.is_ok();
}
} }
false
} }
false
} }
#[export_name = "clone_attr"] #[unsafe(export_name = "clone_attr")]
unsafe extern "C" fn clone_attr_for_cxx(src: *const c_char, dest: *const c_char) -> bool { unsafe extern "C" fn clone_attr_for_cxx(src: *const c_char, dest: *const c_char) -> bool {
if let Ok(src) = Utf8CStr::from_ptr(src) { unsafe {
if let Ok(dest) = Utf8CStr::from_ptr(dest) { if let Ok(src) = Utf8CStr::from_ptr(src) {
let src = FsPath::from(src); if let Ok(dest) = Utf8CStr::from_ptr(dest) {
let dest = FsPath::from(dest); let src = FsPath::from(src);
return clone_attr(src, dest) let dest = FsPath::from(dest);
.log_cxx_with_msg(|w| { return clone_attr(src, dest)
w.write_fmt(format_args!("clone_attr {} -> {} failed", src, dest)) .log_cxx_with_msg(|w| {
}) w.write_fmt(format_args!("clone_attr {} -> {} failed", src, dest))
.is_ok(); })
.is_ok();
}
} }
false
} }
false
} }
#[export_name = "fclone_attr"] #[unsafe(export_name = "fclone_attr")]
unsafe extern "C" fn fclone_attr_for_cxx(a: RawFd, b: RawFd) -> bool { unsafe extern "C" fn fclone_attr_for_cxx(a: RawFd, b: RawFd) -> bool {
fclone_attr(a, b) fclone_attr(a, b)
.log_cxx_with_msg(|w| w.write_str("fclone_attr failed")) .log_cxx_with_msg(|w| w.write_str("fclone_attr failed"))
.is_ok() .is_ok()
} }
#[export_name = "cxx$utf8str$new"] #[unsafe(export_name = "cxx$utf8str$new")]
unsafe extern "C" fn str_new(this: &mut &Utf8CStr, s: *const u8, len: usize) { unsafe extern "C" fn str_new(this: &mut &Utf8CStr, s: *const u8, len: usize) {
*this = Utf8CStr::from_bytes(slice_from_ptr(s, len)).unwrap_or(cstr!("")); unsafe {
*this = Utf8CStr::from_bytes(slice_from_ptr(s, len)).unwrap_or(cstr!(""));
}
} }
#[export_name = "cxx$utf8str$ptr"] #[unsafe(export_name = "cxx$utf8str$ptr")]
unsafe extern "C" fn str_ptr(this: &&Utf8CStr) -> *const u8 { unsafe extern "C" fn str_ptr(this: &&Utf8CStr) -> *const u8 {
this.as_ptr().cast() this.as_ptr().cast()
} }
#[export_name = "cxx$utf8str$len"] #[unsafe(export_name = "cxx$utf8str$len")]
unsafe extern "C" fn str_len(this: &&Utf8CStr) -> usize { unsafe extern "C" fn str_len(this: &&Utf8CStr) -> usize {
this.len() this.len()
} }

View File

@ -263,7 +263,7 @@ impl DirEntry<'_> {
} }
unsafe fn open_fd(&self, flags: i32) -> io::Result<RawFd> { unsafe fn open_fd(&self, flags: i32) -> io::Result<RawFd> {
self.dir.open_raw_fd(self.name(), flags, 0) unsafe { self.dir.open_raw_fd(self.name(), flags, 0) }
} }
pub fn open_as_dir(&self) -> io::Result<Directory> { pub fn open_as_dir(&self) -> io::Result<Directory> {
@ -361,7 +361,9 @@ impl Directory {
} }
unsafe fn open_raw_fd(&self, name: &CStr, flags: i32, mode: i32) -> io::Result<RawFd> { unsafe fn open_raw_fd(&self, name: &CStr, flags: i32, mode: i32) -> io::Result<RawFd> {
libc::openat(self.as_raw_fd(), name.as_ptr(), flags | O_CLOEXEC, mode).check_os_err() unsafe {
libc::openat(self.as_raw_fd(), name.as_ptr(), flags | O_CLOEXEC, mode).check_os_err()
}
} }
pub fn open_fd(&self, name: &Utf8CStr, flags: i32, mode: i32) -> io::Result<OwnedFd> { pub fn open_fd(&self, name: &Utf8CStr, flags: i32, mode: i32) -> io::Result<OwnedFd> {
@ -929,7 +931,7 @@ impl Drop for MappedFile {
} }
} }
extern "C" { unsafe extern "C" {
// Don't use the declaration from the libc crate as request should be u32 not i32 // Don't use the declaration from the libc crate as request should be u32 not i32
fn ioctl(fd: RawFd, request: u32, ...) -> i32; fn ioctl(fd: RawFd, request: u32, ...) -> i32;
} }

View File

@ -16,20 +16,24 @@ pub fn errno() -> &'static mut i32 {
// When len is 0, don't care whether buf is null or not // When len is 0, don't care whether buf is null or not
#[inline] #[inline]
pub unsafe fn slice_from_ptr<'a, T>(buf: *const T, len: usize) -> &'a [T] { pub unsafe fn slice_from_ptr<'a, T>(buf: *const T, len: usize) -> &'a [T] {
if len == 0 { unsafe {
&[] if len == 0 {
} else { &[]
slice::from_raw_parts(buf, len) } else {
slice::from_raw_parts(buf, len)
}
} }
} }
// When len is 0, don't care whether buf is null or not // When len is 0, don't care whether buf is null or not
#[inline] #[inline]
pub unsafe fn slice_from_ptr_mut<'a, T>(buf: *mut T, len: usize) -> &'a mut [T] { pub unsafe fn slice_from_ptr_mut<'a, T>(buf: *mut T, len: usize) -> &'a mut [T] {
if len == 0 { unsafe {
&mut [] if len == 0 {
} else { &mut []
slice::from_raw_parts_mut(buf, len) } else {
slice::from_raw_parts_mut(buf, len)
}
} }
} }

View File

@ -50,93 +50,107 @@ mod c_export {
use crate::{slice_from_ptr, slice_from_ptr_mut}; use crate::{slice_from_ptr, slice_from_ptr_mut};
#[no_mangle] #[unsafe(no_mangle)]
unsafe extern "C" fn xwrite(fd: RawFd, buf: *const u8, bufsz: usize) -> isize { unsafe extern "C" fn xwrite(fd: RawFd, buf: *const u8, bufsz: usize) -> isize {
super::xwrite(fd, slice_from_ptr(buf, bufsz)) unsafe { super::xwrite(fd, slice_from_ptr(buf, bufsz)) }
} }
#[no_mangle] #[unsafe(no_mangle)]
unsafe extern "C" fn xxread(fd: RawFd, buf: *mut u8, bufsz: usize) -> isize { unsafe extern "C" fn xxread(fd: RawFd, buf: *mut u8, bufsz: usize) -> isize {
super::xxread(fd, slice_from_ptr_mut(buf, bufsz)) unsafe { super::xxread(fd, slice_from_ptr_mut(buf, bufsz)) }
} }
} }
#[no_mangle] #[unsafe(no_mangle)]
unsafe extern "C" fn xrealpath(path: *const c_char, buf: *mut u8, bufsz: usize) -> isize { unsafe extern "C" fn xrealpath(path: *const c_char, buf: *mut u8, bufsz: usize) -> isize {
match Utf8CStr::from_ptr(path) { unsafe {
Ok(p) => { match Utf8CStr::from_ptr(path) {
let mut buf = Utf8CStrBufRef::from_ptr(buf, bufsz); Ok(p) => {
FsPath::from(p) let mut buf = Utf8CStrBufRef::from_ptr(buf, bufsz);
.realpath(&mut buf) FsPath::from(p)
.log_cxx_with_msg(|w| w.write_fmt(format_args!("realpath {} failed", p))) .realpath(&mut buf)
.map_or(-1, |_| buf.len() as isize) .log_cxx_with_msg(|w| w.write_fmt(format_args!("realpath {} failed", p)))
.map_or(-1, |_| buf.len() as isize)
}
Err(_) => -1,
} }
Err(_) => -1,
} }
} }
#[no_mangle] #[unsafe(no_mangle)]
unsafe extern "C" fn xreadlink(path: *const c_char, buf: *mut u8, bufsz: usize) -> isize { unsafe extern "C" fn xreadlink(path: *const c_char, buf: *mut u8, bufsz: usize) -> isize {
match Utf8CStr::from_ptr(path) { unsafe {
Ok(p) => { match Utf8CStr::from_ptr(path) {
let mut buf = Utf8CStrBufRef::from_ptr(buf, bufsz); Ok(p) => {
FsPath::from(p) let mut buf = Utf8CStrBufRef::from_ptr(buf, bufsz);
.read_link(&mut buf) FsPath::from(p)
.log_cxx_with_msg(|w| w.write_fmt(format_args!("readlink {} failed", p))) .read_link(&mut buf)
.map_or(-1, |_| buf.len() as isize) .log_cxx_with_msg(|w| w.write_fmt(format_args!("readlink {} failed", p)))
.map_or(-1, |_| buf.len() as isize)
}
Err(_) => -1,
} }
Err(_) => -1,
} }
} }
#[no_mangle] #[unsafe(no_mangle)]
unsafe extern "C" fn xreadlinkat( unsafe extern "C" fn xreadlinkat(
dirfd: RawFd, dirfd: RawFd,
path: *const c_char, path: *const c_char,
buf: *mut u8, buf: *mut u8,
bufsz: usize, bufsz: usize,
) -> isize { ) -> isize {
let r = readlinkat_for_cxx(dirfd, path, buf, bufsz); unsafe {
if r < 0 { let r = readlinkat_for_cxx(dirfd, path, buf, bufsz);
perror!("readlinkat {}", ptr_to_str(path)) if r < 0 {
perror!("readlinkat {}", ptr_to_str(path))
}
r
} }
r
} }
#[no_mangle] #[unsafe(no_mangle)]
unsafe extern "C" fn xfopen(path: *const c_char, mode: *const c_char) -> *mut libc::FILE { unsafe extern "C" fn xfopen(path: *const c_char, mode: *const c_char) -> *mut libc::FILE {
let fp = libc::fopen(path, mode); unsafe {
if fp.is_null() { let fp = libc::fopen(path, mode);
perror!("fopen {}", ptr_to_str(path)); if fp.is_null() {
perror!("fopen {}", ptr_to_str(path));
}
fp
} }
fp
} }
#[no_mangle] #[unsafe(no_mangle)]
unsafe extern "C" fn xfdopen(fd: RawFd, mode: *const c_char) -> *mut libc::FILE { unsafe extern "C" fn xfdopen(fd: RawFd, mode: *const c_char) -> *mut libc::FILE {
let fp = libc::fdopen(fd, mode); unsafe {
if fp.is_null() { let fp = libc::fdopen(fd, mode);
perror!("fdopen"); if fp.is_null() {
perror!("fdopen");
}
fp
} }
fp
} }
#[no_mangle] #[unsafe(no_mangle)]
unsafe extern "C" fn xopen(path: *const c_char, flags: i32, mode: mode_t) -> RawFd { unsafe extern "C" fn xopen(path: *const c_char, flags: i32, mode: mode_t) -> RawFd {
let r = libc::open(path, flags, mode as c_uint); unsafe {
if r < 0 { let r = libc::open(path, flags, mode as c_uint);
perror!("open {}", ptr_to_str(path)); if r < 0 {
perror!("open {}", ptr_to_str(path));
}
r
} }
r
} }
#[no_mangle] #[unsafe(no_mangle)]
unsafe extern "C" fn xopenat(dirfd: RawFd, path: *const c_char, flags: i32, mode: mode_t) -> RawFd { unsafe extern "C" fn xopenat(dirfd: RawFd, path: *const c_char, flags: i32, mode: mode_t) -> RawFd {
let r = libc::openat(dirfd, path, flags, mode as c_uint); unsafe {
if r < 0 { let r = libc::openat(dirfd, path, flags, mode as c_uint);
perror!("openat {}", ptr_to_str(path)); if r < 0 {
perror!("openat {}", ptr_to_str(path));
}
r
} }
r
} }
// Fully write data slice // Fully write data slice
@ -168,7 +182,7 @@ fn xwrite(fd: RawFd, data: &[u8]) -> isize {
} }
} }
#[no_mangle] #[unsafe(no_mangle)]
unsafe extern "C" fn xread(fd: RawFd, buf: *mut c_void, bufsz: usize) -> isize { unsafe extern "C" fn xread(fd: RawFd, buf: *mut c_void, bufsz: usize) -> isize {
unsafe { unsafe {
let r = libc::read(fd, buf, bufsz); let r = libc::read(fd, buf, bufsz);
@ -208,7 +222,7 @@ fn xxread(fd: RawFd, data: &mut [u8]) -> isize {
} }
} }
#[no_mangle] #[unsafe(no_mangle)]
extern "C" fn xlseek64(fd: RawFd, offset: i64, whence: i32) -> i64 { extern "C" fn xlseek64(fd: RawFd, offset: i64, whence: i32) -> i64 {
unsafe { unsafe {
let r = libc::lseek64(fd, offset, whence); let r = libc::lseek64(fd, offset, whence);
@ -229,7 +243,7 @@ pub(crate) fn xpipe2(fds: &mut [i32; 2], flags: i32) -> i32 {
} }
} }
#[no_mangle] #[unsafe(no_mangle)]
extern "C" fn xsetns(fd: RawFd, nstype: i32) -> i32 { extern "C" fn xsetns(fd: RawFd, nstype: i32) -> i32 {
unsafe { unsafe {
let r = libc::setns(fd, nstype); let r = libc::setns(fd, nstype);
@ -240,7 +254,7 @@ extern "C" fn xsetns(fd: RawFd, nstype: i32) -> i32 {
} }
} }
#[no_mangle] #[unsafe(no_mangle)]
extern "C" fn xunshare(flags: i32) -> i32 { extern "C" fn xunshare(flags: i32) -> i32 {
unsafe { unsafe {
let r = libc::unshare(flags); let r = libc::unshare(flags);
@ -251,16 +265,18 @@ extern "C" fn xunshare(flags: i32) -> i32 {
} }
} }
#[no_mangle] #[unsafe(no_mangle)]
unsafe extern "C" fn xopendir(path: *const c_char) -> *mut libc::DIR { unsafe extern "C" fn xopendir(path: *const c_char) -> *mut libc::DIR {
let dp = libc::opendir(path); unsafe {
if dp.is_null() { let dp = libc::opendir(path);
perror!("opendir {}", ptr_to_str(path)); if dp.is_null() {
perror!("opendir {}", ptr_to_str(path));
}
dp
} }
dp
} }
#[no_mangle] #[unsafe(no_mangle)]
extern "C" fn xfdopendir(fd: RawFd) -> *mut libc::DIR { extern "C" fn xfdopendir(fd: RawFd) -> *mut libc::DIR {
unsafe { unsafe {
let dp = libc::fdopendir(fd); let dp = libc::fdopendir(fd);
@ -271,27 +287,29 @@ extern "C" fn xfdopendir(fd: RawFd) -> *mut libc::DIR {
} }
} }
#[no_mangle] #[unsafe(no_mangle)]
unsafe extern "C" fn xreaddir(dirp: *mut libc::DIR) -> *mut libc::dirent { unsafe extern "C" fn xreaddir(dirp: *mut libc::DIR) -> *mut libc::dirent {
*errno() = 0; unsafe {
loop { *errno() = 0;
let e = libc::readdir(dirp); loop {
if e.is_null() { let e = libc::readdir(dirp);
if *errno() != 0 { if e.is_null() {
perror!("readdir") if *errno() != 0 {
} perror!("readdir")
} else { }
// Filter out . and .. } else {
let s = (*e).d_name.as_ptr(); // Filter out . and ..
if libc::strcmp(s, raw_cstr!(".")) == 0 || libc::strcmp(s, raw_cstr!("..")) == 0 { let s = (*e).d_name.as_ptr();
continue; if libc::strcmp(s, raw_cstr!(".")) == 0 || libc::strcmp(s, raw_cstr!("..")) == 0 {
} continue;
}; }
return e; };
return e;
}
} }
} }
#[no_mangle] #[unsafe(no_mangle)]
extern "C" fn xsetsid() -> i32 { extern "C" fn xsetsid() -> i32 {
unsafe { unsafe {
let r = libc::setsid(); let r = libc::setsid();
@ -302,7 +320,7 @@ extern "C" fn xsetsid() -> i32 {
} }
} }
#[no_mangle] #[unsafe(no_mangle)]
extern "C" fn xsocket(domain: i32, ty: i32, protocol: i32) -> RawFd { extern "C" fn xsocket(domain: i32, ty: i32, protocol: i32) -> RawFd {
unsafe { unsafe {
let fd = libc::socket(domain, ty, protocol); let fd = libc::socket(domain, ty, protocol);
@ -313,16 +331,18 @@ extern "C" fn xsocket(domain: i32, ty: i32, protocol: i32) -> RawFd {
} }
} }
#[no_mangle] #[unsafe(no_mangle)]
unsafe extern "C" fn xbind(socket: i32, address: *const sockaddr, len: socklen_t) -> i32 { unsafe extern "C" fn xbind(socket: i32, address: *const sockaddr, len: socklen_t) -> i32 {
let r = libc::bind(socket, address, len); unsafe {
if r < 0 { let r = libc::bind(socket, address, len);
perror!("bind"); if r < 0 {
perror!("bind");
}
r
} }
r
} }
#[no_mangle] #[unsafe(no_mangle)]
extern "C" fn xlisten(socket: i32, backlog: i32) -> i32 { extern "C" fn xlisten(socket: i32, backlog: i32) -> i32 {
unsafe { unsafe {
let r = libc::listen(socket, backlog); let r = libc::listen(socket, backlog);
@ -333,103 +353,121 @@ extern "C" fn xlisten(socket: i32, backlog: i32) -> i32 {
} }
} }
#[no_mangle] #[unsafe(no_mangle)]
unsafe extern "C" fn xaccept4( unsafe extern "C" fn xaccept4(
sockfd: RawFd, sockfd: RawFd,
addr: *mut sockaddr, addr: *mut sockaddr,
len: *mut socklen_t, len: *mut socklen_t,
flg: i32, flg: i32,
) -> RawFd { ) -> RawFd {
let fd = libc::accept4(sockfd, addr, len, flg); unsafe {
if fd < 0 { let fd = libc::accept4(sockfd, addr, len, flg);
perror!("accept4"); if fd < 0 {
perror!("accept4");
}
fd
} }
fd
} }
#[no_mangle] #[unsafe(no_mangle)]
unsafe extern "C" fn xsendmsg(fd: RawFd, msg: *const libc::msghdr, flags: i32) -> ssize_t { unsafe extern "C" fn xsendmsg(fd: RawFd, msg: *const libc::msghdr, flags: i32) -> ssize_t {
let r = libc::sendmsg(fd, msg, flags); unsafe {
if r < 0 { let r = libc::sendmsg(fd, msg, flags);
perror!("sendmsg"); if r < 0 {
perror!("sendmsg");
}
r
} }
r
} }
#[no_mangle] #[unsafe(no_mangle)]
unsafe extern "C" fn xrecvmsg(fd: RawFd, msg: *mut libc::msghdr, flags: i32) -> ssize_t { unsafe extern "C" fn xrecvmsg(fd: RawFd, msg: *mut libc::msghdr, flags: i32) -> ssize_t {
let r = libc::recvmsg(fd, msg, flags); unsafe {
if r < 0 { let r = libc::recvmsg(fd, msg, flags);
perror!("recvmsg"); if r < 0 {
perror!("recvmsg");
}
r
} }
r
} }
#[no_mangle] #[unsafe(no_mangle)]
unsafe extern "C" fn xaccess(path: *const c_char, mode: i32) -> i32 { unsafe extern "C" fn xaccess(path: *const c_char, mode: i32) -> i32 {
let r = libc::access(path, mode); unsafe {
if r < 0 { let r = libc::access(path, mode);
perror!("access {}", ptr_to_str(path)); if r < 0 {
perror!("access {}", ptr_to_str(path));
}
r
} }
r
} }
#[no_mangle] #[unsafe(no_mangle)]
unsafe extern "C" fn xfaccessat(dirfd: RawFd, path: *const c_char, mode: i32, flags: i32) -> i32 { unsafe extern "C" fn xfaccessat(dirfd: RawFd, path: *const c_char, mode: i32, flags: i32) -> i32 {
#[allow(unused_mut)] unsafe {
let mut r = libc::faccessat(dirfd, path, mode, flags); #[allow(unused_mut)]
if r < 0 { let mut r = libc::faccessat(dirfd, path, mode, flags);
perror!("faccessat {}", ptr_to_str(path)); if r < 0 {
perror!("faccessat {}", ptr_to_str(path));
}
#[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
if r > 0 && *errno() == 0 {
r = 0
}
r
} }
#[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
if r > 0 && *errno() == 0 {
r = 0
}
r
} }
#[no_mangle] #[unsafe(no_mangle)]
unsafe extern "C" fn xstat(path: *const c_char, buf: *mut libc::stat) -> i32 { unsafe extern "C" fn xstat(path: *const c_char, buf: *mut libc::stat) -> i32 {
let r = libc::stat(path, buf); unsafe {
if r < 0 { let r = libc::stat(path, buf);
perror!("stat {}", ptr_to_str(path)); if r < 0 {
perror!("stat {}", ptr_to_str(path));
}
r
} }
r
} }
#[no_mangle] #[unsafe(no_mangle)]
unsafe extern "C" fn xlstat(path: *const c_char, buf: *mut libc::stat) -> i32 { unsafe extern "C" fn xlstat(path: *const c_char, buf: *mut libc::stat) -> i32 {
let r = libc::lstat(path, buf); unsafe {
if r < 0 { let r = libc::lstat(path, buf);
perror!("lstat {}", ptr_to_str(path)); if r < 0 {
perror!("lstat {}", ptr_to_str(path));
}
r
} }
r
} }
#[no_mangle] #[unsafe(no_mangle)]
unsafe extern "C" fn xfstat(fd: RawFd, buf: *mut libc::stat) -> i32 { unsafe extern "C" fn xfstat(fd: RawFd, buf: *mut libc::stat) -> i32 {
let r = libc::fstat(fd, buf); unsafe {
if r < 0 { let r = libc::fstat(fd, buf);
perror!("fstat"); if r < 0 {
perror!("fstat");
}
r
} }
r
} }
#[no_mangle] #[unsafe(no_mangle)]
unsafe extern "C" fn xfstatat( unsafe extern "C" fn xfstatat(
dirfd: RawFd, dirfd: RawFd,
path: *const c_char, path: *const c_char,
buf: *mut libc::stat, buf: *mut libc::stat,
flags: i32, flags: i32,
) -> i32 { ) -> i32 {
let r = libc::fstatat(dirfd, path, buf, flags); unsafe {
if r < 0 { let r = libc::fstatat(dirfd, path, buf, flags);
perror!("fstatat {}", ptr_to_str(path)); if r < 0 {
perror!("fstatat {}", ptr_to_str(path));
}
r
} }
r
} }
#[no_mangle] #[unsafe(no_mangle)]
extern "C" fn xdup(oldfd: RawFd) -> RawFd { extern "C" fn xdup(oldfd: RawFd) -> RawFd {
unsafe { unsafe {
let fd = libc::dup(oldfd); let fd = libc::dup(oldfd);
@ -440,7 +478,7 @@ extern "C" fn xdup(oldfd: RawFd) -> RawFd {
} }
} }
#[no_mangle] #[unsafe(no_mangle)]
extern "C" fn xdup2(oldfd: RawFd, newfd: RawFd) -> RawFd { extern "C" fn xdup2(oldfd: RawFd, newfd: RawFd) -> RawFd {
unsafe { unsafe {
let fd = libc::dup2(oldfd, newfd); let fd = libc::dup2(oldfd, newfd);
@ -451,7 +489,7 @@ extern "C" fn xdup2(oldfd: RawFd, newfd: RawFd) -> RawFd {
} }
} }
#[no_mangle] #[unsafe(no_mangle)]
extern "C" fn xdup3(oldfd: RawFd, newfd: RawFd, flags: i32) -> RawFd { extern "C" fn xdup3(oldfd: RawFd, newfd: RawFd, flags: i32) -> RawFd {
unsafe { unsafe {
let fd = libc::syscall(SYS_dup3, oldfd, newfd, flags) as RawFd; let fd = libc::syscall(SYS_dup3, oldfd, newfd, flags) as RawFd;
@ -462,33 +500,37 @@ extern "C" fn xdup3(oldfd: RawFd, newfd: RawFd, flags: i32) -> RawFd {
} }
} }
#[no_mangle] #[unsafe(no_mangle)]
unsafe extern "C" fn xsymlink(target: *const c_char, linkpath: *const c_char) -> i32 { unsafe extern "C" fn xsymlink(target: *const c_char, linkpath: *const c_char) -> i32 {
let r = libc::symlink(target, linkpath); unsafe {
if r < 0 { let r = libc::symlink(target, linkpath);
perror!("symlink {} -> {}", ptr_to_str(target), ptr_to_str(linkpath)); if r < 0 {
perror!("symlink {} -> {}", ptr_to_str(target), ptr_to_str(linkpath));
}
r
} }
r
} }
#[no_mangle] #[unsafe(no_mangle)]
unsafe extern "C" fn xsymlinkat( unsafe extern "C" fn xsymlinkat(
target: *const c_char, target: *const c_char,
dirfd: RawFd, dirfd: RawFd,
linkpath: *const c_char, linkpath: *const c_char,
) -> i32 { ) -> i32 {
let r = libc::symlinkat(target, dirfd, linkpath); unsafe {
if r < 0 { let r = libc::symlinkat(target, dirfd, linkpath);
perror!( if r < 0 {
"symlinkat {} -> {}", perror!(
ptr_to_str(target), "symlinkat {} -> {}",
ptr_to_str(linkpath) ptr_to_str(target),
); ptr_to_str(linkpath)
);
}
r
} }
r
} }
#[no_mangle] #[unsafe(no_mangle)]
unsafe extern "C" fn xlinkat( unsafe extern "C" fn xlinkat(
olddirfd: RawFd, olddirfd: RawFd,
target: *const c_char, target: *const c_char,
@ -496,14 +538,16 @@ unsafe extern "C" fn xlinkat(
linkpath: *const c_char, linkpath: *const c_char,
flags: i32, flags: i32,
) -> i32 { ) -> i32 {
let r = libc::linkat(olddirfd, target, newdirfd, linkpath, flags); unsafe {
if r < 0 { let r = libc::linkat(olddirfd, target, newdirfd, linkpath, flags);
perror!("linkat {} -> {}", ptr_to_str(target), ptr_to_str(linkpath)); if r < 0 {
perror!("linkat {} -> {}", ptr_to_str(target), ptr_to_str(linkpath));
}
r
} }
r
} }
#[no_mangle] #[unsafe(no_mangle)]
unsafe extern "C" fn xmount( unsafe extern "C" fn xmount(
src: *const c_char, src: *const c_char,
target: *const c_char, target: *const c_char,
@ -511,84 +555,100 @@ unsafe extern "C" fn xmount(
flags: c_ulong, flags: c_ulong,
data: *const c_void, data: *const c_void,
) -> i32 { ) -> i32 {
let r = libc::mount(src, target, fstype, flags, data); unsafe {
if r < 0 { let r = libc::mount(src, target, fstype, flags, data);
perror!("mount {} -> {}", ptr_to_str(src), ptr_to_str(target)); if r < 0 {
perror!("mount {} -> {}", ptr_to_str(src), ptr_to_str(target));
}
r
} }
r
} }
#[no_mangle] #[unsafe(no_mangle)]
unsafe extern "C" fn xumount(target: *const c_char) -> i32 { unsafe extern "C" fn xumount(target: *const c_char) -> i32 {
let r = libc::umount(target); unsafe {
if r < 0 { let r = libc::umount(target);
perror!("umount {}", ptr_to_str(target)); if r < 0 {
perror!("umount {}", ptr_to_str(target));
}
r
} }
r
} }
#[no_mangle] #[unsafe(no_mangle)]
unsafe extern "C" fn xumount2(target: *const c_char, flags: i32) -> i32 { unsafe extern "C" fn xumount2(target: *const c_char, flags: i32) -> i32 {
let r = libc::umount2(target, flags); unsafe {
if r < 0 { let r = libc::umount2(target, flags);
perror!("umount2 {}", ptr_to_str(target)); if r < 0 {
perror!("umount2 {}", ptr_to_str(target));
}
r
} }
r
} }
#[no_mangle] #[unsafe(no_mangle)]
unsafe extern "C" fn xrename(oldname: *const c_char, newname: *const c_char) -> i32 { unsafe extern "C" fn xrename(oldname: *const c_char, newname: *const c_char) -> i32 {
let r = libc::rename(oldname, newname); unsafe {
if r < 0 { let r = libc::rename(oldname, newname);
perror!("rename {} -> {}", ptr_to_str(oldname), ptr_to_str(newname)); if r < 0 {
perror!("rename {} -> {}", ptr_to_str(oldname), ptr_to_str(newname));
}
r
} }
r
} }
#[no_mangle] #[unsafe(no_mangle)]
unsafe extern "C" fn xmkdir(path: *const c_char, mode: mode_t) -> i32 { unsafe extern "C" fn xmkdir(path: *const c_char, mode: mode_t) -> i32 {
let r = libc::mkdir(path, mode); unsafe {
if r < 0 && *errno() != libc::EEXIST { let r = libc::mkdir(path, mode);
perror!("mkdir {}", ptr_to_str(path)); if r < 0 && *errno() != libc::EEXIST {
perror!("mkdir {}", ptr_to_str(path));
}
r
} }
r
} }
#[no_mangle] #[unsafe(no_mangle)]
unsafe extern "C" fn xmkdirs(path: *const c_char, mode: mode_t) -> i32 { unsafe extern "C" fn xmkdirs(path: *const c_char, mode: mode_t) -> i32 {
match Utf8CStr::from_ptr(path) { unsafe {
Ok(p) => FsPath::from(p) match Utf8CStr::from_ptr(path) {
.mkdirs(mode) Ok(p) => FsPath::from(p)
.log_cxx_with_msg(|w| w.write_fmt(format_args!("mkdirs {} failed", p))) .mkdirs(mode)
.map_or(-1, |_| 0), .log_cxx_with_msg(|w| w.write_fmt(format_args!("mkdirs {} failed", p)))
Err(_) => -1, .map_or(-1, |_| 0),
Err(_) => -1,
}
} }
} }
#[no_mangle] #[unsafe(no_mangle)]
unsafe extern "C" fn xmkdirat(dirfd: RawFd, path: *const c_char, mode: mode_t) -> i32 { unsafe extern "C" fn xmkdirat(dirfd: RawFd, path: *const c_char, mode: mode_t) -> i32 {
let r = libc::mkdirat(dirfd, path, mode); unsafe {
if r < 0 && *errno() != libc::EEXIST { let r = libc::mkdirat(dirfd, path, mode);
perror!("mkdirat {}", ptr_to_str(path)); if r < 0 && *errno() != libc::EEXIST {
perror!("mkdirat {}", ptr_to_str(path));
}
r
} }
r
} }
#[no_mangle] #[unsafe(no_mangle)]
unsafe extern "C" fn xsendfile( unsafe extern "C" fn xsendfile(
out_fd: RawFd, out_fd: RawFd,
in_fd: RawFd, in_fd: RawFd,
offset: *mut off_t, offset: *mut off_t,
count: usize, count: usize,
) -> isize { ) -> isize {
let r = libc::sendfile(out_fd, in_fd, offset, count); unsafe {
if r < 0 { let r = libc::sendfile(out_fd, in_fd, offset, count);
perror!("sendfile"); if r < 0 {
perror!("sendfile");
}
r
} }
r
} }
#[no_mangle] #[unsafe(no_mangle)]
unsafe extern "C" fn xmmap( unsafe extern "C" fn xmmap(
addr: *mut c_void, addr: *mut c_void,
len: usize, len: usize,
@ -597,15 +657,17 @@ unsafe extern "C" fn xmmap(
fd: RawFd, fd: RawFd,
offset: off_t, offset: off_t,
) -> *mut c_void { ) -> *mut c_void {
let r = libc::mmap(addr, len, prot, flags, fd, offset); unsafe {
if r == libc::MAP_FAILED { let r = libc::mmap(addr, len, prot, flags, fd, offset);
perror!("mmap"); if r == libc::MAP_FAILED {
return ptr::null_mut(); perror!("mmap");
return ptr::null_mut();
}
r
} }
r
} }
#[no_mangle] #[unsafe(no_mangle)]
extern "C" fn xfork() -> i32 { extern "C" fn xfork() -> i32 {
unsafe { unsafe {
let r = libc::fork(); let r = libc::fork();
@ -616,20 +678,24 @@ extern "C" fn xfork() -> i32 {
} }
} }
#[no_mangle] #[unsafe(no_mangle)]
unsafe extern "C" fn xpoll(fds: *mut pollfd, nfds: nfds_t, timeout: i32) -> i32 { unsafe extern "C" fn xpoll(fds: *mut pollfd, nfds: nfds_t, timeout: i32) -> i32 {
let r = libc::poll(fds, nfds, timeout); unsafe {
if r < 0 { let r = libc::poll(fds, nfds, timeout);
perror!("poll"); if r < 0 {
perror!("poll");
}
r
} }
r
} }
#[no_mangle] #[unsafe(no_mangle)]
unsafe extern "C" fn xmknod(pathname: *const c_char, mode: mode_t, dev: dev_t) -> i32 { unsafe extern "C" fn xmknod(pathname: *const c_char, mode: mode_t, dev: dev_t) -> i32 {
let r = libc::mknod(pathname, mode, dev); unsafe {
if r < 0 { let r = libc::mknod(pathname, mode, dev);
perror!("mknod {}", ptr_to_str(pathname)); if r < 0 {
perror!("mknod {}", ptr_to_str(pathname));
}
r
} }
r
} }

View File

@ -1,9 +1,9 @@
use pb_rs::{types::FileDescriptor, ConfigBuilder}; use pb_rs::{types::FileDescriptor, ConfigBuilder};
use crate::gen::gen_cxx_binding; use crate::codegen::gen_cxx_binding;
#[path = "../include/gen.rs"] #[path = "../include/codegen.rs"]
mod gen; mod codegen;
fn main() { fn main() {
println!("cargo:rerun-if-changed=proto/update_metadata.proto"); println!("cargo:rerun-if-changed=proto/update_metadata.proto");

View File

@ -1,7 +1,10 @@
use std::{cell::UnsafeCell, process::exit}; use std::{cell::UnsafeCell, process::exit};
use argh::FromArgs; use argh::FromArgs;
use fdt::{node::{FdtNode, NodeProperty}, Fdt, FdtError}; use fdt::{
node::{FdtNode, NodeProperty},
Fdt, FdtError,
};
use base::{ use base::{
libc::c_char, log_err, map_args, EarlyExitExt, LoggedResult, MappedFile, ResultExt, Utf8CStr, libc::c_char, log_err, map_args, EarlyExitExt, LoggedResult, MappedFile, ResultExt, Utf8CStr,
@ -172,7 +175,7 @@ fn for_each_fdt<F: FnMut(usize, Fdt) -> LoggedResult<()>>(
Err(FdtError::BufferTooSmall) => { Err(FdtError::BufferTooSmall) => {
eprintln!("dtb.{:04} is truncated", dtb_num); eprintln!("dtb.{:04} is truncated", dtb_num);
break; break;
}, }
Ok(fdt) => fdt, Ok(fdt) => fdt,
e => e?, e => e?,
}; };

View File

@ -63,15 +63,17 @@ fn remove_pattern(buf: &mut [u8], pattern_matcher: unsafe fn(&[u8]) -> Option<us
pub fn patch_verity(buf: &mut [u8]) -> usize { pub fn patch_verity(buf: &mut [u8]) -> usize {
unsafe fn match_verity_pattern(buf: &[u8]) -> Option<usize> { unsafe fn match_verity_pattern(buf: &[u8]) -> Option<usize> {
match_patterns!( unsafe {
buf, match_patterns!(
b"verifyatboot", buf,
b"verify", b"verifyatboot",
b"avb_keys", b"verify",
b"avb", b"avb_keys",
b"support_scfs", b"avb",
b"fsverity" b"support_scfs",
) b"fsverity"
)
}
} }
remove_pattern(buf, match_verity_pattern) remove_pattern(buf, match_verity_pattern)
@ -79,7 +81,7 @@ pub fn patch_verity(buf: &mut [u8]) -> usize {
pub fn patch_encryption(buf: &mut [u8]) -> usize { pub fn patch_encryption(buf: &mut [u8]) -> usize {
unsafe fn match_encryption_pattern(buf: &[u8]) -> Option<usize> { unsafe fn match_encryption_pattern(buf: &[u8]) -> Option<usize> {
match_patterns!(buf, b"forceencrypt", b"forcefdeorfbe", b"fileencryption") unsafe { match_patterns!(buf, b"forceencrypt", b"forcefdeorfbe", b"fileencryption") }
} }
remove_pattern(buf, match_encryption_pattern) remove_pattern(buf, match_encryption_pattern)

View File

@ -157,20 +157,32 @@ struct Signer {
impl Signer { impl Signer {
fn from_private_key(key: &[u8]) -> LoggedResult<Signer> { fn from_private_key(key: &[u8]) -> LoggedResult<Signer> {
let digest: Box<dyn DynDigest>; let digest: Box<dyn DynDigest>;
let key = if let Ok(rsa) = RsaPrivateKey::from_pkcs8_der(key) { let key = match RsaPrivateKey::from_pkcs8_der(key) {
digest = Box::<Sha256>::default(); Ok(rsa) => {
SigningKey::SHA256withRSA(RsaSigningKey::<Sha256>::new(rsa)) digest = Box::<Sha256>::default();
} else if let Ok(ec) = P256SigningKey::from_pkcs8_der(key) { SigningKey::SHA256withRSA(RsaSigningKey::<Sha256>::new(rsa))
digest = Box::<Sha256>::default(); }
SigningKey::SHA256withECDSA(ec) _ => match P256SigningKey::from_pkcs8_der(key) {
} else if let Ok(ec) = P384SigningKey::from_pkcs8_der(key) { Ok(ec) => {
digest = Box::<Sha384>::default(); digest = Box::<Sha256>::default();
SigningKey::SHA384withECDSA(ec) SigningKey::SHA256withECDSA(ec)
} else if let Ok(ec) = P521SigningKey::from_pkcs8_der(key) { }
digest = Box::<Sha512>::default(); _ => match P384SigningKey::from_pkcs8_der(key) {
SigningKey::SHA521withECDSA(ec) Ok(ec) => {
} else { digest = Box::<Sha384>::default();
return Err(log_err!("Unsupported private key")); SigningKey::SHA384withECDSA(ec)
}
_ => match P521SigningKey::from_pkcs8_der(key) {
Ok(ec) => {
digest = Box::<Sha512>::default();
SigningKey::SHA521withECDSA(ec)
}
_ => {
return Err(log_err!("Unsupported private key"));
}
},
},
},
}; };
Ok(Signer { digest, key }) Ok(Signer { digest, key })
} }

View File

@ -1,9 +1,9 @@
use pb_rs::{types::FileDescriptor, ConfigBuilder}; use pb_rs::{types::FileDescriptor, ConfigBuilder};
use crate::gen::gen_cxx_binding; use crate::codegen::gen_cxx_binding;
#[path = "../include/gen.rs"] #[path = "../include/codegen.rs"]
mod gen; mod codegen;
fn main() { fn main() {
println!("cargo:rerun-if-changed=resetprop/proto/persistent_properties.proto"); println!("cargo:rerun-if-changed=resetprop/proto/persistent_properties.proto");

View File

@ -138,7 +138,7 @@ unsafe impl Send for Sqlite3 {}
type SqlBindCallback = Option<unsafe extern "C" fn(*mut c_void, i32, Pin<&mut DbStatement>) -> i32>; type SqlBindCallback = Option<unsafe extern "C" fn(*mut c_void, i32, Pin<&mut DbStatement>) -> i32>;
type SqlExecCallback = Option<unsafe extern "C" fn(*mut c_void, &[String], &DbValues)>; type SqlExecCallback = Option<unsafe extern "C" fn(*mut c_void, &[String], &DbValues)>;
extern "C" { unsafe extern "C" {
fn sql_exec_impl( fn sql_exec_impl(
db: *mut sqlite3, db: *mut sqlite3,
sql: &str, sql: &str,
@ -160,16 +160,18 @@ struct DbArgs<'a> {
} }
unsafe extern "C" fn bind_arguments(v: *mut c_void, idx: i32, stmt: Pin<&mut DbStatement>) -> i32 { unsafe extern "C" fn bind_arguments(v: *mut c_void, idx: i32, stmt: Pin<&mut DbStatement>) -> i32 {
let args = &mut *(v as *mut DbArgs<'_>); unsafe {
if args.curr < args.args.len() { let args = &mut *(v as *mut DbArgs<'_>);
let arg = &args.args[args.curr]; if args.curr < args.args.len() {
args.curr += 1; let arg = &args.args[args.curr];
match *arg { args.curr += 1;
Text(v) => stmt.bind_text(idx, v), match *arg {
Integer(v) => stmt.bind_int64(idx, v), Text(v) => stmt.bind_text(idx, v),
Integer(v) => stmt.bind_int64(idx, v),
}
} else {
0
} }
} else {
0
} }
} }
@ -178,8 +180,10 @@ unsafe extern "C" fn read_db_row<T: SqlTable>(
columns: &[String], columns: &[String],
values: &DbValues, values: &DbValues,
) { ) {
let table = &mut *(v as *mut T); unsafe {
table.on_row(columns, values); let table = &mut *(v as *mut T);
table.on_row(columns, values);
}
} }
impl MagiskD { impl MagiskD {
@ -189,10 +193,9 @@ impl MagiskD {
let raw_db = open_and_init_db(); let raw_db = open_and_init_db();
*db = NonNull::new(raw_db).map(Sqlite3); *db = NonNull::new(raw_db).map(Sqlite3);
} }
if let Some(ref mut db) = *db { match *db {
f(db.0.as_ptr()) Some(ref mut db) => f(db.0.as_ptr()),
} else { _ => -1,
-1
} }
} }
@ -333,7 +336,7 @@ impl MagiskD {
} }
} }
#[export_name = "sql_exec_rs"] #[unsafe(export_name = "sql_exec_rs")]
unsafe extern "C" fn sql_exec_for_cxx( unsafe extern "C" fn sql_exec_for_cxx(
sql: &str, sql: &str,
bind_callback: SqlBindCallback, bind_callback: SqlBindCallback,
@ -341,14 +344,16 @@ unsafe extern "C" fn sql_exec_for_cxx(
exec_callback: SqlExecCallback, exec_callback: SqlExecCallback,
exec_cookie: *mut c_void, exec_cookie: *mut c_void,
) -> i32 { ) -> i32 {
MAGISKD.get().unwrap_unchecked().with_db(|db| { unsafe {
sql_exec_impl( MAGISKD.get().unwrap_unchecked().with_db(|db| {
db, sql_exec_impl(
sql, db,
bind_callback, sql,
bind_cookie, bind_callback,
exec_callback, bind_cookie,
exec_cookie, exec_callback,
) exec_cookie,
}) )
})
}
} }

View File

@ -257,8 +257,10 @@ unsafe impl ExternType for UCred {
impl SuRequest { impl SuRequest {
unsafe fn write_to_fd(&self, fd: i32) { unsafe fn write_to_fd(&self, fd: i32) {
let mut w = ManuallyDrop::new(File::from_raw_fd(fd)); unsafe {
self.encode(w.deref_mut()).ok(); let mut w = ManuallyDrop::new(File::from_raw_fd(fd));
self.encode(w.deref_mut()).ok();
}
} }
} }

View File

@ -42,7 +42,7 @@ enum ALogPriority {
type ThreadEntry = extern "C" fn(*mut c_void) -> *mut c_void; type ThreadEntry = extern "C" fn(*mut c_void) -> *mut c_void;
extern "C" { unsafe extern "C" {
fn __android_log_write(prio: i32, tag: *const c_char, msg: *const c_char); fn __android_log_write(prio: i32, tag: *const c_char, msg: *const c_char);
fn strftime(buf: *mut c_char, len: usize, fmt: *const c_char, tm: *const tm) -> usize; fn strftime(buf: *mut c_char, len: usize, fmt: *const c_char, tm: *const tm) -> usize;
fn new_daemon_thread(entry: ThreadEntry, arg: *mut c_void); fn new_daemon_thread(entry: ThreadEntry, arg: *mut c_void);

View File

@ -485,14 +485,16 @@ impl MagiskD {
} }
pub unsafe fn get_manager_for_cxx(&self, user: i32, ptr: *mut CxxString, install: bool) -> i32 { pub unsafe fn get_manager_for_cxx(&self, user: i32, ptr: *mut CxxString, install: bool) -> i32 {
let mut info = self.manager_info.lock().unwrap(); unsafe {
let (uid, pkg) = info.get_manager(self, user, install); let mut info = self.manager_info.lock().unwrap();
if let Some(str) = ptr.as_mut() { let (uid, pkg) = info.get_manager(self, user, install);
let mut str = Pin::new_unchecked(str); if let Some(str) = ptr.as_mut() {
str.as_mut().clear(); let mut str = Pin::new_unchecked(str);
str.push_str(pkg); str.as_mut().clear();
str.push_str(pkg);
}
uid
} }
uid
} }
// app_id = app_no + AID_APP_START // app_id = app_no + AID_APP_START

View File

@ -130,8 +130,8 @@ pub fn persist_get_prop(name: &Utf8CStr, mut prop_cb: Pin<&mut PropCb>) {
let mut props = proto_read_props()?; let mut props = proto_read_props()?;
let prop = props.find(name)?; let prop = props.find(name)?;
if let PersistentPropertyRecord { if let PersistentPropertyRecord {
name: Some(ref mut n), name: Some(n),
value: Some(ref mut v), value: Some(v),
} = prop } = prop
{ {
prop_cb.exec(Utf8CStr::from_string(n), Utf8CStr::from_string(v)); prop_cb.exec(Utf8CStr::from_string(n), Utf8CStr::from_string(v));
@ -151,8 +151,8 @@ pub fn persist_get_props(mut prop_cb: Pin<&mut PropCb>) {
let mut props = proto_read_props()?; let mut props = proto_read_props()?;
props.iter_mut().for_each(|prop| { props.iter_mut().for_each(|prop| {
if let PersistentPropertyRecord { if let PersistentPropertyRecord {
name: Some(ref mut n), name: Some(n),
value: Some(ref mut v), value: Some(v),
} = prop } = prop
{ {
prop_cb.exec(Utf8CStr::from_string(n), Utf8CStr::from_string(v)); prop_cb.exec(Utf8CStr::from_string(n), Utf8CStr::from_string(v));

View File

@ -39,7 +39,7 @@ fn write_if_diff<P: AsRef<Path>>(path: P, bytes: &[u8]) -> io::Result<()> {
pub fn gen_cxx_binding(name: &str) { pub fn gen_cxx_binding(name: &str) {
println!("cargo:rerun-if-changed=lib.rs"); println!("cargo:rerun-if-changed=lib.rs");
let opt = Opt::default(); let opt = Opt::default();
let gen = cxx_gen::generate_header_and_cc_with_path("lib.rs", &opt); let code = cxx_gen::generate_header_and_cc_with_path("lib.rs", &opt);
write_if_diff(format!("{}.cpp", name), gen.implementation.as_slice()).ok_or_exit(); write_if_diff(format!("{}.cpp", name), code.implementation.as_slice()).ok_or_exit();
write_if_diff(format!("{}.hpp", name), gen.header.as_slice()).ok_or_exit(); write_if_diff(format!("{}.hpp", name), code.header.as_slice()).ok_or_exit();
} }

View File

@ -1,7 +1,7 @@
use crate::gen::gen_cxx_binding; use crate::codegen::gen_cxx_binding;
#[path = "../include/gen.rs"] #[path = "../include/codegen.rs"]
mod gen; mod codegen;
fn main() { fn main() {
gen_cxx_binding("init-rs"); gen_cxx_binding("init-rs");

View File

@ -132,23 +132,25 @@ impl MagiskInit {
} }
} }
#[no_mangle] #[unsafe(no_mangle)]
pub unsafe extern "C" fn main( pub unsafe extern "C" fn main(
argc: i32, argc: i32,
argv: *mut *mut c_char, argv: *mut *mut c_char,
_envp: *const *const c_char, _envp: *const *const c_char,
) -> i32 { ) -> i32 {
umask(0); unsafe {
umask(0);
let name = basename(*argv); let name = basename(*argv);
if CStr::from_ptr(name) == c"magisk" { if CStr::from_ptr(name) == c"magisk" {
return magisk_proxy_main(argc, argv); return magisk_proxy_main(argc, argv);
}
if getpid() == 1 {
MagiskInit::new(argv).start().log_ok();
}
1
} }
if getpid() == 1 {
MagiskInit::new(argv).start().log_ok();
}
1
} }

View File

@ -13,7 +13,7 @@ use std::{
ptr::null as nullptr, ptr::null as nullptr,
}; };
extern "C" { unsafe extern "C" {
static environ: *const *mut libc::c_char; static environ: *const *mut libc::c_char;
} }

View File

@ -75,7 +75,31 @@ impl MagiskInit {
self.restore_ramdisk_init(); self.restore_ramdisk_init();
// fallback to hexpatch if /sdcard exists // fallback to hexpatch if /sdcard exists
if let Ok(mut map) = MappedFile::open_rw(cstr!("/init")) { match MappedFile::open_rw(cstr!("/init")) {
Ok(mut map) => {
let from = "/system/bin/init";
let to = "/data/magiskinit";
// Redirect original init to magiskinit
let v = map.patch(from.as_bytes(), to.as_bytes());
#[allow(unused_variables)]
for off in &v {
debug!("Patch @ {:#010X} [{}] -> [{}]", off, from, to);
}
}
_ => {
error!("Failed to open /init for hexpatch");
}
}
}
}
pub(crate) fn redirect_second_stage(&self) {
let src = path!("/init");
let dest = path!("/data/init");
// Patch init binary
match MappedFile::open(src) {
Ok(mut map) => {
let from = "/system/bin/init"; let from = "/system/bin/init";
let to = "/data/magiskinit"; let to = "/data/magiskinit";
@ -85,33 +109,18 @@ impl MagiskInit {
for off in &v { for off in &v {
debug!("Patch @ {:#010X} [{}] -> [{}]", off, from, to); debug!("Patch @ {:#010X} [{}] -> [{}]", off, from, to);
} }
} else { match dest.create(O_CREAT | O_WRONLY, 0) {
error!("Failed to open /init for hexpatch"); Ok(mut dest) => {
dest.write_all(map.as_ref()).log_ok();
}
_ => {
error!("Failed to create {}", dest);
}
}
} }
} _ => {
} error!("Failed to open {} for hexpatch", src);
pub(crate) fn redirect_second_stage(&self) {
let src = path!("/init");
let dest = path!("/data/init");
// Patch init binary
if let Ok(mut map) = MappedFile::open(src) {
let from = "/system/bin/init";
let to = "/data/magiskinit";
// Redirect original init to magiskinit
let v = map.patch(from.as_bytes(), to.as_bytes());
#[allow(unused_variables)]
for off in &v {
debug!("Patch @ {:#010X} [{}] -> [{}]", off, from, to);
} }
if let Ok(mut dest) = dest.create(O_CREAT | O_WRONLY, 0) {
dest.write_all(map.as_ref()).log_ok();
} else {
error!("Failed to create {}", dest);
}
} else {
error!("Failed to open {} for hexpatch", src);
} }
clone_attr(src, dest).log_ok(); clone_attr(src, dest).log_ok();
unsafe { unsafe {

View File

@ -1,7 +1,7 @@
use crate::gen::gen_cxx_binding; use crate::codegen::gen_cxx_binding;
#[path = "../include/gen.rs"] #[path = "../include/codegen.rs"]
mod gen; mod codegen;
fn main() { fn main() {
gen_cxx_binding("policy-rs"); gen_cxx_binding("policy-rs");