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