返回资讯中心
外部精选
软件工程
#开发者实时流

Decoding FAT12's 1.5-byte table entries by hand

FAT12 is a pleasantly simple file system. A volume is just four regions laid out back to back: the reserved region with the boot sector, the File Allocation Tables (usually two identical copies), the root directory, and…

Hacker News 最新BjoernGoetz2026/11/23 · 今天29 分钟阅读

以下正文同步自 Hacker News 最新,版权归原站所有,已转换为易读排版。

FAT12 is a pleasantly simple file system. A volume is just four regions laid out back to back: the reserved region with the boot sector, the File Allocation Tables (usually two identical copies), the root directory, and the data region. Its on-disk structures are flat, fixed-size structs you can map straight onto C. No extents, no B-trees, just a linked list of clusters.

Until you try to read an entry out of the FAT. That’s where the headaches start. Forum threads are full of people stuck right here, and most explanations hand you a formula without ever saying how or why it works.

The 12 in FAT12 means every FAT entry is exactly 12 bits wide. That doesn’t sound worrying until you say it differently: every entry is one and a half bytes. A CPU addresses memory in whole bytes, so there is no “byte 9.5” to load. The entries don’t line up with the bytes: entry 0 starts at byte 0, but entry 1 starts halfway through byte 1. And on top of that, they are stored little-endian.

First we decode two real entries by hand with xxd on a real disk image and check the result against the file’s actual data. Then we see how the same steps work in C. This post is adapted from Chapter 5 of my FAT12 book.

A directory entry tells you only where a file starts, not where it continues: its first cluster. A cluster is the smallest unit FAT12 allocates, a fixed number of sectors chosen when the volume is formatted, so a file bigger than one cluster continues somewhere else, and that somewhere doesn’t have to be the next cluster. Files grow and get deleted, and their clusters end up scattered across the volume.

The FAT strings them back together. It’s a flat array with one entry per cluster, and each entry holds the number of the file’s next cluster. If a file continues from cluster 5 to cluster 9, entry 5 holds the value 9. That makes every file a linked list, the cluster chain. A few values are special:

Entries 0 and 1 are reserved, which is why the first data cluster is cluster 2.

Let’s start by creating a disk image, so you can follow along byte for byte. The commands we use need Linux, so if you’re on another OS, use a Linux VM or a privileged Linux Docker container:

docker run --rm -it --privileged -v "$PWD":/work -w /work debian

Install the tools we need:

apt-get update && apt-get install -y dosfstools fatcat xxd sudo

Then create and format the disk image:

dd if=/dev/zero of=disk.img bs=1M count=4 mkfs.fat -F 12 -s 2 -S 512 -n MYDISK disk.img

That gives us a 4 MiB volume with 512-byte sectors and 2 sectors per cluster, so each cluster is 1024 bytes.

With the disk image in place, let’s mount it and add the files whose FAT entries we’ll decode: three tiny ones that each fit in a single cluster, and BIGFILE.TXT, which needs two. It’s 1025 A’s, one byte too many for one cluster.

sudo mkdir -p /mnt/fat12 sudo mount -o loop disk.img /mnt/fat12

for f in ONE TWO THREE; do echo hi | sudo tee /mnt/fat12/$f.TXT > /dev/null; done printf '%1025s' '' | tr ' ' 'A' | sudo tee /mnt/fat12/BIGFILE.TXT > /dev/null

sudo umount /mnt/fat12

Next we need the file’s first cluster, which is in its directory entry. fatcat lists the entries for us:

fatcat disk.img -l /

Listing path / Directory cluster: 0 f 4/11/2026 06:21:54 ONE.TXT c=3 s=3 (3B) f 4/11/2026 06:21:54 TWO.TXT c=4 s=3 (3B) f 4/11/2026 06:21:54 THREE.TXT c=5 s=3 (3B) f 4/11/2026 06:21:54 BIGFILE.TXT c=6 s=1025 (1.00098K)

c is the first cluster, so BIGFILE.TXT starts at cluster 6. The tiny files do two jobs here. They push BIGFILE.TXT onto an even cluster followed by an odd one, and we’ll see that those two decode differently. They also leave a few simple entries for you to practice on later. Your dates will differ, but the rest won’t.

