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
use std::fs;
use std::cmp;
use std::rc::Rc;
use std::cell::RefCell;
use std::fmt::Write;
use femtos::Instant;
use emulator_hal::{self, BusAccess, ErrorType};

use crate::error::Error;
use crate::devices::{Address, Addressable, Transmutable, Device, read_beu16};


/// A contiguous block of `Addressable` memory, backed by a `Vec`
pub struct MemoryBlock {
    read_only: bool,
    contents: Vec<u8>,
}

impl MemoryBlock {
    pub fn new(contents: Vec<u8>) -> MemoryBlock {
        MemoryBlock {
            read_only: false,
            contents,
        }
    }

    pub fn load(filename: &str) -> Result<MemoryBlock, Error> {
        match fs::read(filename) {
            Ok(contents) => Ok(MemoryBlock::new(contents)),
            Err(_) => Err(Error::new(format!("Error reading contents of {}", filename))),
        }
    }

    pub fn load_at(&mut self, addr: Address, filename: &str) -> Result<(), Error> {
        match fs::read(filename) {
            Ok(contents) => {
                self.contents[(addr as usize)..(addr as usize) + contents.len()].copy_from_slice(&contents);
                Ok(())
            },
            Err(_) => Err(Error::new(format!("Error reading contents of {}", filename))),
        }
    }

    pub fn read_only(&mut self) {
        self.read_only = true;
    }

    pub fn resize(&mut self, new_size: usize) {
        self.contents.resize(new_size, 0);
    }
}

impl Addressable for MemoryBlock {
    fn size(&self) -> usize {
        self.contents.len()
    }

    fn read(&mut self, _clock: Instant, addr: Address, data: &mut [u8]) -> Result<(), Error> {
        data.copy_from_slice(&self.contents[(addr as usize)..(addr as usize) + data.len()]);
        Ok(())
    }

    fn write(&mut self, _clock: Instant, addr: Address, data: &[u8]) -> Result<(), Error> {
        if self.read_only {
            return Err(Error::breakpoint(format!(
                "Attempt to write to read-only memory at {:x} with data {:?}",
                addr, data
            )));
        }

        self.contents[(addr as usize)..(addr as usize) + data.len()].copy_from_slice(data);
        Ok(())
    }
}

impl Transmutable for MemoryBlock {
    fn as_addressable(&mut self) -> Option<&mut dyn Addressable> {
        Some(self)
    }
}


/// An address adapter that repeats the address space of the subdevice over the given range
pub struct AddressRepeater {
    subdevice: Device,
    range: Address,
}

impl AddressRepeater {
    pub fn new(subdevice: Device, range: Address) -> Self {
        Self {
            subdevice,
            range,
        }
    }
}

impl Addressable for AddressRepeater {
    fn size(&self) -> usize {
        self.range as usize
    }

    fn read(&mut self, clock: Instant, addr: Address, data: &mut [u8]) -> Result<(), Error> {
        let size = self.subdevice.borrow_mut().as_addressable().unwrap().size() as Address;
        self.subdevice
            .borrow_mut()
            .as_addressable()
            .unwrap()
            .read(clock, addr % size, data)
    }

    fn write(&mut self, clock: Instant, addr: Address, data: &[u8]) -> Result<(), Error> {
        let size = self.subdevice.borrow_mut().as_addressable().unwrap().size() as Address;
        self.subdevice
            .borrow_mut()
            .as_addressable()
            .unwrap()
            .write(clock, addr % size, data)
    }
}

impl Transmutable for AddressRepeater {
    fn as_addressable(&mut self) -> Option<&mut dyn Addressable> {
        Some(self)
    }
}


/// An address adapter that uses a closure to translate the address before accessing the subdevice
pub struct AddressTranslator {
    subdevice: Device,
    size: usize,
    func: Box<dyn Fn(Address) -> Address>,
}

impl AddressTranslator {
    pub fn new<F>(subdevice: Device, size: usize, func: F) -> Self
    where
        F: Fn(Address) -> Address + 'static,
    {
        Self {
            subdevice,
            size,
            func: Box::new(func),
        }
    }
}

impl Addressable for AddressTranslator {
    fn size(&self) -> usize {
        self.size
    }

    fn read(&mut self, clock: Instant, addr: Address, data: &mut [u8]) -> Result<(), Error> {
        self.subdevice
            .borrow_mut()
            .as_addressable()
            .unwrap()
            .read(clock, (self.func)(addr), data)
    }

