luadec 0.2.0

A Lua 5.1 bytecode decompiler library, originated from lbcdec
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
560
561
562
563
564
565
566
567
568
// Generic reverse register allocator
// Attempts to derive meaning from register allocation information
// Takes a list of instructions and returns a list of information for each instruction

use log::trace;

use crate::instruction_definitions::{LuaInstruction, InstructionInfo, RegOrTop, Reg};

#[derive(Debug, PartialEq, Eq)]
pub enum InstructionClass {
    /// Stack-based instructions "pop" a specified number of arguments, off the stack at their base
    /// Afterwards, they may "push" a specified number of return results, leaving the rest of the register
    /// stack undefined.
    /// Some instructions may choose to output like a free-form instruction (see CONCAT).
    Stack,
    /// Free-form instructions can use any allocated register as input and output to any allocated register (or next free register).
    FreeForm
}

impl Default for InstructionClass {
    fn default() -> Self {
        InstructionClass::FreeForm
    }
}

#[derive(Debug, PartialEq, Eq)]
enum FreeFormRegType {
    Incoming,
    Outgoing
}

#[derive(Debug, PartialEq, Eq, Copy, Clone)]
enum FreeFormReg {
    None,
    Initial(Reg),
    Concrete(Reg),
}

impl FreeFormReg {
    fn is_none(&self) -> bool {
        match self {
            FreeFormReg::None => true,
            _ => false,
        }
    }

    fn as_reg(&self) -> Option<Reg> {
        match *self {
            FreeFormReg::None => None,
            FreeFormReg::Initial(reg) | FreeFormReg::Concrete(reg) => Some(reg),
        }
    }
}

#[derive(Debug)]
struct FreeFormData {
    incoming: FreeFormReg,
    outgoing: FreeFormReg,
}

#[derive(Debug)]
struct StackData {
    incoming: RegOrTop,
    outgoing: RegOrTop,
    info: InstructionInfo,
}

#[derive(Debug)]
enum Data {
    FreeForm(FreeFormData),
    Stack(StackData),
}

impl Data {
    fn stack(&self) -> Option<&StackData> {
        if let Data::Stack(data) = self {
            Some(data)
        } else {
            None
        }
    }

    fn free_form(&self) -> Option<&FreeFormData> {
        if let Data::FreeForm(data) = self {
            Some(data)
        } else {
            None
        }
    }

    fn stack_mut(&mut self) -> Option<&mut StackData> {
        if let Data::Stack(data) = self {
            Some(data)
        } else {
            None
        }
    }

    fn free_form_mut(&mut self) -> Option<&mut FreeFormData> {
        if let Data::FreeForm(data) = self {
            Some(data)
        } else {
            None
        }
    }
}

#[derive(Debug)]
struct Info {
    data: Data,
    redirect: Option<usize>,
}

impl Info {
    fn class(&self) -> InstructionClass {
        match self.data {
            Data::FreeForm(..) => InstructionClass::FreeForm,
            Data::Stack(..) => InstructionClass::Stack,
        }
    }

    fn pc(&self, pc: usize) -> usize {
        self.redirect.unwrap_or(pc)
    }

    fn incoming(&self) -> Option<Reg> {
        match &self.data {
            Data::FreeForm(data) => match data.incoming {
                FreeFormReg::None => None,
                FreeFormReg::Initial(reg) => Some(reg),
                FreeFormReg::Concrete(reg) => Some(reg),
            },
            Data::Stack(data) => match data.incoming {
                RegOrTop::Reg(reg) => Some(reg),
                RegOrTop::Top => panic!("Use incoming_or_top for varargs support"),
            }
        }
    }

    fn incoming_or_top(&self) -> Option<RegOrTop> {
        match &self.data {
            Data::FreeForm(data) => match data.incoming {
                FreeFormReg::None => None,
                FreeFormReg::Initial(reg) => Some(RegOrTop::Reg(reg)),
                FreeFormReg::Concrete(reg) => Some(RegOrTop::Reg(reg)),
            },
            Data::Stack(data) => Some(data.incoming)
        }
    }

    fn outgoing(&self) -> Option<Reg> {
        match &self.data {
            Data::FreeForm(data) => match data.outgoing {
                FreeFormReg::None => None,
                FreeFormReg::Initial(reg) => Some(reg),
                FreeFormReg::Concrete(reg) => Some(reg),
            },
            Data::Stack(data) => match data.outgoing {
                RegOrTop::Reg(reg) => Some(reg),
                RegOrTop::Top => panic!("Use outgoing_or_top for varargs support"),
            }
        }
    }

