From 2735ea5b962a25ce44caa8d167660ffa56843c83 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tom=C3=A1=C5=A1=20Hozza?= Date: Mon, 24 Oct 2022 10:28:10 +0200 Subject: [PATCH] internal/disk: fix potential nil pointer dereference MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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 --- internal/disk/partition_table.go | 16 +++++++++------- 1 file changed, 9 insertions(+), 7 deletions(-) diff --git a/internal/disk/partition_table.go b/internal/disk/partition_table.go index 827819ce6..91719deb0 100644 --- a/internal/disk/partition_table.go +++ b/internal/disk/partition_table.go @@ -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