Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merge dev into main #57

Merged
merged 12 commits into from
Mar 7, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 4 additions & 0 deletions Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,8 @@
# - `QEMU_LOG`: Enable QEMU logging (log file is "qemu.log")
# - `NET_DUMP`: Enable network packet dump (log file is "netdump.pcap")
# - `NET_DEV`: QEMU netdev backend types: user, tap
# - `START_PORT`: The starting port number for the open ports in QEMU (default is port 5555)
# - `PORT_NUM`: The number of open ports in QEMU (default is 5)
# * 9P options:
# - `V9P_PATH`: Host path for backend of virtio-9p
# - `NET_9P_ADDR`: Server address and port for 9P netdev
Expand Down Expand Up @@ -64,6 +66,8 @@ NET_9P_ADDR ?= 127.0.0.1:564
ANAME_9P ?= ./
PROTOCOL_9P ?= 9P2000.L

START_PORT ?= 5555
PORTS_NUM ?= 5
# Network options
IP ?= 10.0.2.15
GW ?= 10.0.2.2
Expand Down
51 changes: 42 additions & 9 deletions api/ruxos_posix_api/src/imp/fs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
*/

use alloc::sync::Arc;
use core::ffi::{c_char, c_int, c_long, c_uint};
use core::ffi::{c_char, c_int, c_long};

