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