write_x86_64 0.2.0

Crate to help you write x86_64 assembly code
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
use std::io::Write;

use crate::reg::{Label, Operand};
use crate::traits::{Reg, Writable};

/// Various conditionals
///
/// Informations given as FLAGS = meaning after cmp
#[derive(Debug)]
pub enum Cond {
    /// Same as Z
    E,
    /// ZF = equal to 0
    Z,
    /// Same as NZ
    NE,
    /// not(ZF) = equal to 0
    NZ,
    /// SF = negative
    S,
    /// not(SF) = non-negative
    NS,
    /// not(SF xor OF) and not(ZF) = greater
    G,
    /// not(SF xor OF) = greater or equal
    GE,
    /// SF xor OF = lower
    L,
    /// (SF xor OF) or ZF = lower or equal
    LE,
    /// not(CF) and not(ZF) = above (unsigned greater)
    A,
    /// not(CF) = above or equal (unsigned greater or equal)
    AE,
    /// CF = below (unsigned lower)
    B,
    /// CF or ZF = below or equal (unsigned lower or equal)
    BE,
}

impl Cond {
    fn to_str(&self) -> &'static str {
        match self {
            Self::E => "e",
            Self::Z => "z",
            Self::NE => "ne",
            Self::NZ => "nz",
            Self::S => "s",
            Self::NS => "ns",
            Self::G => "g",
            Self::GE => "ge",
            Self::L => "l",
            Self::LE => "le",
            Self::A => "a",
            Self::AE => "ae",
            Self::B => "b",
            Self::BE => "be",
        }
    }
}

/// Various instructions names
#[derive(Debug)]
pub enum InstrName {
    /// Move operation
    Move,
    /// Add operation
    Add,
    /// Substration
    Sub,
    /// Bitwise And
    And,
    /// Bitwise Or
    Or,
    /// Bitwise Xor
    Xor,
    /// Left shift
    Shl,
    /// Logical right shift
    Shr,
    /// Arithmetic right shift
    Sar,
    /// Compare (set flags based on Sub instr)
    Cmp,
    /// Test  (set flags based on And instr)
    Test,
    /// Compute address and stores the address instead of value pointed
    Lea,
    /// Signed multiplication
    IMul,

    /// Sign extend move
    Movs,
    /// Fill with zeros move
    Movz,
    /// Logical shift left
    ShlC,
    /// Logical shift right
    ShrC,

    /// Increment value
    Inc,
    /// Decrement value
    Dec,
    /// Arithmetic negation
    Neg,
    /// Bitwise negation
    Not,
    /// Push on stack
    Push,
    /// Pop from stack
    Pop,
    /// Unsigned division (beware of edx/rdc register)
    UnsignedDiv,
    /// Signed division (beware of edx/rdc register)
    SignedDiv,

    /// Equivalent to popq rip
    Ret,
    /// Complex return from call
    Leave,
    /// Syscall
    Syscall,
    /// Hlt instruction
    Hlt,
    /// Sign extend %eax into %edx::%eax
    Cltd,
    /// Sign extend %rax into %rdx::%rax
    Cqto,
    /// Does nothing
    Nop,
    /// Conditionnal move
    Cmov(Cond),
    /// Call label
    Call(Label),
    /// Call address
    CallStar,
    /// Conditionnal jump
    CondJump(Cond, Label),
    /// Jump to label
    Jump(Label),
    /// Jump to address
    JumpStar,
    /// Set operand to 0 or 1 based on the condition
    Set(Cond),
}

