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
use ihex;
use ihex::record::Record::*;

use std::{
    fs::File,
    io::{Read, Seek, SeekFrom},
    path::Path,
};

use super::*;
use crate::{
    config::{MemoryRange, MemoryRegion},
    session::Session,
};

use thiserror::Error;

pub struct BinOptions {
    /// The address in memory where the binary will be put at.
    base_address: Option<u32>,
    /// The number of bytes to skip at the start of the binary file.
    skip: u32,
}

pub enum Format {
    Bin(BinOptions),
    Hex,
    Elf,
}

#[derive(Debug, Error)]
pub enum FileDownloadError {
    #[error("{0}")]
    FlashLoader(#[from] FlashLoaderError),
    #[error("{0}")]
    IhexRead(#[from] ihex::reader::ReaderError),
    #[error("{0}")]
    IO(#[from] std::io::Error),
    #[error("Object Error: {0}.")]
    Object(&'static str),
}

/// Downloads a file at `path` into flash.
pub fn download_file_with_progress_reporting(
    session: &Session,
    path: &Path,
    format: Format,
    memory_map: &[MemoryRegion],
    progress: &FlashProgress,
) -> Result<(), FileDownloadError> {
    download_file_internal(session, path, format, memory_map, progress)
}

/// Downloads a file at `path` into flash.
pub fn download_file(
    session: &Session,
    path: &Path,
    format: Format,
    memory_map: &[MemoryRegion],
) -> Result<(), FileDownloadError> {
    download_file_internal(
        session,
        path,
        format,
        memory_map,
        &FlashProgress::new(|_| {}),
    )
}

/// Downloads a file at `path` into flash.
fn download_file_internal(
    session: &Session,
    path: &Path,
    format: Format,
    memory_map: &[MemoryRegion],
    progress: &FlashProgress,
) -> Result<(), FileDownloadError> {
    let mut file = match File::open(path) {
        Ok(file) => file,
        Err(e) => return Err(FileDownloadError::IO(e)),
    };
    let mut buffer = vec![];
    let mut buffer_vec = vec![];
    // IMPORTANT: Change this to an actual memory map of a real chip
    let mut loader = FlashLoader::new(memory_map, false);

    match format {
        Format::Bin(options) => download_bin(&mut buffer, &mut file, &mut loader, options),
        Format::Elf => download_elf(&mut buffer, &mut file, &mut loader),
        Format::Hex => download_hex(&mut buffer_vec, &mut file, &mut loader),
    }?;

    loader
        // TODO: hand out chip erase flag
        .commit(session, progress, false)
        .map_err(FileDownloadError::FlashLoader)
}

/// Starts the download of a binary file.
fn download_bin<'b, T: Read + Seek>(
    buffer: &'b mut Vec<u8>,
    file: &'b mut T,
    loader: &mut FlashLoader<'_, 'b>,
    options: BinOptions,
) -> Result<(), FileDownloadError> {
    // Skip the specified bytes.
    file.seek(SeekFrom::Start(u64::from(options.skip)))?;

    file.read_to_end(buffer)?;

    loader.add_data(
        if let Some(address) = options.base_address {
            address
        } else {
            // If no base address is specified use the start of the boot memory.
            // TODO: Implement this as soon as we know targets.
            0
        },
        buffer.as_slice(),
    )?;

    Ok(())
}

/// Starts the download of a hex file.
fn download_hex<'b, T: Read + Seek>(
    buffer: &'b mut Vec<(u32, Vec<u8>)>,
    file: &mut T,
    loader: &mut FlashLoader<'_, 'b>,
) -> Result<(), FileDownloadError> {
    let mut _extended_segment_address = 0;
    let mut extended_linear_address = 0;

    let mut data = String::new();
    file.read_to_string(&mut data)?;

    for record in ihex::reader::Reader::new(&data) {
        let record = record?;
        match record {
            Data { offset, value } => {
                let offset = extended_linear_address | offset as u32;
                buffer.push((offset, value));
            }
            EndOfFile => return Ok(()),
            ExtendedSegmentAddress(address) => {
                _extended_segment_address = address * 16;
            }
            StartSegmentAddress { .. } => (),
            ExtendedLinearAddress(address) => {
                extended_linear_address = (address as u32) << 16;
            }
            StartLinearAddress(_) => (),
        };
    }
    for (offset, data) in buffer {
        loader.add_data(*offset, data.as_slice())?;
    }
    Ok(())
}

/// Starts the download of a elf file.
fn download_elf<'b, T: Read + Seek>(
    buffer: &'b mut Vec<u8>,
    file: &'b mut T,
    loader: &mut FlashLoader<'_, 'b>,
) -> Result<(), FileDownloadError> {
    file.read_to_end(buffer)?;

    use goblin::elf::program_header::*;

    if let Ok(binary) = goblin::elf::Elf::parse(&buffer.as_slice()) {
        for ph in &binary.program_headers {
            if ph.p_type == PT_LOAD && ph.p_filesz > 0 {
                log::debug!("Found loadable segment containing:");

                let sector: core::ops::Range<u32> =
                    ph.p_offset as u32..ph.p_offset as u32 + ph.p_filesz as u32;

                for sh in &binary.section_headers {
                    if sector.contains_range(
                        &(sh.sh_offset as u32..sh.sh_offset as u32 + sh.sh_size as u32),
                    ) {
                        log::debug!("{:?}", &binary.shdr_strtab[sh.sh_name]);
                        #[cfg(feature = "hexdump")]
                        for line in hexdump::hexdump_iter(
                            &buffer[sh.sh_offset as usize..][..sh.sh_size as usize],
                        ) {
                            log::trace!("{}", line);
                        }
                    }
                }

                loader.add_data(
                    ph.p_paddr as u32,
                    &buffer[ph.p_offset as usize..][..ph.p_filesz as usize],
                )?;
            }
        }
    }
    Ok(())
}