mod.rs 49 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502
  1. use crate::filesystem::overlayfs::OverlayMountData;
  2. use crate::filesystem::vfs::FileSystemMakerData;
  3. use core::mem::size_of;
  4. use alloc::{string::String, sync::Arc, vec::Vec};
  5. use log::warn;
  6. use system_error::SystemError;
  7. use crate::producefs;
  8. use crate::syscall::user_access::UserBufferReader;
  9. use crate::{
  10. driver::base::{block::SeekFrom, device::device_number::DeviceNumber},
  11. filesystem::vfs::{file::FileDescriptorVec, vcore as Vcore},
  12. libs::rwlock::RwLockWriteGuard,
  13. mm::VirtAddr,
  14. process::ProcessManager,
  15. syscall::{
  16. user_access::{self, check_and_clone_cstr, UserBufferWriter},
  17. Syscall,
  18. },
  19. time::{syscall::PosixTimeval, PosixTimeSpec},
  20. };
  21. use super::stat::{do_newfstatat, do_statx, vfs_fstat};
  22. use super::vcore::do_symlinkat;
  23. use super::{
  24. fcntl::{AtFlags, FcntlCommand, FD_CLOEXEC},
  25. file::{File, FileMode},
  26. open::{
  27. do_faccessat, do_fchmodat, do_fchownat, do_sys_open, do_utimensat, do_utimes, ksys_fchown,
  28. },
  29. utils::{rsplit_path, user_path_at},
  30. vcore::{do_mkdir_at, do_remove_dir, do_unlink_at},
  31. Dirent, FileType, IndexNode, SuperBlock, FSMAKER, MAX_PATHLEN, ROOT_INODE,
  32. VFS_MAX_FOLLOW_SYMLINK_TIMES,
  33. };
  34. mod open_utils;
  35. mod sys_close;
  36. #[cfg(any(target_arch = "x86_64", target_arch = "riscv64"))]
  37. mod sys_fstat;
  38. mod sys_ioctl;
  39. #[cfg(target_arch = "x86_64")]
  40. mod sys_lstat;
  41. #[cfg(target_arch = "x86_64")]
  42. mod sys_open;
  43. mod sys_read;
  44. mod sys_readv;
  45. #[cfg(target_arch = "x86_64")]
  46. mod sys_stat;
  47. mod sys_write;
  48. mod sys_writev;
  49. pub const SEEK_SET: u32 = 0;
  50. pub const SEEK_CUR: u32 = 1;
  51. pub const SEEK_END: u32 = 2;
  52. pub const SEEK_MAX: u32 = 3;
  53. bitflags! {
  54. /// 文件类型和权限
  55. #[repr(C)]
  56. pub struct ModeType: u32 {
  57. /// 掩码
  58. const S_IFMT = 0o0_170_000;
  59. /// 文件类型
  60. const S_IFSOCK = 0o140000;
  61. const S_IFLNK = 0o120000;
  62. const S_IFREG = 0o100000;
  63. const S_IFBLK = 0o060000;
  64. const S_IFDIR = 0o040000;
  65. const S_IFCHR = 0o020000;
  66. const S_IFIFO = 0o010000;
  67. const S_ISUID = 0o004000;
  68. const S_ISGID = 0o002000;
  69. const S_ISVTX = 0o001000;
  70. /// 文件用户权限
  71. const S_IRWXU = 0o0700;
  72. const S_IRUSR = 0o0400;
  73. const S_IWUSR = 0o0200;
  74. const S_IXUSR = 0o0100;
  75. /// 文件组权限
  76. const S_IRWXG = 0o0070;
  77. const S_IRGRP = 0o0040;
  78. const S_IWGRP = 0o0020;
  79. const S_IXGRP = 0o0010;
  80. /// 文件其他用户权限
  81. const S_IRWXO = 0o0007;
  82. const S_IROTH = 0o0004;
  83. const S_IWOTH = 0o0002;
  84. const S_IXOTH = 0o0001;
  85. /// 0o777
  86. const S_IRWXUGO = Self::S_IRWXU.bits | Self::S_IRWXG.bits | Self::S_IRWXO.bits;
  87. /// 0o7777
  88. const S_IALLUGO = Self::S_ISUID.bits | Self::S_ISGID.bits | Self::S_ISVTX.bits| Self::S_IRWXUGO.bits;
  89. /// 0o444
  90. const S_IRUGO = Self::S_IRUSR.bits | Self::S_IRGRP.bits | Self::S_IROTH.bits;
  91. /// 0o222
  92. const S_IWUGO = Self::S_IWUSR.bits | Self::S_IWGRP.bits | Self::S_IWOTH.bits;
  93. /// 0o111
  94. const S_IXUGO = Self::S_IXUSR.bits | Self::S_IXGRP.bits | Self::S_IXOTH.bits;
  95. }
  96. }
  97. #[repr(C)]
  98. #[derive(Clone, Copy)]
  99. /// # 文件信息结构体X
  100. pub struct PosixStatx {
  101. /* 0x00 */
  102. pub stx_mask: PosixStatxMask,
  103. /// 文件系统块大小
  104. pub stx_blksize: u32,
  105. /// Flags conveying information about the file [uncond]
  106. pub stx_attributes: StxAttributes,
  107. /* 0x10 */
  108. /// 硬链接数
  109. pub stx_nlink: u32,
  110. /// 所有者用户ID
  111. pub stx_uid: u32,
  112. /// 所有者组ID
  113. pub stx_gid: u32,
  114. /// 文件权限
  115. pub stx_mode: ModeType,
  116. /* 0x20 */
  117. /// inode号
  118. pub stx_inode: u64,
  119. /// 文件大小
  120. pub stx_size: i64,
  121. /// 分配的512B块数
  122. pub stx_blocks: u64,
  123. /// Mask to show what's supported in stx_attributes
  124. pub stx_attributes_mask: StxAttributes,
  125. /* 0x40 */
  126. /// 最后访问时间
  127. pub stx_atime: PosixTimeSpec,
  128. /// 文件创建时间
  129. pub stx_btime: PosixTimeSpec,
  130. /// 最后状态变化时间
  131. pub stx_ctime: PosixTimeSpec,
  132. /// 最后修改时间
  133. pub stx_mtime: PosixTimeSpec,
  134. /* 0x80 */
  135. /// 主设备ID
  136. pub stx_rdev_major: u32,
  137. /// 次设备ID
  138. pub stx_rdev_minor: u32,
  139. /// 主硬件设备ID
  140. pub stx_dev_major: u32,
  141. /// 次硬件设备ID
  142. pub stx_dev_minor: u32,
  143. /* 0x90 */
  144. pub stx_mnt_id: u64,
  145. pub stx_dio_mem_align: u32,
  146. pub stx_dio_offset_align: u32,
  147. }
  148. impl PosixStatx {
  149. #[inline(never)]
  150. pub(super) fn new() -> Self {
  151. Self {
  152. stx_mask: PosixStatxMask::STATX_BASIC_STATS,
  153. stx_blksize: 0,
  154. stx_attributes: StxAttributes::STATX_ATTR_APPEND,
  155. stx_nlink: 0,
  156. stx_uid: 0,
  157. stx_gid: 0,
  158. stx_mode: ModeType { bits: 0 },
  159. stx_inode: 0,
  160. stx_size: 0,
  161. stx_blocks: 0,
  162. stx_attributes_mask: StxAttributes::STATX_ATTR_APPEND,
  163. stx_atime: PosixTimeSpec {
  164. tv_sec: 0,
  165. tv_nsec: 0,
  166. },
  167. stx_btime: PosixTimeSpec {
  168. tv_sec: 0,
  169. tv_nsec: 0,
  170. },
  171. stx_ctime: PosixTimeSpec {
  172. tv_sec: 0,
  173. tv_nsec: 0,
  174. },
  175. stx_mtime: PosixTimeSpec {
  176. tv_sec: 0,
  177. tv_nsec: 0,
  178. },
  179. stx_rdev_major: 0,
  180. stx_rdev_minor: 0,
  181. stx_dev_major: 0,
  182. stx_dev_minor: 0,
  183. stx_mnt_id: 0,
  184. stx_dio_mem_align: 0,
  185. stx_dio_offset_align: 0,
  186. }
  187. }
  188. }
  189. bitflags! {
  190. pub struct PosixStatxMask: u32{
  191. /// Want stx_mode & S_IFMT
  192. const STATX_TYPE = 0x00000001;
  193. /// Want stx_mode & ~S_IFMT
  194. const STATX_MODE = 0x00000002;
  195. /// Want stx_nlink
  196. const STATX_NLINK = 0x00000004;
  197. /// Want stx_uid
  198. const STATX_UID = 0x00000008;
  199. /// Want stx_gid
  200. const STATX_GID = 0x00000010;
  201. /// Want stx_atime
  202. const STATX_ATIME = 0x00000020;
  203. /// Want stx_mtime
  204. const STATX_MTIME = 0x00000040;
  205. /// Want stx_ctime
  206. const STATX_CTIME = 0x00000080;
  207. /// Want stx_ino
  208. const STATX_INO = 0x00000100;
  209. /// Want stx_size
  210. const STATX_SIZE = 0x00000200;
  211. /// Want stx_blocks
  212. const STATX_BLOCKS = 0x00000400;
  213. /// [All of the above]
  214. const STATX_BASIC_STATS = 0x000007ff;
  215. /// Want stx_btime
  216. const STATX_BTIME = 0x00000800;
  217. /// The same as STATX_BASIC_STATS | STATX_BTIME.
  218. /// It is deprecated and should not be used.
  219. const STATX_ALL = 0x00000fff;
  220. /// Want stx_mnt_id (since Linux 5.8)
  221. const STATX_MNT_ID = 0x00001000;
  222. /// Want stx_dio_mem_align and stx_dio_offset_align
  223. /// (since Linux 6.1; support varies by filesystem)
  224. const STATX_DIOALIGN = 0x00002000;
  225. /// Reserved for future struct statx expansion
  226. const STATX_RESERVED = 0x80000000;
  227. /// Want/got stx_change_attr
  228. const STATX_CHANGE_COOKIE = 0x40000000;
  229. }
  230. }
  231. bitflags! {
  232. pub struct StxAttributes: u64 {
  233. /// 文件被文件系统压缩
  234. const STATX_ATTR_COMPRESSED = 0x00000004;
  235. /// 文件被标记为不可修改
  236. const STATX_ATTR_IMMUTABLE = 0x00000010;
  237. /// 文件是只追加写入的
  238. const STATX_ATTR_APPEND = 0x00000020;
  239. /// 文件不会被备份
  240. const STATX_ATTR_NODUMP = 0x00000040;
  241. /// 文件需要密钥才能在文件系统中解密
  242. const STATX_ATTR_ENCRYPTED = 0x00000800;
  243. /// 目录是自动挂载触发器
  244. const STATX_ATTR_AUTOMOUNT = 0x00001000;
  245. /// 目录是挂载点的根目录
  246. const STATX_ATTR_MOUNT_ROOT = 0x00002000;
  247. /// 文件受到 Verity 保护
  248. const STATX_ATTR_VERITY = 0x00100000;
  249. /// 文件当前处于 DAX 状态 CPU直接访问
  250. const STATX_ATTR_DAX = 0x00200000;
  251. /// version monotonically increases
  252. const STATX_ATTR_CHANGE_MONOTONIC = 0x8000000000000000;
  253. }
  254. }
  255. bitflags! {
  256. pub struct UtimensFlags: u32 {
  257. /// 不需要解释符号链接
  258. const AT_SYMLINK_NOFOLLOW = 0x100;
  259. }
  260. }
  261. #[repr(C)]
  262. #[derive(Debug, Clone, Copy)]
  263. pub struct PosixStatfs {
  264. f_type: u64,
  265. f_bsize: u64,
  266. f_blocks: u64,
  267. f_bfree: u64,
  268. f_bavail: u64,
  269. f_files: u64,
  270. f_ffree: u64,
  271. f_fsid: u64,
  272. f_namelen: u64,
  273. f_frsize: u64,
  274. f_flags: u64,
  275. f_spare: [u64; 4],
  276. }
  277. impl From<SuperBlock> for PosixStatfs {
  278. fn from(super_block: SuperBlock) -> Self {
  279. Self {
  280. f_type: super_block.magic.bits,
  281. f_bsize: super_block.bsize,
  282. f_blocks: super_block.blocks,
  283. f_bfree: super_block.bfree,
  284. f_bavail: super_block.bavail,
  285. f_files: super_block.files,
  286. f_ffree: super_block.ffree,
  287. f_fsid: super_block.fsid,
  288. f_namelen: super_block.namelen,
  289. f_frsize: super_block.frsize,
  290. f_flags: super_block.flags,
  291. f_spare: [0u64; 4],
  292. }
  293. }
  294. }
  295. ///
  296. /// Arguments for how openat2(2) should open the target path. If only @flags and
  297. /// @mode are non-zero, then openat2(2) operates very similarly to openat(2).
  298. ///
  299. /// However, unlike openat(2), unknown or invalid bits in @flags result in
  300. /// -EINVAL rather than being silently ignored. @mode must be zero unless one of
  301. /// {O_CREAT, O_TMPFILE} are set.
  302. ///
  303. /// ## 成员变量
  304. ///
  305. /// - flags: O_* flags.
  306. /// - mode: O_CREAT/O_TMPFILE file mode.
  307. /// - resolve: RESOLVE_* flags.
  308. #[derive(Debug, Clone, Copy)]
  309. #[repr(C)]
  310. pub struct PosixOpenHow {
  311. pub flags: u64,
  312. pub mode: u64,
  313. pub resolve: u64,
  314. }
  315. impl PosixOpenHow {
  316. #[allow(dead_code)]
  317. pub fn new(flags: u64, mode: u64, resolve: u64) -> Self {
  318. Self {
  319. flags,
  320. mode,
  321. resolve,
  322. }
  323. }
  324. }
  325. #[allow(dead_code)]
  326. #[derive(Debug, Clone, Copy)]
  327. pub struct OpenHow {
  328. pub o_flags: FileMode,
  329. pub mode: ModeType,
  330. pub resolve: OpenHowResolve,
  331. }
  332. impl OpenHow {
  333. pub fn new(mut o_flags: FileMode, mut mode: ModeType, resolve: OpenHowResolve) -> Self {
  334. if !o_flags.contains(FileMode::O_CREAT) {
  335. mode = ModeType::empty();
  336. }
  337. if o_flags.contains(FileMode::O_PATH) {
  338. o_flags = o_flags.intersection(FileMode::O_PATH_FLAGS);
  339. }
  340. Self {
  341. o_flags,
  342. mode,
  343. resolve,
  344. }
  345. }
  346. }
  347. impl From<PosixOpenHow> for OpenHow {
  348. fn from(posix_open_how: PosixOpenHow) -> Self {
  349. let o_flags = FileMode::from_bits_truncate(posix_open_how.flags as u32);
  350. let mode = ModeType::from_bits_truncate(posix_open_how.mode as u32);
  351. let resolve = OpenHowResolve::from_bits_truncate(posix_open_how.resolve);
  352. return Self::new(o_flags, mode, resolve);
  353. }
  354. }
  355. bitflags! {
  356. pub struct OpenHowResolve: u64{
  357. /// Block mount-point crossings
  358. /// (including bind-mounts).
  359. const RESOLVE_NO_XDEV = 0x01;
  360. /// Block traversal through procfs-style
  361. /// "magic-links"
  362. const RESOLVE_NO_MAGICLINKS = 0x02;
  363. /// Block traversal through all symlinks
  364. /// (implies OEXT_NO_MAGICLINKS)
  365. const RESOLVE_NO_SYMLINKS = 0x04;
  366. /// Block "lexical" trickery like
  367. /// "..", symlinks, and absolute
  368. const RESOLVE_BENEATH = 0x08;
  369. /// Make all jumps to "/" and ".."
  370. /// be scoped inside the dirfd
  371. /// (similar to chroot(2)).
  372. const RESOLVE_IN_ROOT = 0x10;
  373. // Only complete if resolution can be
  374. // completed through cached lookup. May
  375. // return -EAGAIN if that's not
  376. // possible.
  377. const RESOLVE_CACHED = 0x20;
  378. }
  379. }
  380. bitflags! {
  381. pub struct UmountFlag: i32 {
  382. const DEFAULT = 0; /* Default call to umount. */
  383. const MNT_FORCE = 1; /* Force unmounting. */
  384. const MNT_DETACH = 2; /* Just detach from the tree. */
  385. const MNT_EXPIRE = 4; /* Mark for expiry. */
  386. const UMOUNT_NOFOLLOW = 8; /* Don't follow symlink on umount. */
  387. }
  388. }
  389. impl Syscall {
  390. pub fn openat(
  391. dirfd: i32,
  392. path: *const u8,
  393. o_flags: u32,
  394. mode: u32,
  395. follow_symlink: bool,
  396. ) -> Result<usize, SystemError> {
  397. let path = check_and_clone_cstr(path, Some(MAX_PATHLEN))?
  398. .into_string()
  399. .map_err(|_| SystemError::EINVAL)?;
  400. let open_flags: FileMode = FileMode::from_bits(o_flags).ok_or(SystemError::EINVAL)?;
  401. let mode = ModeType::from_bits(mode).ok_or(SystemError::EINVAL)?;
  402. return do_sys_open(dirfd, &path, open_flags, mode, follow_symlink);
  403. }
  404. /// @brief 调整文件操作指针的位置
  405. ///
  406. /// @param fd 文件描述符编号
  407. /// @param seek 调整的方式
  408. ///
  409. /// @return Ok(usize) 调整后,文件访问指针相对于文件头部的偏移量
  410. /// @return Err(SystemError) 调整失败,返回posix错误码
  411. pub fn lseek(fd: i32, offset: i64, seek: u32) -> Result<usize, SystemError> {
  412. let seek = match seek {
  413. SEEK_SET => Ok(SeekFrom::SeekSet(offset)),
  414. SEEK_CUR => Ok(SeekFrom::SeekCurrent(offset)),
  415. SEEK_END => Ok(SeekFrom::SeekEnd(offset)),
  416. SEEK_MAX => Ok(SeekFrom::SeekEnd(0)),
  417. _ => Err(SystemError::EINVAL),
  418. }?;
  419. let binding = ProcessManager::current_pcb().fd_table();
  420. let fd_table_guard = binding.read();
  421. let file = fd_table_guard
  422. .get_file_by_fd(fd)
  423. .ok_or(SystemError::EBADF)?;
  424. // drop guard 以避免无法调度的问题
  425. drop(fd_table_guard);
  426. return file.lseek(seek);
  427. }
  428. /// # sys_pread64 系统调用的实际执行函数
  429. ///
  430. /// ## 参数
  431. /// - `fd`: 文件描述符
  432. /// - `buf`: 读出缓冲区
  433. /// - `len`: 要读取的字节数
  434. /// - `offset`: 文件偏移量
  435. pub fn pread(fd: i32, buf: &mut [u8], len: usize, offset: usize) -> Result<usize, SystemError> {
  436. let binding = ProcessManager::current_pcb().fd_table();
  437. let fd_table_guard = binding.read();
  438. let file = fd_table_guard.get_file_by_fd(fd);
  439. if file.is_none() {
  440. return Err(SystemError::EBADF);
  441. }
  442. // drop guard 以避免无法调度的问题
  443. drop(fd_table_guard);
  444. let file = file.unwrap();
  445. return file.pread(offset, len, buf);
  446. }
  447. /// # sys_pwrite64 系统调用的实际执行函数
  448. ///
  449. /// ## 参数
  450. /// - `fd`: 文件描述符
  451. /// - `buf`: 写入缓冲区
  452. /// - `len`: 要写入的字节数
  453. /// - `offset`: 文件偏移量
  454. pub fn pwrite(fd: i32, buf: &[u8], len: usize, offset: usize) -> Result<usize, SystemError> {
  455. let binding = ProcessManager::current_pcb().fd_table();
  456. let fd_table_guard = binding.read();
  457. let file = fd_table_guard.get_file_by_fd(fd);
  458. if file.is_none() {
  459. return Err(SystemError::EBADF);
  460. }
  461. // drop guard 以避免无法调度的问题
  462. drop(fd_table_guard);
  463. let file = file.unwrap();
  464. return file.pwrite(offset, len, buf);
  465. }
  466. /// @brief 切换工作目录
  467. ///
  468. /// @param dest_path 目标路径
  469. ///
  470. /// @return 返回码 描述
  471. /// 0 | 成功
  472. ///
  473. /// EACCESS | 权限不足
  474. ///
  475. /// ELOOP | 解析path时遇到路径循环
  476. ///
  477. /// ENAMETOOLONG | 路径名过长
  478. ///
  479. /// ENOENT | 目标文件或目录不存在
  480. ///
  481. /// ENODIR | 检索期间发现非目录项
  482. ///
  483. /// ENOMEM | 系统内存不足
  484. ///
  485. /// EFAULT | 错误的地址
  486. ///
  487. /// ENAMETOOLONG | 路径过长
  488. pub fn chdir(path: *const u8) -> Result<usize, SystemError> {
  489. if path.is_null() {
  490. return Err(SystemError::EFAULT);
  491. }
  492. let path = check_and_clone_cstr(path, Some(MAX_PATHLEN))?
  493. .into_string()
  494. .map_err(|_| SystemError::EINVAL)?;
  495. let proc = ProcessManager::current_pcb();
  496. // Copy path to kernel space to avoid some security issues
  497. let mut new_path = String::from("");
  498. if !path.is_empty() {
  499. let cwd = match path.as_bytes()[0] {
  500. b'/' => String::from("/"),
  501. _ => proc.basic().cwd(),
  502. };
  503. let mut cwd_vec: Vec<_> = cwd.split('/').filter(|&x| !x.is_empty()).collect();
  504. let path_split = path.split('/').filter(|&x| !x.is_empty());
  505. for seg in path_split {
  506. if seg == ".." {
  507. cwd_vec.pop();
  508. } else if seg == "." {
  509. // 当前目录
  510. } else {
  511. cwd_vec.push(seg);
  512. }
  513. }
  514. //proc.basic().set_path(String::from(""));
  515. for seg in cwd_vec {
  516. new_path.push('/');
  517. new_path.push_str(seg);
  518. }
  519. if new_path.is_empty() {
  520. new_path = String::from("/");
  521. }
  522. }
  523. let inode =
  524. match ROOT_INODE().lookup_follow_symlink(&new_path, VFS_MAX_FOLLOW_SYMLINK_TIMES) {
  525. Err(_) => {
  526. return Err(SystemError::ENOENT);
  527. }
  528. Ok(i) => i,
  529. };
  530. let metadata = inode.metadata()?;
  531. if metadata.file_type == FileType::Dir {
  532. proc.basic_mut().set_cwd(new_path);
  533. proc.fs_struct_mut().set_pwd(inode);
  534. return Ok(0);
  535. } else {
  536. return Err(SystemError::ENOTDIR);
  537. }
  538. }
  539. pub fn fchdir(fd: i32) -> Result<usize, SystemError> {
  540. let pcb = ProcessManager::current_pcb();
  541. let file = pcb
  542. .fd_table()
  543. .read()
  544. .get_file_by_fd(fd)
  545. .ok_or(SystemError::EBADF)?;
  546. let inode = file.inode();
  547. if inode.metadata()?.file_type != FileType::Dir {
  548. return Err(SystemError::ENOTDIR);
  549. }
  550. let path = inode.absolute_path()?;
  551. pcb.basic_mut().set_cwd(path);
  552. pcb.fs_struct_mut().set_pwd(inode);
  553. return Ok(0);
  554. }
  555. /// @brief 获取当前进程的工作目录路径
  556. ///
  557. /// @param buf 指向缓冲区的指针
  558. /// @param size 缓冲区的大小
  559. ///
  560. /// @return 成功,返回的指针指向包含工作目录路径的字符串
  561. /// @return 错误,没有足够的空间
  562. pub fn getcwd(buf: &mut [u8]) -> Result<VirtAddr, SystemError> {
  563. let proc = ProcessManager::current_pcb();
  564. let cwd = proc.basic().cwd();
  565. let cwd_bytes = cwd.as_bytes();
  566. let cwd_len = cwd_bytes.len();
  567. if cwd_len + 1 > buf.len() {
  568. return Err(SystemError::ENOMEM);
  569. }
  570. buf[..cwd_len].copy_from_slice(cwd_bytes);
  571. buf[cwd_len] = 0;
  572. return Ok(VirtAddr::new(buf.as_ptr() as usize));
  573. }
  574. /// @brief 获取目录中的数据
  575. ///
  576. /// TODO: 这个函数的语义与Linux不一致,需要修改!!!
  577. ///
  578. /// @param fd 文件描述符号
  579. /// @param buf 输出缓冲区
  580. ///
  581. /// @return 成功返回读取的字节数,失败返回错误码
  582. pub fn getdents(fd: i32, buf: &mut [u8]) -> Result<usize, SystemError> {
  583. let dirent =
  584. unsafe { (buf.as_mut_ptr() as *mut Dirent).as_mut() }.ok_or(SystemError::EFAULT)?;
  585. if fd < 0 || fd as usize > FileDescriptorVec::PROCESS_MAX_FD {
  586. return Err(SystemError::EBADF);
  587. }
  588. // 获取fd
  589. let binding = ProcessManager::current_pcb().fd_table();
  590. let fd_table_guard = binding.read();
  591. let file = fd_table_guard
  592. .get_file_by_fd(fd)
  593. .ok_or(SystemError::EBADF)?;
  594. // drop guard 以避免无法调度的问题
  595. drop(fd_table_guard);
  596. let res = file.readdir(dirent).map(|x| x as usize);
  597. return res;
  598. }
  599. /// @brief 创建文件夹
  600. ///
  601. /// @param path(r8) 路径 / mode(r9) 模式
  602. ///
  603. /// @return uint64_t 负数错误码 / 0表示成功
  604. pub fn mkdir(path: *const u8, mode: usize) -> Result<usize, SystemError> {
  605. let path = check_and_clone_cstr(path, Some(MAX_PATHLEN))?
  606. .into_string()
  607. .map_err(|_| SystemError::EINVAL)?;
  608. do_mkdir_at(
  609. AtFlags::AT_FDCWD.bits(),
  610. &path,
  611. FileMode::from_bits_truncate(mode as u32),
  612. )?;
  613. return Ok(0);
  614. }
  615. pub fn mkdir_at(dirfd: i32, path: *const u8, mode: usize) -> Result<usize, SystemError> {
  616. let path = check_and_clone_cstr(path, Some(MAX_PATHLEN))?
  617. .into_string()
  618. .map_err(|_| SystemError::EINVAL)?;
  619. do_mkdir_at(dirfd, &path, FileMode::from_bits_truncate(mode as u32))?;
  620. return Ok(0);
  621. }
  622. /// **创建硬连接的系统调用**
  623. ///
  624. /// ## 参数
  625. ///
  626. /// - 'oldfd': 用于解析源文件路径的文件描述符
  627. /// - 'old': 源文件路径
  628. /// - 'newfd': 用于解析新文件路径的文件描述符
  629. /// - 'new': 新文件将创建的路径
  630. /// - 'flags': 标志位,仅以位或方式包含AT_EMPTY_PATH和AT_SYMLINK_FOLLOW
  631. ///
  632. ///
  633. pub fn do_linkat(
  634. oldfd: i32,
  635. old: &str,
  636. newfd: i32,
  637. new: &str,
  638. flags: AtFlags,
  639. ) -> Result<usize, SystemError> {
  640. // flag包含其他未规定值时返回EINVAL
  641. if !(AtFlags::AT_EMPTY_PATH | AtFlags::AT_SYMLINK_FOLLOW).contains(flags) {
  642. return Err(SystemError::EINVAL);
  643. }
  644. // TODO AT_EMPTY_PATH标志启用时,进行调用者CAP_DAC_READ_SEARCH或相似的检查
  645. let symlink_times = if flags.contains(AtFlags::AT_SYMLINK_FOLLOW) {
  646. 0_usize
  647. } else {
  648. VFS_MAX_FOLLOW_SYMLINK_TIMES
  649. };
  650. let pcb = ProcessManager::current_pcb();
  651. // 得到源路径的inode
  652. let old_inode: Arc<dyn IndexNode> = if old.is_empty() {
  653. if flags.contains(AtFlags::AT_EMPTY_PATH) {
  654. // 在AT_EMPTY_PATH启用时,old可以为空,old_inode实际为oldfd所指文件,但该文件不能为目录。
  655. let binding = pcb.fd_table();
  656. let fd_table_guard = binding.read();
  657. let file = fd_table_guard
  658. .get_file_by_fd(oldfd)
  659. .ok_or(SystemError::EBADF)?;
  660. let old_inode = file.inode();
  661. old_inode
  662. } else {
  663. return Err(SystemError::ENONET);
  664. }
  665. } else {
  666. let (old_begin_inode, old_remain_path) = user_path_at(&pcb, oldfd, old)?;
  667. old_begin_inode.lookup_follow_symlink(&old_remain_path, symlink_times)?
  668. };
  669. // old_inode为目录时返回EPERM
  670. if old_inode.metadata().unwrap().file_type == FileType::Dir {
  671. return Err(SystemError::EPERM);
  672. }
  673. // 得到新创建节点的父节点
  674. let (new_begin_inode, new_remain_path) = user_path_at(&pcb, newfd, new)?;
  675. let (new_name, new_parent_path) = rsplit_path(&new_remain_path);
  676. let new_parent =
  677. new_begin_inode.lookup_follow_symlink(new_parent_path.unwrap_or("/"), symlink_times)?;
  678. // 被调用者利用downcast_ref判断两inode是否为同一文件系统
  679. return new_parent.link(new_name, &old_inode).map(|_| 0);
  680. }
  681. pub fn link(old: *const u8, new: *const u8) -> Result<usize, SystemError> {
  682. let get_path = |cstr: *const u8| -> Result<String, SystemError> {
  683. let res = check_and_clone_cstr(cstr, Some(MAX_PATHLEN))?
  684. .into_string()
  685. .map_err(|_| SystemError::EINVAL)?;
  686. if res.len() >= MAX_PATHLEN {
  687. return Err(SystemError::ENAMETOOLONG);
  688. }
  689. if res.is_empty() {
  690. return Err(SystemError::ENOENT);
  691. }
  692. Ok(res)
  693. };
  694. let old = get_path(old)?;
  695. let new = get_path(new)?;
  696. return Self::do_linkat(
  697. AtFlags::AT_FDCWD.bits(),
  698. &old,
  699. AtFlags::AT_FDCWD.bits(),
  700. &new,
  701. AtFlags::empty(),
  702. );
  703. }
  704. pub fn linkat(
  705. oldfd: i32,
  706. old: *const u8,
  707. newfd: i32,
  708. new: *const u8,
  709. flags: i32,
  710. ) -> Result<usize, SystemError> {
  711. let old = check_and_clone_cstr(old, Some(MAX_PATHLEN))?
  712. .into_string()
  713. .map_err(|_| SystemError::EINVAL)?;
  714. let new = check_and_clone_cstr(new, Some(MAX_PATHLEN))?
  715. .into_string()
  716. .map_err(|_| SystemError::EINVAL)?;
  717. if old.len() >= MAX_PATHLEN || new.len() >= MAX_PATHLEN {
  718. return Err(SystemError::ENAMETOOLONG);
  719. }
  720. // old 根据flags & AtFlags::AT_EMPTY_PATH判空
  721. if new.is_empty() {
  722. return Err(SystemError::ENOENT);
  723. }
  724. let flags = AtFlags::from_bits(flags).ok_or(SystemError::EINVAL)?;
  725. Self::do_linkat(oldfd, &old, newfd, &new, flags)
  726. }
  727. /// **删除文件夹、取消文件的链接、删除文件的系统调用**
  728. ///
  729. /// ## 参数
  730. ///
  731. /// - `dirfd`:文件夹的文件描述符.目前暂未实现
  732. /// - `pathname`:文件夹的路径
  733. /// - `flags`:标志位
  734. ///
  735. ///
  736. pub fn unlinkat(dirfd: i32, path: *const u8, flags: u32) -> Result<usize, SystemError> {
  737. let flags = AtFlags::from_bits(flags as i32).ok_or(SystemError::EINVAL)?;
  738. let path = check_and_clone_cstr(path, Some(MAX_PATHLEN))?
  739. .into_string()
  740. .map_err(|_| SystemError::EINVAL)?;
  741. if flags.contains(AtFlags::AT_REMOVEDIR) {
  742. // debug!("rmdir");
  743. match do_remove_dir(dirfd, &path) {
  744. Err(err) => {
  745. return Err(err);
  746. }
  747. Ok(_) => {
  748. return Ok(0);
  749. }
  750. }
  751. }
  752. match do_unlink_at(dirfd, &path) {
  753. Err(err) => {
  754. return Err(err);
  755. }
  756. Ok(_) => {
  757. return Ok(0);
  758. }
  759. }
  760. }
  761. pub fn rmdir(path: *const u8) -> Result<usize, SystemError> {
  762. let path = check_and_clone_cstr(path, Some(MAX_PATHLEN))?
  763. .into_string()
  764. .map_err(|_| SystemError::EINVAL)?;
  765. return do_remove_dir(AtFlags::AT_FDCWD.bits(), &path).map(|v| v as usize);
  766. }
  767. pub fn unlink(path: *const u8) -> Result<usize, SystemError> {
  768. let path = check_and_clone_cstr(path, Some(MAX_PATHLEN))?
  769. .into_string()
  770. .map_err(|_| SystemError::EINVAL)?;
  771. return do_unlink_at(AtFlags::AT_FDCWD.bits(), &path).map(|v| v as usize);
  772. }
  773. pub fn symlink(oldname: *const u8, newname: *const u8) -> Result<usize, SystemError> {
  774. return do_symlinkat(oldname, AtFlags::AT_FDCWD.bits(), newname);
  775. }
  776. pub fn symlinkat(
  777. oldname: *const u8,
  778. newdfd: i32,
  779. newname: *const u8,
  780. ) -> Result<usize, SystemError> {
  781. return do_symlinkat(oldname, newdfd, newname);
  782. }
  783. /// # 修改文件名
  784. ///
  785. ///
  786. /// ## 参数
  787. ///
  788. /// - oldfd: 源文件夹文件描述符
  789. /// - filename_from: 源文件路径
  790. /// - newfd: 目标文件夹文件描述符
  791. /// - filename_to: 目标文件路径
  792. /// - flags: 标志位
  793. ///
  794. ///
  795. /// ## 返回值
  796. /// - Ok(返回值类型): 返回值的说明
  797. /// - Err(错误值类型): 错误的说明
  798. ///
  799. pub fn do_renameat2(
  800. oldfd: i32,
  801. filename_from: *const u8,
  802. newfd: i32,
  803. filename_to: *const u8,
  804. _flags: u32,
  805. ) -> Result<usize, SystemError> {
  806. let filename_from = check_and_clone_cstr(filename_from, Some(MAX_PATHLEN))
  807. .unwrap()
  808. .into_string()
  809. .map_err(|_| SystemError::EINVAL)?;
  810. let filename_to = check_and_clone_cstr(filename_to, Some(MAX_PATHLEN))
  811. .unwrap()
  812. .into_string()
  813. .map_err(|_| SystemError::EINVAL)?;
  814. // 文件名过长
  815. if filename_from.len() > MAX_PATHLEN || filename_to.len() > MAX_PATHLEN {
  816. return Err(SystemError::ENAMETOOLONG);
  817. }
  818. //获取pcb,文件节点
  819. let pcb = ProcessManager::current_pcb();
  820. let (_old_inode_begin, old_remain_path) = user_path_at(&pcb, oldfd, &filename_from)?;
  821. let (_new_inode_begin, new_remain_path) = user_path_at(&pcb, newfd, &filename_to)?;
  822. //获取父目录
  823. let (old_filename, old_parent_path) = rsplit_path(&old_remain_path);
  824. let old_parent_inode = ROOT_INODE()
  825. .lookup_follow_symlink(old_parent_path.unwrap_or("/"), VFS_MAX_FOLLOW_SYMLINK_TIMES)?;
  826. let (new_filename, new_parent_path) = rsplit_path(&new_remain_path);
  827. let new_parent_inode = ROOT_INODE()
  828. .lookup_follow_symlink(new_parent_path.unwrap_or("/"), VFS_MAX_FOLLOW_SYMLINK_TIMES)?;
  829. old_parent_inode.move_to(old_filename, &new_parent_inode, new_filename)?;
  830. return Ok(0);
  831. }
  832. /// @brief 根据提供的文件描述符的fd,复制对应的文件结构体,并返回新复制的文件结构体对应的fd
  833. pub fn dup(oldfd: i32) -> Result<usize, SystemError> {
  834. let binding = ProcessManager::current_pcb().fd_table();
  835. let mut fd_table_guard = binding.write();
  836. let old_file = fd_table_guard
  837. .get_file_by_fd(oldfd)
  838. .ok_or(SystemError::EBADF)?;
  839. let new_file = old_file.try_clone().ok_or(SystemError::EBADF)?;
  840. // dup默认非cloexec
  841. new_file.set_close_on_exec(false);
  842. // 申请文件描述符,并把文件对象存入其中
  843. let res = fd_table_guard.alloc_fd(new_file, None).map(|x| x as usize);
  844. return res;
  845. }
  846. /// 根据提供的文件描述符的fd,和指定新fd,复制对应的文件结构体,
  847. /// 并返回新复制的文件结构体对应的fd.
  848. /// 如果新fd已经打开,则会先关闭新fd.
  849. ///
  850. /// ## 参数
  851. ///
  852. /// - `oldfd`:旧文件描述符
  853. /// - `newfd`:新文件描述符
  854. ///
  855. /// ## 返回值
  856. ///
  857. /// - 成功:新文件描述符
  858. /// - 失败:错误码
  859. pub fn dup2(oldfd: i32, newfd: i32) -> Result<usize, SystemError> {
  860. let binding = ProcessManager::current_pcb().fd_table();
  861. let mut fd_table_guard = binding.write();
  862. return Self::do_dup2(oldfd, newfd, &mut fd_table_guard);
  863. }
  864. pub fn dup3(oldfd: i32, newfd: i32, flags: u32) -> Result<usize, SystemError> {
  865. let flags = FileMode::from_bits_truncate(flags);
  866. if (flags.bits() & !FileMode::O_CLOEXEC.bits()) != 0 {
  867. return Err(SystemError::EINVAL);
  868. }
  869. if oldfd == newfd {
  870. return Err(SystemError::EINVAL);
  871. }
  872. let binding = ProcessManager::current_pcb().fd_table();
  873. let mut fd_table_guard = binding.write();
  874. return Self::do_dup3(oldfd, newfd, flags, &mut fd_table_guard);
  875. }
  876. fn do_dup2(
  877. oldfd: i32,
  878. newfd: i32,
  879. fd_table_guard: &mut RwLockWriteGuard<'_, FileDescriptorVec>,
  880. ) -> Result<usize, SystemError> {
  881. Self::do_dup3(oldfd, newfd, FileMode::empty(), fd_table_guard)
  882. }
  883. fn do_dup3(
  884. oldfd: i32,
  885. newfd: i32,
  886. flags: FileMode,
  887. fd_table_guard: &mut RwLockWriteGuard<'_, FileDescriptorVec>,
  888. ) -> Result<usize, SystemError> {
  889. // 确认oldfd, newid是否有效
  890. if !(FileDescriptorVec::validate_fd(oldfd) && FileDescriptorVec::validate_fd(newfd)) {
  891. return Err(SystemError::EBADF);
  892. }
  893. if oldfd == newfd {
  894. // 若oldfd与newfd相等
  895. return Ok(newfd as usize);
  896. }
  897. let new_exists = fd_table_guard.get_file_by_fd(newfd).is_some();
  898. if new_exists {
  899. // close newfd
  900. if fd_table_guard.drop_fd(newfd).is_err() {
  901. // An I/O error occurred while attempting to close fildes2.
  902. return Err(SystemError::EIO);
  903. }
  904. }
  905. let old_file = fd_table_guard
  906. .get_file_by_fd(oldfd)
  907. .ok_or(SystemError::EBADF)?;
  908. let new_file = old_file.try_clone().ok_or(SystemError::EBADF)?;
  909. if flags.contains(FileMode::O_CLOEXEC) {
  910. new_file.set_close_on_exec(true);
  911. } else {
  912. new_file.set_close_on_exec(false);
  913. }
  914. // 申请文件描述符,并把文件对象存入其中
  915. let res = fd_table_guard
  916. .alloc_fd(new_file, Some(newfd))
  917. .map(|x| x as usize);
  918. return res;
  919. }
  920. /// # fcntl
  921. ///
  922. /// ## 参数
  923. ///
  924. /// - `fd`:文件描述符
  925. /// - `cmd`:命令
  926. /// - `arg`:参数
  927. pub fn fcntl(fd: i32, cmd: FcntlCommand, arg: i32) -> Result<usize, SystemError> {
  928. // debug!("fcntl ({cmd:?}) fd: {fd}, arg={arg}");
  929. match cmd {
  930. FcntlCommand::DupFd | FcntlCommand::DupFdCloexec => {
  931. if arg < 0 || arg as usize >= FileDescriptorVec::PROCESS_MAX_FD {
  932. return Err(SystemError::EBADF);
  933. }
  934. let arg = arg as usize;
  935. for i in arg..FileDescriptorVec::PROCESS_MAX_FD {
  936. let binding = ProcessManager::current_pcb().fd_table();
  937. let mut fd_table_guard = binding.write();
  938. if fd_table_guard.get_file_by_fd(i as i32).is_none() {
  939. if cmd == FcntlCommand::DupFd {
  940. return Self::do_dup2(fd, i as i32, &mut fd_table_guard);
  941. } else {
  942. return Self::do_dup3(
  943. fd,
  944. i as i32,
  945. FileMode::O_CLOEXEC,
  946. &mut fd_table_guard,
  947. );
  948. }
  949. }
  950. }
  951. return Err(SystemError::EMFILE);
  952. }
  953. FcntlCommand::GetFd => {
  954. // Get file descriptor flags.
  955. let binding = ProcessManager::current_pcb().fd_table();
  956. let fd_table_guard = binding.read();
  957. if let Some(file) = fd_table_guard.get_file_by_fd(fd) {
  958. // drop guard 以避免无法调度的问题
  959. drop(fd_table_guard);
  960. if file.close_on_exec() {
  961. return Ok(FD_CLOEXEC as usize);
  962. } else {
  963. return Ok(0);
  964. }
  965. }
  966. return Err(SystemError::EBADF);
  967. }
  968. FcntlCommand::SetFd => {
  969. // Set file descriptor flags.
  970. let binding = ProcessManager::current_pcb().fd_table();
  971. let fd_table_guard = binding.write();
  972. if let Some(file) = fd_table_guard.get_file_by_fd(fd) {
  973. // drop guard 以避免无法调度的问题
  974. drop(fd_table_guard);
  975. let arg = arg as u32;
  976. if arg & FD_CLOEXEC != 0 {
  977. file.set_close_on_exec(true);
  978. } else {
  979. file.set_close_on_exec(false);
  980. }
  981. return Ok(0);
  982. }
  983. return Err(SystemError::EBADF);
  984. }
  985. FcntlCommand::GetFlags => {
  986. // Get file status flags.
  987. let binding = ProcessManager::current_pcb().fd_table();
  988. let fd_table_guard = binding.read();
  989. if let Some(file) = fd_table_guard.get_file_by_fd(fd) {
  990. // drop guard 以避免无法调度的问题
  991. drop(fd_table_guard);
  992. return Ok(file.mode().bits() as usize);
  993. }
  994. return Err(SystemError::EBADF);
  995. }
  996. FcntlCommand::SetFlags => {
  997. // Set file status flags.
  998. let binding = ProcessManager::current_pcb().fd_table();
  999. let fd_table_guard = binding.write();
  1000. if let Some(file) = fd_table_guard.get_file_by_fd(fd) {
  1001. let arg = arg as u32;
  1002. let mode = FileMode::from_bits(arg).ok_or(SystemError::EINVAL)?;
  1003. // drop guard 以避免无法调度的问题
  1004. drop(fd_table_guard);
  1005. file.set_mode(mode)?;
  1006. return Ok(0);
  1007. }
  1008. return Err(SystemError::EBADF);
  1009. }
  1010. _ => {
  1011. // TODO: unimplemented
  1012. // 未实现的命令,返回0,不报错。
  1013. warn!("fcntl: unimplemented command: {:?}, defaults to 0.", cmd);
  1014. return Err(SystemError::ENOSYS);
  1015. }
  1016. }
  1017. }
  1018. /// # ftruncate
  1019. ///
  1020. /// ## 描述
  1021. ///
  1022. /// 改变文件大小.
  1023. /// 如果文件大小大于原来的大小,那么文件的内容将会被扩展到指定的大小,新的空间将会用0填充.
  1024. /// 如果文件大小小于原来的大小,那么文件的内容将会被截断到指定的大小.
  1025. ///
  1026. /// ## 参数
  1027. ///
  1028. /// - `fd`:文件描述符
  1029. /// - `len`:文件大小
  1030. ///
  1031. /// ## 返回值
  1032. ///
  1033. /// 如果成功,返回0,否则返回错误码.
  1034. pub fn ftruncate(fd: i32, len: usize) -> Result<usize, SystemError> {
  1035. let binding = ProcessManager::current_pcb().fd_table();
  1036. let fd_table_guard = binding.read();
  1037. if let Some(file) = fd_table_guard.get_file_by_fd(fd) {
  1038. // drop guard 以避免无法调度的问题
  1039. drop(fd_table_guard);
  1040. let r = file.ftruncate(len).map(|_| 0);
  1041. return r;
  1042. }
  1043. return Err(SystemError::EBADF);
  1044. }
  1045. pub fn statfs(path: *const u8, user_statfs: *mut PosixStatfs) -> Result<usize, SystemError> {
  1046. let mut writer = UserBufferWriter::new(user_statfs, size_of::<PosixStatfs>(), true)?;
  1047. let fd = open_utils::do_open(
  1048. path,
  1049. FileMode::O_RDONLY.bits(),
  1050. ModeType::empty().bits(),
  1051. true,
  1052. )?;
  1053. let path = check_and_clone_cstr(path, Some(MAX_PATHLEN))
  1054. .unwrap()
  1055. .into_string()
  1056. .map_err(|_| SystemError::EINVAL)?;
  1057. let pcb = ProcessManager::current_pcb();
  1058. let (_inode_begin, remain_path) = user_path_at(&pcb, fd as i32, &path)?;
  1059. let inode = ROOT_INODE().lookup_follow_symlink(&remain_path, MAX_PATHLEN)?;
  1060. let statfs = PosixStatfs::from(inode.fs().super_block());
  1061. writer.copy_one_to_user(&statfs, 0)?;
  1062. return Ok(0);
  1063. }
  1064. pub fn fstatfs(fd: i32, user_statfs: *mut PosixStatfs) -> Result<usize, SystemError> {
  1065. let mut writer = UserBufferWriter::new(user_statfs, size_of::<PosixStatfs>(), true)?;
  1066. let binding = ProcessManager::current_pcb().fd_table();
  1067. let fd_table_guard = binding.read();
  1068. let file = fd_table_guard
  1069. .get_file_by_fd(fd)
  1070. .ok_or(SystemError::EBADF)?;
  1071. drop(fd_table_guard);
  1072. let statfs = PosixStatfs::from(file.inode().fs().super_block());
  1073. writer.copy_one_to_user(&statfs, 0)?;
  1074. return Ok(0);
  1075. }
  1076. #[inline(never)]
  1077. pub fn statx(
  1078. dfd: i32,
  1079. filename_ptr: usize,
  1080. flags: u32,
  1081. mask: u32,
  1082. user_kstat_ptr: usize,
  1083. ) -> Result<usize, SystemError> {
  1084. if user_kstat_ptr == 0 {
  1085. return Err(SystemError::EFAULT);
  1086. }
  1087. let filename = check_and_clone_cstr(filename_ptr as *const u8, Some(MAX_PATHLEN))?;
  1088. let filename_str = filename.to_str().map_err(|_| SystemError::EINVAL)?;
  1089. do_statx(dfd, filename_str, flags, mask, user_kstat_ptr).map(|_| 0)
  1090. }
  1091. #[inline(never)]
  1092. pub fn newfstatat(
  1093. dfd: i32,
  1094. filename_ptr: usize,
  1095. user_stat_buf_ptr: usize,
  1096. flags: u32,
  1097. ) -> Result<usize, SystemError> {
  1098. if user_stat_buf_ptr == 0 {
  1099. return Err(SystemError::EFAULT);
  1100. }
  1101. let filename = check_and_clone_cstr(filename_ptr as *const u8, Some(MAX_PATHLEN))?;
  1102. let filename_str = filename.to_str().map_err(|_| SystemError::EINVAL)?;
  1103. do_newfstatat(dfd, filename_str, user_stat_buf_ptr, flags).map(|_| 0)
  1104. }
  1105. #[inline(never)]
  1106. pub fn newfstat(fd: i32, user_stat_buf_ptr: usize) -> Result<usize, SystemError> {
  1107. if user_stat_buf_ptr == 0 {
  1108. return Err(SystemError::EFAULT);
  1109. }
  1110. let stat = vfs_fstat(fd)?;
  1111. // log::debug!("newfstat fd: {}, stat.size: {:?}",fd,stat.size);
  1112. super::stat::cp_new_stat(stat, user_stat_buf_ptr).map(|_| 0)
  1113. }
  1114. pub fn mknod(
  1115. path: *const u8,
  1116. mode: ModeType,
  1117. dev_t: DeviceNumber,
  1118. ) -> Result<usize, SystemError> {
  1119. let path = check_and_clone_cstr(path, Some(MAX_PATHLEN))?
  1120. .into_string()
  1121. .map_err(|_| SystemError::EINVAL)?;
  1122. let path = path.as_str().trim();
  1123. let inode: Result<Arc<dyn IndexNode>, SystemError> =
  1124. ROOT_INODE().lookup_follow_symlink(path, VFS_MAX_FOLLOW_SYMLINK_TIMES);
  1125. if inode.is_ok() {
  1126. return Err(SystemError::EEXIST);
  1127. }
  1128. let (filename, parent_path) = rsplit_path(path);
  1129. // 查找父目录
  1130. let parent_inode: Arc<dyn IndexNode> = ROOT_INODE()
  1131. .lookup_follow_symlink(parent_path.unwrap_or("/"), VFS_MAX_FOLLOW_SYMLINK_TIMES)?;
  1132. // 创建nod
  1133. parent_inode.mknod(filename, mode, dev_t)?;
  1134. return Ok(0);
  1135. }
  1136. pub fn readlink_at(
  1137. dirfd: i32,
  1138. path: *const u8,
  1139. user_buf: *mut u8,
  1140. buf_size: usize,
  1141. ) -> Result<usize, SystemError> {
  1142. let path = check_and_clone_cstr(path, Some(MAX_PATHLEN))?
  1143. .into_string()
  1144. .map_err(|_| SystemError::EINVAL)?;
  1145. let path = path.as_str().trim();
  1146. let mut user_buf = UserBufferWriter::new(user_buf, buf_size, true)?;
  1147. let (inode, path) = user_path_at(&ProcessManager::current_pcb(), dirfd, path)?;
  1148. let inode = inode.lookup(path.as_str())?;
  1149. if inode.metadata()?.file_type != FileType::SymLink {
  1150. return Err(SystemError::EINVAL);
  1151. }
  1152. let ubuf = user_buf.buffer::<u8>(0).unwrap();
  1153. let file = File::new(inode, FileMode::O_RDONLY)?;
  1154. let len = file.read(buf_size, ubuf)?;
  1155. return Ok(len);
  1156. }
  1157. pub fn readlink(
  1158. path: *const u8,
  1159. user_buf: *mut u8,
  1160. buf_size: usize,
  1161. ) -> Result<usize, SystemError> {
  1162. return Self::readlink_at(AtFlags::AT_FDCWD.bits(), path, user_buf, buf_size);
  1163. }
  1164. pub fn access(pathname: *const u8, mode: u32) -> Result<usize, SystemError> {
  1165. return do_faccessat(
  1166. AtFlags::AT_FDCWD.bits(),
  1167. pathname,
  1168. ModeType::from_bits(mode).ok_or(SystemError::EINVAL)?,
  1169. 0,
  1170. );
  1171. }
  1172. pub fn faccessat2(
  1173. dirfd: i32,
  1174. pathname: *const u8,
  1175. mode: u32,
  1176. flags: u32,
  1177. ) -> Result<usize, SystemError> {
  1178. return do_faccessat(
  1179. dirfd,
  1180. pathname,
  1181. ModeType::from_bits(mode).ok_or(SystemError::EINVAL)?,
  1182. flags,
  1183. );
  1184. }
  1185. pub fn chmod(pathname: *const u8, mode: u32) -> Result<usize, SystemError> {
  1186. return do_fchmodat(
  1187. AtFlags::AT_FDCWD.bits(),
  1188. pathname,
  1189. ModeType::from_bits(mode).ok_or(SystemError::EINVAL)?,
  1190. );
  1191. }
  1192. pub fn fchmodat(dirfd: i32, pathname: *const u8, mode: u32) -> Result<usize, SystemError> {
  1193. return do_fchmodat(
  1194. dirfd,
  1195. pathname,
  1196. ModeType::from_bits(mode).ok_or(SystemError::EINVAL)?,
  1197. );
  1198. }
  1199. pub fn fchmod(fd: i32, mode: u32) -> Result<usize, SystemError> {
  1200. let _mode = ModeType::from_bits(mode).ok_or(SystemError::EINVAL)?;
  1201. let binding = ProcessManager::current_pcb().fd_table();
  1202. let fd_table_guard = binding.read();
  1203. let _file = fd_table_guard
  1204. .get_file_by_fd(fd)
  1205. .ok_or(SystemError::EBADF)?;
  1206. // fchmod没完全实现,因此不修改文件的权限
  1207. // todo: 实现fchmod
  1208. warn!("fchmod not fully implemented");
  1209. return Ok(0);
  1210. }
  1211. pub fn chown(pathname: *const u8, uid: usize, gid: usize) -> Result<usize, SystemError> {
  1212. let pathname = user_access::check_and_clone_cstr(pathname, Some(MAX_PATHLEN))?
  1213. .into_string()
  1214. .map_err(|_| SystemError::EINVAL)?;
  1215. return do_fchownat(
  1216. AtFlags::AT_FDCWD.bits(),
  1217. &pathname,
  1218. uid,
  1219. gid,
  1220. AtFlags::AT_STATX_SYNC_AS_STAT,
  1221. );
  1222. }
  1223. pub fn lchown(pathname: *const u8, uid: usize, gid: usize) -> Result<usize, SystemError> {
  1224. let pathname = user_access::check_and_clone_cstr(pathname, Some(MAX_PATHLEN))?
  1225. .into_string()
  1226. .map_err(|_| SystemError::EINVAL)?;
  1227. return do_fchownat(
  1228. AtFlags::AT_FDCWD.bits(),
  1229. &pathname,
  1230. uid,
  1231. gid,
  1232. AtFlags::AT_SYMLINK_NOFOLLOW,
  1233. );
  1234. }
  1235. pub fn fchownat(
  1236. dirfd: i32,
  1237. pathname: *const u8,
  1238. uid: usize,
  1239. gid: usize,
  1240. flags: i32,
  1241. ) -> Result<usize, SystemError> {
  1242. let pathname = user_access::check_and_clone_cstr(pathname, Some(MAX_PATHLEN))?
  1243. .into_string()
  1244. .map_err(|_| SystemError::EINVAL)?;
  1245. let pathname = pathname.as_str().trim();
  1246. let flags = AtFlags::from_bits_truncate(flags);
  1247. return do_fchownat(dirfd, pathname, uid, gid, flags);
  1248. }
  1249. pub fn fchown(fd: i32, uid: usize, gid: usize) -> Result<usize, SystemError> {
  1250. return ksys_fchown(fd, uid, gid);
  1251. }
  1252. /// #挂载文件系统
  1253. ///
  1254. /// 用于挂载文件系统,目前仅支持ramfs挂载
  1255. ///
  1256. /// ## 参数:
  1257. ///
  1258. /// - source 挂载设备(暂时不支持)
  1259. /// - target 挂载目录
  1260. /// - filesystemtype 文件系统
  1261. /// - mountflags 挂载选项(暂未实现)
  1262. /// - data 带数据挂载
  1263. ///
  1264. /// ## 返回值
  1265. /// - Ok(0): 挂载成功
  1266. /// - Err(SystemError) :挂载过程中出错
  1267. pub fn mount(
  1268. _source: *const u8,
  1269. target: *const u8,
  1270. filesystemtype: *const u8,
  1271. _mountflags: usize,
  1272. data: *const u8,
  1273. ) -> Result<usize, SystemError> {
  1274. let target = user_access::check_and_clone_cstr(target, Some(MAX_PATHLEN))?
  1275. .into_string()
  1276. .map_err(|_| SystemError::EINVAL)?;
  1277. let fstype_str = user_access::check_and_clone_cstr(filesystemtype, Some(MAX_PATHLEN))?;
  1278. let fstype_str = fstype_str.to_str().map_err(|_| SystemError::EINVAL)?;
  1279. let fstype = producefs!(FSMAKER, fstype_str, data)?;
  1280. Vcore::do_mount(fstype, &target)?;
  1281. return Ok(0);
  1282. }
  1283. // 想法:可以在VFS中实现一个文件系统分发器,流程如下:
  1284. // 1. 接受从上方传来的文件类型字符串
  1285. // 2. 将传入值与启动时准备好的字符串数组逐个比较(probe)
  1286. // 3. 直接在函数内调用构造方法并直接返回文件系统对象
  1287. /// src/linux/mount.c `umount` & `umount2`
  1288. ///
  1289. /// [umount(2) — Linux manual page](https://www.man7.org/linux/man-pages/man2/umount.2.html)
  1290. pub fn umount2(target: *const u8, flags: i32) -> Result<(), SystemError> {
  1291. let target = user_access::check_and_clone_cstr(target, Some(MAX_PATHLEN))?
  1292. .into_string()
  1293. .map_err(|_| SystemError::EINVAL)?;
  1294. Vcore::do_umount2(
  1295. AtFlags::AT_FDCWD.bits(),
  1296. &target,
  1297. UmountFlag::from_bits(flags).ok_or(SystemError::EINVAL)?,
  1298. )?;
  1299. return Ok(());
  1300. }
  1301. pub fn sys_utimensat(
  1302. dirfd: i32,
  1303. pathname: *const u8,
  1304. times: *const PosixTimeSpec,
  1305. flags: u32,
  1306. ) -> Result<usize, SystemError> {
  1307. let pathname = if pathname.is_null() {
  1308. None
  1309. } else {
  1310. let pathname = check_and_clone_cstr(pathname, Some(MAX_PATHLEN))?
  1311. .into_string()
  1312. .map_err(|_| SystemError::EINVAL)?;
  1313. Some(pathname)
  1314. };
  1315. let flags = UtimensFlags::from_bits(flags).ok_or(SystemError::EINVAL)?;
  1316. let times = if times.is_null() {
  1317. None
  1318. } else {
  1319. let times_reader = UserBufferReader::new(times, size_of::<PosixTimeSpec>() * 2, true)?;
  1320. let times = times_reader.read_from_user::<PosixTimeSpec>(0)?;
  1321. Some([times[0], times[1]])
  1322. };
  1323. do_utimensat(dirfd, pathname, times, flags)
  1324. }
  1325. pub fn sys_utimes(
  1326. pathname: *const u8,
  1327. times: *const PosixTimeval,
  1328. ) -> Result<usize, SystemError> {
  1329. let pathname = check_and_clone_cstr(pathname, Some(MAX_PATHLEN))?
  1330. .into_string()
  1331. .map_err(|_| SystemError::EINVAL)?;
  1332. let times = if times.is_null() {
  1333. None
  1334. } else {
  1335. let times_reader = UserBufferReader::new(times, size_of::<PosixTimeval>() * 2, true)?;
  1336. let times = times_reader.read_from_user::<PosixTimeval>(0)?;
  1337. Some([times[0], times[1]])
  1338. };
  1339. do_utimes(&pathname, times)
  1340. }
  1341. }