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
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
use crate::CLIConfig;
use crate::DARK_RED_COLOR;
use crate::GREEN_COLOR;
use crate::LIGHT_RED_COLOR;
// use crate::NO_COLOR;
use crate::ORANGE_COLOR;
use crate::PURPLE_COLOR;
use kerbalobjects::ksmfile::sections::CodeSection;
use kerbalobjects::ksmfile::sections::DebugEntry;
use kerbalobjects::ksmfile::sections::DebugRange;
use kerbalobjects::ksmfile::Instr;
use kerbalobjects::ksmfile::KSMFile;
use kerbalobjects::KOSValue;
use kerbalobjects::Opcode;
use std::io::Write;
use termcolor::ColorSpec;
use termcolor::StandardStream;
use termcolor::WriteColor;

use super::{DumpResult, DynResult};

pub struct KSMFileDebug {
    ksmfile: KSMFile,
}

impl KSMFileDebug {
    pub fn new(ksmfile: KSMFile) -> Self {
        KSMFileDebug { ksmfile }
    }

    pub fn dump(&self, stream: &mut StandardStream, config: &CLIConfig) -> DumpResult {
        let no_color = ColorSpec::new();
        // no_color.set_fg(Some(NO_COLOR));
        let mut purple = ColorSpec::new();
        purple.set_fg(Some(PURPLE_COLOR));
        let mut light_red = ColorSpec::new();
        light_red.set_fg(Some(LIGHT_RED_COLOR));
        let mut green = ColorSpec::new();
        green.set_fg(Some(GREEN_COLOR));
        let mut dark_red = ColorSpec::new();
        dark_red.set_fg(Some(DARK_RED_COLOR));
        let mut orange = ColorSpec::new();
        orange.set_fg(Some(ORANGE_COLOR));

        if config.info {
            writeln!(stream, "\nKSM File Info:")?;
            writeln!(stream, "\t{}", self.get_info())?;
        }

        if config.argument_section || config.full_contents {
            self.dump_argument_section(stream, &no_color, &green, &light_red)?;
        }

        if config.disassemble || config.full_contents {
            self.dump_code_sections(
                stream, config, &no_color, &orange, &purple, &dark_red, &light_red,
            )?;
        }

        if config.disassemble_symbol {
            self.dump_code_by_symbol(
                stream,
                config,
                &config.disassemble_symbol_value,
                &no_color,
                &orange,
                &purple,
                &dark_red,
                &light_red,
            )?;
        }

        if config.full_contents {
            self.dump_debug(stream, &no_color)?;
        }

        Ok(())
    }

    fn get_info(&self) -> String {
        match self.ksmfile.arg_section().get(0) {
            Some(value) => {
                match value {
                    KOSValue::String(s) => {
                        // If it is either a label that is used for reset or a KS formatted function name
                        if s.starts_with("@") || s.contains("`") {
                            String::from("Compiled using official kOS compiler.")
                        } else {
                            format!("{}", s)
                        }
                    }
                    _ => String::from("Unknown compiler"),
                }
            }
            None => String::from("Unknown compiler"),
        }
    }

    fn dump_debug(&self, stream: &mut StandardStream, regular_color: &ColorSpec) -> DumpResult {
        stream.set_color(regular_color)?;

        writeln!(stream, "\nDebug section:")?;

        let max_line_number = self.max_debug_line_number();
        let max_width = max_line_number.to_string().len();

        for debug_entry in self.ksmfile.debug_section().debug_entries() {
            write!(
                stream,
                "  Line {:>width$}, ",
                debug_entry.line_number(),
                width = max_width
            )?;

            let num_ranges = debug_entry.number_ranges();

            match num_ranges {
                1 => {
                    write!(stream, "1 range: ")?;
                }
                _ => {
                    write!(stream, "{} ranges: ", num_ranges)?;
                }
            }

            for (index, range) in debug_entry.ranges().enumerate() {
                write!(stream, "[{:0>6x}, {:0>6x}]", range.start(), range.end())?;

                if index < num_ranges - 1 {
                    write!(stream, ",")?;
                }
            }

            writeln!(stream, "")?;
        }

        Ok(())
    }

