syscall.rs 57 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737
  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, vfs_fstat};
  22. use super::vcore::do_symlinkat;
  23. use super::{
  24. fcntl::{AtFlags, FcntlCommand, FD_CLOEXEC},
  25. file::{File, FileMode},
  26. open::{
  27. do_faccessat, do_fchmodat, do_fchownat, do_sys_open, do_utimensat, do_utimes, ksys_fchown,
  28. },
  29. utils::{rsplit_path, user_path_at},
  30. vcore::{do_mkdir_at, do_remove_dir, do_unlink_at},
  31. Dirent, FileType, IndexNode, SuperBlock, FSMAKER, MAX_PATHLEN, ROOT_INODE,
  32. VFS_MAX_FOLLOW_SYMLINK_TIMES,
  33. };
  34. 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. #[inline(never)]
  1122. pub fn fstat(fd: i32, user_stat_ptr: usize) -> Result<usize, SystemError> {
  1123. Self::newfstat(fd, user_stat_ptr)
  1124. }
  1125. pub fn stat(path: *const u8, user_stat_ptr: usize) -> Result<usize, SystemError> {
  1126. let fd = Self::open(
  1127. path,
  1128. FileMode::O_RDONLY.bits(),
  1129. ModeType::empty().bits(),
  1130. true,
  1131. )?;
  1132. let r = Self::fstat(fd as i32, user_stat_ptr);
  1133. Self::close(fd).ok();
  1134. return r;
  1135. }
  1136. pub fn lstat(path: *const u8, user_stat_ptr: usize) -> Result<usize, SystemError> {
  1137. let fd = Self::open(
  1138. path,
  1139. FileMode::O_RDONLY.bits(),
  1140. ModeType::empty().bits(),
  1141. false,
  1142. )?;
  1143. let r = Self::fstat(fd as i32, user_stat_ptr);
  1144. Self::close(fd).ok();
  1145. return r;
  1146. }
  1147. pub fn statfs(path: *const u8, user_statfs: *mut PosixStatfs) -> Result<usize, SystemError> {
  1148. let mut writer = UserBufferWriter::new(user_statfs, size_of::<PosixStatfs>(), true)?;
  1149. let fd = Self::open(
  1150. path,
  1151. FileMode::O_RDONLY.bits(),
  1152. ModeType::empty().bits(),
  1153. true,
  1154. )?;
  1155. let path = check_and_clone_cstr(path, Some(MAX_PATHLEN))
  1156. .unwrap()
  1157. .into_string()
  1158. .map_err(|_| SystemError::EINVAL)?;
  1159. let pcb = ProcessManager::current_pcb();
  1160. let (_inode_begin, remain_path) = user_path_at(&pcb, fd as i32, &path)?;
  1161. let inode = ROOT_INODE().lookup_follow_symlink(&remain_path, MAX_PATHLEN)?;
  1162. let statfs = PosixStatfs::from(inode.fs().super_block());
  1163. writer.copy_one_to_user(&statfs, 0)?;
  1164. return Ok(0);
  1165. }
  1166. pub fn fstatfs(fd: i32, user_statfs: *mut PosixStatfs) -> Result<usize, SystemError> {
  1167. let mut writer = UserBufferWriter::new(user_statfs, size_of::<PosixStatfs>(), true)?;
  1168. let binding = ProcessManager::current_pcb().fd_table();
  1169. let fd_table_guard = binding.read();
  1170. let file = fd_table_guard
  1171. .get_file_by_fd(fd)
  1172. .ok_or(SystemError::EBADF)?;
  1173. drop(fd_table_guard);
  1174. let statfs = PosixStatfs::from(file.inode().fs().super_block());
  1175. writer.copy_one_to_user(&statfs, 0)?;
  1176. return Ok(0);
  1177. }
  1178. #[inline(never)]
  1179. pub fn statx(
  1180. dfd: i32,
  1181. filename_ptr: usize,
  1182. flags: u32,
  1183. mask: u32,
  1184. user_kstat_ptr: usize,
  1185. ) -> Result<usize, SystemError> {
  1186. if user_kstat_ptr == 0 {
  1187. return Err(SystemError::EFAULT);
  1188. }
  1189. let filename = check_and_clone_cstr(filename_ptr as *const u8, Some(MAX_PATHLEN))?;
  1190. let filename_str = filename.to_str().map_err(|_| SystemError::EINVAL)?;
  1191. do_statx(dfd, filename_str, flags, mask, user_kstat_ptr).map(|_| 0)
  1192. }
  1193. #[inline(never)]
  1194. pub fn newfstatat(
  1195. dfd: i32,
  1196. filename_ptr: usize,
  1197. user_stat_buf_ptr: usize,
  1198. flags: u32,
  1199. ) -> Result<usize, SystemError> {
  1200. if user_stat_buf_ptr == 0 {
  1201. return Err(SystemError::EFAULT);
  1202. }
  1203. let filename = check_and_clone_cstr(filename_ptr as *const u8, Some(MAX_PATHLEN))?;
  1204. let filename_str = filename.to_str().map_err(|_| SystemError::EINVAL)?;
  1205. do_newfstatat(dfd, filename_str, user_stat_buf_ptr, flags).map(|_| 0)
  1206. }
  1207. #[inline(never)]
  1208. pub fn newfstat(fd: i32, user_stat_buf_ptr: usize) -> Result<usize, SystemError> {
  1209. if user_stat_buf_ptr == 0 {
  1210. return Err(SystemError::EFAULT);
  1211. }
  1212. let stat = vfs_fstat(fd)?;
  1213. // log::debug!("newfstat fd: {}, stat.size: {:?}",fd,stat.size);
  1214. super::stat::cp_new_stat(stat, user_stat_buf_ptr).map(|_| 0)
  1215. }
  1216. pub fn mknod(
  1217. path: *const u8,
  1218. mode: ModeType,
  1219. dev_t: DeviceNumber,
  1220. ) -> Result<usize, SystemError> {
  1221. let path = check_and_clone_cstr(path, Some(MAX_PATHLEN))?
  1222. .into_string()
  1223. .map_err(|_| SystemError::EINVAL)?;
  1224. let path = path.as_str().trim();
  1225. let inode: Result<Arc<dyn IndexNode>, SystemError> =
  1226. ROOT_INODE().lookup_follow_symlink(path, VFS_MAX_FOLLOW_SYMLINK_TIMES);
  1227. if inode.is_ok() {
  1228. return Err(SystemError::EEXIST);
  1229. }
  1230. let (filename, parent_path) = rsplit_path(path);
  1231. // 查找父目录
  1232. let parent_inode: Arc<dyn IndexNode> = ROOT_INODE()
  1233. .lookup_follow_symlink(parent_path.unwrap_or("/"), VFS_MAX_FOLLOW_SYMLINK_TIMES)?;
  1234. // 创建nod
  1235. parent_inode.mknod(filename, mode, dev_t)?;
  1236. return Ok(0);
  1237. }
  1238. pub fn writev(fd: i32, iov: usize, count: usize) -> Result<usize, SystemError> {
  1239. // IoVecs会进行用户态检验
  1240. let iovecs = unsafe { IoVecs::from_user(iov as *const IoVec, count, false) }?;
  1241. let data = iovecs.gather();
  1242. Self::write(fd, &data)
  1243. }
  1244. pub fn readv(fd: i32, iov: usize, count: usize) -> Result<usize, SystemError> {
  1245. // IoVecs会进行用户态检验
  1246. let mut iovecs = unsafe { IoVecs::from_user(iov as *const IoVec, count, true) }?;
  1247. let mut data = vec![0; iovecs.0.iter().map(|x| x.len()).sum()];
  1248. let len = Self::read(fd, &mut data)?;
  1249. iovecs.scatter(&data[..len]);
  1250. return Ok(len);
  1251. }
  1252. pub fn readlink_at(
  1253. dirfd: i32,
  1254. path: *const u8,
  1255. user_buf: *mut u8,
  1256. buf_size: usize,
  1257. ) -> Result<usize, SystemError> {
  1258. let path = check_and_clone_cstr(path, Some(MAX_PATHLEN))?
  1259. .into_string()
  1260. .map_err(|_| SystemError::EINVAL)?;
  1261. let path = path.as_str().trim();
  1262. let mut user_buf = UserBufferWriter::new(user_buf, buf_size, true)?;
  1263. let (inode, path) = user_path_at(&ProcessManager::current_pcb(), dirfd, path)?;
  1264. let inode = inode.lookup(path.as_str())?;
  1265. if inode.metadata()?.file_type != FileType::SymLink {
  1266. return Err(SystemError::EINVAL);
  1267. }
  1268. let ubuf = user_buf.buffer::<u8>(0).unwrap();
  1269. let file = File::new(inode, FileMode::O_RDONLY)?;
  1270. let len = file.read(buf_size, ubuf)?;
  1271. return Ok(len);
  1272. }
  1273. pub fn readlink(
  1274. path: *const u8,
  1275. user_buf: *mut u8,
  1276. buf_size: usize,
  1277. ) -> Result<usize, SystemError> {
  1278. return Self::readlink_at(AtFlags::AT_FDCWD.bits(), path, user_buf, buf_size);
  1279. }
  1280. pub fn access(pathname: *const u8, mode: u32) -> Result<usize, SystemError> {
  1281. return do_faccessat(
  1282. AtFlags::AT_FDCWD.bits(),
  1283. pathname,
  1284. ModeType::from_bits(mode).ok_or(SystemError::EINVAL)?,
  1285. 0,
  1286. );
  1287. }
  1288. pub fn faccessat2(
  1289. dirfd: i32,
  1290. pathname: *const u8,
  1291. mode: u32,
  1292. flags: u32,
  1293. ) -> Result<usize, SystemError> {
  1294. return do_faccessat(
  1295. dirfd,
  1296. pathname,
  1297. ModeType::from_bits(mode).ok_or(SystemError::EINVAL)?,
  1298. flags,
  1299. );
  1300. }
  1301. pub fn chmod(pathname: *const u8, mode: u32) -> Result<usize, SystemError> {
  1302. return do_fchmodat(
  1303. AtFlags::AT_FDCWD.bits(),
  1304. pathname,
  1305. ModeType::from_bits(mode).ok_or(SystemError::EINVAL)?,
  1306. );
  1307. }
  1308. pub fn fchmodat(dirfd: i32, pathname: *const u8, mode: u32) -> Result<usize, SystemError> {
  1309. return do_fchmodat(
  1310. dirfd,
  1311. pathname,
  1312. ModeType::from_bits(mode).ok_or(SystemError::EINVAL)?,
  1313. );
  1314. }
  1315. pub fn fchmod(fd: i32, mode: u32) -> Result<usize, SystemError> {
  1316. let _mode = ModeType::from_bits(mode).ok_or(SystemError::EINVAL)?;
  1317. let binding = ProcessManager::current_pcb().fd_table();
  1318. let fd_table_guard = binding.read();
  1319. let _file = fd_table_guard
  1320. .get_file_by_fd(fd)
  1321. .ok_or(SystemError::EBADF)?;
  1322. // fchmod没完全实现,因此不修改文件的权限
  1323. // todo: 实现fchmod
  1324. warn!("fchmod not fully implemented");
  1325. return Ok(0);
  1326. }
  1327. pub fn chown(pathname: *const u8, uid: usize, gid: usize) -> Result<usize, SystemError> {
  1328. let pathname = user_access::check_and_clone_cstr(pathname, Some(MAX_PATHLEN))?
  1329. .into_string()
  1330. .map_err(|_| SystemError::EINVAL)?;
  1331. return do_fchownat(
  1332. AtFlags::AT_FDCWD.bits(),
  1333. &pathname,
  1334. uid,
  1335. gid,
  1336. AtFlags::AT_STATX_SYNC_AS_STAT,
  1337. );
  1338. }
  1339. pub fn lchown(pathname: *const u8, uid: usize, gid: usize) -> Result<usize, SystemError> {
  1340. let pathname = user_access::check_and_clone_cstr(pathname, Some(MAX_PATHLEN))?
  1341. .into_string()
  1342. .map_err(|_| SystemError::EINVAL)?;
  1343. return do_fchownat(
  1344. AtFlags::AT_FDCWD.bits(),
  1345. &pathname,
  1346. uid,
  1347. gid,
  1348. AtFlags::AT_SYMLINK_NOFOLLOW,
  1349. );
  1350. }
  1351. pub fn fchownat(
  1352. dirfd: i32,
  1353. pathname: *const u8,
  1354. uid: usize,
  1355. gid: usize,
  1356. flags: i32,
  1357. ) -> Result<usize, SystemError> {
  1358. let pathname = user_access::check_and_clone_cstr(pathname, Some(MAX_PATHLEN))?
  1359. .into_string()
  1360. .map_err(|_| SystemError::EINVAL)?;
  1361. let pathname = pathname.as_str().trim();
  1362. let flags = AtFlags::from_bits_truncate(flags);
  1363. return do_fchownat(dirfd, pathname, uid, gid, flags);
  1364. }
  1365. pub fn fchown(fd: i32, uid: usize, gid: usize) -> Result<usize, SystemError> {
  1366. return ksys_fchown(fd, uid, gid);
  1367. }
  1368. /// #挂载文件系统
  1369. ///
  1370. /// 用于挂载文件系统,目前仅支持ramfs挂载
  1371. ///
  1372. /// ## 参数:
  1373. ///
  1374. /// - source 挂载设备(暂时不支持)
  1375. /// - target 挂载目录
  1376. /// - filesystemtype 文件系统
  1377. /// - mountflags 挂载选项(暂未实现)
  1378. /// - data 带数据挂载
  1379. ///
  1380. /// ## 返回值
  1381. /// - Ok(0): 挂载成功
  1382. /// - Err(SystemError) :挂载过程中出错
  1383. pub fn mount(
  1384. _source: *const u8,
  1385. target: *const u8,
  1386. filesystemtype: *const u8,
  1387. _mountflags: usize,
  1388. data: *const u8,
  1389. ) -> Result<usize, SystemError> {
  1390. let target = user_access::check_and_clone_cstr(target, Some(MAX_PATHLEN))?
  1391. .into_string()
  1392. .map_err(|_| SystemError::EINVAL)?;
  1393. let fstype_str = user_access::check_and_clone_cstr(filesystemtype, Some(MAX_PATHLEN))?;
  1394. let fstype_str = fstype_str.to_str().map_err(|_| SystemError::EINVAL)?;
  1395. let fstype = producefs!(FSMAKER, fstype_str, data)?;
  1396. Vcore::do_mount(fstype, &target)?;
  1397. return Ok(0);
  1398. }
  1399. // 想法:可以在VFS中实现一个文件系统分发器,流程如下:
  1400. // 1. 接受从上方传来的文件类型字符串
  1401. // 2. 将传入值与启动时准备好的字符串数组逐个比较(probe)
  1402. // 3. 直接在函数内调用构造方法并直接返回文件系统对象
  1403. /// src/linux/mount.c `umount` & `umount2`
  1404. ///
  1405. /// [umount(2) — Linux manual page](https://www.man7.org/linux/man-pages/man2/umount.2.html)
  1406. pub fn umount2(target: *const u8, flags: i32) -> Result<(), SystemError> {
  1407. let target = user_access::check_and_clone_cstr(target, Some(MAX_PATHLEN))?
  1408. .into_string()
  1409. .map_err(|_| SystemError::EINVAL)?;
  1410. Vcore::do_umount2(
  1411. AtFlags::AT_FDCWD.bits(),
  1412. &target,
  1413. UmountFlag::from_bits(flags).ok_or(SystemError::EINVAL)?,
  1414. )?;
  1415. return Ok(());
  1416. }
  1417. pub fn sys_utimensat(
  1418. dirfd: i32,
  1419. pathname: *const u8,
  1420. times: *const PosixTimeSpec,
  1421. flags: u32,
  1422. ) -> Result<usize, SystemError> {
  1423. let pathname = if pathname.is_null() {
  1424. None
  1425. } else {
  1426. let pathname = check_and_clone_cstr(pathname, Some(MAX_PATHLEN))?
  1427. .into_string()
  1428. .map_err(|_| SystemError::EINVAL)?;
  1429. Some(pathname)
  1430. };
  1431. let flags = UtimensFlags::from_bits(flags).ok_or(SystemError::EINVAL)?;
  1432. let times = if times.is_null() {
  1433. None
  1434. } else {
  1435. let times_reader = UserBufferReader::new(times, size_of::<PosixTimeSpec>() * 2, true)?;
  1436. let times = times_reader.read_from_user::<PosixTimeSpec>(0)?;
  1437. Some([times[0], times[1]])
  1438. };
  1439. do_utimensat(dirfd, pathname, times, flags)
  1440. }
  1441. pub fn sys_utimes(
  1442. pathname: *const u8,
  1443. times: *const PosixTimeval,
  1444. ) -> Result<usize, SystemError> {
  1445. let pathname = check_and_clone_cstr(pathname, Some(MAX_PATHLEN))?
  1446. .into_string()
  1447. .map_err(|_| SystemError::EINVAL)?;
  1448. let times = if times.is_null() {
  1449. None
  1450. } else {
  1451. let times_reader = UserBufferReader::new(times, size_of::<PosixTimeval>() * 2, true)?;
  1452. let times = times_reader.read_from_user::<PosixTimeval>(0)?;
  1453. Some([times[0], times[1]])
  1454. };
  1455. do_utimes(&pathname, times)
  1456. }
  1457. }
  1458. #[repr(C)]
  1459. #[derive(Debug, Clone, Copy)]
  1460. pub struct IoVec {
  1461. /// 缓冲区的起始地址
  1462. pub iov_base: *mut u8,
  1463. /// 缓冲区的长度
  1464. pub iov_len: usize,
  1465. }
  1466. /// 用于存储多个来自用户空间的IoVec
  1467. ///
  1468. /// 由于目前内核中的文件系统还不支持分散读写,所以暂时只支持将用户空间的IoVec聚合成一个缓冲区,然后进行操作。
  1469. /// TODO:支持分散读写
  1470. #[derive(Debug)]
  1471. pub struct IoVecs(Vec<&'static mut [u8]>);
  1472. impl IoVecs {
  1473. /// 从用户空间的IoVec中构造IoVecs
  1474. ///
  1475. /// @param iov 用户空间的IoVec
  1476. /// @param iovcnt 用户空间的IoVec的数量
  1477. /// @param readv 是否为readv系统调用
  1478. ///
  1479. /// @return 构造成功返回IoVecs,否则返回错误码
  1480. pub unsafe fn from_user(
  1481. iov: *const IoVec,
  1482. iovcnt: usize,
  1483. _readv: bool,
  1484. ) -> Result<Self, SystemError> {
  1485. // 检查iov指针所在空间是否合法
  1486. verify_area(
  1487. VirtAddr::new(iov as usize),
  1488. iovcnt * core::mem::size_of::<IoVec>(),
  1489. )
  1490. .map_err(|_| SystemError::EFAULT)?;
  1491. // 将用户空间的IoVec转换为引用(注意:这里的引用是静态的,因为用户空间的IoVec不会被释放)
  1492. let iovs: &[IoVec] = core::slice::from_raw_parts(iov, iovcnt);
  1493. let mut slices: Vec<&mut [u8]> = Vec::with_capacity(iovs.len());
  1494. for iov in iovs.iter() {
  1495. if iov.iov_len == 0 {
  1496. continue;
  1497. }
  1498. verify_area(VirtAddr::new(iov.iov_base as usize), iov.iov_len)
  1499. .map_err(|_| SystemError::EFAULT)?;
  1500. slices.push(core::slice::from_raw_parts_mut(iov.iov_base, iov.iov_len));
  1501. }
  1502. return Ok(Self(slices));
  1503. }
  1504. /// @brief 将IoVecs中的数据聚合到一个缓冲区中
  1505. ///
  1506. /// @return 返回聚合后的缓冲区
  1507. pub fn gather(&self) -> Vec<u8> {
  1508. let mut buf = Vec::new();
  1509. for slice in self.0.iter() {
  1510. buf.extend_from_slice(slice);
  1511. }
  1512. return buf;
  1513. }
  1514. /// @brief 将给定的数据分散写入到IoVecs中
  1515. pub fn scatter(&mut self, data: &[u8]) {
  1516. let mut data: &[u8] = data;
  1517. for slice in self.0.iter_mut() {
  1518. let len = core::cmp::min(slice.len(), data.len());
  1519. if len == 0 {
  1520. continue;
  1521. }
  1522. slice[..len].copy_from_slice(&data[..len]);
  1523. data = &data[len..];
  1524. }
  1525. }
  1526. /// @brief 创建与IoVecs等长的缓冲区
  1527. ///
  1528. /// @param set_len 是否设置返回的Vec的len。
  1529. /// 如果为true,则返回的Vec的len为所有IoVec的长度之和;
  1530. /// 否则返回的Vec的len为0,capacity为所有IoVec的长度之和.
  1531. ///
  1532. /// @return 返回创建的缓冲区
  1533. pub fn new_buf(&self, set_len: bool) -> Vec<u8> {
  1534. let total_len: usize = self.0.iter().map(|slice| slice.len()).sum();
  1535. let mut buf: Vec<u8> = Vec::with_capacity(total_len);
  1536. if set_len {
  1537. buf.resize(total_len, 0);
  1538. }
  1539. return buf;
  1540. }
  1541. }