    fn outgoing_or_top(&self) -> Option<RegOrTop> {
        match &self.data {
            Data::FreeForm(data) => match data.outgoing {
                FreeFormReg::None => None,
                FreeFormReg::Initial(reg) => Some(RegOrTop::Reg(reg)),
                FreeFormReg::Concrete(reg) => Some(RegOrTop::Reg(reg)),
            },
            Data::Stack(data) => Some(data.outgoing)
        }
    }
}

/// Stack instructions are common, they control the placement of scopes.
/// Without them, we can't determine anything.

#[derive(Default, Debug)]
pub struct InstrInfo {
    class: InstructionClass,
    incoming: Option<RegOrTop>,
    outgoing: Option<RegOrTop>,
    info: Option<InstructionInfo>,
    in_newtable: bool,
    redirect: Option<usize>,
}

struct RAllocCtx<'a> {
    decoded: &'a [LuaInstruction],
    info: Vec<Info>,
}

pub struct RAllocData {
    info: Vec<Info>,
}

impl RAllocData {
    pub fn incoming_free_mark_at(&self, pc: usize) -> Option<Reg> {
        self.info[pc].incoming_or_top().and_then(|rt| match rt {
            RegOrTop::Reg(reg) => Some(reg),
            _ => None
        })
    }
}

