elfkit 0.0.7

an elf parser and manipulation library in pure rust
Documentation
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
extern crate indexmap;

use {Header, types, symbol, relocation, section, Error};
use std;
use std::io::Write;
use std::collections::hash_map::{self, HashMap};
use std::collections::HashSet;
use loader::{self, Loader};
use std::sync::atomic::{self, AtomicUsize};

pub type LinkGlobalId = usize;

pub struct LinkableSymbol {
    pub obj:    LinkGlobalId,
    pub sym:    symbol::Symbol,
}

pub struct Object {
    /// the link layout global id, assigned by the symbolic linker
    pub lid:        LinkGlobalId,

    /// loader hash of the original object
    pub hash:       String,

    /// name of the object + section name
    pub name:       String,

    /// copy of the original objects elf Header
    pub header:     Header,

    /// the actual section extracted from the object
    pub section:    section::Section,

    /// relocations that need to be applied to this section
    /// reloc.sym points at SymbolicLinker.symtab
    pub relocs:     Vec<relocation::Relocation>,

    // global source object id. this is used for debugging
    oid:        LinkGlobalId,
}

#[derive(Default)]
pub struct SymbolicLinker {
    pub objects: HashMap<LinkGlobalId, Object>,
    pub symtab:  Vec<LinkableSymbol>,

    lookup:      HashMap<Vec<u8>, usize>,
    lid_counter: AtomicUsize,

    objects_seen: HashSet<String>,
}

impl SymbolicLinker {
    pub fn link_all(&mut self, loader: Vec<loader::State>) -> Result<(), Error> {
        let loader = loader.load_all(&|e,name| {
            println!("elfkit::Linker {:?} while loading {}", e, name);
            Vec::with_capacity(0)
        });
        self.objects.reserve(loader.len());
        for ma in loader {
            if let loader::State::Object{name, hash, header, symbols, sections} = ma {
                if self.objects_seen.insert(hash.clone()) {
                    self.insert_object(name, hash, header, symbols, sections)?;
                }
            }
        }
        Ok(())
    }
    pub fn link(&mut self, mut loader: Vec<loader::State>) -> Result<(), Error> {
        loop {
            let (l2, matches) = self.link_iteration(loader);
            loader = l2;
            if matches.len() == 0 {
                for link in self.symtab.iter() {
                    if link.sym.shndx == symbol::SymbolSectionIndex::Undefined &&
                        link.sym.bind == types::SymbolBind::GLOBAL {
                        return Err(Error::UndefinedReference{
                            obj: self.objects[&link.obj].name.clone(),
                            sym: String::from_utf8_lossy(&link.sym.name).into_owned(),
                        });
                    }
                }
                break;
            }

            self.objects.reserve(matches.len());
            for ma in matches {
                if let loader::State::Object{name, hash, header, symbols, sections} = ma {
                    if self.objects_seen.insert(hash.clone()) {
                        self.insert_object(name, hash, header, symbols, sections)?;
                    }
                }
            }
        }
        Ok(())
    }

    fn link_iteration(&mut self, loader: Vec<loader::State>) -> (Vec<loader::State>, Vec<loader::State>) {
        let (state2, matches) : (Vec<loader::State>, Vec<loader::State>) = {
            let undefined_refs = self.symtab.iter().filter_map(|link|{
                match link.sym.shndx {
                    symbol::SymbolSectionIndex::Undefined => {
                        if link.sym.bind == types::SymbolBind::GLOBAL {
                            Some(link.sym.name.as_ref())
                        } else {
                            None
                        }
                    },
                    symbol::SymbolSectionIndex::Common => {
                        //note that this will only pull in objects that have this symbol as global,
                        //not those who merely also define it as common
                        Some(link.sym.name.as_ref())
                    },
                    _ => None,
                }
            }).collect();

            loader.load_if(&undefined_refs, &|e,name| {
                println!("elfkit::Linker {:?} while loading {}", e, name);
                Vec::with_capacity(0)
            })
        };
        (state2, matches)
    }

    fn insert_object(&mut self, name: String, hash:String, header: Header, symbols: Vec<symbol::Symbol>,
                     sections: Vec<(usize, section::Section, Vec<relocation::Relocation>)>)
        -> Result<(), Error>  {

        assert!((sections.len() as u16) <= header.shnum,
        "incoming object header.shnum is {} but loader gave us {} sections ", header.shnum, sections.len());
        let lid_base = self.lid_counter.fetch_add(header.shnum as usize, atomic::Ordering::Acquire);

        let locations = match self.link_locations(lid_base, symbols) {
            Ok(v) => v,
            Err(Error::ConflictingSymbol{sym, obj1_name, obj1_hash, ..}) => {
                return Err(Error::ConflictingSymbol{sym, obj1_name, obj2_name:name,
                    obj1_hash, obj2_hash: hash});
            },
            Err(e) => return Err(e),
        };


        let name = name.split("/").last().unwrap().to_owned();
        for (sec_shndx, sec, mut relocs) in sections {

            // point the relocs at the global symtab
            for reloc in &mut relocs {
                reloc.sym = locations[reloc.sym as usize] as u32;
            };

            self.objects.insert(lid_base + sec_shndx as usize, Object {
                oid:        lid_base,
                lid:        lid_base + sec_shndx as usize,
                hash:       hash.clone(),
                name:       name.clone() + "("+ &String::from_utf8_lossy(&sec.name) + ")",
                header:     header.clone(),
                section:    sec,
                relocs:     relocs,
            });
        }

        // TODO insert a fake object at base + 0 so error messages
        // can correctly report the name of an object when a Needed
        // symbol isn't statisfied
        // this is a bit hackish tho, and we need to rely on gc()
        // to remove the crap object before layout

        self.objects.insert(lid_base, Object {
            oid:        lid_base,
            lid:        lid_base,
            hash:       hash.clone(),
            name:       name.clone(),
            header:     header.clone(),
            section:    section::Section::default(),
            relocs:     Vec::new(),
        });

        Ok(())
    }