    fn dump_code_by_symbol(
        &self,
        stream: &mut StandardStream,
        config: &CLIConfig,
        symbol: &String,
        regular_color: &ColorSpec,
        line_color: &ColorSpec,
        label_color: &ColorSpec,
        mnemonic_color: &ColorSpec,
        variable_color: &ColorSpec,
    ) -> DumpResult {
        let mut index = 1;
        let mut addr = 0;
        let mut found_section = None;

        for code_section in self.ksmfile.code_sections() {
            let matches = match code_section.section_type() {
                kerbalobjects::ksmfile::sections::CodeType::Main => {
                    symbol.eq_ignore_ascii_case("main")
                }
                kerbalobjects::ksmfile::sections::CodeType::Initialization => {
                    symbol.eq_ignore_ascii_case("init")
                }
                kerbalobjects::ksmfile::sections::CodeType::Function => false,
                kerbalobjects::ksmfile::sections::CodeType::Unknown => false,
            };

            if matches {
                found_section = Some(code_section);
                break;
            } else {
                for instr in code_section.instructions() {
                    let matches = match instr {
                        Instr::ZeroOp(_) => false,
                        Instr::OneOp(_, op1) => {
                            let val1 = self.value_from_operand(*op1)?;

                            match val1 {
                                KOSValue::String(s) | KOSValue::StringValue(s) => s == symbol,
                                _ => false,
                            }
                        }
                        Instr::TwoOp(_, op1, op2) => {
                            let val1 = self.value_from_operand(*op1)?;
                            let val2 = self.value_from_operand(*op2)?;

                            let match1 = match val1 {
                                KOSValue::String(s) | KOSValue::StringValue(s) => s == symbol,
                                _ => false,
                            };
                            let match2 = match val2 {
                                KOSValue::String(s) | KOSValue::StringValue(s) => s == symbol,
                                _ => false,
                            };

                            match1 || match2
                        }
                    };

                    if matches {
                        found_section = Some(code_section);
                        break;
                    }
                }
            }

            index += code_section.instructions().len() as i32;

            addr += 2; // Offsets for the header bytes
            for instr in code_section.instructions() {
                addr += self.instr_size(instr);
            }
        }

        match found_section {
            Some(code_section) => {
                self.dump_code_section(
                    stream,
                    code_section,
                    index,
                    addr,
                    regular_color,
                    line_color,
                    label_color,
                    mnemonic_color,
                    variable_color,
                    config.line_numbers,
                    !config.show_no_labels,
                    !config.show_no_raw_instr,
                )?;
            }
            None => {
                writeln!(stream, "\nNo section found with that symbol.")?;
            }
        }

        Ok(())
    }

    fn dump_code_sections(
        &self,
        stream: &mut StandardStream,
        config: &CLIConfig,
        regular_color: &ColorSpec,
        line_color: &ColorSpec,
        label_color: &ColorSpec,
        mnemonic_color: &ColorSpec,
        variable_color: &ColorSpec,
    ) -> DumpResult {
        let mut index = 1;
        let mut addr = 0;

        for code_section in self.ksmfile.code_sections() {
            if code_section.instructions().len() != 0 {
                let (new_index, new_addr) = self.dump_code_section(
                    stream,
                    code_section,
                    index,
                    addr,
                    regular_color,
                    line_color,
                    label_color,
                    mnemonic_color,
                    variable_color,
                    config.line_numbers,
                    !config.show_no_labels,
                    !config.show_no_raw_instr,
                )?;

                index = new_index;
                addr = new_addr;
            } else {
                index += code_section.instructions().len() as i32;

                addr += 2; // Offsets for the header bytes
                for instr in code_section.instructions() {
                    addr += self.instr_size(instr);
                }
            }
        }

        Ok(())
    }