impl<'a> RAllocCtx<'a> {
    fn run(mut self) -> RAllocData {
        // First, find all stack based instructions and fill out their instruction info
        for (i, instr) in self.decoded.iter().enumerate() {
            let instr_info = instr.info();
            let data = match instr_info {
                Some(info) => {
                    let (incoming, outgoing) = {
                        let InstructionInfo::Stack { base, inputs, outputs } = info;
                        ((base + inputs).into(), (base + outputs).into())
                    };
                    Data::Stack(StackData {
                        incoming,
                        outgoing,
                        info
                    })
                },
                None => {
                    let last = i == self.decoded.len()-1;

                    let incoming;
                    let outgoing;

                    if !last {
                        let (top_read, base_write) = (instr.top_read().map(|r| r.next()), instr.base_write());
                        incoming = match (top_read, base_write) {
                            (Some(tr), Some(bw)) if bw.is_above(tr) => Some(bw),
                            (None, Some(bw)) => Some(bw),
                            (tr, ..) => tr,
                        };
                        outgoing = match (incoming, base_write.map(|r| r.next())) {
                            (Some(incoming), Some(bw)) if bw.is_above(incoming) => Some(bw),
                            (None, Some(bw)) => Some(bw),
                            (incoming, ..) => incoming,
                        };
                    } else {
                        // Last instruction must have an incoming of 0 and an outgoing of 0
                        incoming = Some(Reg(0));
                        outgoing = Some(Reg(0));
                    }

                    trace!("{} {:?} {:?}", i, incoming, outgoing);

                    Data::FreeForm(FreeFormData {
                        incoming: incoming.map(FreeFormReg::Initial).unwrap_or(FreeFormReg::None),
                        outgoing: outgoing.map(FreeFormReg::Initial).unwrap_or(FreeFormReg::None),
                    })
                },
            };
            self.info.push(Info {
                data,
                redirect: None
            });
        }

        // Find forward jumps to TFORLOOP instructions and swap their instruction info
        for (i, instr) in self.decoded.iter().enumerate() {
            if let LuaInstruction::Jump { offset } = *instr {
                let target = offset.apply(i as u32) as usize;
                if let LuaInstruction::TForLoop {..} = self.decoded[target] {
                    if self.info[target].redirect.is_none() {
                        self.info.swap(i, target);
                        self.info[i].redirect = Some(target);
                        self.info[target].redirect = Some(i);
                        self.info[target].data = {
                            let info = self.decoded[target].info().unwrap();
                            let (incoming, outgoing) = {
                                let InstructionInfo::Stack { base, outputs, .. } = info;
                                ((base + outputs).into(), (base + outputs).into())
                            };
                            Data::Stack(StackData {
                                incoming,
                                outgoing,
                                info
                            })
                        };
                    }
                }
            }
        }

        // Fix outgoing for CONCAT instructions
        for (i, instr) in self.decoded.iter().enumerate() {
            if let LuaInstruction::Concat { dest, .. } = *instr {
                let stack_data = self.info[i].data.stack_mut().unwrap();
                if let RegOrTop::Reg(ref mut reg) = stack_data.outgoing {
                    if dest.is_at_or_above(*reg) {
                        *reg = dest.next();
                    }
                }
            }
        }

        // Downwards propagation: instructions going to our current instruction
        // Upwards propagation: instructions our current instruction is going to
        // We generate a graph (!!!) so we can determine the order for both upwards and downwards inference
        // Free mark is determined (for indeterminates) by using upward and downward inference, the one with the lowest concrete base (which is still valid for the instruction, looking at its inputs) wins
        let mut succ = vec![Vec::new(); self.decoded.len()];
        let mut pred = vec![Vec::new(); self.decoded.len()];
        for (i, instr) in self.decoded.iter().enumerate() {
            if i > 0 {
                let absolute_jump = match self.decoded[i - 1] {
                    LuaInstruction::Jump {..} | LuaInstruction::TailCall {..} | LuaInstruction::Return {..} | LuaInstruction::LoadBool { skip_next: true, .. } => {
                        // Always jumps, so it can't be a source of downwards propagation
                        true
                    },
                    _ => false,
                };
                if !absolute_jump {
                    pred[i].push(i - 1);
                    succ[i - 1].push(i);
                }
            }

            match instr {
                LuaInstruction::Jump { offset } | LuaInstruction::ForLoop { target: offset, .. } | LuaInstruction::ForPrep { target: offset, .. } => {
                    let target = offset.apply(i as u32) as usize;
                    pred[target].push(i);
                    succ[i].push(target);
                },
                LuaInstruction::BinCondOp {..} | LuaInstruction::Test {..} | LuaInstruction::TestSet {..} | LuaInstruction::TForLoop {..} | LuaInstruction::LoadBool { skip_next: true, .. } => {
                    // May skip next instruction, may not
                    pred[i + 2].push(i);
                    succ[i].push(i + 2);
                },
                _ => {},
            }
        }

        // Get rid of dead instructions

        let mut worklist = WorkList::new(self.decoded.len(), true);
        let mut dead_list = vec![];
        loop {
            while let Some(pc) = worklist.next() {
                let mut changed = false;
                for &p in &pred[pc] {
                    if p != 0 && pred[p].is_empty() {
                        dead_list.push(p);
                        succ[p].clear();
                        changed = true;
                    }
                }
                for dead in dead_list.drain(..) {
                    let ind = pred[pc].iter().position(|v| *v == dead).unwrap();
                    pred[pc].swap_remove(ind);
                }
                dead_list.clear();
                if changed {
                    // Push our succ
                    for &s in &succ[pc] {
                        worklist.insert(s);
                    }
                }
                worklist.commit(pc);
            }
            if !worklist.flip() {
                break
            }
        }

        use std::collections::BTreeSet;
        struct WorkList {
            worklist: Vec<usize>,
            next_worklist: Vec<usize>,
            worklist_set: BTreeSet<usize>,
        }

        impl WorkList {
            fn new(items: usize, reversed: bool) -> WorkList {
                use std::iter::FromIterator;
                let worklist = if !reversed {
                    Vec::from_iter(0..items)
                } else {
                    Vec::from_iter((0..items).rev())
                };
                let next_worklist = Vec::new();
                let worklist_set = std::collections::BTreeSet::from_iter(0..items);
                WorkList { worklist, next_worklist, worklist_set }
            }

            fn flip(&mut self) -> bool {
                std::mem::swap(&mut self.worklist, &mut self.next_worklist);
                !self.worklist.is_empty()
            }

            fn next(&mut self) -> Option<usize> {
                self.worklist.pop()
            }

            fn commit(&mut self, item: usize) {
                self.worklist_set.remove(&item);
            }

            fn insert(&mut self, item: usize) {
                if self.worklist_set.insert(item) {
                    self.next_worklist.push(item)
                }
            }
        }

        let mut worklist = WorkList::new(self.decoded.len(), true);
        loop {
            while let Some(pc) = worklist.next() {
                let mut changed = false;
                if self.info[pc].class() == InstructionClass::FreeForm {
                    let pred = &pred[pc];
                    let redirect_pc = self.info[pc].redirect.unwrap_or(pc);
                    let our_outgoing = self.info[pc].outgoing();
                    // Derive incoming from predecessors, use lowest value
                    for &p in pred {
                        let outgoing = self.info[p].outgoing();
                        match outgoing {
                            Some(outgoing) => {
                                let info = self.info[pc].data.free_form_mut().unwrap();
                                let compatible = !self.decoded[redirect_pc].does_read_at_or_above(outgoing) && (our_outgoing.is_none() || Some(outgoing.next()) == our_outgoing || Some(outgoing) == our_outgoing);
                                match info.incoming {
                                    FreeFormReg::Initial(ref mut incoming) | FreeFormReg::Concrete(ref mut incoming) => {
                                        if incoming.is_above(outgoing) && compatible {
                                            #[cfg(debug_assertions)]
                                            println!("For {}, using pred {}, incoming = {:?} because old incoming > outgoing ({:?} > {:?})", pc, p, outgoing, incoming, outgoing);
                                            *incoming = outgoing;
                                            changed = true;
                                        }
                                    }
                                    _ => {
                                        if compatible {
                                            #[cfg(debug_assertions)]
                                            println!("For {}, using pred {}, incoming = {:?} because no incoming", p, pc, outgoing);
                                            info.incoming = FreeFormReg::Concrete(outgoing);
                                            changed = true;
                                        }
                                    }
                                }
                            },
                            _ => {}
                        }
                    }
                    // If this instruction writes, derive outgoing to be the write base, otherwise its the same as incoming
                    if let Some(incoming) = self.info[pc].incoming() {
                        let outgoing = if self.does_write(pc, incoming) {
                            incoming.next()
                        } else {
                            incoming
                        };
                        let info = self.info[pc].data.free_form_mut().unwrap();
                        let old = info.outgoing;
                        if old.is_none() {
                            let new = FreeFormReg::Concrete(outgoing);
                            info.outgoing = new;
                            if old != new {
                                changed = true;
                            }
                        }
                    }
                }
                if changed {
                    // Push our succ
                    for &s in &succ[pc] {
                        worklist.insert(s);
                    }
                }
                worklist.commit(pc);
            }
            if !worklist.flip() {
                break
            }
        }

        #[cfg(debug_assertions)]
        for (i, info) in self.info.iter().enumerate() {
            println!("{} {:?}: {:?} (p: {:?}, s: {:?})", i, self.decoded[i], (info.incoming_or_top(), info.outgoing_or_top()), pred[i], succ[i]);
        }

        let mut worklist = WorkList::new(self.decoded.len(), false);
        loop {
            while let Some(item) = worklist.next() {
                let mut changed = false;
                if self.info[item].class() == InstructionClass::FreeForm {
                    // For all succ
                    for &s in &succ[item] {
                        let incoming = self.info[s].incoming().unwrap();
                        let pc = self.info[item].pc(item);
                        let info = self.info[item].data.free_form_mut().unwrap();
                        let outgoing = info.outgoing.as_reg().unwrap();
                        if outgoing.is_above(incoming) && !self.decoded[pc].does_write_at_or_above(incoming) {
                            #[cfg(debug_assertions)]
                            println!("For {}, using succ {}, outgoing = {:?} because old outgoing > incoming ({:?} > {:?})", item, s, incoming, outgoing, incoming);
                            changed = true;
                            info.outgoing = FreeFormReg::Concrete(incoming);
                        } else if outgoing != incoming {
                            info.incoming = FreeFormReg::Concrete(incoming);
                            info.outgoing = FreeFormReg::Concrete(incoming);
                        }
                        // TODO: if our outgoing < succ incoming and its impossible for us to allocate those registers, take on succ incoming for both
                    }
                }
                if changed {
                    // Push our predecessors
                    for &p in &pred[item] {
                        worklist.insert(p);
                    }
                }
                worklist.commit(item);
            }
            if !worklist.flip() {
                break
            }
        }

        // Manually fix loadbool pairs
        for (i, instr) in self.decoded.iter().enumerate() {
            if let LuaInstruction::LoadBool { skip_next: true, .. } = *instr {
                if let LuaInstruction::LoadBool { skip_next: false, .. } = self.decoded[i + 1] {
                    {
                        let skipping = self.info[i].data.free_form_mut().unwrap();
                        skipping.incoming = skipping.outgoing;
                    }
                    {
                        let skipped = self.info[i + 1].data.free_form_mut().unwrap();
                        skipped.incoming = skipped.outgoing;
                    }
                }
            }
        }

        self.info.last_mut().unwrap().data = Data::FreeForm(FreeFormData {
            incoming: FreeFormReg::None,
            outgoing: FreeFormReg::None,
        });

        #[cfg(debug_assertions)]
        for (i, info) in self.info.iter().enumerate() {
            println!("{} {:?}: {:?} (p: {:?}, s: {:?})", i, self.decoded[i], info, pred[i], succ[i]);
        }

        RAllocData {
            info: self.info,
        }
    }

    fn does_read(&self, pc: usize, reg: Reg) -> bool {
        let pc = self.info[pc].pc(pc);
        self.decoded[pc].does_read(reg)
    }

    fn does_write(&self, pc: usize, reg: Reg) -> bool {
        let pc = self.info[pc].pc(pc);
        self.decoded[pc].does_write(reg)
    }
}

pub fn run(decoded: &[LuaInstruction]) -> RAllocData {
    let info = Vec::with_capacity(decoded.len());

    let ctx = RAllocCtx {
        decoded,
        info
    };
    ctx.run()
}