lsblk.cpp 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. /*
  2. * Copyright (c) 2022, Liav A. <liavalb@hotmail.co.il>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <AK/Hex.h>
  7. #include <AK/String.h>
  8. #include <AK/StringView.h>
  9. #include <LibCore/ArgsParser.h>
  10. #include <LibCore/DirIterator.h>
  11. #include <LibCore/File.h>
  12. #include <LibCore/System.h>
  13. #include <LibMain/Main.h>
  14. static constexpr StringView format_row = "{:10s}\t{:10s}\t{:10s}\t{:10s}"sv;
  15. ErrorOr<int> serenity_main(Main::Arguments arguments)
  16. {
  17. TRY(Core::System::pledge("stdio rpath"));
  18. TRY(Core::System::unveil("/sys/devices/storage", "r"));
  19. TRY(Core::System::unveil(nullptr, nullptr));
  20. Core::ArgsParser args_parser;
  21. args_parser.set_general_help("List Storage (Block) devices.");
  22. args_parser.parse(arguments);
  23. Core::DirIterator di("/sys/devices/storage/", Core::DirIterator::SkipParentAndBaseDir);
  24. if (di.has_error()) {
  25. warnln("Failed to open /sys/devices/storage - {}", di.error());
  26. return 1;
  27. }
  28. outln(format_row, "LUN"sv, "Command set"sv, "Block Size"sv, "Last LBA"sv);
  29. TRY(Core::System::pledge("stdio rpath"));
  30. while (di.has_next()) {
  31. auto dir = di.next_path();
  32. auto command_set_file = Core::File::construct(String::formatted("/sys/devices/storage/{}/command_set", dir));
  33. if (!command_set_file->open(Core::OpenMode::ReadOnly)) {
  34. dbgln("Error: Could not open {}: {}", command_set_file->name(), command_set_file->error_string());
  35. continue;
  36. }
  37. auto last_lba_file = Core::File::construct(String::formatted("/sys/devices/storage/{}/last_lba", dir));
  38. if (!last_lba_file->open(Core::OpenMode::ReadOnly)) {
  39. dbgln("Error: Could not open {}: {}", last_lba_file->name(), last_lba_file->error_string());
  40. continue;
  41. }
  42. auto sector_size_file = Core::File::construct(String::formatted("/sys/devices/storage/{}/sector_size", dir));
  43. if (!sector_size_file->open(Core::OpenMode::ReadOnly)) {
  44. dbgln("Error: Could not open {}: {}", sector_size_file->name(), sector_size_file->error_string());
  45. continue;
  46. }
  47. String command_set = StringView(command_set_file->read_all().bytes());
  48. String last_lba = StringView(last_lba_file->read_all().bytes());
  49. String sector_size = StringView(sector_size_file->read_all().bytes());
  50. outln(format_row, dir, command_set, sector_size, last_lba);
  51. }
  52. return 0;
  53. }