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
use crate::bits::BitReader;
use crate::test_binary::{
    Abort, RelayAction, RelayInstr, Segment, SensorAction, SensorInstr, Test, TestBody,
};
use crate::{result::CompilerResult, test_binary::DeviceAddress};
use std::fs::File;
use std::io::Write;
use std::path::PathBuf;

/// Emits a TAF file from the disassembled tbf to a
/// specified output path. If no output path is specified,
/// the TAF will be saved to the current directory as "a.taf"
pub fn emit(test: Test, output_path: Option<PathBuf>) -> CompilerResult<()> {
    let mut res = CompilerResult::status_only("Emitting TAF");

    let mut file = check!(
        res,
        File::create(output_path.unwrap_or_else(|| "./a.taf".into()))
    );

    let taf_string = check!(res, test.disassemble());
    check!(res, file.write(taf_string.as_bytes()));

    res
}

/// Disassembles a TBF at a speciifed path into a CompilerResult
/// containing a Test struct
pub fn disassemble_tbf(path: PathBuf) -> CompilerResult<Test> {
    let mut res = CompilerResult::new("Test disassembly");
    let mut tbf_reader = check!(res, BitReader::from_file(path));

    // Throw out the TBF header which is 88 bytes
    // 704 bits / 8 = 88 bytes
    tbf_reader.skip(704);
    let aborts = check!(res, disassemble_aborts(&mut tbf_reader));
    let body = check!(res, disassemble_test_body(&mut tbf_reader));

    let test = Test { aborts, body };

    res.with_value(test)
}

fn disassemble_aborts(tbf_reader: &mut BitReader) -> CompilerResult<[Abort; 15]> {
    let mut res = CompilerResult::new("Abort disassembly");
    let mut aborts = [
        Abort::new(),
        Abort::new(),
        Abort::new(),
        Abort::new(),
        Abort::new(),
        Abort::new(),
        Abort::new(),
        Abort::new(),
        Abort::new(),
        Abort::new(),
        Abort::new(),
        Abort::new(),
        Abort::new(),
        Abort::new(),
        Abort::new(),
    ];

    for _i in 0..15 {
        // Throw out abort's 0xF0 byte
        if check!(res, tbf_reader.read_u8(8), "Couldn't read abort prefix") != 0xF0u8 {
            res.error("Invalid abort prefix");
        }
        let abort_idx = check!(res, tbf_reader.read_u8(8), "Couldn't read abort idx");

        // Section Length in bytes
        let section_length = check!(
            res,
            tbf_reader.read_u16(16),
            "Couldn't read abort section length"
        );
        // Remaining bits once section has been read
        // Add 32 to section end due to the section header being read by the bitreader
        let section_end = tbf_reader.remaining_len() + 32 - (section_length * 8) as usize;

        check!(
            res,
            disassemble_section(
                tbf_reader,
                &mut aborts[abort_idx as usize - 1].segments,
                section_end as usize,
            )
        );
    }

    res.with_value(aborts)
}

fn disassemble_test_body(tbf_reader: &mut BitReader) -> CompilerResult<TestBody> {
    let mut res = CompilerResult::new("Test body disassembly");

    let mut test_body = TestBody::new();
    let body_prefix = check!(
        res,
        tbf_reader.read_u8(8),
        "Couldn't ready test body prefix"
    );

    if body_prefix != 0xF1u8 {
        res.error("Invalid test body header byte!");
        return res;
    }

    let body_length = check!(
        res,
        tbf_reader.read_u32(24),
        "Couldn't read test body length"
    );

    let section_end = tbf_reader.remaining_len() + 32 - (body_length * 8) as usize;

    check!(
        res,
        disassemble_section(tbf_reader, &mut test_body.segments, section_end)
    );

    res.with_value(test_body)
}

