1 # Copyright 2012 GRNET S.A. All rights reserved.
3 # Redistribution and use in source and binary forms, with or
4 # without modification, are permitted provided that the following
7 # 1. Redistributions of source code must retain the above
8 # copyright notice, this list of conditions and the following
11 # 2. Redistributions in binary form must reproduce the above
12 # copyright notice, this list of conditions and the following
13 # disclaimer in the documentation and/or other materials
14 # provided with the distribution.
16 # THIS SOFTWARE IS PROVIDED BY GRNET S.A. ``AS IS'' AND ANY EXPRESS
17 # OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
18 # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
19 # PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GRNET S.A OR
20 # CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
21 # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
22 # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
23 # USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
24 # AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25 # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
26 # ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
27 # POSSIBILITY OF SUCH DAMAGE.
29 # The views and conclusions contained in the software and
30 # documentation are those of the authors and should not be
31 # interpreted as representing official policies, either expressed
32 # or implied, of GRNET S.A.
43 """Represents a Master Boot Record."""
44 class Partition(object):
47 def __init__(self, raw_part):
55 ) = struct.unpack(self.format, raw_part)
58 return struct.pack(self.format,
68 """Returns the size of an MBR partition entry"""
69 return struct.calcsize(MBR.Partition.format)
72 start = self.unpack_chs(self.start)
73 end = self.unpack_chs(self.end)
74 return "%d %s %d %s %d %d" % (self.status, start, self.type, end,
75 self.first_sector, self.sector_count)
77 def unpack_chs(self, chs):
78 """Unpacks a CHS address string to a tuple."""
82 head = struct.unpack('<B', chs[0])[0]
83 sector = struct.unpack('<B', chs[1])[0] & 0x3f
84 cylinder = (struct.unpack('<B', chs[1])[0] & 0xC0) << 2 | \
85 struct.unpack('<B', chs[2])[0]
87 return (cylinder, head, sector)
89 def pack_chs(self, cylinder, head, sector):
90 """Packs a CHS tuple to an address string."""
92 assert 1 <= sector <= 63
93 assert 0 <= cylinder <= 1023
94 assert 0 <= head <= 255
97 byte1 = (cylinder >> 2) & 0xC0 | sector
98 byte2 = cylinder & 0xff
100 return struct.pack('<BBB', byte0, byte1, byte2)
102 format = "<444s2x16s16s16s16s2s"
104 Offset Length Contents
105 0 440(max. 446) code area
106 440 2(optional) disk signature
114 def __init__(self, block):
121 self.signature) = struct.unpack(self.format, block)
125 self.part[i] = self.Partition(raw_part[i])
129 """Returns the size of a Master Boot Record."""
130 return struct.calcsize(MBR.format)
133 """Packs an MBR to a binary string."""
134 return struct.pack(self.format,
145 ret += "Partition %d: %s\n" % (i, self.part[i])
146 ret += "Signature: %s %s\n" % (hex(ord(self.signature[0])),
147 hex(ord(self.signature[1])))
151 class GPTPartitionTable(object):
152 """Represents a GUID Partition Table."""
153 class GPTHeader(object):
154 """Represents a GPT Header of a GUID Partition Table."""
155 format = "<8s4sII4xQQQQ16sQIII"
157 Offset Length Contents
160 12 4 bytes Header size in little endian
161 16 4 bytes CRC32 of header
162 20 4 bytes Reserved; must be zero
163 24 8 bytes Current LBA
164 32 8 bytes Backup LBA
165 40 8 bytes First usable LBA for partitions
166 48 8 bytes Last usable LBA
167 56 16 bytes Disk GUID
168 72 8 bytes Partition entries starting LBA
169 80 4 bytes Number of partition entries
170 84 4 bytes Size of a partition entry
171 88 4 bytes CRC32 of partition array
172 92 * Reserved; must be zeroes
176 def __init__(self, block):
183 self.first_usable_lba,
184 self.last_usable_lba,
186 self.part_entry_start,
188 self.part_entry_size,
189 self.part_crc32) = struct.unpack(self.format, block)
192 """Packs a GPT Header to a binary string."""
193 return struct.pack(self.format,
200 self.first_usable_lba,
201 self.last_usable_lba,
203 self.part_entry_start,
205 self.part_entry_size,
210 """Returns the size of a GPT Header."""
211 return struct.calcsize(GPTPartitionTable.GPTHeader.format)
214 return "Signature: %s\n" % self.signature + \
215 "Revision: %r\n" % self.revision + \
216 "Header Size: %d\n" % self.hdr_size + \
217 "CRC32: %d\n" % self.header_crc32 + \
218 "Current LBA: %d\n" % self.current_lba + \
219 "Backup LBA: %d\n" % self.backup_lba + \
220 "First Usable LBA: %d\n" % self.first_usable_lba + \
221 "Last Usable LBA: %d\n" % self.last_usable_lba + \
222 "Disk GUID: %s\n" % uuid.UUID(bytes=self.uuid) + \
223 "Partition entries starting LBA: %d\n" % \
224 self.part_entry_start + \
225 "Number of Partition entries: %d\n" % self.part_count + \
226 "Size of a partition entry: %d\n" % self.part_entry_size + \
227 "CRC32 of partition array: %s\n" % self.part_crc32
229 def __init__(self, disk):
231 with open(disk, "rb") as d:
232 # MBR (Logical block address 0)
233 lba0 = d.read(BLOCKSIZE)
236 # Primary GPT Header (LBA 1)
237 raw_header = d.read(self.GPTHeader.size())
238 self.primary = self.GPTHeader(raw_header)
240 # Partition entries (LBA 2...34)
241 d.seek(self.primary.part_entry_start * BLOCKSIZE)
242 entries_size = self.primary.part_count * \
243 self.primary.part_entry_size
244 self.part_entries = d.read(entries_size)
246 # Secondary GPT Header (LBA -1)
247 d.seek(self.primary.backup_lba * BLOCKSIZE)
248 raw_header = d.read(self.GPTHeader.size())
249 self.secondary = self.GPTHeader(raw_header)
252 """Returns the payload size of GPT partitioned device."""
253 return (self.primary.backup_lba + 1) * BLOCKSIZE
255 def shrink(self, size, old_size):
256 """Move the secondary GPT Header entries to the address specified by
260 # Most partition manipulation programs leave 2048 sector after the last
262 aligned = size + 2048 * BLOCKSIZE
264 # new_size is at least: size + Partition Entries + Secondary GPT Header
265 new_size = aligned if aligned <= old_size else \
266 size + len(self.part_entries) + BLOCKSIZE
268 assert new_size <= old_size, "The secodary GPT fits in the device"
270 if new_size == self.size():
273 lba_count = new_size // BLOCKSIZE
276 #TODO: Check if the partition tables is hybrid
277 self.mbr.part[0].sector_count = (new_size // BLOCKSIZE) - 1
280 self.primary.header_crc32 = 0
281 self.primary.backup_lba = lba_count - 1 # LBA-1
282 self.primary.last_usable_lba = lba_count - 34 # LBA-34
283 self.primary.header_crc32 = \
284 binascii.crc32(self.primary.pack()) & 0xffffffff
286 # Fix Secondary header
287 self.secondary.header_crc32 = 0
288 self.secondary.current_lba = self.primary.backup_lba
289 self.secondary.last_usable_lba = lba_count - 34 # LBA-34
290 self.secondary.part_entry_start = lba_count - 33 # LBA-33
291 self.secondary.header_crc32 = \
292 binascii.crc32(self.secondary.pack()) & 0xffffffff
294 # Copy the new partition table back to the device
295 with open(self.disk, "wb") as d:
296 d.write(self.mbr.pack())
297 d.write(self.primary.pack())
298 d.write('\x00' * (BLOCKSIZE - self.primary.size()))
299 d.seek(self.secondary.part_entry_start * BLOCKSIZE)
300 d.write(self.part_entries)
301 d.seek(self.primary.backup_lba * BLOCKSIZE)
302 d.write(self.secondary.pack())
303 d.write('\x00' * (BLOCKSIZE - self.secondary.size()))
307 if __name__ == '__main__':
308 ptable = GPTPartitionTable(sys.argv[1])
310 print "MBR:\n%s" % ptable.mbr
311 print "Primary partition table:\n%s" % ptable.primary
312 print "Secondary partition table:\n%s" % ptable.secondary
314 # vim: set sta sts=4 shiftwidth=4 sw=4 et ai :