open.cpp 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. /*
  2. * Copyright (c) 2018-2020, Andreas Kling <kling@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <Kernel/Debug.h>
  7. #include <Kernel/FileSystem/Custody.h>
  8. #include <Kernel/FileSystem/FileDescription.h>
  9. #include <Kernel/FileSystem/VirtualFileSystem.h>
  10. #include <Kernel/Process.h>
  11. namespace Kernel {
  12. KResultOr<FlatPtr> Process::sys$open(Userspace<const Syscall::SC_open_params*> user_params)
  13. {
  14. Syscall::SC_open_params params;
  15. if (!copy_from_user(&params, user_params))
  16. return EFAULT;
  17. int dirfd = params.dirfd;
  18. int options = params.options;
  19. u16 mode = params.mode;
  20. if (options & O_NOFOLLOW_NOERROR)
  21. return EINVAL;
  22. if (options & O_UNLINK_INTERNAL)
  23. return EINVAL;
  24. if (options & O_WRONLY)
  25. REQUIRE_PROMISE(wpath);
  26. else if (options & O_RDONLY)
  27. REQUIRE_PROMISE(rpath);
  28. if (options & O_CREAT)
  29. REQUIRE_PROMISE(cpath);
  30. // Ignore everything except permission bits.
  31. mode &= 0777;
  32. auto path = get_syscall_path_argument(params.path);
  33. if (path.is_error())
  34. return path.error();
  35. dbgln_if(IO_DEBUG, "sys$open(dirfd={}, path='{}', options={}, mode={})", dirfd, path.value()->view(), options, mode);
  36. int fd = alloc_fd();
  37. if (fd < 0)
  38. return fd;
  39. RefPtr<Custody> base;
  40. if (dirfd == AT_FDCWD) {
  41. base = current_directory();
  42. } else {
  43. auto base_description = file_description(dirfd);
  44. if (!base_description)
  45. return EBADF;
  46. if (!base_description->is_directory())
  47. return ENOTDIR;
  48. if (!base_description->custody())
  49. return EINVAL;
  50. base = base_description->custody();
  51. }
  52. auto result = VFS::the().open(path.value()->view(), options, mode & ~umask(), *base);
  53. if (result.is_error())
  54. return result.error();
  55. auto description = result.value();
  56. if (description->inode() && description->inode()->socket())
  57. return ENXIO;
  58. u32 fd_flags = (options & O_CLOEXEC) ? FD_CLOEXEC : 0;
  59. m_fds[fd].set(move(description), fd_flags);
  60. return fd;
  61. }
  62. KResultOr<FlatPtr> Process::sys$close(int fd)
  63. {
  64. REQUIRE_PROMISE(stdio);
  65. auto description = file_description(fd);
  66. dbgln_if(IO_DEBUG, "sys$close({}) {}", fd, description.ptr());
  67. if (!description)
  68. return EBADF;
  69. int rc = description->close();
  70. m_fds[fd] = {};
  71. return rc;
  72. }
  73. }