    fn dump_code_section(
        &self,
        stream: &mut StandardStream,
        code_section: &CodeSection,
        start_index: i32,
        start_addr: usize,
        regular_color: &ColorSpec,
        line_color: &ColorSpec,
        label_color: &ColorSpec,
        mnemonic_color: &ColorSpec,
        variable_color: &ColorSpec,
        show_line_numbers: bool,
        show_labels: bool,
        show_raw_instr: bool,
    ) -> DynResult<(i32, usize)> {
        let section_type = code_section.section_type();
        let addr_width = self.ksmfile.arg_section().num_index_bytes();

        let name = match section_type {
            kerbalobjects::ksmfile::sections::CodeType::Main => "MAIN",
            kerbalobjects::ksmfile::sections::CodeType::Initialization => "INIT",
            kerbalobjects::ksmfile::sections::CodeType::Function => {
                match code_section.instructions().next() {
                    Some(instr) => match instr {
                        kerbalobjects::ksmfile::Instr::OneOp(opcode, op1) => {
                            if *opcode == Opcode::Lbrt {
                                let operand = self.value_from_operand(*op1)?;

                                match operand {
                                    KOSValue::String(s) | KOSValue::StringValue(s) => {
                                        // If this is a kOS-compiled function
                                        if s.contains("`") {
                                            s.split("`").next().unwrap()
                                        } else {
                                            s
                                        }
                                    }
                                    _ => "FUNC",
                                }
                            } else {
                                "FUNC"
                            }
                        }
                        _ => "FUNC",
                    },
                    None => "FUNC",
                }
            }
            kerbalobjects::ksmfile::sections::CodeType::Unknown => "UNKNOWN",
        };

        stream.set_color(regular_color)?;
        writeln!(stream, "\n{}:", name)?;

        let mut label = String::from("@0000001");
        let mut index = start_index;
        let mut addr = start_addr + 2;

        let max_line_number = self.max_debug_line_number();
        let max_width = max_line_number.to_string().len();

        for instr in code_section.instructions() {
            let instr_size = self.instr_size(instr);

            if show_line_numbers {
                let debug_entry = self.find_entry_with_addr(addr);

                match debug_entry {
                    Some((entry, range)) => {
                        let line_num = entry.line_number();
                        let range_start = range.start();
                        let range_end = range.end();
                        let range_middle = ((range_end - range_start) / 2) + range_start;
                        let operand_length = instr_size - 1;

                        let state = if addr == range_start
                            && range_start + operand_length == range_end
                        {
                            3
                        } else if addr == range_start {
                            let next_instr_option =
                                code_section.instructions().nth(index as usize + 1);

                            match next_instr_option {
                                Some(next_instr) => {
                                    if addr + operand_length + self.instr_size(next_instr)
                                        == range_end
                                    {
                                        5
                                    } else {
                                        0
                                    }
                                }
                                None => 0,
                            }
                        } else if addr + operand_length == range_end {
                            4
                        } else if range_middle >= addr && (range_middle <= (addr + operand_length))
                        {
                            2
                        } else if addr + operand_length < range_end && addr > range_start {
                            1
                        } else {
                            6
                        };

                        let num_str = match state {
                            2 | 3 | 5 => line_num.to_string(),
                            _ => String::new(),
                        };

                        let art = match state {
                            0 => " ╔═",
                            1 => " ║ ",
                            2 => "═╣ ",
                            3 => "═══",
                            4 => " ╚═",
                            5 => "═╦═",
                            _ => "   ",
                        };

                        stream.set_color(line_color)?;
                        write!(stream, "   {:>width$} {} ", num_str, art, width = max_width)?;
                        stream.set_color(regular_color)?;
                    }
                    None => {
                        println!("Just sad");
                        write!(stream, "   {:>width$}     ", "", width = max_width)?;
                    }
                }
            } else {
                write!(stream, "  ")?;
            }

            let instr_opcode = match instr {
                kerbalobjects::ksmfile::Instr::ZeroOp(opcode) => *opcode,
                kerbalobjects::ksmfile::Instr::OneOp(opcode, _) => *opcode,
                kerbalobjects::ksmfile::Instr::TwoOp(opcode, _, _) => *opcode,
            };

            let is_lbrt = instr_opcode == Opcode::Lbrt;

            if show_labels {
                stream.set_color(label_color)?;

                if is_lbrt {
                    write!(stream, "{:7} ", "")?;
                } else {
                    write!(stream, "{:<7} ", label)?;
                }
            }

            stream.set_color(regular_color)?;

            if is_lbrt {
                match instr {
                    kerbalobjects::ksmfile::Instr::OneOp(_, op) => {
                        let arg = self.value_from_operand(*op)?;

                        match arg {
                            KOSValue::String(s) => {
                                label = s.clone();

                                if label.starts_with("@") {
                                    // Makes @0013 @000013
                                    label.insert_str(1, "00");
                                }
                            }
                            _ => {}
                        }

                        label.truncate(7);
                    }
                    _ => {}
                }
            }
            // If it isn't a label reset
            else {
                index += 1;
                label = format!("@{:>06}", index);
            }

            addr += instr_size;

            if show_raw_instr {
                match instr {
                    kerbalobjects::ksmfile::Instr::ZeroOp(opcode) => {
                        write!(
                            stream,
                            "{:x} {:<width$} {:<width$}",
                            u8::from(*opcode),
                            "",
                            "",
                            width = addr_width * 2
                        )?;
                    }
                    kerbalobjects::ksmfile::Instr::OneOp(opcode, op1) => {
                        write!(
                            stream,
                            "{:x} {:0>width$x} {:<width$}",
                            u8::from(*opcode),
                            op1,
                            "",
                            width = addr_width * 2
                        )?;
                    }
                    kerbalobjects::ksmfile::Instr::TwoOp(opcode, op1, op2) => {
                        write!(
                            stream,
                            "{:x} {:0>width$x} {:0>width$x}",
                            u8::from(*opcode),
                            op1,
                            op2,
                            width = addr_width * 2
                        )?;
                    }
                }
            }

            stream.set_color(mnemonic_color)?;

            let mnemonic: &str = instr_opcode.into();

            write!(stream, "  {:<6}", mnemonic)?;

            stream.set_color(regular_color)?;

            match instr {
                kerbalobjects::ksmfile::Instr::ZeroOp(_) => {}
                kerbalobjects::ksmfile::Instr::OneOp(_, op1) => {
                    let val1 = self.value_from_operand(*op1)?;

                    super::write_kosvalue(stream, val1, regular_color, variable_color)?;
                }
                kerbalobjects::ksmfile::Instr::TwoOp(_, op1, op2) => {
                    let val1 = self.value_from_operand(*op1)?;
                    let val2 = self.value_from_operand(*op2)?;

                    super::write_kosvalue(stream, val1, regular_color, variable_color)?;

                    write!(stream, ",")?;

                    super::write_kosvalue(stream, val2, regular_color, variable_color)?;
                }
            }

            writeln!(stream, "")?;
        }

        Ok((index, addr))
    }

