-
Notifications
You must be signed in to change notification settings - Fork 24
/
Copy pathgpt.py
339 lines (258 loc) · 8.67 KB
/
gpt.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
#!/usr/bin/env python
"""
Copyright (C) 2016 Elliott Mitchell <[email protected]>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
"""
from __future__ import print_function
import os
import sys
import io
from collections import OrderedDict
from struct import Struct
from uuid import UUID
from binascii import crc32
verbose = lambda msg: None
class NoGPT(Exception):
def __init__(self, errmsg):
self.errmsg = errmsg
def __str__(self):
return self.errmsg
class GPTSlice(object):
"""
Class for handling invidual slices^Wpartitions of a GUID table
"""
_gpt_slice_length = 128 # this is *default*!
# Format string dict
# itemName is the new dict key for the data to be stored under
# formatString is the Python formatstring for struct.unpack()
# Example:
# ('itemName', ('formatString'))
_gpt_slice_fmt = OrderedDict([
('type', ('16s')),
('uuid', ('16s')),
('startLBA', ('Q')),
('endLBA', ('Q')),
('flags', ('Q')),
('name', ('72s'))
])
# Generate the formatstring for struct.unpack()
_gpt_struct = Struct("<" + "".join([x for x in _gpt_slice_fmt.values()]))
def display(self, idx):
"""
Display the data for this slice of a GPT
"""
if self.type == UUID(int=0):
verbose("Name: <empty entry>")
return None
verbose("Name({:d}): \"{:s}\" start={:d} end={:d} count={:d}".format(idx, self.name, self.startLBA, self.endLBA, self.endLBA-self.startLBA+1))
verbose("typ={:s} id={:s}".format(str(self.type), str(self.uuid)))
def __init__(self, buf):
"""
Initialize the GPTSlice class
"""
data = dict(zip(
self._gpt_slice_fmt.keys(),
self._gpt_struct.unpack(buf)
))
self.type = UUID(bytes=data['type'])
self.uuid = UUID(bytes=data['uuid'])
self.startLBA = data['startLBA']
self.endLBA = data['endLBA']
self.flags = data['flags']
self.name = data['name'].decode("utf16").rstrip('\x00')
class GPT(object):
"""
Class for handling of GUID Partition Tables
(https://en.wikipedia.org/wiki/GUID_Partition_Table)
"""
_gpt_header = b"EFI PART"
_gpt_size = 0x5C # default, can be overridden by headerSize
# Format string dict
# itemName is the new dict key for the data to be stored under
# formatString is the Python formatstring for struct.unpack()
# Example:
# ('itemName', ('formatString'))
_gpt_head_fmt = OrderedDict([
('header', ('8s')), # magic number
('revision', ('I')), # actually 2 shorts, Struct...
('headerSize', ('I')),
('crc32', ('I')),
('reserved', ('I')),
('myLBA', ('Q')),
('altLBA', ('Q')),
('dataStartLBA',('Q')),
('dataEndLBA', ('Q')),
('uuid', ('16s')),
('entryStart', ('Q')),
('entryCount', ('I')),
('entrySize', ('I')),
('entryCrc32', ('I')),
])
# Generate the formatstring for struct.unpack()
_gpt_struct = Struct("<" + "".join([x for x in _gpt_head_fmt.values()]))
def display(self):
"""
Display the data in the particular GPT
"""
verbose("")
verbose("block size is {:d} bytes (shift {:d})".format(1<<self.shiftLBA, self.shiftLBA))
verbose("device={:s}".format(str(self.uuid)))
verbose("myLBA={:d} altLBA={:d} dataStart={:d} dataEnd={:d}".format(self.myLBA, self.altLBA, self.dataStartLBA, self.dataEndLBA))
verbose("")
if self.myLBA == 1:
if self.entryStart != 2:
verbose("Note: {:d} unused blocks between GPT header and entry table".format(self.entryStart-2))
endEntry = self.entryStart + ((self.entrySize * self.entryCount + (1<<self.shiftLBA)-1)>>self.shiftLBA)
if endEntry < self.dataStartLBA:
verbose("Note: {:d} unused slice entry blocks before first usable block".format(self.dataStartLBA - endEntry))
else:
if self.entryStart != self.dataEndLBA+1:
verbose("Note: {:d} unused slice entry blocks after last usable block".format(self.entryStart-self.dataEndLBA-1))
endEntry = self.entryStart + ((self.entrySize * self.entryCount + (1<<self.shiftLBA)-1)>>self.shiftLBA)
if endEntry < self.myLBA-1:
verbose("Note: {:d} unused blocks between GPT header and entry table".format(self.myLBA-endEntry+1))
current = self.dataStartLBA
idx = 1
for slice in self.slices:
if slice.type != UUID(int=0):
if slice.startLBA != current:
verbose("Note: non-contiguous ({:d} unused)".format(slice.startLBA-current))
current = slice.endLBA + 1
slice.display(idx)
idx += 1
current-=1
if self.dataEndLBA != current:
verbose("Note: empty LBAs at end ({:d} unused)".format(self.dataEndLBA-current))
def tryParseHeader(self, buf):
"""
Try to parse a buffer as a GPT header, return None on failure
"""
if len(buf) < self._gpt_size:
raise NoGPT("Failed to locate GPT")
data = dict(zip(
self._gpt_head_fmt.keys(),
self._gpt_struct.unpack(buf[0:self._gpt_size])
))
if data['header'] != self._gpt_header:
return None
tmp = data['crc32']
data['crc32'] = 0
crc = crc32(self._gpt_struct.pack(*[data[k] for k in self._gpt_head_fmt.keys()]))
data['crc32'] = tmp
# just in case future ones are larger
crc = crc32(buf[self._gpt_size:data['headerSize']], crc)
crc &= 0xFFFFFFFF
if crc != data['crc32']:
verbose("Warning: Found GPT candidate with bad CRC")
return None
return data
def __init__(self, buf, type=None, lbaMinShift=9, lbaMaxShift=16):
"""
Initialize the GPT class
"""
# sanity checking
if self._gpt_struct.size != self._gpt_size:
raise NoGPT("GPT format string wrong!")
# we assume we're searching, start with the bottom end
shiftLBA = lbaMinShift
lbaSize = 1<<shiftLBA
shiftLBA-=1
# search for the GPT, since block size is unknown
while shiftLBA < lbaMaxShift:
# non power of 2 sizes are illegal
shiftLBA+=1
lbaSize = 1<<shiftLBA
# try for a primary GPT
hbuf = buf[lbaSize:lbaSize<<1]
data = self.tryParseHeader(hbuf)
if data:
verbose("Found Primary GPT")
break
# try for a backup GPT
hbuf = buf[-lbaSize:]
data = self.tryParseHeader(hbuf)
if data:
verbose("Found Backup GPT")
break
else:
raise NoGPT("Failed to locate GPT")
self.shiftLBA = shiftLBA
if data['reserved'] != 0:
verbose("Warning: Reserved area non-zero")
self.revision = data['revision']
self.headerSize = data['headerSize']
self.reserved = data['reserved']
self.myLBA = data['myLBA']
self.altLBA = data['altLBA']
self.dataStartLBA = data['dataStartLBA']
self.dataEndLBA = data['dataEndLBA']
self.uuid = UUID(bytes=data['uuid'])
self.entryStart = data['entryStart']
self.entryCount = data['entryCount']
self.entrySize = data['entrySize']
self.entryCrc32 = data['entryCrc32']
if self.revision>>16 != 1:
raise NoGPT("Error: GPT major version isn't 1")
elif self.revision&0xFFFF != 0:
verbose("Warning: Newer GPT revision")
# these tests were against our version and may well fail
elif self.reserved != 0:
verbose("Warning: Reserved area non-zero")
# this is an error according to the specs
if (self.myLBA != 1) and (self.altLBA != 1):
raise NoGPT("Error: No GPT at LBA 1 ?!")
# this is an error according to the specs
if self.entrySize & (self.entrySize-1):
raise NoGPT("Error: entry size is not a power of 2")
if self.myLBA == 1:
sliceAddr = self.entryStart<<self.shiftLBA
else:
sliceAddr = (self.entryStart-self.myLBA-1)<<self.shiftLBA
self.slices = []
crc = 0
for i in range(self.entryCount):
sbuf = buf[sliceAddr:sliceAddr+self.entrySize]
crc = crc32(sbuf, crc)
slice = GPTSlice(sbuf)
self.slices.append(slice)
sliceAddr+=self.entrySize
crc &= 0xFFFFFFFF
if crc != self.entryCrc32:
raise NoGPT("Error: bad slice entry CRC")
last = 0
for slice in self.slices:
if slice.type == UUID(int=0):
continue
if slice.startLBA <= last:
verbose("Note: slices are out of order in GPT")
self.ordered = False
break
last = slice.endLBA
else:
self.ordered = True
if __name__ == "__main__":
verbose = lambda msg: print(msg)
progname = sys.argv[0]
del sys.argv[0]
for arg in sys.argv:
if arg == "-":
file = sys.stdin
else:
file = io.FileIO(arg, "rb")
# header is always in second LBA, slice entries in third
# if you run out of slice entries with a 64KB LBA, oy vey!
buf = file.read(1<<17+1<<16)
try:
gpt = GPT(buf)
gpt.display()
except NoGPT:
print(NoGPT, file=sys.stderr)