    fn write(&mut self, clock: Instant, addr: Address, data: &[u8]) -> Result<(), Error> {
        self.subdevice
            .borrow_mut()
            .as_addressable()
            .unwrap()
            .write(clock, (self.func)(addr), data)
    }
}

impl Transmutable for AddressTranslator {
    fn as_addressable(&mut self) -> Option<&mut dyn Addressable> {
        Some(self)
    }
}


#[derive(Clone)]
pub struct Block {
    pub base: Address,
    pub size: usize,
    pub dev: Device,
}

/// A bus-like collection of `Addressable` `Device`s mapped to different address ranges
///
/// This is the fundamental means of connecting devices together to a CPU implementation.
#[derive(Clone, Default)]
pub struct Bus {
    blocks: Vec<Block>,
    ignore_unmapped: bool,
    watchers: Vec<Address>,
    watcher_modified: bool,
}

impl Bus {
    pub fn set_ignore_unmapped(&mut self, ignore_unmapped: bool) {
        self.ignore_unmapped = ignore_unmapped;
    }

    pub fn clear_all_bus_devices(&mut self) {
        self.blocks.clear();
    }

    pub fn insert(&mut self, base: Address, dev: Device) {
        let size = dev.borrow_mut().as_addressable().unwrap().size();
        let block = Block {
            base,
            size,
            dev,
        };
        let i = self
            .blocks
            .iter()
            .position(|cur| cur.base > block.base)
            .unwrap_or(self.blocks.len());
        self.blocks.insert(i, block);
    }

    pub fn get_device_at(&self, addr: Address, count: usize) -> Result<(Device, Address), Error> {
        for block in &self.blocks {
            if addr >= block.base && addr < (block.base + block.size as Address) {
                let relative_addr = addr - block.base;
                if relative_addr as usize + count <= block.size {
                    return Ok((block.dev.clone(), relative_addr));
                } else {
                    return Err(Error::new(format!("Error reading address {:#010x}", addr)));
                }
            }
        }
        Err(Error::new(format!("No segment found at {:#010x}", addr)))
    }

    pub fn dump_memory(&mut self, clock: Instant, mut addr: Address, mut count: Address) {
        while count > 0 {
            let mut line = format!("{:#010x}: ", addr);

            let to = if count < 16 { count / 2 } else { 8 };
            for _ in 0..to {
                let word = Addressable::read_beu16(self, clock, addr);
                if word.is_err() {
                    println!("{}", line);
                    return;
                }
                write!(line, "{:#06x} ", word.unwrap()).unwrap();
                addr += 2;
                count -= 2;
            }
            println!("{}", line);
        }
    }

    pub fn add_watcher(&mut self, addr: Address) {
        self.watchers.push(addr);
    }

    pub fn remove_watcher(&mut self, addr: Address) {
        self.watchers.push(addr);
        if let Some(index) = self.watchers.iter().position(|a| *a == addr) {
            self.watchers.remove(index);
        }
    }

    pub fn check_and_reset_watcher_modified(&mut self) -> bool {
        let result = self.watcher_modified;
        self.watcher_modified = false;
        result
    }
}

impl Addressable for Bus {
    fn size(&self) -> usize {
        let block = &self.blocks[self.blocks.len() - 1];
        (block.base as usize) + block.size
    }

    fn read(&mut self, clock: Instant, addr: Address, data: &mut [u8]) -> Result<(), Error> {
        let (dev, relative_addr) = match self.get_device_at(addr, data.len()) {
            Ok(result) => result,
            Err(err) if self.ignore_unmapped => {
                log::info!("{:?}", err);
                return Ok(());
            },
            Err(err) => return Err(err),
        };
        let result = dev.borrow_mut().as_addressable().unwrap().read(clock, relative_addr, data);
        result
    }

    fn write(&mut self, clock: Instant, addr: Address, data: &[u8]) -> Result<(), Error> {
        if self.watchers.iter().any(|a| *a == addr) {
            println!("watch: writing to address {:#06x} with {:?}", addr, data);
            self.watcher_modified = true;
        }

        let (dev, relative_addr) = match self.get_device_at(addr, data.len()) {
            Ok(result) => result,
            Err(err) if self.ignore_unmapped => {
                log::info!("{:?}", err);
                return Ok(());
            },
            Err(err) => return Err(err),
        };
        let result = dev.borrow_mut().as_addressable().unwrap().write(clock, relative_addr, data);
        result
    }
}