use axerrno::{LinuxError, LinuxResult};
use axio::{PollState, SeekFrom};
Expand Down Expand Up @@ -232,7 +232,7 @@ pub unsafe fn sys_fdatasync(fd: c_int) -> c_int {
/// Get the file metadata by `path` and write into `buf`.
///
/// Return 0 if success.
pub unsafe fn sys_stat(path: *const c_char, buf: *mut ctypes::stat) -> c_int {
pub unsafe fn sys_stat(path: *const c_char, buf: *mut core::ffi::c_void) -> c_int {
let path = char_ptr_to_str(path);
debug!("sys_stat <= {:?} {:#x}", path, buf as usize);
syscall_body!(sys_stat, {
Expand All @@ -243,8 +243,30 @@ pub unsafe fn sys_stat(path: *const c_char, buf: *mut ctypes::stat) -> c_int {
options.read(true);
let file = ruxfs::fops::File::open(path?, &options)?;
let st = File::new(file).stat()?;
unsafe { *buf = st };
Ok(0)

#[cfg(not(feature = "musl"))]
{
let buf = buf as *mut ctypes::stat;
unsafe { *buf = st };
Ok(0)
}

#[cfg(feature = "musl")]
{
let kst = buf as *mut ctypes::kstat;
unsafe {
(*kst).st_dev = st.st_dev;
(*kst).st_ino = st.st_ino;
(*kst).st_mode = st.st_mode;
(*kst).st_nlink = st.st_nlink;
(*kst).st_uid = st.st_uid;
(*kst).st_gid = st.st_gid;
(*kst).st_size = st.st_size;
(*kst).st_blocks = st.st_blocks;
(*kst).st_blksize = st.st_blksize;
}
Ok(0)
}
})
}

Expand All @@ -267,14 +289,21 @@ pub unsafe fn sys_fstat(fd: c_int, kst: *mut core::ffi::c_void) -> c_int {
let kst = kst as *mut ctypes::kstat;
unsafe {
(*kst).st_dev = st.st_dev;
(*kst).st_ino = st.st_dev;
(*kst).st_ino = st.st_ino;
(*kst).st_mode = st.st_mode;
(*kst).st_nlink = st.st_nlink;
(*kst).st_uid = st.st_uid;
(*kst).st_gid = st.st_gid;
(*kst).st_size = st.st_size;
(*kst).st_blocks = st.st_blocks;
(*kst).st_blksize = st.st_blksize;
(*kst).st_atime_sec = st.st_atime.tv_sec;
(*kst).st_atime_nsec = st.st_atime.tv_nsec;
(*kst).st_mtime_sec = st.st_mtime.tv_sec;
(*kst).st_mtime_nsec = st.st_mtime.tv_nsec;
(*kst).st_ctime_sec = st.st_ctime.tv_sec;
(*kst).st_ctime_nsec = st.st_ctime.tv_nsec;
(*kst).st_rdev = st.st_rdev;
}
Ok(0)
}
Expand Down Expand Up @@ -319,7 +348,7 @@ pub unsafe fn sys_newfstatat(
let st = File::new(file).stat()?;
unsafe {
(*kst).st_dev = st.st_dev;
(*kst).st_ino = st.st_dev;
(*kst).st_ino = st.st_ino;
(*kst).st_mode = st.st_mode;
(*kst).st_nlink = st.st_nlink;
(*kst).st_uid = st.st_uid;
Expand Down Expand Up @@ -508,15 +537,19 @@ fn convert_name_to_array(name: &[u8]) -> [i8; 256] {
/// Read directory entries from a directory file descriptor.
///
/// TODO: check errors, change 280 to a special value
pub unsafe fn sys_getdents64(fd: c_uint, dirent: *mut LinuxDirent64, count: c_uint) -> c_long {
pub unsafe fn sys_getdents64(
fd: c_int,
dirent: *mut LinuxDirent64,
count: ctypes::size_t,
) -> c_long {
debug!(
"sys_getdents64 <= fd: {}, dirent: {:p}, count: {}",
fd, dirent, count
);

syscall_body!(sys_getdents64, {
let expect_entries = count as usize / 280;
let dir = Directory::from_fd(fd as i32)?;
let expect_entries = count / 280;
let dir = Directory::from_fd(fd)?;
let mut my_dirent: Vec<DirEntry> =
(0..expect_entries).map(|_| DirEntry::default()).collect();

Expand Down
2 changes: 1 addition & 1 deletion api/ruxos_posix_api/src/imp/io_mpx/poll.rs
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ pub unsafe fn sys_ppoll(
pub unsafe fn sys_poll(fds: *mut ctypes::pollfd, nfds: ctypes::nfds_t, timeout: c_int) -> c_int {
debug!("sys_poll <= nfds: {} timeout: {} ms", nfds, timeout);

syscall_body!(ax_poll, {
syscall_body!(sys_poll, {
if nfds == 0 {
return Err(LinuxError::EINVAL);
}
Expand Down
17 changes: 5 additions & 12 deletions api/ruxos_posix_api/src/imp/mmap.rs
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@ pub fn sys_mprotect(addr: *mut c_void, len: ctypes::size_t, prot: c_int) -> c_in

/// Remap a virtual memory address
///
/// TODO: only support
/// TODO: null implementation
pub fn sys_mremap(
old_addr: *mut c_void,
old_size: ctypes::size_t,
Expand All @@ -84,24 +84,17 @@ pub fn sys_mremap(
"sys_mremap <= old_addr: {:p}, old_size: {}, new_size: {}, flags: {}, new_addr: {:p}",
old_addr, old_size, new_size, _flags, _new_addr
);
syscall_body!(sys_mremap, {
if old_addr.is_null() {
// TODO: It should be ctypes::MAP_FAILED,
// but it is not defined in ctypes for an unknown reason
return Ok(-1 as _);
}
Ok::<*mut c_void, LinuxError>(-1 as _)
})
syscall_body!(sys_mremap, Ok::<*mut c_void, LinuxError>(-1 as _))
}

/// give advice about use of memory
/// if success return 0, if error return -1
///
/// TODO: implement this
pub fn sys_madvice(addr: *mut c_void, len: ctypes::size_t, advice: c_int) -> c_int {
pub fn sys_madvise(addr: *mut c_void, len: ctypes::size_t, advice: c_int) -> c_int {
debug!(
"sys_madvice <= addr: {:p}, len: {}, advice: {}",
"sys_madvise <= addr: {:p}, len: {}, advice: {}",
addr, len, advice
);
syscall_body!(sys_madvice, Ok(0))
syscall_body!(sys_madvise, Ok(0))
}
1 change: 1 addition & 0 deletions api/ruxos_posix_api/src/imp/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
mod stdio;

pub mod io;
pub mod prctl;
pub mod resources;
pub mod rt_sig;
pub mod stat;
Expand Down
6 changes: 6 additions & 0 deletions api/ruxos_posix_api/src/imp/net.rs
Original file line number Diff line number Diff line change
Expand Up @@ -241,6 +241,7 @@ fn from_sockaddr(
pub fn sys_socket(domain: c_int, socktype: c_int, protocol: c_int) -> c_int {
debug!("sys_socket <= {} {} {}", domain, socktype, protocol);
let (domain, socktype, protocol) = (domain as u32, socktype as u32, protocol as u32);
pub const _SOCK_STREAM_NONBLOCK: u32 = ctypes::SOCK_STREAM | ctypes::SOCK_NONBLOCK;
syscall_body!(sys_socket, {
match (domain, socktype, protocol) {
(ctypes::AF_INET, ctypes::SOCK_STREAM, ctypes::IPPROTO_TCP)
Expand All @@ -251,6 +252,11 @@ pub fn sys_socket(domain: c_int, socktype: c_int, protocol: c_int) -> c_int {
| (ctypes::AF_INET, ctypes::SOCK_DGRAM, 0) => {
Socket::Udp(Mutex::new(UdpSocket::new())).add_to_fd_table()
}
(ctypes::AF_INET, _SOCK_STREAM_NONBLOCK, ctypes::IPPROTO_TCP) => {
let tcp_socket = TcpSocket::new();
tcp_socket.set_nonblocking(true);
Socket::Tcp(Mutex::new(tcp_socket)).add_to_fd_table()
}
_ => Err(LinuxError::EINVAL),
}
})
Expand Down
36 changes: 24 additions & 12 deletions api/ruxos_posix_api/src/imp/pipe.rs
Original file line number Diff line number Diff line change
Expand Up @@ -122,26 +122,38 @@ impl FileLike for Pipe {
}
let mut read_size = 0usize;
let max_len = buf.len();
let mut ring_buffer = self.buffer.lock();
// First, check if there is data in the read end.
// This loop is only runs when the write end is open
// and there is no data available
loop {
let mut ring_buffer = self.buffer.lock();
let loop_read = ring_buffer.available_read();
// If there is no data
if loop_read == 0 {
if self.write_end_close() {
return Ok(read_size);
// write end is closed, read 0 bytes.
return Ok(0);
} else {
// write end is open
drop(ring_buffer);
// Data not ready, wait for write end
crate::sys_sched_yield(); // TODO: use synconize primitive
ring_buffer = self.buffer.lock();
}
drop(ring_buffer);
// Data not ready, wait for write end
crate::sys_sched_yield(); // TODO: use synconize primitive
continue;
} else {
break;
}
for _ in 0..loop_read {
if read_size == max_len {
return Ok(read_size);
}
buf[read_size] = ring_buffer.read_byte();
read_size += 1;
}
// read data
let loop_read = ring_buffer.available_read();
for _ in 0..loop_read {
if read_size == max_len {
return Ok(read_size);
}
buf[read_size] = ring_buffer.read_byte();
read_size += 1;
}
Ok(read_size)
}

fn write(&self, buf: &[u8]) -> LinuxResult<usize> {
Expand Down
39 changes: 39 additions & 0 deletions api/ruxos_posix_api/src/imp/prctl.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
/* Copyright (c) [2023] [Syswonder Community]
* [Ruxos] is licensed under Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at:
* http://license.coscl.org.cn/MulanPSL2
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PSL v2 for more details.
*/

use core::ffi::{c_int, c_ulong};

use axerrno::LinuxError;

const ARCH_SET_FS: i32 = 0x1002;

/// set thread state
pub fn sys_arch_prctl(code: c_int, addr: c_ulong) -> c_int {
debug!("sys_arch_prctl <= code: {}, addr: {:#x}", code, addr);
syscall_body!(sys_arch_prctl, {
match code {
ARCH_SET_FS => {
unsafe {
ruxhal::arch::write_thread_pointer(addr as _);
}
Ok(0)
}
_ => Err(LinuxError::EINVAL),
}
})
}

/// TODO: fake implementation for prctl
pub fn sys_prctl(op: c_int, arg0: c_ulong, arg1: c_ulong, arg2: c_ulong, arg3: c_ulong) -> c_int {
debug!(
"sys_prctl <= op: {}, arg0: {}, arg1: {}, arg2: {}, arg3: {}",
op, arg0, arg1, arg2, arg3
);
syscall_body!(sys_prctl, Ok(0))
}
3 changes: 2 additions & 1 deletion api/ruxos_posix_api/src/imp/pthread/futex.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ use ruxtask::{current, AxTaskRef, TaskState, WaitQueue};

use crate::ctypes;

#[derive(Debug)]
enum FutexFlags {
Wait,
Wake,
Expand Down Expand Up @@ -59,7 +60,7 @@ pub fn sys_futex(
check_dead_wait();
let flag = FutexFlags::from(op);
let current_task = current();
let timeout = if to != 0 {
let timeout = if to != 0 && to > 0xffff000000000000usize {
let dur = unsafe { Duration::from(*(to as *const ctypes::timespec)) };
dur.as_nanos() as u64
} else {
Expand Down
58 changes: 56 additions & 2 deletions api/ruxos_posix_api/src/imp/pthread/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -97,7 +97,7 @@ impl Pthread {
}

/// Posix create, used by musl libc
#[cfg(feature = "musl")]
#[cfg(all(feature = "musl", any(target_arch = "x86_64", target_arch = "aarch64")))]
fn pcreate(
_attr: *const ctypes::pthread_attr_t,
start_routine: extern "C" fn(arg: *mut c_void) -> *mut c_void,
Expand Down Expand Up @@ -239,7 +239,7 @@ unsafe impl<T> Send for ForceSendSync<T> {}
unsafe impl<T> Sync for ForceSendSync<T> {}

/// Create new thread by `sys_clone`, return new thread ID
#[cfg(feature = "musl")]
#[cfg(all(feature = "musl", target_arch = "aarch64"))]
pub unsafe fn sys_clone(
flags: c_int,
stack: *mut c_void,
Expand Down Expand Up @@ -291,6 +291,60 @@ pub unsafe fn sys_clone(
})
}

/// Create new thread by `sys_clone`, return new thread ID
#[cfg(all(feature = "musl", target_arch = "x86_64"))]
pub unsafe fn sys_clone(
flags: c_int,
stack: *mut c_void, // for x86_64, stack points to arg
ptid: *mut ctypes::pid_t,
ctid: *mut ctypes::pid_t,
tls: *mut c_void,
func: *mut c_void,
) -> c_int {
debug!(
"sys_clone <= flags: {:x}, stack: {:p}, ctid: {:x}, func: {:x}, tls: {:#x}",
flags, stack, ctid as usize, func as usize, tls as usize,
);

syscall_body!(sys_clone, {
if (flags as u32 & ctypes::CLONE_THREAD) == 0 {
debug!("ONLY support thread");
return Err(LinuxError::EINVAL);
}

let func = unsafe {
core::mem::transmute::<*const (), extern "C" fn(arg: *mut c_void) -> *mut c_void>(
func as usize as *const (),
)
};
let args = unsafe { *((stack as usize) as *mut usize) } as *mut c_void;

let set_tid = if (flags as u32 & ctypes::CLONE_CHILD_SETTID) != 0 {
core::sync::atomic::AtomicU64::new(ctid as _)
} else {
core::sync::atomic::AtomicU64::new(0)
};

let (tid, task_inner) = Pthread::pcreate(
core::ptr::null(),
func,
args,
tls,
set_tid,
core::sync::atomic::AtomicU64::from(ctid as u64),
)?;

// write tid to ptid
if (flags as u32 & ctypes::CLONE_PARENT_SETTID) != 0 {
unsafe { *ptid = tid as c_int };
}

ruxtask::put_task(task_inner);

Ok(tid)
})
}

/// Set child tid address
#[cfg(feature = "musl")]
pub fn sys_set_tid_address(tid: usize) -> c_int {
Expand Down
Loading
Loading