hao 0.0.19

Read, edit, create and write .net assemblies
Documentation
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
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
//! CIL method bodies (ECMA-335 II.25.4, III): reading, editing and building them.
//!
//! A method's code is a [`MethodBody`]: a list of [`Instruction`]s (an
//! [`OpCode`] plus an [`Operand`]), its local variable types and its exception
//! handlers. Branches target instruction indices ([`Label`]), so a body can be
//! edited freely; byte offsets, short/long branch forms and `max_stack` are
//! worked out when the module is written.
//!
//! [`Emitter`] builds a body, resolving forward branches and `try` blocks. This
//! one computes `x * x` through a local:
//!
//! ```
//! use hao::dotnet::{
//!     il::{Emitter, OpCode},
//!     signature::TypeSig,
//! };
//!
//! let mut e = Emitter::new();
//! let square = e.declare_local(TypeSig::INT32);
//! e.ldarg(0).ldarg(0).op(OpCode::Mul).stloc(square);
//! e.ldloc(square).ret();
//! let body = e.finish();
//!
//! assert_eq!(body.locals, [TypeSig::INT32]);
//! let code: Vec<String> = body.instructions.iter().map(|i| i.opcode.to_string()).collect();
//! assert_eq!(code, ["ldarg.0", "ldarg.0", "mul", "stloc.0", "ldloc.0", "ret"]);
//! ```
//!
//! Set it as a method's [`body`](crate::dotnet::entries::Method::body). The
//! [`callchain!`](crate::callchain) and [`managed_body!`](crate::managed_body)
//! macros build common shapes of body declaratively.

pub mod callchain;
mod emitter;
pub mod managed_body;
mod opcodes;
mod reader;
mod writer;

pub use crate::callchain;
pub use crate::managed_body;
pub use callchain::ChainImports;
pub use emitter::{EmitLabel, Emitter};
pub use managed_body::{CallKind, ManagedLocal, ManagedMethod};
pub use opcodes::*;
pub(crate) use reader::{BodyReader, BodyResolver};
pub use writer::compute_max_stack;
pub(crate) use writer::{encode_body, BodyEncoder};

use crate::dotnet::{
    entries::{
        Entry, Field, MemberRef, Method, MethodSpec, TypeDef, TypeDefOrRef, TypeRef, TypeSpec,
    },
    signature::{MethodSig, TypeSig},
};

/// Index of an instruction in [`MethodBody::instructions`].
/// Equal to `instructions.len()` for the end of the method.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[cfg_attr(feature = "reflect", derive(facet::Facet))]
pub struct Label(pub usize);

/// A metadata token operand, resolved to its entry: the type, field or method
/// an instruction such as `call`, `ldfld` or `newarr` refers to.
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "reflect", derive(facet::Facet))]
#[cfg_attr(feature = "reflect", repr(C))]
pub enum MemberToken {
    /// A type defined in this module.
    TypeDef(Entry<TypeDef>),
    /// A type from another assembly or module.
    TypeRef(Entry<TypeRef>),
    /// A constructed type (generic instance, array, pointer).
    TypeSpec(Entry<TypeSpec>),
    /// A field defined in this module.
    Field(Entry<Field>),
    /// A method defined in this module.
    Method(Entry<Method>),
    /// A method or field of another type, by reference.
    MemberRef(Entry<MemberRef>),
    /// A generic method instance.
    MethodSpec(Entry<MethodSpec>),
}

impl From<&MemberToken> for MemberToken {
    fn from(value: &MemberToken) -> Self {
        value.clone()
    }
}

impl From<TypeDefOrRef> for MemberToken {
    fn from(value: TypeDefOrRef) -> Self {
        match value {
            TypeDefOrRef::TypeDef(t) => Self::TypeDef(t),
            TypeDefOrRef::TypeRef(t) => Self::TypeRef(t),
            TypeDefOrRef::TypeSpec(t) => Self::TypeSpec(t),
        }
    }
}

macro_rules! member_token_from {
    ($($variant:ident),*) => {$(
        impl From<Entry<$variant>> for MemberToken {
            fn from(value: Entry<$variant>) -> Self {
                Self::$variant(value)
            }
        }
    )*};
}

