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
use types::Endianness;
use utils;
use structure::{Field,Structure};
use std::collections::HashMap;
// use fxhash::FxHashMap as HashMap;
use std::str;
use file_block::FileBlock;
use file::Header;
use types::{Error,Result};

fn sdna_string_list_and_next_pos(data: &[u8], endianness: Endianness) -> (Vec<String>, usize){
    let num_strings = utils::read_i32(data, endianness) as usize;
    let str_iter =  utils::ByteStringIter::new(&data[4..], num_strings);
    let mut next_pos = 0;
    let strings = str_iter.map(|(name, pos)|{
        next_pos = pos;
        name.to_string()
    }).collect();
    (strings, next_pos + 4)
}


fn sdna_u16_list_with_size(data: &[u8], num_elements: usize, endianness: Endianness) -> Vec<u16>{
    data.chunks(2).take(num_elements).map(|two_bytes| utils::read_u16(two_bytes, endianness)).collect()
}

#[derive(Clone)]
pub struct SDNA{
    block: FileBlock,
    endianness: Endianness,
    pointer_bytes: usize,
    names: Vec<String>,                         // fields names in any struct
    names_index: HashMap<String, usize>,        // field name to it's position in the Vec
    types: Vec<String>,                         // types names
    types_index: HashMap<String, usize>,        // type name to it's position in the Vec
    lengths: Vec<u16>,                          // length of every type, same len/order as type
    structures: Vec<Structure>,                 // every struct
    // structure_ids_index: HashMap<u16, usize>,    // struct name id -> pos in structures
    structure_names_index: HashMap<String, usize>    // struct name -> pos in structures
}

impl SDNA{
    pub fn new(header: &Header, block: FileBlock) -> Result<SDNA>{
        if str::from_utf8(&block.data[0..4]).unwrap() != "SDNA"{
            return Err(Error("Error parsing dna, found dna header != SDNA".to_string()))
        }

        if str::from_utf8(&block.data[4..8]).unwrap() != "NAME"{
            return Err(Error("Error parsing dna, found names header != NAME".to_string()))
        }
        let endianness = header.endianness().unwrap();

        // Parse names
        let begin_names = 8;
        let (names, next) = sdna_string_list_and_next_pos(&block.data[begin_names..], endianness);
        let names_index = names.iter().cloned().enumerate().map(|(i, n)| (n,i)).collect();

        // Parse types
        let next = utils::next_multiple(next + begin_names, 4);
        if str::from_utf8(&block.data[next..next+4]).unwrap() != "TYPE"{
            return Err(Error("Error parsing dna, found type header != TYPE".to_string()))
        }
        let begin_types = next + 4;
        let (types, next) = sdna_string_list_and_next_pos(&block.data[begin_types..], endianness);
        let types_index = types.iter().cloned().enumerate().map(|(i,t)| (t,i)).collect();

        // Parse lengths
        let next = utils::next_multiple(next + begin_types, 4);
        if str::from_utf8(&block.data[next..next+4]).unwrap() != "TLEN"{
            return Err(Error("Error parsing dna, found tlen header != TLEN".to_string()))
        }
        let begin_lengths = next + 4;
        let lengths = sdna_u16_list_with_size(&block.data[begin_lengths..], types.len(), endianness);

        // Parse structures
        let next = utils::next_multiple(begin_lengths + 2*types.len(), 4);
        if str::from_utf8(&block.data[next..next+4]).unwrap() != "STRC"{
            return Err(Error("Error parsing dna, found structures header != STRC".to_string()))
        }
        let begin_structures = next + 4;
        let mut dna = SDNA{
            block: block,
            endianness: endianness,
            pointer_bytes: header.pointer_bytes().unwrap(),
            names: names,
            names_index: names_index,
            types: types,
            types_index: types_index,
            lengths: lengths,
            structures: Vec::new(),
            structure_names_index: HashMap::default(),
            // structure_ids_index: HashMap::default(),
        };
        dna.fill_structures(begin_structures);

        Ok(dna)
    }

    fn fill_structures(&mut self, pos_structures: usize){
        let data = &self.block.data[pos_structures..];
        let num_elements = utils::read_i32(data, self.endianness) as usize;
        let mut pos = 0;

        self.structures = (0..num_elements).filter_map(|e|{
            let structure = Structure::new(&data[pos..], self);
            pos += 4 + structure.fields().len() * 4;
            if e > 0{
                Some(structure)
            }else{
                None
            }
        }).collect();

        // let (structure_names_index, structure_ids_index) = self.structures.iter().enumerate().map(|(i,s)|{
        //     ((s.name().to_owned(), i), (s.type_idx(), i))
        // }).unzip();
        // self.structure_names_index = structure_names_index;
        // self.structure_ids_index = structure_ids_index;


        self.structure_names_index = self.structures.iter().enumerate().map(|(i,s)|{
            (s.name().to_owned(), i)
        }).collect();
    }

    pub fn size_of_type_idx(&self, type_idx: u16) -> u16{
        self.lengths[type_idx as usize]
    }

    pub fn size_of(&self, type_name: &str) -> Option<u16>{
        self.lengths.get(*self.names_index.get(type_name)?).cloned()
    }

    pub fn type_name(&self, type_idx: u16) -> &str{
        &self.types[type_idx as usize]
    }

    pub fn name(&self, name_idx: u16) -> &str{
        &self.names[name_idx as usize]
    }

    pub fn name_idx(&self, name: &str) -> Option<u16>{
        self.names_index.get(name).map(|idx| *idx as u16)
    }

    pub fn type_idx(&self, name: &str) -> Option<u16>{
        self.types_index.get(name).map(|idx| *idx as u16)
    }

    pub fn structure_idx(&self, name: &str) -> Option<i32>{
        self.structure_names_index.get(name).map(|idx| *idx as i32)
    }

    // pub fn structure_by_type_idx(&self, type_idx: u16) -> Result<&Structure>{
    //     match self.structure_ids_index.get(&type_idx){
    //         Some(idx) => Ok(&self.structures[*idx]),
    //         None => Err(Error(format!("Couldn't find structure for type id {}", type_idx)))
    //     }

    // }

    pub fn structure(&self, name: &str) -> Result<&Structure>{
        match self.structure_names_index.get(name){
            Some(idx) => Ok(&self.structures[*idx]),
            None => Err(Error(format!("Couldn't find structure named {}", name)))
        }
    }

    pub fn structures(&self) -> &[Structure]{
        &self.structures
    }

    pub fn field_structure(&self, field: &Field) -> Result<&Structure>{
        self.structure(field.type_name())
    }

    pub fn endianness(&self) -> Endianness{
        self.endianness
    }

    pub fn pointer_size(&self) -> usize{
        if self.pointer_bytes == 8{
            64
        }else{
            32
        }
    }

    pub fn pointer_bytes(&self) -> usize{
        self.pointer_bytes
    }

    pub fn parse_ptr(&self, ptr_data: &[u8]) -> Result<u64>{
        if ptr_data.len() < self.pointer_bytes(){
            Err(Error(format!("Tried to parse pointer of size {} from data of size {}", self.pointer_bytes(), ptr_data.len())))
        }else{
            let addr = if self.pointer_size() == 32{
                utils::read_u32(ptr_data, self.endianness()) as u64
            }else{
                utils::read_u64(ptr_data, self.endianness())
            };
            if addr == 0{
                Err(Error("nullptr".to_string()))
            }else{
                Ok(addr)
            }
        }
    }
}