impl Writable for InstrName {
    fn write_in(&self, file: &mut std::fs::File) -> std::io::Result<()> {
        match self {
            InstrName::Move => file.write_all(b"mov"),
            InstrName::Add => file.write_all(b"add"),
            InstrName::Sub => file.write_all(b"sub"),
            InstrName::And => file.write_all(b"and"),
            InstrName::Or => file.write_all(b"or"),
            InstrName::Xor => file.write_all(b"xor"),
            InstrName::Shl => file.write_all(b"shl"),
            InstrName::Shr => file.write_all(b"shr"),
            InstrName::Sar => file.write_all(b"sar"),
            InstrName::Cmp => file.write_all(b"cmp"),
            InstrName::Test => file.write_all(b"test"),
            InstrName::Lea => file.write_all(b"lea"),
            InstrName::IMul => file.write_all(b"imul"),
            InstrName::Movs => file.write_all(b"movs"),
            InstrName::Movz => file.write_all(b"movz"),
            InstrName::ShlC => file.write_all(b"shl"),
            InstrName::ShrC => file.write_all(b"shr"),
            InstrName::Inc => file.write_all(b"inc"),
            InstrName::Dec => file.write_all(b"dec"),
            InstrName::Neg => file.write_all(b"neg"),
            InstrName::Not => file.write_all(b"not"),
            InstrName::Push => file.write_all(b"push"),
            InstrName::Pop => file.write_all(b"pop"),
            InstrName::UnsignedDiv => file.write_all(b"div"),
            InstrName::SignedDiv => file.write_all(b"idiv"),
            InstrName::Ret => file.write_all(b"ret"),
            InstrName::Leave => file.write_all(b"leave"),
            InstrName::Syscall => file.write_all(b"syscall"),
            InstrName::Hlt => file.write_all(b"hlt"),
            InstrName::Cltd => file.write_all(b"cltd"),
            InstrName::Cqto => file.write_all(b"cqto"),
            InstrName::Nop => file.write_all(b"nop"),
            InstrName::Cmov(cond) => {
                file.write_all(b"cmov")?;
                file.write_all(cond.to_str().as_bytes())
            }
            InstrName::Call(label) => {
                file.write_all(b"call ")?;
                label.write_in(file)
            }
            InstrName::CallStar => file.write_all(b"call *"),
            InstrName::CondJump(cond, label) => {
                file.write_all(b"j")?;
                file.write_all(cond.to_str().as_bytes())?;
                file.write_all(b" ")?;
                label.write_in(file)
            }
            InstrName::Jump(label) => {
                file.write_all(b"jmp ")?;
                label.write_in(file)
            }
            InstrName::JumpStar => file.write_all(b"jmp *"),
            InstrName::Set(cond) => {
                file.write_all(b"set")?;
                file.write_all(cond.to_str().as_bytes())
            }
        }
    }
}

impl InstrName {
    fn nb_args(&self) -> usize {
        match self {
            InstrName::Move
            | InstrName::Add
            | InstrName::Sub
            | InstrName::And
            | InstrName::Or
            | InstrName::Xor
            | InstrName::Shl
            | InstrName::Shr
            | InstrName::Sar
            | InstrName::Cmp
            | InstrName::Test
            | InstrName::Lea
            | InstrName::IMul => 2,
            InstrName::Movs | InstrName::Movz | InstrName::ShlC | InstrName::ShrC => 2,
            InstrName::Inc
            | InstrName::Dec
            | InstrName::Neg
            | InstrName::Not
            | InstrName::Push
            | InstrName::Pop
            | InstrName::UnsignedDiv
            | InstrName::SignedDiv => 1,
            InstrName::Ret
            | InstrName::Leave
            | InstrName::Syscall
            | InstrName::Hlt
            | InstrName::Cltd
            | InstrName::Cqto
            | InstrName::Nop => 0,
            InstrName::Cmov(_) => 2,
            InstrName::Call(_) => 0,
            InstrName::CallStar => 1,
            InstrName::CondJump(_, _) => 0,
            InstrName::Jump(_) => 0,
            InstrName::JumpStar => 1,
            InstrName::Set(_) => 1,
        }
    }

