EBRPartitionTable.cpp 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. /*
  2. * Copyright (c) 2020-2022, Liav A. <liavalb@hotmail.co.il>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <LibPartition/EBRPartitionTable.h>
  7. namespace Partition {
  8. ErrorOr<NonnullOwnPtr<EBRPartitionTable>> EBRPartitionTable::try_to_initialize(PartitionableDevice device)
  9. {
  10. auto table = TRY(adopt_nonnull_own_or_enomem(new (nothrow) EBRPartitionTable(move(device))));
  11. if (table->is_protective_mbr())
  12. return Error::from_errno(ENOTSUP);
  13. if (!table->is_valid())
  14. return Error::from_errno(EINVAL);
  15. return table;
  16. }
  17. void EBRPartitionTable::search_extended_partition(MBRPartitionTable& checked_ebr, u64 current_block_offset, size_t limit)
  18. {
  19. if (limit == 0)
  20. return;
  21. // EBRs should not carry more than 2 partitions (because they need to form a linked list)
  22. VERIFY(checked_ebr.partitions_count() <= 2);
  23. // FIXME: We should not crash the Kernel or any apps when the EBR is malformed.
  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(m_device.clone_unowned(), current_block_offset);
  32. if (!next_ebr)
  33. return;
  34. // FIXME: Should not rely on TCO here, since this might be called from inside the Kernel, where stack space isn't exactly free.
  35. search_extended_partition(*next_ebr, current_block_offset, (limit - 1));
  36. }
  37. EBRPartitionTable::EBRPartitionTable(PartitionableDevice device)
  38. : MBRPartitionTable(move(device))
  39. {
  40. if (!is_header_valid())
  41. return;
  42. m_valid = true;
  43. VERIFY(partitions_count() == 0);
  44. auto& header = this->header();
  45. for (size_t index = 0; index < 4; index++) {
  46. auto& entry = header.entry[index];
  47. // Start enumerating all logical partitions
  48. if (entry.type == 0xf) {
  49. auto checked_ebr = MBRPartitionTable::try_to_initialize(m_device.clone_unowned(), entry.offset);
  50. if (!checked_ebr)
  51. continue;
  52. // It's quite unlikely to see that amount of partitions, so stop at 128 partitions.
  53. search_extended_partition(*checked_ebr, entry.offset, 128);
  54. continue;
  55. }
  56. if (entry.offset == 0x00) {
  57. continue;
  58. }
  59. MUST(m_partitions.try_empend(entry.offset, (entry.offset + entry.length) - 1, entry.type));
  60. }
  61. }
  62. EBRPartitionTable::~EBRPartitionTable() = default;
  63. }