Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access the RAW disk using C/C++

I have a large storage device (flash memory) plugged onto my computer via the PCIe bus, I want to access such device directly, i.e., without any file system (e.g., NTFS or ext4) on it.

How can I do this using C/C++? (on both Windows 7 and Linux) I am wondering if I can 1) open the device just as a file, and then read and write binary data to it, or 2) allocate the whole device using some function like malloc, then each byte on the device have an address so that I can access them based on the addresses.

I prefer the second way if it possible, but I don't know if the OS supports this since it seems the address space needs to be shared with the main memory.

like image 968
Bloodmoon Avatar asked Dec 03 '22 18:12

Bloodmoon


2 Answers

According to Microsoft documentation:

On Windows you can open a physical drive using CreateFile using a path of the form

\\.\PhysicalDriveN

where N is the device number or a logical drive using a path of the form

\\.\X:

You will need to seek, read and write in multiples of the sector size which can be retrieved using DeviceIoControl() with IOCTL_DISK_GET_DRIVE_GEOMETRY.

like image 197
mclaassen Avatar answered Dec 25 '22 08:12

mclaassen


On Linux each storage device ends up getting a device entry in /dev. The first storage device is typically /dev/sda, the second storage device, if one is present, is /dev/sdb. Note that an optical disk is a storage device, so a CD-ROM or a DVD-ROM drive, if one is present, would get a device node entry.

Some Linux distributions may use a different naming convention, but this is what it usually is. So, you'll need to figure out which device corresponds to your flash disk, and just open the /dev/sdX device, and simply read and write from it. Your reads and writes must be for even block (sector) sizes, and seeking the opened file governs which disk blocks/sectors the subsequent read or write will affect.

Generally, /dev/sdX will be owned by root, but there are usually some Linux distribution-specific ways to fiddle the userid that owns a particular device node.

like image 22
Sam Varshavchik Avatar answered Dec 25 '22 06:12

Sam Varshavchik