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