Skip to content

Commit 8fc4c62

Browse files
committed
better uf2 validation
1 parent c7032cc commit 8fc4c62

File tree

2 files changed

+16
-8
lines changed

2 files changed

+16
-8
lines changed

cmd/picobin/uf2.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -43,7 +43,7 @@ func uf2info(r io.ReaderAt, flags Flags) error {
4343
if err != nil {
4444
return err
4545
}
46-
return blockInfo(blocks, uint64(block0start), flags)
46+
return blockInfo(blocks, romstart+uint64(block0start), flags)
4747
}
4848

4949
func uf2conv(r io.ReaderAt, flags Flags) error {

uf2/uf2.go

Lines changed: 15 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -10,10 +10,12 @@ import (
1010
)
1111

1212
var (
13-
errSmallBlock = errors.New("buffer too small to contain block")
14-
errMagic0 = errors.New("first word is not magic0 word \"UF2\\n\"")
15-
errMagic1 = errors.New("second word is not magic1 word")
16-
errMagicEnd = errors.New("last word is not magic end word")
13+
errSmallBlock = errors.New("buffer too small to contain block")
14+
errPayload = errors.New("payload size exceeds max UF2 block size")
15+
errBlockNumbering = errors.New("block number larger than number of blocks")
16+
errMagic0 = errors.New("first word is not magic0 word \"UF2\\n\"")
17+
errMagic1 = errors.New("second word is not magic1 word")
18+
errMagicEnd = errors.New("last word is not magic end word")
1719
)
1820

1921
const (
@@ -89,9 +91,11 @@ func (b *Block) Data() ([]byte, error) {
8991
func (b *Block) Validate() error {
9092
sz := b.PayloadSize
9193
if sz > BlockMaxData {
92-
return errors.New("payload size exeeds permissible maximum")
94+
return errPayload
9395
} else if sz == 0 {
9496
return errors.New("zero payload size")
97+
} else if b.BlockNum >= b.NumBlocks {
98+
return errBlockNumbering
9599
}
96100
return nil
97101
}
@@ -128,11 +132,15 @@ func DecodeAppendBlocks(dst []Block, r io.Reader, scratchBuf []byte) ([]Block, i
128132

129133
// DecodeBlock decodes a 512 byte block from the argument buffer. Buffer must be at least 512 bytes long.
130134
func DecodeBlock(text []byte) (Block, error) {
131-
err := ValidateBlock(text)
135+
err := validateMagic(text)
132136
if err != nil {
133137
return Block{}, err
134138
}
135139
block := MustDecodeBlock(text)
140+
err = block.Validate()
141+
if err != nil {
142+
return Block{}, err
143+
}
136144
return block, nil
137145
}
138146

@@ -149,7 +157,7 @@ func MustDecodeBlock(text []byte) (block Block) {
149157
return block
150158
}
151159

152-
func ValidateBlock(text []byte) error {
160+
func validateMagic(text []byte) error {
153161
if len(text) < 512 {
154162
return errSmallBlock
155163
}

0 commit comments

Comments
 (0)