member_token_from!(TypeDef, TypeRef, TypeSpec, Field, Method, MemberRef, MethodSpec);

impl From<crate::dotnet::entries::MethodDefOrRef> for MemberToken {
    fn from(value: crate::dotnet::entries::MethodDefOrRef) -> Self {
        match value {
            crate::dotnet::entries::MethodDefOrRef::Method(m) => Self::Method(m),
            crate::dotnet::entries::MethodDefOrRef::MemberRef(m) => Self::MemberRef(m),
        }
    }
}

impl MemberToken {
    /// The token as a type, or `None` if it is a field or method.
    pub fn as_type(&self) -> Option<TypeDefOrRef> {
        Some(match self {
            Self::TypeDef(t) => TypeDefOrRef::TypeDef(t.clone()),
            Self::TypeRef(t) => TypeDefOrRef::TypeRef(t.clone()),
            Self::TypeSpec(t) => TypeDefOrRef::TypeSpec(t.clone()),
            _ => return None,
        })
    }

    /// The signature of a method operand, used to work out stack usage.
    pub fn method_sig(&self) -> Option<MethodSig> {
        match self {
            Self::Method(m) => Some(m.get().signature.clone()),
            Self::MemberRef(m) => match &m.get().signature {
                crate::dotnet::signature::MemberRefSig::Method(sig) => Some(sig.clone()),
                _ => None,
            },
            Self::MethodSpec(m) => match &m.get().method {
                crate::dotnet::entries::MethodDefOrRef::Method(m) => {
                    Some(m.get().signature.clone())
                }
                crate::dotnet::entries::MethodDefOrRef::MemberRef(m) => match &m.get().signature {
                    crate::dotnet::signature::MemberRefSig::Method(sig) => Some(sig.clone()),
                    _ => None,
                },
            },
            _ => None,
        }
    }
}

/// An instruction's operand. Which variant an opcode takes is given by its
/// [`OpCode::operand_type`].
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(feature = "reflect", derive(facet::Facet))]
#[cfg_attr(feature = "reflect", repr(C))]
pub enum Operand {
    /// No operand (`add`, `ret`, `ldarg.0`, ...).
    None,
    /// An `int32` immediate: `ldc.i4`, `ldc.i4.s` (which must fit in `i8`).
    Int32(i32),
    /// An `int64` immediate, for `ldc.i8`.
    Int64(i64),
    /// A `float32` immediate, for `ldc.r4`.
    Float32(f32),
    /// A `float64` immediate, for `ldc.r8`.
    Float64(f64),
    /// A branch target: the instruction the branch jumps to.
    Target(Label),
    /// The jump table of `switch`, one target per case.
    Switch(Vec<Label>),
    /// A local variable index (`ldloc.s`, `stloc`, `ldloca`, ...).
    Local(u16),
    /// An argument index (`ldarg.s`, `starg`, `ldarga`, ...). Index 0 is `this` in
    /// instance methods.
    Arg(u16),
    /// A type, field or method (`call`, `newobj`, `ldfld`, `box`, `ldtoken`, ...).
    Token(MemberToken),
    /// A string literal, for `ldstr`.
    String(String),
    /// The call-site signature of `calli`.
    Sig(MethodSig),
}

impl From<&str> for Operand {
    fn from(value: &str) -> Self {
        Self::String(value.into())
    }
}

impl From<String> for Operand {
    fn from(value: String) -> Self {
        Self::String(value)
    }
}

impl From<MemberToken> for Operand {
    fn from(value: MemberToken) -> Self {
        Self::Token(value)
    }
}

/// One IL instruction: an opcode and its operand.
///
/// Branch operands are instruction indices ([`Label`]), not byte offsets, so
/// instructions can be inserted and removed without re-encoding; offsets are
/// worked out when the body is written. The constructors pick the short form
/// where there is one.
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(feature = "reflect", derive(facet::Facet))]
pub struct Instruction {
    /// What the instruction does.
    pub opcode: OpCode,
    /// Its operand; [`Operand::None`] for opcodes that take none.
    pub operand: Operand,
}

impl Instruction {
    /// An instruction with any operand. Nothing checks that the operand fits the
    /// opcode.
    pub fn new(opcode: OpCode, operand: Operand) -> Self {
        Self { opcode, operand }
    }