/// An adapter for limiting the access requests of a device (eg. CPU) on a `Bus` to the address
/// and data widths of the device
#[derive(Clone)]
pub struct BusPort {
    offset: Address,
    address_mask: Address,
    data_width: u8,
    subdevice: Rc<RefCell<Bus>>,
}

impl BusPort {
    pub fn new(offset: Address, address_bits: u8, data_bits: u8, bus: Rc<RefCell<Bus>>) -> Self {
        Self {
            offset,
            address_mask: (1 << address_bits) - 1,
            data_width: data_bits / 8,
            subdevice: bus,
        }
    }

    pub fn dump_memory(&mut self, clock: Instant, addr: Address, count: Address) {
        self.subdevice
            .borrow_mut()
            .dump_memory(clock, self.offset + (addr & self.address_mask), count)
    }

    #[inline]
    pub fn address_mask(&self) -> Address {
        self.address_mask
    }

    #[inline]
    pub fn data_width(&self) -> u8 {
        self.data_width
    }
}

impl Addressable for BusPort {
    fn size(&self) -> usize {
        self.subdevice.borrow().size()
    }

    fn read(&mut self, clock: Instant, addr: Address, data: &mut [u8]) -> Result<(), Error> {
        let addr = self.offset + (addr & self.address_mask);
        let mut subdevice = self.subdevice.borrow_mut();
        for i in (0..data.len()).step_by(self.data_width as usize) {
            let addr_index = (addr + i as Address) & self.address_mask;
            let end = cmp::min(i + self.data_width as usize, data.len());
            Addressable::read(&mut *subdevice, clock, addr_index, &mut data[i..end])?;
        }
        Ok(())
    }

    fn write(&mut self, clock: Instant, addr: Address, data: &[u8]) -> Result<(), Error> {
        let addr = self.offset + (addr & self.address_mask);
        let mut subdevice = self.subdevice.borrow_mut();
        for i in (0..data.len()).step_by(self.data_width as usize) {
            let addr_index = (addr + i as Address) & self.address_mask;
            let end = cmp::min(i + self.data_width as usize, data.len());
            Addressable::write(&mut *subdevice, clock, addr_index, &data[i..end])?;
        }
        Ok(())
    }
}

pub fn dump_slice(data: &[u8], mut count: usize) {
    let mut addr = 0;
    while count > 0 {
        let mut line = format!("{:#010x}: ", addr);

        let to = if count < 16 { count / 2 } else { 8 };
        for _ in 0..to {
            let word = read_beu16(&data[addr..]);
            write!(line, "{:#06x} ", word).unwrap();
            addr += 2;
            count -= 2;
        }
        println!("{}", line);
    }
}

pub fn dump_memory<Bus, Address, Instant>(bus: &mut Bus, clock: Instant, addr: Address, count: Address)
where
    Bus: BusAccess<Address, Instant = Instant>,
    Address: From<u64> + Into<u64> + Copy,
    Instant: Copy,
{
    let mut addr = addr.into();
    let mut count = count.into();
    while count > 0 {
        let mut line = format!("{:#010x}: ", addr);

        let to = if count < 16 { count / 2 } else { 8 };
        for _ in 0..to {
            let word = bus.read_beu16(clock, Address::from(addr));
            if word.is_err() {
                println!("{}", line);
                return;
            }
            write!(line, "{:#06x} ", word.unwrap()).unwrap();
            addr += 2;
            count -= 2;
        }
        println!("{}", line);
    }
}

impl ErrorType for Error {}

impl BusAccess<u64> for &mut dyn Addressable {
    type Instant = Instant;
    type Error = Error;

    fn read(&mut self, now: Instant, addr: Address, data: &mut [u8]) -> Result<usize, Self::Error> {
        (*self).read(now, addr, data)?;
        Ok(data.len())
    }

    fn write(&mut self, now: Instant, addr: Address, data: &[u8]) -> Result<usize, Self::Error> {
        (*self).write(now, addr, data)?;
        Ok(data.len())
    }
}

impl BusAccess<u64> for Bus {
    type Instant = Instant;
    type Error = Error;

    fn read(&mut self, now: Instant, addr: Address, data: &mut [u8]) -> Result<usize, Self::Error> {
        Addressable::read(self, now, addr, data)?;
        Ok(data.len())
    }

    fn write(&mut self, now: Instant, addr: Address, data: &[u8]) -> Result<usize, Self::Error> {
        Addressable::write(self, now, addr, data)?;
        Ok(data.len())
    }
}