Now for the FAT itself. fsck.fat can show us where it is: -v prints how the boot sector lays out the volume, -n keeps it read-only, and grep keeps just the lines we need:

fsck.fat -v -n disk.img | grep -E 'per cluster|starts at|data clusters'

1024 bytes per cluster First FAT starts at byte 512 (sector 1) Root directory starts at byte 12800 (sector 25) Data area starts at byte 29184 (sector 57) 4067 data clusters (4164608 bytes)

The first FAT starts at byte 512, right after the boot sector. That’s 0x200 in hex, so let’s dump its first 16 bytes:

xxd -g 1 -s 0x200 -l 16 disk.img

00000200: f8 ff ff 00 f0 ff ff ff ff 07 f0 ff 00 00 00 00 ................

These are the 12-bit entries, packed back to back and shown byte by byte in hex. We saw that BIGFILE.TXT starts at cluster 6, so somewhere in these bytes is the entry for cluster 6, which tells us where the file continues. Let’s find it.

C has no 12-bit type, so we read the next bigger unit made of whole bytes, a 16-bit value. No entry ever reaches into a third byte, which means those two bytes always hold the entry’s 12 bits plus one stray nibble from a neighbor.

That gives us three steps: find the byte where the entry starts, read two bytes from there as one 16-bit value, and remove the neighbor’s stray nibble from that value, so only the entry’s 12 bits are left, in the lowest bits.

Finding the start is the easy part, because the entries follow a pattern that repeats every three bytes: 24 bits hold exactly two entries. An even entry starts on a byte boundary. An odd one starts in the middle of the byte it shares with the even entry before it:

Every entry is 1.5 bytes long, so cluster N starts N * 1.5 bytes into the FAT. For odd clusters, integer division rounds that down to the shared byte:

Byte offset = N + N / 2 (rounded down)

The other two steps are easiest to see with real bytes, so let’s decode the two entries BIGFILE.TXT needs.

6 + 6 / 2 gives byte 9. Bytes 9 and 10 of our dump are 07 f0.

Little-endian means the second byte is the high byte, so reading the dump we swap the bytes, not the nibbles: 07 f0 becomes 0xF007. Cluster 6 is even, so its 12 bits already sit at the bottom. The F on top belongs to cluster 7, and masking it off leaves 0x007:

7 + 7 / 2 is 7 + 3, byte 10. Bytes 10 and 11 are f0 ff, and swapping them gives 0xFFF0. This time the stray nibble is the 0 at the bottom, the top nibble of cluster 6’s entry. Shifting right by 4 pushes it out and moves the entry’s 12 bits down into the lowest bits:

Cluster 7 holds 0xFFF, end of chain, so the file is 6 -> 7 -> end. That’s the whole algorithm: read two bytes at N + N / 2 as one little-endian value, the second byte on top, then mask if N is even or shift if N is odd.

Want to check you’ve got it? Decode entries 0 to 5 from the same dump. You should get 0xFF8 and 0xFFF for the two reserved entries (entry 0 isn’t an end-of-chain mark: it’s the media byte F8 padded with 1 bits), 0x000 for cluster 2, and 0xFFF for clusters 3, 4 and 5, our three tiny files. Cluster 2 is free because Linux’s FAT driver started handing out clusters at 3 on this fresh volume.

If we got it right, cluster 7 holds the file’s last byte, a single A. To look, we turn the cluster number into a byte offset. fsck.fat told us the data area starts at sector 57, and the first cluster there is cluster 2, so cluster 7 is 7 - 2 = 5 clusters in. Each cluster is 2 sectors, which puts it at sector 57 + 5 * 2 = 67. Each sector is 512 bytes, so that’s byte 67 * 512 = 34304, or 0x8600 in hex:

$ xxd -g 1 -s 0x8600 -l 16 disk.img 00008600: 41 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 A...............

0x41, our last A, and after it nothing but zeros.

Here are the three steps as a function. It takes the FAT as a byte array and a cluster number, and returns that cluster’s entry:

