Skip to content

Commit

Permalink
fix: return partition table not exist when trying to read an empty dev
Browse files Browse the repository at this point in the history
Fixes: #51

Signed-off-by: Artem Chernyshev <[email protected]>
  • Loading branch information
Unix4ever committed Nov 23, 2021
1 parent b9517d5 commit 15b182d
Show file tree
Hide file tree
Showing 3 changed files with 16 additions and 18 deletions.
22 changes: 8 additions & 14 deletions blockdevice/blockdevice_linux.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
package blockdevice

import (
"bytes"
"errors"
"fmt"
"io"
"os"
Expand Down Expand Up @@ -88,22 +88,16 @@ func Open(devname string, setters ...Option) (bd *BlockDevice, err error) {

bd.g = g
} else {
buf := make([]byte, 1)
// PMBR protective entry starts at 446. The partition type is at offset
// 4 from the start of the PMBR protective entry.
_, err = f.ReadAt(buf, 450)
if err != nil {
var g *gpt.GPT
if g, err = gpt.Open(f); err != nil {
if errors.Is(err, gpt.ErrPartitionTableDoesNotExist) {
return bd, nil
}

return nil, err
}

// For GPT, the partition type should be 0xee (EFI GPT).
if bytes.Equal(buf, []byte{0xee}) {
var g *gpt.GPT
if g, err = gpt.Open(f); err != nil {
return nil, err
}
bd.g = g
}
bd.g = g
}

return bd, nil
Expand Down
10 changes: 7 additions & 3 deletions blockdevice/partition/gpt/gpt.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,11 +26,11 @@ const (

var (
// ErrPartitionTableDoesNotExist indicates that the partition table does not exist.
ErrPartitionTableDoesNotExist = errors.New("does not exist")
ErrPartitionTableDoesNotExist = errors.New("block device partition table does not exist")
// ErrHeaderCRCMismatch indicates that the header CRC does not match what is on disk.
ErrHeaderCRCMismatch = errors.New("header CRC mismatch")
ErrHeaderCRCMismatch = errors.New("block device partition table header CRC mismatch")
// ErrEntriesCRCMismatch indicates that the partitions array CRC does not match what is on disk.
ErrEntriesCRCMismatch = errors.New("entries CRC mismatch")
ErrEntriesCRCMismatch = errors.New("block device partition table entries CRC mismatch")
)

type outOfSpaceError struct {
Expand Down Expand Up @@ -84,6 +84,10 @@ func Open(f *os.File) (g *GPT, err error) {
markMBRBootable: buf[0] == 0x80,
}

if err = h.DeserializeSignature(); err != nil {
return nil, ErrPartitionTableDoesNotExist
}

return g, nil
}

Expand Down
2 changes: 1 addition & 1 deletion blockdevice/partition/gpt/gpt_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ func (suite *GPTSuite) SetupTest() {

func (suite *GPTSuite) TestEmpty() {
_, err := gpt.Open(suite.Dev)
suite.Require().Error(err)
suite.Require().EqualError(err, gpt.ErrPartitionTableDoesNotExist.Error())
}

func (suite *GPTSuite) TestReset() {
Expand Down

0 comments on commit 15b182d

Please sign in to comment.