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
// SPDX-License-Identifier: MIT
// Copyright (C) 2018-present iced project and contributors

pub(crate) mod cpuid_table;
pub(crate) mod enums;
pub(crate) mod factory;
pub(crate) mod info_table;
pub(crate) mod rflags_table;
#[cfg(test)]
mod tests;

use crate::iced_constants::IcedConstants;
pub use crate::info::factory::*;
use crate::*;
use alloc::vec::Vec;
use core::fmt;

/// A register used by an instruction
#[derive(Default, Copy, Clone, Eq, PartialEq, Hash)]
pub struct UsedRegister {
	register: Register,
	access: OpAccess,
}

impl UsedRegister {
	/// Creates a new instance
	///
	/// # Arguments
	///
	/// * `register`: Register
	/// * `access`: Register access
	#[must_use]
	#[inline]
	pub const fn new(register: Register, access: OpAccess) -> Self {
		Self { register, access }
	}

	/// Gets the register
	#[must_use]
	#[inline]
	pub const fn register(&self) -> Register {
		self.register
	}

	/// Gets the register access
	#[must_use]
	#[inline]
	pub const fn access(&self) -> OpAccess {
		self.access
	}
}

impl fmt::Debug for UsedRegister {
	#[allow(clippy::missing_inline_in_public_items)]
	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
		write!(f, "{:?}:{:?}", self.register(), self.access())?;
		Ok(())
	}
}

/// A memory location used by an instruction
#[derive(Default, Copy, Clone, Eq, PartialEq, Hash)]
pub struct UsedMemory {
	displacement: u64,
	segment: Register,
	base: Register,
	index: Register,
	scale: u8,
	memory_size: MemorySize,
	access: OpAccess,
	address_size: CodeSize,
	vsib_size: u8,
}

impl UsedMemory {
	/// Creates a new instance
	///
	/// # Arguments
	///
	/// * `segment`: Effective segment register or [`Register::None`] if the segment register is ignored
	/// * `base`: Base register
	/// * `index`: Index register
	/// * `scale`: 1, 2, 4 or 8
	/// * `displacement`: Displacement
	/// * `memory_size`: Memory size
	/// * `access`: Access
	///
	/// [`Register::None`]: enum.Register.html#variant.None
	#[must_use]
	#[inline]
	pub const fn new(
		segment: Register, base: Register, index: Register, scale: u32, displacement: u64, memory_size: MemorySize, access: OpAccess,
	) -> Self {
		Self { segment, base, index, scale: scale as u8, displacement, memory_size, access, address_size: CodeSize::Unknown, vsib_size: 0 }
	}

	/// Creates a new instance
	///
	/// # Arguments
	///
	/// * `segment`: Effective segment register or [`Register::None`] if the segment register is ignored
	/// * `base`: Base register
	/// * `index`: Index register
	/// * `scale`: 1, 2, 4 or 8
	/// * `displacement`: Displacement
	/// * `memory_size`: Memory size
	/// * `access`: Access
	/// * `address_size`: Address size
	/// * `vsib_size`: VSIB size (`0`, `4` or `8`)
	///
	/// [`Register::None`]: enum.Register.html#variant.None
	#[must_use]
	#[inline]
	pub fn new2(
		segment: Register, base: Register, index: Register, scale: u32, displacement: u64, memory_size: MemorySize, access: OpAccess,
		address_size: CodeSize, vsib_size: u32,
	) -> Self {
		debug_assert!(vsib_size == 0 || vsib_size == 4 || vsib_size == 8);
		Self { segment, base, index, scale: scale as u8, displacement, memory_size, access, address_size, vsib_size: vsib_size as u8 }
	}

	/// Effective segment register or [`Register::None`] if the segment register is ignored
	///
	/// [`Register::None`]: enum.Register.html#variant.None
	#[must_use]
	#[inline]
	pub const fn segment(&self) -> Register {
		self.segment
	}

	/// Base register or [`Register::None`] if none
	///
	/// [`Register::None`]: enum.Register.html#variant.None
	#[must_use]
	#[inline]
	pub const fn base(&self) -> Register {
		self.base
	}

