-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathentry.py
More file actions
280 lines (214 loc) · 8.13 KB
/
entry.py
File metadata and controls
280 lines (214 loc) · 8.13 KB
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
#!/usr/bin/python
import types
from bindata import BinData
from bytestream import ByteStream
class Entry(object):
"""
Generic Entry
This class is used to generate other classes
dinamically that represents the target file
format
"""
"STUB: will be replaced during create() call"
attr_map = []
def __init__(self,bstream,offset=None):
"""Generic initialization of an entry structure"""
self.corrupted = False
self.attributes = []
self._prepare_stream(bstream,offset)
for item in self.attr_map:
self._add_attr(bstream,item)
def blob(self):
"""Serialize the bytes of the Entry"""
blob = bytearray('')
for attr in self.attributes:
blob += attr.data
return blob
def _prepare_stream(self,bstream,offset):
"""
Initialize the offset and mode the stream to it.
The offset should a BinData object to allow references to it
As so, an update in an offset will update all its the references.
"""
if offset == None:
offset = bstream.offset
if issubclass(offset.__class__,(types.IntType,)):
self.offset = BinData(4)
self.offset.init_data_from_int(offset)
elif issubclass(offset.__class__,(BinData,)):
self.offset = offset
elif (issubclass(offset.__class__,(Entry,)) and
'__int__' in dir(offset)):
self.offset = offset
else:
raise Exception('Invalid type for EntryList offset (%s) in class %s' %
(offset,self))
bstream.seek(int(self.offset))
def _get_size(self,bstream,size):
"""
Return an integer value based on the provided size.
Size can be an Integer, a BinData object, a method
in the format func(self,bstream) or an attribute name
"""
#size is a constant value
if issubclass(size.__class__,(types.IntType,)):
return size
elif issubclass(size.__class__,(BinData,)):
return int(size)
#size is calculated from method
elif (issubclass(size.__class__,(types.FunctionType,)) or
issubclass(size.__class__,(types.MethodType,))):
return size(self,bstream)
elif issubclass(size.__class__,(types.StringType,)):
#size is in another field from this entry
if size in self.__dict__.keys():
return int(self.__dict__[size])
#size is an evaluated expression
else:
return eval(size)
else:
raise Exception("Invalid size type in Entry.")
def _add_attr(self,bstream,attr_item):
"""
Parse all the structures in the attr_map and
initialize the attributes in the dictionary
"""
name = attr_item[0]
size = self._get_size(bstream,attr_item[1])
etype = attr_item[2]
#Raw binary data
if issubclass(etype,(BinData,)):
self.attributes.append(etype(size))
# No need to read if bytestream is already exhausted
if not bstream.exhausted:
self.attributes[-1].init_data(bstream.read(size))
#Entry subclass
elif issubclass(etype,Entry):
if size > 0:
self.attributes.append(etype(bstream))
else:
self.__dict__[name] = None
return
#Entry List
elif etype == EntryList:
if len(attr_item) < 4:
raise Exception("Missing value for entry %s" % name)
list_type = attr_item[3]
self.attributes.append(EntryList(bstream,list_type,size))
else:
raise Exception("Invalid type for entry field: %s" % etype)
#If we could not read, mark self as corrupted
if bstream.exhausted:
self.corrupted = True
#add attr name to dictionary
self.__dict__[name] = self.attributes[-1]
@staticmethod
def create(name,attr_map):
"""
Creates a specialized Entry
The attr_list should be a dictionaly with the
tuple [field_name,field_size,field_mode,extra]
field_name:
- String naming the field
field_size:
- Integer: Hardcode size in bytes
- function(bytestrem): A function that will be called on
target bytestream to get the size
- String: The name of another field previously read that provides
the size or an expression to be evaluated with eval()
that evaluates to an integer
field_mode:
- The BinData mode of the field
extra:
- for BinData: BinData mode
- for Entry: unused
- for EntryList: entry type of the list
"""
return type(name,(Entry,),{'attr_map':attr_map})
class EntryList(object):
"""
This class represents a linear list of entry structures
in the target file. The structures must be sequential in
the file and must be of the same type.
"""
def __init__(self,bstream,entry_type,size,offset=None):
"""
Parse an entry list from a bytestream
entry_type should be any Entry type generated
with Entry.create()
"""
self.data = []
self.corrupted = False
self.type = entry_type
#Set the entry offset
if offset == None:
self.offset = BinData(4)
self.offset.init_data_from_int(bstream.offset)
elif issubclass(offset.__class__,(types.IntType,)):
self.offset = BinData(4)
self.offset.init_data_from_int(offset)
elif issubclass(offset.__class__,(BinData,)):
self.offset = offset
else:
raise Exception('Invalid type for EntryList offset: %s' % offset.__class__)
bstream.seek(int(self.offset))
if issubclass(size.__class__,(types.IntType,)):
self.size = BinData(4)
self.size.init_data_from_int(size)
elif issubclass(size.__class__,(BinData,)):
self.size = size
else:
raise Exception('Invalid type for EntryList size: %s' % size.__class__)
for i in xrange(int(self.size)):
self.data.append(self.type(bstream))
if bstream.exhausted:
self.corrupted = True
break
def blob(self):
blob = bytearray('')
for entry in self.data:
blob += entry.blob()
return blob
def __getitem__(self, key):
if key >= 0 or key < len(self.data):
return self.data[key]
return None
def __setitem__(self, key, value):
if key >= 0 and key < len(self.data):
self.data[key] = value
class EntryTable(object):
"""
Given an EntryList, this class will itarate the list
and parse 'etype' structures using the 'offset_field'
attribute of the objects in the EntryList as offset
for parsing the object.
"""
def __init__(self,bstream,etype,elist=None,offset_field=None,ignore_offset=None):
self.corrupted = False
self.data = []
self.type = etype
self.parse_list(bstream,elist,offset_field,ignore_offset)
def parse_list(self,bstream,elist,offset_field,ignore_offset=None):
"""
Parse entries from an EntryList or and EntryTable
"""
if elist == None or offset_field == None:
return
for entry in elist.data:
offset = entry.__dict__[offset_field];
if ignore_offset != None and int(offset) == ignore_offset:
continue
self.parse_entry(bstream,offset)
def parse_entry(self,bstream,offset):
self.data.append(self.type(bstream,offset))
if bstream.exhausted:
self.corrupted = True
def __getitem__(self, key):
for entry in self.data:
if int(entry.offset) == int(key):
return entry
return None
def __setitem__(self, key, value):
for i,item in enumerate(self.data):
if int(item.offset) == int(offset):
self.data[i] = value