    /// An instruction without an operand, e.g. `add` or `ldnull`.
    pub fn simple(opcode: OpCode) -> Self {
        Self::new(opcode, Operand::None)
    }

    /// `pop`: discards the top of the stack.
    pub fn pop() -> Self {
        Self::simple(OpCode::Pop)
    }

    /// `ret`: returns from the method, with the return value (if any) on the stack.
    pub fn ret() -> Self {
        Self::simple(OpCode::Ret)
    }

    /// `ldstr`: pushes a string literal.
    pub fn ldstr(value: impl Into<String>) -> Self {
        Self::new(OpCode::Ldstr, Operand::String(value.into()))
    }

    /// `call`: calls a method without virtual dispatch (static methods, base
    /// calls, value-type methods).
    pub fn call(method: impl Into<MemberToken>) -> Self {
        Self::new(OpCode::Call, Operand::Token(method.into()))
    }

    /// `callvirt`: calls an instance method with virtual dispatch and a null check.
    pub fn callvirt(method: impl Into<MemberToken>) -> Self {
        Self::new(OpCode::Callvirt, Operand::Token(method.into()))
    }

    /// Calls the native function at `address` with the arguments on the stack.
    /// `signature` is usually [`MethodSig::native`].
    pub fn call_native(address: usize, signature: MethodSig) -> [Self; 3] {
        [
            Self::new(OpCode::Ldc_I8, Operand::Int64(address as i64)),
            Self::simple(OpCode::Conv_I),
            Self::new(OpCode::Calli, Operand::Sig(signature)),
        ]
    }

    /// `newobj`: creates an object by calling `constructor` (a `.ctor`) and pushes it.
    pub fn newobj(constructor: impl Into<MemberToken>) -> Self {
        Self::new(OpCode::Newobj, Operand::Token(constructor.into()))
    }

    /// `ldc.i4` using the shortest encoding for `value`.
    pub fn ldc_i4(value: i32) -> Self {
        const SHORT: [OpCode; 10] = [
            OpCode::Ldc_I4_M1,
            OpCode::Ldc_I4_0,
            OpCode::Ldc_I4_1,
            OpCode::Ldc_I4_2,
            OpCode::Ldc_I4_3,
            OpCode::Ldc_I4_4,
            OpCode::Ldc_I4_5,
            OpCode::Ldc_I4_6,
            OpCode::Ldc_I4_7,
            OpCode::Ldc_I4_8,
        ];
        match value {
            -1..=8 => Self::simple(SHORT[(value + 1) as usize]),
            -128..=127 => Self::new(OpCode::Ldc_I4_S, Operand::Int32(value)),
            _ => Self::new(OpCode::Ldc_I4, Operand::Int32(value)),
        }
    }

    /// `ldarg` using the shortest encoding for `index`.
    pub fn ldarg(index: u16) -> Self {
        match index {
            0 => Self::simple(OpCode::Ldarg_0),
            1 => Self::simple(OpCode::Ldarg_1),
            2 => Self::simple(OpCode::Ldarg_2),
            3 => Self::simple(OpCode::Ldarg_3),
            4..=255 => Self::new(OpCode::Ldarg_S, Operand::Arg(index)),
            _ => Self::new(OpCode::Ldarg, Operand::Arg(index)),
        }
    }

    /// `ldloc` using the shortest encoding for `index`.
    pub fn ldloc(index: u16) -> Self {
        match index {
            0 => Self::simple(OpCode::Ldloc_0),
            1 => Self::simple(OpCode::Ldloc_1),
            2 => Self::simple(OpCode::Ldloc_2),
            3 => Self::simple(OpCode::Ldloc_3),
            4..=255 => Self::new(OpCode::Ldloc_S, Operand::Local(index)),
            _ => Self::new(OpCode::Ldloc, Operand::Local(index)),
        }
    }

    /// `stloc` using the shortest encoding for `index`.
    pub fn stloc(index: u16) -> Self {
        match index {
            0 => Self::simple(OpCode::Stloc_0),
            1 => Self::simple(OpCode::Stloc_1),
            2 => Self::simple(OpCode::Stloc_2),
            3 => Self::simple(OpCode::Stloc_3),
            4..=255 => Self::new(OpCode::Stloc_S, Operand::Local(index)),
            _ => Self::new(OpCode::Stloc, Operand::Local(index)),
        }
    }

