Go to ...

Techpository

A Better Technical Repository

RSS Feed

Linux: Finding what hard drive sectors occupy a file


The physical geometry of modern hard drives is no longer directly accessible by the operating system. Early hard drives were simple enough that it was possible to address them according to their physical structure, cylinder-head-sector. Modern drives are much more complex and use systems like zone bit recording , in which not all tracks have the same amount of sectors. It’s no longer practical to address them according to their physical geometry.

from the fdisk man page:

If possible, fdisk will obtain the disk geometry automatically. This is not necessarily the physical disk geometry (indeed, modern disks do not really have anything like a physical geometry, certainly not something that can be described in simplistic Cylinders/Heads/Sectors form)

To get around this problem modern drives are addressed using Logical Block Addressing, which is what the operating system knows about. LBA is an addressing scheme where the entire disk is represented as a linear set of blocks, each block being a uniform amount of bytes (usually 512 or larger).

About Files

In order to understand where a “file” is located on a disk (at the LBA level) you will need to understand what a file is. This is going to be dependent on what file system you are using. In Unix style file systems there is a structure called an inode which describes a file. The inode stores all the attributes a file has and points to the LBA location of the actual data.

Ubuntu Example

Here’s an example of finding the LBA location of file data.

First get your file’s inode number

$ ls -i
659908 test.txt

Run the file system debugger. “yourPartition” will be something like sda1, it is the partition that your file system is located on.

$sudo debugfs /dev/yourPartition
debugfs: stat <659908>

Inode: 659908 Type: regular Mode: 0644 Flags: 0x80000
Generation: 3039230668 Version: 0x00000000:00000001


Size of extra inode fields: 28
EXTENTS:
(0): 266301

The number under “EXTENTS”, 266301, is the logical block in the file system that your file is located on. If your file is large there will be multiple blocks listed. There’s probably an easier way to get that number, I couldn’t find one.

To validate that we have the right block use dd to read that block off the disk. To find out your file system block size, use dumpe2fs.

dumpe2fs -h /dev/yourPartition | grep “Block size”

Then put your block size in the ibs= parameter, and the extent logical block in the skip= parameter, and run dd like this:

sudo dd if=/dev/yourPartition of=success.txt ibs=4096 count=1 skip=266301

success.txt should now contain the original file’s contents.

By: Chandler and Peter