internal/disk: fix potential nil pointer dereference

The `PartitionTable.Clone()` method could end up dereferencing a `nil`
pointer in the `part` variable, if there would be a `nil` partition in
the partition table. Such situation would be an error of its own.
There is no point in checking if the cloned partition is not `nil` and
casting it to another variable. The logic should check if the cloned
partition is `nil` and panic in such situation. The following code can
then cast the clone to a different variable without issues and there is
no risk of dereferencing a `nil` pointer.

Signed-off-by: Tomáš Hozza <thozza@redhat.com>
This commit is contained in:
Tomáš Hozza 2022-10-24 10:28:10 +02:00 committed by Tomáš Hozza
parent baa5e96734
commit 2735ea5b96

View file

@ -75,15 +75,17 @@ func (pt *PartitionTable) Clone() Entity {
for idx, partition := range pt.Partitions {
ent := partition.Clone()
var part *Partition
if ent != nil {
pEnt, cloneOk := ent.(*Partition)
if !cloneOk {
panic("PartitionTable.Clone() returned an Entity that cannot be converted to *PartitionTable; this is a programming error")
}
part = pEnt
// partition.Clone() will return nil only if the partition is nil
if ent == nil {
panic(fmt.Sprintf("partition %d in a Partition Table is nil; this is a programming error", idx))
}
part, cloneOk := ent.(*Partition)
if !cloneOk {
panic("PartitionTable.Clone() returned an Entity that cannot be converted to *PartitionTable; this is a programming error")
}
clone.Partitions[idx] = *part
}
return clone