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
//! Iterator implementations for method instruction traversal.
//!
//! This module provides efficient iteration over method instructions without copying.
//! The main iterator yields instructions in execution order across all basic blocks,
//! enabling seamless analysis of the complete instruction stream.
//!
//! # Architecture Notes
//!
//! The iterator operates on a slice of basic blocks (`&[BasicBlock]`) rather than
//! a specific container type, providing flexibility and compatibility with both
//! `Vec<BasicBlock>` and other slice-like containers. This design supports the
//! Method struct's `OnceLock<Vec<BasicBlock>>` architecture while remaining generic.
//!
//! # Key Components
//!
//! - [`InstructionIterator`] - Iterator that yields instructions across all basic blocks
//!
//! # Thread Safety
//!
//! The iterator itself is not `Send` or `Sync` as it holds references to the underlying
//! data, but it can be safely created from thread-safe Method instances since it only
//! borrows immutable references to the blocks.
//!
//! # Examples
//!
//! ## Basic Iteration
//!
//! ```rust,no_run
//! use dotscope::CilObject;
//! use std::path::Path;
//!
//! let assembly = CilObject::from_path(Path::new("tests/samples/WindowsBase.dll"))?;
//! let methods = assembly.methods();
//!
//! for entry in methods.iter().take(5) {
//! let method = entry.value();
//! println!("Method: {} has {} instructions",
//! method.name, method.instruction_count());
//!
//! for (i, instruction) in method.instructions().enumerate() {
//! let operand_str = match &instruction.operand {
//! dotscope::assembly::Operand::None => String::new(),
//! _ => format!("{:?}", instruction.operand),
//! };
//! println!(" [{}] {} {}", i, instruction.mnemonic, operand_str);
//!
//! if i >= 5 { break; } // Limit for readability
//! }
//! }
//! # Ok::<(), dotscope::Error>(())
//! ```
//!
//! ## Combined with Block Analysis
//!
//! ```rust,no_run
//! use dotscope::CilObject;
//! use std::path::Path;
//!
//! let assembly = CilObject::from_path(Path::new("tests/samples/WindowsBase.dll"))?;
//! let methods = assembly.methods();
//!
//! for entry in methods.iter().take(3) {
//! let method = entry.value();
//! println!("Method: {} - {} blocks, {} total instructions",
//! method.name, method.block_count(), method.instruction_count());
//!
//! // Analyze each block separately
//! for (block_index, block) in method.blocks() {
//! println!(" Block {}: {} instructions", block_index, block.instructions.len());
//! }
//!
//! // Then iterate over all instructions linearly
//! let mut instruction_index = 0;
//! for instruction in method.instructions() {
//! if instruction.mnemonic.contains("call") {
//! println!(" Call instruction at index {}: {}",
//! instruction_index, instruction.mnemonic);
//! }
//! instruction_index += 1;
//! }
//! }
//! # Ok::<(), dotscope::Error>(())
//! ```
//!
//! # ECMA-335 References
//!
//! - §III.1 - CIL instruction set overview
//! - §III.3 - Base instructions (used during iteration analysis)
use crateBasicBlock;
/// Iterator over all instructions in a method, yielding them in execution order.
///
/// This iterator efficiently traverses all basic blocks in a method and yields
/// their instructions without copying. Instructions are yielded in the order
/// they would be executed (basic block order, then instruction order within blocks).
///
/// The iterator provides accurate size hints and handles empty basic blocks gracefully,
/// making it suitable for both simple iteration and collection operations.
///
/// # Architecture
///
/// The iterator operates on a slice of `BasicBlock`s (`&[BasicBlock]`), making it
/// compatible with the Method's `OnceLock<Vec<BasicBlock>>` storage while remaining
/// generic enough to work with other slice-like containers.
///
/// Internal state tracking:
/// - `current_block`: Index of the current basic block being processed
/// - `current_instruction`: Index within the current basic block's instruction vector
/// - Automatically advances to the next non-empty block when a block is exhausted
///
/// # Thread Safety
///
/// The iterator itself is not `Send` or `Sync` as it holds references to the underlying
/// instruction data. However, it can be safely created from thread-safe Method instances
/// since it only borrows immutable references.
///
/// # Examples
///
/// ## Basic Usage
///
/// ```rust,no_run
/// use dotscope::CilObject;
/// use std::path::Path;
///
/// let assembly = CilObject::from_path(Path::new("tests/samples/WindowsBase.dll"))?;
/// for entry in assembly.methods().iter().take(3) {
/// let method = entry.value();
/// let mut instruction_count = 0;
///
/// for instruction in method.instructions() {
/// println!("IL_{:04X}: {} {:?}",
/// instruction.offset, instruction.mnemonic, instruction.operand);
/// instruction_count += 1;
///
/// if instruction_count >= 10 { break; } // Limit for readability
/// }
///
/// println!("Method {} has {} total instructions",
/// method.name, method.instruction_count());
/// }
/// # Ok::<(), dotscope::Error>(())
/// ```
///
/// ## Collecting and Analyzing Instructions
///
/// ```rust,no_run
/// use dotscope::CilObject;
/// use std::path::Path;
///
/// let assembly = CilObject::from_path(Path::new("tests/samples/WindowsBase.dll"))?;
/// for entry in assembly.methods().iter().take(1) {
/// let method = entry.value();
///
/// // Use size hint for efficient pre-allocation
/// let (lower_bound, upper_bound) = method.instructions().size_hint();
/// println!("Expected {} to {:?} instructions", lower_bound, upper_bound);
///
/// // Collect specific instruction types
/// let call_instructions: Vec<_> = method.instructions()
/// .filter(|instr| instr.mnemonic.starts_with("call"))
/// .collect();
///
/// println!("Found {} call instructions in {}",
/// call_instructions.len(), method.name);
/// }
/// # Ok::<(), dotscope::Error>(())
/// ```
///
/// ## Iterator Combinators
///
/// ```rust,no_run
/// use dotscope::CilObject;
/// use std::path::Path;
///
/// let assembly = CilObject::from_path(Path::new("tests/samples/WindowsBase.dll"))?;
/// for entry in assembly.methods().iter().take(5) {
/// let method = entry.value();
///
/// // Count different instruction types
/// let branch_count = method.instructions()
/// .filter(|instr| instr.mnemonic.contains("br"))
/// .count();
///
/// let load_count = method.instructions()
/// .filter(|instr| instr.mnemonic.starts_with("ld"))
/// .count();
///
/// println!("{}: {} branches, {} loads",
/// method.name, branch_count, load_count);
/// }
/// # Ok::<(), dotscope::Error>(())
/// ```
///
/// Implementation of `ExactSizeIterator` trait.
///
/// This implementation is valid because the `size_hint()` method provides exact bounds
/// for the remaining number of instructions. This enables optimizations in standard
/// library collection methods and provides the `len()` method for getting the exact
/// remaining count.
///
/// # Benefits
///
/// - Enables `iter.len()` to get exact remaining instruction count
/// - Allows standard library to optimize collection operations
/// - Provides stronger guarantees for iterator consumers
/// - Compatible with parallel processing libraries that require exact sizes