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
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
mod block;
mod enums;
mod instr;
#[cfg(test)]
mod tests;
use crate::block_enc::block::*;
pub use crate::block_enc::enums::*;
use crate::block_enc::instr::*;
use crate::iced_constants::IcedConstants;
use crate::iced_error::IcedError;
use crate::*;
use alloc::rc::Rc;
use alloc::vec::Vec;
use core::cell::RefCell;
use core::{mem, u32};
#[cfg(not(feature = "std"))]
use hashbrown::HashMap;
#[cfg(feature = "std")]
use std::collections::HashMap;
#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
pub struct RelocInfo {
pub address: u64,
pub kind: RelocKind,
}
impl RelocInfo {
#[must_use]
#[inline]
pub fn new(kind: RelocKind, address: u64) -> Self {
Self { address, kind }
}
}
#[derive(Debug)]
pub struct InstructionBlock<'a> {
instructions: &'a [Instruction],
rip: u64,
}
impl<'a> InstructionBlock<'a> {
#[must_use]
#[inline]
pub fn new(instructions: &'a [Instruction], rip: u64) -> Self {
Self { instructions, rip }
}
}
#[derive(Debug)]
pub struct BlockEncoderResult {
pub rip: u64,
pub code_buffer: Vec<u8>,
pub reloc_infos: Vec<RelocInfo>,
pub new_instruction_offsets: Vec<u32>,
pub constant_offsets: Vec<ConstantOffsets>,
}
#[allow(missing_debug_implementations)]
pub struct BlockEncoder {
bitness: u32,
options: u32,
blocks: Vec<(Rc<RefCell<Block>>, Vec<Rc<RefCell<dyn Instr>>>)>,
null_encoder: Encoder,
to_instr: HashMap<u64, Rc<RefCell<dyn Instr>>>,
has_multiple_zero_ip_instrs: bool,
}
impl BlockEncoder {
fn bitness(&self) -> u32 {
self.bitness
}
fn fix_branches(&self) -> bool {
(self.options & BlockEncoderOptions::DONT_FIX_BRANCHES) == 0
}
fn new(bitness: u32, instr_blocks: &[InstructionBlock<'_>], options: u32) -> Result<Self, IcedError> {
if bitness != 16 && bitness != 32 && bitness != 64 {
return Err(IcedError::new("Invalid bitness"));
}
let mut this = Self {
bitness,
options,
blocks: Vec::with_capacity(instr_blocks.len()),
null_encoder: Encoder::try_new(bitness)?,
to_instr: HashMap::new(),
has_multiple_zero_ip_instrs: false,
};
let mut instr_count = 0;
for instr_block in instr_blocks {
let instructions = instr_block.instructions;
let block = Rc::new(RefCell::new(Block::new(
&this,
instr_block.rip,
if (options & BlockEncoderOptions::RETURN_RELOC_INFOS) != 0 { Some(Vec::new()) } else { None },
)?));
let mut instrs = Vec::with_capacity(instructions.len());
let mut ip = instr_block.rip;
for instruction in instructions {
let instr = InstrUtils::create(&mut this, Rc::clone(&block), instruction);
instr.borrow_mut().set_ip(ip);
instrs.push(Rc::clone(&instr));
instr_count += 1;
debug_assert!(instr.borrow().size() != 0);
ip = ip.wrapping_add(instr.borrow().size() as u64);
}
this.blocks.push((Rc::clone(&block), instrs));
}
this.blocks.sort_unstable_by(|a, b| a.0.borrow().rip.cmp(&b.0.borrow().rip));
this.to_instr = HashMap::with_capacity(instr_count);
for info in &this.blocks {
for instr in &info.1 {
let orig_ip = instr.borrow().orig_ip();
if this.to_instr.get(&orig_ip).is_some() {
if orig_ip != 0 {
return Err(IcedError::with_string(format!("Multiple instructions with the same IP: 0x{:X}", orig_ip)));
}
this.has_multiple_zero_ip_instrs = true;
} else {
let _ = this.to_instr.insert(orig_ip, Rc::clone(instr));
}
}
}
if this.has_multiple_zero_ip_instrs {
let _ = this.to_instr.remove(&0);
}
let mut tmp_blocks = mem::replace(&mut this.blocks, Vec::new());
for info in &mut tmp_blocks {
let mut ip = info.0.borrow().rip;
for instr in &mut info.1 {
let mut instr = instr.borrow_mut();
instr.set_ip(ip);
let old_size = instr.size();
instr.initialize(&this);
if instr.size() > old_size {
return Err(IcedError::new("Internal error"));
}
ip = ip.wrapping_add(instr.size() as u64);
}
}
this.blocks = tmp_blocks;
Ok(this)
}
#[inline]
pub fn encode(bitness: u32, block: InstructionBlock<'_>, options: u32) -> Result<BlockEncoderResult, IcedError> {
match Self::encode_slice(bitness, &[block], options) {
Ok(ref mut result_vec) => {
debug_assert_eq!(result_vec.len(), 1);
Ok(result_vec.remove(0))
}
Err(err) => Err(err),
}
}
#[inline]
pub fn encode_slice(bitness: u32, blocks: &[InstructionBlock<'_>], options: u32) -> Result<Vec<BlockEncoderResult>, IcedError> {
Self::new(bitness, blocks, options)?.encode2()
}
fn encode2(&mut self) -> Result<Vec<BlockEncoderResult>, IcedError> {
for _ in 0..1000 {
let mut updated = false;
for info in &mut self.blocks {
let mut ip = info.0.borrow().rip;
for instr in &mut info.1 {
let mut instr = instr.borrow_mut();
instr.set_ip(ip);
let old_size = instr.size();
if instr.optimize() {
let instr_size = instr.size();
if instr_size > old_size {
return Err(IcedError::new("Internal error"));
}
if instr_size < old_size {
updated = true;
}
} else if instr.size() != old_size {
return Err(IcedError::new("Internal error"));
}
ip = ip.wrapping_add(instr.size() as u64);
}
}
if !updated {
break;
}
}
for info in &mut self.blocks {
info.0.borrow_mut().initialize_data(&info.1);
}
let mut result_vec: Vec<BlockEncoderResult> = Vec::with_capacity(self.blocks.len());
for info in &mut self.blocks {
let mut block = info.0.borrow_mut();
let mut ip = block.rip;
let mut new_instruction_offsets: Vec<u32> =
if (self.options & BlockEncoderOptions::RETURN_NEW_INSTRUCTION_OFFSETS) != 0 { Vec::with_capacity(info.1.len()) } else { Vec::new() };
let mut constant_offsets: Vec<ConstantOffsets> =
if (self.options & BlockEncoderOptions::RETURN_CONSTANT_OFFSETS) != 0 { Vec::with_capacity(info.1.len()) } else { Vec::new() };
for instr in &mut info.1 {
let mut instr = instr.borrow_mut();
let buffer_pos = block.buffer_pos();
let is_original_instruction = if (self.options & BlockEncoderOptions::RETURN_CONSTANT_OFFSETS) != 0 {
let result = instr.encode(&mut block)?;
constant_offsets.push(result.0);
result.1
} else {
instr.encode(&mut block)?.1
};
let size = block.buffer_pos() - buffer_pos;
if size != instr.size() as usize {
return Err(IcedError::new("Internal error"));
}
if (self.options & BlockEncoderOptions::RETURN_NEW_INSTRUCTION_OFFSETS) != 0 {
new_instruction_offsets.push(if is_original_instruction { ip.wrapping_sub(block.rip) as u32 } else { u32::MAX });
}
ip = ip.wrapping_add(size as u64);
}
block.write_data()?;
result_vec.push(BlockEncoderResult {
rip: block.rip,
code_buffer: block.take_buffer(),
reloc_infos: block.take_reloc_infos(),
new_instruction_offsets,
constant_offsets,
});
block.dispose();
info.1.clear();
}
self.to_instr.clear();
if cfg!(debug_assertions) {
for info in &self.blocks {
if Rc::strong_count(&info.0) != 1 {
return Err(IcedError::new("Internal error"));
}
}
}
Ok(result_vec)
}
fn get_target(&self, instr: &dyn Instr, address: u64) -> TargetInstr {
if (address != 0 || !self.has_multiple_zero_ip_instrs) && instr.orig_ip() == address {
TargetInstr::new_owner()
} else {
self.to_instr.get(&address).map_or_else(|| TargetInstr::new_address(address), |instr| TargetInstr::new_instr(Rc::clone(instr)))
}
}
fn get_instruction_size(&mut self, instruction: &Instruction, ip: u64) -> u32 {
self.null_encoder.clear_buffer();
self.null_encoder.encode(instruction, ip).map_or_else(|_| IcedConstants::MAX_INSTRUCTION_LENGTH as u32, |len| len as u32)
}
}