/// Helper function for parsing the instruction section for
/// both the test body and each abort
fn disassemble_section(
    tbf_reader: &mut BitReader,
    input_vector: &mut Vec<Segment>,
    section_end: usize,
) -> CompilerResult<()> {
    let mut res = CompilerResult::status_only("Disassembling segments within test body or abort.");
    while tbf_reader.remaining_len() > section_end {
        if (check!(res, tbf_reader.read_u8(3), "Couldn't read segment prefix.") == 0b000) {
            input_vector.push(check!(res, disassemble_segment(tbf_reader)));
        } else {
            res.error("Invalid segment prefix!");
            return res;
        }
    }
    res
}

fn disassemble_segment(tbf_reader: &mut BitReader) -> CompilerResult<Segment> {
    let mut res = CompilerResult::new("Segment disassembly");
    let _z = check!(res, tbf_reader.read_u8(1), "Couldn't read segment z");

    let relative_time = check!(
        res,
        tbf_reader.read_u32(20),
        "Couldn't read segment relative time"
    );
    let num_sensors = check!(
        res,
        tbf_reader.read_u16(16),
        "Couldn't read number of sensor instructions in segment"
    );
    let num_relays = check!(
        res,
        tbf_reader.read_u16(16),
        "Couldn't read number of relay instructions in segment"
    );
    let mut segment = check!(res, Segment::try_new(relative_time as u32));

    for _i in 0..(num_relays + num_sensors) {
        let prefix = check!(
            res,
            tbf_reader.read_u8(3),
            "Couldn't read instruction prefix for segment."
        );
        match prefix {
            0b010 => segment
                .sensor_instructions
                .push(check!(res, disassemble_sensor_instr(tbf_reader))),
            0b001 => segment
                .relay_instructions
                .push(check!(res, disassemble_relay_instr(tbf_reader))),
            _ => {
                res.error("Invalid instruction prefix!");
                return res;
            }
        }
    }

    res.with_value(segment)
}

fn disassemble_sensor_instr(tbf_reader: &mut BitReader) -> CompilerResult<SensorInstr> {
    let mut res = CompilerResult::new("Sensor Instruction disassembly");

    let opcode = check!(
        res,
        tbf_reader.read_u8(6),
        "Couldn't read sensor instruction opcode"
    );
    let action = match opcode {
        0b000000 => SensorAction::stop_check,
        0b000001 => SensorAction::start_check_in,
        0b111111 => SensorAction::is_now_in,
        _ => {
            res.error("Invalid sensor opcode!");
            return res;
        }
    };

    let abort_idx = check!(
        res,
        tbf_reader.read_u8(4),
        "Couldn't read sensor instruction abort index"
    );
    let virtuality = check!(
        res,
        tbf_reader.read_u16(1),
        "Couldn't read sensor instruction virtuality"
    );
    let device_address = check!(
        res,
        tbf_reader.read_u16(10),
        "Couldn't read sensor instruction device address"
    );
    let device_address = DeviceAddress {
        value: device_address,
        virtuality,
    };
    let left_bound = check!(res, tbf_reader.read_u16(12), "Couldn't read left bound");
    let right_bound = check!(res, tbf_reader.read_u16(12), "Couldn't read right bound");

    let sensor_instr = check!(
        res,
        SensorInstr::try_new(action, abort_idx, device_address, left_bound, right_bound)
    );

    res.with_value(sensor_instr)
}

fn disassemble_relay_instr(tbf_reader: &mut BitReader) -> CompilerResult<RelayInstr> {
    let mut res = CompilerResult::new("Relay Instruction disassembly");

    let opcode = check!(
        res,
        tbf_reader.read_u8(2),
        "Couldn't read relay instruction opcode"
    );
    let action = match opcode {
        0b0 => RelayAction::Set,
        0b1 => RelayAction::Unset,
        _ => {
            res.error("Invalid relay opcode!");
            return res;
        }
    };
    let virtuality = check!(
        res,
        tbf_reader.read_u16(1),
        "Couldn't read relay instruction virtuality"
    );
    let device_address = check!(
        res,
        tbf_reader.read_u16(10),
        "Couldn't read relay instruction device address"
    );
    let device_address = DeviceAddress {
        value: device_address,
        virtuality,
    };

    let relay_instr = check!(res, RelayInstr::try_new(action, device_address));

    res.with_value(relay_instr)
}