blob: 1c6681646e82f36656c081ce2bc6260806ca7601 [file] [log] [blame]
Lorenz Brunee17d832022-10-18 12:02:45 +00001// Package gpt implements reading and writing GUID Partition Tables as specified
2// in the UEFI Specification. It only implements up to 128 partitions per table
3// (same as most other implementations) as more would require a dynamic table
4// size, significantly complicating the code for little gain.
5package gpt
6
7import (
8 "bytes"
9 "encoding/binary"
10 "errors"
11 "fmt"
12 "hash/crc32"
Jan Schäre479eee2024-08-21 16:01:39 +020013 "slices"
Lorenz Brunee17d832022-10-18 12:02:45 +000014 "strings"
15 "unicode/utf16"
16
17 "github.com/google/uuid"
Lorenz Brun60d6b902023-06-20 16:02:40 +020018
Tim Windelschmidt9f21f532024-05-07 15:14:20 +020019 "source.monogon.dev/osbase/blockdev"
20 "source.monogon.dev/osbase/msguid"
Lorenz Brunee17d832022-10-18 12:02:45 +000021)
22
23var gptSignature = [8]byte{'E', 'F', 'I', ' ', 'P', 'A', 'R', 'T'}
Jan Schäre479eee2024-08-21 16:01:39 +020024
25const gptRevision uint32 = 0x00010000 // First 2 bytes major, second 2 bytes minor
Lorenz Brunee17d832022-10-18 12:02:45 +000026
27// See UEFI Specification 2.9 Table 5-5
28type header struct {
29 Signature [8]byte
30 Revision uint32
31 HeaderSize uint32
32 HeaderCRC32 uint32
33 _ [4]byte
34
35 HeaderBlock uint64
36 AlternateHeaderBlock uint64
37 FirstUsableBlock uint64
38 LastUsableBlock uint64
39
40 ID [16]byte
41
42 PartitionEntriesStartBlock uint64
43 PartitionEntryCount uint32
44 PartitionEntrySize uint32
45 PartitionEntriesCRC32 uint32
46}
47
48// See UEFI Specification 2.9 Table 5-6
49type partition struct {
50 Type [16]byte
51 ID [16]byte
52 FirstBlock uint64
53 LastBlock uint64
54 Attributes uint64
55 Name [36]uint16
56}
57
58var (
59 PartitionTypeEFISystem = uuid.MustParse("C12A7328-F81F-11D2-BA4B-00A0C93EC93B")
60)
61
Lorenz Brunee17d832022-10-18 12:02:45 +000062// Attribute is a bitfield of attributes set on a partition. Bits 0 to 47 are
63// reserved for UEFI specification use and all current assignments are in the
64// following const block. Bits 48 to 64 are available for per-Type use by
65// the organization controlling the partition Type.
66type Attribute uint64
67
68const (
69 // AttrRequiredPartition indicates that this partition is required for the
70 // platform to function. Mostly used by vendors to mark things like recovery
71 // partitions.
72 AttrRequiredPartition = 1 << 0
73 // AttrNoBlockIOProto indicates that EFI firmware must not provide an EFI
74 // block device (EFI_BLOCK_IO_PROTOCOL) for this partition.
75 AttrNoBlockIOProto = 1 << 1
76 // AttrLegacyBIOSBootable indicates to special-purpose software outside of
77 // UEFI that this partition can be booted using a traditional PC BIOS.
78 // Don't use this unless you know that you need it specifically.
79 AttrLegacyBIOSBootable = 1 << 2
80)
81
82// PerTypeAttrs returns the top 24 bits which are reserved for custom per-Type
83// attributes. The top 8 bits of the returned uint32 are always 0.
84func (a Attribute) PerTypeAttrs() uint32 {
85 return uint32(a >> 48)
86}
87
88// SetPerTypeAttrs sets the top 24 bits which are reserved for custom per-Type
89// attributes. It does not touch the lower attributes which are specified by the
90// UEFI specification. The top 8 bits of v are silently discarded.
91func (a *Attribute) SetPerTypeAttrs(v uint32) {
92 *a &= 0x000000FF_FFFFFFFF
93 *a |= Attribute(v) << 48
94}
95
96type Partition struct {
97 // Name of the partition, will be truncated if it expands to more than 36
98 // UTF-16 code points. Not all systems can display non-BMP code points.
99 Name string
100 // Type is the type of Table partition, can either be one of the predefined
101 // constants by the UEFI specification or a custom type identifier.
102 // Note that the all-zero UUID denotes an empty partition slot, so this
103 // MUST be set to something, otherwise it is not treated as a partition.
104 Type uuid.UUID
105 // ID is a unique identifier for this specific partition. It should be
106 // changed when cloning the partition.
107 ID uuid.UUID
108 // The first logical block of the partition (inclusive)
109 FirstBlock uint64
110 // The last logical block of the partition (inclusive)
111 LastBlock uint64
112 // Bitset of attributes of this partition.
113 Attributes Attribute
Lorenz Brunad131882023-06-28 16:42:20 +0200114
115 *blockdev.Section
Lorenz Brunee17d832022-10-18 12:02:45 +0000116}
117
118// SizeBlocks returns the size of the partition in blocks
119func (p *Partition) SizeBlocks() uint64 {
120 return 1 + p.LastBlock - p.FirstBlock
121}
122
123// IsUnused checks if the partition is unused, i.e. it is nil or its type is
124// the null UUID.
125func (p *Partition) IsUnused() bool {
126 if p == nil {
127 return true
128 }
Lorenz Brunad131882023-06-28 16:42:20 +0200129 return p.Type == uuid.Nil
130}
131
132// New returns an empty table on the given block device.
133// It does not read any existing GPT on the disk (use Read for that), nor does
134// it write anything until Write is called.
135func New(b blockdev.BlockDev) (*Table, error) {
136 return &Table{
137 b: b,
138 }, nil
Lorenz Brunee17d832022-10-18 12:02:45 +0000139}
140
141type Table struct {
142 // ID is the unique identifier of this specific disk / GPT.
143 // If this is left uninitialized/all-zeroes a new random ID is automatically
144 // generated when writing.
145 ID uuid.UUID
146
147 // Data put at the start of the very first block. Gets loaded and executed
148 // by a legacy BIOS bootloader. This can be used to make GPT-partitioned
149 // disks bootable by legacy systems or display a nice error message.
150 // Maximum length is 440 bytes, if that is exceeded Write returns an error.
151 // Should be left empty if the device is not bootable and/or compatibility
152 // with BIOS booting is not required. Only useful on x86 systems.
153 BootCode []byte
154
Lorenz Brunee17d832022-10-18 12:02:45 +0000155 // Partitions contains the list of partitions in this table. This is
Lorenz Brun5a90d302023-10-09 17:38:13 +0200156 // artificially limited to 128 partitions. Holes in the partition list are
157 // represented as nil values. Call IsUnused before checking any other
158 // properties of the partition.
Lorenz Brunee17d832022-10-18 12:02:45 +0000159 Partitions []*Partition
Lorenz Brunad131882023-06-28 16:42:20 +0200160
161 b blockdev.BlockDev
Lorenz Brunee17d832022-10-18 12:02:45 +0000162}
Lorenz Brunad131882023-06-28 16:42:20 +0200163
Lorenz Brunee17d832022-10-18 12:02:45 +0000164type addOptions struct {
165 preferEnd bool
166 keepEmptyEntries bool
167 alignment int64
168}
169
170// AddOption is a bitset controlling various
171type AddOption func(*addOptions)
172
173// WithPreferEnd tries to put the partition as close to the end as possible
174// instead of as close to the start.
175func WithPreferEnd() AddOption {
176 return func(options *addOptions) {
177 options.preferEnd = true
178 }
179}
180
181// WithKeepEmptyEntries does not fill up empty entries which are followed by
182// filled ones. It always appends the partition after the last used entry.
183// Without this flag, the partition is placed in the first empty entry.
184func WithKeepEmptyEntries() AddOption {
185 return func(options *addOptions) {
186 options.keepEmptyEntries = true
187 }
188}
189
190// WithAlignment allows aligning the partition start block to a non-default
191// value. By default, these are aligned to 1MiB.
Lorenz Brun60d6b902023-06-20 16:02:40 +0200192// Only use this flag if you are certain you need it, it can cause quite severe
Lorenz Brunee17d832022-10-18 12:02:45 +0000193// performance degradation under certain conditions.
Jan Schäre479eee2024-08-21 16:01:39 +0200194func WithAlignment(alignment int64) AddOption {
Lorenz Brunee17d832022-10-18 12:02:45 +0000195 return func(options *addOptions) {
Jan Schäre479eee2024-08-21 16:01:39 +0200196 options.alignment = alignment
Lorenz Brunee17d832022-10-18 12:02:45 +0000197 }
198}
199
200// AddPartition takes a pointer to a partition and adds it, placing it into
201// the first (or last using WithPreferEnd) continuous free space which fits it.
Jan Schäre479eee2024-08-21 16:01:39 +0200202// If size is -1, the partition will fill the largest free space.
Lorenz Brunee17d832022-10-18 12:02:45 +0000203// It writes the placement information (FirstBlock, LastBlock) back to p.
204// By default, AddPartition aligns FirstBlock to 1MiB boundaries, but this can
205// be overridden using WithAlignment.
Tim Windelschmidt0c57d342024-04-11 01:38:47 +0200206func (gpt *Table) AddPartition(p *Partition, size int64, options ...AddOption) error {
207 blockSize := gpt.b.BlockSize()
Lorenz Brunee17d832022-10-18 12:02:45 +0000208 var opts addOptions
209 // Align to 1MiB or the block size, whichever is bigger
210 opts.alignment = 1 * 1024 * 1024
Lorenz Brunad131882023-06-28 16:42:20 +0200211 if blockSize > opts.alignment {
212 opts.alignment = blockSize
Lorenz Brunee17d832022-10-18 12:02:45 +0000213 }
214 for _, o := range options {
215 o(&opts)
216 }
Jan Schäre479eee2024-08-21 16:01:39 +0200217 if opts.alignment <= 0 {
218 return fmt.Errorf("alignment (%d bytes) must be positive", opts.alignment)
219 }
Lorenz Brunad131882023-06-28 16:42:20 +0200220 if opts.alignment%blockSize != 0 {
221 return fmt.Errorf("requested alignment (%d bytes) is not an integer multiple of the block size (%d), unable to align", opts.alignment, blockSize)
Lorenz Brunee17d832022-10-18 12:02:45 +0000222 }
Jan Schäre479eee2024-08-21 16:01:39 +0200223 alignBlocks := opts.alignment / blockSize
Lorenz Brunad131882023-06-28 16:42:20 +0200224 if p.ID == uuid.Nil {
225 p.ID = uuid.New()
226 }
227
Tim Windelschmidt0c57d342024-04-11 01:38:47 +0200228 fs, _, err := gpt.GetFreeSpaces()
Lorenz Brunee17d832022-10-18 12:02:45 +0000229 if err != nil {
230 return fmt.Errorf("unable to determine free space: %v", err)
231 }
232 if opts.preferEnd {
233 // Reverse fs slice to start iteration at the end
Jan Schäre479eee2024-08-21 16:01:39 +0200234 slices.Reverse(fs)
Lorenz Brunee17d832022-10-18 12:02:45 +0000235 }
Jan Schäre479eee2024-08-21 16:01:39 +0200236 var largestFreeSpace int64
Lorenz Brunee17d832022-10-18 12:02:45 +0000237 for _, freeInt := range fs {
Jan Schäre479eee2024-08-21 16:01:39 +0200238 startAligned := (freeInt[0] + alignBlocks - 1) / alignBlocks * alignBlocks
239 freeBlocks := freeInt[1] - startAligned
240 if freeBlocks > largestFreeSpace {
241 largestFreeSpace = freeBlocks
Lorenz Brunee17d832022-10-18 12:02:45 +0000242 }
243 }
244
Jan Schäre479eee2024-08-21 16:01:39 +0200245 // Number of blocks the partition should occupy, rounded up.
246 blocks := (size + blockSize - 1) / blockSize
247 if size == -1 {
Jan Schär02d72172024-09-02 17:47:27 +0200248 // When size is -1, use the largest free space. Align the size to ensure
249 // that the partition does not overlap the hardware blocks containing the
250 // alternate GPT.
251 blocks = largestFreeSpace / alignBlocks * alignBlocks
252 if blocks == 0 {
Jan Schäre479eee2024-08-21 16:01:39 +0200253 return errors.New("no free space")
254 }
Jan Schäre479eee2024-08-21 16:01:39 +0200255 } else if size <= 0 {
256 return fmt.Errorf("partition size (%d bytes) must be positive or the special value -1", size)
257 }
258 for _, freeInt := range fs {
259 startAligned := (freeInt[0] + alignBlocks - 1) / alignBlocks * alignBlocks
260 freeBlocks := freeInt[1] - startAligned
261 if freeBlocks < blocks {
262 continue
263 }
264 if opts.preferEnd {
265 startAligned += (freeBlocks - blocks) / alignBlocks * alignBlocks
266 }
267 p.FirstBlock = uint64(startAligned)
268 p.LastBlock = uint64(startAligned + blocks - 1)
269
270 newPartPos := -1
271 if !opts.keepEmptyEntries {
272 for i, part := range gpt.Partitions {
273 if part.IsUnused() {
274 newPartPos = i
275 break
276 }
277 }
278 }
279 if newPartPos == -1 {
280 gpt.Partitions = append(gpt.Partitions, p)
281 } else {
282 gpt.Partitions[newPartPos] = p
283 }
284 p.Section, err = blockdev.NewSection(gpt.b, int64(p.FirstBlock), int64(p.LastBlock)+1)
285 if err != nil {
286 return fmt.Errorf("failed to create blockdev Section for partition: %w", err)
287 }
288 return nil
289 }
290
291 return fmt.Errorf("no space for partition of %d blocks, largest continuous free space after alignment is %d blocks", blocks, largestFreeSpace)
Lorenz Brunee17d832022-10-18 12:02:45 +0000292}
293
294// FirstUsableBlock returns the first usable (i.e. a partition can start there)
295// block.
Tim Windelschmidt0c57d342024-04-11 01:38:47 +0200296func (gpt *Table) FirstUsableBlock() int64 {
297 blockSize := gpt.b.BlockSize()
Lorenz Brunad131882023-06-28 16:42:20 +0200298 partitionEntryBlocks := (16384 + blockSize - 1) / blockSize
Lorenz Brunee17d832022-10-18 12:02:45 +0000299 return 2 + partitionEntryBlocks
300}
301
302// LastUsableBlock returns the last usable (i.e. a partition can end there)
303// block. This block is inclusive.
Tim Windelschmidt0c57d342024-04-11 01:38:47 +0200304func (gpt *Table) LastUsableBlock() int64 {
305 blockSize := gpt.b.BlockSize()
Lorenz Brunad131882023-06-28 16:42:20 +0200306 partitionEntryBlocks := (16384 + blockSize - 1) / blockSize
Tim Windelschmidt0c57d342024-04-11 01:38:47 +0200307 return gpt.b.BlockCount() - (2 + partitionEntryBlocks)
Lorenz Brunee17d832022-10-18 12:02:45 +0000308}
309
310// GetFreeSpaces returns a slice of tuples, each containing a half-closed
311// interval of logical blocks not occupied by the GPT itself or any partition.
312// The returned intervals are always in ascending order as well as
313// non-overlapping. It also returns if it detected any overlaps between
314// partitions or partitions and the GPT. It returns an error if and only if any
315// partition has its FirstBlock before the LastBlock or exceeds the amount of
316// blocks on the block device.
317//
318// Note that the most common use cases for this function are covered by
319// AddPartition, you're encouraged to use it instead.
Tim Windelschmidt0c57d342024-04-11 01:38:47 +0200320func (gpt *Table) GetFreeSpaces() ([][2]int64, bool, error) {
Lorenz Brunee17d832022-10-18 12:02:45 +0000321 // This implements an efficient algorithm for finding free intervals given
322 // a set of potentially overlapping occupying intervals. It uses O(n*log n)
323 // time for n being the amount of intervals, i.e. partitions. It uses O(n)
324 // additional memory. This makes it de facto infinitely scalable in the
325 // context of partition tables as the size of the block device is not part
326 // of its cyclomatic complexity and O(n*log n) is tiny for even very big
327 // partition tables.
328
Tim Windelschmidt0c57d342024-04-11 01:38:47 +0200329 blockCount := gpt.b.BlockCount()
Lorenz Brunad131882023-06-28 16:42:20 +0200330
Lorenz Brunee17d832022-10-18 12:02:45 +0000331 // startBlocks contains the start blocks (inclusive) of all occupied
332 // intervals.
333 var startBlocks []int64
334 // endBlocks contains the end blocks (exclusive!) of all occupied intervals.
335 // The interval at index i is given by [startBlock[i], endBlock[i]).
336 var endBlocks []int64
337
338 // Reserve the primary GPT interval including the protective MBR.
339 startBlocks = append(startBlocks, 0)
Tim Windelschmidt0c57d342024-04-11 01:38:47 +0200340 endBlocks = append(endBlocks, gpt.FirstUsableBlock())
Lorenz Brunee17d832022-10-18 12:02:45 +0000341
342 // Reserve the alternate GPT interval (needs +1 for exclusive interval)
Tim Windelschmidt0c57d342024-04-11 01:38:47 +0200343 startBlocks = append(startBlocks, gpt.LastUsableBlock()+1)
Lorenz Brunad131882023-06-28 16:42:20 +0200344 endBlocks = append(endBlocks, blockCount)
Lorenz Brunee17d832022-10-18 12:02:45 +0000345
Tim Windelschmidt0c57d342024-04-11 01:38:47 +0200346 for i, part := range gpt.Partitions {
Lorenz Brunee17d832022-10-18 12:02:45 +0000347 if part.IsUnused() {
348 continue
349 }
350 // Bail if partition does not contain a valid interval. These are open
351 // intervals, thus part.FirstBlock == part.LastBlock denotes a valid
352 // partition with a size of one block.
353 if part.FirstBlock > part.LastBlock {
354 return nil, false, fmt.Errorf("partition %d has a LastBlock smaller than its FirstBlock, its interval is [%d, %d]", i, part.FirstBlock, part.LastBlock)
355 }
Lorenz Brunad131882023-06-28 16:42:20 +0200356 if part.FirstBlock >= uint64(blockCount) || part.LastBlock >= uint64(blockCount) {
Lorenz Brunee17d832022-10-18 12:02:45 +0000357 return nil, false, fmt.Errorf("partition %d exceeds the block count of the block device", i)
358 }
359 startBlocks = append(startBlocks, int64(part.FirstBlock))
360 // Algorithm needs open-closed intervals, thus add +1 to the end.
361 endBlocks = append(endBlocks, int64(part.LastBlock)+1)
362 }
363 // Sort both sets of blocks independently in ascending order. Note that it
364 // is now no longer possible to extract the original intervals. Integers
365 // have no identity thus it doesn't matter if the sort is stable or not.
Jan Schäre479eee2024-08-21 16:01:39 +0200366 slices.Sort(startBlocks)
367 slices.Sort(endBlocks)
Lorenz Brunee17d832022-10-18 12:02:45 +0000368
369 var freeSpaces [][2]int64
370
371 // currentIntervals contains the number of intervals which contain the
372 // position currently being iterated over. If currentIntervals is ever
373 // bigger than 1, there is overlap within the given intervals.
374 currentIntervals := 0
375 var hasOverlap bool
376
377 // Iterate for as long as there are interval boundaries to be processed.
378 for len(startBlocks) != 0 || len(endBlocks) != 0 {
379 // Short-circuit boundary processing. If an interval ends at x and the
380 // next one starts at x (this is using half-open intervals), it would
381 // otherwise perform useless processing as well as create an empty free
382 // interval which would then need to be filtered back out.
383 if len(startBlocks) != 0 && len(endBlocks) != 0 && startBlocks[0] == endBlocks[0] {
384 startBlocks = startBlocks[1:]
385 endBlocks = endBlocks[1:]
386 continue
387 }
388 // Pick the lowest boundary from either startBlocks or endBlocks,
389 // preferring endBlocks if they are equal. Don't try to pick from empty
390 // slices.
391 if (len(startBlocks) != 0 && len(endBlocks) != 0 && startBlocks[0] < endBlocks[0]) || len(endBlocks) == 0 {
392 // If currentIntervals == 0 a free space region ends here.
393 // Since this algorithm creates the free space interval at the end
394 // of an occupied interval, for the first interval there is no free
395 // space entry. But in this case it's fine to just ignore it as the
396 // first interval always starts at 0 because of the GPT.
397 if currentIntervals == 0 && len(freeSpaces) != 0 {
398 freeSpaces[len(freeSpaces)-1][1] = startBlocks[0]
399 }
400 // This is the start of an interval, increase the number of active
401 // intervals.
402 currentIntervals++
403 hasOverlap = hasOverlap || currentIntervals > 1
404 // Drop processed startBlock from slice.
405 startBlocks = startBlocks[1:]
406 } else {
407 // This is the end of an interval, decrease the number of active
408 // intervals.
409 currentIntervals--
410 // If currentIntervals == 0 a free space region starts here.
411 // Same as with the startBlocks, ignore a potential free block after
412 // the final range as the GPT occupies the last blocks anyway.
413 if currentIntervals == 0 && len(startBlocks) != 0 {
414 freeSpaces = append(freeSpaces, [2]int64{endBlocks[0], 0})
415 }
416 endBlocks = endBlocks[1:]
417 }
418 }
419 return freeSpaces, hasOverlap, nil
420}
421
422// Overhead returns the number of blocks the GPT partitioning itself consumes,
423// i.e. aren't usable for user data.
424func Overhead(blockSize int64) int64 {
425 // 3 blocks + 2x 16384 bytes (partition entry space)
426 partitionEntryBlocks := (16384 + blockSize - 1) / blockSize
427 return 3 + (2 * partitionEntryBlocks)
428}
429
Lorenz Brunad131882023-06-28 16:42:20 +0200430// Write writes the two GPTs, first the alternate, then the primary to the
431// block device. If gpt.ID or any of the partition IDs are the all-zero UUID,
432// new random ones are generated and written back. If the output is supposed
433// to be reproducible, generate the UUIDs beforehand.
434func (gpt *Table) Write() error {
435 blockSize := gpt.b.BlockSize()
436 blockCount := gpt.b.BlockCount()
437 if blockSize < 512 {
Lorenz Brunee17d832022-10-18 12:02:45 +0000438 return errors.New("block size is smaller than 512 bytes, this is unsupported")
439 }
440 // Layout looks as follows:
441 // Block 0: Protective MBR
442 // Block 1: GPT Header
443 // Block 2-(16384 bytes): GPT partition entries
444 // Block (16384 bytes)-n: GPT partition entries alternate copy
445 // Block n: GPT Header alternate copy
Lorenz Brunad131882023-06-28 16:42:20 +0200446 partitionEntryCount := 128
447 if len(gpt.Partitions) > partitionEntryCount {
448 return errors.New("bigger-than default GPTs (>128 partitions) are unimplemented")
Lorenz Brunee17d832022-10-18 12:02:45 +0000449 }
450
Lorenz Brunad131882023-06-28 16:42:20 +0200451 partitionEntryBlocks := (16384 + blockSize - 1) / blockSize
452 if blockCount < 3+(2*partitionEntryBlocks) {
Lorenz Brunee17d832022-10-18 12:02:45 +0000453 return errors.New("not enough blocks to write GPT")
454 }
455
Lorenz Brunad131882023-06-28 16:42:20 +0200456 if gpt.ID == uuid.Nil {
Lorenz Brunee17d832022-10-18 12:02:45 +0000457 gpt.ID = uuid.New()
458 }
459
460 partSize := binary.Size(partition{})
Lorenz Brunee17d832022-10-18 12:02:45 +0000461 var partitionEntriesData bytes.Buffer
Lorenz Brunad131882023-06-28 16:42:20 +0200462 for i := 0; i < partitionEntryCount; i++ {
Lorenz Brunee17d832022-10-18 12:02:45 +0000463 if len(gpt.Partitions) <= i || gpt.Partitions[i] == nil {
Lorenz Brunad131882023-06-28 16:42:20 +0200464 // Write an empty entry
Lorenz Brunee17d832022-10-18 12:02:45 +0000465 partitionEntriesData.Write(make([]byte, partSize))
466 continue
467 }
468 p := gpt.Partitions[i]
Lorenz Brunad131882023-06-28 16:42:20 +0200469 if p.ID == uuid.Nil {
Lorenz Brunee17d832022-10-18 12:02:45 +0000470 p.ID = uuid.New()
471 }
472 rawP := partition{
Lorenz Brun60d6b902023-06-20 16:02:40 +0200473 Type: msguid.From(p.Type),
474 ID: msguid.From(p.ID),
Lorenz Brunee17d832022-10-18 12:02:45 +0000475 FirstBlock: p.FirstBlock,
476 LastBlock: p.LastBlock,
477 Attributes: uint64(p.Attributes),
478 }
479 nameUTF16 := utf16.Encode([]rune(p.Name))
480 // copy will automatically truncate if target is too short
481 copy(rawP.Name[:], nameUTF16)
482 binary.Write(&partitionEntriesData, binary.LittleEndian, rawP)
483 }
484
485 hdr := header{
486 Signature: gptSignature,
487 Revision: gptRevision,
488 HeaderSize: uint32(binary.Size(&header{})),
Lorenz Brun60d6b902023-06-20 16:02:40 +0200489 ID: msguid.From(gpt.ID),
Lorenz Brunee17d832022-10-18 12:02:45 +0000490
Lorenz Brunad131882023-06-28 16:42:20 +0200491 PartitionEntryCount: uint32(partitionEntryCount),
Lorenz Brunee17d832022-10-18 12:02:45 +0000492 PartitionEntrySize: uint32(partSize),
493
494 FirstUsableBlock: uint64(2 + partitionEntryBlocks),
Lorenz Brunad131882023-06-28 16:42:20 +0200495 LastUsableBlock: uint64(blockCount - (2 + partitionEntryBlocks)),
Lorenz Brunee17d832022-10-18 12:02:45 +0000496 }
497 hdr.PartitionEntriesCRC32 = crc32.ChecksumIEEE(partitionEntriesData.Bytes())
498
499 hdrChecksum := crc32.NewIEEE()
500
501 // Write alternate header first, as otherwise resizes are unsafe. If the
502 // alternate is currently not at the end of the block device, it cannot
503 // be found. Thus if the write operation is aborted abnormally, the
504 // primary GPT is corrupted and the alternate cannot be found because it
505 // is not at its canonical location. Rewriting the alternate first avoids
506 // this problem.
507
508 // Alternate header
Lorenz Brunad131882023-06-28 16:42:20 +0200509 hdr.HeaderBlock = uint64(blockCount - 1)
Lorenz Brunee17d832022-10-18 12:02:45 +0000510 hdr.AlternateHeaderBlock = 1
Lorenz Brunad131882023-06-28 16:42:20 +0200511 hdr.PartitionEntriesStartBlock = uint64(blockCount - (1 + partitionEntryBlocks))
Lorenz Brunee17d832022-10-18 12:02:45 +0000512
513 hdrChecksum.Reset()
514 hdr.HeaderCRC32 = 0
515 binary.Write(hdrChecksum, binary.LittleEndian, &hdr)
516 hdr.HeaderCRC32 = hdrChecksum.Sum32()
517
Lorenz Brunad131882023-06-28 16:42:20 +0200518 for partitionEntriesData.Len()%int(blockSize) != 0 {
519 partitionEntriesData.WriteByte(0x00)
520 }
521 if _, err := gpt.b.WriteAt(partitionEntriesData.Bytes(), int64(hdr.PartitionEntriesStartBlock)*blockSize); err != nil {
Lorenz Brunee17d832022-10-18 12:02:45 +0000522 return fmt.Errorf("failed to write alternate partition entries: %w", err)
523 }
Lorenz Brunee17d832022-10-18 12:02:45 +0000524
Lorenz Brunad131882023-06-28 16:42:20 +0200525 var hdrRaw bytes.Buffer
526 if err := binary.Write(&hdrRaw, binary.LittleEndian, &hdr); err != nil {
527 return fmt.Errorf("failed to encode alternate header: %w", err)
Lorenz Brunee17d832022-10-18 12:02:45 +0000528 }
Lorenz Brunad131882023-06-28 16:42:20 +0200529 for hdrRaw.Len()%int(blockSize) != 0 {
530 hdrRaw.WriteByte(0x00)
531 }
532 if _, err := gpt.b.WriteAt(hdrRaw.Bytes(), (blockCount-1)*blockSize); err != nil {
533 return fmt.Errorf("failed to write alternate header: %v", err)
Lorenz Brunee17d832022-10-18 12:02:45 +0000534 }
535
Jan Schärc39b1dc2024-08-26 17:21:14 +0200536 // Sync device after writing each GPT, to ensure there is at least one valid
537 // GPT at all times.
538 if err := gpt.b.Sync(); err != nil {
539 return fmt.Errorf("failed to sync device after writing alternate GPT: %w", err)
540 }
541
Lorenz Brunee17d832022-10-18 12:02:45 +0000542 // Primary header
Lorenz Brunee17d832022-10-18 12:02:45 +0000543 hdr.HeaderBlock = 1
Lorenz Brunad131882023-06-28 16:42:20 +0200544 hdr.AlternateHeaderBlock = uint64(blockCount - 1)
Lorenz Brunee17d832022-10-18 12:02:45 +0000545 hdr.PartitionEntriesStartBlock = 2
546
547 hdrChecksum.Reset()
548 hdr.HeaderCRC32 = 0
549 binary.Write(hdrChecksum, binary.LittleEndian, &hdr)
550 hdr.HeaderCRC32 = hdrChecksum.Sum32()
551
Lorenz Brunad131882023-06-28 16:42:20 +0200552 hdrRaw.Reset()
553
554 if err := makeProtectiveMBR(&hdrRaw, blockCount, gpt.BootCode); err != nil {
555 return fmt.Errorf("failed creating protective MBR: %w", err)
556 }
557 for hdrRaw.Len()%int(blockSize) != 0 {
558 hdrRaw.WriteByte(0x00)
559 }
560 if err := binary.Write(&hdrRaw, binary.LittleEndian, &hdr); err != nil {
561 panic(err)
562 }
563 for hdrRaw.Len()%int(blockSize) != 0 {
564 hdrRaw.WriteByte(0x00)
565 }
566 hdrRaw.Write(partitionEntriesData.Bytes())
567 for hdrRaw.Len()%int(blockSize) != 0 {
568 hdrRaw.WriteByte(0x00)
Lorenz Brunee17d832022-10-18 12:02:45 +0000569 }
570
Lorenz Brunad131882023-06-28 16:42:20 +0200571 if _, err := gpt.b.WriteAt(hdrRaw.Bytes(), 0); err != nil {
572 return fmt.Errorf("failed to write primary GPT: %w", err)
Lorenz Brunee17d832022-10-18 12:02:45 +0000573 }
Jan Schärc39b1dc2024-08-26 17:21:14 +0200574 if err := gpt.b.Sync(); err != nil {
575 return fmt.Errorf("failed to sync device after writing primary GPT: %w", err)
576 }
Lorenz Brunee17d832022-10-18 12:02:45 +0000577 return nil
578}
579
Lorenz Brunad131882023-06-28 16:42:20 +0200580// Read reads a Table from a block device.
581func Read(r blockdev.BlockDev) (*Table, error) {
582 if Overhead(r.BlockSize()) > r.BlockCount() {
Lorenz Brunee17d832022-10-18 12:02:45 +0000583 return nil, errors.New("disk cannot contain a GPT as the block count is too small to store one")
584 }
Lorenz Brunad131882023-06-28 16:42:20 +0200585 zeroBlock := make([]byte, r.BlockSize())
586 if _, err := r.ReadAt(zeroBlock, 0); err != nil {
587 return nil, fmt.Errorf("failed to read first block: %w", err)
Lorenz Brunee17d832022-10-18 12:02:45 +0000588 }
589
590 var m mbr
591 if err := binary.Read(bytes.NewReader(zeroBlock[:512]), binary.LittleEndian, &m); err != nil {
592 panic(err) // Read is from memory and with enough data
593 }
594 // The UEFI standard says that the only acceptable MBR for a GPT-partitioned
595 // device is a pure protective MBR with one partition of type 0xEE covering
596 // the entire disk. But reality is sadly not so simple. People have come up
597 // with hacks like Hybrid MBR which is basically a way to expose partitions
598 // as both GPT partitions and MBR partitions. There are also GPTs without
599 // any MBR at all.
600 // Following the standard strictly when reading means that this library
601 // would fail to read valid GPT disks where such schemes are employed.
602 // On the other hand just looking at the GPT signature is also dangerous
603 // as not all tools clear the second block where the GPT resides when
604 // writing an MBR, which results in reading a wrong/obsolete GPT.
605 // As a pragmatic solution this library treats any disk as GPT-formatted if
606 // the first block does not contain an MBR signature or at least one MBR
607 // partition has type 0xEE (GPT). It does however not care in which slot
608 // this partition is or if it begins at the start of the disk.
609 //
610 // Note that the block signatures for MBR and FAT are shared. This is a
611 // historical artifact from DOS. It is not reliably possible to
612 // differentiate the two as either has boot code where the other has meta-
613 // data and both lack any checksums. Because the MBR partition table is at
614 // the very end of the FAT bootcode section the following code always
615 // assumes that it is dealing with an MBR. This is both more likely and
616 // the 0xEE marker is rarer and thus more specific than FATs 0x00, 0x80 and
617 // 0x02.
618 var bootCode []byte
619 hasDOSBootSig := m.Signature == mbrSignature
620 if hasDOSBootSig {
621 var isGPT bool
622 for _, p := range m.PartitionRecords {
623 if p.Type == 0xEE {
624 isGPT = true
625 }
626 }
627 // Note that there is a small but non-zero chance that isGPT is true
628 // for a raw FAT filesystem if the bootcode contains a "valid" MBR.
629 // The next error message mentions that possibility.
630 if !isGPT {
631 return nil, errors.New("block device contains an MBR table without a GPT marker or a raw FAT filesystem")
632 }
633 // Trim right zeroes away as they are padded back when writing. This
634 // makes BootCode empty when it is all-zeros, making it easier to work
635 // with while still round-tripping correctly.
636 bootCode = bytes.TrimRight(m.BootCode[:], "\x00")
637 }
638 // Read the primary GPT. If it is damaged and/or broken, read the alternate.
Lorenz Brunad131882023-06-28 16:42:20 +0200639 primaryGPT, err := readSingleGPT(r, 1)
Lorenz Brunee17d832022-10-18 12:02:45 +0000640 if err != nil {
Lorenz Brunad131882023-06-28 16:42:20 +0200641 alternateGPT, err2 := readSingleGPT(r, r.BlockCount()-1)
Lorenz Brunee17d832022-10-18 12:02:45 +0000642 if err2 != nil {
643 return nil, fmt.Errorf("failed to read both GPTs: primary GPT (%v), secondary GPT (%v)", err, err2)
644 }
645 alternateGPT.BootCode = bootCode
646 return alternateGPT, nil
647 }
648 primaryGPT.BootCode = bootCode
649 return primaryGPT, nil
650}
651
Lorenz Brunad131882023-06-28 16:42:20 +0200652func readSingleGPT(r blockdev.BlockDev, headerBlockPos int64) (*Table, error) {
653 hdrBlock := make([]byte, r.BlockSize())
654 if _, err := r.ReadAt(hdrBlock, r.BlockSize()*headerBlockPos); err != nil {
Lorenz Brunee17d832022-10-18 12:02:45 +0000655 return nil, fmt.Errorf("failed to read GPT header block: %w", err)
656 }
657 hdrBlockReader := bytes.NewReader(hdrBlock)
658 var hdr header
659 if err := binary.Read(hdrBlockReader, binary.LittleEndian, &hdr); err != nil {
660 panic(err) // Read from memory with enough bytes, should not fail
661 }
662 if hdr.Signature != gptSignature {
663 return nil, errors.New("no GPT signature found")
664 }
665 if hdr.HeaderSize < uint32(binary.Size(hdr)) {
666 return nil, fmt.Errorf("GPT header size is too small, likely corrupted")
667 }
Lorenz Brunad131882023-06-28 16:42:20 +0200668 if int64(hdr.HeaderSize) > r.BlockSize() {
Lorenz Brunee17d832022-10-18 12:02:45 +0000669 return nil, fmt.Errorf("GPT header size is bigger than block size, likely corrupted")
670 }
671 // Use reserved bytes to hash, but do not expose them to the user.
672 // If someone has a need to process them, they should extend this library
673 // with whatever an updated UEFI specification contains.
674 // It has been considered to store these in the user-exposed GPT struct to
675 // be able to round-trip them cleanly, but there is significant complexity
676 // and risk involved in doing so.
677 reservedBytes := hdrBlock[binary.Size(hdr):hdr.HeaderSize]
678 hdrExpectedCRC := hdr.HeaderCRC32
679 hdr.HeaderCRC32 = 0
680 hdrCRC := crc32.NewIEEE()
681 binary.Write(hdrCRC, binary.LittleEndian, &hdr)
682 hdrCRC.Write(reservedBytes)
683 if hdrCRC.Sum32() != hdrExpectedCRC {
684 return nil, fmt.Errorf("GPT header checksum mismatch, probably corrupted")
685 }
686 if hdr.HeaderBlock != uint64(headerBlockPos) {
687 return nil, errors.New("GPT header indicates wrong block")
688 }
689 if hdr.PartitionEntrySize < uint32(binary.Size(partition{})) {
690 return nil, errors.New("partition entry size too small")
691 }
Lorenz Brunad131882023-06-28 16:42:20 +0200692 if hdr.PartitionEntriesStartBlock > uint64(r.BlockCount()) {
Lorenz Brunee17d832022-10-18 12:02:45 +0000693 return nil, errors.New("partition entry start block is out of range")
694 }
695 // Sanity-check total size of the partition entry area. Otherwise, this is a
696 // trivial DoS as it could cause allocation of gigabytes of memory.
697 // 4MiB is equivalent to around 45k partitions at the current size.
698 // I know of no operating system which would handle even a fraction of this.
699 if uint64(hdr.PartitionEntryCount)*uint64(hdr.PartitionEntrySize) > 4*1024*1024 {
700 return nil, errors.New("partition entry area bigger than 4MiB, refusing to read")
701 }
702 partitionEntryData := make([]byte, hdr.PartitionEntrySize*hdr.PartitionEntryCount)
Lorenz Brunad131882023-06-28 16:42:20 +0200703 if _, err := r.ReadAt(partitionEntryData, r.BlockSize()*int64(hdr.PartitionEntriesStartBlock)); err != nil {
Lorenz Brunee17d832022-10-18 12:02:45 +0000704 return nil, fmt.Errorf("failed to read partition entries: %w", err)
705 }
706 if crc32.ChecksumIEEE(partitionEntryData) != hdr.PartitionEntriesCRC32 {
707 return nil, errors.New("GPT partition entry table checksum mismatch")
708 }
709 var g Table
Lorenz Brun60d6b902023-06-20 16:02:40 +0200710 g.ID = msguid.To(hdr.ID)
Lorenz Brunee17d832022-10-18 12:02:45 +0000711 for i := uint32(0); i < hdr.PartitionEntryCount; i++ {
712 entryReader := bytes.NewReader(partitionEntryData[i*hdr.PartitionEntrySize : (i+1)*hdr.PartitionEntrySize])
713 var part partition
714 if err := binary.Read(entryReader, binary.LittleEndian, &part); err != nil {
715 panic(err) // Should not happen
716 }
717 // If the partition type is the all-zero UUID, this slot counts as
718 // unused.
Lorenz Brunad131882023-06-28 16:42:20 +0200719 if part.Type == uuid.Nil {
Lorenz Brunee17d832022-10-18 12:02:45 +0000720 g.Partitions = append(g.Partitions, nil)
721 continue
722 }
723 g.Partitions = append(g.Partitions, &Partition{
Lorenz Brun60d6b902023-06-20 16:02:40 +0200724 ID: msguid.To(part.ID),
725 Type: msguid.To(part.Type),
Lorenz Brunee17d832022-10-18 12:02:45 +0000726 Name: strings.TrimRight(string(utf16.Decode(part.Name[:])), "\x00"),
727 FirstBlock: part.FirstBlock,
728 LastBlock: part.LastBlock,
729 Attributes: Attribute(part.Attributes),
730 })
731 }
732 // Remove long list of nils at the end as it's inconvenient to work with
733 // (append doesn't work, debug prints are very long) and it round-trips
734 // correctly even without it as it gets zero-padded when writing anyway.
735 var maxValidPartition int
736 for i, p := range g.Partitions {
737 if !p.IsUnused() {
738 maxValidPartition = i
739 }
740 }
741 g.Partitions = g.Partitions[:maxValidPartition+1]
Lorenz Brunad131882023-06-28 16:42:20 +0200742 g.b = r
Lorenz Brunee17d832022-10-18 12:02:45 +0000743 return &g, nil
744}