blob: f0cb23336fd944ee6d88730bd9f746615f753a40 [file] [log] [blame]
You-Cheng Syud5692942018-01-04 14:40:59 +08001#!/usr/bin/env python
Hung-Te Linc772e1a2017-04-14 16:50:50 +08002# Copyright 2017 The Chromium OS Authors. All rights reserved.
3# Use of this source code is governed by a BSD-style license that can be
4# found in the LICENSE file.
5
6"""An utility to manipulate GPT on a disk image.
7
8Chromium OS factory software usually needs to access partitions from disk
9images. However, there is no good, lightweight, and portable GPT utility.
10Most Chromium OS systems use `cgpt`, but that's not by default installed on
11Ubuntu. Most systems have parted (GNU) or partx (util-linux-ng) but they have
12their own problems.
13
14For example, when a disk image is resized (usually enlarged for putting more
15resources on stateful partition), GPT table must be updated. However,
16 - `parted` can't repair partition without interactive console in exception
17 handler.
18 - `partx` cannot fix headers nor make changes to partition table.
19 - `cgpt repair` does not fix `LastUsableLBA` so we cannot enlarge partition.
20 - `gdisk` is not installed on most systems.
21
22As a result, we need a dedicated tool to help processing GPT.
23
24This pygpt.py provides a simple and customized implementation for processing
25GPT, as a replacement for `cgpt`.
26"""
27
28
29from __future__ import print_function
30
31import argparse
32import binascii
Hung-Te Linc772e1a2017-04-14 16:50:50 +080033import logging
34import os
Hung-Te Lin446eb512018-05-02 18:39:16 +080035import stat
Hung-Te Linc772e1a2017-04-14 16:50:50 +080036import struct
Hung-Te Linf641d302018-04-18 15:09:35 +080037import subprocess
38import sys
Hung-Te Linc772e1a2017-04-14 16:50:50 +080039import uuid
40
41
Hung-Te Lin86ca4bb2018-04-25 10:22:10 +080042class StructError(Exception):
43 """Exceptions in packing and unpacking from/to struct fields."""
44 pass
Hung-Te Linc772e1a2017-04-14 16:50:50 +080045
Hung-Te Linc772e1a2017-04-14 16:50:50 +080046
Hung-Te Lin86ca4bb2018-04-25 10:22:10 +080047class StructField(object):
48 """Definition of a field in struct.
49
50 Attributes:
51 fmt: a format string for struct.{pack,unpack} to use.
52 name: a string for name of processed field.
53 """
54 __slots__ = ['fmt', 'name']
55
56 def __init__(self, fmt, name):
57 self.fmt = fmt
58 self.name = name
59
60 def Pack(self, value):
61 """"Packs given value from given format."""
62 del self # Unused.
63 return value
64
65 def Unpack(self, value):
66 """Unpacks given value into given format."""
67 del self # Unused.
68 return value
69
70
71class UTF16StructField(StructField):
72 """A field in UTF encoded string."""
73 __slots__ = ['encoding', 'max_length']
74 encoding = 'utf-16-le'
75
76 def __init__(self, max_length, name):
77 self.max_length = max_length
78 fmt = '%ds' % max_length
79 super(UTF16StructField, self).__init__(fmt, name)
80
81 def Pack(self, value):
82 new_value = value.encode(self.encoding)
83 if len(new_value) >= self.max_length:
84 raise StructError('Value "%s" cannot be packed into field %s (len=%s)' %
85 (value, self.name, self.max_length))
86 return new_value
87
88 def Unpack(self, value):
89 return value.decode(self.encoding).strip('\x00')
Hung-Te Linc772e1a2017-04-14 16:50:50 +080090
Hung-Te Linbf8aa272018-04-19 03:02:29 +080091
92class GUID(uuid.UUID):
93 """A special UUID that defaults to upper case in str()."""
94
95 def __str__(self):
96 """Returns GUID in upper case."""
97 return super(GUID, self).__str__().upper()
98
99 @staticmethod
100 def Random():
101 return uuid.uuid4()
102
103
Hung-Te Lin86ca4bb2018-04-25 10:22:10 +0800104class GUIDStructField(StructField):
105 """A GUID field."""
106
107 def __init__(self, name):
108 super(GUIDStructField, self).__init__('16s', name)
109
110 def Pack(self, value):
111 if value is None:
112 return '\x00' * 16
113 if not isinstance(value, uuid.UUID):
114 raise StructError('Field %s needs a GUID value instead of [%r].' %
115 (self.name, value))
116 return value.bytes_le
117
118 def Unpack(self, value):
119 return GUID(bytes_le=value)
120
121
Hung-Te Lin49ac3c22018-04-17 14:37:54 +0800122def BitProperty(getter, setter, shift, mask):
123 """A generator for bit-field properties.
124
125 This is used inside a class to manipulate an integer-like variable using
126 properties. The getter and setter should be member functions to change the
127 underlying member data.
Hung-Te Linc772e1a2017-04-14 16:50:50 +0800128
129 Args:
Hung-Te Lin49ac3c22018-04-17 14:37:54 +0800130 getter: a function to read integer type variable (for all the bits).
131 setter: a function to set the new changed integer type variable.
132 shift: integer for how many bits should be shifted (right).
133 mask: integer for the mask to filter out bit field.
Hung-Te Linc772e1a2017-04-14 16:50:50 +0800134 """
Hung-Te Lin49ac3c22018-04-17 14:37:54 +0800135 def _getter(self):
136 return (getter(self) >> shift) & mask
137 def _setter(self, value):
138 assert value & mask == value, (
139 'Value %s out of range (mask=%s)' % (value, mask))
140 setter(self, getter(self) & ~(mask << shift) | value << shift)
141 return property(_getter, _setter)
142
143
Hung-Te Lin86ca4bb2018-04-25 10:22:10 +0800144class PartitionAttributes(object):
145 """Wrapper for Partition.Attributes.
Hung-Te Lin49ac3c22018-04-17 14:37:54 +0800146
Hung-Te Lin86ca4bb2018-04-25 10:22:10 +0800147 This can be created using Partition.attrs, but the changed properties won't
148 apply to underlying Partition until an explicit call with
149 Partition.Update(Attributes=new_attrs).
Hung-Te Lin49ac3c22018-04-17 14:37:54 +0800150 """
151
Hung-Te Lin86ca4bb2018-04-25 10:22:10 +0800152 def __init__(self, attrs):
153 self._attrs = attrs
Hung-Te Lin49ac3c22018-04-17 14:37:54 +0800154
155 @property
Hung-Te Lin86ca4bb2018-04-25 10:22:10 +0800156 def raw(self):
157 """Returns the raw integer type attributes."""
158 return self._Get()
159
160 def _Get(self):
161 return self._attrs
162
163 def _Set(self, value):
164 self._attrs = value
165
166 successful = BitProperty(_Get, _Set, 56, 1)
167 tries = BitProperty(_Get, _Set, 52, 0xf)
168 priority = BitProperty(_Get, _Set, 48, 0xf)
169 legacy_boot = BitProperty(_Get, _Set, 2, 1)
170 required = BitProperty(_Get, _Set, 0, 1)
171 raw_16 = BitProperty(_Get, _Set, 48, 0xffff)
172
173
174class PartitionAttributeStructField(StructField):
175
176 def Pack(self, value):
177 if not isinstance(value, PartitionAttributes):
178 raise StructError('Given value %r is not %s.' %
179 (value, PartitionAttributes.__name__))
180 return value.raw
181
182 def Unpack(self, value):
183 return PartitionAttributes(value)
184
185
186# The binascii.crc32 returns signed integer, so CRC32 in in struct must be
187# declared as 'signed' (l) instead of 'unsigned' (L).
188# http://en.wikipedia.org/wiki/GUID_Partition_Table#Partition_table_header_.28LBA_1.29
189HEADER_FIELDS = [
190 StructField('8s', 'Signature'),
191 StructField('4s', 'Revision'),
192 StructField('L', 'HeaderSize'),
193 StructField('l', 'CRC32'),
194 StructField('4s', 'Reserved'),
195 StructField('Q', 'CurrentLBA'),
196 StructField('Q', 'BackupLBA'),
197 StructField('Q', 'FirstUsableLBA'),
198 StructField('Q', 'LastUsableLBA'),
199 GUIDStructField('DiskGUID'),
200 StructField('Q', 'PartitionEntriesStartingLBA'),
201 StructField('L', 'PartitionEntriesNumber'),
202 StructField('L', 'PartitionEntrySize'),
203 StructField('l', 'PartitionArrayCRC32'),
204]
205
206# http://en.wikipedia.org/wiki/GUID_Partition_Table#Partition_entries
207PARTITION_FIELDS = [
208 GUIDStructField('TypeGUID'),
209 GUIDStructField('UniqueGUID'),
210 StructField('Q', 'FirstLBA'),
211 StructField('Q', 'LastLBA'),
212 PartitionAttributeStructField('Q', 'Attributes'),
213 UTF16StructField(72, 'Names'),
214]
215
216# The PMBR has so many variants. The basic format is defined in
217# https://en.wikipedia.org/wiki/Master_boot_record#Sector_layout, and our
218# implementation, as derived from `cgpt`, is following syslinux as:
219# https://chromium.googlesource.com/chromiumos/platform/vboot_reference/+/master/cgpt/cgpt.h#32
220PMBR_FIELDS = [
221 StructField('424s', 'BootCode'),
222 GUIDStructField('BootGUID'),
223 StructField('L', 'DiskID'),
224 StructField('2s', 'Magic'),
225 StructField('16s', 'LegacyPart0'),
226 StructField('16s', 'LegacyPart1'),
227 StructField('16s', 'LegacyPart2'),
228 StructField('16s', 'LegacyPart3'),
229 StructField('2s', 'Signature'),
230]
Hung-Te Linc772e1a2017-04-14 16:50:50 +0800231
232
Hung-Te Lin4dfd3302018-04-17 14:47:52 +0800233class GPTError(Exception):
234 """All exceptions by GPT."""
235 pass
236
237
Hung-Te Lin86ca4bb2018-04-25 10:22:10 +0800238class GPTObject(object):
239 """A base object in GUID Partition Table.
240
241 All objects (for instance, header or partition entries) must inherit this
242 class and define the FIELD attribute with a list of field definitions using
243 StructField.
244
245 The 'name' in StructField will become the attribute name of GPT objects that
246 can be directly packed into / unpacked from. Derived (calculated from existing
247 attributes) attributes should be in lower_case.
248
249 It is also possible to attach some additional properties to the object as meta
250 data (for example path of the underlying image file). To do that, first
251 include it in __slots__ list and specify them as dictionary-type args in
252 constructors. These properties will be preserved when you call Clone().
253
254 To create a new object, call the constructor. Field data can be assigned as
255 in arguments, or give nothing to initialize as zero (see Zero()). Field data
256 and meta values can be also specified in keyword arguments (**kargs) at the
257 same time.
258
259 To read a object from file or stream, use class method ReadFrom(source).
260 To make changes, modify the field directly or use Update(dict), or create a
261 copy by Clone() first then Update.
262
263 To wipe all fields (but not meta), call Zero(). There is currently no way
264 to clear meta except setting them to None one by one.
265 """
266 __slots__ = []
267
268 FIELDS = None
269 """A list of StructField definitions."""
270
271 def __init__(self, *args, **kargs):
272 if args:
273 if len(args) != len(self.FIELDS):
274 raise GPTError('%s need %s arguments (found %s).' %
275 (type(self).__name__, len(self.FIELDS), len(args)))
276 for f, value in zip(self.FIELDS, args):
277 setattr(self, f.name, value)
278 else:
279 self.Zero()
280
281 all_names = [f for f in self.__slots__]
282 for name, value in kargs.iteritems():
283 if name not in all_names:
284 raise GPTError('%s does not support keyword arg <%s>.' %
285 (type(self).__name__, name))
286 setattr(self, name, value)
287
288 def __iter__(self):
289 """An iterator to return all fields associated in the object."""
290 return (getattr(self, f.name) for f in self.FIELDS)
291
292 def __repr__(self):
293 return '(%s: %s)' % (type(self).__name__, ', '.join(
294 '%s=%r' %(f, getattr(self, f)) for f in self.__slots__))
295
296 @classmethod
297 def GetStructFormat(cls):
298 """Returns a format string for struct to use."""
299 return '<' + ''.join(f.fmt for f in cls.FIELDS)
300
301 @classmethod
302 def ReadFrom(cls, source, **kargs):
303 """Returns an object from given source."""
304 obj = cls(**kargs)
305 obj.Unpack(source)
306 return obj
307
308 @property
309 def blob(self):
310 """The (packed) blob representation of the object."""
311 return self.Pack()
312
313 @property
314 def meta(self):
315 """Meta values (those not in GPT object fields)."""
316 metas = set(self.__slots__) - set([f.name for f in self.FIELDS])
317 return dict((name, getattr(self, name)) for name in metas)
318
319 def Unpack(self, source):
320 """Unpacks values from a given source.
321
322 Args:
323 source: a string of bytes or a file-like object to read from.
324 """
325 fmt = self.GetStructFormat()
326 if source is None:
327 source = '\x00' * struct.calcsize(fmt)
328 if not isinstance(source, basestring):
329 return self.Unpack(source.read(struct.calcsize(fmt)))
330 for f, value in zip(self.FIELDS, struct.unpack(fmt, source)):
331 setattr(self, f.name, f.Unpack(value))
332
333 def Pack(self):
334 """Packs values in all fields into a string by struct format."""
335 return struct.pack(self.GetStructFormat(),
336 *(f.Pack(getattr(self, f.name)) for f in self.FIELDS))
337
338 def Clone(self):
339 """Clones a new instance."""
340 return type(self)(*self, **self.meta)
341
342 def Update(self, **dargs):
343 """Applies multiple values in current object."""
344 for name, value in dargs.iteritems():
345 setattr(self, name, value)
346
347 def Zero(self):
348 """Set all fields to values representing zero or empty.
349
350 Note the meta attributes won't be cleared.
351 """
352 class ZeroReader(object):
353 """A /dev/zero like stream."""
354
355 @staticmethod
356 def read(num):
357 return '\x00' * num
358
359 self.Unpack(ZeroReader())
360
361
Hung-Te Linc772e1a2017-04-14 16:50:50 +0800362class GPT(object):
363 """A GPT helper class.
364
365 To load GPT from an existing disk image file, use `LoadFromFile`.
366 After modifications were made, use `WriteToFile` to commit changes.
367
368 Attributes:
Hung-Te Lin49ac3c22018-04-17 14:37:54 +0800369 header: a namedtuple of GPT header.
Hung-Te Linc6e009c2018-04-17 15:06:16 +0800370 pmbr: a namedtuple of Protective MBR.
Hung-Te Lin49ac3c22018-04-17 14:37:54 +0800371 partitions: a list of GPT partition entry nametuple.
372 block_size: integer for size of bytes in one block (sector).
Hung-Te Linc34d89c2018-04-17 15:11:34 +0800373 is_secondary: boolean to indicate if the header is from primary or backup.
Hung-Te Linc772e1a2017-04-14 16:50:50 +0800374 """
Hung-Te Linf148d322018-04-13 10:24:42 +0800375 DEFAULT_BLOCK_SIZE = 512
Hung-Te Linc772e1a2017-04-14 16:50:50 +0800376 TYPE_GUID_MAP = {
Hung-Te Linbf8aa272018-04-19 03:02:29 +0800377 GUID('00000000-0000-0000-0000-000000000000'): 'Unused',
378 GUID('EBD0A0A2-B9E5-4433-87C0-68B6B72699C7'): 'Linux data',
379 GUID('FE3A2A5D-4F32-41A7-B725-ACCC3285A309'): 'ChromeOS kernel',
380 GUID('3CB8E202-3B7E-47DD-8A3C-7FF2A13CFCEC'): 'ChromeOS rootfs',
381 GUID('2E0A753D-9E48-43B0-8337-B15192CB1B5E'): 'ChromeOS reserved',
382 GUID('CAB6E88E-ABF3-4102-A07A-D4BB9BE3C1D3'): 'ChromeOS firmware',
383 GUID('C12A7328-F81F-11D2-BA4B-00A0C93EC93B'): 'EFI System Partition',
Hung-Te Linc772e1a2017-04-14 16:50:50 +0800384 }
Hung-Te Linbf8aa272018-04-19 03:02:29 +0800385 TYPE_GUID_FROM_NAME = dict(
Hung-Te Linfcd1a8d2018-04-17 15:15:01 +0800386 ('efi' if v.startswith('EFI') else v.lower().split()[-1], k)
387 for k, v in TYPE_GUID_MAP.iteritems())
Hung-Te Linbf8aa272018-04-19 03:02:29 +0800388 TYPE_GUID_UNUSED = TYPE_GUID_FROM_NAME['unused']
389 TYPE_GUID_CHROMEOS_KERNEL = TYPE_GUID_FROM_NAME['kernel']
390 TYPE_GUID_LIST_BOOTABLE = [
391 TYPE_GUID_CHROMEOS_KERNEL,
392 TYPE_GUID_FROM_NAME['efi'],
Hung-Te Linc772e1a2017-04-14 16:50:50 +0800393 ]
394
Hung-Te Linc6e009c2018-04-17 15:06:16 +0800395 class ProtectiveMBR(GPTObject):
396 """Protective MBR (PMBR) in GPT."""
Hung-Te Lin86ca4bb2018-04-25 10:22:10 +0800397 FIELDS = PMBR_FIELDS
398 __slots__ = [f.name for f in FIELDS]
399
Hung-Te Linc6e009c2018-04-17 15:06:16 +0800400 SIGNATURE = '\x55\xAA'
401 MAGIC = '\x1d\x9a'
402
Hung-Te Lin49ac3c22018-04-17 14:37:54 +0800403 class Header(GPTObject):
404 """Wrapper to Header in GPT."""
Hung-Te Lin86ca4bb2018-04-25 10:22:10 +0800405 FIELDS = HEADER_FIELDS
406 __slots__ = [f.name for f in FIELDS]
407
Hung-Te Lin49ac3c22018-04-17 14:37:54 +0800408 SIGNATURES = ['EFI PART', 'CHROMEOS']
409 SIGNATURE_IGNORE = 'IGNOREME'
410 DEFAULT_REVISION = '\x00\x00\x01\x00'
411
412 DEFAULT_PARTITION_ENTRIES = 128
413 DEFAULT_PARTITIONS_LBA = 2 # LBA 0 = MBR, LBA 1 = GPT Header.
414
Hung-Te Lin6c3575a2018-04-17 15:00:49 +0800415 @classmethod
416 def Create(cls, size, block_size, pad_blocks=0,
417 part_entries=DEFAULT_PARTITION_ENTRIES):
418 """Creates a header with default values.
419
420 Args:
421 size: integer of expected image size.
422 block_size: integer for size of each block (sector).
423 pad_blocks: number of preserved sectors between header and partitions.
424 part_entries: number of partitions to include in header.
425 """
Hung-Te Lin86ca4bb2018-04-25 10:22:10 +0800426 PART_FORMAT = GPT.Partition.GetStructFormat()
427 FORMAT = cls.GetStructFormat()
428 part_entry_size = struct.calcsize(PART_FORMAT)
Hung-Te Lin6c3575a2018-04-17 15:00:49 +0800429 parts_lba = cls.DEFAULT_PARTITIONS_LBA + pad_blocks
430 parts_bytes = part_entries * part_entry_size
431 parts_blocks = parts_bytes / block_size
432 if parts_bytes % block_size:
433 parts_blocks += 1
Hung-Te Lin86ca4bb2018-04-25 10:22:10 +0800434 # CRC32 and PartitionsCRC32 must be updated later explicitly.
435 return cls(
Hung-Te Lin6c3575a2018-04-17 15:00:49 +0800436 Signature=cls.SIGNATURES[0],
437 Revision=cls.DEFAULT_REVISION,
Hung-Te Lin86ca4bb2018-04-25 10:22:10 +0800438 HeaderSize=struct.calcsize(FORMAT),
Hung-Te Lin6c3575a2018-04-17 15:00:49 +0800439 CurrentLBA=1,
440 BackupLBA=size / block_size - 1,
441 FirstUsableLBA=parts_lba + parts_blocks,
442 LastUsableLBA=size / block_size - parts_blocks - parts_lba,
Hung-Te Lin86ca4bb2018-04-25 10:22:10 +0800443 DiskGUID=GUID.Random(),
Hung-Te Lin6c3575a2018-04-17 15:00:49 +0800444 PartitionEntriesStartingLBA=parts_lba,
445 PartitionEntriesNumber=part_entries,
Hung-Te Lin86ca4bb2018-04-25 10:22:10 +0800446 PartitionEntrySize=part_entry_size)
Hung-Te Lin6c3575a2018-04-17 15:00:49 +0800447
Hung-Te Lin86ca4bb2018-04-25 10:22:10 +0800448 def UpdateChecksum(self):
449 """Updates the CRC32 field in GPT header.
Hung-Te Lin49ac3c22018-04-17 14:37:54 +0800450
Hung-Te Lin86ca4bb2018-04-25 10:22:10 +0800451 Note the PartitionArrayCRC32 is not touched - you have to make sure that
452 is correct before calling Header.UpdateChecksum().
453 """
454 self.Update(CRC32=0)
455 self.Update(CRC32=binascii.crc32(self.blob))
Hung-Te Lin49ac3c22018-04-17 14:37:54 +0800456
Hung-Te Lin49ac3c22018-04-17 14:37:54 +0800457 class Partition(GPTObject):
458 """The partition entry in GPT.
459
460 Please include following properties when creating a Partition object:
461 - image: a string for path to the image file the partition maps to.
462 - number: the 1-based partition number.
463 - block_size: an integer for size of each block (LBA, or sector).
464 """
Hung-Te Lin86ca4bb2018-04-25 10:22:10 +0800465 FIELDS = PARTITION_FIELDS
466 __slots__ = [f.name for f in FIELDS] + ['image', 'number', 'block_size']
Hung-Te Lin49ac3c22018-04-17 14:37:54 +0800467 NAMES_ENCODING = 'utf-16-le'
468 NAMES_LENGTH = 72
469
Hung-Te Lin49ac3c22018-04-17 14:37:54 +0800470 def __str__(self):
471 return '%s#%s' % (self.image, self.number)
472
473 def IsUnused(self):
474 """Returns if the partition is unused and can be allocated."""
Hung-Te Lin86ca4bb2018-04-25 10:22:10 +0800475 return self.TypeGUID == GPT.TYPE_GUID_UNUSED
Hung-Te Lin49ac3c22018-04-17 14:37:54 +0800476
Hung-Te Linfe724f82018-04-18 15:03:58 +0800477 def IsChromeOSKernel(self):
478 """Returns if the partition is a Chrome OS kernel partition."""
Hung-Te Lin048ac5e2018-05-03 23:47:45 +0800479 return self.TypeGUID == GPT.TYPE_GUID_CHROMEOS_KERNEL
Hung-Te Linfe724f82018-04-18 15:03:58 +0800480
Hung-Te Lin49ac3c22018-04-17 14:37:54 +0800481 @property
482 def blocks(self):
483 """Return size of partition in blocks (see block_size)."""
484 return self.LastLBA - self.FirstLBA + 1
485
486 @property
487 def offset(self):
488 """Returns offset to partition in bytes."""
489 return self.FirstLBA * self.block_size
490
491 @property
492 def size(self):
493 """Returns size of partition in bytes."""
494 return self.blocks * self.block_size
495
Hung-Te Linc772e1a2017-04-14 16:50:50 +0800496 def __init__(self):
Hung-Te Lin49ac3c22018-04-17 14:37:54 +0800497 """GPT constructor.
498
499 See LoadFromFile for how it's usually used.
500 """
Hung-Te Linc6e009c2018-04-17 15:06:16 +0800501 self.pmbr = None
Hung-Te Linc772e1a2017-04-14 16:50:50 +0800502 self.header = None
503 self.partitions = None
Hung-Te Linf148d322018-04-13 10:24:42 +0800504 self.block_size = self.DEFAULT_BLOCK_SIZE
Hung-Te Linc34d89c2018-04-17 15:11:34 +0800505 self.is_secondary = False
Hung-Te Linc772e1a2017-04-14 16:50:50 +0800506
Hung-Te Linc772e1a2017-04-14 16:50:50 +0800507 @classmethod
Hung-Te Linbf8aa272018-04-19 03:02:29 +0800508 def GetTypeGUID(cls, value):
509 """The value may be a GUID in string or a short type string."""
510 guid = cls.TYPE_GUID_FROM_NAME.get(value.lower())
511 return GUID(value) if guid is None else guid
Hung-Te Linf641d302018-04-18 15:09:35 +0800512
513 @classmethod
Hung-Te Lin6c3575a2018-04-17 15:00:49 +0800514 def Create(cls, image_name, size, block_size, pad_blocks=0):
515 """Creates a new GPT instance from given size and block_size.
516
517 Args:
518 image_name: a string of underlying disk image file name.
519 size: expected size of disk image.
520 block_size: size of each block (sector) in bytes.
521 pad_blocks: number of blocks between header and partitions array.
522 """
523 gpt = cls()
524 gpt.block_size = block_size
525 gpt.header = cls.Header.Create(size, block_size, pad_blocks)
526 gpt.partitions = [
Hung-Te Lin86ca4bb2018-04-25 10:22:10 +0800527 cls.Partition(block_size=block_size, image=image_name, number=i + 1)
Hung-Te Lin6c3575a2018-04-17 15:00:49 +0800528 for i in xrange(gpt.header.PartitionEntriesNumber)]
529 return gpt
530
Hung-Te Lin446eb512018-05-02 18:39:16 +0800531 @staticmethod
532 def IsBlockDevice(image):
533 """Returns if the image is a block device file."""
534 return stat.S_ISBLK(os.stat(image).st_mode)
535
536 @classmethod
537 def GetImageSize(cls, image):
538 """Returns the size of specified image (plain or block device file)."""
539 if not cls.IsBlockDevice(image):
540 return os.path.getsize(image)
541
542 fd = os.open(image, os.O_RDONLY)
543 try:
544 return os.lseek(fd, 0, os.SEEK_END)
545 finally:
546 os.close(fd)
547
548 @classmethod
549 def GetLogicalBlockSize(cls, block_dev):
550 """Returns the logical block (sector) size from a block device file.
551
552 The underlying call is BLKSSZGET. An alternative command is blockdev,
553 but that needs root permission even if we just want to get sector size.
554 """
555 assert cls.IsBlockDevice(block_dev), '%s must be block device.' % block_dev
556 return int(subprocess.check_output(
557 ['lsblk', '-d', '-n', '-r', '-o', 'log-sec', block_dev]).strip())
558
Hung-Te Lin6c3575a2018-04-17 15:00:49 +0800559 @classmethod
Hung-Te Lin6977ae12018-04-17 12:20:32 +0800560 def LoadFromFile(cls, image):
561 """Loads a GPT table from give disk image file object.
562
563 Args:
564 image: a string as file path or a file-like object to read from.
565 """
566 if isinstance(image, basestring):
567 with open(image, 'rb') as f:
568 return cls.LoadFromFile(f)
569
Hung-Te Lin49ac3c22018-04-17 14:37:54 +0800570 gpt = cls()
Hung-Te Linc6e009c2018-04-17 15:06:16 +0800571 image.seek(0)
572 pmbr = gpt.ProtectiveMBR.ReadFrom(image)
573 if pmbr.Signature == cls.ProtectiveMBR.SIGNATURE:
574 logging.debug('Found MBR signature in %s', image.name)
575 if pmbr.Magic == cls.ProtectiveMBR.MAGIC:
576 logging.debug('Found PMBR in %s', image.name)
577 gpt.pmbr = pmbr
578
Hung-Te Linf148d322018-04-13 10:24:42 +0800579 # Try DEFAULT_BLOCK_SIZE, then 4K.
Hung-Te Lin446eb512018-05-02 18:39:16 +0800580 block_sizes = [cls.DEFAULT_BLOCK_SIZE, 4096]
581 if cls.IsBlockDevice(image.name):
582 block_sizes = [cls.GetLogicalBlockSize(image.name)]
583
584 for block_size in block_sizes:
Hung-Te Linc34d89c2018-04-17 15:11:34 +0800585 # Note because there are devices setting Primary as ignored and the
586 # partition table signature accepts 'CHROMEOS' which is also used by
587 # Chrome OS kernel partition, we have to look for Secondary (backup) GPT
588 # first before trying other block sizes, otherwise we may incorrectly
589 # identify a kernel partition as LBA 1 of larger block size system.
590 for i, seek in enumerate([(block_size * 1, os.SEEK_SET),
591 (-block_size, os.SEEK_END)]):
592 image.seek(*seek)
593 header = gpt.Header.ReadFrom(image)
594 if header.Signature in cls.Header.SIGNATURES:
595 gpt.block_size = block_size
596 if i != 0:
597 gpt.is_secondary = True
598 break
Hung-Te Lin86ca4bb2018-04-25 10:22:10 +0800599 # TODO(hungte) Try harder to see if this block is valid.
Hung-Te Linc34d89c2018-04-17 15:11:34 +0800600 else:
601 # Nothing found, try next block size.
602 continue
603 # Found a valid signature.
604 break
Hung-Te Linf148d322018-04-13 10:24:42 +0800605 else:
Hung-Te Lin4dfd3302018-04-17 14:47:52 +0800606 raise GPTError('Invalid signature in GPT header.')
Hung-Te Linf148d322018-04-13 10:24:42 +0800607
Hung-Te Lin6977ae12018-04-17 12:20:32 +0800608 image.seek(gpt.block_size * header.PartitionEntriesStartingLBA)
Hung-Te Lin86ca4bb2018-04-25 10:22:10 +0800609 def ReadPartition(image, number):
Hung-Te Lin49ac3c22018-04-17 14:37:54 +0800610 p = gpt.Partition.ReadFrom(
Hung-Te Lin86ca4bb2018-04-25 10:22:10 +0800611 image, image=image.name, number=number, block_size=gpt.block_size)
Hung-Te Lin49ac3c22018-04-17 14:37:54 +0800612 return p
613
Hung-Te Linc772e1a2017-04-14 16:50:50 +0800614 gpt.header = header
Hung-Te Lin49ac3c22018-04-17 14:37:54 +0800615 gpt.partitions = [
Hung-Te Lin86ca4bb2018-04-25 10:22:10 +0800616 ReadPartition(image, i + 1)
617 for i in xrange(header.PartitionEntriesNumber)]
Hung-Te Linc772e1a2017-04-14 16:50:50 +0800618 return gpt
619
Hung-Te Linc5196682018-04-18 22:59:59 +0800620 def GetUsedPartitions(self):
621 """Returns a list of partitions with type GUID not set to unused.
Hung-Te Linc772e1a2017-04-14 16:50:50 +0800622
Hung-Te Linc5196682018-04-18 22:59:59 +0800623 Use 'number' property to find the real location of partition in
624 self.partitions.
Hung-Te Linc772e1a2017-04-14 16:50:50 +0800625 """
Hung-Te Linc5196682018-04-18 22:59:59 +0800626 return [p for p in self.partitions if not p.IsUnused()]
Hung-Te Linc772e1a2017-04-14 16:50:50 +0800627
628 def GetMaxUsedLBA(self):
Hung-Te Lind3a2e9a2018-04-19 13:07:26 +0800629 """Returns the max LastLBA from all used partitions."""
Hung-Te Linc5196682018-04-18 22:59:59 +0800630 parts = self.GetUsedPartitions()
Hung-Te Lind3a2e9a2018-04-19 13:07:26 +0800631 return (max(p.LastLBA for p in parts)
632 if parts else self.header.FirstUsableLBA - 1)
Hung-Te Linc772e1a2017-04-14 16:50:50 +0800633
634 def GetPartitionTableBlocks(self, header=None):
635 """Returns the blocks (or LBA) of partition table from given header."""
636 if header is None:
637 header = self.header
638 size = header.PartitionEntrySize * header.PartitionEntriesNumber
Hung-Te Linf148d322018-04-13 10:24:42 +0800639 blocks = size / self.block_size
640 if size % self.block_size:
Hung-Te Linc772e1a2017-04-14 16:50:50 +0800641 blocks += 1
642 return blocks
643
Hung-Te Lin5f0dea42018-04-18 23:20:11 +0800644 def GetPartition(self, number):
645 """Gets the Partition by given (1-based) partition number.
646
647 Args:
648 number: an integer as 1-based partition number.
649 """
650 if not 0 < number <= len(self.partitions):
651 raise GPTError('Invalid partition number %s.' % number)
652 return self.partitions[number - 1]
653
Hung-Te Lin86ca4bb2018-04-25 10:22:10 +0800654 def UpdatePartition(self, part, number):
Hung-Te Lin5f0dea42018-04-18 23:20:11 +0800655 """Updates the entry in partition table by given Partition object.
656
Hung-Te Lin86ca4bb2018-04-25 10:22:10 +0800657 Usually you only need to call this if you want to copy one partition to
658 different location (number of image).
659
Hung-Te Lin5f0dea42018-04-18 23:20:11 +0800660 Args:
661 part: a Partition GPT object.
Hung-Te Lin86ca4bb2018-04-25 10:22:10 +0800662 number: an integer as 1-based partition number.
Hung-Te Lin5f0dea42018-04-18 23:20:11 +0800663 """
Hung-Te Lin86ca4bb2018-04-25 10:22:10 +0800664 ref = self.partitions[number - 1]
665 part = part.Clone()
666 part.number = number
667 part.image = ref.image
668 part.block_size = ref.block_size
Hung-Te Lin5f0dea42018-04-18 23:20:11 +0800669 self.partitions[number - 1] = part
670
Hung-Te Linc772e1a2017-04-14 16:50:50 +0800671 def Resize(self, new_size):
672 """Adjust GPT for a disk image in given size.
673
674 Args:
675 new_size: Integer for new size of disk image file.
676 """
Hung-Te Linf148d322018-04-13 10:24:42 +0800677 old_size = self.block_size * (self.header.BackupLBA + 1)
678 if new_size % self.block_size:
Hung-Te Lin4dfd3302018-04-17 14:47:52 +0800679 raise GPTError(
680 'New file size %d is not valid for image files.' % new_size)
Hung-Te Linf148d322018-04-13 10:24:42 +0800681 new_blocks = new_size / self.block_size
Hung-Te Linc772e1a2017-04-14 16:50:50 +0800682 if old_size != new_size:
683 logging.warn('Image size (%d, LBA=%d) changed from %d (LBA=%d).',
Hung-Te Linf148d322018-04-13 10:24:42 +0800684 new_size, new_blocks, old_size, old_size / self.block_size)
Hung-Te Linc772e1a2017-04-14 16:50:50 +0800685 else:
686 logging.info('Image size (%d, LBA=%d) not changed.',
687 new_size, new_blocks)
Hung-Te Lind3a2e9a2018-04-19 13:07:26 +0800688 return
Hung-Te Linc772e1a2017-04-14 16:50:50 +0800689
Hung-Te Lind3a2e9a2018-04-19 13:07:26 +0800690 # Expected location
Hung-Te Linc772e1a2017-04-14 16:50:50 +0800691 backup_lba = new_blocks - 1
Hung-Te Lind3a2e9a2018-04-19 13:07:26 +0800692 last_usable_lba = backup_lba - self.header.FirstUsableLBA
Hung-Te Linc772e1a2017-04-14 16:50:50 +0800693
Hung-Te Lind3a2e9a2018-04-19 13:07:26 +0800694 if last_usable_lba < self.header.LastUsableLBA:
695 max_used_lba = self.GetMaxUsedLBA()
696 if last_usable_lba < max_used_lba:
Hung-Te Lin4dfd3302018-04-17 14:47:52 +0800697 raise GPTError('Backup partition tables will overlap used partitions')
Hung-Te Linc772e1a2017-04-14 16:50:50 +0800698
Hung-Te Lin86ca4bb2018-04-25 10:22:10 +0800699 self.header.Update(BackupLBA=backup_lba, LastUsableLBA=last_usable_lba)
Hung-Te Linc772e1a2017-04-14 16:50:50 +0800700
701 def GetFreeSpace(self):
702 """Returns the free (available) space left according to LastUsableLBA."""
703 max_lba = self.GetMaxUsedLBA()
704 assert max_lba <= self.header.LastUsableLBA, "Partitions too large."
Hung-Te Linf148d322018-04-13 10:24:42 +0800705 return self.block_size * (self.header.LastUsableLBA - max_lba)
Hung-Te Linc772e1a2017-04-14 16:50:50 +0800706
Hung-Te Lin5f0dea42018-04-18 23:20:11 +0800707 def ExpandPartition(self, number):
Hung-Te Linc772e1a2017-04-14 16:50:50 +0800708 """Expands a given partition to last usable LBA.
709
710 Args:
Hung-Te Lin5f0dea42018-04-18 23:20:11 +0800711 number: an integer to specify partition in 1-based number.
Hung-Te Lin5cb0c312018-04-17 14:56:43 +0800712
713 Returns:
714 (old_blocks, new_blocks) for size in blocks.
Hung-Te Linc772e1a2017-04-14 16:50:50 +0800715 """
716 # Assume no partitions overlap, we need to make sure partition[i] has
717 # largest LBA.
Hung-Te Lin5f0dea42018-04-18 23:20:11 +0800718 p = self.GetPartition(number)
719 if p.IsUnused():
720 raise GPTError('Partition %s is unused.' % p)
Hung-Te Linc772e1a2017-04-14 16:50:50 +0800721 max_used_lba = self.GetMaxUsedLBA()
Hung-Te Linc5196682018-04-18 22:59:59 +0800722 # TODO(hungte) We can do more by finding free space after i.
Hung-Te Linc772e1a2017-04-14 16:50:50 +0800723 if max_used_lba > p.LastLBA:
Hung-Te Lin4dfd3302018-04-17 14:47:52 +0800724 raise GPTError(
Hung-Te Linc5196682018-04-18 22:59:59 +0800725 'Cannot expand %s because it is not allocated at last.' % p)
Hung-Te Linc772e1a2017-04-14 16:50:50 +0800726
Hung-Te Lin49ac3c22018-04-17 14:37:54 +0800727 old_blocks = p.blocks
Hung-Te Lin86ca4bb2018-04-25 10:22:10 +0800728 p.Update(LastLBA=self.header.LastUsableLBA)
Hung-Te Lin49ac3c22018-04-17 14:37:54 +0800729 new_blocks = p.blocks
Hung-Te Lin5cb0c312018-04-17 14:56:43 +0800730 logging.warn(
731 '%s expanded, size in LBA: %d -> %d.', p, old_blocks, new_blocks)
732 return (old_blocks, new_blocks)
Hung-Te Linc772e1a2017-04-14 16:50:50 +0800733
Hung-Te Lin3b491672018-04-19 01:41:20 +0800734 def CheckIntegrity(self):
735 """Checks if the GPT objects all look good."""
736 # Check if the header allocation looks good. CurrentLBA and
737 # PartitionEntriesStartingLBA should be all outside [FirstUsableLBA,
738 # LastUsableLBA].
739 header = self.header
740 entries_first_lba = header.PartitionEntriesStartingLBA
741 entries_last_lba = entries_first_lba + self.GetPartitionTableBlocks() - 1
742
743 def CheckOutsideUsable(name, lba, outside_entries=False):
744 if lba < 1:
745 raise GPTError('%s should not live in LBA %s.' % (name, lba))
746 if lba > max(header.BackupLBA, header.CurrentLBA):
747 # Note this is "in theory" possible, but we want to report this as
748 # error as well, since it usually leads to error.
749 raise GPTError('%s (%s) should not be larger than BackupLBA (%s).' %
750 (name, lba, header.BackupLBA))
751 if header.FirstUsableLBA <= lba <= header.LastUsableLBA:
752 raise GPTError('%s (%s) should not be included in usable LBAs [%s,%s]' %
753 (name, lba, header.FirstUsableLBA, header.LastUsableLBA))
754 if outside_entries and entries_first_lba <= lba <= entries_last_lba:
755 raise GPTError('%s (%s) should be outside partition entries [%s,%s]' %
756 (name, lba, entries_first_lba, entries_last_lba))
757 CheckOutsideUsable('Header', header.CurrentLBA, True)
758 CheckOutsideUsable('Backup header', header.BackupLBA, True)
759 CheckOutsideUsable('Partition entries', entries_first_lba)
760 CheckOutsideUsable('Partition entries end', entries_last_lba)
761
762 parts = self.GetUsedPartitions()
763 # Check if partition entries overlap with each other.
764 lba_list = [(p.FirstLBA, p.LastLBA, p) for p in parts]
765 lba_list.sort(key=lambda t: t[0])
766 for i in xrange(len(lba_list) - 1):
767 if lba_list[i][1] >= lba_list[i + 1][0]:
768 raise GPTError('Overlap in partition entries: [%s,%s]%s, [%s,%s]%s.' %
769 (lba_list[i] + lba_list[i + 1]))
770 # Now, check the first and last partition.
771 if lba_list:
772 p = lba_list[0][2]
773 if p.FirstLBA < header.FirstUsableLBA:
774 raise GPTError(
775 'Partition %s must not go earlier (%s) than FirstUsableLBA=%s' %
776 (p, p.FirstLBA, header.FirstLBA))
777 p = lba_list[-1][2]
778 if p.LastLBA > header.LastUsableLBA:
779 raise GPTError(
780 'Partition %s must not go further (%s) than LastUsableLBA=%s' %
781 (p, p.LastLBA, header.LastLBA))
782 # Check if UniqueGUIDs are not unique.
783 if len(set(p.UniqueGUID for p in parts)) != len(parts):
784 raise GPTError('Partition UniqueGUIDs are duplicated.')
785 # Check if CRCs match.
786 if (binascii.crc32(''.join(p.blob for p in self.partitions)) !=
787 header.PartitionArrayCRC32):
788 raise GPTError('GPT Header PartitionArrayCRC32 does not match.')
Hung-Te Lin86ca4bb2018-04-25 10:22:10 +0800789 header_crc = header.Clone()
790 header_crc.UpdateChecksum()
791 if header_crc.CRC32 != header.CRC32:
792 raise GPTError('GPT Header CRC32 does not match.')
Hung-Te Lin3b491672018-04-19 01:41:20 +0800793
Hung-Te Linc772e1a2017-04-14 16:50:50 +0800794 def UpdateChecksum(self):
Hung-Te Lin86ca4bb2018-04-25 10:22:10 +0800795 """Updates all checksum fields in GPT objects."""
Hung-Te Lin49ac3c22018-04-17 14:37:54 +0800796 parts = ''.join(p.blob for p in self.partitions)
Hung-Te Lin86ca4bb2018-04-25 10:22:10 +0800797 self.header.Update(PartitionArrayCRC32=binascii.crc32(parts))
798 self.header.UpdateChecksum()
Hung-Te Linc772e1a2017-04-14 16:50:50 +0800799
Hung-Te Linc34d89c2018-04-17 15:11:34 +0800800 def GetBackupHeader(self, header):
Hung-Te Lin86ca4bb2018-04-25 10:22:10 +0800801 """Returns the backup header according to given header.
802
803 This should be invoked only after GPT.UpdateChecksum() has updated all CRC32
804 fields.
805 """
Hung-Te Linc772e1a2017-04-14 16:50:50 +0800806 partitions_starting_lba = (
Hung-Te Linc34d89c2018-04-17 15:11:34 +0800807 header.BackupLBA - self.GetPartitionTableBlocks())
Hung-Te Lin86ca4bb2018-04-25 10:22:10 +0800808 h = header.Clone()
809 h.Update(
Hung-Te Linc34d89c2018-04-17 15:11:34 +0800810 BackupLBA=header.CurrentLBA,
811 CurrentLBA=header.BackupLBA,
Hung-Te Linc772e1a2017-04-14 16:50:50 +0800812 PartitionEntriesStartingLBA=partitions_starting_lba)
Hung-Te Lin86ca4bb2018-04-25 10:22:10 +0800813 h.UpdateChecksum()
814 return h
Hung-Te Linc772e1a2017-04-14 16:50:50 +0800815
Hung-Te Linc6e009c2018-04-17 15:06:16 +0800816 @classmethod
817 def WriteProtectiveMBR(cls, image, create, bootcode=None, boot_guid=None):
818 """Writes a protective MBR to given file.
819
820 Each MBR is 512 bytes: 424 bytes for bootstrap code, 16 bytes of boot GUID,
821 4 bytes of disk id, 2 bytes of bootcode magic, 4*16 for 4 partitions, and 2
822 byte as signature. cgpt has hard-coded the CHS and bootstrap magic values so
823 we can follow that.
824
825 Args:
826 create: True to re-create PMBR structure.
827 bootcode: a blob of new boot code.
828 boot_guid a blob for new boot GUID.
829
830 Returns:
831 The written PMBR structure.
832 """
833 if isinstance(image, basestring):
834 with open(image, 'rb+') as f:
835 return cls.WriteProtectiveMBR(f, create, bootcode, boot_guid)
836
837 image.seek(0)
Hung-Te Lin86ca4bb2018-04-25 10:22:10 +0800838 pmbr_format = cls.ProtectiveMBR.GetStructFormat()
839 assert struct.calcsize(pmbr_format) == cls.DEFAULT_BLOCK_SIZE
Hung-Te Linc6e009c2018-04-17 15:06:16 +0800840 pmbr = cls.ProtectiveMBR.ReadFrom(image)
841
842 if create:
843 legacy_sectors = min(
844 0x100000000,
Hung-Te Lin446eb512018-05-02 18:39:16 +0800845 GPT.GetImageSize(image.name) / cls.DEFAULT_BLOCK_SIZE) - 1
Hung-Te Linc6e009c2018-04-17 15:06:16 +0800846 # Partition 0 must have have the fixed CHS with number of sectors
847 # (calculated as legacy_sectors later).
848 part0 = ('00000200eeffffff01000000'.decode('hex') +
849 struct.pack('<I', legacy_sectors))
850 # Partition 1~3 should be all zero.
851 part1 = '\x00' * 16
852 assert len(part0) == len(part1) == 16, 'MBR entry is wrong.'
Hung-Te Lin86ca4bb2018-04-25 10:22:10 +0800853 pmbr.Update(
Hung-Te Linc6e009c2018-04-17 15:06:16 +0800854 BootGUID=cls.TYPE_GUID_UNUSED,
855 DiskID=0,
Hung-Te Lin86ca4bb2018-04-25 10:22:10 +0800856 Magic=pmbr.MAGIC,
Hung-Te Linc6e009c2018-04-17 15:06:16 +0800857 LegacyPart0=part0,
858 LegacyPart1=part1,
859 LegacyPart2=part1,
860 LegacyPart3=part1,
Hung-Te Lin86ca4bb2018-04-25 10:22:10 +0800861 Signature=pmbr.SIGNATURE)
Hung-Te Linc6e009c2018-04-17 15:06:16 +0800862
863 if bootcode:
864 if len(bootcode) > len(pmbr.BootCode):
865 logging.info(
866 'Bootcode is larger (%d > %d)!', len(bootcode), len(pmbr.BootCode))
867 bootcode = bootcode[:len(pmbr.BootCode)]
Hung-Te Lin86ca4bb2018-04-25 10:22:10 +0800868 pmbr.Update(BootCode=bootcode)
Hung-Te Linc6e009c2018-04-17 15:06:16 +0800869 if boot_guid:
Hung-Te Lin86ca4bb2018-04-25 10:22:10 +0800870 pmbr.Update(BootGUID=boot_guid)
Hung-Te Linc6e009c2018-04-17 15:06:16 +0800871
872 blob = pmbr.blob
873 assert len(blob) == cls.DEFAULT_BLOCK_SIZE
874 image.seek(0)
875 image.write(blob)
876 return pmbr
877
Hung-Te Lin6977ae12018-04-17 12:20:32 +0800878 def WriteToFile(self, image):
879 """Updates partition table in a disk image file.
880
881 Args:
882 image: a string as file path or a file-like object to write into.
883 """
884 if isinstance(image, basestring):
885 with open(image, 'rb+') as f:
886 return self.WriteToFile(f)
Hung-Te Linc772e1a2017-04-14 16:50:50 +0800887
888 def WriteData(name, blob, lba):
889 """Writes a blob into given location."""
890 logging.info('Writing %s in LBA %d (offset %d)',
Hung-Te Linf148d322018-04-13 10:24:42 +0800891 name, lba, lba * self.block_size)
Hung-Te Lin6977ae12018-04-17 12:20:32 +0800892 image.seek(lba * self.block_size)
893 image.write(blob)
Hung-Te Linc772e1a2017-04-14 16:50:50 +0800894
895 self.UpdateChecksum()
Hung-Te Lin3b491672018-04-19 01:41:20 +0800896 self.CheckIntegrity()
Hung-Te Lin49ac3c22018-04-17 14:37:54 +0800897 parts_blob = ''.join(p.blob for p in self.partitions)
Hung-Te Linc34d89c2018-04-17 15:11:34 +0800898
899 header = self.header
900 WriteData('GPT Header', header.blob, header.CurrentLBA)
901 WriteData('GPT Partitions', parts_blob, header.PartitionEntriesStartingLBA)
902 logging.info(
903 'Usable LBA: First=%d, Last=%d', header.FirstUsableLBA,
904 header.LastUsableLBA)
905
906 if not self.is_secondary:
907 # When is_secondary is True, the header we have is actually backup header.
908 backup_header = self.GetBackupHeader(self.header)
909 WriteData(
910 'Backup Partitions', parts_blob,
911 backup_header.PartitionEntriesStartingLBA)
912 WriteData(
913 'Backup Header', backup_header.blob, backup_header.CurrentLBA)
Hung-Te Linc772e1a2017-04-14 16:50:50 +0800914
915
916class GPTCommands(object):
917 """Collection of GPT sub commands for command line to use.
918
919 The commands are derived from `cgpt`, but not necessary to be 100% compatible
920 with cgpt.
921 """
922
923 FORMAT_ARGS = [
Peter Shihc7156ca2018-02-26 14:46:24 +0800924 ('begin', 'beginning sector'),
Hung-Te Lin49ac3c22018-04-17 14:37:54 +0800925 ('size', 'partition size (in sectors)'),
Peter Shihc7156ca2018-02-26 14:46:24 +0800926 ('type', 'type guid'),
927 ('unique', 'unique guid'),
928 ('label', 'label'),
929 ('Successful', 'Successful flag'),
930 ('Tries', 'Tries flag'),
931 ('Priority', 'Priority flag'),
932 ('Legacy', 'Legacy Boot flag'),
933 ('Attribute', 'raw 16-bit attribute value (bits 48-63)')]
Hung-Te Linc772e1a2017-04-14 16:50:50 +0800934
935 def __init__(self):
Hung-Te Lin5cb0c312018-04-17 14:56:43 +0800936 commands = dict(
937 (command.lower(), getattr(self, command)())
938 for command in dir(self)
939 if (isinstance(getattr(self, command), type) and
940 issubclass(getattr(self, command), self.SubCommand) and
941 getattr(self, command) is not self.SubCommand)
942 )
943 self.commands = commands
Hung-Te Linc772e1a2017-04-14 16:50:50 +0800944
Hung-Te Lin5cb0c312018-04-17 14:56:43 +0800945 def DefineArgs(self, parser):
946 """Defines all available commands to an argparser subparsers instance."""
947 subparsers = parser.add_subparsers(help='Sub-command help.', dest='command')
948 for name, instance in sorted(self.commands.iteritems()):
949 parser = subparsers.add_parser(
950 name, description=instance.__doc__,
951 formatter_class=argparse.RawDescriptionHelpFormatter,
952 help=instance.__doc__.splitlines()[0])
953 instance.DefineArgs(parser)
Hung-Te Linc772e1a2017-04-14 16:50:50 +0800954
Hung-Te Lin5cb0c312018-04-17 14:56:43 +0800955 def Execute(self, args):
956 """Execute the sub commands by given parsed arguments."""
Hung-Te Linf641d302018-04-18 15:09:35 +0800957 return self.commands[args.command].Execute(args)
Hung-Te Linc772e1a2017-04-14 16:50:50 +0800958
Hung-Te Lin5cb0c312018-04-17 14:56:43 +0800959 class SubCommand(object):
960 """A base class for sub commands to derive from."""
961
962 def DefineArgs(self, parser):
963 """Defines command line arguments to argparse parser.
964
965 Args:
966 parser: An argparse parser instance.
967 """
968 del parser # Unused.
969 raise NotImplementedError
970
971 def Execute(self, args):
972 """Execute the command.
973
974 Args:
975 args: An argparse parsed namespace.
976 """
977 del args # Unused.
978 raise NotImplementedError
979
Hung-Te Lin6c3575a2018-04-17 15:00:49 +0800980 class Create(SubCommand):
981 """Create or reset GPT headers and tables.
982
983 Create or reset an empty GPT.
984 """
985
986 def DefineArgs(self, parser):
987 parser.add_argument(
988 '-z', '--zero', action='store_true',
989 help='Zero the sectors of the GPT table and entries')
990 parser.add_argument(
Hung-Te Linbf8aa272018-04-19 03:02:29 +0800991 '-p', '--pad-blocks', type=int, default=0,
Hung-Te Lin6c3575a2018-04-17 15:00:49 +0800992 help=('Size (in blocks) of the disk to pad between the '
993 'primary GPT header and its entries, default %(default)s'))
994 parser.add_argument(
Hung-Te Lin446eb512018-05-02 18:39:16 +0800995 '--block_size', type=int,
Hung-Te Lin6c3575a2018-04-17 15:00:49 +0800996 help='Size of each block (sector) in bytes.')
997 parser.add_argument(
998 'image_file', type=argparse.FileType('rb+'),
999 help='Disk image file to create.')
1000
1001 def Execute(self, args):
1002 block_size = args.block_size
Hung-Te Lin446eb512018-05-02 18:39:16 +08001003 if block_size is None:
1004 if GPT.IsBlockDevice(args.image_file.name):
1005 block_size = GPT.GetLogicalBlockSize(args.image_file.name)
1006 else:
1007 block_size = GPT.DEFAULT_BLOCK_SIZE
1008
1009 if block_size != GPT.DEFAULT_BLOCK_SIZE:
1010 logging.info('Block (sector) size for %s is set to %s bytes.',
1011 args.image_file.name, block_size)
1012
Hung-Te Lin6c3575a2018-04-17 15:00:49 +08001013 gpt = GPT.Create(
Hung-Te Lin446eb512018-05-02 18:39:16 +08001014 args.image_file.name, GPT.GetImageSize(args.image_file.name),
Hung-Te Lin6c3575a2018-04-17 15:00:49 +08001015 block_size, args.pad_blocks)
1016 if args.zero:
1017 # In theory we only need to clear LBA 1, but to make sure images already
1018 # initialized with different block size won't have GPT signature in
1019 # different locations, we should zero until first usable LBA.
1020 args.image_file.seek(0)
1021 args.image_file.write('\0' * block_size * gpt.header.FirstUsableLBA)
1022 gpt.WriteToFile(args.image_file)
1023 print('OK: Created GPT for %s' % args.image_file.name)
1024
Hung-Te Linc6e009c2018-04-17 15:06:16 +08001025 class Boot(SubCommand):
1026 """Edit the PMBR sector for legacy BIOSes.
1027
1028 With no options, it will just print the PMBR boot guid.
1029 """
1030
1031 def DefineArgs(self, parser):
1032 parser.add_argument(
1033 '-i', '--number', type=int,
1034 help='Set bootable partition')
1035 parser.add_argument(
1036 '-b', '--bootloader', type=argparse.FileType('r'),
1037 help='Install bootloader code in the PMBR')
1038 parser.add_argument(
1039 '-p', '--pmbr', action='store_true',
1040 help='Create legacy PMBR partition table')
1041 parser.add_argument(
1042 'image_file', type=argparse.FileType('rb+'),
1043 help='Disk image file to change PMBR.')
1044
1045 def Execute(self, args):
1046 """Rebuilds the protective MBR."""
1047 bootcode = args.bootloader.read() if args.bootloader else None
1048 boot_guid = None
1049 if args.number is not None:
1050 gpt = GPT.LoadFromFile(args.image_file)
Hung-Te Lin5f0dea42018-04-18 23:20:11 +08001051 boot_guid = gpt.GetPartition(args.number).UniqueGUID
Hung-Te Linc6e009c2018-04-17 15:06:16 +08001052 pmbr = GPT.WriteProtectiveMBR(
1053 args.image_file, args.pmbr, bootcode=bootcode, boot_guid=boot_guid)
1054
Hung-Te Linbf8aa272018-04-19 03:02:29 +08001055 print(pmbr.boot_guid)
1056
Hung-Te Linc6e009c2018-04-17 15:06:16 +08001057
Hung-Te Linc34d89c2018-04-17 15:11:34 +08001058 class Legacy(SubCommand):
1059 """Switch between GPT and Legacy GPT.
1060
1061 Switch GPT header signature to "CHROMEOS".
1062 """
1063
1064 def DefineArgs(self, parser):
1065 parser.add_argument(
1066 '-e', '--efi', action='store_true',
1067 help='Switch GPT header signature back to "EFI PART"')
1068 parser.add_argument(
1069 '-p', '--primary-ignore', action='store_true',
1070 help='Switch primary GPT header signature to "IGNOREME"')
1071 parser.add_argument(
1072 'image_file', type=argparse.FileType('rb+'),
1073 help='Disk image file to change.')
1074
1075 def Execute(self, args):
1076 gpt = GPT.LoadFromFile(args.image_file)
1077 # cgpt behavior: if -p is specified, -e is ignored.
1078 if args.primary_ignore:
1079 if gpt.is_secondary:
1080 raise GPTError('Sorry, the disk already has primary GPT ignored.')
1081 args.image_file.seek(gpt.header.CurrentLBA * gpt.block_size)
1082 args.image_file.write(gpt.header.SIGNATURE_IGNORE)
1083 gpt.header = gpt.GetBackupHeader(self.header)
1084 gpt.is_secondary = True
1085 else:
1086 new_signature = gpt.Header.SIGNATURES[0 if args.efi else 1]
Hung-Te Lin86ca4bb2018-04-25 10:22:10 +08001087 gpt.header.Update(Signature=new_signature)
Hung-Te Linc34d89c2018-04-17 15:11:34 +08001088 gpt.WriteToFile(args.image_file)
1089 if args.primary_ignore:
1090 print('OK: Set %s primary GPT header to %s.' %
1091 (args.image_file.name, gpt.header.SIGNATURE_IGNORE))
1092 else:
1093 print('OK: Changed GPT signature for %s to %s.' %
1094 (args.image_file.name, new_signature))
1095
Hung-Te Lin5cb0c312018-04-17 14:56:43 +08001096 class Repair(SubCommand):
Hung-Te Linc772e1a2017-04-14 16:50:50 +08001097 """Repair damaged GPT headers and tables."""
Hung-Te Linc772e1a2017-04-14 16:50:50 +08001098
Hung-Te Lin5cb0c312018-04-17 14:56:43 +08001099 def DefineArgs(self, parser):
1100 parser.add_argument(
1101 'image_file', type=argparse.FileType('rb+'),
1102 help='Disk image file to repair.')
1103
1104 def Execute(self, args):
1105 gpt = GPT.LoadFromFile(args.image_file)
Hung-Te Lin446eb512018-05-02 18:39:16 +08001106 gpt.Resize(GPT.GetImageSize(args.image_file.name))
Hung-Te Lin5cb0c312018-04-17 14:56:43 +08001107 gpt.WriteToFile(args.image_file)
1108 print('Disk image file %s repaired.' % args.image_file.name)
1109
1110 class Expand(SubCommand):
1111 """Expands a GPT partition to all available free space."""
1112
1113 def DefineArgs(self, parser):
1114 parser.add_argument(
1115 '-i', '--number', type=int, required=True,
1116 help='The partition to expand.')
1117 parser.add_argument(
1118 'image_file', type=argparse.FileType('rb+'),
1119 help='Disk image file to modify.')
1120
1121 def Execute(self, args):
1122 gpt = GPT.LoadFromFile(args.image_file)
Hung-Te Lin5f0dea42018-04-18 23:20:11 +08001123 old_blocks, new_blocks = gpt.ExpandPartition(args.number)
Hung-Te Lin5cb0c312018-04-17 14:56:43 +08001124 gpt.WriteToFile(args.image_file)
1125 if old_blocks < new_blocks:
1126 print(
1127 'Partition %s on disk image file %s has been extended '
1128 'from %s to %s .' %
1129 (args.number, args.image_file.name, old_blocks * gpt.block_size,
1130 new_blocks * gpt.block_size))
Hung-Te Linc772e1a2017-04-14 16:50:50 +08001131 else:
Hung-Te Lin5cb0c312018-04-17 14:56:43 +08001132 print('Nothing to expand for disk image %s partition %s.' %
1133 (args.image_file.name, args.number))
Hung-Te Linc772e1a2017-04-14 16:50:50 +08001134
Hung-Te Linfcd1a8d2018-04-17 15:15:01 +08001135 class Add(SubCommand):
1136 """Add, edit, or remove a partition entry.
1137
1138 Use the -i option to modify an existing partition.
1139 The -b, -s, and -t options must be given for new partitions.
1140
1141 The partition type may also be given as one of these aliases:
1142
1143 firmware ChromeOS firmware
1144 kernel ChromeOS kernel
1145 rootfs ChromeOS rootfs
1146 data Linux data
1147 reserved ChromeOS reserved
1148 efi EFI System Partition
1149 unused Unused (nonexistent) partition
1150 """
1151 def DefineArgs(self, parser):
1152 parser.add_argument(
1153 '-i', '--number', type=int,
1154 help='Specify partition (default is next available)')
1155 parser.add_argument(
1156 '-b', '--begin', type=int,
1157 help='Beginning sector')
1158 parser.add_argument(
1159 '-s', '--sectors', type=int,
1160 help='Size in sectors (logical blocks).')
1161 parser.add_argument(
Hung-Te Linbf8aa272018-04-19 03:02:29 +08001162 '-t', '--type-guid', type=GPT.GetTypeGUID,
Hung-Te Linfcd1a8d2018-04-17 15:15:01 +08001163 help='Partition Type GUID')
1164 parser.add_argument(
Hung-Te Linbf8aa272018-04-19 03:02:29 +08001165 '-u', '--unique-guid', type=GUID,
Hung-Te Linfcd1a8d2018-04-17 15:15:01 +08001166 help='Partition Unique ID')
1167 parser.add_argument(
1168 '-l', '--label',
1169 help='Label')
1170 parser.add_argument(
1171 '-S', '--successful', type=int, choices=xrange(2),
1172 help='set Successful flag')
1173 parser.add_argument(
1174 '-T', '--tries', type=int,
1175 help='set Tries flag (0-15)')
1176 parser.add_argument(
1177 '-P', '--priority', type=int,
1178 help='set Priority flag (0-15)')
1179 parser.add_argument(
1180 '-R', '--required', type=int, choices=xrange(2),
1181 help='set Required flag')
1182 parser.add_argument(
Hung-Te Linbf8aa272018-04-19 03:02:29 +08001183 '-B', '--boot-legacy', dest='legacy_boot', type=int,
Hung-Te Linfcd1a8d2018-04-17 15:15:01 +08001184 choices=xrange(2),
1185 help='set Legacy Boot flag')
1186 parser.add_argument(
1187 '-A', '--attribute', dest='raw_16', type=int,
1188 help='set raw 16-bit attribute value (bits 48-63)')
1189 parser.add_argument(
1190 'image_file', type=argparse.FileType('rb+'),
1191 help='Disk image file to modify.')
1192
Hung-Te Linfcd1a8d2018-04-17 15:15:01 +08001193 def Execute(self, args):
1194 gpt = GPT.LoadFromFile(args.image_file)
Hung-Te Linfcd1a8d2018-04-17 15:15:01 +08001195 number = args.number
1196 if number is None:
Hung-Te Linc5196682018-04-18 22:59:59 +08001197 number = next(p for p in gpt.partitions if p.IsUnused()).number
Hung-Te Linfcd1a8d2018-04-17 15:15:01 +08001198
1199 # First and last LBA must be calculated explicitly because the given
1200 # argument is size.
Hung-Te Lin5f0dea42018-04-18 23:20:11 +08001201 part = gpt.GetPartition(number)
Hung-Te Linc5196682018-04-18 22:59:59 +08001202 is_new_part = part.IsUnused()
Hung-Te Linfcd1a8d2018-04-17 15:15:01 +08001203
1204 if is_new_part:
Hung-Te Lin86ca4bb2018-04-25 10:22:10 +08001205 part.Zero()
1206 part.Update(
Hung-Te Linc5196682018-04-18 22:59:59 +08001207 FirstLBA=gpt.GetMaxUsedLBA() + 1,
Hung-Te Linfcd1a8d2018-04-17 15:15:01 +08001208 LastLBA=gpt.header.LastUsableLBA,
Hung-Te Linbf8aa272018-04-19 03:02:29 +08001209 UniqueGUID=GUID.Random(),
Hung-Te Linf641d302018-04-18 15:09:35 +08001210 TypeGUID=gpt.GetTypeGUID('data'))
Hung-Te Linfcd1a8d2018-04-17 15:15:01 +08001211
Hung-Te Linbf8aa272018-04-19 03:02:29 +08001212 def UpdateAttr(name):
1213 value = getattr(args, name)
1214 if value is None:
1215 return
1216 setattr(attrs, name, value)
Hung-Te Linfcd1a8d2018-04-17 15:15:01 +08001217
Hung-Te Linbf8aa272018-04-19 03:02:29 +08001218 def GetArg(arg_value, default_value):
1219 return default_value if arg_value is None else arg_value
1220
Hung-Te Lin86ca4bb2018-04-25 10:22:10 +08001221 attrs = part.Attributes
Hung-Te Linbf8aa272018-04-19 03:02:29 +08001222 for name in ['legacy_boot', 'required', 'priority', 'tries',
1223 'successful', 'raw_16']:
1224 UpdateAttr(name)
1225 first_lba = GetArg(args.begin, part.FirstLBA)
Hung-Te Lin86ca4bb2018-04-25 10:22:10 +08001226 part.Update(
1227 Names=GetArg(args.label, part.Names),
Hung-Te Linfcd1a8d2018-04-17 15:15:01 +08001228 FirstLBA=first_lba,
Hung-Te Linbf8aa272018-04-19 03:02:29 +08001229 LastLBA=first_lba - 1 + GetArg(args.sectors, part.blocks),
1230 TypeGUID=GetArg(args.type_guid, part.TypeGUID),
1231 UniqueGUID=GetArg(args.unique_guid, part.UniqueGUID),
1232 Attributes=attrs)
Hung-Te Linfcd1a8d2018-04-17 15:15:01 +08001233
Hung-Te Linfcd1a8d2018-04-17 15:15:01 +08001234 # Wipe partition again if it should be empty.
1235 if part.IsUnused():
Hung-Te Lin86ca4bb2018-04-25 10:22:10 +08001236 part.Zero()
Hung-Te Linfcd1a8d2018-04-17 15:15:01 +08001237
Hung-Te Linfcd1a8d2018-04-17 15:15:01 +08001238 gpt.WriteToFile(args.image_file)
1239 if part.IsUnused():
1240 # If we do ('%s' % part) there will be TypeError.
1241 print('OK: Deleted (zeroed) %s.' % (part,))
1242 else:
1243 print('OK: %s %s (%s+%s).' %
1244 ('Added' if is_new_part else 'Modified',
1245 part, part.FirstLBA, part.blocks))
1246
Hung-Te Lin5cb0c312018-04-17 14:56:43 +08001247 class Show(SubCommand):
1248 """Show partition table and entries.
Hung-Te Linc772e1a2017-04-14 16:50:50 +08001249
Hung-Te Lin5cb0c312018-04-17 14:56:43 +08001250 Display the GPT table.
Hung-Te Linc772e1a2017-04-14 16:50:50 +08001251 """
Hung-Te Linc772e1a2017-04-14 16:50:50 +08001252
Hung-Te Lin5cb0c312018-04-17 14:56:43 +08001253 def DefineArgs(self, parser):
1254 parser.add_argument(
1255 '--numeric', '-n', action='store_true',
1256 help='Numeric output only.')
1257 parser.add_argument(
1258 '--quick', '-q', action='store_true',
1259 help='Quick output.')
1260 parser.add_argument(
1261 '-i', '--number', type=int,
1262 help='Show specified partition only, with format args.')
1263 for name, help_str in GPTCommands.FORMAT_ARGS:
1264 # TODO(hungte) Alert if multiple args were specified.
1265 parser.add_argument(
1266 '--%s' % name, '-%c' % name[0], action='store_true',
1267 help='[format] %s.' % help_str)
1268 parser.add_argument(
1269 'image_file', type=argparse.FileType('rb'),
1270 help='Disk image file to show.')
Hung-Te Linc772e1a2017-04-14 16:50:50 +08001271
Hung-Te Lin5cb0c312018-04-17 14:56:43 +08001272 def Execute(self, args):
1273 """Show partition table and entries."""
Hung-Te Linc772e1a2017-04-14 16:50:50 +08001274
Hung-Te Lin5cb0c312018-04-17 14:56:43 +08001275 def FormatTypeGUID(p):
Hung-Te Lin86ca4bb2018-04-25 10:22:10 +08001276 guid = p.TypeGUID
Hung-Te Lin5cb0c312018-04-17 14:56:43 +08001277 if not args.numeric:
Hung-Te Linbf8aa272018-04-19 03:02:29 +08001278 names = gpt.TYPE_GUID_MAP.get(guid)
Hung-Te Lin5cb0c312018-04-17 14:56:43 +08001279 if names:
1280 return names
Hung-Te Linbf8aa272018-04-19 03:02:29 +08001281 return str(guid)
Hung-Te Linc772e1a2017-04-14 16:50:50 +08001282
Hung-Te Linbf8aa272018-04-19 03:02:29 +08001283 def IsBootableType(guid):
1284 if not guid:
1285 return False
1286 return guid in gpt.TYPE_GUID_LIST_BOOTABLE
Hung-Te Linc772e1a2017-04-14 16:50:50 +08001287
Hung-Te Lin5cb0c312018-04-17 14:56:43 +08001288 def FormatAttribute(attrs, chromeos_kernel=False):
1289 if args.numeric:
1290 return '[%x]' % (attrs.raw >> 48)
1291 results = []
1292 if chromeos_kernel:
1293 results += [
1294 'priority=%d' % attrs.priority,
1295 'tries=%d' % attrs.tries,
1296 'successful=%d' % attrs.successful]
1297 if attrs.required:
1298 results += ['required=1']
1299 if attrs.legacy_boot:
1300 results += ['legacy_boot=1']
1301 return ' '.join(results)
Hung-Te Linc772e1a2017-04-14 16:50:50 +08001302
Hung-Te Lin5cb0c312018-04-17 14:56:43 +08001303 def ApplyFormatArgs(p):
1304 if args.begin:
1305 return p.FirstLBA
1306 elif args.size:
1307 return p.blocks
1308 elif args.type:
1309 return FormatTypeGUID(p)
1310 elif args.unique:
Hung-Te Lin86ca4bb2018-04-25 10:22:10 +08001311 return p.UniqueGUID
Hung-Te Lin5cb0c312018-04-17 14:56:43 +08001312 elif args.label:
Hung-Te Lin86ca4bb2018-04-25 10:22:10 +08001313 return p.Names
Hung-Te Lin5cb0c312018-04-17 14:56:43 +08001314 elif args.Successful:
Hung-Te Lin86ca4bb2018-04-25 10:22:10 +08001315 return p.Attributes.successful
Hung-Te Lin5cb0c312018-04-17 14:56:43 +08001316 elif args.Priority:
Hung-Te Lin86ca4bb2018-04-25 10:22:10 +08001317 return p.Attributes.priority
Hung-Te Lin5cb0c312018-04-17 14:56:43 +08001318 elif args.Tries:
Hung-Te Lin86ca4bb2018-04-25 10:22:10 +08001319 return p.Attributes.tries
Hung-Te Lin5cb0c312018-04-17 14:56:43 +08001320 elif args.Legacy:
Hung-Te Lin86ca4bb2018-04-25 10:22:10 +08001321 return p.Attributes.legacy_boot
Hung-Te Lin5cb0c312018-04-17 14:56:43 +08001322 elif args.Attribute:
Hung-Te Lin86ca4bb2018-04-25 10:22:10 +08001323 return '[%x]' % (p.Attributes.raw >> 48)
Hung-Te Lin5cb0c312018-04-17 14:56:43 +08001324 else:
1325 return None
Hung-Te Linc772e1a2017-04-14 16:50:50 +08001326
Hung-Te Lin5cb0c312018-04-17 14:56:43 +08001327 def IsFormatArgsSpecified():
1328 return any(getattr(args, arg[0]) for arg in GPTCommands.FORMAT_ARGS)
Hung-Te Linc772e1a2017-04-14 16:50:50 +08001329
Hung-Te Lin5cb0c312018-04-17 14:56:43 +08001330 gpt = GPT.LoadFromFile(args.image_file)
1331 logging.debug('%r', gpt.header)
1332 fmt = '%12s %11s %7s %s'
1333 fmt2 = '%32s %s: %s'
1334 header = ('start', 'size', 'part', 'contents')
Hung-Te Linc772e1a2017-04-14 16:50:50 +08001335
Hung-Te Lin5cb0c312018-04-17 14:56:43 +08001336 if IsFormatArgsSpecified() and args.number is None:
1337 raise GPTError('Format arguments must be used with -i.')
Hung-Te Linc772e1a2017-04-14 16:50:50 +08001338
Hung-Te Lin5cb0c312018-04-17 14:56:43 +08001339 if not (args.number is None or
1340 0 < args.number <= gpt.header.PartitionEntriesNumber):
1341 raise GPTError('Invalid partition number: %d' % args.number)
Hung-Te Linc772e1a2017-04-14 16:50:50 +08001342
Hung-Te Lin5cb0c312018-04-17 14:56:43 +08001343 partitions = gpt.partitions
1344 do_print_gpt_blocks = False
1345 if not (args.quick or IsFormatArgsSpecified()):
1346 print(fmt % header)
1347 if args.number is None:
1348 do_print_gpt_blocks = True
Hung-Te Linc772e1a2017-04-14 16:50:50 +08001349
Hung-Te Lin5cb0c312018-04-17 14:56:43 +08001350 if do_print_gpt_blocks:
Hung-Te Linc34d89c2018-04-17 15:11:34 +08001351 if gpt.pmbr:
1352 print(fmt % (0, 1, '', 'PMBR'))
1353 if gpt.is_secondary:
1354 print(fmt % (gpt.header.BackupLBA, 1, 'IGNORED', 'Pri GPT header'))
1355 else:
1356 print(fmt % (gpt.header.CurrentLBA, 1, '', 'Pri GPT header'))
1357 print(fmt % (gpt.header.PartitionEntriesStartingLBA,
1358 gpt.GetPartitionTableBlocks(), '', 'Pri GPT table'))
Hung-Te Linc772e1a2017-04-14 16:50:50 +08001359
Hung-Te Lin5cb0c312018-04-17 14:56:43 +08001360 for p in partitions:
1361 if args.number is None:
1362 # Skip unused partitions.
1363 if p.IsUnused():
1364 continue
1365 elif p.number != args.number:
1366 continue
Hung-Te Linc772e1a2017-04-14 16:50:50 +08001367
Hung-Te Lin5cb0c312018-04-17 14:56:43 +08001368 if IsFormatArgsSpecified():
1369 print(ApplyFormatArgs(p))
1370 continue
Hung-Te Linc772e1a2017-04-14 16:50:50 +08001371
Hung-Te Lin5cb0c312018-04-17 14:56:43 +08001372 print(fmt % (p.FirstLBA, p.blocks, p.number,
1373 FormatTypeGUID(p) if args.quick else
Hung-Te Lin86ca4bb2018-04-25 10:22:10 +08001374 'Label: "%s"' % p.Names))
Hung-Te Linc772e1a2017-04-14 16:50:50 +08001375
Hung-Te Lin5cb0c312018-04-17 14:56:43 +08001376 if not args.quick:
1377 print(fmt2 % ('', 'Type', FormatTypeGUID(p)))
Hung-Te Lin86ca4bb2018-04-25 10:22:10 +08001378 print(fmt2 % ('', 'UUID', p.UniqueGUID))
1379 if args.numeric or IsBootableType(p.TypeGUID):
Hung-Te Lin5cb0c312018-04-17 14:56:43 +08001380 print(fmt2 % ('', 'Attr', FormatAttribute(
Hung-Te Lin86ca4bb2018-04-25 10:22:10 +08001381 p.Attributes, p.IsChromeOSKernel())))
Hung-Te Linc772e1a2017-04-14 16:50:50 +08001382
Hung-Te Lin5cb0c312018-04-17 14:56:43 +08001383 if do_print_gpt_blocks:
Hung-Te Linc34d89c2018-04-17 15:11:34 +08001384 if gpt.is_secondary:
1385 header = gpt.header
1386 else:
1387 f = args.image_file
1388 f.seek(gpt.header.BackupLBA * gpt.block_size)
1389 header = gpt.Header.ReadFrom(f)
Hung-Te Lin5cb0c312018-04-17 14:56:43 +08001390 print(fmt % (header.PartitionEntriesStartingLBA,
1391 gpt.GetPartitionTableBlocks(header), '',
1392 'Sec GPT table'))
1393 print(fmt % (header.CurrentLBA, 1, '', 'Sec GPT header'))
Hung-Te Linc772e1a2017-04-14 16:50:50 +08001394
Hung-Te Lin3b491672018-04-19 01:41:20 +08001395 # Check integrity after showing all fields.
1396 gpt.CheckIntegrity()
1397
Hung-Te Linfe724f82018-04-18 15:03:58 +08001398 class Prioritize(SubCommand):
1399 """Reorder the priority of all kernel partitions.
1400
1401 Reorder the priority of all active ChromeOS Kernel partitions.
1402
1403 With no options this will set the lowest active kernel to priority 1 while
1404 maintaining the original order.
1405 """
1406
1407 def DefineArgs(self, parser):
1408 parser.add_argument(
1409 '-P', '--priority', type=int,
1410 help=('Highest priority to use in the new ordering. '
1411 'The other partitions will be ranked in decreasing '
1412 'priority while preserving their original order. '
1413 'If necessary the lowest ranks will be coalesced. '
1414 'No active kernels will be lowered to priority 0.'))
1415 parser.add_argument(
1416 '-i', '--number', type=int,
1417 help='Specify the partition to make the highest in the new order.')
1418 parser.add_argument(
1419 '-f', '--friends', action='store_true',
1420 help=('Friends of the given partition (those with the same '
1421 'starting priority) are also updated to the new '
1422 'highest priority. '))
1423 parser.add_argument(
1424 'image_file', type=argparse.FileType('rb+'),
1425 help='Disk image file to prioritize.')
1426
1427 def Execute(self, args):
1428 gpt = GPT.LoadFromFile(args.image_file)
1429 parts = [p for p in gpt.partitions if p.IsChromeOSKernel()]
Hung-Te Lin86ca4bb2018-04-25 10:22:10 +08001430 prios = list(set(p.Attributes.priority for p in parts
1431 if p.Attributes.priority))
Hung-Te Linfe724f82018-04-18 15:03:58 +08001432 prios.sort(reverse=True)
Hung-Te Lin86ca4bb2018-04-25 10:22:10 +08001433 groups = [[p for p in parts if p.Attributes.priority == priority]
Hung-Te Linfe724f82018-04-18 15:03:58 +08001434 for priority in prios]
1435 if args.number:
Hung-Te Lin5f0dea42018-04-18 23:20:11 +08001436 p = gpt.GetPartition(args.number)
Hung-Te Linfe724f82018-04-18 15:03:58 +08001437 if p not in parts:
1438 raise GPTError('%s is not a ChromeOS kernel.' % p)
1439 if args.friends:
Hung-Te Lin86ca4bb2018-04-25 10:22:10 +08001440 group0 = [f for f in parts
1441 if f.Attributes.priority == p.Attributes.priority]
Hung-Te Linfe724f82018-04-18 15:03:58 +08001442 else:
1443 group0 = [p]
1444 groups.insert(0, group0)
1445
1446 # Max priority is 0xf.
1447 highest = min(args.priority or len(prios), 0xf)
1448 logging.info('New highest priority: %s', highest)
1449 done = []
1450
1451 new_priority = highest
1452 for g in groups:
1453 has_new_part = False
1454 for p in g:
1455 if p.number in done:
1456 continue
1457 done.append(p.number)
Hung-Te Lin86ca4bb2018-04-25 10:22:10 +08001458 attrs = p.Attributes
Hung-Te Linfe724f82018-04-18 15:03:58 +08001459 old_priority = attrs.priority
1460 assert new_priority > 0, 'Priority must be > 0.'
1461 attrs.priority = new_priority
Hung-Te Lin86ca4bb2018-04-25 10:22:10 +08001462 p.Update(Attributes=attrs)
Hung-Te Linfe724f82018-04-18 15:03:58 +08001463 has_new_part = True
1464 logging.info('%s priority changed from %s to %s.', p, old_priority,
1465 new_priority)
1466 if has_new_part:
1467 new_priority -= 1
1468
1469 gpt.WriteToFile(args.image_file)
1470
Hung-Te Linf641d302018-04-18 15:09:35 +08001471 class Find(SubCommand):
1472 """Locate a partition by its GUID.
1473
1474 Find a partition by its UUID or label. With no specified DRIVE it scans all
1475 physical drives.
1476
1477 The partition type may also be given as one of these aliases:
1478
1479 firmware ChromeOS firmware
1480 kernel ChromeOS kernel
1481 rootfs ChromeOS rootfs
1482 data Linux data
1483 reserved ChromeOS reserved
1484 efi EFI System Partition
1485 unused Unused (nonexistent) partition
1486 """
1487 def DefineArgs(self, parser):
1488 parser.add_argument(
Hung-Te Linbf8aa272018-04-19 03:02:29 +08001489 '-t', '--type-guid', type=GPT.GetTypeGUID,
Hung-Te Linf641d302018-04-18 15:09:35 +08001490 help='Search for Partition Type GUID')
1491 parser.add_argument(
Hung-Te Linbf8aa272018-04-19 03:02:29 +08001492 '-u', '--unique-guid', type=GUID,
Hung-Te Linf641d302018-04-18 15:09:35 +08001493 help='Search for Partition Unique GUID')
1494 parser.add_argument(
1495 '-l', '--label',
1496 help='Search for Label')
1497 parser.add_argument(
1498 '-n', '--numeric', action='store_true',
1499 help='Numeric output only.')
1500 parser.add_argument(
1501 '-1', '--single-match', action='store_true',
1502 help='Fail if more than one match is found.')
1503 parser.add_argument(
1504 '-M', '--match-file', type=str,
1505 help='Matching partition data must also contain MATCH_FILE content.')
1506 parser.add_argument(
1507 '-O', '--offset', type=int, default=0,
1508 help='Byte offset into partition to match content (default 0).')
1509 parser.add_argument(
1510 'drive', type=argparse.FileType('rb+'), nargs='?',
1511 help='Drive or disk image file to find.')
1512
1513 def Execute(self, args):
1514 if not any((args.type_guid, args.unique_guid, args.label)):
1515 raise GPTError('You must specify at least one of -t, -u, or -l')
1516
1517 drives = [args.drive.name] if args.drive else (
1518 '/dev/%s' % name for name in subprocess.check_output(
1519 'lsblk -d -n -r -o name', shell=True).split())
1520
1521 match_pattern = None
1522 if args.match_file:
1523 with open(args.match_file) as f:
1524 match_pattern = f.read()
1525
1526 found = 0
1527 for drive in drives:
1528 try:
1529 gpt = GPT.LoadFromFile(drive)
1530 except GPTError:
1531 if args.drive:
1532 raise
1533 # When scanning all block devices on system, ignore failure.
1534
Hung-Te Linbf8aa272018-04-19 03:02:29 +08001535 def Unmatch(a, b):
1536 return a is not None and a != b
1537
Hung-Te Linf641d302018-04-18 15:09:35 +08001538 for p in gpt.partitions:
Hung-Te Linbf8aa272018-04-19 03:02:29 +08001539 if (p.IsUnused() or
Hung-Te Lin86ca4bb2018-04-25 10:22:10 +08001540 Unmatch(args.label, p.Names) or
1541 Unmatch(args.unique_guid, p.UniqueGUID) or
1542 Unmatch(args.type_guid, p.TypeGUID)):
Hung-Te Linf641d302018-04-18 15:09:35 +08001543 continue
1544 if match_pattern:
1545 with open(drive, 'rb') as f:
1546 f.seek(p.offset + args.offset)
1547 if f.read(len(match_pattern)) != match_pattern:
1548 continue
1549 # Found the partition, now print.
1550 found += 1
1551 if args.numeric:
1552 print(p.number)
1553 else:
1554 # This is actually more for block devices.
1555 print('%s%s%s' % (p.image, 'p' if p.image[-1].isdigit() else '',
1556 p.number))
1557
1558 if found < 1 or (args.single_match and found > 1):
1559 return 1
1560 return 0
1561
Hung-Te Linc772e1a2017-04-14 16:50:50 +08001562
1563def main():
Hung-Te Lin5cb0c312018-04-17 14:56:43 +08001564 commands = GPTCommands()
Hung-Te Linc772e1a2017-04-14 16:50:50 +08001565 parser = argparse.ArgumentParser(description='GPT Utility.')
1566 parser.add_argument('--verbose', '-v', action='count', default=0,
1567 help='increase verbosity.')
1568 parser.add_argument('--debug', '-d', action='store_true',
1569 help='enable debug output.')
Hung-Te Lin5cb0c312018-04-17 14:56:43 +08001570 commands.DefineArgs(parser)
Hung-Te Linc772e1a2017-04-14 16:50:50 +08001571
1572 args = parser.parse_args()
1573 log_level = max(logging.WARNING - args.verbose * 10, logging.DEBUG)
1574 if args.debug:
1575 log_level = logging.DEBUG
1576 logging.basicConfig(format='%(module)s:%(funcName)s %(message)s',
1577 level=log_level)
Hung-Te Linc772e1a2017-04-14 16:50:50 +08001578 try:
Hung-Te Linf641d302018-04-18 15:09:35 +08001579 code = commands.Execute(args)
1580 if type(code) is int:
1581 sys.exit(code)
Hung-Te Linc772e1a2017-04-14 16:50:50 +08001582 except Exception as e:
1583 if args.verbose or args.debug:
1584 logging.exception('Failure in command [%s]', args.command)
Hung-Te Lin5cb0c312018-04-17 14:56:43 +08001585 exit('ERROR: %s: %s' % (args.command, str(e) or 'Unknown error.'))
Hung-Te Linc772e1a2017-04-14 16:50:50 +08001586
1587
1588if __name__ == '__main__':
1589 main()