syscall.rs 58 KB

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