Lab: Create, destroy and repair a file system
Introduction
First of all: File system is just a layer used to organize how data is stored and retrieved. It is different from partition or volume. A great feature of Linux is that we can create a new filesystem in a plain file instead of a partition or disk. Then, we can mount the file to our working system.
Tools to be used:
- dd
- hexdump(xxd)
- mkfs(mke2fs)
- dumpe2fs
- losetup
- blkid
Create a file system
In this section, create a single file and format it to a ext4 fs.
First, create a file of 1GB with 0
.
1 | dd if=/dev/zero of=x.img bs=1G count=1 |
Then, create an ext4 file system in this file with mke2fs
. This command may require running as root.
1 | # Method 1 |
Check the file system with dumpe2fs
. Also run as root. You will get the ext4 file system infomation such as superblocks or blocksize.
It is interesting that only dumpe2fs
is provided by Linux, and dumpfs
seems to be a tool for FreeBSD.
1 | sudo dumpe2fs x.img |
Check the content of the image file. Start from a small length like 16 Bytes, then enlarge it to find the first non-zero “line”. (See Also: xdd)
1 | hexdump -C -n 16 x.img # All zero |
Destroy the file system
Just do a little damage to the image file: set the bytes from 0x400
to 0x410
with all 0
. Remember to use conv=notrunc
to ensure that the data after 0x410
will not be dropped.
1 | dd if=/dev/zero of=x.img seek=$((0x400)) bs=16 count=1 conv=notrunc |
This will make the file system unable to be identified or mounted. It can be confirmed with dumpe2fs
.
Repair the file system
Use fsck
to check the file system within the image file, and act accoding to the prompt to repair it.
1 | sudo fsck.ext4 x.img |
Note that fsck only deals with file systems that are not mounted yet. So if you are tring to repair the root file system you are on now, reboot and use the initramfs, or take use of an LiveCD.
SP: Mount a file system
Just treat it like a disk/partition device:
1 | mkdir x.dir |
Infact, this will first make this image file a loop device in system, then mount it as a block device. You can use sudo blkid
to locate the device, it’s usally /dev/loopX
(X starts from 0).
If you want to create the device by yourself, use losetup
.
1 | # "-f" indicates finding a usable device number X to avoid name conflicts |
If you want to mount the file automatically, configure it in fstab. Remember to use loop
option.
1 | /path/to/x.img /path/to/x.dir ext4 loop 0 0 |
SP: Partition a fs image
As mentioned above, a file system image file can be seen as a block device, and it can also be partitioned.
1 | dd if=/dev/zero of=y.img bs=128M count=2 |
Now that this img is partitioned, we should also tell losetup
to detect its partition when turning it to loopback devices.
1 | sudo losetup -f -P y.img |