1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3  * elf.c - ELF access library
4  *
5  * Adapted from kpatch (https://github.com/dynup/kpatch):
6  * Copyright (C) 2013-2015 Josh Poimboeuf <jpoimboe@redhat.com>
7  * Copyright (C) 2014 Seth Jennings <sjenning@redhat.com>
8  */
9 
10 #include <sys/types.h>
11 #include <sys/stat.h>
12 #include <sys/mman.h>
13 #include <fcntl.h>
14 #include <stdio.h>
15 #include <stdlib.h>
16 #include <string.h>
17 #include <unistd.h>
18 #include <errno.h>
19 #include <linux/interval_tree_generic.h>
20 #include <objtool/builtin.h>
21 
22 #include <objtool/elf.h>
23 #include <objtool/warn.h>
24 
str_hash(const char * str)25 static inline u32 str_hash(const char *str)
26 {
27 	return jhash(str, strlen(str), 0);
28 }
29 
30 #define __elf_table(name)	(elf->name##_hash)
31 #define __elf_bits(name)	(elf->name##_bits)
32 
33 #define __elf_table_entry(name, key) \
34 	__elf_table(name)[hash_min(key, __elf_bits(name))]
35 
36 #define elf_hash_add(name, node, key)					\
37 ({									\
38 	struct elf_hash_node *__node = node;				\
39 	__node->next = __elf_table_entry(name, key);			\
40 	__elf_table_entry(name, key) = __node;				\
41 })
42 
__elf_hash_del(struct elf_hash_node * node,struct elf_hash_node ** head)43 static inline void __elf_hash_del(struct elf_hash_node *node,
44 				  struct elf_hash_node **head)
45 {
46 	struct elf_hash_node *cur, *prev;
47 
48 	if (node == *head) {
49 		*head = node->next;
50 		return;
51 	}
52 
53 	for (prev = NULL, cur = *head; cur; prev = cur, cur = cur->next) {
54 		if (cur == node) {
55 			prev->next = cur->next;
56 			break;
57 		}
58 	}
59 }
60 
61 #define elf_hash_del(name, node, key) \
62 	__elf_hash_del(node, &__elf_table_entry(name, key))
63 
64 #define elf_list_entry(ptr, type, member)				\
65 ({									\
66 	typeof(ptr) __ptr = (ptr);					\
67 	__ptr ? container_of(__ptr, type, member) : NULL;		\
68 })
69 
70 #define elf_hash_for_each_possible(name, obj, member, key)		\
71 	for (obj = elf_list_entry(__elf_table_entry(name, key), typeof(*obj), member); \
72 	     obj;							\
73 	     obj = elf_list_entry(obj->member.next, typeof(*(obj)), member))
74 
75 #define elf_alloc_hash(name, size)					\
76 ({									\
77 	__elf_bits(name) = max(10, ilog2(size));			\
78 	__elf_table(name) = mmap(NULL, sizeof(struct elf_hash_node *) << __elf_bits(name), \
79 				 PROT_READ|PROT_WRITE,			\
80 				 MAP_PRIVATE|MAP_ANON, -1, 0);		\
81 	if (__elf_table(name) == (void *)-1L) {				\
82 		ERROR_GLIBC("mmap fail " #name);			\
83 		__elf_table(name) = NULL;				\
84 	}								\
85 	__elf_table(name);						\
86 })
87 
__sym_start(struct symbol * s)88 static inline unsigned long __sym_start(struct symbol *s)
89 {
90 	return s->offset;
91 }
92 
__sym_last(struct symbol * s)93 static inline unsigned long __sym_last(struct symbol *s)
94 {
95 	return s->offset + s->len - 1;
96 }
97 
98 INTERVAL_TREE_DEFINE(struct symbol, node, unsigned long, __subtree_last,
99 		     __sym_start, __sym_last, static, __sym)
100 
101 #define __sym_for_each(_iter, _tree, _start, _end)			\
102 	for (_iter = __sym_iter_first((_tree), (_start), (_end));	\
103 	     _iter; _iter = __sym_iter_next(_iter, (_start), (_end)))
104 
105 struct symbol_hole {
106 	unsigned long key;
107 	const struct symbol *sym;
108 };
109 
110 /*
111  * Find !section symbol where @offset is after it.
112  */
symbol_hole_by_offset(const void * key,const struct rb_node * node)113 static int symbol_hole_by_offset(const void *key, const struct rb_node *node)
114 {
115 	const struct symbol *s = rb_entry(node, struct symbol, node);
116 	struct symbol_hole *sh = (void *)key;
117 
118 	if (sh->key < s->offset)
119 		return -1;
120 
121 	if (sh->key >= s->offset + s->len) {
122 		if (s->type != STT_SECTION)
123 			sh->sym = s;
124 		return 1;
125 	}
126 
127 	return 0;
128 }
129 
find_section_by_name(const struct elf * elf,const char * name)130 struct section *find_section_by_name(const struct elf *elf, const char *name)
131 {
132 	struct section *sec;
133 
134 	elf_hash_for_each_possible(section_name, sec, name_hash, str_hash(name)) {
135 		if (!strcmp(sec->name, name))
136 			return sec;
137 	}
138 
139 	return NULL;
140 }
141 
find_section_by_index(struct elf * elf,unsigned int idx)142 static struct section *find_section_by_index(struct elf *elf,
143 					     unsigned int idx)
144 {
145 	struct section *sec;
146 
147 	elf_hash_for_each_possible(section, sec, hash, idx) {
148 		if (sec->idx == idx)
149 			return sec;
150 	}
151 
152 	return NULL;
153 }
154 
find_symbol_by_index(struct elf * elf,unsigned int idx)155 static struct symbol *find_symbol_by_index(struct elf *elf, unsigned int idx)
156 {
157 	struct symbol *sym;
158 
159 	elf_hash_for_each_possible(symbol, sym, hash, idx) {
160 		if (sym->idx == idx)
161 			return sym;
162 	}
163 
164 	return NULL;
165 }
166 
find_symbol_by_offset(struct section * sec,unsigned long offset)167 struct symbol *find_symbol_by_offset(struct section *sec, unsigned long offset)
168 {
169 	struct rb_root_cached *tree = (struct rb_root_cached *)&sec->symbol_tree;
170 	struct symbol *iter;
171 
172 	__sym_for_each(iter, tree, offset, offset) {
173 		if (iter->offset == offset && iter->type != STT_SECTION)
174 			return iter;
175 	}
176 
177 	return NULL;
178 }
179 
find_func_by_offset(struct section * sec,unsigned long offset)180 struct symbol *find_func_by_offset(struct section *sec, unsigned long offset)
181 {
182 	struct rb_root_cached *tree = (struct rb_root_cached *)&sec->symbol_tree;
183 	struct symbol *iter;
184 
185 	__sym_for_each(iter, tree, offset, offset) {
186 		if (iter->offset == offset && iter->type == STT_FUNC)
187 			return iter;
188 	}
189 
190 	return NULL;
191 }
192 
find_symbol_containing(const struct section * sec,unsigned long offset)193 struct symbol *find_symbol_containing(const struct section *sec, unsigned long offset)
194 {
195 	struct rb_root_cached *tree = (struct rb_root_cached *)&sec->symbol_tree;
196 	struct symbol *iter;
197 
198 	__sym_for_each(iter, tree, offset, offset) {
199 		if (iter->type != STT_SECTION)
200 			return iter;
201 	}
202 
203 	return NULL;
204 }
205 
206 /*
207  * Returns size of hole starting at @offset.
208  */
find_symbol_hole_containing(const struct section * sec,unsigned long offset)209 int find_symbol_hole_containing(const struct section *sec, unsigned long offset)
210 {
211 	struct symbol_hole hole = {
212 		.key = offset,
213 		.sym = NULL,
214 	};
215 	struct rb_node *n;
216 	struct symbol *s;
217 
218 	/*
219 	 * Find the rightmost symbol for which @offset is after it.
220 	 */
221 	n = rb_find(&hole, &sec->symbol_tree.rb_root, symbol_hole_by_offset);
222 
223 	/* found a symbol that contains @offset */
224 	if (n)
225 		return 0; /* not a hole */
226 
227 	/*
228 	 * @offset >= sym->offset + sym->len, find symbol after it.
229 	 * When hole.sym is empty, use the first node to compute the hole.
230 	 * If there is no symbol in the section, the first node will be NULL,
231 	 * in which case, -1 is returned to skip the whole section.
232 	 */
233 	if (hole.sym)
234 		n = rb_next(&hole.sym->node);
235 	else
236 		n = rb_first_cached(&sec->symbol_tree);
237 
238 	if (!n)
239 		return -1; /* until end of address space */
240 
241 	/* hole until start of next symbol */
242 	s = rb_entry(n, struct symbol, node);
243 	return s->offset - offset;
244 }
245 
find_func_containing(struct section * sec,unsigned long offset)246 struct symbol *find_func_containing(struct section *sec, unsigned long offset)
247 {
248 	struct rb_root_cached *tree = (struct rb_root_cached *)&sec->symbol_tree;
249 	struct symbol *iter;
250 
251 	__sym_for_each(iter, tree, offset, offset) {
252 		if (iter->type == STT_FUNC)
253 			return iter;
254 	}
255 
256 	return NULL;
257 }
258 
find_symbol_by_name(const struct elf * elf,const char * name)259 struct symbol *find_symbol_by_name(const struct elf *elf, const char *name)
260 {
261 	struct symbol *sym;
262 
263 	elf_hash_for_each_possible(symbol_name, sym, name_hash, str_hash(name)) {
264 		if (!strcmp(sym->name, name))
265 			return sym;
266 	}
267 
268 	return NULL;
269 }
270 
find_reloc_by_dest_range(const struct elf * elf,struct section * sec,unsigned long offset,unsigned int len)271 struct reloc *find_reloc_by_dest_range(const struct elf *elf, struct section *sec,
272 				     unsigned long offset, unsigned int len)
273 {
274 	struct reloc *reloc, *r = NULL;
275 	struct section *rsec;
276 	unsigned long o;
277 
278 	rsec = sec->rsec;
279 	if (!rsec)
280 		return NULL;
281 
282 	for_offset_range(o, offset, offset + len) {
283 		elf_hash_for_each_possible(reloc, reloc, hash,
284 					   sec_offset_hash(rsec, o)) {
285 			if (reloc->sec != rsec)
286 				continue;
287 
288 			if (reloc_offset(reloc) >= offset &&
289 			    reloc_offset(reloc) < offset + len) {
290 				if (!r || reloc_offset(reloc) < reloc_offset(r))
291 					r = reloc;
292 			}
293 		}
294 		if (r)
295 			return r;
296 	}
297 
298 	return NULL;
299 }
300 
find_reloc_by_dest(const struct elf * elf,struct section * sec,unsigned long offset)301 struct reloc *find_reloc_by_dest(const struct elf *elf, struct section *sec, unsigned long offset)
302 {
303 	return find_reloc_by_dest_range(elf, sec, offset, 1);
304 }
305 
is_dwarf_section(struct section * sec)306 static bool is_dwarf_section(struct section *sec)
307 {
308 	return !strncmp(sec->name, ".debug_", 7);
309 }
310 
read_sections(struct elf * elf)311 static int read_sections(struct elf *elf)
312 {
313 	Elf_Scn *s = NULL;
314 	struct section *sec;
315 	size_t shstrndx, sections_nr;
316 	int i;
317 
318 	if (elf_getshdrnum(elf->elf, &sections_nr)) {
319 		ERROR_ELF("elf_getshdrnum");
320 		return -1;
321 	}
322 
323 	if (elf_getshdrstrndx(elf->elf, &shstrndx)) {
324 		ERROR_ELF("elf_getshdrstrndx");
325 		return -1;
326 	}
327 
328 	if (!elf_alloc_hash(section, sections_nr) ||
329 	    !elf_alloc_hash(section_name, sections_nr))
330 		return -1;
331 
332 	elf->section_data = calloc(sections_nr, sizeof(*sec));
333 	if (!elf->section_data) {
334 		ERROR_GLIBC("calloc");
335 		return -1;
336 	}
337 	for (i = 0; i < sections_nr; i++) {
338 		sec = &elf->section_data[i];
339 
340 		INIT_LIST_HEAD(&sec->symbol_list);
341 
342 		s = elf_getscn(elf->elf, i);
343 		if (!s) {
344 			ERROR_ELF("elf_getscn");
345 			return -1;
346 		}
347 
348 		sec->idx = elf_ndxscn(s);
349 
350 		if (!gelf_getshdr(s, &sec->sh)) {
351 			ERROR_ELF("gelf_getshdr");
352 			return -1;
353 		}
354 
355 		sec->name = elf_strptr(elf->elf, shstrndx, sec->sh.sh_name);
356 		if (!sec->name) {
357 			ERROR_ELF("elf_strptr");
358 			return -1;
359 		}
360 
361 		if (sec->sh.sh_size != 0 && !is_dwarf_section(sec)) {
362 			sec->data = elf_getdata(s, NULL);
363 			if (!sec->data) {
364 				ERROR_ELF("elf_getdata");
365 				return -1;
366 			}
367 			if (sec->data->d_off != 0 ||
368 			    sec->data->d_size != sec->sh.sh_size) {
369 				ERROR("unexpected data attributes for %s", sec->name);
370 				return -1;
371 			}
372 		}
373 
374 		list_add_tail(&sec->list, &elf->sections);
375 		elf_hash_add(section, &sec->hash, sec->idx);
376 		elf_hash_add(section_name, &sec->name_hash, str_hash(sec->name));
377 
378 		if (is_reloc_sec(sec))
379 			elf->num_relocs += sec_num_entries(sec);
380 	}
381 
382 	if (opts.stats) {
383 		printf("nr_sections: %lu\n", (unsigned long)sections_nr);
384 		printf("section_bits: %d\n", elf->section_bits);
385 	}
386 
387 	/* sanity check, one more call to elf_nextscn() should return NULL */
388 	if (elf_nextscn(elf->elf, s)) {
389 		ERROR("section entry mismatch");
390 		return -1;
391 	}
392 
393 	return 0;
394 }
395 
elf_add_symbol(struct elf * elf,struct symbol * sym)396 static void elf_add_symbol(struct elf *elf, struct symbol *sym)
397 {
398 	struct list_head *entry;
399 	struct rb_node *pnode;
400 	struct symbol *iter;
401 
402 	INIT_LIST_HEAD(&sym->pv_target);
403 	sym->alias = sym;
404 
405 	sym->type = GELF_ST_TYPE(sym->sym.st_info);
406 	sym->bind = GELF_ST_BIND(sym->sym.st_info);
407 
408 	if (sym->type == STT_FILE)
409 		elf->num_files++;
410 
411 	sym->offset = sym->sym.st_value;
412 	sym->len = sym->sym.st_size;
413 
414 	__sym_for_each(iter, &sym->sec->symbol_tree, sym->offset, sym->offset) {
415 		if (iter->offset == sym->offset && iter->type == sym->type)
416 			iter->alias = sym;
417 	}
418 
419 	__sym_insert(sym, &sym->sec->symbol_tree);
420 	pnode = rb_prev(&sym->node);
421 	if (pnode)
422 		entry = &rb_entry(pnode, struct symbol, node)->list;
423 	else
424 		entry = &sym->sec->symbol_list;
425 	list_add(&sym->list, entry);
426 	elf_hash_add(symbol, &sym->hash, sym->idx);
427 	elf_hash_add(symbol_name, &sym->name_hash, str_hash(sym->name));
428 
429 	/*
430 	 * Don't store empty STT_NOTYPE symbols in the rbtree.  They
431 	 * can exist within a function, confusing the sorting.
432 	 */
433 	if (!sym->len)
434 		__sym_remove(sym, &sym->sec->symbol_tree);
435 }
436 
read_symbols(struct elf * elf)437 static int read_symbols(struct elf *elf)
438 {
439 	struct section *symtab, *symtab_shndx, *sec;
440 	struct symbol *sym, *pfunc;
441 	int symbols_nr, i;
442 	char *coldstr;
443 	Elf_Data *shndx_data = NULL;
444 	Elf32_Word shndx;
445 
446 	symtab = find_section_by_name(elf, ".symtab");
447 	if (symtab) {
448 		symtab_shndx = find_section_by_name(elf, ".symtab_shndx");
449 		if (symtab_shndx)
450 			shndx_data = symtab_shndx->data;
451 
452 		symbols_nr = sec_num_entries(symtab);
453 	} else {
454 		/*
455 		 * A missing symbol table is actually possible if it's an empty
456 		 * .o file. This can happen for thunk_64.o. Make sure to at
457 		 * least allocate the symbol hash tables so we can do symbol
458 		 * lookups without crashing.
459 		 */
460 		symbols_nr = 0;
461 	}
462 
463 	if (!elf_alloc_hash(symbol, symbols_nr) ||
464 	    !elf_alloc_hash(symbol_name, symbols_nr))
465 		return -1;
466 
467 	elf->symbol_data = calloc(symbols_nr, sizeof(*sym));
468 	if (!elf->symbol_data) {
469 		ERROR_GLIBC("calloc");
470 		return -1;
471 	}
472 	for (i = 0; i < symbols_nr; i++) {
473 		sym = &elf->symbol_data[i];
474 
475 		sym->idx = i;
476 
477 		if (!gelf_getsymshndx(symtab->data, shndx_data, i, &sym->sym,
478 				      &shndx)) {
479 			ERROR_ELF("gelf_getsymshndx");
480 			goto err;
481 		}
482 
483 		sym->name = elf_strptr(elf->elf, symtab->sh.sh_link,
484 				       sym->sym.st_name);
485 		if (!sym->name) {
486 			ERROR_ELF("elf_strptr");
487 			goto err;
488 		}
489 
490 		if ((sym->sym.st_shndx > SHN_UNDEF &&
491 		     sym->sym.st_shndx < SHN_LORESERVE) ||
492 		    (shndx_data && sym->sym.st_shndx == SHN_XINDEX)) {
493 			if (sym->sym.st_shndx != SHN_XINDEX)
494 				shndx = sym->sym.st_shndx;
495 
496 			sym->sec = find_section_by_index(elf, shndx);
497 			if (!sym->sec) {
498 				ERROR("couldn't find section for symbol %s", sym->name);
499 				goto err;
500 			}
501 			if (GELF_ST_TYPE(sym->sym.st_info) == STT_SECTION) {
502 				sym->name = sym->sec->name;
503 				sym->sec->sym = sym;
504 			}
505 		} else
506 			sym->sec = find_section_by_index(elf, 0);
507 
508 		elf_add_symbol(elf, sym);
509 	}
510 
511 	if (opts.stats) {
512 		printf("nr_symbols: %lu\n", (unsigned long)symbols_nr);
513 		printf("symbol_bits: %d\n", elf->symbol_bits);
514 	}
515 
516 	/* Create parent/child links for any cold subfunctions */
517 	list_for_each_entry(sec, &elf->sections, list) {
518 		sec_for_each_sym(sec, sym) {
519 			char *pname;
520 			size_t pnamelen;
521 			if (sym->type != STT_FUNC)
522 				continue;
523 
524 			if (sym->pfunc == NULL)
525 				sym->pfunc = sym;
526 
527 			if (sym->cfunc == NULL)
528 				sym->cfunc = sym;
529 
530 			coldstr = strstr(sym->name, ".cold");
531 			if (!coldstr)
532 				continue;
533 
534 			pnamelen = coldstr - sym->name;
535 			pname = strndup(sym->name, pnamelen);
536 			if (!pname) {
537 				ERROR("%s(): failed to allocate memory", sym->name);
538 				return -1;
539 			}
540 
541 			pfunc = find_symbol_by_name(elf, pname);
542 			free(pname);
543 
544 			if (!pfunc) {
545 				ERROR("%s(): can't find parent function", sym->name);
546 				return -1;
547 			}
548 
549 			sym->pfunc = pfunc;
550 			pfunc->cfunc = sym;
551 
552 			/*
553 			 * Unfortunately, -fnoreorder-functions puts the child
554 			 * inside the parent.  Remove the overlap so we can
555 			 * have sane assumptions.
556 			 *
557 			 * Note that pfunc->len now no longer matches
558 			 * pfunc->sym.st_size.
559 			 */
560 			if (sym->sec == pfunc->sec &&
561 			    sym->offset >= pfunc->offset &&
562 			    sym->offset + sym->len == pfunc->offset + pfunc->len) {
563 				pfunc->len -= sym->len;
564 			}
565 		}
566 	}
567 
568 	return 0;
569 
570 err:
571 	free(sym);
572 	return -1;
573 }
574 
575 /*
576  * @sym's idx has changed.  Update the relocs which reference it.
577  */
elf_update_sym_relocs(struct elf * elf,struct symbol * sym)578 static int elf_update_sym_relocs(struct elf *elf, struct symbol *sym)
579 {
580 	struct reloc *reloc;
581 
582 	for (reloc = sym->relocs; reloc; reloc = sym_next_reloc(reloc))
583 		set_reloc_sym(elf, reloc, reloc->sym->idx);
584 
585 	return 0;
586 }
587 
588 /*
589  * The libelf API is terrible; gelf_update_sym*() takes a data block relative
590  * index value, *NOT* the symbol index. As such, iterate the data blocks and
591  * adjust index until it fits.
592  *
593  * If no data block is found, allow adding a new data block provided the index
594  * is only one past the end.
595  */
elf_update_symbol(struct elf * elf,struct section * symtab,struct section * symtab_shndx,struct symbol * sym)596 static int elf_update_symbol(struct elf *elf, struct section *symtab,
597 			     struct section *symtab_shndx, struct symbol *sym)
598 {
599 	Elf32_Word shndx = sym->sec ? sym->sec->idx : SHN_UNDEF;
600 	Elf_Data *symtab_data = NULL, *shndx_data = NULL;
601 	Elf64_Xword entsize = symtab->sh.sh_entsize;
602 	int max_idx, idx = sym->idx;
603 	Elf_Scn *s, *t = NULL;
604 	bool is_special_shndx = sym->sym.st_shndx >= SHN_LORESERVE &&
605 				sym->sym.st_shndx != SHN_XINDEX;
606 
607 	if (is_special_shndx)
608 		shndx = sym->sym.st_shndx;
609 
610 	s = elf_getscn(elf->elf, symtab->idx);
611 	if (!s) {
612 		ERROR_ELF("elf_getscn");
613 		return -1;
614 	}
615 
616 	if (symtab_shndx) {
617 		t = elf_getscn(elf->elf, symtab_shndx->idx);
618 		if (!t) {
619 			ERROR_ELF("elf_getscn");
620 			return -1;
621 		}
622 	}
623 
624 	for (;;) {
625 		/* get next data descriptor for the relevant sections */
626 		symtab_data = elf_getdata(s, symtab_data);
627 		if (t)
628 			shndx_data = elf_getdata(t, shndx_data);
629 
630 		/* end-of-list */
631 		if (!symtab_data) {
632 			/*
633 			 * Over-allocate to avoid O(n^2) symbol creation
634 			 * behaviour.  The down side is that libelf doesn't
635 			 * like this; see elf_truncate_section() for the fixup.
636 			 */
637 			int num = max(1U, sym->idx/3);
638 			void *buf;
639 
640 			if (idx) {
641 				/* we don't do holes in symbol tables */
642 				ERROR("index out of range");
643 				return -1;
644 			}
645 
646 			/* if @idx == 0, it's the next contiguous entry, create it */
647 			symtab_data = elf_newdata(s);
648 			if (t)
649 				shndx_data = elf_newdata(t);
650 
651 			buf = calloc(num, entsize);
652 			if (!buf) {
653 				ERROR_GLIBC("calloc");
654 				return -1;
655 			}
656 
657 			symtab_data->d_buf = buf;
658 			symtab_data->d_size = num * entsize;
659 			symtab_data->d_align = 1;
660 			symtab_data->d_type = ELF_T_SYM;
661 
662 			mark_sec_changed(elf, symtab, true);
663 			symtab->truncate = true;
664 
665 			if (t) {
666 				buf = calloc(num, sizeof(Elf32_Word));
667 				if (!buf) {
668 					ERROR_GLIBC("calloc");
669 					return -1;
670 				}
671 
672 				shndx_data->d_buf = buf;
673 				shndx_data->d_size = num * sizeof(Elf32_Word);
674 				shndx_data->d_align = sizeof(Elf32_Word);
675 				shndx_data->d_type = ELF_T_WORD;
676 
677 				mark_sec_changed(elf, symtab_shndx, true);
678 				symtab_shndx->truncate = true;
679 			}
680 
681 			break;
682 		}
683 
684 		/* empty blocks should not happen */
685 		if (!symtab_data->d_size) {
686 			ERROR("zero size data");
687 			return -1;
688 		}
689 
690 		/* is this the right block? */
691 		max_idx = symtab_data->d_size / entsize;
692 		if (idx < max_idx)
693 			break;
694 
695 		/* adjust index and try again */
696 		idx -= max_idx;
697 	}
698 
699 	/* something went side-ways */
700 	if (idx < 0) {
701 		ERROR("negative index");
702 		return -1;
703 	}
704 
705 	/* setup extended section index magic and write the symbol */
706 	if ((shndx >= SHN_UNDEF && shndx < SHN_LORESERVE) || is_special_shndx) {
707 		sym->sym.st_shndx = shndx;
708 		if (!shndx_data)
709 			shndx = 0;
710 	} else {
711 		sym->sym.st_shndx = SHN_XINDEX;
712 		if (!shndx_data) {
713 			ERROR("no .symtab_shndx");
714 			return -1;
715 		}
716 	}
717 
718 	if (!gelf_update_symshndx(symtab_data, shndx_data, idx, &sym->sym, shndx)) {
719 		ERROR_ELF("gelf_update_symshndx");
720 		return -1;
721 	}
722 
723 	return 0;
724 }
725 
726 static struct symbol *
__elf_create_symbol(struct elf * elf,struct symbol * sym)727 __elf_create_symbol(struct elf *elf, struct symbol *sym)
728 {
729 	struct section *symtab, *symtab_shndx;
730 	Elf32_Word first_non_local, new_idx;
731 	struct symbol *old;
732 
733 	symtab = find_section_by_name(elf, ".symtab");
734 	if (symtab) {
735 		symtab_shndx = find_section_by_name(elf, ".symtab_shndx");
736 	} else {
737 		ERROR("no .symtab");
738 		return NULL;
739 	}
740 
741 	new_idx = sec_num_entries(symtab);
742 
743 	if (GELF_ST_BIND(sym->sym.st_info) != STB_LOCAL)
744 		goto non_local;
745 
746 	/*
747 	 * Move the first global symbol, as per sh_info, into a new, higher
748 	 * symbol index. This fees up a spot for a new local symbol.
749 	 */
750 	first_non_local = symtab->sh.sh_info;
751 	old = find_symbol_by_index(elf, first_non_local);
752 	if (old) {
753 
754 		elf_hash_del(symbol, &old->hash, old->idx);
755 		elf_hash_add(symbol, &old->hash, new_idx);
756 		old->idx = new_idx;
757 
758 		if (elf_update_symbol(elf, symtab, symtab_shndx, old)) {
759 			ERROR("elf_update_symbol move");
760 			return NULL;
761 		}
762 
763 		if (elf_update_sym_relocs(elf, old))
764 			return NULL;
765 
766 		new_idx = first_non_local;
767 	}
768 
769 	/*
770 	 * Either way, we will add a LOCAL symbol.
771 	 */
772 	symtab->sh.sh_info += 1;
773 
774 non_local:
775 	sym->idx = new_idx;
776 	if (elf_update_symbol(elf, symtab, symtab_shndx, sym)) {
777 		ERROR("elf_update_symbol");
778 		return NULL;
779 	}
780 
781 	symtab->sh.sh_size += symtab->sh.sh_entsize;
782 	mark_sec_changed(elf, symtab, true);
783 
784 	if (symtab_shndx) {
785 		symtab_shndx->sh.sh_size += sizeof(Elf32_Word);
786 		mark_sec_changed(elf, symtab_shndx, true);
787 	}
788 
789 	return sym;
790 }
791 
792 static struct symbol *
elf_create_section_symbol(struct elf * elf,struct section * sec)793 elf_create_section_symbol(struct elf *elf, struct section *sec)
794 {
795 	struct symbol *sym = calloc(1, sizeof(*sym));
796 
797 	if (!sym) {
798 		ERROR_GLIBC("malloc");
799 		return NULL;
800 	}
801 
802 	sym->name = sec->name;
803 	sym->sec = sec;
804 
805 	// st_name 0
806 	sym->sym.st_info = GELF_ST_INFO(STB_LOCAL, STT_SECTION);
807 	// st_other 0
808 	// st_value 0
809 	// st_size 0
810 
811 	sym = __elf_create_symbol(elf, sym);
812 	if (sym)
813 		elf_add_symbol(elf, sym);
814 
815 	return sym;
816 }
817 
818 static int elf_add_string(struct elf *elf, struct section *strtab, char *str);
819 
820 struct symbol *
elf_create_prefix_symbol(struct elf * elf,struct symbol * orig,long size)821 elf_create_prefix_symbol(struct elf *elf, struct symbol *orig, long size)
822 {
823 	struct symbol *sym = calloc(1, sizeof(*sym));
824 	size_t namelen = strlen(orig->name) + sizeof("__pfx_");
825 	char *name = malloc(namelen);
826 
827 	if (!sym || !name) {
828 		ERROR_GLIBC("malloc");
829 		return NULL;
830 	}
831 
832 	snprintf(name, namelen, "__pfx_%s", orig->name);
833 
834 	sym->name = name;
835 	sym->sec = orig->sec;
836 
837 	sym->sym.st_name = elf_add_string(elf, NULL, name);
838 	sym->sym.st_info = orig->sym.st_info;
839 	sym->sym.st_value = orig->sym.st_value - size;
840 	sym->sym.st_size = size;
841 
842 	sym = __elf_create_symbol(elf, sym);
843 	if (sym)
844 		elf_add_symbol(elf, sym);
845 
846 	return sym;
847 }
848 
elf_init_reloc(struct elf * elf,struct section * rsec,unsigned int reloc_idx,unsigned long offset,struct symbol * sym,s64 addend,unsigned int type)849 static struct reloc *elf_init_reloc(struct elf *elf, struct section *rsec,
850 				    unsigned int reloc_idx,
851 				    unsigned long offset, struct symbol *sym,
852 				    s64 addend, unsigned int type)
853 {
854 	struct reloc *reloc, empty = { 0 };
855 
856 	if (reloc_idx >= sec_num_entries(rsec)) {
857 		ERROR("%s: bad reloc_idx %u for %s with %d relocs",
858 		      __func__, reloc_idx, rsec->name, sec_num_entries(rsec));
859 		return NULL;
860 	}
861 
862 	reloc = &rsec->relocs[reloc_idx];
863 
864 	if (memcmp(reloc, &empty, sizeof(empty))) {
865 		ERROR("%s: %s: reloc %d already initialized!",
866 		      __func__, rsec->name, reloc_idx);
867 		return NULL;
868 	}
869 
870 	reloc->sec = rsec;
871 	reloc->sym = sym;
872 
873 	set_reloc_offset(elf, reloc, offset);
874 	set_reloc_sym(elf, reloc, sym->idx);
875 	set_reloc_type(elf, reloc, type);
876 	set_reloc_addend(elf, reloc, addend);
877 
878 	elf_hash_add(reloc, &reloc->hash, reloc_hash(reloc));
879 	set_sym_next_reloc(reloc, sym->relocs);
880 	sym->relocs = reloc;
881 
882 	return reloc;
883 }
884 
elf_init_reloc_text_sym(struct elf * elf,struct section * sec,unsigned long offset,unsigned int reloc_idx,struct section * insn_sec,unsigned long insn_off)885 struct reloc *elf_init_reloc_text_sym(struct elf *elf, struct section *sec,
886 				      unsigned long offset,
887 				      unsigned int reloc_idx,
888 				      struct section *insn_sec,
889 				      unsigned long insn_off)
890 {
891 	struct symbol *sym = insn_sec->sym;
892 	int addend = insn_off;
893 
894 	if (!(insn_sec->sh.sh_flags & SHF_EXECINSTR)) {
895 		ERROR("bad call to %s() for data symbol %s", __func__, sym->name);
896 		return NULL;
897 	}
898 
899 	if (!sym) {
900 		/*
901 		 * Due to how weak functions work, we must use section based
902 		 * relocations. Symbol based relocations would result in the
903 		 * weak and non-weak function annotations being overlaid on the
904 		 * non-weak function after linking.
905 		 */
906 		sym = elf_create_section_symbol(elf, insn_sec);
907 		if (!sym)
908 			return NULL;
909 
910 		insn_sec->sym = sym;
911 	}
912 
913 	return elf_init_reloc(elf, sec->rsec, reloc_idx, offset, sym, addend,
914 			      elf_text_rela_type(elf));
915 }
916 
elf_init_reloc_data_sym(struct elf * elf,struct section * sec,unsigned long offset,unsigned int reloc_idx,struct symbol * sym,s64 addend)917 struct reloc *elf_init_reloc_data_sym(struct elf *elf, struct section *sec,
918 				      unsigned long offset,
919 				      unsigned int reloc_idx,
920 				      struct symbol *sym,
921 				      s64 addend)
922 {
923 	if (sym->sec && (sec->sh.sh_flags & SHF_EXECINSTR)) {
924 		ERROR("bad call to %s() for text symbol %s", __func__, sym->name);
925 		return NULL;
926 	}
927 
928 	return elf_init_reloc(elf, sec->rsec, reloc_idx, offset, sym, addend,
929 			      elf_data_rela_type(elf));
930 }
931 
read_relocs(struct elf * elf)932 static int read_relocs(struct elf *elf)
933 {
934 	unsigned long nr_reloc, max_reloc = 0;
935 	struct section *rsec;
936 	struct reloc *reloc;
937 	unsigned int symndx;
938 	struct symbol *sym;
939 	int i;
940 
941 	if (!elf_alloc_hash(reloc, elf->num_relocs))
942 		return -1;
943 
944 	list_for_each_entry(rsec, &elf->sections, list) {
945 		if (!is_reloc_sec(rsec))
946 			continue;
947 
948 		rsec->base = find_section_by_index(elf, rsec->sh.sh_info);
949 		if (!rsec->base) {
950 			ERROR("can't find base section for reloc section %s", rsec->name);
951 			return -1;
952 		}
953 
954 		rsec->base->rsec = rsec;
955 
956 		nr_reloc = 0;
957 		rsec->relocs = calloc(sec_num_entries(rsec), sizeof(*reloc));
958 		if (!rsec->relocs) {
959 			ERROR_GLIBC("calloc");
960 			return -1;
961 		}
962 		for (i = 0; i < sec_num_entries(rsec); i++) {
963 			reloc = &rsec->relocs[i];
964 
965 			reloc->sec = rsec;
966 			symndx = reloc_sym(reloc);
967 			reloc->sym = sym = find_symbol_by_index(elf, symndx);
968 			if (!reloc->sym) {
969 				ERROR("can't find reloc entry symbol %d for %s", symndx, rsec->name);
970 				return -1;
971 			}
972 
973 			elf_hash_add(reloc, &reloc->hash, reloc_hash(reloc));
974 			set_sym_next_reloc(reloc, sym->relocs);
975 			sym->relocs = reloc;
976 
977 			nr_reloc++;
978 		}
979 		max_reloc = max(max_reloc, nr_reloc);
980 	}
981 
982 	if (opts.stats) {
983 		printf("max_reloc: %lu\n", max_reloc);
984 		printf("num_relocs: %lu\n", elf->num_relocs);
985 		printf("reloc_bits: %d\n", elf->reloc_bits);
986 	}
987 
988 	return 0;
989 }
990 
elf_open_read(const char * name,int flags)991 struct elf *elf_open_read(const char *name, int flags)
992 {
993 	struct elf *elf;
994 	Elf_Cmd cmd;
995 
996 	elf_version(EV_CURRENT);
997 
998 	elf = malloc(sizeof(*elf));
999 	if (!elf) {
1000 		ERROR_GLIBC("malloc");
1001 		return NULL;
1002 	}
1003 	memset(elf, 0, sizeof(*elf));
1004 
1005 	INIT_LIST_HEAD(&elf->sections);
1006 
1007 	elf->fd = open(name, flags);
1008 	if (elf->fd == -1) {
1009 		fprintf(stderr, "objtool: Can't open '%s': %s\n",
1010 			name, strerror(errno));
1011 		goto err;
1012 	}
1013 
1014 	if ((flags & O_ACCMODE) == O_RDONLY)
1015 		cmd = ELF_C_READ_MMAP;
1016 	else if ((flags & O_ACCMODE) == O_RDWR)
1017 		cmd = ELF_C_RDWR;
1018 	else /* O_WRONLY */
1019 		cmd = ELF_C_WRITE;
1020 
1021 	elf->elf = elf_begin(elf->fd, cmd, NULL);
1022 	if (!elf->elf) {
1023 		ERROR_ELF("elf_begin");
1024 		goto err;
1025 	}
1026 
1027 	if (!gelf_getehdr(elf->elf, &elf->ehdr)) {
1028 		ERROR_ELF("gelf_getehdr");
1029 		goto err;
1030 	}
1031 
1032 	if (read_sections(elf))
1033 		goto err;
1034 
1035 	if (read_symbols(elf))
1036 		goto err;
1037 
1038 	if (read_relocs(elf))
1039 		goto err;
1040 
1041 	return elf;
1042 
1043 err:
1044 	elf_close(elf);
1045 	return NULL;
1046 }
1047 
elf_add_string(struct elf * elf,struct section * strtab,char * str)1048 static int elf_add_string(struct elf *elf, struct section *strtab, char *str)
1049 {
1050 	Elf_Data *data;
1051 	Elf_Scn *s;
1052 	int len;
1053 
1054 	if (!strtab)
1055 		strtab = find_section_by_name(elf, ".strtab");
1056 	if (!strtab) {
1057 		ERROR("can't find .strtab section");
1058 		return -1;
1059 	}
1060 
1061 	s = elf_getscn(elf->elf, strtab->idx);
1062 	if (!s) {
1063 		ERROR_ELF("elf_getscn");
1064 		return -1;
1065 	}
1066 
1067 	data = elf_newdata(s);
1068 	if (!data) {
1069 		ERROR_ELF("elf_newdata");
1070 		return -1;
1071 	}
1072 
1073 	data->d_buf = str;
1074 	data->d_size = strlen(str) + 1;
1075 	data->d_align = 1;
1076 
1077 	len = strtab->sh.sh_size;
1078 	strtab->sh.sh_size += data->d_size;
1079 
1080 	mark_sec_changed(elf, strtab, true);
1081 
1082 	return len;
1083 }
1084 
elf_create_section(struct elf * elf,const char * name,size_t entsize,unsigned int nr)1085 struct section *elf_create_section(struct elf *elf, const char *name,
1086 				   size_t entsize, unsigned int nr)
1087 {
1088 	struct section *sec, *shstrtab;
1089 	size_t size = entsize * nr;
1090 	Elf_Scn *s;
1091 
1092 	sec = malloc(sizeof(*sec));
1093 	if (!sec) {
1094 		ERROR_GLIBC("malloc");
1095 		return NULL;
1096 	}
1097 	memset(sec, 0, sizeof(*sec));
1098 
1099 	INIT_LIST_HEAD(&sec->symbol_list);
1100 
1101 	s = elf_newscn(elf->elf);
1102 	if (!s) {
1103 		ERROR_ELF("elf_newscn");
1104 		return NULL;
1105 	}
1106 
1107 	sec->name = strdup(name);
1108 	if (!sec->name) {
1109 		ERROR_GLIBC("strdup");
1110 		return NULL;
1111 	}
1112 
1113 	sec->idx = elf_ndxscn(s);
1114 
1115 	sec->data = elf_newdata(s);
1116 	if (!sec->data) {
1117 		ERROR_ELF("elf_newdata");
1118 		return NULL;
1119 	}
1120 
1121 	sec->data->d_size = size;
1122 	sec->data->d_align = 1;
1123 
1124 	if (size) {
1125 		sec->data->d_buf = malloc(size);
1126 		if (!sec->data->d_buf) {
1127 			ERROR_GLIBC("malloc");
1128 			return NULL;
1129 		}
1130 		memset(sec->data->d_buf, 0, size);
1131 	}
1132 
1133 	if (!gelf_getshdr(s, &sec->sh)) {
1134 		ERROR_ELF("gelf_getshdr");
1135 		return NULL;
1136 	}
1137 
1138 	sec->sh.sh_size = size;
1139 	sec->sh.sh_entsize = entsize;
1140 	sec->sh.sh_type = SHT_PROGBITS;
1141 	sec->sh.sh_addralign = 1;
1142 	sec->sh.sh_flags = SHF_ALLOC;
1143 
1144 	/* Add section name to .shstrtab (or .strtab for Clang) */
1145 	shstrtab = find_section_by_name(elf, ".shstrtab");
1146 	if (!shstrtab)
1147 		shstrtab = find_section_by_name(elf, ".strtab");
1148 	if (!shstrtab) {
1149 		ERROR("can't find .shstrtab or .strtab section");
1150 		return NULL;
1151 	}
1152 	sec->sh.sh_name = elf_add_string(elf, shstrtab, sec->name);
1153 	if (sec->sh.sh_name == -1)
1154 		return NULL;
1155 
1156 	list_add_tail(&sec->list, &elf->sections);
1157 	elf_hash_add(section, &sec->hash, sec->idx);
1158 	elf_hash_add(section_name, &sec->name_hash, str_hash(sec->name));
1159 
1160 	mark_sec_changed(elf, sec, true);
1161 
1162 	return sec;
1163 }
1164 
elf_create_rela_section(struct elf * elf,struct section * sec,unsigned int reloc_nr)1165 static struct section *elf_create_rela_section(struct elf *elf,
1166 					       struct section *sec,
1167 					       unsigned int reloc_nr)
1168 {
1169 	struct section *rsec;
1170 	char *rsec_name;
1171 
1172 	rsec_name = malloc(strlen(sec->name) + strlen(".rela") + 1);
1173 	if (!rsec_name) {
1174 		ERROR_GLIBC("malloc");
1175 		return NULL;
1176 	}
1177 	strcpy(rsec_name, ".rela");
1178 	strcat(rsec_name, sec->name);
1179 
1180 	rsec = elf_create_section(elf, rsec_name, elf_rela_size(elf), reloc_nr);
1181 	free(rsec_name);
1182 	if (!rsec)
1183 		return NULL;
1184 
1185 	rsec->data->d_type = ELF_T_RELA;
1186 	rsec->sh.sh_type = SHT_RELA;
1187 	rsec->sh.sh_addralign = elf_addr_size(elf);
1188 	rsec->sh.sh_link = find_section_by_name(elf, ".symtab")->idx;
1189 	rsec->sh.sh_info = sec->idx;
1190 	rsec->sh.sh_flags = SHF_INFO_LINK;
1191 
1192 	rsec->relocs = calloc(sec_num_entries(rsec), sizeof(struct reloc));
1193 	if (!rsec->relocs) {
1194 		ERROR_GLIBC("calloc");
1195 		return NULL;
1196 	}
1197 
1198 	sec->rsec = rsec;
1199 	rsec->base = sec;
1200 
1201 	return rsec;
1202 }
1203 
elf_create_section_pair(struct elf * elf,const char * name,size_t entsize,unsigned int nr,unsigned int reloc_nr)1204 struct section *elf_create_section_pair(struct elf *elf, const char *name,
1205 					size_t entsize, unsigned int nr,
1206 					unsigned int reloc_nr)
1207 {
1208 	struct section *sec;
1209 
1210 	sec = elf_create_section(elf, name, entsize, nr);
1211 	if (!sec)
1212 		return NULL;
1213 
1214 	if (!elf_create_rela_section(elf, sec, reloc_nr))
1215 		return NULL;
1216 
1217 	return sec;
1218 }
1219 
elf_write_insn(struct elf * elf,struct section * sec,unsigned long offset,unsigned int len,const char * insn)1220 int elf_write_insn(struct elf *elf, struct section *sec,
1221 		   unsigned long offset, unsigned int len,
1222 		   const char *insn)
1223 {
1224 	Elf_Data *data = sec->data;
1225 
1226 	if (data->d_type != ELF_T_BYTE || data->d_off) {
1227 		ERROR("write to unexpected data for section: %s", sec->name);
1228 		return -1;
1229 	}
1230 
1231 	memcpy(data->d_buf + offset, insn, len);
1232 
1233 	mark_sec_changed(elf, sec, true);
1234 
1235 	return 0;
1236 }
1237 
1238 /*
1239  * When Elf_Scn::sh_size is smaller than the combined Elf_Data::d_size
1240  * do you:
1241  *
1242  *   A) adhere to the section header and truncate the data, or
1243  *   B) ignore the section header and write out all the data you've got?
1244  *
1245  * Yes, libelf sucks and we need to manually truncate if we over-allocate data.
1246  */
elf_truncate_section(struct elf * elf,struct section * sec)1247 static int elf_truncate_section(struct elf *elf, struct section *sec)
1248 {
1249 	u64 size = sec->sh.sh_size;
1250 	bool truncated = false;
1251 	Elf_Data *data = NULL;
1252 	Elf_Scn *s;
1253 
1254 	s = elf_getscn(elf->elf, sec->idx);
1255 	if (!s) {
1256 		ERROR_ELF("elf_getscn");
1257 		return -1;
1258 	}
1259 
1260 	for (;;) {
1261 		/* get next data descriptor for the relevant section */
1262 		data = elf_getdata(s, data);
1263 
1264 		if (!data) {
1265 			if (size) {
1266 				ERROR("end of section data but non-zero size left\n");
1267 				return -1;
1268 			}
1269 			return 0;
1270 		}
1271 
1272 		if (truncated) {
1273 			/* when we remove symbols */
1274 			ERROR("truncated; but more data\n");
1275 			return -1;
1276 		}
1277 
1278 		if (!data->d_size) {
1279 			ERROR("zero size data");
1280 			return -1;
1281 		}
1282 
1283 		if (data->d_size > size) {
1284 			truncated = true;
1285 			data->d_size = size;
1286 		}
1287 
1288 		size -= data->d_size;
1289 	}
1290 }
1291 
elf_write(struct elf * elf)1292 int elf_write(struct elf *elf)
1293 {
1294 	struct section *sec;
1295 	Elf_Scn *s;
1296 
1297 	/* Update changed relocation sections and section headers: */
1298 	list_for_each_entry(sec, &elf->sections, list) {
1299 		if (sec->truncate)
1300 			elf_truncate_section(elf, sec);
1301 
1302 		if (sec_changed(sec)) {
1303 			s = elf_getscn(elf->elf, sec->idx);
1304 			if (!s) {
1305 				ERROR_ELF("elf_getscn");
1306 				return -1;
1307 			}
1308 
1309 			/* Note this also flags the section dirty */
1310 			if (!gelf_update_shdr(s, &sec->sh)) {
1311 				ERROR_ELF("gelf_update_shdr");
1312 				return -1;
1313 			}
1314 
1315 			mark_sec_changed(elf, sec, false);
1316 		}
1317 	}
1318 
1319 	/* Make sure the new section header entries get updated properly. */
1320 	elf_flagelf(elf->elf, ELF_C_SET, ELF_F_DIRTY);
1321 
1322 	/* Write all changes to the file. */
1323 	if (elf_update(elf->elf, ELF_C_WRITE) < 0) {
1324 		ERROR_ELF("elf_update");
1325 		return -1;
1326 	}
1327 
1328 	elf->changed = false;
1329 
1330 	return 0;
1331 }
1332 
elf_close(struct elf * elf)1333 void elf_close(struct elf *elf)
1334 {
1335 	if (elf->elf)
1336 		elf_end(elf->elf);
1337 
1338 	if (elf->fd > 0)
1339 		close(elf->fd);
1340 
1341 	/*
1342 	 * NOTE: All remaining allocations are leaked on purpose.  Objtool is
1343 	 * about to exit anyway.
1344 	 */
1345 }
1346