chdir.cpp 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. /*
  2. * Copyright (c) 2018-2020, Andreas Kling <kling@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <Kernel/FileSystem/Custody.h>
  7. #include <Kernel/FileSystem/VirtualFileSystem.h>
  8. #include <Kernel/Process.h>
  9. namespace Kernel {
  10. KResultOr<FlatPtr> Process::sys$chdir(Userspace<const char*> user_path, size_t path_length)
  11. {
  12. VERIFY_PROCESS_BIG_LOCK_ACQUIRED(this);
  13. REQUIRE_PROMISE(rpath);
  14. auto path = get_syscall_path_argument(user_path, path_length);
  15. if (path.is_error())
  16. return path.error();
  17. auto directory_or_error = VirtualFileSystem::the().open_directory(path.value()->view(), current_directory());
  18. if (directory_or_error.is_error())
  19. return directory_or_error.error();
  20. m_cwd = *directory_or_error.value();
  21. return 0;
  22. }
  23. KResultOr<FlatPtr> Process::sys$fchdir(int fd)
  24. {
  25. VERIFY_PROCESS_BIG_LOCK_ACQUIRED(this);
  26. REQUIRE_PROMISE(stdio);
  27. auto description = fds().file_description(fd);
  28. if (!description)
  29. return EBADF;
  30. if (!description->is_directory())
  31. return ENOTDIR;
  32. if (!description->metadata().may_execute(*this))
  33. return EACCES;
  34. m_cwd = description->custody();
  35. return 0;
  36. }
  37. KResultOr<FlatPtr> Process::sys$getcwd(Userspace<char*> buffer, size_t size)
  38. {
  39. VERIFY_PROCESS_BIG_LOCK_ACQUIRED(this);
  40. REQUIRE_PROMISE(rpath);
  41. if (size > NumericLimits<ssize_t>::max())
  42. return EINVAL;
  43. auto maybe_path = current_directory().try_create_absolute_path();
  44. if (!maybe_path)
  45. return ENOMEM;
  46. auto& path = *maybe_path;
  47. size_t ideal_size = path.length() + 1;
  48. auto size_to_copy = min(ideal_size, size);
  49. if (!copy_to_user(buffer, path.characters(), size_to_copy))
  50. return EFAULT;
  51. // Note: we return the whole size here, not the copied size.
  52. return ideal_size;
  53. }
  54. }