1use std::error::Error;
2use std::ffi::OsStr;
3use std::fmt::{self, Display, Formatter};
4use std::fs::OpenOptions;
5use std::io::{BufReader, Read};
6
7use crate::reader_leader;
8use base::prelude::*;
9
10#[derive(Debug)]
11pub enum DisassemblerFailure {
12 ReadFailed(String),
13 OutputFailed(std::io::Error),
14 Generic(String),
15 ShortFile,
16}
17
18impl Display for DisassemblerFailure {
19 fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), fmt::Error> {
20 match self {
21 DisassemblerFailure::Generic(message) | DisassemblerFailure::ReadFailed(message) => {
22 f.write_str(message)
23 }
24 DisassemblerFailure::ShortFile => f.write_str("file ended unexpectedly"),
25 DisassemblerFailure::OutputFailed(inner) => {
26 write!(f, "failed to write output: {inner}") }
28 }
29 }
30}
31
32impl Error for DisassemblerFailure {}
33
34fn update_sum(sum: Signed18Bit, word: Unsigned36Bit) -> Signed18Bit {
35 let (left, right) = split_halves(word);
36 sum.wrapping_add(right.reinterpret_as_signed())
37 .wrapping_add(left.reinterpret_as_signed())
38}
39
40fn read_splayed_words<R: Read>(
41 input: &mut R,
42 count: usize,
43 mut maybe_checksum: Option<&mut Signed18Bit>,
44) -> Result<Vec<Unsigned36Bit>, DisassemblerFailure> {
45 const SPLAY_SIZE: usize = 6;
46 let mut result: Vec<Unsigned36Bit> = Vec::with_capacity(count);
47 for _ in 0..count {
48 let mut w = Unsigned36Bit::ZERO;
49 let mut buf: [u8; SPLAY_SIZE] = [0; SPLAY_SIZE];
50 match input.read(&mut buf) {
51 Ok(0) => {
52 return Err(DisassemblerFailure::ShortFile);
53 }
54 Ok(nbytes) => {
55 if nbytes != SPLAY_SIZE {
56 return Err(DisassemblerFailure::Generic(
57 "input file length should be a multiple of 6 bytes".to_string(),
58 ));
59 }
60 for byte in buf {
61 let line: Unsigned6Bit = Unsigned6Bit::try_from(byte & 0o77).unwrap();
62 w = cycle_and_splay(w, line);
63 }
64 if let Some(ref mut checksum) = maybe_checksum {
65 **checksum = update_sum(**checksum, w);
66 }
67 result.push(w);
68 }
69 Err(e) => {
70 return Err(DisassemblerFailure::ReadFailed(e.to_string()));
71 }
72 }
73 }
74 Ok(result)
75}
76
77fn disassemble_block<W: std::io::Write>(
78 mut pos: Unsigned18Bit,
79 block: &[Unsigned36Bit],
80 output: &mut W,
81) -> Result<(), std::io::Error> {
82 let mut is_origin: bool = true;
83 for w in block {
84 disassemble_word(pos, *w, is_origin, output)?;
85 is_origin = false;
86 pos = pos.wrapping_add(Unsigned18Bit::ONE);
87 }
88 Ok(())
89}
90
91fn disassemble_word<W: std::io::Write>(
92 loc: Unsigned18Bit,
93 w: Unsigned36Bit,
94 is_origin: bool,
95 output: &mut W,
96) -> Result<(), std::io::Error> {
97 if is_origin {
98 write!(output, "{loc:>06o}|")?;
99 } else {
100 write!(output, "{:7}", "")?;
101 }
102 let raw = Instruction::from(w);
103 match SymbolicInstruction::try_from(&raw) {
104 Ok(symbolic) => {
105 write!(output, "{:<20}", symbolic.to_string())?;
106 }
107 Err(_) => {
108 write!(output, "{:<20}", "")?;
109 }
110 }
111 let (left, right) = split_halves(w);
112 writeln!(output, "|{left:>06o} {right:>06o}|{loc:>6o}")
113}
114
115fn report_on_checksum<W: std::io::Write, V: std::io::Write>(
116 checksum: Signed18Bit,
117 output: &mut W,
118 warning_output: &mut V,
119) -> Result<(), std::io::Error> {
120 let unsigned_checksum = checksum.reinterpret_as_unsigned();
121 if unsigned_checksum.is_zero() {
122 write!(output, "** Checksum is valid: {unsigned_checksum:>06o}")
123 } else {
124 write!(
125 warning_output,
126 "** Checksum is not valid: {unsigned_checksum:>06o}, this tape cannot be loaded as-is",
127 )
128 }
129}
130
131fn disassemble_chunk<R: Read, W: std::io::Write, V: std::io::Write>(
132 input: &mut R,
133 checksum: &mut Signed18Bit,
134 output: &mut W,
135 warning_output: &mut V,
136) -> Result<bool, DisassemblerFailure> {
137 let first = read_splayed_words(input, 1, Some(checksum))?;
138 let (chunk_size, origin) = match first.as_slice() {
139 [only] => {
140 let (len_rep, end) = split_halves(*only);
141 let len = match Signed18Bit::ONE.checked_sub(len_rep.reinterpret_as_signed()) {
142 Some(n) => {
143 if n.is_zero() {
144 Some(Unsigned18Bit::ZERO)
145 } else if n > Signed18Bit::ZERO {
146 Some(n.reinterpret_as_unsigned())
147 } else {
148 None
149 }
150 }
151 None => None,
152 }
153 .expect("overflow in block length");
154 writeln!(output, "** {len}-word chunk ending at {end}")
155 .map_err(DisassemblerFailure::OutputFailed)?;
156 let u_origin = end
157 .checked_sub(len)
158 .and_then(|n| n.checked_add(Unsigned18Bit::ONE))
159 .expect("overflow in origin calculation");
160 let chunk_size: usize = usize::from(len);
161 (chunk_size, u_origin)
162 }
163 [] => return Err(DisassemblerFailure::ShortFile),
164 _ => unreachable!(),
165 };
166 let block: Vec<Unsigned36Bit> = read_splayed_words(input, chunk_size, Some(checksum))?;
167 let trailer: Vec<Unsigned36Bit> = read_splayed_words(input, 1, Some(checksum))?;
168 let (_adj, next) = match trailer.as_slice() {
169 [only] => split_halves(*only),
170 [] => return Err(DisassemblerFailure::ShortFile),
171 _ => unreachable!(),
172 };
173 disassemble_block(origin, &block, output)
174 .and_then(|()| report_on_checksum(*checksum, output, warning_output))
175 .map_err(DisassemblerFailure::OutputFailed)?;
176
177 if next == u18!(3) {
178 Ok(true)
179 } else if next == u18!(0o27) {
180 writeln!(output, "** This is the final block")
181 .map_err(DisassemblerFailure::OutputFailed)?;
182 Ok(false)
183 } else {
184 writeln!(
185 warning_output,
186 "warning: block has unexpected next-address {next:o}"
187 )
188 .map_err(DisassemblerFailure::OutputFailed)?;
189 Ok(false)
190 }
191}
192
193fn check_header<R: Read, W: std::io::Write>(
194 input: &mut R,
195 output: &mut W,
196) -> Result<(), DisassemblerFailure> {
197 let expected_leader = reader_leader();
198 let header = read_splayed_words(input, expected_leader.len(), None)?;
199 for (pos, (want, got)) in expected_leader.iter().zip(header.iter()).enumerate() {
200 if want != got {
201 return Err(DisassemblerFailure::Generic(format!(
202 "File does not begin with the expected header; at position {pos} we expected {want:>012o} but got {got:>012o}"
203 )));
204 }
205 }
206 write!(output, "** reader leader is valid:")
207 .and_then(|()| disassemble_block(Unsigned18Bit::from(3_u8), &header, output))
208 .and_then(|()| write!(output, "** end of reader leader"))
209 .map_err(DisassemblerFailure::OutputFailed)?;
210 Ok(())
211}
212
213pub fn disassemble_file<W: std::io::Write, V: std::io::Write>(
220 input_file_name: &OsStr,
221 output: &mut W,
222 warning_output: &mut V,
223) -> Result<(), DisassemblerFailure> {
224 let input_file = OpenOptions::new()
225 .read(true)
226 .open(input_file_name)
227 .map_err(|e| DisassemblerFailure::Generic(format!("failed to open input file: {e}")))?;
228 let mut reader = BufReader::new(input_file);
229 check_header(&mut reader, output)?;
230 let mut checksum: Signed18Bit = Signed18Bit::ZERO;
231 loop {
232 match disassemble_chunk(&mut reader, &mut checksum, output, warning_output) {
233 Ok(true) => (), Ok(false) => {
235 break;
236 }
237 Err(e) => {
238 return Err(e);
239 }
240 }
241 }
242 let mut trailing_junk_count: usize = 0;
245 let mut buf = [0; 1];
246 loop {
247 match reader.read(&mut buf) {
248 Ok(0) => break,
249 Ok(n) => {
250 for junk in buf {
251 eprintln!("trailing junk byte: {junk:o}");
252 }
253 trailing_junk_count = trailing_junk_count.saturating_add(n);
254 }
255 Err(e) => {
256 return Err(DisassemblerFailure::ReadFailed(e.to_string()));
257 }
258 }
259 }
260 if trailing_junk_count > 0 {
261 Err(DisassemblerFailure::Generic(
262 "input file contains more data after what was apparently the last block".to_string(),
263 ))
264 } else {
265 Ok(())
266 }
267}