Wednesday, November 17, 2021

Creating a GPT Partitioned image from Scratch in Linux

Some points for later understanding and usage

Protective MBR is for backward comparability.

Primary GPT size = 512 * 34 = 17408 bytes or 17Kb

Secondary GPT size = 512  * 33 = 16896 bytes

 

We will create a 100Mb disk(my.img) with three partitions P1 -> 30MB P2-> 30Mb and P2->Rest

=============Script Start===============

#!/bin/bash

truncate -s 100MiB my.img

parted my.img mklabel gpt /*Create a GPT Table*/
parted my.img mkpart primary ext4 2MiB 30MiB /*create Partition P1*/
parted my.img mkpart primary ext4 30MiB 60MiB /*create Partition P2*/
parted my.img mkpart primary ext4 60MiB 99MiB /*create Partition P3*/

/*Find the free loop device*/
(base) vijay@INDD611T72:~$ sudo losetup -f
[sudo] password for vijay:
/dev/loop2
 

sudo losetup -P /devloop2p1 my.img
sudo mkfs.ext4 /dev/loop2p1
sudo mkdir -p /mnt/P1
sudo mkdir -p /mnt/P2
sudo mkdir -p /mnt/P3
sudo mount /dev/loop2p1 /mnt/P1
sudo mount /dev/loop2p2 /mnt/P2
sudo mount /dev/loop2p3 /mnt/P3

#Copy the required files to the respective partitions

sudo sync
sudo umount /mnt/P1
sudo umount /mnt/P2
sudo umount /mnt/P3
sudo rm -rf /mnt/P1
sudo rm -rf /mnt/P2
sudo rm -rf /mnt/P3
sudo losetup -d /dev/loop2

=============Script End=============== 

Extracting GPT table:

We can extract the GPT table out from the image using following dd commands.

dd if=./my.img of=./gpt-prim.bin skip=0 bs=512 count=34   

 /** primary (34 * 512) bytes**/

 

dd if=./my.img of=./gpt-bkup.bin skip=204767 bs=512 count=33 

/**  100mb -(512*33) = (204767*512) **/

Steps done in PC for reference:

 

 

 

 

 Copy the contents after mounting each partitions individually.

Ref: https://unix.stackexchange.com/questions/87183/how-to-create-a-formatted-partition-image-file-from-scratch

No comments:

Post a Comment

Simple dlopen-example

        A simple sample for checking whether a .so in Linux both dynamically linked & dynamically loaded-linked in a process will share ...