    fn link_locations(&mut self, lid_base: LinkGlobalId, symbols: Vec<symbol::Symbol>)
        -> Result<Vec<usize>, Error> {

        let mut locations = Vec::with_capacity(symbols.len());
        for mut sym in symbols {
            match sym.shndx {
                symbol::SymbolSectionIndex::Undefined => {
                    if sym.name == b"_GLOBAL_OFFSET_TABLE_" {
                        //emit as not linkable, because nothing should relocate here
                        //the symbol appears to be mainly a hint that the linker needs to
                        //emit a GOT. which it knows from relocs anyway, so this appears to
                        //be kinda useless. We could emit a fake symbol to statisy it,
                        //but i want to ensure really nothing actually uses this symbol.
                        //Absolute will show up as error when a reloc points to it.
                        sym.shndx = symbol::SymbolSectionIndex::Absolute;
                    }
                    if sym.bind == types::SymbolBind::LOCAL {
                        if sym.name.len() > 0 {
                            panic!("local undefined symbol {:?}", sym);
                        }
                    }
                    let gsi = match self.lookup.entry(sym.name.clone()) {
                        hash_map::Entry::Occupied(e) => {
                            *e.get()
                        },
                        hash_map::Entry::Vacant(e) => {
                            let i = self.symtab.len();
                            self.symtab.push(LinkableSymbol{sym: sym, obj: lid_base});
                            e.insert(i);
                            i
                        },
                    };
                    locations.push(gsi);
                },
                symbol::SymbolSectionIndex::Common => {
                    let gsi = match self.lookup.entry(sym.name.clone()) {
                        hash_map::Entry::Occupied(e) => {
                            let i = *e.get();
                            if let symbol::SymbolSectionIndex::Undefined = self.symtab[i].sym.shndx {
                                self.symtab[i] = LinkableSymbol{sym: sym, obj: lid_base};
                            } else {
                                //TODO check that the existing symbol is common with the same size
                            }
                            i
                        },
                        hash_map::Entry::Vacant(e) => {
                            let i = self.symtab.len();
                            self.symtab.push(LinkableSymbol{sym: sym, obj: lid_base});
                            e.insert(i);
                            i
                        },
                    };
                    locations.push(gsi);
                },
                symbol::SymbolSectionIndex::Absolute  => {
                    locations.push(self.symtab.len());
                    self.symtab.push(LinkableSymbol{sym: sym, obj: lid_base});
                },
                symbol::SymbolSectionIndex::Section(shndx)  => {
                    match sym.bind {
                        types::SymbolBind::GLOBAL => {
                            let gsi = match self.lookup.entry(sym.name.clone()) {
                                hash_map::Entry::Occupied(e) => {
                                    let i = *e.get();
                                    if let symbol::SymbolSectionIndex::Section(_) = self.symtab[i].sym.shndx {
                                        if self.symtab[i].sym.bind != types::SymbolBind::WEAK {
                                            return Err(Error::ConflictingSymbol{
                                                sym:   String::from_utf8_lossy(&self.symtab[i].sym.name)
                                                    .into_owned(),
                                                    obj1_name:   self.objects[&self.symtab[i].obj].name.clone(),
                                                    obj1_hash:   self.objects[&self.symtab[i].obj].hash.clone(),
                                                    obj2_name:   String::default(),
                                                    obj2_hash:   String::default(),
                                            });
                                        }
                                    };
                                    self.symtab[i] = LinkableSymbol{sym: sym,
                                    obj: lid_base + shndx as usize};
                                    i
                                },
                                hash_map::Entry::Vacant(e) => {
                                    let i = self.symtab.len();
                                    self.symtab.push(LinkableSymbol{sym: sym, obj: lid_base + shndx as usize});
                                    e.insert(i);
                                    i
                                },
                            };
                            locations.push(gsi);
                        },
                        types::SymbolBind::WEAK => {
                            let gsi = match self.lookup.entry(sym.name.clone()) {
                                hash_map::Entry::Occupied(e) => {
                                    let i = e.get();
                                    if let symbol::SymbolSectionIndex::Undefined = self.symtab[*i].sym.shndx {
                                        self.symtab[*i] = LinkableSymbol{sym: sym,
                                            obj: lid_base + shndx as usize};
                                    };
                                    *i
                                },
                                hash_map::Entry::Vacant(e) => {
                                    let i = self.symtab.len();
                                    self.symtab.push(LinkableSymbol{sym: sym,
                                        obj: lid_base + shndx as usize});
                                    e.insert(i);
                                    i
                                },
                            };
                            locations.push(gsi);
                        }
                        _ => {
                            locations.push(self.symtab.len());
                            self.symtab.push(LinkableSymbol{sym: sym, obj: lid_base + shndx as usize});
                        },
                    }
                },
            }
        }
        Ok(locations)
    }