#include <stdint.h>

uint16_t get_fat_entry(const uint8_t fat, uint16_t cluster) { / 1.5 bytes per entry; integer division rounds odd clusters down to the shared byte */ uint32_t offset = cluster + (cluster / 2);

/* two bytes, little-endian: 07 f0 -> 0xF007 */ uint16_t value = (fat[offset + 1] << 8) | fat[offset];

if (cluster & 1) { /* odd: drop the bottom nibble / return value >> 4; } else { / even: drop the top nibble */ return value & 0x0FFF; } }

The function expects the whole FAT in memory, and that matters. If you load the FAT one sector at a time, as small bootloaders often do, an entry that starts on a sector’s last byte spans two sectors. The first is cluster 341, since 341 + 341 / 2 = 511, and it recurs twice every three sectors (682 is next). The entry’s second byte is already in the next sector, so load the whole FAT, or at least two sectors at a time.

To try it, we don’t even need the disk image. A minimal main can hand it the 16 bytes from our xxd dump and decode the first eight entries:

#include <stdio.h>

int main(void) { /* the first 16 bytes of our FAT, straight from xxd */ const uint8_t fat[16] = {0xf8, 0xff, 0xff, 0x00, 0xf0, 0xff, 0xff, 0xff, 0xff, 0x07, 0xf0, 0xff, 0x00, 0x00, 0x00, 0x00};

for (uint16_t cluster = 0; cluster <= 7; cluster++) printf("entry %u: 0x%03X\n", cluster, get_fat_entry(fat, cluster));

return 0; }

Put both listings in one file, fat.c, then build and run it on any machine with a C compiler:

gcc -Wall -Wextra fat.c -o fat && ./fat

It compiles without warnings and prints:

entry 0: 0xFF8 entry 1: 0xFFF entry 2: 0x000 entry 3: 0xFFF entry 4: 0xFFF entry 5: 0xFFF entry 6: 0x007 entry 7: 0xFFF

Entries 6 and 7 are the ones we decoded by hand, and entries 0 to 5 match the self-check from above. To follow a cluster chain, you call get_fat_entry in a loop: start at a file’s first cluster, read the entry, jump to the cluster it names, and stop once the value no longer points to a valid next cluster. That means an end-of-chain marker, a bad-cluster marker, or a number outside the volume’s data clusters. Those are numbered from 2, so on our volume the 4067 clusters run from 2 to 4068.

Get a step wrong and nothing crashes. You just get a different cluster number, and it looks fine.

Get the byte order wrong, and 07 f0 reads as 0x07F0. Masked, that’s cluster 2032. Our volume has 4067 clusters, so it passes every range check, and you read 1 KiB of whatever happens to sit there. Mix up the mask and the shift, and cluster 6 decodes as 0xF007 >> 4, cluster 3840: also in range, also the wrong data.

Even correct code needs a guard. A corrupt FAT can point a chain back at itself (6 -> 7 -> 6), and since every number in that loop is in range, the walk never ends on its own. So give it a hard limit: no chain can be longer than the volume has clusters.

The broken versions of this code look just as reasonable as the correct one, so reading it won’t catch these bugs. That goes double for a get_fat_entry you got from an LLM or a forum post: right or wrong, it will look plausible. The test I trust is the one we did above: decode a few entries by hand with xxd, then check that the code agrees.

In a read-only driver, a read bug only returns wrong data. A write bug damages the volume, and so does a read bug once your delete or allocate code trusts it. Writing an entry means changing two bytes, and half of one of them belongs to a neighbor’s entry. Forget to preserve that nibble, and you silently cut or redirect another file’s chain, and nothing tells you until that file comes back wrong.

Chapter 7 of my FAT12 book builds the write side, set_fat_entry, and checks it on a real disk image: a trace of every FAT byte it touches, including one that two neighboring entries share, then a hexdump of the FAT copies on the volume.

正文由 探How 从来源站点 RSS 同步,内容未经改写;遇到排版缺失或需要图片、视频时请以原文为准。

打开原文
去社区讨论 →