open.cpp 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  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/VirtualFileSystem.h>
  9. #include <Kernel/Process.h>
  10. namespace Kernel {
  11. KResultOr<FlatPtr> Process::sys$open(Userspace<const Syscall::SC_open_params*> user_params)
  12. {
  13. VERIFY_PROCESS_BIG_LOCK_ACQUIRED(this)
  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. auto fd_or_error = m_fds.allocate();
  37. if (fd_or_error.is_error())
  38. return fd_or_error.error();
  39. auto new_fd = fd_or_error.release_value();
  40. RefPtr<Custody> base;
  41. if (dirfd == AT_FDCWD) {
  42. base = current_directory();
  43. } else {
  44. auto base_description = fds().file_description(dirfd);
  45. if (!base_description)
  46. return EBADF;
  47. if (!base_description->is_directory())
  48. return ENOTDIR;
  49. if (!base_description->custody())
  50. return EINVAL;
  51. base = base_description->custody();
  52. }
  53. auto result = VirtualFileSystem::the().open(path.value()->view(), options, mode & ~umask(), *base);
  54. if (result.is_error())
  55. return result.error();
  56. auto description = result.value();
  57. if (description->inode() && description->inode()->socket())
  58. return ENXIO;
  59. u32 fd_flags = (options & O_CLOEXEC) ? FD_CLOEXEC : 0;
  60. m_fds[new_fd.fd].set(move(description), fd_flags);
  61. return new_fd.fd;
  62. }
  63. KResultOr<FlatPtr> Process::sys$close(int fd)
  64. {
  65. VERIFY_PROCESS_BIG_LOCK_ACQUIRED(this)
  66. REQUIRE_PROMISE(stdio);
  67. auto description = fds().file_description(fd);
  68. dbgln_if(IO_DEBUG, "sys$close({}) {}", fd, description.ptr());
  69. if (!description)
  70. return EBADF;
  71. auto result = description->close();
  72. m_fds[fd] = {};
  73. return result;
  74. }
  75. }