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
use header::Header;
use types;
use error::Error;
use section::*;
use symbol::*;
use dynamic::*;
use relocation::*;
use strtab::*;
use segment::*;
use std::io::{Read, Write, Seek, SeekFrom};
use std::io::BufWriter;
use std;
use std::collections::HashSet;
pub struct Elf {
    pub header:   Header,
    pub segments: Vec<SegmentHeader>,
    pub sections: Vec<Section>,
    s_lookup: Option<HashSet<String>>,
}
impl Default for Elf {
    fn default() -> Self {
        let mut r = Elf {
            header:   Header::default(),
            segments: Vec::default(),
            sections: Vec::default(),
            s_lookup: None,
        };
        
        
        
        r
    }
}
impl Elf {
    pub fn from_reader<R>(io: &mut R) -> Result<Elf, Error> where R: Read + Seek {
        let mut r = Elf::default();
        r.header = Header::from_reader(io)?;
        
        r.segments.clear();
        io.seek(SeekFrom::Start(r.header.phoff))?;
        for _ in 0..r.header.phnum {
            let segment = SegmentHeader::from_reader(io, &r.header)?;
            r.segments.push(segment);
        }
        
        r.sections.clear();
        io.seek(SeekFrom::Start(r.header.shoff))?;
        let mut section_headers = Vec::new();
        for _ in 0..r.header.shnum {
            section_headers.push(SectionHeader::from_reader(io, &r.header)?);
        }
        
        for sh in section_headers {
            r.sections.push(Section{
                name: String::default(),
                content: match sh.shtype {
                    types::SectionType::NULL | types::SectionType::NOBITS => {
                        SectionContent::None
                    },
                    _ => {
                        io.seek(SeekFrom::Start(sh.offset))?;
                        let mut bb = vec![0; sh.size as usize];
                        io.read_exact(&mut bb)?;
                        SectionContent::Raw(bb)
                    }
                },
                header: sh,
            });
        }
        
        let shstrtab = match r.sections.get(r.header.shstrndx as usize) {
            None => return Err(Error::MissingShstrtabSection),
            Some(sec) => {
                match sec.content {
                    SectionContent::Raw(ref s) => s,
                    _ => return Err(Error::MissingShstrtabSection),
                }
            }
        }.clone();
        for ref mut sec in &mut r.sections {
            sec.name = String::from_utf8_lossy(
                shstrtab[sec.header.name as usize ..].split(|e|*e==0).next().unwrap_or(&[0;0])
                ).into_owned();
        }
        Ok(r)
    }
    fn load(&self, raw: Vec<u8>, sh: &SectionHeader, linked: Option<&SectionContent>)
        -> Result<(SectionContent), Error> {
            Ok(match sh.shtype {
                types::SectionType::STRTAB => {
                    let io = &raw[..];
                    Strtab::from_reader(io, linked, &self.header)?
                },
                types::SectionType::RELA   => {
                    let io = &raw[..];
                    Relocation::from_reader(io, linked, &self.header)?
                },
                types::SectionType::SYMTAB | types::SectionType::DYNSYM => {
                    let io = &raw[..];
                    Symbol::from_reader(io, linked, &self.header)?
                }
                types::SectionType::DYNAMIC => {
                    let io = &raw[..];
                    Dynamic::from_reader(io, linked, &self.header)?
                }
                _ => SectionContent::Raw(raw),
            })
        }
    pub fn load_at(&mut self, i: usize) -> Result<(), Error>{
        let is_loaded = match self.sections[i].content {
            SectionContent::Raw(_) | SectionContent::None => false,
            _ => true,
        };
        if is_loaded {
            return Ok(())
        }
        
        let mut sec = std::mem::replace(&mut self.sections[i], Section::default());
        {
            let linked = {
                if sec.header.link < 1 || sec.header.link as usize >= self.sections.len() {
                    None
                } else {
                    self.load_at(sec.header.link as usize)?;
                    Some(&self.sections[sec.header.link as usize].content)
                }
            };
            sec.content = match sec.content {
                SectionContent::Raw(raw) => {
                    self.load(raw, &sec.header, linked)?
                },
                any => any,
            };
        }
        
        self.sections[i] = sec;
        Ok(())
    }
    pub fn load_all(&mut self) -> Result<(), Error> {
        for i in 0..self.sections.len() {
            self.load_at(i)?;
        }
        Ok(())
    }
    fn store(eh: &Header, mut sec: Section, mut linked: Option<&mut SectionContent>) -> Result<(Section), Error> {
        match sec.content {
            SectionContent::Relocations(vv) => {
                let mut raw = Vec::new();
                for v in vv {
                    v.to_writer(&mut raw, None, eh)?;
                }
                sec.header.entsize  = Relocation::entsize(eh) as u64;
                sec.header.size     = raw.len() as u64;
                sec.content         = SectionContent::Raw(raw);
            },
            SectionContent::Symbols(vv) => {
                for (i, sym) in vv.iter().enumerate() {
                    if sym.bind == types::SymbolBind::GLOBAL {
                        sec.header.info = i as u32;
                        break;
                    }
                }
                let mut raw = Vec::new();
                for v in vv {
                    v.to_writer(&mut raw, linked.as_mut().map(|r|&mut **r), eh)?;
                }
                sec.header.entsize  = Symbol::entsize(eh) as u64;
                sec.header.size     = raw.len() as u64;
                sec.content         = SectionContent::Raw(raw);
            },
            SectionContent::Dynamic(vv) => {
                let mut raw = Vec::new();
                for v in vv {
                    v.to_writer(&mut raw, linked.as_mut().map(|r|&mut **r), eh)?;
                }
                sec.header.entsize  = Dynamic::entsize(eh) as u64;
                sec.header.size     = raw.len() as u64;
                sec.content         = SectionContent::Raw(raw);
            },
            SectionContent::Strtab(v) => {
                let mut raw = Vec::new();
                v.to_writer(&mut raw, None, eh)?;
                sec.header.entsize  = Strtab::entsize(eh) as u64;
                sec.header.size     = raw.len() as u64;
                sec.content         = SectionContent::Raw(raw);
            },
            SectionContent::None | SectionContent::Raw(_) => {},
        };
        Ok(sec)
    }
    fn store_at(&mut self, i: usize) -> Result<(bool), Error>{
        let is_stored = match self.sections[i].content {
            SectionContent::Raw(_) | SectionContent::None => true,
            _ => false,
        };
        if is_stored {
            return Ok((false))
        }
        
        let mut sec = std::mem::replace(&mut self.sections[i], Section::default());
        {
            
            
            let linked = {
                if sec.header.link < 1 || sec.header.link as usize >= self.sections.len() {
                    None
                } else {
                    self.load_at(sec.header.link as usize)?;
                    Some(&mut self.sections[sec.header.link as usize].content)
                }
            };
            sec = Elf::store(&self.header, sec, linked)?;
        }
        
        self.sections[i] = sec;
        Ok((true))
    }
    pub fn store_all(&mut self) -> Result<(), Error> {
        self.header.shstrndx = match self.sections.iter().position(|s|s.name == ".shstrtab") {
            Some(i) => i as u16,
            None => return Err(Error::MissingShstrtabSection),
        };
        loop {
            let mut still_need_to_store = false;
            for i in 0..self.sections.len(){
                still_need_to_store = still_need_to_store || self.store_at(i)?;
            }
            if !still_need_to_store {
                break
            }
        }
        Ok(())
    }
    
    
    pub fn sync_all(&mut self) -> Result<(), Error> {
        match self.sections.iter().position(|s|s.name == ".shstrtab") {
            Some(i) => {
                self.header.shstrndx = i as u16;
                let mut shstrtab = std::mem::replace(
                    &mut self.sections[self.header.shstrndx as usize].content, SectionContent::default());
                for sec in &mut self.sections {
                    sec.header.name = shstrtab.as_strtab_mut().unwrap().insert(sec.name.as_bytes().to_vec()) as u32;
                }
                self.sections[self.header.shstrndx as usize].content = shstrtab;
            }
            None => {},
        };
        let mut dirty : Vec<usize> = (0..self.sections.len()).collect();
        while dirty.len() > 0 {
            for i in std::mem::replace(&mut dirty, Vec::new()).iter() {
                
                let mut sec = std::mem::replace(&mut self.sections[*i], Section::default());
                {
                    let linked = {
                        if sec.header.link < 1 || sec.header.link as usize >= self.sections.len() {
                            None
                        } else {
                            dirty.push(sec.header.link as usize);
                            self.load_at(sec.header.link as usize)?;
                            Some(&mut self.sections[sec.header.link as usize].content)
                        }
                    };
                    sec.sync(&self.header, linked)?;
                }
                
                self.sections[*i] = sec;
            }
        }
        Ok(())
    }
    pub fn to_writer<R>(&mut self, io: &mut R) -> Result<(), Error> where R: Write + Seek {
        io.seek(SeekFrom::Start(0))?;
        let mut off = self.header.size();
        io.write(&vec![0;off])?;
        
        
        
        if self.segments.len() > 0 {
            self.header.phoff = off as u64;
            for seg in &self.segments {
                seg.to_writer(&self.header, io)?;
            }
            let at = io.seek(SeekFrom::Current(0))? as usize;
            self.header.phnum       = self.segments.len() as u16;
            self.header.phentsize   = ((at - off)/ self.segments.len()) as u16;
            off = at;
        }
        let headers : Vec<SectionHeader> = self.sections.iter().map(|s|s.header.clone()).collect();
        let mut sections = std::mem::replace(&mut self.sections, Vec::new());
        
        sections.sort_unstable_by(|a,b|a.header.offset.cmp(&b.header.offset));
        for sec in sections {
            let off = io.seek(SeekFrom::Current(0))? as usize;
            assert_eq!(io.seek(SeekFrom::Start(sec.header.offset))?, sec.header.offset);
            match sec.content {
                SectionContent::Raw(ref v) => {
                    if off > sec.header.offset as usize {
                        println!("BUG: section layout is broken. \
would write section '{}' at position 0x{:x} over previous section that ended at 0x{:x}",
sec.name, sec.header.offset, off);
                    }
                    io.write(&v.as_ref())?;
                }
                _ => {},
            }
        }
        
        let mut off = io.seek(SeekFrom::End(0))? as usize;
        self.header.shoff = off as u64;
        for sec in &headers{
            sec.to_writer(&self.header, io)?;
        }
        let at = io.seek(SeekFrom::Current(0))? as usize;
        self.header.shnum       = headers.len() as u16;
        self.header.shentsize   = SectionHeader::entsize(&self.header) as u16;
        off = at;
        
        self.header.ehsize = self.header.size() as u16;
        io.seek(SeekFrom::Start(0))?;
        self.header.to_writer(io)?;
        Ok(())
    }
    
