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
use std::io::{Read, Write};
use {types, Error, Header, SectionContent};
use utils::hextab;
use num_traits::{FromPrimitive, ToPrimitive};
use strtab::Strtab;
use section::{Section, SectionHeader};
use std::fmt;

#[derive(Debug, Clone, Eq, PartialEq)]
pub enum SymbolSectionIndex {
    Section(u16), // 1-6551
    Undefined,    // 0
    Absolute,     // 65521,
    Common,       // 6552,
}
impl Default for SymbolSectionIndex {
    fn default() -> SymbolSectionIndex {
        SymbolSectionIndex::Undefined
    }
}

#[derive(Default, Clone)]
pub struct Symbol {
    pub shndx:  SymbolSectionIndex,
    pub value:  u64,
    pub size:   u64,

    pub name:   Vec<u8>,
    pub stype:  types::SymbolType,
    pub bind:   types::SymbolBind,
    pub vis:    types::SymbolVis,

    pub _name:  u32,
}

impl fmt::Debug for Symbol {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f,
               "  {} {:>5.5} {:<7.7} {:<6.6} {:<8.8} {:<3.3} {} ",
               hextab(16, self.value),
               self.size,
               format!("{:?}", self.stype),
               format!("{:?}", self.bind),
               format!("{:?}", self.vis),
               match self.shndx {
                   SymbolSectionIndex::Undefined => String::from("UND"),
                   SymbolSectionIndex::Absolute => String::from("ABS"),
                   SymbolSectionIndex::Common => String::from("COM"),
                   SymbolSectionIndex::Section(i) => format!("{}", i),
               },
               String::from_utf8_lossy(&self.name)
              )
    }
}

impl Symbol {
    fn from_val(
        tab:    Option<&Strtab>,
        _name:  u32,
        info:   u8,
        other:  u8,
        shndx:  u16,
        value:  u64,
        size:   u64,
    ) -> Result<Symbol, Error> {
        let name = match tab {
            Some(tab) => tab.get(_name as usize),
            None => Vec::default(),
        };

        let shndx = match shndx {
            0 => SymbolSectionIndex::Undefined,
            65521 => SymbolSectionIndex::Absolute,
            65522 => SymbolSectionIndex::Common,
            _ if shndx > 0 && shndx < 6552 => SymbolSectionIndex::Section(shndx),
            _ => return Err(Error::InvalidSymbolShndx(String::from_utf8_lossy(&name).into_owned(), shndx)),
        };

        let reb = info & 0xf;
        let stype = match types::SymbolType::from_u8(reb) {
            Some(v) => v,
            None => return Err(Error::InvalidSymbolType(reb)),
        };

        let reb = info >> 4;
        let bind = match types::SymbolBind::from_u8(reb) {
            Some(v) => v,
            None => return Err(Error::InvalidSymbolBind(reb)),
        };

        let reb = other & 0x3;
        let vis = match types::SymbolVis::from_u8(reb) {
            Some(v) => v,
            None => return Err(Error::InvalidSymbolVis(reb)),
        };

        Ok(Symbol {
            shndx: shndx,
            value: value,
            size: size,

            name: name,
            stype: stype,
            bind: bind,
            vis: vis,

            _name: _name,
        })
    }

    pub fn entsize(eh: &Header) -> usize {
        match eh.ident_class {
            types::Class::Class64 => 24,
            types::Class::Class32 => 16,
        }
    }

    pub fn from_reader<R>(
        mut io: R,
        linked: Option<&SectionContent>,
        eh: &Header,
    ) -> Result<SectionContent, Error>
    where
        R: Read,
    {
        let tab = match linked {
            None => None,
            Some(&SectionContent::Strtab(ref s)) => Some(s),
            any => return Err(Error::LinkedSectionIsNotStrtab{
                during: "reading symbols",
                link: any.map(|v|v.clone()),
            }),
        };

        let mut r = Vec::new();
        let mut b = vec![0; Self::entsize(eh)];
        while io.read(&mut b)? > 0 {
            let mut br = &b[..];
            elf_dispatch_endianness!(eh => {
                let _name = read_u32(&mut br)?;
                r.push(match eh.ident_class {
                    types::Class::Class64 => {
                        let info = b[4];
                        let other = b[5];
                        br = &b[6..];
                        let shndx = read_u16(&mut br)?;
                        let value = read_u64(&mut br)?;
                        let size  = read_u64(&mut br)?;

                        Symbol::from_val(tab, _name, info, other, shndx, value, size)?
                    }
                    types::Class::Class32 => {
                        let value = read_u32(&mut br)?;
                        let size  = read_u32(&mut br)?;
                        let info  = b[12];
                        let other = b[13];
                        br = &b[14..];
                        let shndx = read_u16(&mut br)?;

                        Symbol::from_val(tab, _name, info, other, shndx, value as u64, size as u64)?
                    }
                })
            })
        }

        Ok(SectionContent::Symbols(r))
    }