    fn print_size_1(&self) -> bool {
        match self {
            InstrName::Move
            | InstrName::Add
            | InstrName::Sub
            | InstrName::And
            | InstrName::Or
            | InstrName::Xor
            | InstrName::Shl
            | InstrName::Shr
            | InstrName::Sar
            | InstrName::Cmp
            | InstrName::Test
            | InstrName::Lea
            | InstrName::IMul => false,
            InstrName::Movs | InstrName::Movz => true,
            InstrName::ShlC | InstrName::ShrC => false,
            InstrName::Inc
            | InstrName::Dec
            | InstrName::Neg
            | InstrName::Not
            | InstrName::Push
            | InstrName::Pop
            | InstrName::UnsignedDiv
            | InstrName::SignedDiv => true,
            InstrName::Ret
            | InstrName::Leave
            | InstrName::Syscall
            | InstrName::Hlt
            | InstrName::Cltd
            | InstrName::Cqto
            | InstrName::Nop => false,
            InstrName::Cmov(_) => false,
            InstrName::Call(_) => false,
            InstrName::CallStar => false,
            InstrName::CondJump(_, _) => false,
            InstrName::Jump(_) => false,
            InstrName::JumpStar => false,
            InstrName::Set(_) => false,
        }
    }

    fn print_size_2(&self) -> bool {
        match self {
            InstrName::Move
            | InstrName::Add
            | InstrName::Sub
            | InstrName::And
            | InstrName::Or
            | InstrName::Xor
            | InstrName::Shl
            | InstrName::Shr
            | InstrName::Sar
            | InstrName::Cmp
            | InstrName::Test
            | InstrName::Lea
            | InstrName::IMul => true,
            InstrName::Movs | InstrName::Movz => true,
            InstrName::ShlC | InstrName::ShrC => true,
            InstrName::Inc
            | InstrName::Dec
            | InstrName::Neg
            | InstrName::Not
            | InstrName::Push
            | InstrName::Pop
            | InstrName::UnsignedDiv
            | InstrName::SignedDiv => false,
            InstrName::Ret
            | InstrName::Leave
            | InstrName::Syscall
            | InstrName::Hlt
            | InstrName::Cltd
            | InstrName::Cqto
            | InstrName::Nop => false,
            InstrName::Cmov(_) => false,
            InstrName::Call(_) => false,
            InstrName::CallStar => false,
            InstrName::CondJump(_, _) => false,
            InstrName::Jump(_) => false,
            InstrName::JumpStar => false,
            InstrName::Set(_) => false,
        }
    }

    fn add_space(&self) -> bool {
        match self {
            InstrName::CallStar | InstrName::JumpStar => false,
            _ => true,
        }
    }
}

/// Structure storing the instruction name and a most 2 operands.
/// To type with less than 2 operands use the type RegInv which can never be used for real operands
pub struct Instruction<S1: Reg = crate::reg::RegInv, S2: Reg = crate::reg::RegInv> {
    /// Instruction name
    pub instr: InstrName,
    /// First operand if exists
    pub reg1: Option<Operand<S1>>,
    /// Second operand if exists
    pub reg2: Option<Operand<S2>>,
}

/// Trait to wrap around all instructions types
pub trait InstrTrait {
    /// Write the instruction in a file
    fn write_instr(&self, file: &mut std::fs::File) -> std::io::Result<()>;
}

impl<S1: Reg, S2: Reg> InstrTrait for Instruction<S1, S2> {
    fn write_instr(&self, file: &mut std::fs::File) -> std::io::Result<()> {
        self.instr.write_in(file)?;
        if self.instr.print_size_1() {
            file.write_all(&[S1::SIZE.to_char() as u8])?;
        }
        if self.instr.print_size_2() {
            file.write_all(&[S2::SIZE.to_char() as u8])?;
        }
        if self.instr.nb_args() >= 1 {
            if self.instr.add_space() {
                file.write_all(b" ")?
            };
            self.reg1.as_ref().unwrap().write_in(file)?;
        } else {
            if self.reg1.is_some() {
                panic!(
                    "Instruction {:?} expects 0 arguments but received a least 1",
                    self.instr
                )
            }
        }
        if self.instr.nb_args() >= 2 {
            file.write_all(b", ")?;
            self.reg2.as_ref().unwrap().write_in(file)?;
        } else {
            if self.reg2.is_some() {
                panic!(
                    "Instruction {:?} expects at most 1 arguments but received a second argument",
                    self.instr
                )
            }
        }
        std::io::Result::Ok(())
    }
}

/// Type representing an instruction
pub type Instr = Box<dyn InstrTrait>;

impl Writable for Instr {
    fn write_in(&self, file: &mut std::fs::File) -> std::io::Result<()> {
        self.write_instr(file)
    }
}