chdir.cpp 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  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/FileDescription.h>
  8. #include <Kernel/FileSystem/VirtualFileSystem.h>
  9. #include <Kernel/Process.h>
  10. namespace Kernel {
  11. KResultOr<int> Process::sys$chdir(Userspace<const char*> user_path, size_t path_length)
  12. {
  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 = VFS::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<int> Process::sys$fchdir(int fd)
  24. {
  25. REQUIRE_PROMISE(stdio);
  26. auto description = file_description(fd);
  27. if (!description)
  28. return EBADF;
  29. if (!description->is_directory())
  30. return ENOTDIR;
  31. if (!description->metadata().may_execute(*this))
  32. return EACCES;
  33. m_cwd = description->custody();
  34. return 0;
  35. }
  36. KResultOr<int> Process::sys$getcwd(Userspace<char*> buffer, size_t size)
  37. {
  38. REQUIRE_PROMISE(rpath);
  39. if (size > NumericLimits<ssize_t>::max())
  40. return EINVAL;
  41. auto path = current_directory().absolute_path();
  42. size_t ideal_size = path.length() + 1;
  43. auto size_to_copy = min(ideal_size, size);
  44. if (!copy_to_user(buffer, path.characters(), size_to_copy))
  45. return EFAULT;
  46. // Note: we return the whole size here, not the copied size.
  47. return ideal_size;
  48. }
  49. }