blob: 388d44ed1a7cb20ea62a49a154c041a075cdb289 [file] [log] [blame] [edit]
// Copyright 2026 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package partutil
import (
"fmt"
"strconv"
"strings"
)
func parseGUIDAttrs(field string) (uint64, error) {
var result uint64
field = strings.TrimPrefix(field, "GUID:")
for _, bit := range strings.Split(field, ",") {
bitNum, err := strconv.Atoi(bit)
if err != nil {
return result, err
}
result |= 1 << bitNum
}
return result, nil
}
// ParseGPTAttrs reads a GPT attributes string output by sfdisk and converts it
// into a uint64 with the appropriate bits set.
func ParseGPTAttrs(attrs string) (uint64, error) {
var result uint64
fields := strings.Fields(attrs)
for i, field := range fields {
if strings.HasPrefix(field, "GUID:") {
guidBits, err := parseGUIDAttrs(field)
if err != nil {
return result, fmt.Errorf("could not parse field %d: %v", i, err)
}
result |= guidBits
} else if field == "RequiredPartition" {
result |= 1 << 0
} else if field == "NoBlockIOProtocol" {
result |= 1 << 1
} else if field == "LegacyBIOSBootable" {
result |= 1 << 2
} else {
return result, fmt.Errorf("unknown field %q when parsing %q", field, attrs)
}
}
return result, nil
}
// GPTPriority extracts the GPT priority value from the given sfdisk attributes.
func GPTPriority(attrs string) (uint64, error) {
bits, err := ParseGPTAttrs(attrs)
if err != nil {
return 0, err
}
return (bits >> 48) & 0xf, nil
}