summaryrefslogtreecommitdiff
path: root/rust/src/low_level_il.rs
blob: 12a74106484c174ea68416c341db5879e9ab50bd (plain)
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
// Copyright 2021-2026 Vector 35 Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

use std::borrow::Cow;
use std::fmt;
use std::fmt::{Debug, Display};
// TODO : provide some way to forbid emitting register reads for certain registers
// also writing for certain registers (e.g. zero register must prohibit il.set_reg and il.reg
// (replace with nop or const(0) respectively)
// requirements on load/store memory address sizes?
// can reg/set_reg be used with sizes that differ from what is in BNRegisterInfo?

use crate::architecture::{Architecture, Flag, RegisterId};
use crate::architecture::{CoreRegister, Register as ArchReg};
use crate::function::Location;

pub mod block;
pub mod expression;
pub mod function;
pub mod instruction;
pub mod lifting;
pub mod operation;

use self::expression::*;
use self::function::*;
use self::instruction::*;

/// Regular low-level IL, if you are not modifying the functions IL or needing SSA, use this.
pub type LowLevelILRegularFunction = LowLevelILFunction<Finalized, NonSSA>;
pub type LowLevelILRegularInstruction<'a> = LowLevelILInstruction<'a, Finalized, NonSSA>;
pub type LowLevelILRegularInstructionKind<'a> = LowLevelILInstructionKind<'a, Finalized, NonSSA>;
pub type LowLevelILRegularExpression<'a, ReturnType> =
    LowLevelILExpression<'a, Finalized, NonSSA, ReturnType>;
pub type LowLevelILRegularExpressionKind<'a> = LowLevelILExpressionKind<'a, Finalized, NonSSA>;

/// Mutable low-level IL, used when lifting in architectures and modifying IL in workflow activities.
pub type LowLevelILMutableFunction = LowLevelILFunction<Mutable, NonSSA>;
pub type LowLevelILMutableExpression<'a, ReturnType> =
    LowLevelILExpression<'a, Mutable, NonSSA, ReturnType>;

/// SSA Variant of low-level IL, this can never be mutated directly.
pub type LowLevelILSSAFunction = LowLevelILFunction<Finalized, SSA>;

#[derive(Copy, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct LowLevelILTempRegister {
    /// The temporary id for the register, this will **NOT** be the referenced id in the core.
    ///
    /// Do not attempt to pass this to the core. Use [`LowLevelILTempRegister::id`] instead.
    temp_id: RegisterId,
}

impl LowLevelILTempRegister {
    pub fn new(temp_id: u32) -> Self {
        Self {
            temp_id: RegisterId(temp_id),
        }
    }

    pub fn from_id(id: RegisterId) -> Option<Self> {
        match id.is_temporary() {
            true => {
                let temp_id = RegisterId(id.0 & 0x7fff_ffff);
                Some(Self { temp_id })
            }
            false => None,
        }
    }

    /// The temporary registers core id, with the temporary bit set.
    pub fn id(&self) -> RegisterId {
        RegisterId(self.temp_id.0 | 0x8000_0000)
    }
}

impl Debug for LowLevelILTempRegister {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        write!(f, "temp{}", self.temp_id)
    }
}

impl Display for LowLevelILTempRegister {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        Debug::fmt(self, f)
    }
}

impl TryFrom<RegisterId> for LowLevelILTempRegister {
    type Error = ();

    fn try_from(value: RegisterId) -> Result<Self, Self::Error> {
        Self::from_id(value).ok_or(())
    }
}

impl From<u32> for LowLevelILTempRegister {
    fn from(value: u32) -> Self {
        Self::new(value)
    }
}

#[derive(Copy, Clone, PartialEq, Eq)]
pub enum LowLevelILRegisterKind<R: ArchReg> {
    Arch(R),
    Temp(LowLevelILTempRegister),
}

impl<R: ArchReg> LowLevelILRegisterKind<R> {
    pub fn from_raw(arch: &impl Architecture<Register = R>, val: RegisterId) -> Option<Self> {
        match val.is_temporary() {
            true => {
                let temp_reg = LowLevelILTempRegister::from_id(val)?;
                Some(LowLevelILRegisterKind::Temp(temp_reg))
            }
            false => {
                let arch_reg = arch.register_from_id(val)?;
                Some(LowLevelILRegisterKind::Arch(arch_reg))
            }
        }
    }

    pub fn from_temp(temp: impl Into<LowLevelILTempRegister>) -> Self {
        LowLevelILRegisterKind::Temp(temp.into())
    }

    pub fn id(&self) -> RegisterId {
        match *self {
            LowLevelILRegisterKind::Arch(ref r) => r.id(),
            LowLevelILRegisterKind::Temp(temp) => temp.id(),
        }
    }

    pub fn name(&self) -> Cow<'_, str> {
        match *self {
            LowLevelILRegisterKind::Arch(ref r) => r.name(),
            LowLevelILRegisterKind::Temp(temp) => Cow::Owned(format!("temp{}", temp.temp_id)),
        }
    }
}

impl<R: ArchReg> Debug for LowLevelILRegisterKind<R> {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        match *self {
            LowLevelILRegisterKind::Arch(ref r) => r.fmt(f),
            LowLevelILRegisterKind::Temp(ref id) => Debug::fmt(id, f),
        }
    }
}

