mod.rs 49 KB

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