    fn instr_size(&self, instr: &Instr) -> usize {
        let addr_width = self.ksmfile.arg_section().num_index_bytes() as usize;

        match instr {
            kerbalobjects::ksmfile::Instr::ZeroOp(_) => 1,
            kerbalobjects::ksmfile::Instr::OneOp(_, _) => 1 + addr_width,
            kerbalobjects::ksmfile::Instr::TwoOp(_, _, _) => 1 + addr_width * 2,
        }
    }

    fn max_debug_line_number(&self) -> isize {
        let mut max = 0;

        for debug_entry in self.ksmfile.debug_section().debug_entries() {
            if debug_entry.line_number() > max {
                max = debug_entry.line_number();
            }
        }

        max
    }

    fn find_entry_with_addr(&self, addr: usize) -> Option<(&DebugEntry, &DebugRange)> {
        let debug_section = self.ksmfile.debug_section();

        for debug_entry in debug_section.debug_entries() {
            for debug_range in debug_entry.ranges() {
                if addr >= debug_range.start() && addr <= debug_range.end() {
                    return Some((debug_entry, debug_range));
                }
            }
        }

        None
    }

    fn value_from_operand(&self, op: usize) -> DynResult<&KOSValue> {
        self.ksmfile
            .arg_section()
            .get(op)
            .ok_or("Instruction referenced invalid argument index".into())
    }

