| Tim Windelschmidt | 6d33a43 | 2025-02-04 14:34:25 +0100 | [diff] [blame] | 1 | // Copyright The Monogon Project Authors. |
| 2 | // SPDX-License-Identifier: Apache-2.0 |
| 3 | |
| Lorenz Brun | bd2ce6d | 2022-07-22 00:00:13 +0000 | [diff] [blame] | 4 | // Package fat32 implements a writer for the FAT32 filesystem. |
| 5 | package fat32 |
| 6 | |
| 7 | import ( |
| 8 | "crypto/rand" |
| 9 | "encoding/binary" |
| 10 | "errors" |
| 11 | "fmt" |
| 12 | "io" |
| 13 | "io/fs" |
| 14 | "math" |
| 15 | "math/bits" |
| Lorenz Brun | bd2ce6d | 2022-07-22 00:00:13 +0000 | [diff] [blame] | 16 | "time" |
| 17 | "unicode/utf16" |
| Jan Schär | c1b6df4 | 2025-03-20 08:52:18 +0000 | [diff] [blame^] | 18 | |
| 19 | "source.monogon.dev/osbase/structfs" |
| Lorenz Brun | bd2ce6d | 2022-07-22 00:00:13 +0000 | [diff] [blame] | 20 | ) |
| 21 | |
| 22 | // This package contains multiple references to the FAT32 specification, called |
| 23 | // Microsoft Extensible Firmware Initiative FAT32 File System Specification |
| 24 | // version 1.03 (just called the spec from now on). You can get it at |
| 25 | // https://download.microsoft.com/download/0/8/4/\ |
| 26 | // 084c452b-b772-4fe5-89bb-a0cbf082286a/fatgen103.doc |
| 27 | |
| 28 | type Options struct { |
| 29 | // Size of a logical block on the block device. Needs to be a power of two |
| 30 | // equal or bigger than 512. If left at zero, defaults to 512. |
| 31 | BlockSize uint16 |
| 32 | |
| 33 | // Number of blocks the filesystem should span. If zero, it will be exactly |
| 34 | // as large as it needs to be. |
| 35 | BlockCount uint32 |
| 36 | |
| Jan Schär | c1b6df4 | 2025-03-20 08:52:18 +0000 | [diff] [blame^] | 37 | // Human-readable filesystem label. Maximum 11 bytes (gets cut off), should |
| Lorenz Brun | bd2ce6d | 2022-07-22 00:00:13 +0000 | [diff] [blame] | 38 | // be uppercase alphanumeric. |
| 39 | Label string |
| 40 | |
| 41 | // Filesystem identifier. If unset (i.e. left at zero) a random value will |
| 42 | // be assigned by WriteFS. |
| 43 | ID uint32 |
| 44 | } |
| 45 | |
| Jan Schär | c1b6df4 | 2025-03-20 08:52:18 +0000 | [diff] [blame^] | 46 | // Attribute is a bitset of flags set on a directory entry. |
| Lorenz Brun | bd2ce6d | 2022-07-22 00:00:13 +0000 | [diff] [blame] | 47 | // See also the spec page 24 |
| 48 | type Attribute uint8 |
| 49 | |
| 50 | const ( |
| 51 | // AttrReadOnly marks a file as read-only |
| 52 | AttrReadOnly Attribute = 0x01 |
| 53 | // AttrHidden indicates that directory listings should not show this file. |
| 54 | AttrHidden Attribute = 0x02 |
| 55 | // AttrSystem indicates that this is an operating system file. |
| 56 | AttrSystem Attribute = 0x04 |
| Jan Schär | c1b6df4 | 2025-03-20 08:52:18 +0000 | [diff] [blame^] | 57 | // attrVolumeID indicates that this is a special directory entry which |
| 58 | // contains the volume label. |
| 59 | attrVolumeID Attribute = 0x08 |
| 60 | // attrDirectory indicates that this is a directory and not a file. |
| 61 | attrDirectory Attribute = 0x10 |
| Lorenz Brun | bd2ce6d | 2022-07-22 00:00:13 +0000 | [diff] [blame] | 62 | // AttrArchive canonically indicates that a file has been created/modified |
| 63 | // since the last backup. Its use in practice is inconsistent. |
| 64 | AttrArchive Attribute = 0x20 |
| 65 | ) |
| 66 | |
| Jan Schär | c1b6df4 | 2025-03-20 08:52:18 +0000 | [diff] [blame^] | 67 | // DirEntrySys contains additional directory entry fields which are specific to |
| 68 | // FAT32. To set these fields, the Sys field of a [structfs.Node] can be set to |
| 69 | // a pointer to this or to a struct which embeds it. |
| 70 | type DirEntrySys struct { |
| Lorenz Brun | bd2ce6d | 2022-07-22 00:00:13 +0000 | [diff] [blame] | 71 | // Time the file or directory was created |
| 72 | CreateTime time.Time |
| 73 | // Attributes |
| 74 | Attrs Attribute |
| Jan Schär | c1b6df4 | 2025-03-20 08:52:18 +0000 | [diff] [blame^] | 75 | } |
| Lorenz Brun | bd2ce6d | 2022-07-22 00:00:13 +0000 | [diff] [blame] | 76 | |
| Jan Schär | c1b6df4 | 2025-03-20 08:52:18 +0000 | [diff] [blame^] | 77 | func (d *DirEntrySys) FAT32() *DirEntrySys { |
| 78 | return d |
| 79 | } |
| 80 | |
| 81 | // DirEntrySysAccessor is used to access [DirEntrySys] instead of directly type |
| 82 | // asserting the struct, to allow for embedding. |
| 83 | type DirEntrySysAccessor interface { |
| 84 | FAT32() *DirEntrySys |
| 85 | } |
| 86 | |
| 87 | // node is a file or directory on the FAT32 filesystem. It wraps a |
| 88 | // [structfs.Node] and holds additional fields which are filled during planning. |
| 89 | type node struct { |
| 90 | *structfs.Node |
| Lorenz Brun | bd2ce6d | 2022-07-22 00:00:13 +0000 | [diff] [blame] | 91 | dosName [11]byte |
| Jan Schär | c1b6df4 | 2025-03-20 08:52:18 +0000 | [diff] [blame^] | 92 | createTime time.Time |
| 93 | attrs Attribute |
| 94 | parent *node |
| 95 | children []*node |
| 96 | size uint32 |
| 97 | startCluster int |
| Lorenz Brun | bd2ce6d | 2022-07-22 00:00:13 +0000 | [diff] [blame] | 98 | } |
| 99 | |
| 100 | // Number of LFN entries + normal entry (all 32 bytes) |
| Jan Schär | c1b6df4 | 2025-03-20 08:52:18 +0000 | [diff] [blame^] | 101 | func (i node) metaSize() (int64, error) { |
| Lorenz Brun | bd2ce6d | 2022-07-22 00:00:13 +0000 | [diff] [blame] | 102 | fileNameUTF16 := utf16.Encode([]rune(i.Name)) |
| 103 | // VFAT file names are null-terminated |
| 104 | fileNameUTF16 = append(fileNameUTF16, 0x00) |
| 105 | if len(fileNameUTF16) > 255 { |
| 106 | return 0, errors.New("file name too long, maximum is 255 UTF-16 code points") |
| 107 | } |
| 108 | |
| 109 | // ⌈len(fileNameUTF16)/codepointsPerEntry⌉ |
| 110 | numEntries := (len(fileNameUTF16) + codepointsPerEntry - 1) / codepointsPerEntry |
| 111 | return (int64(numEntries) + 1) * 32, nil |
| 112 | } |
| 113 | |
| 114 | func lfnChecksum(dosName [11]byte) uint8 { |
| 115 | var sum uint8 |
| 116 | for _, b := range dosName { |
| 117 | sum = ((sum & 1) << 7) + (sum >> 1) + b |
| 118 | } |
| 119 | return sum |
| 120 | } |
| 121 | |
| Jan Schär | c1b6df4 | 2025-03-20 08:52:18 +0000 | [diff] [blame^] | 122 | // writeMeta writes information about this node into the contents of the parent |
| 123 | // node. |
| 124 | func (i node) writeMeta(w io.Writer) error { |
| Lorenz Brun | bd2ce6d | 2022-07-22 00:00:13 +0000 | [diff] [blame] | 125 | fileNameUTF16 := utf16.Encode([]rune(i.Name)) |
| 126 | // VFAT file names are null-terminated |
| 127 | fileNameUTF16 = append(fileNameUTF16, 0x00) |
| 128 | if len(fileNameUTF16) > 255 { |
| 129 | return errors.New("file name too long, maximum is 255 UTF-16 code points") |
| 130 | } |
| 131 | |
| 132 | // ⌈len(fileNameUTF16)/codepointsPerEntry⌉ |
| 133 | numEntries := (len(fileNameUTF16) + codepointsPerEntry - 1) / codepointsPerEntry |
| 134 | // Fill up to space in given number of entries with fill code point 0xffff |
| 135 | fillCodePoints := (numEntries * codepointsPerEntry) - len(fileNameUTF16) |
| 136 | for j := 0; j < fillCodePoints; j++ { |
| 137 | fileNameUTF16 = append(fileNameUTF16, 0xffff) |
| 138 | } |
| 139 | |
| 140 | // Write entries in reverse order |
| 141 | for j := numEntries; j > 0; j-- { |
| 142 | // Index of the code point being processed |
| 143 | cpIdx := (j - 1) * codepointsPerEntry |
| 144 | var entry lfnEntry |
| 145 | entry.Checksum = lfnChecksum(i.dosName) |
| 146 | // Downcast is safe as i <= numEntries <= ⌈255/codepointsPerEntry⌉ |
| 147 | entry.SequenceNumber = uint8(j) |
| 148 | if j == numEntries { |
| 149 | entry.SequenceNumber |= lastSequenceNumberFlag |
| 150 | } |
| 151 | entry.Attributes = 0x0F |
| 152 | copy(entry.NamePart1[:], fileNameUTF16[cpIdx:]) |
| 153 | cpIdx += len(entry.NamePart1) |
| 154 | copy(entry.NamePart2[:], fileNameUTF16[cpIdx:]) |
| 155 | cpIdx += len(entry.NamePart2) |
| 156 | copy(entry.NamePart3[:], fileNameUTF16[cpIdx:]) |
| 157 | cpIdx += len(entry.NamePart3) |
| 158 | |
| 159 | if err := binary.Write(w, binary.LittleEndian, entry); err != nil { |
| 160 | return err |
| 161 | } |
| 162 | } |
| Jan Schär | c1b6df4 | 2025-03-20 08:52:18 +0000 | [diff] [blame^] | 163 | selfSize := i.size |
| 164 | if i.attrs&attrDirectory != 0 { |
| Lorenz Brun | bd2ce6d | 2022-07-22 00:00:13 +0000 | [diff] [blame] | 165 | selfSize = 0 // Directories don't have an explicit size |
| 166 | } |
| 167 | date, t, _ := timeToMsDosTime(i.ModTime) |
| Jan Schär | c1b6df4 | 2025-03-20 08:52:18 +0000 | [diff] [blame^] | 168 | cdate, ctime, ctens := timeToMsDosTime(i.createTime) |
| Lorenz Brun | bd2ce6d | 2022-07-22 00:00:13 +0000 | [diff] [blame] | 169 | if err := binary.Write(w, binary.LittleEndian, &dirEntry{ |
| 170 | DOSName: i.dosName, |
| Jan Schär | c1b6df4 | 2025-03-20 08:52:18 +0000 | [diff] [blame^] | 171 | Attributes: uint8(i.attrs), |
| Jan Schär | 7959519 | 2024-11-11 14:55:56 +0100 | [diff] [blame] | 172 | CreationTenMilli: ctens, |
| 173 | CreationTime: ctime, |
| 174 | CreationDate: cdate, |
| Lorenz Brun | bd2ce6d | 2022-07-22 00:00:13 +0000 | [diff] [blame] | 175 | FirstClusterHigh: uint16(i.startCluster >> 16), |
| 176 | LastWrittenToTime: t, |
| 177 | LastWrittenToDate: date, |
| 178 | FirstClusterLow: uint16(i.startCluster & 0xffff), |
| Jan Schär | c1b6df4 | 2025-03-20 08:52:18 +0000 | [diff] [blame^] | 179 | FileSize: selfSize, |
| Lorenz Brun | bd2ce6d | 2022-07-22 00:00:13 +0000 | [diff] [blame] | 180 | }); err != nil { |
| 181 | return err |
| 182 | } |
| 183 | return nil |
| 184 | } |
| 185 | |
| Jan Schär | c1b6df4 | 2025-03-20 08:52:18 +0000 | [diff] [blame^] | 186 | // writeData writes the contents of this node (including possible metadata |
| Lorenz Brun | bd2ce6d | 2022-07-22 00:00:13 +0000 | [diff] [blame] | 187 | // of its children, but not its children's data) |
| Jan Schär | c1b6df4 | 2025-03-20 08:52:18 +0000 | [diff] [blame^] | 188 | func (i node) writeData(w io.Writer, volumeLabel [11]byte) error { |
| 189 | if i.attrs&attrDirectory != 0 { |
| Lorenz Brun | bd2ce6d | 2022-07-22 00:00:13 +0000 | [diff] [blame] | 190 | if i.parent == nil { |
| 191 | if err := binary.Write(w, binary.LittleEndian, &dirEntry{ |
| 192 | DOSName: volumeLabel, |
| Jan Schär | c1b6df4 | 2025-03-20 08:52:18 +0000 | [diff] [blame^] | 193 | Attributes: uint8(attrVolumeID), |
| Lorenz Brun | bd2ce6d | 2022-07-22 00:00:13 +0000 | [diff] [blame] | 194 | }); err != nil { |
| 195 | return err |
| 196 | } |
| 197 | } else { |
| 198 | date, t, _ := timeToMsDosTime(i.ModTime) |
| Jan Schär | c1b6df4 | 2025-03-20 08:52:18 +0000 | [diff] [blame^] | 199 | cdate, ctime, ctens := timeToMsDosTime(i.createTime) |
| Lorenz Brun | bd2ce6d | 2022-07-22 00:00:13 +0000 | [diff] [blame] | 200 | if err := binary.Write(w, binary.LittleEndian, &dirEntry{ |
| 201 | DOSName: [11]byte{'.', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '}, |
| 202 | CreationDate: cdate, |
| 203 | CreationTime: ctime, |
| 204 | CreationTenMilli: ctens, |
| 205 | LastWrittenToTime: t, |
| 206 | LastWrittenToDate: date, |
| Jan Schär | c1b6df4 | 2025-03-20 08:52:18 +0000 | [diff] [blame^] | 207 | Attributes: uint8(i.attrs), |
| Lorenz Brun | bd2ce6d | 2022-07-22 00:00:13 +0000 | [diff] [blame] | 208 | FirstClusterHigh: uint16(i.startCluster >> 16), |
| 209 | FirstClusterLow: uint16(i.startCluster & 0xffff), |
| 210 | }); err != nil { |
| 211 | return err |
| 212 | } |
| 213 | startCluster := i.parent.startCluster |
| 214 | if i.parent.parent == nil { |
| 215 | // Special case: When the dotdot directory points to the root |
| 216 | // directory, the start cluster is defined to be zero even if |
| 217 | // it isn't. |
| 218 | startCluster = 0 |
| 219 | } |
| 220 | // Time is intentionally taken from this directory, not the parent |
| 221 | if err := binary.Write(w, binary.LittleEndian, &dirEntry{ |
| 222 | DOSName: [11]byte{'.', '.', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '}, |
| Jan Schär | 7959519 | 2024-11-11 14:55:56 +0100 | [diff] [blame] | 223 | CreationDate: cdate, |
| 224 | CreationTime: ctime, |
| 225 | CreationTenMilli: ctens, |
| Lorenz Brun | bd2ce6d | 2022-07-22 00:00:13 +0000 | [diff] [blame] | 226 | LastWrittenToTime: t, |
| 227 | LastWrittenToDate: date, |
| Jan Schär | c1b6df4 | 2025-03-20 08:52:18 +0000 | [diff] [blame^] | 228 | Attributes: uint8(attrDirectory), |
| Lorenz Brun | bd2ce6d | 2022-07-22 00:00:13 +0000 | [diff] [blame] | 229 | FirstClusterHigh: uint16(startCluster >> 16), |
| 230 | FirstClusterLow: uint16(startCluster & 0xffff), |
| 231 | }); err != nil { |
| 232 | return err |
| 233 | } |
| 234 | } |
| Jan Schär | c1b6df4 | 2025-03-20 08:52:18 +0000 | [diff] [blame^] | 235 | for _, c := range i.children { |
| Lorenz Brun | bd2ce6d | 2022-07-22 00:00:13 +0000 | [diff] [blame] | 236 | if err := c.writeMeta(w); err != nil { |
| 237 | return err |
| 238 | } |
| 239 | } |
| 240 | } else { |
| Jan Schär | c1b6df4 | 2025-03-20 08:52:18 +0000 | [diff] [blame^] | 241 | content, err := i.Content.Open() |
| 242 | if err != nil { |
| 243 | return err |
| 244 | } |
| 245 | defer content.Close() |
| 246 | if _, err := io.CopyN(w, content, int64(i.size)); err != nil { |
| Lorenz Brun | bd2ce6d | 2022-07-22 00:00:13 +0000 | [diff] [blame] | 247 | return err |
| 248 | } |
| 249 | } |
| 250 | return nil |
| 251 | } |
| 252 | |
| Jan Schär | c1b6df4 | 2025-03-20 08:52:18 +0000 | [diff] [blame^] | 253 | func (i node) dirSize() (uint32, error) { |
| 254 | var size int64 |
| 255 | if i.parent != nil { |
| 256 | // Dot and dotdot directories |
| 257 | size += 2 * 32 |
| Lorenz Brun | bd2ce6d | 2022-07-22 00:00:13 +0000 | [diff] [blame] | 258 | } else { |
| Jan Schär | c1b6df4 | 2025-03-20 08:52:18 +0000 | [diff] [blame^] | 259 | // Volume ID |
| 260 | size += 1 * 32 |
| Lorenz Brun | bd2ce6d | 2022-07-22 00:00:13 +0000 | [diff] [blame] | 261 | } |
| Jan Schär | c1b6df4 | 2025-03-20 08:52:18 +0000 | [diff] [blame^] | 262 | for _, c := range i.children { |
| 263 | cs, err := c.metaSize() |
| 264 | if err != nil { |
| 265 | return 0, err |
| Lorenz Brun | bd2ce6d | 2022-07-22 00:00:13 +0000 | [diff] [blame] | 266 | } |
| Jan Schär | c1b6df4 | 2025-03-20 08:52:18 +0000 | [diff] [blame^] | 267 | size += cs |
| Lorenz Brun | bd2ce6d | 2022-07-22 00:00:13 +0000 | [diff] [blame] | 268 | } |
| Jan Schär | c1b6df4 | 2025-03-20 08:52:18 +0000 | [diff] [blame^] | 269 | if size > 2*1024*1024 { |
| 270 | return 0, errors.New("directory contains > 2MiB of metadata which is prohibited in FAT32") |
| 271 | } |
| 272 | return uint32(size), nil |
| Lorenz Brun | bd2ce6d | 2022-07-22 00:00:13 +0000 | [diff] [blame] | 273 | } |
| 274 | |
| 275 | type planningState struct { |
| Jan Schär | c1b6df4 | 2025-03-20 08:52:18 +0000 | [diff] [blame^] | 276 | // List of nodes in filesystem layout order |
| 277 | orderedNodes []*node |
| Lorenz Brun | bd2ce6d | 2022-07-22 00:00:13 +0000 | [diff] [blame] | 278 | // File Allocation Table |
| 279 | fat []uint32 |
| 280 | // Size of a single cluster in the FAT in bytes |
| 281 | clusterSize int64 |
| 282 | } |
| 283 | |
| 284 | // Allocates clusters capable of holding at least b bytes and returns the |
| 285 | // starting cluster index |
| 286 | func (p *planningState) allocBytes(b int64) int { |
| 287 | // Zero-byte data entries are located at the cluster zero by definition |
| 288 | // No actual allocation is performed |
| 289 | if b == 0 { |
| 290 | return 0 |
| 291 | } |
| 292 | // Calculate the number of clusters to be allocated |
| 293 | n := (b + p.clusterSize - 1) / p.clusterSize |
| 294 | allocStartCluster := len(p.fat) |
| 295 | for i := int64(0); i < n-1; i++ { |
| 296 | p.fat = append(p.fat, uint32(len(p.fat)+1)) |
| 297 | } |
| 298 | p.fat = append(p.fat, fatEOF) |
| 299 | return allocStartCluster |
| 300 | } |
| 301 | |
| Jan Schär | c1b6df4 | 2025-03-20 08:52:18 +0000 | [diff] [blame^] | 302 | func (i *node) placeRecursively(p *planningState) error { |
| 303 | if i.Mode.IsDir() { |
| 304 | for _, c := range i.Node.Children { |
| 305 | node := &node{ |
| 306 | Node: c, |
| 307 | createTime: c.ModTime, |
| 308 | parent: i, |
| 309 | } |
| 310 | if sys, ok := c.Sys.(DirEntrySysAccessor); ok { |
| 311 | sys := sys.FAT32() |
| 312 | node.attrs = sys.Attrs & (AttrReadOnly | AttrHidden | AttrSystem | AttrArchive) |
| 313 | if !sys.CreateTime.IsZero() { |
| 314 | node.createTime = sys.CreateTime |
| 315 | } |
| 316 | } |
| 317 | switch { |
| 318 | case c.Mode.IsRegular(): |
| 319 | size := c.Content.Size() |
| 320 | if size < 0 { |
| 321 | return fmt.Errorf("%s: negative file size", c.Name) |
| 322 | } |
| 323 | if size >= 4*1024*1024*1024 { |
| 324 | return fmt.Errorf("%s: single file size exceeds 4GiB which is prohibited in FAT32", c.Name) |
| 325 | } |
| 326 | node.size = uint32(size) |
| 327 | if len(c.Children) != 0 { |
| 328 | return fmt.Errorf("%s: file cannot have children", c.Name) |
| 329 | } |
| 330 | case c.Mode.IsDir(): |
| 331 | node.attrs |= attrDirectory |
| 332 | default: |
| 333 | return fmt.Errorf("%s: unsupported file type %s", c.Name, c.Mode.Type().String()) |
| 334 | } |
| 335 | i.children = append(i.children, node) |
| 336 | } |
| 337 | err := makeUniqueDOSNames(i.children) |
| 338 | if err != nil { |
| 339 | return err |
| 340 | } |
| 341 | i.size, err = i.dirSize() |
| 342 | if err != nil { |
| 343 | return fmt.Errorf("%s: %w", i.Name, err) |
| 344 | } |
| Lorenz Brun | bd2ce6d | 2022-07-22 00:00:13 +0000 | [diff] [blame] | 345 | } |
| Jan Schär | c1b6df4 | 2025-03-20 08:52:18 +0000 | [diff] [blame^] | 346 | i.startCluster = p.allocBytes(int64(i.size)) |
| 347 | p.orderedNodes = append(p.orderedNodes, i) |
| 348 | for _, c := range i.children { |
| 349 | err := c.placeRecursively(p) |
| Lorenz Brun | bd2ce6d | 2022-07-22 00:00:13 +0000 | [diff] [blame] | 350 | if err != nil { |
| 351 | return fmt.Errorf("%s/%w", i.Name, err) |
| 352 | } |
| 353 | } |
| 354 | return nil |
| 355 | } |
| 356 | |
| Jan Schär | c1b6df4 | 2025-03-20 08:52:18 +0000 | [diff] [blame^] | 357 | // WriteFS writes a filesystem described by a tree to a given io.Writer. |
| 358 | func WriteFS(w io.Writer, root structfs.Tree, opts Options) error { |
| 359 | bs, fsi, p, err := prepareFS(&opts, root) |
| Tim Windelschmidt | d7e34c4 | 2024-07-09 17:32:13 +0200 | [diff] [blame] | 360 | if err != nil { |
| 361 | return err |
| 362 | } |
| 363 | |
| 364 | wb := newBlockWriter(w) |
| 365 | |
| 366 | // Write superblock |
| 367 | if err := binary.Write(wb, binary.LittleEndian, bs); err != nil { |
| 368 | return err |
| 369 | } |
| 370 | if err := wb.FinishBlock(int64(opts.BlockSize), true); err != nil { |
| 371 | return err |
| 372 | } |
| 373 | if err := binary.Write(wb, binary.LittleEndian, fsi); err != nil { |
| 374 | return err |
| 375 | } |
| 376 | if err := wb.FinishBlock(int64(opts.BlockSize), true); err != nil { |
| 377 | return err |
| 378 | } |
| 379 | |
| 380 | block := make([]byte, opts.BlockSize) |
| 381 | for i := 0; i < 4; i++ { |
| 382 | if _, err := wb.Write(block); err != nil { |
| 383 | return err |
| 384 | } |
| 385 | } |
| 386 | // Backup of superblock at block 6 |
| 387 | if err := binary.Write(wb, binary.LittleEndian, bs); err != nil { |
| 388 | return err |
| 389 | } |
| 390 | if err := wb.FinishBlock(int64(opts.BlockSize), true); err != nil { |
| 391 | return err |
| 392 | } |
| 393 | if err := binary.Write(wb, binary.LittleEndian, fsi); err != nil { |
| 394 | return err |
| 395 | } |
| 396 | if err := wb.FinishBlock(int64(opts.BlockSize), true); err != nil { |
| 397 | return err |
| 398 | } |
| 399 | |
| 400 | for i := uint8(0); i < bs.NumFATs; i++ { |
| 401 | if err := binary.Write(wb, binary.LittleEndian, p.fat); err != nil { |
| 402 | return err |
| 403 | } |
| 404 | if err := wb.FinishBlock(int64(opts.BlockSize), true); err != nil { |
| 405 | return err |
| 406 | } |
| 407 | } |
| 408 | |
| Jan Schär | c1b6df4 | 2025-03-20 08:52:18 +0000 | [diff] [blame^] | 409 | for _, i := range p.orderedNodes { |
| Tim Windelschmidt | d7e34c4 | 2024-07-09 17:32:13 +0200 | [diff] [blame] | 410 | if err := i.writeData(wb, bs.Label); err != nil { |
| Jan Schär | c1b6df4 | 2025-03-20 08:52:18 +0000 | [diff] [blame^] | 411 | return fmt.Errorf("failed to write contents of %q: %w", i.Name, err) |
| Tim Windelschmidt | d7e34c4 | 2024-07-09 17:32:13 +0200 | [diff] [blame] | 412 | } |
| Jan Schär | d589b6a | 2024-11-11 14:55:38 +0100 | [diff] [blame] | 413 | if err := wb.FinishBlock(int64(opts.BlockSize)*int64(bs.BlocksPerCluster), true); err != nil { |
| Tim Windelschmidt | d7e34c4 | 2024-07-09 17:32:13 +0200 | [diff] [blame] | 414 | return err |
| 415 | } |
| 416 | } |
| 417 | // Creatively use block writer to write out all empty data at the end |
| 418 | if err := wb.FinishBlock(int64(opts.BlockSize)*int64(bs.TotalBlocks), false); err != nil { |
| 419 | return err |
| 420 | } |
| 421 | return nil |
| 422 | } |
| 423 | |
| Jan Schär | c1b6df4 | 2025-03-20 08:52:18 +0000 | [diff] [blame^] | 424 | func prepareFS(opts *Options, root structfs.Tree) (*bootSector, *fsinfo, *planningState, error) { |
| Lorenz Brun | bd2ce6d | 2022-07-22 00:00:13 +0000 | [diff] [blame] | 425 | if opts.BlockSize == 0 { |
| 426 | opts.BlockSize = 512 |
| 427 | } |
| 428 | if bits.OnesCount16(opts.BlockSize) != 1 { |
| Tim Windelschmidt | d7e34c4 | 2024-07-09 17:32:13 +0200 | [diff] [blame] | 429 | return nil, nil, nil, fmt.Errorf("option BlockSize is not a power of two") |
| Lorenz Brun | bd2ce6d | 2022-07-22 00:00:13 +0000 | [diff] [blame] | 430 | } |
| 431 | if opts.BlockSize < 512 { |
| Tim Windelschmidt | d7e34c4 | 2024-07-09 17:32:13 +0200 | [diff] [blame] | 432 | return nil, nil, nil, fmt.Errorf("option BlockSize must be at least 512 bytes") |
| Lorenz Brun | bd2ce6d | 2022-07-22 00:00:13 +0000 | [diff] [blame] | 433 | } |
| 434 | if opts.ID == 0 { |
| 435 | var buf [4]byte |
| 436 | if _, err := rand.Read(buf[:]); err != nil { |
| Tim Windelschmidt | 5f1a7de | 2024-09-19 02:00:14 +0200 | [diff] [blame] | 437 | return nil, nil, nil, fmt.Errorf("failed to assign random FAT ID: %w", err) |
| Lorenz Brun | bd2ce6d | 2022-07-22 00:00:13 +0000 | [diff] [blame] | 438 | } |
| 439 | opts.ID = binary.BigEndian.Uint32(buf[:]) |
| 440 | } |
| Lorenz Brun | bd2ce6d | 2022-07-22 00:00:13 +0000 | [diff] [blame] | 441 | bs := bootSector{ |
| 442 | // Assembled x86_32 machine code corresponding to |
| 443 | // jmp $ |
| 444 | // nop |
| 445 | // i.e. an infinite loop doing nothing. Nothing created in the last 35 |
| 446 | // years should boot this anyway. |
| 447 | // TODO(q3k): write a stub |
| 448 | JmpInstruction: [3]byte{0xEB, 0xFE, 0x90}, |
| 449 | // Identification |
| 450 | OEMName: [8]byte{'M', 'O', 'N', 'O', 'G', 'O', 'N'}, |
| 451 | ID: opts.ID, |
| 452 | // Block geometry |
| 453 | BlockSize: opts.BlockSize, |
| 454 | TotalBlocks: opts.BlockCount, |
| 455 | // BootSector block + FSInfo Block, backup copy at blocks 6 and 7 |
| 456 | ReservedBlocks: 8, |
| 457 | // FSInfo block is always in block 1, right after this block |
| 458 | FSInfoBlock: 1, |
| 459 | // Start block of the backup of the boot block and FSInfo block |
| 460 | // De facto this must be 6 as it is only used when the primary |
| 461 | // boot block is damaged at which point this field can no longer be |
| 462 | // read. |
| 463 | BackupStartBlock: 6, |
| 464 | // A lot of implementations only work with 2, so use that |
| 465 | NumFATs: 2, |
| 466 | BlocksPerCluster: 1, |
| 467 | // Flags and signatures |
| 468 | MediaCode: 0xf8, |
| 469 | BootSignature: 0x29, |
| 470 | Label: [11]byte{' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '}, |
| 471 | Type: [8]byte{'F', 'A', 'T', '3', '2', ' ', ' ', ' '}, |
| 472 | Signature: [2]byte{0x55, 0xaa}, |
| 473 | } |
| 474 | |
| 475 | copy(bs.Label[:], opts.Label) |
| 476 | |
| Tim Windelschmidt | d7e34c4 | 2024-07-09 17:32:13 +0200 | [diff] [blame] | 477 | fsi := fsinfo{ |
| Lorenz Brun | bd2ce6d | 2022-07-22 00:00:13 +0000 | [diff] [blame] | 478 | // Signatures |
| 479 | LeadSignature: [4]byte{0x52, 0x52, 0x61, 0x41}, |
| 480 | StructSignature: [4]byte{0x72, 0x72, 0x41, 0x61}, |
| 481 | TrailingSignature: [2]byte{0x55, 0xAA}, |
| 482 | |
| 483 | // This is the unset value which is always legal |
| 484 | NextFreeCluster: 0xFFFFFFFF, |
| 485 | } |
| 486 | |
| 487 | p := planningState{ |
| 488 | clusterSize: int64(bs.BlocksPerCluster) * int64(bs.BlockSize), |
| 489 | } |
| 490 | if opts.BlockCount != 0 { |
| 491 | // Preallocate FAT if we know how big it needs to be |
| 492 | p.fat = make([]uint32, 0, opts.BlockCount/uint32(bs.BlocksPerCluster)) |
| 493 | } else { |
| 494 | // Preallocate minimum size FAT |
| 495 | // See the spec page 15 for the origin of this calculation. |
| 496 | p.fat = make([]uint32, 0, 65525+2) |
| 497 | } |
| 498 | // First two clusters are special |
| 499 | p.fat = append(p.fat, 0x0fffff00|uint32(bs.MediaCode), 0x0fffffff) |
| Jan Schär | c1b6df4 | 2025-03-20 08:52:18 +0000 | [diff] [blame^] | 500 | rootNode := &node{ |
| 501 | Node: &structfs.Node{ |
| 502 | Mode: fs.ModeDir, |
| 503 | Children: root, |
| 504 | }, |
| 505 | attrs: attrDirectory, |
| 506 | } |
| 507 | err := rootNode.placeRecursively(&p) |
| Lorenz Brun | bd2ce6d | 2022-07-22 00:00:13 +0000 | [diff] [blame] | 508 | if err != nil { |
| Tim Windelschmidt | d7e34c4 | 2024-07-09 17:32:13 +0200 | [diff] [blame] | 509 | return nil, nil, nil, err |
| Lorenz Brun | bd2ce6d | 2022-07-22 00:00:13 +0000 | [diff] [blame] | 510 | } |
| 511 | |
| 512 | allocClusters := len(p.fat) |
| 513 | if allocClusters >= fatMask&math.MaxUint32 { |
| Tim Windelschmidt | d7e34c4 | 2024-07-09 17:32:13 +0200 | [diff] [blame] | 514 | return nil, nil, nil, fmt.Errorf("filesystem contains more than 2^28 FAT entries, this is unsupported. Note that this package currently always creates minimal clusters") |
| Lorenz Brun | bd2ce6d | 2022-07-22 00:00:13 +0000 | [diff] [blame] | 515 | } |
| 516 | |
| 517 | // Fill out FAT to minimum size for FAT32 |
| 518 | for len(p.fat) < 65525+2 { |
| 519 | p.fat = append(p.fat, fatFree) |
| 520 | } |
| 521 | |
| Jan Schär | c1b6df4 | 2025-03-20 08:52:18 +0000 | [diff] [blame^] | 522 | bs.RootClusterNumber = uint32(rootNode.startCluster) |
| Lorenz Brun | bd2ce6d | 2022-07-22 00:00:13 +0000 | [diff] [blame] | 523 | |
| 524 | bs.BlocksPerFAT = uint32(binary.Size(p.fat)+int(opts.BlockSize)-1) / uint32(opts.BlockSize) |
| 525 | occupiedBlocks := uint32(bs.ReservedBlocks) + (uint32(len(p.fat)-2) * uint32(bs.BlocksPerCluster)) + bs.BlocksPerFAT*uint32(bs.NumFATs) |
| 526 | if bs.TotalBlocks == 0 { |
| 527 | bs.TotalBlocks = occupiedBlocks |
| 528 | } else if bs.TotalBlocks < occupiedBlocks { |
| Tim Windelschmidt | d7e34c4 | 2024-07-09 17:32:13 +0200 | [diff] [blame] | 529 | return nil, nil, nil, fmt.Errorf("content (minimum %d blocks) would exceed number of blocks specified (%d blocks)", occupiedBlocks, bs.TotalBlocks) |
| Lorenz Brun | bd2ce6d | 2022-07-22 00:00:13 +0000 | [diff] [blame] | 530 | } else { // Fixed-size file system with enough space |
| 531 | blocksToDistribute := bs.TotalBlocks - uint32(bs.ReservedBlocks) |
| 532 | // Number of data blocks which can be described by one metadata/FAT |
| 533 | // block. Always an integer because 4 (bytes per uint32) is a divisor of |
| 534 | // all powers of two equal or bigger than 8 and FAT32 requires a minimum |
| 535 | // of 512. |
| 536 | dataBlocksPerFATBlock := (uint32(bs.BlocksPerCluster) * uint32(bs.BlockSize)) / (uint32(binary.Size(p.fat[0]))) |
| 537 | // Split blocksToDistribute between metadata and data so that exactly as |
| 538 | // much metadata (FAT) exists for describing the amount of data blocks |
| 539 | // while respecting alignment. |
| 540 | divisor := dataBlocksPerFATBlock + uint32(bs.NumFATs) |
| 541 | // 2*blocksPerCluster compensates for the first two "magic" FAT entries |
| 542 | // which do not have corresponding data. |
| 543 | bs.BlocksPerFAT = (bs.TotalBlocks + 2*uint32(bs.BlocksPerCluster) + (divisor - 1)) / divisor |
| 544 | dataBlocks := blocksToDistribute - (uint32(bs.NumFATs) * bs.BlocksPerFAT) |
| 545 | // Align to full clusters |
| 546 | dataBlocks -= dataBlocks % uint32(bs.BlocksPerCluster) |
| 547 | // Magic +2 as the first two entries do not describe data |
| 548 | for len(p.fat) < (int(dataBlocks)/int(bs.BlocksPerCluster))+2 { |
| 549 | p.fat = append(p.fat, fatFree) |
| 550 | } |
| 551 | } |
| Tim Windelschmidt | d7e34c4 | 2024-07-09 17:32:13 +0200 | [diff] [blame] | 552 | fsi.FreeCount = uint32(len(p.fat) - allocClusters) |
| 553 | if fsi.FreeCount > 1 { |
| 554 | fsi.NextFreeCluster = uint32(allocClusters) + 1 |
| 555 | } |
| 556 | return &bs, &fsi, &p, nil |
| 557 | } |
| 558 | |
| 559 | // SizeFS returns the number of blocks required to hold the filesystem defined |
| Jan Schär | c1b6df4 | 2025-03-20 08:52:18 +0000 | [diff] [blame^] | 560 | // by root and opts. This can be used for sizing calculations before calling |
| 561 | // WriteFS. |
| 562 | func SizeFS(root structfs.Tree, opts Options) (int64, error) { |
| 563 | bs, _, _, err := prepareFS(&opts, root) |
| Tim Windelschmidt | d7e34c4 | 2024-07-09 17:32:13 +0200 | [diff] [blame] | 564 | if err != nil { |
| 565 | return 0, err |
| Lorenz Brun | bd2ce6d | 2022-07-22 00:00:13 +0000 | [diff] [blame] | 566 | } |
| 567 | |
| Tim Windelschmidt | d7e34c4 | 2024-07-09 17:32:13 +0200 | [diff] [blame] | 568 | return int64(bs.TotalBlocks), nil |
| Lorenz Brun | bd2ce6d | 2022-07-22 00:00:13 +0000 | [diff] [blame] | 569 | } |