    /// Encoded size in bytes.
    pub fn size(&self) -> usize {
        self.opcode.size()
            + match &self.operand {
                Operand::Switch(targets) => targets.len() * 4,
                _ => 0,
            }
    }
}

/// Byte offset of every instruction, plus one extra for the end of the code.
pub fn instruction_offsets(instructions: &[Instruction]) -> Vec<u32> {
    let mut offsets = Vec::with_capacity(instructions.len() + 1);
    let mut offset = 0;
    for instruction in instructions {
        offsets.push(offset);
        offset += instruction.size() as u32;
    }
    offsets.push(offset);
    offsets
}

/// What kind of exception handler an [`ExceptionHandler`] is.
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "reflect", derive(facet::Facet))]
#[cfg_attr(feature = "reflect", repr(C))]
pub enum HandlerKind {
    /// `catch (T)`: runs when the exception is a `T`.
    Catch(TypeDefOrRef),
    /// `catch when (...)`: the filter code starts at the label and decides
    /// whether the handler runs.
    Filter(Label),
    /// `finally`: always runs when the protected block exits.
    Finally,
    /// `fault`: runs only when the protected block exits by an exception.
    Fault,
}

/// A protected region of a method body and its handler. Ranges are
/// half-open: `try_start..try_end` and `handler_start..handler_end`.
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "reflect", derive(facet::Facet))]
pub struct ExceptionHandler {
    /// The kind of handler, with its catch type or filter.
    pub kind: HandlerKind,
    /// First instruction of the `try` block.
    pub try_start: Label,
    /// The instruction after the `try` block.
    pub try_end: Label,
    /// First instruction of the handler.
    pub handler_start: Label,
    /// The instruction after the handler.
    pub handler_end: Label,
}

impl ExceptionHandler {
    /// `"catch"`, `"filter"`, `"finally"` or `"fault"`.
    pub fn kind_name(&self) -> &'static str {
        match self.kind {
            HandlerKind::Catch(_) => "catch",
            HandlerKind::Filter(_) => "filter",
            HandlerKind::Finally => "finally",
            HandlerKind::Fault => "fault",
        }
    }
}

/// The IL code of a method: its locals, instructions and exception handlers.
///
/// Build one with [`Emitter`], or edit a loaded one in place with
/// [`insert`](Self::insert), [`prefix`](Self::prefix), [`postfix`](Self::postfix)
/// and [`remove`](Self::remove), which keep branch targets pointing at the same
/// instructions.
#[derive(Debug, Clone, PartialEq, Default)]
#[cfg_attr(feature = "reflect", derive(facet::Facet))]
pub struct MethodBody {
    /// The deepest the evaluation stack gets. Writing computes it again and uses
    /// the larger value, so `0` is fine for new bodies.
    pub max_stack: u16,
    /// Whether locals start zeroed (`localsinit`). Verifiable code needs it if
    /// there are locals; [`Emitter::declare_local`] sets it.
    pub init_locals: bool,
    /// Local variable types, indexed by `ldloc`/`stloc`.
    pub locals: Vec<TypeSig>,
    /// The code. [`Label`]s index into this.
    pub instructions: Vec<Instruction>,
    /// `try` regions, innermost first.
    pub exception_handlers: Vec<ExceptionHandler>,
}

impl MethodBody {
    fn remap_labels(&mut self, f: impl Fn(usize) -> usize) {
        let f = |l: &mut Label| l.0 = f(l.0);
        for instruction in &mut self.instructions {
            match &mut instruction.operand {
                Operand::Target(t) => f(t),
                Operand::Switch(targets) => targets.iter_mut().for_each(f),
                _ => {}
            }
        }
        for h in &mut self.exception_handlers {
            f(&mut h.try_start);
            f(&mut h.try_end);
            f(&mut h.handler_start);
            f(&mut h.handler_end);
            if let HandlerKind::Filter(start) = &mut h.kind {
                f(start);
            }
        }
    }

