open.cpp 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  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. ErrorOr<FlatPtr> Process::sys$open(Userspace<const Syscall::SC_open_params*> user_params)
  12. {
  13. VERIFY_PROCESS_BIG_LOCK_ACQUIRED(this)
  14. auto params = TRY(copy_typed_from_user(user_params));
  15. int dirfd = params.dirfd;
  16. int options = params.options;
  17. u16 mode = params.mode;
  18. if (options & O_NOFOLLOW_NOERROR)
  19. return EINVAL;
  20. if (options & O_UNLINK_INTERNAL)
  21. return EINVAL;
  22. if (options & O_WRONLY)
  23. TRY(require_promise(Pledge::wpath));
  24. else if (options & O_RDONLY)
  25. TRY(require_promise(Pledge::rpath));
  26. if (options & O_CREAT)
  27. TRY(require_promise(Pledge::cpath));
  28. // Ignore everything except permission bits.
  29. mode &= 0777;
  30. auto path = TRY(get_syscall_path_argument(params.path));
  31. dbgln_if(IO_DEBUG, "sys$open(dirfd={}, path='{}', options={}, mode={})", dirfd, path->view(), options, mode);
  32. auto fd_allocation = TRY(m_fds.allocate());
  33. RefPtr<Custody> base;
  34. if (dirfd == AT_FDCWD) {
  35. base = current_directory();
  36. } else {
  37. auto base_description = TRY(fds().open_file_description(dirfd));
  38. if (!base_description->is_directory())
  39. return ENOTDIR;
  40. if (!base_description->custody())
  41. return EINVAL;
  42. base = base_description->custody();
  43. }
  44. auto description = TRY(VirtualFileSystem::the().open(path->view(), options, mode & ~umask(), *base));
  45. if (description->inode() && description->inode()->socket())
  46. return ENXIO;
  47. u32 fd_flags = (options & O_CLOEXEC) ? FD_CLOEXEC : 0;
  48. m_fds[fd_allocation.fd].set(move(description), fd_flags);
  49. return fd_allocation.fd;
  50. }
  51. ErrorOr<FlatPtr> Process::sys$close(int fd)
  52. {
  53. VERIFY_PROCESS_BIG_LOCK_ACQUIRED(this)
  54. TRY(require_promise(Pledge::stdio));
  55. auto description = TRY(fds().open_file_description(fd));
  56. auto result = description->close();
  57. m_fds[fd] = {};
  58. if (result.is_error())
  59. return result.release_error();
  60. return 0;
  61. }
  62. }