    pub fn to_writer<W>(
        &self,
        mut io: W,
        eh: &Header,
    ) -> Result<(usize), Error>
    where
        W: Write,
    {
        let info = (self.bind.to_u8().unwrap() << 4) + (self.stype.to_u8().unwrap() & 0xf);
        let other = self.vis.to_u8().unwrap();

        let shndx = match self.shndx {
            SymbolSectionIndex::Section(i) => i,
            SymbolSectionIndex::Undefined => 0,
            SymbolSectionIndex::Absolute => 65521,
            SymbolSectionIndex::Common => 65522,
        };

        elf_write_u32!(eh, io, self._name)?;

        Ok(match eh.ident_class {
            types::Class::Class64 => {
                io.write(&[info, other])?;
                elf_write_u16!(eh, io, shndx)?;
                elf_write_u64!(eh, io, self.value)?;
                elf_write_u64!(eh, io, self.size)?;

                2+2+8+8
            }
            types::Class::Class32 => {
                elf_write_u32!(eh, io, self.value as u32)?;
                elf_write_u32!(eh, io, self.size as u32)?;
                io.write(&[info, other])?;
                elf_write_u16!(eh, io, shndx)?;

                4+4+2+2
            }
        })
    }

    pub fn sync(&mut self, linked: Option<&mut SectionContent>, _: &Header) -> Result<(), Error> {
        match linked {
            Some(&mut SectionContent::Strtab(ref mut strtab)) => {
                self._name = strtab.insert(&self.name) as u32;
            }
            any => return Err(Error::LinkedSectionIsNotStrtab{
                during: "syncing symbols",
                link: any.map(|v|v.clone()),
            }),
        }
        Ok(())
    }
}

pub fn sysv_hash(s: &String) -> u64 {
    let mut h: u64 = 0;
    let mut g: u64;

    for byte in s.bytes() {
        h = (h << 4) + byte as u64;
        g = h & 0xf0000000;
        if g > 0 {
            h ^= g >> 24;
        }
        h &= !g;
    }
    return h;
}


pub fn symhash(eh: &Header, symbols: &Vec<Symbol>, link: u32) -> Result<Section, Error> {
    assert!(symbols.len() > 0);
    //TODO i'm too lazy to do this correctly now, so we'll just emit a hashtable with nbuckets  == 1
    let mut b = Vec::new();
    {
        let io = &mut b;
        elf_write_uclass!(eh, io, 1)?; //nbuckets
        elf_write_uclass!(eh, io, symbols.len() as u64)?; //nchains

        elf_write_uclass!(eh, io, 1)?; //the bucket. pointing at symbol 1

        elf_write_uclass!(eh, io, 0)?; //symbol 0

        //the chains. every symbol just points at the next, because nbuckets == 1
        for i in 1..symbols.len() - 1 {
            elf_write_uclass!(eh, io, i as u64 + 1)?;
        }

        //except the last one
        elf_write_uclass!(eh, io, 0)?;
    }

    Ok(Section {
        name: b".hash".to_vec(),
        header: SectionHeader {
            name: 0,
            shtype: types::SectionType::HASH,
            flags: types::SectionFlags::ALLOC,
            addr: 0,
            offset: 0,
            size: b.len() as u64,
            link: link,
            info: 0,
            addralign: 0,
            entsize: 8, // or 4 for CLass32
        },
        content: SectionContent::Raw(b),
        addrlock: false,
    })
}