    pub fn remove_section(&mut self, at: usize) -> Result<(Section), Error> {
        let r = self.sections.remove(at);
        for sec in &mut self.sections {
            if sec.header.link == at as u32{
                sec.header.link = 0;
                
            } else if sec.header.link > at as u32{
                sec.header.link -= 1;
            }
            if sec.header.flags.contains(types::SectionFlags::INFO_LINK) {
                if sec.header.info == at as u32{
                    sec.header.info = 0;
                   
                } else if sec.header.info > at as u32{
                    sec.header.info -= 1;
                }
            }
        }
        Ok((r))
    }
    pub fn insert_section(&mut self, at: usize, sec: Section) -> Result<(), Error> {
        self.sections.insert(at, sec);
        for sec in &mut self.sections {
            if sec.header.link >= at as u32{
                sec.header.link += 1;
            }
            if sec.header.flags.contains(types::SectionFlags::INFO_LINK) {
                if sec.header.info > at as u32{
                    sec.header.info += 1;
                }
            }
        }
        Ok(())
    }
    pub fn move_section(&mut self, from: usize, mut to:usize) -> Result<(), Error> {
        if to == from {
            return Ok(())
        }
        if to > from {
            to -= 1;
        }
        for sec in &mut self.sections {
            if sec.header.link == from as u32{
                sec.header.link = 999999;
            }
            if sec.header.flags.contains(types::SectionFlags::INFO_LINK) {
                if sec.header.info == from as u32{
                    sec.header.info = 999999;
                }
            }
        }
        let sec = self.remove_section(from)?;
        self.insert_section(to, sec)?;
        for sec in &mut self.sections {
            if sec.header.link == 999999{
                sec.header.link = to as u32;
            }
            if sec.header.flags.contains(types::SectionFlags::INFO_LINK) {
                if sec.header.info == 999999{
                    sec.header.info = to as u32;
                }
            }
        }
        Ok(())
    }
}
impl Elf {
    
    
    
    
    
    
    pub fn contains_symbol(&mut self, name: &str) -> Result<bool, Error> {
        if None == self.s_lookup {
            let mut hm = HashSet::new();
            for i in self.sections.iter().enumerate().filter_map(|(i, ref sec)|{
                if sec.header.shtype == types::SectionType::SYMTAB ||
                    sec.header.shtype == types::SectionType::DYNSYM {
                        Some (i)
                    } else {
                        None
                    }
            }).collect::<Vec<usize>>().iter() {
                self.load_at(*i)?;
                for sym in self.sections[*i].content.as_symbols().unwrap() {
                    if sym.bind != types::SymbolBind::LOCAL && sym.shndx != SymbolSectionIndex::Undefined {
                        hm.insert(sym.name.clone());
                    }
                }
            };
            self.s_lookup = Some(hm);
        }
        Ok(self.s_lookup.as_ref().unwrap().contains(name))
    }
}