    /// Inserts instructions before `index`. Branches and exception ranges that
    /// pointed at `index` or later keep pointing at the same instructions.
    pub fn insert(&mut self, index: usize, instructions: impl IntoIterator<Item = Instruction>) {
        let new: Vec<Instruction> = instructions.into_iter().collect();
        let count = new.len();
        self.remap_labels(|l| if l >= index { l + count } else { l });
        self.instructions.splice(index..index, new);
    }

    /// Runs `instructions` when the method starts, before its original code.
    pub fn prefix(&mut self, instructions: impl IntoIterator<Item = Instruction>) {
        self.insert(0, instructions);
    }

    /// Runs the instructions from `postfix` before every `ret`, with the return
    /// value (if any) on the stack; they must leave the value to return. Branches
    /// to a `ret` run the postfix too.
    pub fn postfix(&mut self, postfix: impl Fn() -> Vec<Instruction>) {
        let rets: Vec<usize> = (0..self.instructions.len())
            .filter(|&i| self.instructions[i].opcode == OpCode::Ret)
            .collect();
        for ret in rets.into_iter().rev() {
            let mut code = postfix().into_iter();
            let Some(first) = code.next() else { return };
            // The `ret` becomes the postfix's first instruction, so branches to it run the postfix.
            self.instructions[ret] = first;
            self.insert(ret + 1, code.chain([Instruction::ret()]));
        }
    }

    /// Removes the instruction at `index`. Branches to it now target the next instruction.
    pub fn remove(&mut self, index: usize) -> Instruction {
        self.remap_labels(|l| if l > index { l - 1 } else { l });
        self.instructions.remove(index)
    }

    /// Replaces every operand equal to `from`, returning how many were replaced.
    pub fn replace_operand(&mut self, from: &Operand, to: Operand) -> usize {
        let mut count = 0;
        for instruction in &mut self.instructions {
            if instruction.operand == *from {
                instruction.operand = to.clone();
                count += 1;
            }
        }
        count
    }

    /// Index of the first instruction matching `f`.
    pub fn position(&self, f: impl Fn(&Instruction) -> bool) -> Option<usize> {
        self.instructions.iter().position(f)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn postfix_runs_before_every_return() {
        let mut body = MethodBody {
            instructions: vec![
                Instruction::ldarg(0),
                Instruction::new(OpCode::Brtrue_S, Operand::Target(Label(3))),
                Instruction::ldc_i4(1),
                Instruction::ret(),
            ],
            ..Default::default()
        };
        body.postfix(|| vec![Instruction::ldc_i4(5), Instruction::simple(OpCode::Add)]);
        let opcodes: Vec<OpCode> = body.instructions.iter().map(|i| i.opcode).collect();
        assert_eq!(
            opcodes,
            [
                OpCode::Ldarg_0,
                OpCode::Brtrue_S,
                OpCode::Ldc_I4_1,
                OpCode::Ldc_I4_5,
                OpCode::Add,
                OpCode::Ret
            ]
        );
        // The branch to the old `ret` now runs the postfix.
        assert_eq!(body.instructions[1].operand, Operand::Target(Label(3)));
    }

    #[test]
    fn insert_and_remove_keep_branch_targets() {
        let mut body = MethodBody {
            instructions: vec![
                Instruction::simple(OpCode::Nop),
                Instruction::new(OpCode::Br_S, Operand::Target(Label(0))),
                Instruction::simple(OpCode::Ret),
            ],
            exception_handlers: vec![ExceptionHandler {
                kind: HandlerKind::Finally,
                try_start: Label(0),
                try_end: Label(2),
                handler_start: Label(2),
                handler_end: Label(3),
            }],
            ..Default::default()
        };
        body.insert(
            0,
            [
                Instruction::simple(OpCode::Ldnull),
                Instruction::simple(OpCode::Pop),
            ],
        );
        assert_eq!(body.instructions[3].operand, Operand::Target(Label(2)));
        assert_eq!(body.exception_handlers[0].handler_end, Label(5));

        body.remove(2);
        assert_eq!(body.instructions[2].operand, Operand::Target(Label(2)));
        assert_eq!(body.exception_handlers[0].try_start, Label(2));
    }
}