    fn dump_argument_section(
        &self,
        stream: &mut StandardStream,
        regular_color: &ColorSpec,
        type_color: &ColorSpec,
        variable_color: &ColorSpec,
    ) -> DumpResult {
        let arg_section = self.ksmfile.arg_section();
        let addr_width = arg_section.num_index_bytes();

        stream.set_color(regular_color)?;

        writeln!(stream, "\nArgument section:")?;

        writeln!(
            stream,
            "  {:18}{:<12}{:<24}",
            format!(
                "Index ({} byte{})",
                addr_width,
                if addr_width > 1 { "s" } else { "" }
            ),
            "Type",
            "Value",
        )?;

        let mut index = 3;

        for value in arg_section.arguments() {
            stream.set_color(regular_color)?;

            let index_str = format!("  {:0>width$x}", index, width = addr_width * 2);

            write!(stream, "{:<20}", index_str)?;

            index += value.size_bytes();

            stream.set_color(type_color)?;
            match value {
                kerbalobjects::KOSValue::Null => {
                    writeln!(stream, "NULL")?;
                }
                kerbalobjects::KOSValue::Bool(b) => {
                    write!(stream, "{:<12}", "BOOL")?;
                    stream.set_color(regular_color)?;
                    write!(stream, "{}", if *b { "true" } else { "false" })?;
                }
                kerbalobjects::KOSValue::Byte(b) => {
                    write!(stream, "{:<12}", "BYTE")?;
                    stream.set_color(regular_color)?;
                    write!(stream, "{}", b)?;
                }
                kerbalobjects::KOSValue::Int16(i) => {
                    write!(stream, "{:<12}", "INT16")?;
                    stream.set_color(regular_color)?;
                    write!(stream, "{}", i)?;
                }
                kerbalobjects::KOSValue::Int32(i) => {
                    write!(stream, "{:<12}", "INT32")?;
                    stream.set_color(regular_color)?;
                    write!(stream, "{}", i)?;
                }
                kerbalobjects::KOSValue::Float(f) => {
                    write!(stream, "{:<12}", "FLOAT")?;
                    stream.set_color(regular_color)?;
                    write!(stream, "{:.5}", f)?;
                }
                kerbalobjects::KOSValue::Double(d) => {
                    write!(stream, "{:<12}", "DOUBLE")?;
                    stream.set_color(regular_color)?;
                    write!(stream, "{:.5}", d)?;
                }
                kerbalobjects::KOSValue::String(s) => {
                    write!(stream, "{:<12.80}", "STRING")?;
                    stream.set_color(regular_color)?;
                    write!(stream, "\"")?;
                    if s.starts_with("$") {
                        stream.set_color(variable_color)?;
                    } else {
                        stream.set_color(regular_color)?;
                    }
                    write!(stream, "{}", s)?;
                    stream.set_color(regular_color)?;
                    write!(stream, "\"")?;
                }
                kerbalobjects::KOSValue::ArgMarker => {
                    write!(stream, "{:<12}", "ARGMARKER")?;
                }
                kerbalobjects::KOSValue::ScalarInt(i) => {
                    write!(stream, "{:<12}", "SCALARINT")?;
                    stream.set_color(regular_color)?;
                    write!(stream, "{}", i)?;
                }
                kerbalobjects::KOSValue::ScalarDouble(d) => {
                    write!(stream, "{:<12}", "SCALARDOUBLE")?;
                    stream.set_color(regular_color)?;
                    write!(stream, "{}", d)?;
                }
                kerbalobjects::KOSValue::BoolValue(b) => {
                    write!(stream, "{:<12}", "SCALARDOUBLE")?;
                    stream.set_color(regular_color)?;
                    write!(stream, "{}", if *b { "true" } else { "false" })?;
                }
                kerbalobjects::KOSValue::StringValue(s) => {
                    write!(stream, "{:<12.80}", "STRINGVALUE")?;
                    if s.starts_with("$") {
                        stream.set_color(variable_color)?;
                    } else {
                        stream.set_color(regular_color)?;
                    }
                    write!(stream, "\"{}\"", s)?;
                }
            }
            writeln!(stream, "")?;
        }

        Ok(())
    }
}