-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
javavm_memory.py
390 lines (314 loc) · 15.8 KB
/
javavm_memory.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
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
import binascii
import logging
import os
from .. import concretization_strategies
from ..engines.soot.values import (SimSootValue_ArrayRef,
SimSootValue_InstanceFieldRef,
SimSootValue_Local, SimSootValue_ParamRef,
SimSootValue_StaticFieldRef,
SimSootValue_StringRef)
from ..errors import SimMemoryAddressError, SimUnsatError
from ..sim_state import SimState
from ..storage.memory import SimMemory
from .keyvalue_memory import SimKeyValueMemory
from .plugin import SimStatePlugin
l = logging.getLogger("angr.state_plugins.javavm_memory")
MAX_ARRAY_SIZE = 1000 # FIXME arbitrarily chosen limit
class SimJavaVmMemory(SimMemory):
def __init__(self, memory_id="mem", stack=None, heap=None, vm_static_table=None,
load_strategies=None, store_strategies=None):
super(SimJavaVmMemory, self).__init__()
self.id = memory_id
self._stack = [] if stack is None else stack
self.heap = SimKeyValueMemory("mem") if heap is None else heap
self.vm_static_table = SimKeyValueMemory("mem") if vm_static_table is None else vm_static_table
# Heap helper
# TODO: ask someone how we want to manage this
# TODO: Manage out of memory allocation
# self._heap_allocation_id = 0
self.max_array_size = MAX_ARRAY_SIZE
# concretizing strategies
self.load_strategies = load_strategies if load_strategies else []
self.store_strategies = store_strategies if store_strategies else []
@staticmethod
def get_new_uuid():
"""
Generate a unique id within the scope of the JavaVM memory. This, for
example, is used for distinguishing memory objects of the same type
(e.g. multiple instances of the same class).
"""
# self._heap_allocation_id += 1
# return str(self._heap_allocation_id)
return binascii.hexlify(os.urandom(4))
def store(self, addr, data, frame=0): # pylint: disable=arguments-differ
if type(addr) is SimSootValue_Local:
cstack = self._stack[-1+(-1*frame)]
cstack.store(addr.id, data, type_=addr.type)
elif type(addr) is SimSootValue_ParamRef:
cstack = self._stack[-1+(-1*frame)]
cstack.store(addr.id, data, type_=addr.type)
elif type(addr) is SimSootValue_ArrayRef:
self.store_array_element(addr.base, addr.index, data)
elif type(addr) is SimSootValue_StaticFieldRef:
self.vm_static_table.store(addr.id, data, type_=addr.type)
elif type(addr) is SimSootValue_InstanceFieldRef:
self.heap.store(addr.id, data, type_=addr.type)
elif type(addr) is SimSootValue_StringRef:
self.heap.store(addr.id, data, type_=addr.type)
else:
l.error("Unknown addr type %s", addr)
def load(self, addr, frame=0, none_if_missing=False): # pylint: disable=arguments-differ
if type(addr) is SimSootValue_Local:
cstack = self._stack[-1+(-1*frame)]
return cstack.load(addr.id, none_if_missing=none_if_missing)
elif type(addr) is SimSootValue_ArrayRef:
return self.load_array_element(addr.base, addr.index)
elif type(addr) is SimSootValue_ParamRef:
cstack = self._stack[-1+(-1*frame)]
return cstack.load(addr.id, none_if_missing=none_if_missing)
elif type(addr) is SimSootValue_StaticFieldRef:
value = self.vm_static_table.load(addr.id, none_if_missing=none_if_missing)
if value is None:
# initialize field
value = self.state.project.simos.get_default_value_by_type(addr.type, state=self.state)
l.debug("Initializing static field %s with %s.", addr, value)
self.store(addr, value)
return value
elif type(addr) is SimSootValue_InstanceFieldRef:
value = self.heap.load(addr.id, none_if_missing=none_if_missing)
if value is None:
# initialize field
value = self.state.project.simos.get_default_value_by_type(addr.type, state=self.state)
l.debug("Initializing field %s with %s.", addr, value)
self.store(addr, value)
return value
elif type(addr) is SimSootValue_StringRef:
return self.heap.load(addr.id, none_if_missing=none_if_missing)
else:
l.error("Unknown addr type %s", addr)
return None
def push_stack_frame(self):
self._stack.append(SimKeyValueMemory("mem"))
def pop_stack_frame(self):
self._stack = self._stack[:-1]
@property
def stack(self):
return self._stack[-1]
#
# Array // Store
#
def store_array_element(self, array, idx, value):
self.store_array_elements(array, idx, value)
def store_array_elements(self, array, start_idx, data):
"""
Stores either a single element or a range of elements in the array.
:param array: Reference to the array.
:param start_idx: Starting index for the store.
:param data: Either a single value or a list of values.
"""
# we process data as a list of elements
# => if there is only a single element, wrap it in a list
data = data if isinstance(data, list) else [data]
# concretize start index
concrete_start_idxes = self.concretize_store_idx(start_idx)
if len(concrete_start_idxes) == 1:
# only one start index
# => concrete store
concrete_start_idx = concrete_start_idxes[0]
for i, value in enumerate(data):
self._store_array_element_on_heap(array=array,
idx=concrete_start_idx+i,
value=value,
value_type=array.element_type)
# if the index was symbolic before concretization, this
# constraint it to concrete start idx
self.state.solver.add(concrete_start_idx == start_idx)
else:
# multiple start indexes
# => symbolic store
start_idx_options = []
for concrete_start_idx in concrete_start_idxes:
start_idx_options.append(concrete_start_idx == start_idx)
# we store elements condtioned with the start index:
# => if concrete_start_idx == start_idx
# then store the value
# else keep the current value
for i, value in enumerate(data):
self._store_array_element_on_heap(array=array,
idx=concrete_start_idx+i,
value=value,
value_type=array.element_type,
store_condition=start_idx_options[-1])
# constraint start_idx, s.t. it evals to one of the concretized indexes
constraint_on_start_idx = self.state.solver.Or(*start_idx_options)
self.state.add_constraints(constraint_on_start_idx)
def _store_array_element_on_heap(self, array, idx, value, value_type, store_condition=None):
heap_elem_id = '%s[%d]' % (array.id, idx)
l.debug("Set %s to %s with condition %s", heap_elem_id, value, store_condition)
if store_condition is not None:
current_value = self._load_array_element_from_heap(array, idx)
new_value = value
value = self.state.solver.If(store_condition, new_value, current_value)
self.heap.store(heap_elem_id, value, value_type)
#
# Array // Load
#
def load_array_element(self, array, idx):
return self.load_array_elements(array, idx, 1)[0]
def load_array_elements(self, array, start_idx, no_of_elements):
"""
Loads either a single element or a range of elements from the array.
:param array: Reference to the array.
:param start_idx: Starting index for the load.
:param no_of_elements: Number of elements to load.
"""
# concretize start index
concrete_start_idxes = self.concretize_load_idx(start_idx)
if len(concrete_start_idxes) == 1:
# only one start index
# => concrete load
concrete_start_idx = concrete_start_idxes[0]
load_values = [self._load_array_element_from_heap(array, idx)
for idx in range(concrete_start_idx, concrete_start_idx+no_of_elements)]
# if the index was symbolic before concretization, this
# constraint it to concrete start idx
self.state.solver.add(start_idx == concrete_start_idx)
else:
# multiple start indexes
# => symbolic load
# start with load values for the first concrete index
concrete_start_idx = concrete_start_idxes[0]
load_values = [self._load_array_element_from_heap(array, idx)
for idx in range(concrete_start_idx, concrete_start_idx+no_of_elements)]
start_idx_options = [concrete_start_idx == start_idx]
# update load values with all remaining start indexes
for concrete_start_idx in concrete_start_idxes[1:]:
# load values for this start index
values = [self._load_array_element_from_heap(array, idx)
for idx in range(concrete_start_idx, concrete_start_idx+no_of_elements)]
# update load values with the new ones
for i, value in enumerate(values):
# condition every value with the start idx
# => if concrete_start_idx == start_idx
# then use new value
# else use the current value
load_values[i] = self.state.solver.If(
concrete_start_idx == start_idx,
value,
load_values[i]
)
start_idx_options.append(start_idx == concrete_start_idx)
# constraint start_idx, s.t. it evals to one of the concretized indexes
constraint_on_start_idx = self.state.solver.Or(*start_idx_options)
self.state.add_constraints(constraint_on_start_idx)
return load_values
def _load_array_element_from_heap(self, array, idx):
# try to load the element
heap_elem_id = '%s[%d]' % (array.id, idx)
value = self.heap.load(heap_elem_id, none_if_missing=True)
# if it's not available, initialize it
if value is None:
value = array.get_default_value(self.state)
l.debug("Init %s with %s", heap_elem_id, value)
element_type = value.element_type if hasattr(value, 'element_type') else None
self.heap.store(heap_elem_id, value, type_=element_type)
else:
l.debug("Load %s from %s", heap_elem_id, value)
return value
#
# Concretization strategies
#
def _apply_concretization_strategies(self, idx, strategies, action): # pylint: disable=unused-argument
"""
Applies concretization strategies on the index, until one of them succeeds.
"""
for s in strategies:
try:
idxes = s.concretize(self, idx)
except SimUnsatError:
idxes = None
if idxes:
return idxes
raise SimMemoryAddressError("Unable to concretize index %s" % idx)
def concretize_store_idx(self, idx, strategies=None):
"""
Concretizes a store index.
:param idx: An expression for the index.
:param strategies: A list of concretization strategies (to override the default).
:param min_idx: Minimum value for a concretized index (inclusive).
:param max_idx: Maximum value for a concretized index (exclusive).
:returns: A list of concrete indexes.
"""
if isinstance(idx, int):
return [idx]
elif not self.state.solver.symbolic(idx):
return [self.state.solver.eval(idx)]
strategies = self.store_strategies if strategies is None else strategies
return self._apply_concretization_strategies(idx, strategies, 'store')
def concretize_load_idx(self, idx, strategies=None):
"""
Concretizes a load index.
:param idx: An expression for the index.
:param strategies: A list of concretization strategies (to override the default).
:param min_idx: Minimum value for a concretized index (inclusive).
:param max_idx: Maximum value for a concretized index (exclusive).
:returns: A list of concrete indexes.
"""
if isinstance(idx, int):
return [idx]
elif not self.state.solver.symbolic(idx):
return [self.state.solver.eval(idx)]
strategies = self.load_strategies if strategies is None else strategies
return self._apply_concretization_strategies(idx, strategies, 'load')
def _create_default_load_strategies(self):
# reset dict
self.load_strategies = []
# symbolically read up to 1024 elements
s = concretization_strategies.SimConcretizationStrategyRange(1024)
self.load_strategies.append(s)
# if range is too big, fallback to load only one arbitrary element
s = concretization_strategies.SimConcretizationStrategyAny()
self.load_strategies.append(s)
def _create_default_store_strategies(self):
# reset dict
self.store_strategies = []
# symbolically write up to 256 elements
s = concretization_strategies.SimConcretizationStrategyRange(256)
self.store_strategies.append(s)
# if range is too big, fallback to store only the last element
s = concretization_strategies.SimConcretizationStrategyMax()
self.store_strategies.append(s)
#
# MISC
#
def set_state(self, state):
super(SimJavaVmMemory, self).set_state(state)
if not self.load_strategies:
self._create_default_load_strategies()
if not self.store_strategies:
self._create_default_store_strategies()
@SimStatePlugin.memo
def copy(self, memo): # pylint: disable=unused-argument
return SimJavaVmMemory(
memory_id=self.id,
stack=[stack_frame.copy() for stack_frame in self._stack],
heap=self.heap.copy(),
vm_static_table=self.vm_static_table.copy(),
load_strategies=[s.copy() for s in self.load_strategies],
store_strategies=[s.copy() for s in self.store_strategies]
)
def merge(self, others, merge_conditions, common_ancestor=None): # pylint: disable=unused-argument
l.warning("Merging is not implemented for JavaVM memory!")
return False
def widen(self, others): # pylint: disable=unused-argument
l.warning("Widening is not implemented for JavaVM memory!")
return False
def _find(self, addr, what, max_search=None, max_symbolic_bytes=None, default=None, step=1): # pylint: disable=unused-argument
l.warning("Find is not implemented for JavaVM memory!")
return None
def _load(self, _addr, _size, condition=None, fallback=None, # pylint: disable=unused-argument
inspect=True, events=True, ret_on_segv=False):
raise NotImplementedError("JavaVM memory overwrites load function directly.")
def _store(self, _request): # pylint: disable=unused-argument
raise NotImplementedError("JavaVM memory overwrites store function directly.")
SimState.register_default('javavm_memory', SimJavaVmMemory)