TestLoopDevice.cpp 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. /*
  2. * Copyright (c) 2024, Liav A. <liavalb@hotmail.co.il>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <AK/ByteString.h>
  7. #include <AK/StringView.h>
  8. #include <Kernel/API/Ioctl.h>
  9. #include <LibTest/TestCase.h>
  10. #include <fcntl.h>
  11. #include <sys/ioctl.h>
  12. #include <unistd.h>
  13. static int open_loop_device(int loop_device_index)
  14. {
  15. auto loop_device_path = ByteString::formatted("/dev/loop/{}", loop_device_index);
  16. return open(loop_device_path.view().characters_without_null_termination(), O_RDONLY);
  17. }
  18. TEST_CASE(create_attach_and_destory_loop_device)
  19. {
  20. constexpr char const* test_path = "/tmp/create_attach_and_destory_loop_device_test";
  21. int devctl_fd = open("/dev/devctl", O_RDONLY);
  22. VERIFY(devctl_fd >= 0);
  23. auto cleanup_devctl_fd_guard = ScopeGuard([&] {
  24. close(devctl_fd);
  25. });
  26. u8 buf[0x1000];
  27. memset(buf, 0, sizeof(buf));
  28. int fd = open(test_path, O_RDWR | O_CREAT, 0644);
  29. VERIFY(fd >= 0);
  30. auto cleanup_fd_guard = ScopeGuard([&] {
  31. close(fd);
  32. unlink(test_path);
  33. });
  34. auto rc = write(fd, buf, sizeof(buf));
  35. VERIFY(rc == sizeof(buf));
  36. int value = fd;
  37. auto create_result = ioctl(devctl_fd, DEVCTL_CREATE_LOOP_DEVICE, &value);
  38. EXPECT_EQ(create_result, 0);
  39. auto loop_device_index = value;
  40. auto loop_device_fd_or_error = open_loop_device(loop_device_index);
  41. EXPECT(loop_device_fd_or_error >= 0);
  42. auto cleanup_loop_device_fd_guard = ScopeGuard([&] {
  43. close(loop_device_fd_or_error);
  44. });
  45. auto destroy_result = ioctl(devctl_fd, DEVCTL_DESTROY_LOOP_DEVICE, &loop_device_index);
  46. EXPECT_EQ(destroy_result, 0);
  47. }