syscall.rs 58 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778
  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_newfstatat, 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. proc.fs_struct_mut().set_pwd(inode);
  610. return Ok(0);
  611. } else {
  612. return Err(SystemError::ENOTDIR);
  613. }
  614. }
  615. pub fn fchdir(fd: i32) -> Result<usize, SystemError> {
  616. let pcb = ProcessManager::current_pcb();
  617. let file = pcb
  618. .fd_table()
  619. .read()
  620. .get_file_by_fd(fd)
  621. .ok_or(SystemError::EBADF)?;
  622. let inode = file.inode();
  623. if inode.metadata()?.file_type != FileType::Dir {
  624. return Err(SystemError::ENOTDIR);
  625. }
  626. let path = inode.absolute_path()?;
  627. pcb.basic_mut().set_cwd(path);
  628. pcb.fs_struct_mut().set_pwd(inode);
  629. return Ok(0);
  630. }
  631. /// @brief 获取当前进程的工作目录路径
  632. ///
  633. /// @param buf 指向缓冲区的指针
  634. /// @param size 缓冲区的大小
  635. ///
  636. /// @return 成功,返回的指针指向包含工作目录路径的字符串
  637. /// @return 错误,没有足够的空间
  638. pub fn getcwd(buf: &mut [u8]) -> Result<VirtAddr, SystemError> {
  639. let proc = ProcessManager::current_pcb();
  640. let cwd = proc.basic().cwd();
  641. let cwd_bytes = cwd.as_bytes();
  642. let cwd_len = cwd_bytes.len();
  643. if cwd_len + 1 > buf.len() {
  644. return Err(SystemError::ENOMEM);
  645. }
  646. buf[..cwd_len].copy_from_slice(cwd_bytes);
  647. buf[cwd_len] = 0;
  648. return Ok(VirtAddr::new(buf.as_ptr() as usize));
  649. }
  650. /// @brief 获取目录中的数据
  651. ///
  652. /// TODO: 这个函数的语义与Linux不一致,需要修改!!!
  653. ///
  654. /// @param fd 文件描述符号
  655. /// @param buf 输出缓冲区
  656. ///
  657. /// @return 成功返回读取的字节数,失败返回错误码
  658. pub fn getdents(fd: i32, buf: &mut [u8]) -> Result<usize, SystemError> {
  659. let dirent =
  660. unsafe { (buf.as_mut_ptr() as *mut Dirent).as_mut() }.ok_or(SystemError::EFAULT)?;
  661. if fd < 0 || fd as usize > FileDescriptorVec::PROCESS_MAX_FD {
  662. return Err(SystemError::EBADF);
  663. }
  664. // 获取fd
  665. let binding = ProcessManager::current_pcb().fd_table();
  666. let fd_table_guard = binding.read();
  667. let file = fd_table_guard
  668. .get_file_by_fd(fd)
  669. .ok_or(SystemError::EBADF)?;
  670. // drop guard 以避免无法调度的问题
  671. drop(fd_table_guard);
  672. let res = file.readdir(dirent).map(|x| x as usize);
  673. return res;
  674. }
  675. /// @brief 创建文件夹
  676. ///
  677. /// @param path(r8) 路径 / mode(r9) 模式
  678. ///
  679. /// @return uint64_t 负数错误码 / 0表示成功
  680. pub fn mkdir(path: *const u8, mode: usize) -> Result<usize, SystemError> {
  681. let path = check_and_clone_cstr(path, Some(MAX_PATHLEN))?
  682. .into_string()
  683. .map_err(|_| SystemError::EINVAL)?;
  684. do_mkdir_at(
  685. AtFlags::AT_FDCWD.bits(),
  686. &path,
  687. FileMode::from_bits_truncate(mode as u32),
  688. )?;
  689. return Ok(0);
  690. }
  691. pub fn mkdir_at(dirfd: i32, path: *const u8, mode: usize) -> Result<usize, SystemError> {
  692. let path = check_and_clone_cstr(path, Some(MAX_PATHLEN))?
  693. .into_string()
  694. .map_err(|_| SystemError::EINVAL)?;
  695. do_mkdir_at(dirfd, &path, FileMode::from_bits_truncate(mode as u32))?;
  696. return Ok(0);
  697. }
  698. /// **创建硬连接的系统调用**
  699. ///
  700. /// ## 参数
  701. ///
  702. /// - 'oldfd': 用于解析源文件路径的文件描述符
  703. /// - 'old': 源文件路径
  704. /// - 'newfd': 用于解析新文件路径的文件描述符
  705. /// - 'new': 新文件将创建的路径
  706. /// - 'flags': 标志位,仅以位或方式包含AT_EMPTY_PATH和AT_SYMLINK_FOLLOW
  707. ///
  708. ///
  709. pub fn do_linkat(
  710. oldfd: i32,
  711. old: &str,
  712. newfd: i32,
  713. new: &str,
  714. flags: AtFlags,
  715. ) -> Result<usize, SystemError> {
  716. // flag包含其他未规定值时返回EINVAL
  717. if !(AtFlags::AT_EMPTY_PATH | AtFlags::AT_SYMLINK_FOLLOW).contains(flags) {
  718. return Err(SystemError::EINVAL);
  719. }
  720. // TODO AT_EMPTY_PATH标志启用时,进行调用者CAP_DAC_READ_SEARCH或相似的检查
  721. let symlink_times = if flags.contains(AtFlags::AT_SYMLINK_FOLLOW) {
  722. 0_usize
  723. } else {
  724. VFS_MAX_FOLLOW_SYMLINK_TIMES
  725. };
  726. let pcb = ProcessManager::current_pcb();
  727. // 得到源路径的inode
  728. let old_inode: Arc<dyn IndexNode> = if old.is_empty() {
  729. if flags.contains(AtFlags::AT_EMPTY_PATH) {
  730. // 在AT_EMPTY_PATH启用时,old可以为空,old_inode实际为oldfd所指文件,但该文件不能为目录。
  731. let binding = pcb.fd_table();
  732. let fd_table_guard = binding.read();
  733. let file = fd_table_guard
  734. .get_file_by_fd(oldfd)
  735. .ok_or(SystemError::EBADF)?;
  736. let old_inode = file.inode();
  737. old_inode
  738. } else {
  739. return Err(SystemError::ENONET);
  740. }
  741. } else {
  742. let (old_begin_inode, old_remain_path) = user_path_at(&pcb, oldfd, old)?;
  743. old_begin_inode.lookup_follow_symlink(&old_remain_path, symlink_times)?
  744. };
  745. // old_inode为目录时返回EPERM
  746. if old_inode.metadata().unwrap().file_type == FileType::Dir {
  747. return Err(SystemError::EPERM);
  748. }
  749. // 得到新创建节点的父节点
  750. let (new_begin_inode, new_remain_path) = user_path_at(&pcb, newfd, new)?;
  751. let (new_name, new_parent_path) = rsplit_path(&new_remain_path);
  752. let new_parent =
  753. new_begin_inode.lookup_follow_symlink(new_parent_path.unwrap_or("/"), symlink_times)?;
  754. // 被调用者利用downcast_ref判断两inode是否为同一文件系统
  755. return new_parent.link(new_name, &old_inode).map(|_| 0);
  756. }
  757. pub fn link(old: *const u8, new: *const u8) -> Result<usize, SystemError> {
  758. let get_path = |cstr: *const u8| -> Result<String, SystemError> {
  759. let res = check_and_clone_cstr(cstr, Some(MAX_PATHLEN))?
  760. .into_string()
  761. .map_err(|_| SystemError::EINVAL)?;
  762. if res.len() >= MAX_PATHLEN {
  763. return Err(SystemError::ENAMETOOLONG);
  764. }
  765. if res.is_empty() {
  766. return Err(SystemError::ENOENT);
  767. }
  768. Ok(res)
  769. };
  770. let old = get_path(old)?;
  771. let new = get_path(new)?;
  772. return Self::do_linkat(
  773. AtFlags::AT_FDCWD.bits(),
  774. &old,
  775. AtFlags::AT_FDCWD.bits(),
  776. &new,
  777. AtFlags::empty(),
  778. );
  779. }
  780. pub fn linkat(
  781. oldfd: i32,
  782. old: *const u8,
  783. newfd: i32,
  784. new: *const u8,
  785. flags: i32,
  786. ) -> Result<usize, SystemError> {
  787. let old = check_and_clone_cstr(old, Some(MAX_PATHLEN))?
  788. .into_string()
  789. .map_err(|_| SystemError::EINVAL)?;
  790. let new = check_and_clone_cstr(new, Some(MAX_PATHLEN))?
  791. .into_string()
  792. .map_err(|_| SystemError::EINVAL)?;
  793. if old.len() >= MAX_PATHLEN || new.len() >= MAX_PATHLEN {
  794. return Err(SystemError::ENAMETOOLONG);
  795. }
  796. // old 根据flags & AtFlags::AT_EMPTY_PATH判空
  797. if new.is_empty() {
  798. return Err(SystemError::ENOENT);
  799. }
  800. let flags = AtFlags::from_bits(flags).ok_or(SystemError::EINVAL)?;
  801. Self::do_linkat(oldfd, &old, newfd, &new, flags)
  802. }
  803. /// **删除文件夹、取消文件的链接、删除文件的系统调用**
  804. ///
  805. /// ## 参数
  806. ///
  807. /// - `dirfd`:文件夹的文件描述符.目前暂未实现
  808. /// - `pathname`:文件夹的路径
  809. /// - `flags`:标志位
  810. ///
  811. ///
  812. pub fn unlinkat(dirfd: i32, path: *const u8, flags: u32) -> Result<usize, SystemError> {
  813. let flags = AtFlags::from_bits(flags as i32).ok_or(SystemError::EINVAL)?;
  814. let path = check_and_clone_cstr(path, Some(MAX_PATHLEN))?
  815. .into_string()
  816. .map_err(|_| SystemError::EINVAL)?;
  817. if flags.contains(AtFlags::AT_REMOVEDIR) {
  818. // debug!("rmdir");
  819. match do_remove_dir(dirfd, &path) {
  820. Err(err) => {
  821. return Err(err);
  822. }
  823. Ok(_) => {
  824. return Ok(0);
  825. }
  826. }
  827. }
  828. match do_unlink_at(dirfd, &path) {
  829. Err(err) => {
  830. return Err(err);
  831. }
  832. Ok(_) => {
  833. return Ok(0);
  834. }
  835. }
  836. }
  837. pub fn rmdir(path: *const u8) -> Result<usize, SystemError> {
  838. let path = check_and_clone_cstr(path, Some(MAX_PATHLEN))?
  839. .into_string()
  840. .map_err(|_| SystemError::EINVAL)?;
  841. return do_remove_dir(AtFlags::AT_FDCWD.bits(), &path).map(|v| v as usize);
  842. }
  843. pub fn unlink(path: *const u8) -> Result<usize, SystemError> {
  844. let path = check_and_clone_cstr(path, Some(MAX_PATHLEN))?
  845. .into_string()
  846. .map_err(|_| SystemError::EINVAL)?;
  847. return do_unlink_at(AtFlags::AT_FDCWD.bits(), &path).map(|v| v as usize);
  848. }
  849. pub fn symlink(oldname: *const u8, newname: *const u8) -> Result<usize, SystemError> {
  850. return do_symlinkat(oldname, AtFlags::AT_FDCWD.bits(), newname);
  851. }
  852. pub fn symlinkat(
  853. oldname: *const u8,
  854. newdfd: i32,
  855. newname: *const u8,
  856. ) -> Result<usize, SystemError> {
  857. return do_symlinkat(oldname, newdfd, newname);
  858. }
  859. /// # 修改文件名
  860. ///
  861. ///
  862. /// ## 参数
  863. ///
  864. /// - oldfd: 源文件夹文件描述符
  865. /// - filename_from: 源文件路径
  866. /// - newfd: 目标文件夹文件描述符
  867. /// - filename_to: 目标文件路径
  868. /// - flags: 标志位
  869. ///
  870. ///
  871. /// ## 返回值
  872. /// - Ok(返回值类型): 返回值的说明
  873. /// - Err(错误值类型): 错误的说明
  874. ///
  875. pub fn do_renameat2(
  876. oldfd: i32,
  877. filename_from: *const u8,
  878. newfd: i32,
  879. filename_to: *const u8,
  880. _flags: u32,
  881. ) -> Result<usize, SystemError> {
  882. let filename_from = check_and_clone_cstr(filename_from, Some(MAX_PATHLEN))
  883. .unwrap()
  884. .into_string()
  885. .map_err(|_| SystemError::EINVAL)?;
  886. let filename_to = check_and_clone_cstr(filename_to, Some(MAX_PATHLEN))
  887. .unwrap()
  888. .into_string()
  889. .map_err(|_| SystemError::EINVAL)?;
  890. // 文件名过长
  891. if filename_from.len() > MAX_PATHLEN || filename_to.len() > MAX_PATHLEN {
  892. return Err(SystemError::ENAMETOOLONG);
  893. }
  894. //获取pcb,文件节点
  895. let pcb = ProcessManager::current_pcb();
  896. let (_old_inode_begin, old_remain_path) = user_path_at(&pcb, oldfd, &filename_from)?;
  897. let (_new_inode_begin, new_remain_path) = user_path_at(&pcb, newfd, &filename_to)?;
  898. //获取父目录
  899. let (old_filename, old_parent_path) = rsplit_path(&old_remain_path);
  900. let old_parent_inode = ROOT_INODE()
  901. .lookup_follow_symlink(old_parent_path.unwrap_or("/"), VFS_MAX_FOLLOW_SYMLINK_TIMES)?;
  902. let (new_filename, new_parent_path) = rsplit_path(&new_remain_path);
  903. let new_parent_inode = ROOT_INODE()
  904. .lookup_follow_symlink(new_parent_path.unwrap_or("/"), VFS_MAX_FOLLOW_SYMLINK_TIMES)?;
  905. old_parent_inode.move_to(old_filename, &new_parent_inode, new_filename)?;
  906. return Ok(0);
  907. }
  908. /// @brief 根据提供的文件描述符的fd,复制对应的文件结构体,并返回新复制的文件结构体对应的fd
  909. pub fn dup(oldfd: i32) -> Result<usize, SystemError> {
  910. let binding = ProcessManager::current_pcb().fd_table();
  911. let mut fd_table_guard = binding.write();
  912. let old_file = fd_table_guard
  913. .get_file_by_fd(oldfd)
  914. .ok_or(SystemError::EBADF)?;
  915. let new_file = old_file.try_clone().ok_or(SystemError::EBADF)?;
  916. // dup默认非cloexec
  917. new_file.set_close_on_exec(false);
  918. // 申请文件描述符,并把文件对象存入其中
  919. let res = fd_table_guard.alloc_fd(new_file, None).map(|x| x as usize);
  920. return res;
  921. }
  922. /// 根据提供的文件描述符的fd,和指定新fd,复制对应的文件结构体,
  923. /// 并返回新复制的文件结构体对应的fd.
  924. /// 如果新fd已经打开,则会先关闭新fd.
  925. ///
  926. /// ## 参数
  927. ///
  928. /// - `oldfd`:旧文件描述符
  929. /// - `newfd`:新文件描述符
  930. ///
  931. /// ## 返回值
  932. ///
  933. /// - 成功:新文件描述符
  934. /// - 失败:错误码
  935. pub fn dup2(oldfd: i32, newfd: i32) -> Result<usize, SystemError> {
  936. let binding = ProcessManager::current_pcb().fd_table();
  937. let mut fd_table_guard = binding.write();
  938. return Self::do_dup2(oldfd, newfd, &mut fd_table_guard);
  939. }
  940. pub fn dup3(oldfd: i32, newfd: i32, flags: u32) -> Result<usize, SystemError> {
  941. let flags = FileMode::from_bits_truncate(flags);
  942. if (flags.bits() & !FileMode::O_CLOEXEC.bits()) != 0 {
  943. return Err(SystemError::EINVAL);
  944. }
  945. if oldfd == newfd {
  946. return Err(SystemError::EINVAL);
  947. }
  948. let binding = ProcessManager::current_pcb().fd_table();
  949. let mut fd_table_guard = binding.write();
  950. return Self::do_dup3(oldfd, newfd, flags, &mut fd_table_guard);
  951. }
  952. fn do_dup2(
  953. oldfd: i32,
  954. newfd: i32,
  955. fd_table_guard: &mut RwLockWriteGuard<'_, FileDescriptorVec>,
  956. ) -> Result<usize, SystemError> {
  957. Self::do_dup3(oldfd, newfd, FileMode::empty(), fd_table_guard)
  958. }
  959. fn do_dup3(
  960. oldfd: i32,
  961. newfd: i32,
  962. flags: FileMode,
  963. fd_table_guard: &mut RwLockWriteGuard<'_, FileDescriptorVec>,
  964. ) -> Result<usize, SystemError> {
  965. // 确认oldfd, newid是否有效
  966. if !(FileDescriptorVec::validate_fd(oldfd) && FileDescriptorVec::validate_fd(newfd)) {
  967. return Err(SystemError::EBADF);
  968. }
  969. if oldfd == newfd {
  970. // 若oldfd与newfd相等
  971. return Ok(newfd as usize);
  972. }
  973. let new_exists = fd_table_guard.get_file_by_fd(newfd).is_some();
  974. if new_exists {
  975. // close newfd
  976. if fd_table_guard.drop_fd(newfd).is_err() {
  977. // An I/O error occurred while attempting to close fildes2.
  978. return Err(SystemError::EIO);
  979. }
  980. }
  981. let old_file = fd_table_guard
  982. .get_file_by_fd(oldfd)
  983. .ok_or(SystemError::EBADF)?;
  984. let new_file = old_file.try_clone().ok_or(SystemError::EBADF)?;
  985. if flags.contains(FileMode::O_CLOEXEC) {
  986. new_file.set_close_on_exec(true);
  987. } else {
  988. new_file.set_close_on_exec(false);
  989. }
  990. // 申请文件描述符,并把文件对象存入其中
  991. let res = fd_table_guard
  992. .alloc_fd(new_file, Some(newfd))
  993. .map(|x| x as usize);
  994. return res;
  995. }
  996. /// # fcntl
  997. ///
  998. /// ## 参数
  999. ///
  1000. /// - `fd`:文件描述符
  1001. /// - `cmd`:命令
  1002. /// - `arg`:参数
  1003. pub fn fcntl(fd: i32, cmd: FcntlCommand, arg: i32) -> Result<usize, SystemError> {
  1004. // debug!("fcntl ({cmd:?}) fd: {fd}, arg={arg}");
  1005. match cmd {
  1006. FcntlCommand::DupFd | FcntlCommand::DupFdCloexec => {
  1007. if arg < 0 || arg as usize >= FileDescriptorVec::PROCESS_MAX_FD {
  1008. return Err(SystemError::EBADF);
  1009. }
  1010. let arg = arg as usize;
  1011. for i in arg..FileDescriptorVec::PROCESS_MAX_FD {
  1012. let binding = ProcessManager::current_pcb().fd_table();
  1013. let mut fd_table_guard = binding.write();
  1014. if fd_table_guard.get_file_by_fd(i as i32).is_none() {
  1015. if cmd == FcntlCommand::DupFd {
  1016. return Self::do_dup2(fd, i as i32, &mut fd_table_guard);
  1017. } else {
  1018. return Self::do_dup3(
  1019. fd,
  1020. i as i32,
  1021. FileMode::O_CLOEXEC,
  1022. &mut fd_table_guard,
  1023. );
  1024. }
  1025. }
  1026. }
  1027. return Err(SystemError::EMFILE);
  1028. }
  1029. FcntlCommand::GetFd => {
  1030. // Get file descriptor flags.
  1031. let binding = ProcessManager::current_pcb().fd_table();
  1032. let fd_table_guard = binding.read();
  1033. if let Some(file) = fd_table_guard.get_file_by_fd(fd) {
  1034. // drop guard 以避免无法调度的问题
  1035. drop(fd_table_guard);
  1036. if file.close_on_exec() {
  1037. return Ok(FD_CLOEXEC as usize);
  1038. } else {
  1039. return Ok(0);
  1040. }
  1041. }
  1042. return Err(SystemError::EBADF);
  1043. }
  1044. FcntlCommand::SetFd => {
  1045. // Set file descriptor flags.
  1046. let binding = ProcessManager::current_pcb().fd_table();
  1047. let fd_table_guard = binding.write();
  1048. if let Some(file) = fd_table_guard.get_file_by_fd(fd) {
  1049. // drop guard 以避免无法调度的问题
  1050. drop(fd_table_guard);
  1051. let arg = arg as u32;
  1052. if arg & FD_CLOEXEC != 0 {
  1053. file.set_close_on_exec(true);
  1054. } else {
  1055. file.set_close_on_exec(false);
  1056. }
  1057. return Ok(0);
  1058. }
  1059. return Err(SystemError::EBADF);
  1060. }
  1061. FcntlCommand::GetFlags => {
  1062. // Get file status flags.
  1063. let binding = ProcessManager::current_pcb().fd_table();
  1064. let fd_table_guard = binding.read();
  1065. if let Some(file) = fd_table_guard.get_file_by_fd(fd) {
  1066. // drop guard 以避免无法调度的问题
  1067. drop(fd_table_guard);
  1068. return Ok(file.mode().bits() as usize);
  1069. }
  1070. return Err(SystemError::EBADF);
  1071. }
  1072. FcntlCommand::SetFlags => {
  1073. // Set file status flags.
  1074. let binding = ProcessManager::current_pcb().fd_table();
  1075. let fd_table_guard = binding.write();
  1076. if let Some(file) = fd_table_guard.get_file_by_fd(fd) {
  1077. let arg = arg as u32;
  1078. let mode = FileMode::from_bits(arg).ok_or(SystemError::EINVAL)?;
  1079. // drop guard 以避免无法调度的问题
  1080. drop(fd_table_guard);
  1081. file.set_mode(mode)?;
  1082. return Ok(0);
  1083. }
  1084. return Err(SystemError::EBADF);
  1085. }
  1086. _ => {
  1087. // TODO: unimplemented
  1088. // 未实现的命令,返回0,不报错。
  1089. warn!("fcntl: unimplemented command: {:?}, defaults to 0.", cmd);
  1090. return Err(SystemError::ENOSYS);
  1091. }
  1092. }
  1093. }
  1094. /// # ftruncate
  1095. ///
  1096. /// ## 描述
  1097. ///
  1098. /// 改变文件大小.
  1099. /// 如果文件大小大于原来的大小,那么文件的内容将会被扩展到指定的大小,新的空间将会用0填充.
  1100. /// 如果文件大小小于原来的大小,那么文件的内容将会被截断到指定的大小.
  1101. ///
  1102. /// ## 参数
  1103. ///
  1104. /// - `fd`:文件描述符
  1105. /// - `len`:文件大小
  1106. ///
  1107. /// ## 返回值
  1108. ///
  1109. /// 如果成功,返回0,否则返回错误码.
  1110. pub fn ftruncate(fd: i32, len: usize) -> Result<usize, SystemError> {
  1111. let binding = ProcessManager::current_pcb().fd_table();
  1112. let fd_table_guard = binding.read();
  1113. if let Some(file) = fd_table_guard.get_file_by_fd(fd) {
  1114. // drop guard 以避免无法调度的问题
  1115. drop(fd_table_guard);
  1116. let r = file.ftruncate(len).map(|_| 0);
  1117. return r;
  1118. }
  1119. return Err(SystemError::EBADF);
  1120. }
  1121. fn do_fstat(fd: i32) -> Result<PosixKstat, SystemError> {
  1122. let binding = ProcessManager::current_pcb().fd_table();
  1123. let fd_table_guard = binding.read();
  1124. let file = fd_table_guard
  1125. .get_file_by_fd(fd)
  1126. .ok_or(SystemError::EBADF)?;
  1127. // drop guard 以避免无法调度的问题
  1128. drop(fd_table_guard);
  1129. let mut kstat = PosixKstat::new();
  1130. // 获取文件信息
  1131. let metadata = file.metadata()?;
  1132. kstat.size = metadata.size;
  1133. kstat.dev_id = metadata.dev_id as u64;
  1134. kstat.inode = metadata.inode_id.into() as u64;
  1135. kstat.blcok_size = metadata.blk_size as i64;
  1136. kstat.blocks = metadata.blocks as u64;
  1137. kstat.atime.tv_sec = metadata.atime.tv_sec;
  1138. kstat.atime.tv_nsec = metadata.atime.tv_nsec;
  1139. kstat.mtime.tv_sec = metadata.mtime.tv_sec;
  1140. kstat.mtime.tv_nsec = metadata.mtime.tv_nsec;
  1141. kstat.ctime.tv_sec = metadata.ctime.tv_sec;
  1142. kstat.ctime.tv_nsec = metadata.ctime.tv_nsec;
  1143. kstat.nlink = metadata.nlinks as u64;
  1144. kstat.uid = metadata.uid as i32;
  1145. kstat.gid = metadata.gid as i32;
  1146. kstat.rdev = metadata.raw_dev.data() as i64;
  1147. kstat.mode = metadata.mode;
  1148. match file.file_type() {
  1149. FileType::File => kstat.mode.insert(ModeType::S_IFREG),
  1150. FileType::Dir => kstat.mode.insert(ModeType::S_IFDIR),
  1151. FileType::BlockDevice => kstat.mode.insert(ModeType::S_IFBLK),
  1152. FileType::CharDevice => kstat.mode.insert(ModeType::S_IFCHR),
  1153. FileType::SymLink => kstat.mode.insert(ModeType::S_IFLNK),
  1154. FileType::Socket => kstat.mode.insert(ModeType::S_IFSOCK),
  1155. FileType::Pipe => kstat.mode.insert(ModeType::S_IFIFO),
  1156. FileType::KvmDevice => kstat.mode.insert(ModeType::S_IFCHR),
  1157. FileType::FramebufferDevice => kstat.mode.insert(ModeType::S_IFCHR),
  1158. }
  1159. return Ok(kstat);
  1160. }
  1161. pub fn fstat(fd: i32, usr_kstat: *mut PosixKstat) -> Result<usize, SystemError> {
  1162. let mut writer = UserBufferWriter::new(usr_kstat, size_of::<PosixKstat>(), true)?;
  1163. let kstat = Self::do_fstat(fd)?;
  1164. writer.copy_one_to_user(&kstat, 0)?;
  1165. return Ok(0);
  1166. }
  1167. pub fn stat(path: *const u8, user_kstat: *mut PosixKstat) -> Result<usize, SystemError> {
  1168. let fd = Self::open(
  1169. path,
  1170. FileMode::O_RDONLY.bits(),
  1171. ModeType::empty().bits(),
  1172. true,
  1173. )?;
  1174. let r = Self::fstat(fd as i32, user_kstat);
  1175. Self::close(fd).ok();
  1176. return r;
  1177. }
  1178. pub fn lstat(path: *const u8, user_kstat: *mut PosixKstat) -> Result<usize, SystemError> {
  1179. let fd = Self::open(
  1180. path,
  1181. FileMode::O_RDONLY.bits(),
  1182. ModeType::empty().bits(),
  1183. false,
  1184. )?;
  1185. let r = Self::fstat(fd as i32, user_kstat);
  1186. Self::close(fd).ok();
  1187. return r;
  1188. }
  1189. pub fn statfs(path: *const u8, user_statfs: *mut PosixStatfs) -> Result<usize, SystemError> {
  1190. let mut writer = UserBufferWriter::new(user_statfs, size_of::<PosixStatfs>(), true)?;
  1191. let fd = Self::open(
  1192. path,
  1193. FileMode::O_RDONLY.bits(),
  1194. ModeType::empty().bits(),
  1195. true,
  1196. )?;
  1197. let path = check_and_clone_cstr(path, Some(MAX_PATHLEN))
  1198. .unwrap()
  1199. .into_string()
  1200. .map_err(|_| SystemError::EINVAL)?;
  1201. let pcb = ProcessManager::current_pcb();
  1202. let (_inode_begin, remain_path) = user_path_at(&pcb, fd as i32, &path)?;
  1203. let inode = ROOT_INODE().lookup_follow_symlink(&remain_path, MAX_PATHLEN)?;
  1204. let statfs = PosixStatfs::from(inode.fs().super_block());
  1205. writer.copy_one_to_user(&statfs, 0)?;
  1206. return Ok(0);
  1207. }
  1208. pub fn fstatfs(fd: i32, user_statfs: *mut PosixStatfs) -> Result<usize, SystemError> {
  1209. let mut writer = UserBufferWriter::new(user_statfs, size_of::<PosixStatfs>(), true)?;
  1210. let binding = ProcessManager::current_pcb().fd_table();
  1211. let fd_table_guard = binding.read();
  1212. let file = fd_table_guard
  1213. .get_file_by_fd(fd)
  1214. .ok_or(SystemError::EBADF)?;
  1215. drop(fd_table_guard);
  1216. let statfs = PosixStatfs::from(file.inode().fs().super_block());
  1217. writer.copy_one_to_user(&statfs, 0)?;
  1218. return Ok(0);
  1219. }
  1220. #[inline(never)]
  1221. pub fn statx(
  1222. dfd: i32,
  1223. filename_ptr: usize,
  1224. flags: u32,
  1225. mask: u32,
  1226. user_kstat_ptr: usize,
  1227. ) -> Result<usize, SystemError> {
  1228. if user_kstat_ptr == 0 {
  1229. return Err(SystemError::EFAULT);
  1230. }
  1231. let filename = check_and_clone_cstr(filename_ptr as *const u8, Some(MAX_PATHLEN))?;
  1232. let filename_str = filename.to_str().map_err(|_| SystemError::EINVAL)?;
  1233. do_statx(dfd, filename_str, flags, mask, user_kstat_ptr).map(|_| 0)
  1234. }
  1235. #[inline(never)]
  1236. pub fn newfstatat(
  1237. dfd: i32,
  1238. filename_ptr: usize,
  1239. user_stat_buf_ptr: usize,
  1240. flags: u32,
  1241. ) -> Result<usize, SystemError> {
  1242. if user_stat_buf_ptr == 0 {
  1243. return Err(SystemError::EFAULT);
  1244. }
  1245. let filename = check_and_clone_cstr(filename_ptr as *const u8, Some(MAX_PATHLEN))?;
  1246. let filename_str = filename.to_str().map_err(|_| SystemError::EINVAL)?;
  1247. do_newfstatat(dfd, filename_str, user_stat_buf_ptr, flags).map(|_| 0)
  1248. }
  1249. pub fn mknod(
  1250. path: *const u8,
  1251. mode: ModeType,
  1252. dev_t: DeviceNumber,
  1253. ) -> Result<usize, SystemError> {
  1254. let path = check_and_clone_cstr(path, Some(MAX_PATHLEN))?
  1255. .into_string()
  1256. .map_err(|_| SystemError::EINVAL)?;
  1257. let path = path.as_str().trim();
  1258. let inode: Result<Arc<dyn IndexNode>, SystemError> =
  1259. ROOT_INODE().lookup_follow_symlink(path, VFS_MAX_FOLLOW_SYMLINK_TIMES);
  1260. if inode.is_ok() {
  1261. return Err(SystemError::EEXIST);
  1262. }
  1263. let (filename, parent_path) = rsplit_path(path);
  1264. // 查找父目录
  1265. let parent_inode: Arc<dyn IndexNode> = ROOT_INODE()
  1266. .lookup_follow_symlink(parent_path.unwrap_or("/"), VFS_MAX_FOLLOW_SYMLINK_TIMES)?;
  1267. // 创建nod
  1268. parent_inode.mknod(filename, mode, dev_t)?;
  1269. return Ok(0);
  1270. }
  1271. pub fn writev(fd: i32, iov: usize, count: usize) -> Result<usize, SystemError> {
  1272. // IoVecs会进行用户态检验
  1273. let iovecs = unsafe { IoVecs::from_user(iov as *const IoVec, count, false) }?;
  1274. let data = iovecs.gather();
  1275. Self::write(fd, &data)
  1276. }
  1277. pub fn readv(fd: i32, iov: usize, count: usize) -> Result<usize, SystemError> {
  1278. // IoVecs会进行用户态检验
  1279. let mut iovecs = unsafe { IoVecs::from_user(iov as *const IoVec, count, true) }?;
  1280. let mut data = vec![0; iovecs.0.iter().map(|x| x.len()).sum()];
  1281. let len = Self::read(fd, &mut data)?;
  1282. iovecs.scatter(&data[..len]);
  1283. return Ok(len);
  1284. }
  1285. pub fn readlink_at(
  1286. dirfd: i32,
  1287. path: *const u8,
  1288. user_buf: *mut u8,
  1289. buf_size: usize,
  1290. ) -> Result<usize, SystemError> {
  1291. let path = check_and_clone_cstr(path, Some(MAX_PATHLEN))?
  1292. .into_string()
  1293. .map_err(|_| SystemError::EINVAL)?;
  1294. let path = path.as_str().trim();
  1295. let mut user_buf = UserBufferWriter::new(user_buf, buf_size, true)?;
  1296. let (inode, path) = user_path_at(&ProcessManager::current_pcb(), dirfd, path)?;
  1297. let inode = inode.lookup(path.as_str())?;
  1298. if inode.metadata()?.file_type != FileType::SymLink {
  1299. return Err(SystemError::EINVAL);
  1300. }
  1301. let ubuf = user_buf.buffer::<u8>(0).unwrap();
  1302. let file = File::new(inode, FileMode::O_RDONLY)?;
  1303. let len = file.read(buf_size, ubuf)?;
  1304. return Ok(len);
  1305. }
  1306. pub fn readlink(
  1307. path: *const u8,
  1308. user_buf: *mut u8,
  1309. buf_size: usize,
  1310. ) -> Result<usize, SystemError> {
  1311. return Self::readlink_at(AtFlags::AT_FDCWD.bits(), path, user_buf, buf_size);
  1312. }
  1313. pub fn access(pathname: *const u8, mode: u32) -> Result<usize, SystemError> {
  1314. return do_faccessat(
  1315. AtFlags::AT_FDCWD.bits(),
  1316. pathname,
  1317. ModeType::from_bits(mode).ok_or(SystemError::EINVAL)?,
  1318. 0,
  1319. );
  1320. }
  1321. pub fn faccessat2(
  1322. dirfd: i32,
  1323. pathname: *const u8,
  1324. mode: u32,
  1325. flags: u32,
  1326. ) -> Result<usize, SystemError> {
  1327. return do_faccessat(
  1328. dirfd,
  1329. pathname,
  1330. ModeType::from_bits(mode).ok_or(SystemError::EINVAL)?,
  1331. flags,
  1332. );
  1333. }
  1334. pub fn chmod(pathname: *const u8, mode: u32) -> Result<usize, SystemError> {
  1335. return do_fchmodat(
  1336. AtFlags::AT_FDCWD.bits(),
  1337. pathname,
  1338. ModeType::from_bits(mode).ok_or(SystemError::EINVAL)?,
  1339. );
  1340. }
  1341. pub fn fchmodat(dirfd: i32, pathname: *const u8, mode: u32) -> Result<usize, SystemError> {
  1342. return do_fchmodat(
  1343. dirfd,
  1344. pathname,
  1345. ModeType::from_bits(mode).ok_or(SystemError::EINVAL)?,
  1346. );
  1347. }
  1348. pub fn fchmod(fd: i32, mode: u32) -> Result<usize, SystemError> {
  1349. let _mode = ModeType::from_bits(mode).ok_or(SystemError::EINVAL)?;
  1350. let binding = ProcessManager::current_pcb().fd_table();
  1351. let fd_table_guard = binding.read();
  1352. let _file = fd_table_guard
  1353. .get_file_by_fd(fd)
  1354. .ok_or(SystemError::EBADF)?;
  1355. // fchmod没完全实现,因此不修改文件的权限
  1356. // todo: 实现fchmod
  1357. warn!("fchmod not fully implemented");
  1358. return Ok(0);
  1359. }
  1360. pub fn chown(pathname: *const u8, uid: usize, gid: usize) -> Result<usize, SystemError> {
  1361. let pathname = user_access::check_and_clone_cstr(pathname, Some(MAX_PATHLEN))?
  1362. .into_string()
  1363. .map_err(|_| SystemError::EINVAL)?;
  1364. return do_fchownat(
  1365. AtFlags::AT_FDCWD.bits(),
  1366. &pathname,
  1367. uid,
  1368. gid,
  1369. AtFlags::AT_STATX_SYNC_AS_STAT,
  1370. );
  1371. }
  1372. pub fn lchown(pathname: *const u8, uid: usize, gid: usize) -> Result<usize, SystemError> {
  1373. let pathname = user_access::check_and_clone_cstr(pathname, Some(MAX_PATHLEN))?
  1374. .into_string()
  1375. .map_err(|_| SystemError::EINVAL)?;
  1376. return do_fchownat(
  1377. AtFlags::AT_FDCWD.bits(),
  1378. &pathname,
  1379. uid,
  1380. gid,
  1381. AtFlags::AT_SYMLINK_NOFOLLOW,
  1382. );
  1383. }
  1384. pub fn fchownat(
  1385. dirfd: i32,
  1386. pathname: *const u8,
  1387. uid: usize,
  1388. gid: usize,
  1389. flags: i32,
  1390. ) -> Result<usize, SystemError> {
  1391. let pathname = user_access::check_and_clone_cstr(pathname, Some(MAX_PATHLEN))?
  1392. .into_string()
  1393. .map_err(|_| SystemError::EINVAL)?;
  1394. let pathname = pathname.as_str().trim();
  1395. let flags = AtFlags::from_bits_truncate(flags);
  1396. return do_fchownat(dirfd, pathname, uid, gid, flags);
  1397. }
  1398. pub fn fchown(fd: i32, uid: usize, gid: usize) -> Result<usize, SystemError> {
  1399. return ksys_fchown(fd, uid, gid);
  1400. }
  1401. /// #挂载文件系统
  1402. ///
  1403. /// 用于挂载文件系统,目前仅支持ramfs挂载
  1404. ///
  1405. /// ## 参数:
  1406. ///
  1407. /// - source 挂载设备(暂时不支持)
  1408. /// - target 挂载目录
  1409. /// - filesystemtype 文件系统
  1410. /// - mountflags 挂载选项(暂未实现)
  1411. /// - data 带数据挂载
  1412. ///
  1413. /// ## 返回值
  1414. /// - Ok(0): 挂载成功
  1415. /// - Err(SystemError) :挂载过程中出错
  1416. pub fn mount(
  1417. _source: *const u8,
  1418. target: *const u8,
  1419. filesystemtype: *const u8,
  1420. _mountflags: usize,
  1421. data: *const u8,
  1422. ) -> Result<usize, SystemError> {
  1423. let target = user_access::check_and_clone_cstr(target, Some(MAX_PATHLEN))?
  1424. .into_string()
  1425. .map_err(|_| SystemError::EINVAL)?;
  1426. let fstype_str = user_access::check_and_clone_cstr(filesystemtype, Some(MAX_PATHLEN))?;
  1427. let fstype_str = fstype_str.to_str().map_err(|_| SystemError::EINVAL)?;
  1428. let fstype = producefs!(FSMAKER, fstype_str, data)?;
  1429. Vcore::do_mount(fstype, &target)?;
  1430. return Ok(0);
  1431. }
  1432. // 想法:可以在VFS中实现一个文件系统分发器,流程如下:
  1433. // 1. 接受从上方传来的文件类型字符串
  1434. // 2. 将传入值与启动时准备好的字符串数组逐个比较(probe)
  1435. // 3. 直接在函数内调用构造方法并直接返回文件系统对象
  1436. /// src/linux/mount.c `umount` & `umount2`
  1437. ///
  1438. /// [umount(2) — Linux manual page](https://www.man7.org/linux/man-pages/man2/umount.2.html)
  1439. pub fn umount2(target: *const u8, flags: i32) -> Result<(), SystemError> {
  1440. let target = user_access::check_and_clone_cstr(target, Some(MAX_PATHLEN))?
  1441. .into_string()
  1442. .map_err(|_| SystemError::EINVAL)?;
  1443. Vcore::do_umount2(
  1444. AtFlags::AT_FDCWD.bits(),
  1445. &target,
  1446. UmountFlag::from_bits(flags).ok_or(SystemError::EINVAL)?,
  1447. )?;
  1448. return Ok(());
  1449. }
  1450. pub fn sys_utimensat(
  1451. dirfd: i32,
  1452. pathname: *const u8,
  1453. times: *const PosixTimeSpec,
  1454. flags: u32,
  1455. ) -> Result<usize, SystemError> {
  1456. let pathname = if pathname.is_null() {
  1457. None
  1458. } else {
  1459. let pathname = check_and_clone_cstr(pathname, Some(MAX_PATHLEN))?
  1460. .into_string()
  1461. .map_err(|_| SystemError::EINVAL)?;
  1462. Some(pathname)
  1463. };
  1464. let flags = UtimensFlags::from_bits(flags).ok_or(SystemError::EINVAL)?;
  1465. let times = if times.is_null() {
  1466. None
  1467. } else {
  1468. let times_reader = UserBufferReader::new(times, size_of::<PosixTimeSpec>() * 2, true)?;
  1469. let times = times_reader.read_from_user::<PosixTimeSpec>(0)?;
  1470. Some([times[0], times[1]])
  1471. };
  1472. do_utimensat(dirfd, pathname, times, flags)
  1473. }
  1474. pub fn sys_utimes(
  1475. pathname: *const u8,
  1476. times: *const PosixTimeval,
  1477. ) -> Result<usize, SystemError> {
  1478. let pathname = check_and_clone_cstr(pathname, Some(MAX_PATHLEN))?
  1479. .into_string()
  1480. .map_err(|_| SystemError::EINVAL)?;
  1481. let times = if times.is_null() {
  1482. None
  1483. } else {
  1484. let times_reader = UserBufferReader::new(times, size_of::<PosixTimeval>() * 2, true)?;
  1485. let times = times_reader.read_from_user::<PosixTimeval>(0)?;
  1486. Some([times[0], times[1]])
  1487. };
  1488. do_utimes(&pathname, times)
  1489. }
  1490. }
  1491. #[repr(C)]
  1492. #[derive(Debug, Clone, Copy)]
  1493. pub struct IoVec {
  1494. /// 缓冲区的起始地址
  1495. pub iov_base: *mut u8,
  1496. /// 缓冲区的长度
  1497. pub iov_len: usize,
  1498. }
  1499. /// 用于存储多个来自用户空间的IoVec
  1500. ///
  1501. /// 由于目前内核中的文件系统还不支持分散读写,所以暂时只支持将用户空间的IoVec聚合成一个缓冲区,然后进行操作。
  1502. /// TODO:支持分散读写
  1503. #[derive(Debug)]
  1504. pub struct IoVecs(Vec<&'static mut [u8]>);
  1505. impl IoVecs {
  1506. /// 从用户空间的IoVec中构造IoVecs
  1507. ///
  1508. /// @param iov 用户空间的IoVec
  1509. /// @param iovcnt 用户空间的IoVec的数量
  1510. /// @param readv 是否为readv系统调用
  1511. ///
  1512. /// @return 构造成功返回IoVecs,否则返回错误码
  1513. pub unsafe fn from_user(
  1514. iov: *const IoVec,
  1515. iovcnt: usize,
  1516. _readv: bool,
  1517. ) -> Result<Self, SystemError> {
  1518. // 检查iov指针所在空间是否合法
  1519. verify_area(
  1520. VirtAddr::new(iov as usize),
  1521. iovcnt * core::mem::size_of::<IoVec>(),
  1522. )
  1523. .map_err(|_| SystemError::EFAULT)?;
  1524. // 将用户空间的IoVec转换为引用(注意:这里的引用是静态的,因为用户空间的IoVec不会被释放)
  1525. let iovs: &[IoVec] = core::slice::from_raw_parts(iov, iovcnt);
  1526. let mut slices: Vec<&mut [u8]> = Vec::with_capacity(iovs.len());
  1527. for iov in iovs.iter() {
  1528. if iov.iov_len == 0 {
  1529. continue;
  1530. }
  1531. verify_area(
  1532. VirtAddr::new(iov.iov_base as usize),
  1533. iovcnt * core::mem::size_of::<IoVec>(),
  1534. )
  1535. .map_err(|_| SystemError::EFAULT)?;
  1536. slices.push(core::slice::from_raw_parts_mut(iov.iov_base, iov.iov_len));
  1537. }
  1538. return Ok(Self(slices));
  1539. }
  1540. /// @brief 将IoVecs中的数据聚合到一个缓冲区中
  1541. ///
  1542. /// @return 返回聚合后的缓冲区
  1543. pub fn gather(&self) -> Vec<u8> {
  1544. let mut buf = Vec::new();
  1545. for slice in self.0.iter() {
  1546. buf.extend_from_slice(slice);
  1547. }
  1548. return buf;
  1549. }
  1550. /// @brief 将给定的数据分散写入到IoVecs中
  1551. pub fn scatter(&mut self, data: &[u8]) {
  1552. let mut data: &[u8] = data;
  1553. for slice in self.0.iter_mut() {
  1554. let len = core::cmp::min(slice.len(), data.len());
  1555. if len == 0 {
  1556. continue;
  1557. }
  1558. slice[..len].copy_from_slice(&data[..len]);
  1559. data = &data[len..];
  1560. }
  1561. }
  1562. /// @brief 创建与IoVecs等长的缓冲区
  1563. ///
  1564. /// @param set_len 是否设置返回的Vec的len。
  1565. /// 如果为true,则返回的Vec的len为所有IoVec的长度之和;
  1566. /// 否则返回的Vec的len为0,capacity为所有IoVec的长度之和.
  1567. ///
  1568. /// @return 返回创建的缓冲区
  1569. pub fn new_buf(&self, set_len: bool) -> Vec<u8> {
  1570. let total_len: usize = self.0.iter().map(|slice| slice.len()).sum();
  1571. let mut buf: Vec<u8> = Vec::with_capacity(total_len);
  1572. if set_len {
  1573. buf.resize(total_len, 0);
  1574. }
  1575. return buf;
  1576. }
  1577. }