xref: /linux/tools/objtool/elf.c (revision 2092007aa32f8dd968c38751bd1b7cac9b1f738d)
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 <libgen.h>
20 #include <ctype.h>
21 #include <linux/interval_tree_generic.h>
22 #include <objtool/builtin.h>
23 #include <objtool/elf.h>
24 #include <objtool/warn.h>
25 
26 #define ALIGN_UP(x, align_to) (((x) + ((align_to)-1)) & ~((align_to)-1))
27 #define ALIGN_UP_POW2(x) (1U << ((8 * sizeof(x)) - __builtin_clz((x) - 1U)))
28 #define MAX(a, b) ((a) > (b) ? (a) : (b))
29 
30 static inline u32 str_hash(const char *str)
31 {
32 	return jhash(str, strlen(str), 0);
33 }
34 
35 #define __elf_table(name)	(elf->name##_hash)
36 #define __elf_bits(name)	(elf->name##_bits)
37 
38 #define __elf_table_entry(name, key) \
39 	__elf_table(name)[hash_min(key, __elf_bits(name))]
40 
41 #define elf_hash_add(name, node, key)					\
42 ({									\
43 	struct elf_hash_node *__node = node;				\
44 	__node->next = __elf_table_entry(name, key);			\
45 	__elf_table_entry(name, key) = __node;				\
46 })
47 
48 static inline void __elf_hash_del(struct elf_hash_node *node,
49 				  struct elf_hash_node **head)
50 {
51 	struct elf_hash_node *cur, *prev;
52 
53 	if (node == *head) {
54 		*head = node->next;
55 		return;
56 	}
57 
58 	for (prev = NULL, cur = *head; cur; prev = cur, cur = cur->next) {
59 		if (cur == node) {
60 			prev->next = cur->next;
61 			break;
62 		}
63 	}
64 }
65 
66 #define elf_hash_del(name, node, key) \
67 	__elf_hash_del(node, &__elf_table_entry(name, key))
68 
69 #define elf_list_entry(ptr, type, member)				\
70 ({									\
71 	typeof(ptr) __ptr = (ptr);					\
72 	__ptr ? container_of(__ptr, type, member) : NULL;		\
73 })
74 
75 #define elf_hash_for_each_possible(name, obj, member, key)		\
76 	for (obj = elf_list_entry(__elf_table_entry(name, key), typeof(*obj), member); \
77 	     obj;							\
78 	     obj = elf_list_entry(obj->member.next, typeof(*(obj)), member))
79 
80 #define elf_alloc_hash(name, size)					\
81 ({									\
82 	__elf_bits(name) = max(10, ilog2(size));			\
83 	__elf_table(name) = mmap(NULL, sizeof(struct elf_hash_node *) << __elf_bits(name), \
84 				 PROT_READ|PROT_WRITE,			\
85 				 MAP_PRIVATE|MAP_ANON, -1, 0);		\
86 	if (__elf_table(name) == (void *)-1L) {				\
87 		ERROR_GLIBC("mmap fail " #name);			\
88 		__elf_table(name) = NULL;				\
89 	}								\
90 	__elf_table(name);						\
91 })
92 
93 static inline unsigned long __sym_start(struct symbol *s)
94 {
95 	return s->offset;
96 }
97 
98 static inline unsigned long __sym_last(struct symbol *s)
99 {
100 	return s->offset + (s->len ? s->len - 1 : 0);
101 }
102 
103 INTERVAL_TREE_DEFINE(struct symbol, node, unsigned long, __subtree_last,
104 		     __sym_start, __sym_last, static inline __maybe_unused,
105 		     __sym)
106 
107 #define __sym_for_each(_iter, _tree, _start, _end)			\
108 	for (_iter = __sym_iter_first((_tree), (_start), (_end));	\
109 	     _iter; _iter = __sym_iter_next(_iter, (_start), (_end)))
110 
111 struct symbol_hole {
112 	unsigned long key;
113 	const struct symbol *sym;
114 };
115 
116 /*
117  * Find the last symbol before @offset.
118  */
119 static int symbol_hole_by_offset(const void *key, const struct rb_node *node)
120 {
121 	const struct symbol *s = rb_entry(node, struct symbol, node);
122 	struct symbol_hole *sh = (void *)key;
123 
124 	if (sh->key < s->offset)
125 		return -1;
126 
127 	if (sh->key >= s->offset + s->len) {
128 		sh->sym = s;
129 		return 1;
130 	}
131 
132 	return 0;
133 }
134 
135 struct section *find_section_by_name(const struct elf *elf, const char *name)
136 {
137 	struct section *sec;
138 
139 	elf_hash_for_each_possible(section_name, sec, name_hash, str_hash(name)) {
140 		if (!strcmp(sec->name, name))
141 			return sec;
142 	}
143 
144 	return NULL;
145 }
146 
147 static struct section *find_section_by_index(struct elf *elf,
148 					     unsigned int idx)
149 {
150 	struct section *sec;
151 
152 	elf_hash_for_each_possible(section, sec, hash, idx) {
153 		if (sec->idx == idx)
154 			return sec;
155 	}
156 
157 	return NULL;
158 }
159 
160 static struct symbol *find_symbol_by_index(struct elf *elf, unsigned int idx)
161 {
162 	struct symbol *sym;
163 
164 	elf_hash_for_each_possible(symbol, sym, hash, idx) {
165 		if (sym->idx == idx)
166 			return sym;
167 	}
168 
169 	return NULL;
170 }
171 
172 struct symbol *find_symbol_by_offset(struct section *sec, unsigned long offset)
173 {
174 	struct rb_root_cached *tree = (struct rb_root_cached *)&sec->symbol_tree;
175 	struct symbol *iter;
176 
177 	__sym_for_each(iter, tree, offset, offset) {
178 		if (iter->offset == offset && !is_sec_sym(iter))
179 			return iter;
180 	}
181 
182 	return NULL;
183 }
184 
185 struct symbol *find_func_by_offset(struct section *sec, unsigned long offset)
186 {
187 	struct rb_root_cached *tree = (struct rb_root_cached *)&sec->symbol_tree;
188 	struct symbol *iter;
189 
190 	__sym_for_each(iter, tree, offset, offset) {
191 		if (iter->offset == offset && is_func_sym(iter))
192 			return iter;
193 	}
194 
195 	return NULL;
196 }
197 
198 struct symbol *find_symbol_containing(const struct section *sec, unsigned long offset)
199 {
200 	struct rb_root_cached *tree = (struct rb_root_cached *)&sec->symbol_tree;
201 	struct symbol *sym = NULL, *tmp;
202 
203 	__sym_for_each(tmp, tree, offset, offset) {
204 		if (tmp->len) {
205 			if (!sym) {
206 				sym = tmp;
207 				continue;
208 			}
209 
210 			if (sym->offset != tmp->offset || sym->len != tmp->len) {
211 				/*
212 				 * In the rare case of overlapping symbols,
213 				 * pick the smaller one.
214 				 *
215 				 * TODO: outlaw overlapping symbols
216 				 */
217 				if (tmp->len < sym->len)
218 					sym = tmp;
219 			}
220 		}
221 	}
222 
223 	return sym;
224 }
225 
226 /*
227  * Returns size of hole starting at @offset.
228  */
229 int find_symbol_hole_containing(const struct section *sec, unsigned long offset)
230 {
231 	struct symbol_hole hole = {
232 		.key = offset,
233 		.sym = NULL,
234 	};
235 	struct rb_node *n;
236 	struct symbol *s;
237 
238 	/*
239 	 * Find the rightmost symbol for which @offset is after it.
240 	 */
241 	n = rb_find(&hole, &sec->symbol_tree.rb_root, symbol_hole_by_offset);
242 
243 	/* found a symbol that contains @offset */
244 	if (n)
245 		return 0; /* not a hole */
246 
247 	/*
248 	 * @offset >= sym->offset + sym->len, find symbol after it.
249 	 * When hole.sym is empty, use the first node to compute the hole.
250 	 * If there is no symbol in the section, the first node will be NULL,
251 	 * in which case, -1 is returned to skip the whole section.
252 	 */
253 	if (hole.sym)
254 		n = rb_next(&hole.sym->node);
255 	else
256 		n = rb_first_cached(&sec->symbol_tree);
257 
258 	if (!n)
259 		return -1; /* until end of address space */
260 
261 	/* hole until start of next symbol */
262 	s = rb_entry(n, struct symbol, node);
263 	return s->offset - offset;
264 }
265 
266 struct symbol *find_func_containing(struct section *sec, unsigned long offset)
267 {
268 	struct rb_root_cached *tree = (struct rb_root_cached *)&sec->symbol_tree;
269 	struct symbol *iter;
270 
271 	__sym_for_each(iter, tree, offset, offset) {
272 		if (is_func_sym(iter))
273 			return iter;
274 	}
275 
276 	return NULL;
277 }
278 
279 struct symbol *find_symbol_by_name(const struct elf *elf, const char *name)
280 {
281 	struct symbol *sym;
282 
283 	elf_hash_for_each_possible(symbol_name, sym, name_hash, str_hash(name)) {
284 		if (!strcmp(sym->name, name))
285 			return sym;
286 	}
287 
288 	return NULL;
289 }
290 
291 struct symbol *find_global_symbol_by_name(const struct elf *elf, const char *name)
292 {
293 	struct symbol *sym;
294 
295 	elf_hash_for_each_possible(symbol_name, sym, name_hash, str_hash(name)) {
296 		if (!strcmp(sym->name, name) && !is_local_sym(sym))
297 			return sym;
298 	}
299 
300 	return NULL;
301 }
302 
303 struct reloc *find_reloc_by_dest_range(const struct elf *elf, struct section *sec,
304 				     unsigned long offset, unsigned int len)
305 {
306 	struct reloc *reloc, *r = NULL;
307 	struct section *rsec;
308 	unsigned long o;
309 
310 	rsec = sec->rsec;
311 	if (!rsec)
312 		return NULL;
313 
314 	for_offset_range(o, offset, offset + len) {
315 		elf_hash_for_each_possible(reloc, reloc, hash,
316 					   sec_offset_hash(rsec, o)) {
317 			if (reloc->sec != rsec)
318 				continue;
319 
320 			if (reloc_offset(reloc) >= offset &&
321 			    reloc_offset(reloc) < offset + len) {
322 				if (!r || reloc_offset(reloc) < reloc_offset(r))
323 					r = reloc;
324 			}
325 		}
326 		if (r)
327 			return r;
328 	}
329 
330 	return NULL;
331 }
332 
333 struct reloc *find_reloc_by_dest(const struct elf *elf, struct section *sec, unsigned long offset)
334 {
335 	return find_reloc_by_dest_range(elf, sec, offset, 1);
336 }
337 
338 static bool is_dwarf_section(struct section *sec)
339 {
340 	return !strncmp(sec->name, ".debug_", 7);
341 }
342 
343 static int read_sections(struct elf *elf)
344 {
345 	Elf_Scn *s = NULL;
346 	struct section *sec;
347 	size_t shstrndx, sections_nr;
348 	int i;
349 
350 	if (elf_getshdrnum(elf->elf, &sections_nr)) {
351 		ERROR_ELF("elf_getshdrnum");
352 		return -1;
353 	}
354 
355 	if (elf_getshdrstrndx(elf->elf, &shstrndx)) {
356 		ERROR_ELF("elf_getshdrstrndx");
357 		return -1;
358 	}
359 
360 	if (!elf_alloc_hash(section, sections_nr) ||
361 	    !elf_alloc_hash(section_name, sections_nr))
362 		return -1;
363 
364 	elf->section_data = calloc(sections_nr, sizeof(*sec));
365 	if (!elf->section_data) {
366 		ERROR_GLIBC("calloc");
367 		return -1;
368 	}
369 	for (i = 0; i < sections_nr; i++) {
370 		sec = &elf->section_data[i];
371 
372 		INIT_LIST_HEAD(&sec->symbol_list);
373 
374 		s = elf_getscn(elf->elf, i);
375 		if (!s) {
376 			ERROR_ELF("elf_getscn");
377 			return -1;
378 		}
379 
380 		sec->idx = elf_ndxscn(s);
381 
382 		if (!gelf_getshdr(s, &sec->sh)) {
383 			ERROR_ELF("gelf_getshdr");
384 			return -1;
385 		}
386 
387 		sec->name = elf_strptr(elf->elf, shstrndx, sec->sh.sh_name);
388 		if (!sec->name) {
389 			ERROR_ELF("elf_strptr");
390 			return -1;
391 		}
392 
393 		if (sec_size(sec) != 0 && !is_dwarf_section(sec)) {
394 			sec->data = elf_getdata(s, NULL);
395 			if (!sec->data) {
396 				ERROR_ELF("elf_getdata");
397 				return -1;
398 			}
399 			if (sec->data->d_off != 0 ||
400 			    sec->data->d_size != sec_size(sec)) {
401 				ERROR("unexpected data attributes for %s", sec->name);
402 				return -1;
403 			}
404 		}
405 
406 		list_add_tail(&sec->list, &elf->sections);
407 		elf_hash_add(section, &sec->hash, sec->idx);
408 		elf_hash_add(section_name, &sec->name_hash, str_hash(sec->name));
409 
410 		if (is_reloc_sec(sec))
411 			elf->num_relocs += sec_num_entries(sec);
412 	}
413 
414 	if (opts.stats) {
415 		printf("nr_sections: %lu\n", (unsigned long)sections_nr);
416 		printf("section_bits: %d\n", elf->section_bits);
417 	}
418 
419 	/* sanity check, one more call to elf_nextscn() should return NULL */
420 	if (elf_nextscn(elf->elf, s)) {
421 		ERROR("section entry mismatch");
422 		return -1;
423 	}
424 
425 	return 0;
426 }
427 
428 static const char *demangle_name(struct symbol *sym)
429 {
430 	char *str;
431 
432 	if (!is_local_sym(sym))
433 		return sym->name;
434 
435 	if (!is_func_sym(sym) && !is_object_sym(sym))
436 		return sym->name;
437 
438 	if (!strstarts(sym->name, "__UNIQUE_ID_") && !strchr(sym->name, '.'))
439 		return sym->name;
440 
441 	str = strdup(sym->name);
442 	if (!str) {
443 		ERROR_GLIBC("strdup");
444 		return NULL;
445 	}
446 
447 	for (int i = strlen(str) - 1; i >= 0; i--) {
448 		char c = str[i];
449 
450 		if (!isdigit(c) && c != '.') {
451 			str[i + 1] = '\0';
452 			break;
453 		}
454 	}
455 
456 	return str;
457 }
458 
459 static int elf_add_symbol(struct elf *elf, struct symbol *sym)
460 {
461 	struct list_head *entry;
462 	struct rb_node *pnode;
463 	struct symbol *iter;
464 
465 	INIT_LIST_HEAD(&sym->pv_target);
466 	sym->alias = sym;
467 
468 	sym->type = GELF_ST_TYPE(sym->sym.st_info);
469 	sym->bind = GELF_ST_BIND(sym->sym.st_info);
470 
471 	if (is_file_sym(sym))
472 		elf->num_files++;
473 
474 	sym->offset = sym->sym.st_value;
475 	sym->len = sym->sym.st_size;
476 
477 	__sym_for_each(iter, &sym->sec->symbol_tree, sym->offset, sym->offset) {
478 		if (iter->offset == sym->offset && iter->type == sym->type &&
479 		    iter->len == sym->len)
480 			iter->alias = sym;
481 	}
482 
483 	__sym_insert(sym, &sym->sec->symbol_tree);
484 	pnode = rb_prev(&sym->node);
485 	if (pnode)
486 		entry = &rb_entry(pnode, struct symbol, node)->list;
487 	else
488 		entry = &sym->sec->symbol_list;
489 	list_add(&sym->list, entry);
490 
491 	list_add_tail(&sym->global_list, &elf->symbols);
492 	elf_hash_add(symbol, &sym->hash, sym->idx);
493 	elf_hash_add(symbol_name, &sym->name_hash, str_hash(sym->name));
494 
495 	if (is_func_sym(sym) &&
496 	    (strstarts(sym->name, "__pfx_") ||
497 	     strstarts(sym->name, "__cfi_") ||
498 	     strstarts(sym->name, "__pi___pfx_") ||
499 	     strstarts(sym->name, "__pi___cfi_")))
500 		sym->prefix = 1;
501 
502 	if (strstarts(sym->name, ".klp.sym"))
503 		sym->klp = 1;
504 
505 	if (!sym->klp && is_func_sym(sym) && strstr(sym->name, ".cold"))
506 		sym->cold = 1;
507 	sym->pfunc = sym->cfunc = sym;
508 
509 	sym->demangled_name = demangle_name(sym);
510 	if (!sym->demangled_name)
511 		return -1;
512 
513 	return 0;
514 }
515 
516 static int read_symbols(struct elf *elf)
517 {
518 	struct section *symtab, *symtab_shndx, *sec;
519 	struct symbol *sym, *pfunc;
520 	int symbols_nr, i;
521 	char *coldstr;
522 	Elf_Data *shndx_data = NULL;
523 	Elf32_Word shndx;
524 
525 	symtab = find_section_by_name(elf, ".symtab");
526 	if (symtab) {
527 		symtab_shndx = find_section_by_name(elf, ".symtab_shndx");
528 		if (symtab_shndx)
529 			shndx_data = symtab_shndx->data;
530 
531 		symbols_nr = sec_num_entries(symtab);
532 	} else {
533 		/*
534 		 * A missing symbol table is actually possible if it's an empty
535 		 * .o file. This can happen for thunk_64.o. Make sure to at
536 		 * least allocate the symbol hash tables so we can do symbol
537 		 * lookups without crashing.
538 		 */
539 		symbols_nr = 0;
540 	}
541 
542 	if (!elf_alloc_hash(symbol, symbols_nr) ||
543 	    !elf_alloc_hash(symbol_name, symbols_nr))
544 		return -1;
545 
546 	elf->symbol_data = calloc(symbols_nr, sizeof(*sym));
547 	if (!elf->symbol_data) {
548 		ERROR_GLIBC("calloc");
549 		return -1;
550 	}
551 
552 	INIT_LIST_HEAD(&elf->symbols);
553 
554 	for (i = 0; i < symbols_nr; i++) {
555 		sym = &elf->symbol_data[i];
556 
557 		sym->idx = i;
558 
559 		if (!gelf_getsymshndx(symtab->data, shndx_data, i, &sym->sym,
560 				      &shndx)) {
561 			ERROR_ELF("gelf_getsymshndx");
562 			return -1;
563 		}
564 
565 		sym->name = elf_strptr(elf->elf, symtab->sh.sh_link,
566 				       sym->sym.st_name);
567 		if (!sym->name) {
568 			ERROR_ELF("elf_strptr");
569 			return -1;
570 		}
571 
572 		if ((sym->sym.st_shndx > SHN_UNDEF &&
573 		     sym->sym.st_shndx < SHN_LORESERVE) ||
574 		    (shndx_data && sym->sym.st_shndx == SHN_XINDEX)) {
575 			if (sym->sym.st_shndx != SHN_XINDEX)
576 				shndx = sym->sym.st_shndx;
577 
578 			sym->sec = find_section_by_index(elf, shndx);
579 			if (!sym->sec) {
580 				ERROR("couldn't find section for symbol %s", sym->name);
581 				return -1;
582 			}
583 			if (GELF_ST_TYPE(sym->sym.st_info) == STT_SECTION) {
584 				sym->name = sym->sec->name;
585 				sym->sec->sym = sym;
586 			}
587 		} else
588 			sym->sec = find_section_by_index(elf, 0);
589 
590 		if (elf_add_symbol(elf, sym))
591 			return -1;
592 	}
593 
594 	if (opts.stats) {
595 		printf("nr_symbols: %lu\n", (unsigned long)symbols_nr);
596 		printf("symbol_bits: %d\n", elf->symbol_bits);
597 	}
598 
599 	/* Create parent/child links for any cold subfunctions */
600 	list_for_each_entry(sec, &elf->sections, list) {
601 		sec_for_each_sym(sec, sym) {
602 			char *pname;
603 			size_t pnamelen;
604 
605 			if (!sym->cold)
606 				continue;
607 
608 			coldstr = strstr(sym->name, ".cold");
609 			if (!coldstr) {
610 				ERROR("%s(): cold subfunction without \".cold\"?", sym->name);
611 				return -1;
612 			}
613 
614 			pnamelen = coldstr - sym->name;
615 			pname = strndup(sym->name, pnamelen);
616 			if (!pname) {
617 				ERROR("%s(): failed to allocate memory", sym->name);
618 				return -1;
619 			}
620 
621 			pfunc = find_symbol_by_name(elf, pname);
622 			free(pname);
623 
624 			if (!pfunc) {
625 				ERROR("%s(): can't find parent function", sym->name);
626 				return -1;
627 			}
628 
629 			sym->pfunc = pfunc;
630 			pfunc->cfunc = sym;
631 
632 			/*
633 			 * Unfortunately, -fnoreorder-functions puts the child
634 			 * inside the parent.  Remove the overlap so we can
635 			 * have sane assumptions.
636 			 *
637 			 * Note that pfunc->len now no longer matches
638 			 * pfunc->sym.st_size.
639 			 */
640 			if (sym->sec == pfunc->sec &&
641 			    sym->offset >= pfunc->offset &&
642 			    sym->offset + sym->len == pfunc->offset + pfunc->len) {
643 				pfunc->len -= sym->len;
644 			}
645 		}
646 	}
647 
648 	return 0;
649 }
650 
651 static int mark_group_syms(struct elf *elf)
652 {
653 	struct section *symtab, *sec;
654 	struct symbol *sym;
655 
656 	symtab = find_section_by_name(elf, ".symtab");
657 	if (!symtab) {
658 		ERROR("no .symtab");
659 		return -1;
660 	}
661 
662 	for_each_sec(elf, sec) {
663 		if (sec->sh.sh_type == SHT_GROUP &&
664 		    sec->sh.sh_link == symtab->idx) {
665 			sym = find_symbol_by_index(elf, sec->sh.sh_info);
666 			if (!sym) {
667 				ERROR("%s: can't find SHT_GROUP signature symbol",
668 				      sec->name);
669 				return -1;
670 			}
671 
672 			sym->group_sec = sec;
673 		}
674 	}
675 
676 	return 0;
677 }
678 
679 /*
680  * @sym's idx has changed.  Update the relocs which reference it.
681  */
682 static int elf_update_sym_relocs(struct elf *elf, struct symbol *sym)
683 {
684 	struct reloc *reloc;
685 
686 	for (reloc = sym->relocs; reloc; reloc = sym_next_reloc(reloc))
687 		set_reloc_sym(elf, reloc, reloc->sym->idx);
688 
689 	return 0;
690 }
691 
692 /*
693  * The libelf API is terrible; gelf_update_sym*() takes a data block relative
694  * index value, *NOT* the symbol index. As such, iterate the data blocks and
695  * adjust index until it fits.
696  *
697  * If no data block is found, allow adding a new data block provided the index
698  * is only one past the end.
699  */
700 static int elf_update_symbol(struct elf *elf, struct section *symtab,
701 			     struct section *symtab_shndx, struct symbol *sym)
702 {
703 	Elf32_Word shndx;
704 	Elf_Data *symtab_data = NULL, *shndx_data = NULL;
705 	Elf64_Xword entsize = symtab->sh.sh_entsize;
706 	int max_idx, idx = sym->idx;
707 	Elf_Scn *s, *t = NULL;
708 	bool is_special_shndx = sym->sym.st_shndx >= SHN_LORESERVE &&
709 				sym->sym.st_shndx != SHN_XINDEX;
710 
711 	shndx = is_special_shndx ? sym->sym.st_shndx : sym->sec->idx;
712 
713 	s = elf_getscn(elf->elf, symtab->idx);
714 	if (!s) {
715 		ERROR_ELF("elf_getscn");
716 		return -1;
717 	}
718 
719 	if (symtab_shndx) {
720 		t = elf_getscn(elf->elf, symtab_shndx->idx);
721 		if (!t) {
722 			ERROR_ELF("elf_getscn");
723 			return -1;
724 		}
725 	}
726 
727 	for (;;) {
728 		/* get next data descriptor for the relevant sections */
729 		symtab_data = elf_getdata(s, symtab_data);
730 		if (t)
731 			shndx_data = elf_getdata(t, shndx_data);
732 
733 		/* end-of-list */
734 		if (!symtab_data) {
735 			/*
736 			 * Over-allocate to avoid O(n^2) symbol creation
737 			 * behaviour.  The down side is that libelf doesn't
738 			 * like this; see elf_truncate_section() for the fixup.
739 			 */
740 			int num = max(1U, sym->idx/3);
741 			void *buf;
742 
743 			if (idx) {
744 				/* we don't do holes in symbol tables */
745 				ERROR("index out of range");
746 				return -1;
747 			}
748 
749 			/* if @idx == 0, it's the next contiguous entry, create it */
750 			symtab_data = elf_newdata(s);
751 			if (t)
752 				shndx_data = elf_newdata(t);
753 
754 			buf = calloc(num, entsize);
755 			if (!buf) {
756 				ERROR_GLIBC("calloc");
757 				return -1;
758 			}
759 
760 			symtab_data->d_buf = buf;
761 			symtab_data->d_size = num * entsize;
762 			symtab_data->d_align = 1;
763 			symtab_data->d_type = ELF_T_SYM;
764 
765 			mark_sec_changed(elf, symtab, true);
766 			symtab->truncate = true;
767 
768 			if (t) {
769 				buf = calloc(num, sizeof(Elf32_Word));
770 				if (!buf) {
771 					ERROR_GLIBC("calloc");
772 					return -1;
773 				}
774 
775 				shndx_data->d_buf = buf;
776 				shndx_data->d_size = num * sizeof(Elf32_Word);
777 				shndx_data->d_align = sizeof(Elf32_Word);
778 				shndx_data->d_type = ELF_T_WORD;
779 
780 				mark_sec_changed(elf, symtab_shndx, true);
781 				symtab_shndx->truncate = true;
782 			}
783 
784 			break;
785 		}
786 
787 		/* empty blocks should not happen */
788 		if (!symtab_data->d_size) {
789 			ERROR("zero size data");
790 			return -1;
791 		}
792 
793 		/* is this the right block? */
794 		max_idx = symtab_data->d_size / entsize;
795 		if (idx < max_idx)
796 			break;
797 
798 		/* adjust index and try again */
799 		idx -= max_idx;
800 	}
801 
802 	/* something went side-ways */
803 	if (idx < 0) {
804 		ERROR("negative index");
805 		return -1;
806 	}
807 
808 	/* setup extended section index magic and write the symbol */
809 	if (shndx < SHN_LORESERVE || is_special_shndx) {
810 		sym->sym.st_shndx = shndx;
811 		if (!shndx_data)
812 			shndx = 0;
813 	} else {
814 		sym->sym.st_shndx = SHN_XINDEX;
815 		if (!shndx_data) {
816 			ERROR("no .symtab_shndx");
817 			return -1;
818 		}
819 	}
820 
821 	if (!gelf_update_symshndx(symtab_data, shndx_data, idx, &sym->sym, shndx)) {
822 		ERROR_ELF("gelf_update_symshndx");
823 		return -1;
824 	}
825 
826 	return 0;
827 }
828 
829 struct symbol *elf_create_symbol(struct elf *elf, const char *name,
830 				 struct section *sec, unsigned int bind,
831 				 unsigned int type, unsigned long offset,
832 				 size_t size)
833 {
834 	struct section *symtab, *symtab_shndx;
835 	Elf32_Word first_non_local, new_idx;
836 	struct symbol *old, *sym;
837 
838 	sym = calloc(1, sizeof(*sym));
839 	if (!sym) {
840 		ERROR_GLIBC("calloc");
841 		return NULL;
842 	}
843 
844 	sym->name = strdup(name);
845 	if (!sym->name) {
846 		ERROR_GLIBC("strdup");
847 		return NULL;
848 	}
849 
850 	if (type != STT_SECTION) {
851 		sym->sym.st_name = elf_add_string(elf, NULL, sym->name);
852 		if (sym->sym.st_name == -1)
853 			return NULL;
854 	}
855 
856 	if (sec) {
857 		sym->sec = sec;
858 	} else {
859 		sym->sec = find_section_by_index(elf, 0);
860 		if (!sym->sec) {
861 			ERROR("no NULL section");
862 			return NULL;
863 		}
864 	}
865 
866 	sym->sym.st_info  = GELF_ST_INFO(bind, type);
867 	sym->sym.st_value = offset;
868 	sym->sym.st_size  = size;
869 
870 	symtab = find_section_by_name(elf, ".symtab");
871 	if (!symtab) {
872 		ERROR("no .symtab");
873 		return NULL;
874 	}
875 
876 	symtab_shndx = find_section_by_name(elf, ".symtab_shndx");
877 
878 	new_idx = sec_num_entries(symtab);
879 
880 	if (bind != STB_LOCAL)
881 		goto non_local;
882 
883 	/*
884 	 * Move the first global symbol, as per sh_info, into a new, higher
885 	 * symbol index. This frees up a spot for a new local symbol.
886 	 */
887 	first_non_local = symtab->sh.sh_info;
888 	old = find_symbol_by_index(elf, first_non_local);
889 	if (old) {
890 
891 		elf_hash_del(symbol, &old->hash, old->idx);
892 		elf_hash_add(symbol, &old->hash, new_idx);
893 		old->idx = new_idx;
894 
895 		if (elf_update_symbol(elf, symtab, symtab_shndx, old)) {
896 			ERROR("elf_update_symbol move");
897 			return NULL;
898 		}
899 
900 		if (elf_update_sym_relocs(elf, old))
901 			return NULL;
902 
903 		if (old->group_sec) {
904 			old->group_sec->sh.sh_info = new_idx;
905 			mark_sec_changed(elf, old->group_sec, true);
906 		}
907 
908 		new_idx = first_non_local;
909 	}
910 
911 	/*
912 	 * Either way, we will add a LOCAL symbol.
913 	 */
914 	symtab->sh.sh_info += 1;
915 
916 non_local:
917 	sym->idx = new_idx;
918 	if (sym->idx && elf_update_symbol(elf, symtab, symtab_shndx, sym))
919 		return NULL;
920 
921 	symtab->sh.sh_size += symtab->sh.sh_entsize;
922 	mark_sec_changed(elf, symtab, true);
923 
924 	if (symtab_shndx) {
925 		symtab_shndx->sh.sh_size += sizeof(Elf32_Word);
926 		mark_sec_changed(elf, symtab_shndx, true);
927 	}
928 
929 	if (elf_add_symbol(elf, sym))
930 		return NULL;
931 
932 	return sym;
933 }
934 
935 struct symbol *elf_create_section_symbol(struct elf *elf, struct section *sec)
936 {
937 	struct symbol *sym = calloc(1, sizeof(*sym));
938 
939 	sym = elf_create_symbol(elf, sec->name, sec, STB_LOCAL, STT_SECTION, 0, 0);
940 	if (!sym)
941 		return NULL;
942 
943 	sec->sym = sym;
944 
945 	return sym;
946 }
947 
948 struct reloc *elf_init_reloc(struct elf *elf, struct section *rsec,
949 			     unsigned int reloc_idx, unsigned long offset,
950 			     struct symbol *sym, s64 addend, unsigned int type)
951 {
952 	struct reloc *reloc, empty = { 0 };
953 
954 	if (reloc_idx >= sec_num_entries(rsec)) {
955 		ERROR("%s: bad reloc_idx %u for %s with %d relocs",
956 		      __func__, reloc_idx, rsec->name, sec_num_entries(rsec));
957 		return NULL;
958 	}
959 
960 	reloc = &rsec->relocs[reloc_idx];
961 
962 	if (memcmp(reloc, &empty, sizeof(empty))) {
963 		ERROR("%s: %s: reloc %d already initialized!",
964 		      __func__, rsec->name, reloc_idx);
965 		return NULL;
966 	}
967 
968 	reloc->sec = rsec;
969 	reloc->sym = sym;
970 
971 	set_reloc_offset(elf, reloc, offset);
972 	set_reloc_sym(elf, reloc, sym->idx);
973 	set_reloc_type(elf, reloc, type);
974 	set_reloc_addend(elf, reloc, addend);
975 
976 	elf_hash_add(reloc, &reloc->hash, reloc_hash(reloc));
977 	set_sym_next_reloc(reloc, sym->relocs);
978 	sym->relocs = reloc;
979 
980 	return reloc;
981 }
982 
983 struct reloc *elf_init_reloc_text_sym(struct elf *elf, struct section *sec,
984 				      unsigned long offset,
985 				      unsigned int reloc_idx,
986 				      struct section *insn_sec,
987 				      unsigned long insn_off)
988 {
989 	struct symbol *sym = insn_sec->sym;
990 	s64 addend = insn_off;
991 
992 	if (!is_text_sec(insn_sec)) {
993 		ERROR("bad call to %s() for data symbol %s", __func__, sym->name);
994 		return NULL;
995 	}
996 
997 	if (!sym) {
998 		/*
999 		 * Due to how weak functions work, we must use section based
1000 		 * relocations. Symbol based relocations would result in the
1001 		 * weak and non-weak function annotations being overlaid on the
1002 		 * non-weak function after linking.
1003 		 */
1004 		sym = elf_create_section_symbol(elf, insn_sec);
1005 		if (!sym)
1006 			return NULL;
1007 	}
1008 
1009 	return elf_init_reloc(elf, sec->rsec, reloc_idx, offset, sym, addend,
1010 			      elf_text_rela_type(elf));
1011 }
1012 
1013 struct reloc *elf_init_reloc_data_sym(struct elf *elf, struct section *sec,
1014 				      unsigned long offset,
1015 				      unsigned int reloc_idx,
1016 				      struct symbol *sym,
1017 				      s64 addend)
1018 {
1019 	if (is_text_sec(sec)) {
1020 		ERROR("bad call to %s() for text symbol %s", __func__, sym->name);
1021 		return NULL;
1022 	}
1023 
1024 	return elf_init_reloc(elf, sec->rsec, reloc_idx, offset, sym, addend,
1025 			      elf_data_rela_type(elf));
1026 }
1027 
1028 static int read_relocs(struct elf *elf)
1029 {
1030 	unsigned long nr_reloc, max_reloc = 0;
1031 	struct section *rsec;
1032 	struct reloc *reloc;
1033 	unsigned int symndx;
1034 	struct symbol *sym;
1035 	int i;
1036 
1037 	if (!elf_alloc_hash(reloc, elf->num_relocs))
1038 		return -1;
1039 
1040 	list_for_each_entry(rsec, &elf->sections, list) {
1041 		if (!is_reloc_sec(rsec))
1042 			continue;
1043 
1044 		rsec->base = find_section_by_index(elf, rsec->sh.sh_info);
1045 		if (!rsec->base) {
1046 			ERROR("can't find base section for reloc section %s", rsec->name);
1047 			return -1;
1048 		}
1049 
1050 		rsec->base->rsec = rsec;
1051 
1052 		/* nr_alloc_relocs=0: libelf owns d_buf */
1053 		rsec->nr_alloc_relocs = 0;
1054 
1055 		rsec->relocs = calloc(sec_num_entries(rsec), sizeof(*reloc));
1056 		if (!rsec->relocs) {
1057 			ERROR_GLIBC("calloc");
1058 			return -1;
1059 		}
1060 
1061 		nr_reloc = 0;
1062 		for (i = 0; i < sec_num_entries(rsec); i++) {
1063 			reloc = &rsec->relocs[i];
1064 
1065 			reloc->sec = rsec;
1066 			symndx = reloc_sym(reloc);
1067 			reloc->sym = sym = find_symbol_by_index(elf, symndx);
1068 			if (!reloc->sym) {
1069 				ERROR("can't find reloc entry symbol %d for %s", symndx, rsec->name);
1070 				return -1;
1071 			}
1072 
1073 			elf_hash_add(reloc, &reloc->hash, reloc_hash(reloc));
1074 			set_sym_next_reloc(reloc, sym->relocs);
1075 			sym->relocs = reloc;
1076 
1077 			nr_reloc++;
1078 		}
1079 		max_reloc = max(max_reloc, nr_reloc);
1080 	}
1081 
1082 	if (opts.stats) {
1083 		printf("max_reloc: %lu\n", max_reloc);
1084 		printf("num_relocs: %lu\n", elf->num_relocs);
1085 		printf("reloc_bits: %d\n", elf->reloc_bits);
1086 	}
1087 
1088 	return 0;
1089 }
1090 
1091 struct elf *elf_open_read(const char *name, int flags)
1092 {
1093 	struct elf *elf;
1094 	Elf_Cmd cmd;
1095 
1096 	elf_version(EV_CURRENT);
1097 
1098 	elf = malloc(sizeof(*elf));
1099 	if (!elf) {
1100 		ERROR_GLIBC("malloc");
1101 		return NULL;
1102 	}
1103 	memset(elf, 0, sizeof(*elf));
1104 
1105 	INIT_LIST_HEAD(&elf->sections);
1106 
1107 	elf->fd = open(name, flags);
1108 	if (elf->fd == -1) {
1109 		fprintf(stderr, "objtool: Can't open '%s': %s\n",
1110 			name, strerror(errno));
1111 		goto err;
1112 	}
1113 
1114 	elf->name = strdup(name);
1115 	if (!elf->name) {
1116 		ERROR_GLIBC("strdup");
1117 		return NULL;
1118 	}
1119 
1120 	if ((flags & O_ACCMODE) == O_RDONLY)
1121 		cmd = ELF_C_READ_MMAP;
1122 	else if ((flags & O_ACCMODE) == O_RDWR)
1123 		cmd = ELF_C_RDWR;
1124 	else /* O_WRONLY */
1125 		cmd = ELF_C_WRITE;
1126 
1127 	elf->elf = elf_begin(elf->fd, cmd, NULL);
1128 	if (!elf->elf) {
1129 		ERROR_ELF("elf_begin");
1130 		goto err;
1131 	}
1132 
1133 	if (!gelf_getehdr(elf->elf, &elf->ehdr)) {
1134 		ERROR_ELF("gelf_getehdr");
1135 		goto err;
1136 	}
1137 
1138 	if (read_sections(elf))
1139 		goto err;
1140 
1141 	if (read_symbols(elf))
1142 		goto err;
1143 
1144 	if (mark_group_syms(elf))
1145 		goto err;
1146 
1147 	if (read_relocs(elf))
1148 		goto err;
1149 
1150 	return elf;
1151 
1152 err:
1153 	elf_close(elf);
1154 	return NULL;
1155 }
1156 
1157 struct elf *elf_create_file(GElf_Ehdr *ehdr, const char *name)
1158 {
1159 	struct section *null, *symtab, *strtab, *shstrtab;
1160 	char *dir, *base, *tmp_name;
1161 	struct symbol *sym;
1162 	struct elf *elf;
1163 
1164 	elf_version(EV_CURRENT);
1165 
1166 	elf = calloc(1, sizeof(*elf));
1167 	if (!elf) {
1168 		ERROR_GLIBC("calloc");
1169 		return NULL;
1170 	}
1171 
1172 	INIT_LIST_HEAD(&elf->sections);
1173 
1174 	dir = strdup(name);
1175 	if (!dir) {
1176 		ERROR_GLIBC("strdup");
1177 		return NULL;
1178 	}
1179 
1180 	dir = dirname(dir);
1181 
1182 	base = strdup(name);
1183 	if (!base) {
1184 		ERROR_GLIBC("strdup");
1185 		return NULL;
1186 	}
1187 
1188 	base = basename(base);
1189 
1190 	tmp_name = malloc(256);
1191 	if (!tmp_name) {
1192 		ERROR_GLIBC("malloc");
1193 		return NULL;
1194 	}
1195 
1196 	snprintf(tmp_name, 256, "%s/%s.XXXXXX", dir, base);
1197 
1198 	elf->fd = mkstemp(tmp_name);
1199 	if (elf->fd == -1) {
1200 		ERROR_GLIBC("can't create tmp file");
1201 		exit(1);
1202 	}
1203 
1204 	elf->tmp_name = tmp_name;
1205 
1206 	elf->name = strdup(name);
1207 	if (!elf->name) {
1208 		ERROR_GLIBC("strdup");
1209 		return NULL;
1210 	}
1211 
1212 	elf->elf = elf_begin(elf->fd, ELF_C_WRITE, NULL);
1213 	if (!elf->elf) {
1214 		ERROR_ELF("elf_begin");
1215 		return NULL;
1216 	}
1217 
1218 	if (!gelf_newehdr(elf->elf, ELFCLASS64)) {
1219 		ERROR_ELF("gelf_newehdr");
1220 		return NULL;
1221 	}
1222 
1223 	memcpy(&elf->ehdr, ehdr, sizeof(elf->ehdr));
1224 
1225 	if (!gelf_update_ehdr(elf->elf, &elf->ehdr)) {
1226 		ERROR_ELF("gelf_update_ehdr");
1227 		return NULL;
1228 	}
1229 
1230 	INIT_LIST_HEAD(&elf->symbols);
1231 
1232 	if (!elf_alloc_hash(section,		1000) ||
1233 	    !elf_alloc_hash(section_name,	1000) ||
1234 	    !elf_alloc_hash(symbol,		10000) ||
1235 	    !elf_alloc_hash(symbol_name,	10000) ||
1236 	    !elf_alloc_hash(reloc,		100000))
1237 		return NULL;
1238 
1239 	null		= elf_create_section(elf, NULL, 0, 0, SHT_NULL, 0, 0);
1240 	shstrtab	= elf_create_section(elf, NULL, 0, 0, SHT_STRTAB, 1, 0);
1241 	strtab		= elf_create_section(elf, NULL, 0, 0, SHT_STRTAB, 1, 0);
1242 
1243 	if (!null || !shstrtab || !strtab)
1244 		return NULL;
1245 
1246 	null->name	= "";
1247 	shstrtab->name	= ".shstrtab";
1248 	strtab->name	= ".strtab";
1249 
1250 	null->sh.sh_name	= elf_add_string(elf, shstrtab, null->name);
1251 	shstrtab->sh.sh_name	= elf_add_string(elf, shstrtab, shstrtab->name);
1252 	strtab->sh.sh_name	= elf_add_string(elf, shstrtab, strtab->name);
1253 
1254 	if (null->sh.sh_name == -1 || shstrtab->sh.sh_name == -1 || strtab->sh.sh_name == -1)
1255 		return NULL;
1256 
1257 	elf_hash_add(section_name, &null->name_hash,		str_hash(null->name));
1258 	elf_hash_add(section_name, &strtab->name_hash,		str_hash(strtab->name));
1259 	elf_hash_add(section_name, &shstrtab->name_hash,	str_hash(shstrtab->name));
1260 
1261 	if (elf_add_string(elf, strtab, "") == -1)
1262 		return NULL;
1263 
1264 	symtab = elf_create_section(elf, ".symtab", 0x18, 0x18, SHT_SYMTAB, 0x8, 0);
1265 	if (!symtab)
1266 		return NULL;
1267 
1268 	symtab->sh.sh_link = strtab->idx;
1269 	symtab->sh.sh_info = 1;
1270 
1271 	elf->ehdr.e_shstrndx = shstrtab->idx;
1272 	if (!gelf_update_ehdr(elf->elf, &elf->ehdr)) {
1273 		ERROR_ELF("gelf_update_ehdr");
1274 		return NULL;
1275 	}
1276 
1277 	sym = calloc(1, sizeof(*sym));
1278 	if (!sym) {
1279 		ERROR_GLIBC("calloc");
1280 		return NULL;
1281 	}
1282 
1283 	sym->name = "";
1284 	sym->sec = null;
1285 	elf_add_symbol(elf, sym);
1286 
1287 	return elf;
1288 }
1289 
1290 unsigned int elf_add_string(struct elf *elf, struct section *strtab, const char *str)
1291 {
1292 	unsigned int offset;
1293 
1294 	if (!strtab)
1295 		strtab = find_section_by_name(elf, ".strtab");
1296 	if (!strtab) {
1297 		ERROR("can't find .strtab section");
1298 		return -1;
1299 	}
1300 
1301 	if (!strtab->sh.sh_addralign) {
1302 		ERROR("'%s': invalid sh_addralign", strtab->name);
1303 		return -1;
1304 	}
1305 
1306 	offset = ALIGN_UP(strtab->sh.sh_size, strtab->sh.sh_addralign);
1307 
1308 	if (!elf_add_data(elf, strtab, str, strlen(str) + 1))
1309 		return -1;
1310 
1311 	return offset;
1312 }
1313 
1314 void *elf_add_data(struct elf *elf, struct section *sec, const void *data, size_t size)
1315 {
1316 	unsigned long offset;
1317 	Elf_Scn *s;
1318 
1319 	if (!sec->sh.sh_addralign) {
1320 		ERROR("'%s': invalid sh_addralign", sec->name);
1321 		return NULL;
1322 	}
1323 
1324 	s = elf_getscn(elf->elf, sec->idx);
1325 	if (!s) {
1326 		ERROR_ELF("elf_getscn");
1327 		return NULL;
1328 	}
1329 
1330 	sec->data = elf_newdata(s);
1331 	if (!sec->data) {
1332 		ERROR_ELF("elf_newdata");
1333 		return NULL;
1334 	}
1335 
1336 	sec->data->d_buf = calloc(1, size);
1337 	if (!sec->data->d_buf) {
1338 		ERROR_GLIBC("calloc");
1339 		return NULL;
1340 	}
1341 
1342 	if (data)
1343 		memcpy(sec->data->d_buf, data, size);
1344 
1345 	sec->data->d_size = size;
1346 	sec->data->d_align = 1;
1347 
1348 	offset = ALIGN_UP(sec->sh.sh_size, sec->sh.sh_addralign);
1349 	sec->sh.sh_size = offset + size;
1350 
1351 	mark_sec_changed(elf, sec, true);
1352 
1353 	return sec->data->d_buf;
1354 }
1355 
1356 struct section *elf_create_section(struct elf *elf, const char *name,
1357 				   size_t size, size_t entsize,
1358 				   unsigned int type, unsigned int align,
1359 				   unsigned int flags)
1360 {
1361 	struct section *sec, *shstrtab;
1362 	Elf_Scn *s;
1363 
1364 	if (name && find_section_by_name(elf, name)) {
1365 		ERROR("section '%s' already exists", name);
1366 		return NULL;
1367 	}
1368 
1369 	sec = calloc(1, sizeof(*sec));
1370 	if (!sec) {
1371 		ERROR_GLIBC("calloc");
1372 		return NULL;
1373 	}
1374 
1375 	INIT_LIST_HEAD(&sec->symbol_list);
1376 
1377 	/* don't actually create the section, just the data structures */
1378 	if (type == SHT_NULL)
1379 		goto add;
1380 
1381 	s = elf_newscn(elf->elf);
1382 	if (!s) {
1383 		ERROR_ELF("elf_newscn");
1384 		return NULL;
1385 	}
1386 
1387 	sec->idx = elf_ndxscn(s);
1388 
1389 	if (size) {
1390 		sec->data = elf_newdata(s);
1391 		if (!sec->data) {
1392 			ERROR_ELF("elf_newdata");
1393 			return NULL;
1394 		}
1395 
1396 		sec->data->d_size = size;
1397 		sec->data->d_align = 1;
1398 
1399 		sec->data->d_buf = calloc(1, size);
1400 		if (!sec->data->d_buf) {
1401 			ERROR_GLIBC("calloc");
1402 			return NULL;
1403 		}
1404 	}
1405 
1406 	if (!gelf_getshdr(s, &sec->sh)) {
1407 		ERROR_ELF("gelf_getshdr");
1408 		return NULL;
1409 	}
1410 
1411 	sec->sh.sh_size = size;
1412 	sec->sh.sh_entsize = entsize;
1413 	sec->sh.sh_type = type;
1414 	sec->sh.sh_addralign = align;
1415 	sec->sh.sh_flags = flags;
1416 
1417 	if (name) {
1418 		sec->name = strdup(name);
1419 		if (!sec->name) {
1420 			ERROR("strdup");
1421 			return NULL;
1422 		}
1423 
1424 		/* Add section name to .shstrtab (or .strtab for Clang) */
1425 		shstrtab = find_section_by_name(elf, ".shstrtab");
1426 		if (!shstrtab) {
1427 			shstrtab = find_section_by_name(elf, ".strtab");
1428 			if (!shstrtab) {
1429 				ERROR("can't find .shstrtab or .strtab");
1430 				return NULL;
1431 			}
1432 		}
1433 		sec->sh.sh_name = elf_add_string(elf, shstrtab, sec->name);
1434 		if (sec->sh.sh_name == -1)
1435 			return NULL;
1436 
1437 		elf_hash_add(section_name, &sec->name_hash, str_hash(sec->name));
1438 	}
1439 
1440 add:
1441 	list_add_tail(&sec->list, &elf->sections);
1442 	elf_hash_add(section, &sec->hash, sec->idx);
1443 
1444 	mark_sec_changed(elf, sec, true);
1445 
1446 	return sec;
1447 }
1448 
1449 static int elf_alloc_reloc(struct elf *elf, struct section *rsec)
1450 {
1451 	struct reloc *old_relocs, *old_relocs_end, *new_relocs;
1452 	unsigned int nr_relocs_old = sec_num_entries(rsec);
1453 	unsigned int nr_relocs_new = nr_relocs_old + 1;
1454 	unsigned long nr_alloc;
1455 	struct symbol *sym;
1456 
1457 	if (!rsec->data) {
1458 		rsec->data = elf_newdata(elf_getscn(elf->elf, rsec->idx));
1459 		if (!rsec->data) {
1460 			ERROR_ELF("elf_newdata");
1461 			return -1;
1462 		}
1463 
1464 		rsec->data->d_align = 1;
1465 		rsec->data->d_type = ELF_T_RELA;
1466 		rsec->data->d_buf = NULL;
1467 	}
1468 
1469 	rsec->data->d_size = nr_relocs_new * elf_rela_size(elf);
1470 	rsec->sh.sh_size   = rsec->data->d_size;
1471 
1472 	nr_alloc = MAX(64, ALIGN_UP_POW2(nr_relocs_new));
1473 	if (nr_alloc <= rsec->nr_alloc_relocs)
1474 		return 0;
1475 
1476 	if (rsec->data->d_buf && !rsec->nr_alloc_relocs) {
1477 		void *orig_buf = rsec->data->d_buf;
1478 
1479 		/*
1480 		 * The original d_buf is owned by libelf so it can't be
1481 		 * realloced.
1482 		 */
1483 		rsec->data->d_buf = malloc(nr_alloc * elf_rela_size(elf));
1484 		if (!rsec->data->d_buf) {
1485 			ERROR_GLIBC("malloc");
1486 			return -1;
1487 		}
1488 		memcpy(rsec->data->d_buf, orig_buf,
1489 		       nr_relocs_old * elf_rela_size(elf));
1490 	} else {
1491 		rsec->data->d_buf = realloc(rsec->data->d_buf,
1492 					    nr_alloc * elf_rela_size(elf));
1493 		if (!rsec->data->d_buf) {
1494 			ERROR_GLIBC("realloc");
1495 			return -1;
1496 		}
1497 	}
1498 
1499 	rsec->nr_alloc_relocs = nr_alloc;
1500 
1501 	old_relocs = rsec->relocs;
1502 	new_relocs = calloc(nr_alloc, sizeof(struct reloc));
1503 	if (!new_relocs) {
1504 		ERROR_GLIBC("calloc");
1505 		return -1;
1506 	}
1507 
1508 	if (!old_relocs)
1509 		goto done;
1510 
1511 	/*
1512 	 * The struct reloc's address has changed.  Update all the symbols and
1513 	 * relocs which reference it.
1514 	 */
1515 
1516 	old_relocs_end = &old_relocs[nr_relocs_old];
1517 	for_each_sym(elf, sym) {
1518 		struct reloc *reloc;
1519 
1520 		reloc = sym->relocs;
1521 		if (!reloc)
1522 			continue;
1523 
1524 		if (reloc >= old_relocs && reloc < old_relocs_end)
1525 			sym->relocs = &new_relocs[reloc - old_relocs];
1526 
1527 		while (1) {
1528 			struct reloc *next_reloc = sym_next_reloc(reloc);
1529 
1530 			if (!next_reloc)
1531 				break;
1532 
1533 			if (next_reloc >= old_relocs && next_reloc < old_relocs_end)
1534 				set_sym_next_reloc(reloc, &new_relocs[next_reloc - old_relocs]);
1535 
1536 			reloc = next_reloc;
1537 		}
1538 	}
1539 
1540 	memcpy(new_relocs, old_relocs, nr_relocs_old * sizeof(struct reloc));
1541 
1542 	for (int i = 0; i < nr_relocs_old; i++) {
1543 		struct reloc *old = &old_relocs[i];
1544 		struct reloc *new = &new_relocs[i];
1545 		u32 key = reloc_hash(old);
1546 
1547 		elf_hash_del(reloc, &old->hash, key);
1548 		elf_hash_add(reloc, &new->hash, key);
1549 	}
1550 
1551 	free(old_relocs);
1552 done:
1553 	rsec->relocs = new_relocs;
1554 	return 0;
1555 }
1556 
1557 struct section *elf_create_rela_section(struct elf *elf, struct section *sec,
1558 					unsigned int nr_relocs)
1559 {
1560 	struct section *rsec;
1561 	char *rsec_name;
1562 
1563 	rsec_name = malloc(strlen(sec->name) + strlen(".rela") + 1);
1564 	if (!rsec_name) {
1565 		ERROR_GLIBC("malloc");
1566 		return NULL;
1567 	}
1568 	strcpy(rsec_name, ".rela");
1569 	strcat(rsec_name, sec->name);
1570 
1571 	rsec = elf_create_section(elf, rsec_name, nr_relocs * elf_rela_size(elf),
1572 				  elf_rela_size(elf), SHT_RELA, elf_addr_size(elf),
1573 				  SHF_INFO_LINK);
1574 	free(rsec_name);
1575 	if (!rsec)
1576 		return NULL;
1577 
1578 	if (nr_relocs) {
1579 		rsec->data->d_type = ELF_T_RELA;
1580 
1581 		rsec->nr_alloc_relocs = nr_relocs;
1582 		rsec->relocs = calloc(nr_relocs, sizeof(struct reloc));
1583 		if (!rsec->relocs) {
1584 			ERROR_GLIBC("calloc");
1585 			return NULL;
1586 		}
1587 	}
1588 
1589 	rsec->sh.sh_link = find_section_by_name(elf, ".symtab")->idx;
1590 	rsec->sh.sh_info = sec->idx;
1591 
1592 	sec->rsec = rsec;
1593 	rsec->base = sec;
1594 
1595 	return rsec;
1596 }
1597 
1598 struct reloc *elf_create_reloc(struct elf *elf, struct section *sec,
1599 			       unsigned long offset,
1600 			       struct symbol *sym, s64 addend,
1601 			       unsigned int type)
1602 {
1603 	struct section *rsec = sec->rsec;
1604 
1605 	if (!rsec) {
1606 		rsec = elf_create_rela_section(elf, sec, 0);
1607 		if (!rsec)
1608 			return NULL;
1609 	}
1610 
1611 	if (find_reloc_by_dest(elf, sec, offset)) {
1612 		ERROR_FUNC(sec, offset, "duplicate reloc");
1613 		return NULL;
1614 	}
1615 
1616 	if (elf_alloc_reloc(elf, rsec))
1617 		return NULL;
1618 
1619 	mark_sec_changed(elf, rsec, true);
1620 
1621 	return elf_init_reloc(elf, rsec, sec_num_entries(rsec) - 1, offset, sym,
1622 			      addend, type);
1623 }
1624 
1625 struct section *elf_create_section_pair(struct elf *elf, const char *name,
1626 					size_t entsize, unsigned int nr,
1627 					unsigned int nr_relocs)
1628 {
1629 	struct section *sec;
1630 
1631 	sec = elf_create_section(elf, name, nr * entsize, entsize,
1632 				 SHT_PROGBITS, 1, SHF_ALLOC);
1633 	if (!sec)
1634 		return NULL;
1635 
1636 	if (!elf_create_rela_section(elf, sec, nr_relocs))
1637 		return NULL;
1638 
1639 	return sec;
1640 }
1641 
1642 int elf_write_insn(struct elf *elf, struct section *sec,
1643 		   unsigned long offset, unsigned int len,
1644 		   const char *insn)
1645 {
1646 	Elf_Data *data = sec->data;
1647 
1648 	if (data->d_type != ELF_T_BYTE || data->d_off) {
1649 		ERROR("write to unexpected data for section: %s", sec->name);
1650 		return -1;
1651 	}
1652 
1653 	memcpy(data->d_buf + offset, insn, len);
1654 
1655 	mark_sec_changed(elf, sec, true);
1656 
1657 	return 0;
1658 }
1659 
1660 /*
1661  * When Elf_Scn::sh_size is smaller than the combined Elf_Data::d_size
1662  * do you:
1663  *
1664  *   A) adhere to the section header and truncate the data, or
1665  *   B) ignore the section header and write out all the data you've got?
1666  *
1667  * Yes, libelf sucks and we need to manually truncate if we over-allocate data.
1668  */
1669 static int elf_truncate_section(struct elf *elf, struct section *sec)
1670 {
1671 	u64 size = sec_size(sec);
1672 	bool truncated = false;
1673 	Elf_Data *data = NULL;
1674 	Elf_Scn *s;
1675 
1676 	s = elf_getscn(elf->elf, sec->idx);
1677 	if (!s) {
1678 		ERROR_ELF("elf_getscn");
1679 		return -1;
1680 	}
1681 
1682 	for (;;) {
1683 		/* get next data descriptor for the relevant section */
1684 		data = elf_getdata(s, data);
1685 		if (!data) {
1686 			if (size) {
1687 				ERROR("end of section data but non-zero size left\n");
1688 				return -1;
1689 			}
1690 			return 0;
1691 		}
1692 
1693 		if (truncated) {
1694 			/* when we remove symbols */
1695 			ERROR("truncated; but more data\n");
1696 			return -1;
1697 		}
1698 
1699 		if (!data->d_size) {
1700 			ERROR("zero size data");
1701 			return -1;
1702 		}
1703 
1704 		if (data->d_size > size) {
1705 			truncated = true;
1706 			data->d_size = size;
1707 		}
1708 
1709 		size -= data->d_size;
1710 	}
1711 }
1712 
1713 int elf_write(struct elf *elf)
1714 {
1715 	struct section *sec;
1716 	Elf_Scn *s;
1717 
1718 	/* Update changed relocation sections and section headers: */
1719 	list_for_each_entry(sec, &elf->sections, list) {
1720 		if (sec->truncate && elf_truncate_section(elf, sec))
1721 			return -1;
1722 
1723 		if (sec_changed(sec)) {
1724 			s = elf_getscn(elf->elf, sec->idx);
1725 			if (!s) {
1726 				ERROR_ELF("elf_getscn");
1727 				return -1;
1728 			}
1729 
1730 			/* Note this also flags the section dirty */
1731 			if (!gelf_update_shdr(s, &sec->sh)) {
1732 				ERROR_ELF("gelf_update_shdr");
1733 				return -1;
1734 			}
1735 
1736 			mark_sec_changed(elf, sec, false);
1737 		}
1738 	}
1739 
1740 	/* Make sure the new section header entries get updated properly. */
1741 	elf_flagelf(elf->elf, ELF_C_SET, ELF_F_DIRTY);
1742 
1743 	/* Write all changes to the file. */
1744 	if (elf_update(elf->elf, ELF_C_WRITE) < 0) {
1745 		ERROR_ELF("elf_update");
1746 		return -1;
1747 	}
1748 
1749 	elf->changed = false;
1750 
1751 	return 0;
1752 }
1753 
1754 int elf_close(struct elf *elf)
1755 {
1756 	if (elf->elf)
1757 		elf_end(elf->elf);
1758 
1759 	if (elf->fd > 0)
1760 		close(elf->fd);
1761 
1762 	if (elf->tmp_name && rename(elf->tmp_name, elf->name))
1763 		return -1;
1764 
1765 	/*
1766 	 * NOTE: All remaining allocations are leaked on purpose.  Objtool is
1767 	 * about to exit anyway.
1768 	 */
1769 	return 0;
1770 }
1771