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
391
use crate::abstract_state::{AbstractValue, BorrowState};
use move_binary_format::file_format::{AbilitySet, Bytecode, Signature, SignatureToken};
use rand::{rngs::StdRng, Rng};
use std::collections::{HashMap, VecDeque};
use tracing::debug;
type BlockIDSize = u16;
type BlockLocals = HashMap<usize, (AbstractValue, BorrowState)>;
#[derive(Debug, Default, Clone)]
pub struct BasicBlock {
locals_in: BlockLocals,
locals_out: BlockLocals,
instructions: Vec<Bytecode>,
}
impl BasicBlock {
pub fn new() -> BasicBlock {
BasicBlock {
locals_in: HashMap::new(),
locals_out: HashMap::new(),
instructions: Vec::new(),
}
}
pub fn get_locals_in(&self) -> &BlockLocals {
&self.locals_in
}
pub fn get_locals_out(&self) -> &BlockLocals {
&self.locals_out
}
pub fn set_instructions(&mut self, instructions: Vec<Bytecode>) {
self.instructions = instructions
}
}
#[derive(Debug, Clone)]
pub struct CFG {
basic_blocks: HashMap<BlockIDSize, BasicBlock>,
edges: Vec<(BlockIDSize, BlockIDSize)>,
}
impl CFG {
pub fn new(
rng: &mut StdRng,
locals: &[SignatureToken],
parameters: &Signature,
target_blocks: BlockIDSize,
) -> CFG {
checked_precondition!(target_blocks > 0, "The CFG must haave at least one block");
let mut basic_blocks: HashMap<BlockIDSize, BasicBlock> = HashMap::new();
for i in 0..target_blocks {
basic_blocks.insert(i, BasicBlock::new());
}
let mut edges: Vec<(BlockIDSize, BlockIDSize)> = Vec::new();
let mut block_queue: VecDeque<BlockIDSize> = VecDeque::new();
let mut current_block_id = 0;
block_queue.push_back(current_block_id);
current_block_id += 1;
while current_block_id < target_blocks && !block_queue.is_empty() {
let front_block = block_queue.pop_front();
assume!(front_block.is_some());
let parent_block_id = front_block.unwrap();
assume!(edges.len() < usize::max_value());
edges.push((parent_block_id, current_block_id));
block_queue.push_back(current_block_id);
verify!(current_block_id < u16::max_value());
current_block_id += 1;
if rng.gen_bool(0.5) && current_block_id < target_blocks {
verify!(edges.len() < usize::max_value());
edges.push((parent_block_id, current_block_id));
block_queue.push_back(current_block_id);
verify!(current_block_id < u16::max_value());
current_block_id += 1;
}
}
while !block_queue.is_empty() {
let front_block = block_queue.pop_front();
assume!(front_block.is_some());
let parent_block_id = front_block.unwrap();
assume!(target_blocks > 0);
if parent_block_id != target_blocks - 1 {
edges.push((parent_block_id, target_blocks - 1));
}
}
debug!("Edges: {:?}", edges);
let mut cfg = CFG {
basic_blocks,
edges,
};
assume!(target_blocks == 0 || !cfg.basic_blocks.is_empty());
CFG::add_locals(&mut cfg, rng, locals, parameters.0.len());
cfg
}
pub fn get_basic_blocks(&self) -> &HashMap<BlockIDSize, BasicBlock> {
&self.basic_blocks
}
pub fn get_basic_blocks_mut(&mut self) -> &mut HashMap<BlockIDSize, BasicBlock> {
&mut self.basic_blocks
}
pub fn get_children_ids(&self, block_id: BlockIDSize) -> Vec<BlockIDSize> {
let mut children_ids: Vec<BlockIDSize> = Vec::new();
for (parent, child) in self.edges.iter() {
if *parent == block_id {
verify!(children_ids.len() < usize::max_value());
children_ids.push(*child);
}
}
children_ids
}
pub fn num_children(&self, block_id: BlockIDSize) -> u8 {
self.get_children_ids(block_id).len() as u8
}
pub fn get_parent_ids(&self, block_id: BlockIDSize) -> Vec<BlockIDSize> {
let mut parent_ids: Vec<BlockIDSize> = Vec::new();
for (parent, child) in self.edges.iter() {
if *child == block_id {
verify!(parent_ids.len() < usize::max_value());
parent_ids.push(*parent);
}
}
parent_ids
}
pub fn num_parents(&self, block_id: BlockIDSize) -> u8 {
self.get_parent_ids(block_id).len() as u8
}
fn merge_locals(&self, block_ids: Vec<BlockIDSize>) -> BlockLocals {
checked_precondition!(
!block_ids.is_empty(),
"Cannot merge locals of empty block list"
);
let first_basic_block = self.basic_blocks.get(&block_ids[0]);
assume!(first_basic_block.is_some());
let first_basic_block_locals_out = &first_basic_block.unwrap().locals_out;
let locals_len = first_basic_block_locals_out.len();
let mut locals_out = BlockLocals::new();
for local_index in 0..locals_len {
let abstract_value = first_basic_block_locals_out[&local_index].0.clone();
let mut availability = BorrowState::Available;
for block_id in block_ids.iter() {
let basic_block = self.basic_blocks.get(block_id);
assume!(basic_block.is_some());
if basic_block.unwrap().locals_out[&local_index].1 == BorrowState::Unavailable {
availability = BorrowState::Unavailable;
}
}
locals_out.insert(local_index, (abstract_value, availability));
}
locals_out
}
fn vary_locals(rng: &mut StdRng, locals: BlockLocals) -> BlockLocals {
let mut locals = locals;
for (_, (abstr_val, availability)) in locals.iter_mut() {
if rng.gen_bool(0.5) {
if *availability == BorrowState::Available {
*availability = BorrowState::Unavailable;
} else {
*availability = BorrowState::Available;
}
}
if abstr_val.is_generic() {
*availability = BorrowState::Unavailable;
}
}
locals
}
fn add_locals(cfg: &mut CFG, rng: &mut StdRng, locals: &[SignatureToken], args_len: usize) {
precondition!(
!cfg.basic_blocks.is_empty(),
"Cannot add locals to empty cfg"
);
debug!("add locals: {:#?}", locals);
for block_id in 0..cfg.basic_blocks.len() {
let cfg_copy = cfg.clone();
let basic_block = cfg
.basic_blocks
.get_mut(&(block_id as BlockIDSize))
.unwrap();
if cfg_copy.num_parents(block_id as BlockIDSize) == 0 {
basic_block.locals_in = locals
.iter()
.enumerate()
.map(|(i, token)| {
let borrow_state = if i < args_len {
BorrowState::Available
} else {
BorrowState::Unavailable
};
(
i,
(
AbstractValue::new_value(token.clone(), AbilitySet::PRIMITIVES),
borrow_state,
),
)
})
.collect();
} else {
assume!(!cfg_copy.basic_blocks.is_empty());
basic_block.locals_in =
cfg_copy.merge_locals(cfg_copy.get_parent_ids(block_id as BlockIDSize));
}
basic_block.locals_out = CFG::vary_locals(rng, basic_block.locals_in.clone());
}
}
pub fn serialize_block_order(&self) -> Vec<BlockIDSize> {
let mut block_order: Vec<BlockIDSize> = Vec::new();
let mut block_queue: VecDeque<BlockIDSize> = VecDeque::new();
block_queue.push_back(0);
while !block_queue.is_empty() {
let block_id_front = block_queue.pop_front();
assume!(block_id_front.is_some());
let block_id = block_id_front.unwrap();
let child_ids = self.get_children_ids(block_id);
if child_ids.len() == 2 {
block_queue.push_front(child_ids[0]);
block_queue.push_back(child_ids[1]);
} else if child_ids.len() == 1 {
block_queue.push_back(child_ids[0]);
} else if !child_ids.is_empty() {
unreachable!(
"Invalid number of children for basic block {:?}",
child_ids.len()
);
}
if !block_order.contains(&block_id) {
block_order.push(block_id);
}
}
debug!("Block order: {:?}", block_order);
block_order
}
fn get_block_offset(cfg: &CFG, block_order: &[BlockIDSize], block_id: BlockIDSize) -> u16 {
checked_assume!(
(0..block_id).all(|id| cfg.basic_blocks.get(&id).is_some()),
"Error: Invalid block_id given"
);
let mut offset: u16 = 0;
for i in block_order {
if *i == block_id {
break;
}
if let Some(block) = cfg.basic_blocks.get(i) {
offset += block.instructions.len() as u16;
}
}
offset
}
pub fn serialize(&mut self) -> Vec<Bytecode> {
checked_precondition!(
!self.basic_blocks.is_empty(),
"Error: CFG has no basic blocks"
);
let cfg_copy = self.clone();
let mut bytecode: Vec<Bytecode> = Vec::new();
let block_order = self.serialize_block_order();
for block_id in &block_order {
let block = self.basic_blocks.get_mut(block_id);
assume!(block.is_some());
let block = block.unwrap();
checked_assume!(
!block.instructions.is_empty(),
"Error: block created with no instructions",
);
let last_instruction_index = block.instructions.len() - 1;
let child_ids = cfg_copy.get_children_ids(*block_id);
if child_ids.len() == 2 {
let offset = CFG::get_block_offset(&cfg_copy, &block_order, child_ids[1]);
match block.instructions.last() {
Some(Bytecode::BrTrue(_)) => {
block.instructions[last_instruction_index] =
Bytecode::BrTrue(offset as u16);
}
Some(Bytecode::BrFalse(_)) => {
block.instructions[last_instruction_index] =
Bytecode::BrFalse(offset as u16);
}
_ => unreachable!(
"Error: unsupported two target jump instruction, {:#?}",
block.instructions.last()
),
};
} else if child_ids.len() == 1 {
let offset = CFG::get_block_offset(&cfg_copy, &block_order, child_ids[0]);
match block.instructions.last() {
Some(Bytecode::Branch(_)) => {
block.instructions[last_instruction_index] = Bytecode::Branch(offset);
}
_ => unreachable!(
"Error: unsupported one target jump instruction, {:#?}",
block.instructions.last()
),
}
}
bytecode.extend(block.instructions.clone());
}
debug!("Final bytecode: {:#?}", bytecode);
bytecode
}
}