EBRPartitionTable.cpp 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. /*
  2. * Copyright (c) 2020-2022, Liav A. <liavalb@hotmail.co.il>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <AK/ByteBuffer.h>
  7. #include <Kernel/Storage/Partition/EBRPartitionTable.h>
  8. namespace Kernel {
  9. ErrorOr<NonnullOwnPtr<EBRPartitionTable>> EBRPartitionTable::try_to_initialize(StorageDevice const& device)
  10. {
  11. auto table = TRY(adopt_nonnull_own_or_enomem(new (nothrow) EBRPartitionTable(device)));
  12. if (table->is_protective_mbr())
  13. return Error::from_errno(ENOTSUP);
  14. if (!table->is_valid())
  15. return Error::from_errno(EINVAL);
  16. return table;
  17. }
  18. void EBRPartitionTable::search_extended_partition(StorageDevice const& device, MBRPartitionTable& checked_ebr, u64 current_block_offset, size_t limit)
  19. {
  20. if (limit == 0)
  21. return;
  22. // EBRs should not carry more than 2 partitions (because they need to form a linked list)
  23. VERIFY(checked_ebr.partitions_count() <= 2);
  24. auto checked_logical_partition = checked_ebr.partition(0);
  25. // If we are pointed to an invalid logical partition, something is seriously wrong.
  26. VERIFY(checked_logical_partition.has_value());
  27. m_partitions.append(checked_logical_partition.value().offset(current_block_offset));
  28. if (!checked_ebr.contains_ebr())
  29. return;
  30. current_block_offset += checked_ebr.partition(1).value().start_block();
  31. auto next_ebr = MBRPartitionTable::try_to_initialize(device, current_block_offset);
  32. if (!next_ebr)
  33. return;
  34. search_extended_partition(device, *next_ebr, current_block_offset, (limit - 1));
  35. }
  36. EBRPartitionTable::EBRPartitionTable(StorageDevice const& device)
  37. : MBRPartitionTable(device)
  38. {
  39. if (!is_header_valid())
  40. return;
  41. m_valid = true;
  42. VERIFY(partitions_count() == 0);
  43. auto& header = this->header();
  44. for (size_t index = 0; index < 4; index++) {
  45. auto& entry = header.entry[index];
  46. // Start enumerating all logical partitions
  47. if (entry.type == 0xf) {
  48. auto checked_ebr = MBRPartitionTable::try_to_initialize(device, entry.offset);
  49. if (!checked_ebr)
  50. continue;
  51. // It's quite unlikely to see that amount of partitions, so stop at 128 partitions.
  52. search_extended_partition(device, *checked_ebr, entry.offset, 128);
  53. continue;
  54. }
  55. if (entry.offset == 0x00) {
  56. continue;
  57. }
  58. MUST(m_partitions.try_empend(entry.offset, (entry.offset + entry.length), entry.type));
  59. }
  60. }
  61. EBRPartitionTable::~EBRPartitionTable() = default;
  62. }