1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
|
package main
import (
"fmt"
"os"
"github.com/davecgh/go-spew/spew"
"lukeshu.com/btrfs-tools/pkg/binstruct"
)
func main() {
if err := Main(os.Args[1]); err != nil {
fmt.Fprintf(os.Stderr, "%s: error: %v\n", os.Args[0], err)
os.Exit(1)
}
}
func Main(imgfilename string) (err error) {
maybeSetErr := func(_err error) {
if _err != nil && err == nil {
err = _err
}
}
fh, err := os.Open(imgfilename)
if err != nil {
return err
}
img := &Img{
File: fh,
}
defer func() {
maybeSetErr(img.Close())
}()
superblocks, err := img.Superblocks()
if err != nil {
return err
}
spew := spew.NewDefaultConfig()
spew.DisablePointerAddresses = true
spew.Dump(superblocks[0].data)
sum, err := superblocks[0].data.CalculateChecksum()
if err != nil {
return err
}
fmt.Printf("calculated sum: %x\n", sum)
return nil
}
type Img struct {
*os.File
}
func (img *Img) Size() (int64, error) {
fi, err := img.Stat()
if err != nil {
return 0, err
}
return fi.Size(), nil
}
type Ref[T any] struct {
img *Img
addr int64
data T
}
func (r *Ref[T]) Read() error {
size, err := binstruct.Size(r.data)
if err != nil {
return err
}
buf := make([]byte, size)
if _, err := r.img.ReadAt(buf, r.addr); err != nil {
return err
}
return binstruct.Unmarshal(buf, &r.data)
}
func (img *Img) Superblocks() ([]Ref[Superblock], error) {
const superblockSize = 0x1000
var superblockAddrs = []int64{
0x00_0001_0000, // 64KiB
0x00_0400_0000, // 64MiB
0x40_0000_0000, // 256GiB
}
sz, err := img.Size()
if err != nil {
return nil, err
}
var ret []Ref[Superblock]
for i, addr := range superblockAddrs {
if addr+superblockSize <= sz {
superblock := Ref[Superblock]{
img: img,
addr: addr,
}
if err := superblock.Read(); err != nil {
return nil, fmt.Errorf("superblock %d: %w", i, err)
}
ret = append(ret, superblock)
}
}
if len(ret) == 0 {
return nil, fmt.Errorf("no superblocks")
}
return ret, nil
}
|