    //TODO: maybe too aggressive because stuff like .comment and .note.GNU-stack are culled?
    pub fn gc(&mut self) {

        let mut again = true;
        let mut symtab_remap : Vec<Option<usize>> = vec![None;self.symtab.len()];
        while again {
            symtab_remap = vec![None;self.symtab.len()];
            let mut removelids = HashMap::new();
            for (lid, obj) in &self.objects {

                //TODO yep yep, more hacks
                if obj.section.header.shtype == types::SectionType::INIT_ARRAY ||
                   obj.section.header.shtype == types::SectionType::FINI_ARRAY {
                   continue;
                }
                removelids.insert(*lid, true);
            }

            for (lid, obj) in &self.objects {
                //TODO oh look, more hacks
                if obj.section.name.starts_with(b".debug_") {
                    continue;
                }

                for reloc in &obj.relocs {
                    symtab_remap[reloc.sym as usize] = Some(0);

                    let link = &self.symtab[reloc.sym as usize];

                    if link.obj != *lid {
                        if let symbol::SymbolSectionIndex::Section(_) = link.sym.shndx {
                            removelids.insert(link.obj, false);
                        }
                    }
                }

            }

            //TODO this feels like a hack. I think we should be able to mark root nodes before gc
            if let Some(i) = self.lookup.get(&(b"_start".to_vec())) {
                removelids.insert(self.symtab[*i].obj, false);
            }


            again = false;
            for (lid, t) in removelids {
                if t {
                    again = true;
                    self.objects.remove(&lid);
                } else {
                    for (i, sym) in self.symtab.iter().enumerate() {
                        if sym.obj == lid {
                            symtab_remap[i] = Some(0);
                        }
                    }
                }
            }
        }

        let mut symtab = Vec::new();

        for (i, link)  in self.symtab.drain(..).enumerate() {
            if link.sym.shndx == symbol::SymbolSectionIndex::Absolute {
                symtab_remap[i] = Some(0);
            }
            if let Some(_) = symtab_remap[i] {
                symtab_remap[i] = Some(symtab.len());
                symtab.push(link);
            }
        }

        for (_, obj) in &mut self.objects {
            for reloc in &mut obj.relocs {
                reloc.sym = symtab_remap[reloc.sym as usize]
                    .expect("bug in elfkit: dangling reloc after gc") as u32;
            }
        }

        self.symtab = symtab;

    }


    pub fn write_graphviz<W : Write> (&self, mut file: W) -> std::io::Result<()> {

        for (lid, object) in self.objects.iter() {

            writeln!(file, "    o{}[group=g{}, label=\"<f0>{}|<f1> {}\"];",
                     lid, object.oid, object.oid, object.name)?;


            for reloc in &object.relocs {
                let link = &self.symtab[reloc.sym as usize];

                if link.obj != object.lid {
                    let mut style  = String::new();
                    let mut linkto = format!("o{}", link.obj);
                    let label  = String::from_utf8_lossy(&link.sym.name).to_owned();

                    if link.sym.bind == types::SymbolBind::WEAK {
                        style = String::from(", style=\"dashed\"");
                    };
                    if link.sym.shndx == symbol::SymbolSectionIndex::Common {
                        writeln!(file, "    common_{}[label=\"COMMON {}\", style=\"dotted\"];",
                                 String::from_utf8_lossy(&link.sym.name),
                                 String::from_utf8_lossy(&link.sym.name))?;

                        style  = String::from(", style=\"dotted\"");
                        linkto = format!("common_{}", String::from_utf8_lossy(&link.sym.name));
                    }
                    if link.sym.shndx == symbol::SymbolSectionIndex::Undefined {
                        writeln!(file, "    missing_{}[label=\"UNDEFINED {}\", color=\"red\", style=\"dashed\", fontcolor=\"red\"];",
                                 String::from_utf8_lossy(&link.sym.name),
                                 String::from_utf8_lossy(&link.sym.name)
                                )?;
                        style += ", color=\"red\"";
                        linkto = format!("missing_{}", String::from_utf8_lossy(&link.sym.name));
                    }

                    writeln!(file, "    o{} -> {} [label=\"{}\" {}]",
                             object.lid, linkto, label, style)?;
                }
            }
        }

        Ok(())
    }
}