impl<R: ArchReg> Display for LowLevelILRegisterKind<R> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match *self {
            LowLevelILRegisterKind::Arch(ref r) => write!(f, "{}", r.name()),
            LowLevelILRegisterKind::Temp(ref id) => Display::fmt(id, f),
        }
    }
}

impl From<LowLevelILTempRegister> for LowLevelILRegisterKind<CoreRegister> {
    fn from(reg: LowLevelILTempRegister) -> Self {
        LowLevelILRegisterKind::Temp(reg)
    }
}

#[derive(Copy, Clone, Debug)]
pub struct LowLevelILSSARegister<R: ArchReg> {
    pub reg: LowLevelILRegisterKind<R>,
    /// The SSA version of the register.
    pub version: u32,
}

impl<R: ArchReg> LowLevelILSSARegister<R> {
    pub fn new(reg: LowLevelILRegisterKind<R>, version: u32) -> Self {
        Self { reg, version }
    }

    pub fn name(&self) -> Cow<'_, str> {
        self.reg.name()
    }

    pub fn id(&self) -> RegisterId {
        self.reg.id()
    }
}

impl<R: ArchReg> Display for LowLevelILSSARegister<R> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}#{}", self.reg, self.version)
    }
}

/// The kind of SSA register.
///
/// An SSA register can exist in two states:
///
/// - Full, e.g. `eax` on x86
/// - Partial, e.g. `al` on x86
///
/// If you intend to query for the ssa uses or definitions you must retrieve the physical register
/// using the function [`LowLevelILSSARegisterKind::physical_reg`] which will give you the actual
/// [`LowLevelILSSARegister`].
#[derive(Copy, Clone, Debug)]
pub enum LowLevelILSSARegisterKind<R: ArchReg> {
    /// A full register is one that is not aliasing another, such as `eax` on x86 or `rax` on x86_64.
    Full(LowLevelILSSARegister<R>),
    Partial {
        /// This is the non-aliased register.
        ///
        /// This register is what is used for dataflow, otherwise the backing storage of aliased registers
        /// like `al` on x86 would contain separate value information from the physical register `eax`.
        ///
        /// NOTE: While this is a [`LowLevelILSSARegister`] temporary registers are not allowed in partial
        /// assignments, so this will always be an actual architecture register.
        full_reg: LowLevelILSSARegister<R>,
        /// This is the aliased register.
        ///
        /// On x86 if the register `al` is used that would be considered a partial register, with the
        /// full register `eax` being used as the backing storage.
        partial_reg: CoreRegister,
    },
}

impl<R: ArchReg> LowLevelILSSARegisterKind<R> {
    pub fn new_full(kind: LowLevelILRegisterKind<R>, version: u32) -> Self {
        Self::Full(LowLevelILSSARegister::new(kind, version))
    }

    pub fn new_partial(
        full_reg: LowLevelILRegisterKind<R>,
        version: u32,
        partial_reg: CoreRegister,
    ) -> Self {
        Self::Partial {
            full_reg: LowLevelILSSARegister::new(full_reg, version),
            partial_reg,
        }
    }

    /// This is the non-aliased register used. This should be called when you intend to actually
    /// query for SSA dataflow information, as a partial register is prohibited from being used.
    ///
    /// # Example
    ///
    /// On x86 `al` in the LLIL SSA will have a physical register of `eax`.
    pub fn physical_reg(&self) -> LowLevelILSSARegister<R> {
        match *self {
            LowLevelILSSARegisterKind::Full(reg) => reg,
            LowLevelILSSARegisterKind::Partial { full_reg, .. } => full_reg,
        }
    }

    /// Gets the displayable register, for partial this will be the partial register name.
    ///
    /// # Example
    ///
    /// On x86 this will display "al" not "eax".
    pub fn name(&self) -> Cow<'_, str> {
        match *self {
            LowLevelILSSARegisterKind::Full(ref reg) => reg.reg.name(),
            LowLevelILSSARegisterKind::Partial {
                ref partial_reg, ..
            } => partial_reg.name(),
        }
    }
}

impl<R: ArchReg> AsRef<LowLevelILSSARegister<R>> for LowLevelILSSARegisterKind<R> {
    fn as_ref(&self) -> &LowLevelILSSARegister<R> {
        match self {
            LowLevelILSSARegisterKind::Full(reg) => reg,
            LowLevelILSSARegisterKind::Partial { full_reg, .. } => full_reg,
        }
    }
}

impl<R: ArchReg> From<LowLevelILSSARegister<R>> for LowLevelILSSARegisterKind<R> {
    fn from(value: LowLevelILSSARegister<R>) -> Self {
        LowLevelILSSARegisterKind::Full(value)
    }
}

impl<R: ArchReg> From<LowLevelILSSARegisterKind<R>> for LowLevelILSSARegister<R> {
    fn from(value: LowLevelILSSARegisterKind<R>) -> Self {
        match value {
            LowLevelILSSARegisterKind::Full(reg) => reg,
            LowLevelILSSARegisterKind::Partial { full_reg, .. } => full_reg,
        }
    }
}

#[derive(Copy, Clone, Debug)]
pub struct LowLevelILSSAFlag<F: Flag> {
    pub flag: F,
    pub version: u32,
}

impl<F: Flag> LowLevelILSSAFlag<F> {
    pub fn new(flag: F, version: u32) -> Self {
        Self { flag, version }
    }
}

#[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
pub enum VisitorAction {
    Descend,
    Sibling,
    Halt,
}