	/// Index register or [`Register::None`] if none
	///
	/// [`Register::None`]: enum.Register.html#variant.None
	#[must_use]
	#[inline]
	pub const fn index(&self) -> Register {
		self.index
	}

	/// Index scale (1, 2, 4 or 8)
	#[must_use]
	#[inline]
	pub const fn scale(&self) -> u32 {
		self.scale as u32
	}

	/// Displacement
	#[must_use]
	#[inline]
	pub const fn displacement(&self) -> u64 {
		self.displacement
	}

	/// Size of location
	#[must_use]
	#[inline]
	pub const fn memory_size(&self) -> MemorySize {
		self.memory_size
	}

	/// Memory access
	#[must_use]
	#[inline]
	pub const fn access(&self) -> OpAccess {
		self.access
	}

	/// Address size
	#[must_use]
	#[inline]
	pub const fn address_size(&self) -> CodeSize {
		self.address_size
	}

	/// VSIB size (`0`, `4` or `8`)
	#[must_use]
	#[inline]
	pub const fn vsib_size(&self) -> u32 {
		self.vsib_size as u32
	}

	/// Gets the virtual address of a used memory location, or `None` if register resolution fails.
	///
	/// # Arguments
	///
	/// * `get_register_value`: Function that returns the value of a register or the base address of a segment register, or `None` on failure.
	///
	/// # Call-back function args
	///
	/// * Arg 1: `register`: Register. If it's a segment register, the call-back should return the segment's base address, not the segment's register value.
	/// * Arg 2: `element_index`: Only used if it's a vsib memory operand. This is the element index of the vector index register.
	/// * Arg 3: `element_size`: Only used if it's a vsib memory operand. Size in bytes of elements in vector index register (4 or 8).
	#[must_use]
	#[inline]
	pub fn virtual_address<F>(&self, element_index: usize, get_register_value: F) -> Option<u64>
	where
		F: FnMut(Register, usize, usize) -> Option<u64>,
	{
		self.try_virtual_address(element_index, get_register_value)
	}

	#[must_use]
	#[inline]
	#[doc(hidden)]
	pub fn try_virtual_address<F>(&self, element_index: usize, mut get_register_value: F) -> Option<u64>
	where
		F: FnMut(Register, usize, usize) -> Option<u64>,
	{
		let mut effective = self.displacement;

		match self.base {
			Register::None => {}
			_ => {
				let base = get_register_value(self.base, 0, 0)?;
				effective = effective.wrapping_add(base)
			}
		}

		match self.index {
			Register::None => {}
			_ => {
				let mut index = get_register_value(self.index, element_index, self.vsib_size as usize)?;
				if self.vsib_size == 4 {
					index = index as i32 as u64;
				}
				effective = effective.wrapping_add(index.wrapping_mul(self.scale as u64))
			}
		}

		match self.address_size {
			CodeSize::Code16 => effective = effective as u16 as u64,
			CodeSize::Code32 => effective = effective as u32 as u64,
			_ => {}
		}

		match self.segment {
			Register::None => {}
			_ => {
				let segment_base = get_register_value(self.segment, 0, 0)?;
				effective = effective.wrapping_add(segment_base)
			}
		}

		Some(effective)
	}
}

impl fmt::Debug for UsedMemory {
	#[allow(clippy::missing_inline_in_public_items)]
	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
		write!(f, "[{:?}:", self.segment())?;
		let mut need_plus = if self.base() != Register::None {
			write!(f, "{:?}", self.base())?;
			true
		} else {
			false
		};
		if self.index() != Register::None {
			if need_plus {
				write!(f, "+")?;
			}
			need_plus = true;
			write!(f, "{:?}", self.index())?;
			if self.scale() != 1 {
				write!(f, "*{}", self.scale())?;
			}
		}
		if self.displacement() != 0 || !need_plus {
			if need_plus {
				write!(f, "+")?;
			}
			if self.displacement() <= 9 {
				write!(f, "{}", self.displacement())?;
			} else {
				write!(f, "0x{:X}", self.displacement())?;
			}
		}
		write!(f, ";{:?};{:?}]", self.memory_size(), self.access())?;
		Ok(())
	}
}

