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