syscall.rs 58 KB

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