/// Contains information about an instruction, eg. read/written registers and memory locations, operand accesses.
/// Created by an [`InstructionInfoFactory`].
///
/// [`InstructionInfoFactory`]: struct.InstructionInfoFactory.html
#[derive(Debug, Clone)]
pub struct InstructionInfo {
	used_registers: Vec<UsedRegister>,
	used_memory_locations: Vec<UsedMemory>,
	op_accesses: [OpAccess; IcedConstants::MAX_OP_COUNT],
}

impl InstructionInfo {
	#[must_use]
	#[inline(always)]
	fn new(options: u32) -> Self {
		use crate::info::enums::InstrInfoConstants;
		Self {
			used_registers: if (options & InstructionInfoOptions::NO_REGISTER_USAGE) == 0 {
				Vec::with_capacity(InstrInfoConstants::DEFAULT_USED_REGISTER_COLL_CAPACITY)
			} else {
				Vec::new()
			},
			used_memory_locations: if (options & InstructionInfoOptions::NO_MEMORY_USAGE) == 0 {
				Vec::with_capacity(InstrInfoConstants::DEFAULT_USED_MEMORY_COLL_CAPACITY)
			} else {
				Vec::new()
			},
			op_accesses: [OpAccess::default(); IcedConstants::MAX_OP_COUNT],
		}
	}

	/// Gets all accessed registers. This method doesn't return all accessed registers if [`is_save_restore_instruction()`] is `true`.
	///
	/// Some instructions have a `r16`/`r32` operand but only use the low 8 bits of the register. In that case
	/// this method returns the 8-bit register even if it's `SPL`, `BPL`, `SIL`, `DIL` and the
	/// instruction was decoded in 16 or 32-bit mode. This is more accurate than returning the `r16`/`r32`
	/// register. Example instructions that do this: `PINSRB`, `ARPL`
	///
	/// [`is_save_restore_instruction()`]: #method.is_save_restore_instruction
	#[must_use]
	#[inline]
	pub fn used_registers(&self) -> &[UsedRegister] {
		self.used_registers.as_slice()
	}

	/// Gets all accessed memory locations
	#[must_use]
	#[inline]
	pub fn used_memory(&self) -> &[UsedMemory] {
		self.used_memory_locations.as_slice()
	}

	/// Operand #0 access
	#[must_use]
	#[inline]
	pub const fn op0_access(&self) -> OpAccess {
		self.op_accesses[0]
	}

	/// Operand #1 access
	#[must_use]
	#[inline]
	pub const fn op1_access(&self) -> OpAccess {
		self.op_accesses[1]
	}

	/// Operand #2 access
	#[must_use]
	#[inline]
	pub const fn op2_access(&self) -> OpAccess {
		self.op_accesses[2]
	}

	/// Operand #3 access
	#[must_use]
	#[inline]
	pub const fn op3_access(&self) -> OpAccess {
		self.op_accesses[3]
	}

	/// Operand #4 access
	#[must_use]
	#[inline]
	pub const fn op4_access(&self) -> OpAccess {
		self.op_accesses[4]
	}

	/// Gets operand access
	///
	/// # Arguments
	///
	/// * `operand`: Operand number, 0-4
	#[must_use]
	#[inline]
	pub fn op_access(&self, operand: u32) -> OpAccess {
		match self.op_accesses.get(operand as usize) {
			Some(&value) => value,
			None => {
				debug_assert!(false, "Invalid operand: {}", operand);
				OpAccess::default()
			}
		}
	}

	#[inline]
	#[doc(hidden)]
	pub fn try_op_access(&self, operand: u32) -> Result<OpAccess, IcedError> {
		self.op_accesses.get(operand as usize).map_or_else(|| Err(IcedError::new("Invalid operand")), |&op_access| Ok(op_access))
	}
}