xref: /linux/tools/objtool/elf.c (revision 2058f6d1660edc4a9bda9bee627792b352121b10)
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 (is_func_sym(sym) && strstr(sym->name, ".cold"))
503 		sym->cold = 1;
504 	sym->pfunc = sym->cfunc = sym;
505 
506 	sym->demangled_name = demangle_name(sym);
507 	if (!sym->demangled_name)
508 		return -1;
509 
510 	return 0;
511 }
512 
513 static int read_symbols(struct elf *elf)
514 {
515 	struct section *symtab, *symtab_shndx, *sec;
516 	struct symbol *sym, *pfunc;
517 	int symbols_nr, i;
518 	char *coldstr;
519 	Elf_Data *shndx_data = NULL;
520 	Elf32_Word shndx;
521 
522 	symtab = find_section_by_name(elf, ".symtab");
523 	if (symtab) {
524 		symtab_shndx = find_section_by_name(elf, ".symtab_shndx");
525 		if (symtab_shndx)
526 			shndx_data = symtab_shndx->data;
527 
528 		symbols_nr = sec_num_entries(symtab);
529 	} else {
530 		/*
531 		 * A missing symbol table is actually possible if it's an empty
532 		 * .o file. This can happen for thunk_64.o. Make sure to at
533 		 * least allocate the symbol hash tables so we can do symbol
534 		 * lookups without crashing.
535 		 */
536 		symbols_nr = 0;
537 	}
538 
539 	if (!elf_alloc_hash(symbol, symbols_nr) ||
540 	    !elf_alloc_hash(symbol_name, symbols_nr))
541 		return -1;
542 
543 	elf->symbol_data = calloc(symbols_nr, sizeof(*sym));
544 	if (!elf->symbol_data) {
545 		ERROR_GLIBC("calloc");
546 		return -1;
547 	}
548 
549 	INIT_LIST_HEAD(&elf->symbols);
550 
551 	for (i = 0; i < symbols_nr; i++) {
552 		sym = &elf->symbol_data[i];
553 
554 		sym->idx = i;
555 
556 		if (!gelf_getsymshndx(symtab->data, shndx_data, i, &sym->sym,
557 				      &shndx)) {
558 			ERROR_ELF("gelf_getsymshndx");
559 			return -1;
560 		}
561 
562 		sym->name = elf_strptr(elf->elf, symtab->sh.sh_link,
563 				       sym->sym.st_name);
564 		if (!sym->name) {
565 			ERROR_ELF("elf_strptr");
566 			return -1;
567 		}
568 
569 		if ((sym->sym.st_shndx > SHN_UNDEF &&
570 		     sym->sym.st_shndx < SHN_LORESERVE) ||
571 		    (shndx_data && sym->sym.st_shndx == SHN_XINDEX)) {
572 			if (sym->sym.st_shndx != SHN_XINDEX)
573 				shndx = sym->sym.st_shndx;
574 
575 			sym->sec = find_section_by_index(elf, shndx);
576 			if (!sym->sec) {
577 				ERROR("couldn't find section for symbol %s", sym->name);
578 				return -1;
579 			}
580 			if (GELF_ST_TYPE(sym->sym.st_info) == STT_SECTION) {
581 				sym->name = sym->sec->name;
582 				sym->sec->sym = sym;
583 			}
584 		} else
585 			sym->sec = find_section_by_index(elf, 0);
586 
587 		if (elf_add_symbol(elf, sym))
588 			return -1;
589 	}
590 
591 	if (opts.stats) {
592 		printf("nr_symbols: %lu\n", (unsigned long)symbols_nr);
593 		printf("symbol_bits: %d\n", elf->symbol_bits);
594 	}
595 
596 	/* Create parent/child links for any cold subfunctions */
597 	list_for_each_entry(sec, &elf->sections, list) {
598 		sec_for_each_sym(sec, sym) {
599 			char *pname;
600 			size_t pnamelen;
601 
602 			if (!sym->cold)
603 				continue;
604 
605 			coldstr = strstr(sym->name, ".cold");
606 			if (!coldstr) {
607 				ERROR("%s(): cold subfunction without \".cold\"?", sym->name);
608 				return -1;
609 			}
610 
611 			pnamelen = coldstr - sym->name;
612 			pname = strndup(sym->name, pnamelen);
613 			if (!pname) {
614 				ERROR("%s(): failed to allocate memory", sym->name);
615 				return -1;
616 			}
617 
618 			pfunc = find_symbol_by_name(elf, pname);
619 			free(pname);
620 
621 			if (!pfunc) {
622 				ERROR("%s(): can't find parent function", sym->name);
623 				return -1;
624 			}
625 
626 			sym->pfunc = pfunc;
627 			pfunc->cfunc = sym;
628 
629 			/*
630 			 * Unfortunately, -fnoreorder-functions puts the child
631 			 * inside the parent.  Remove the overlap so we can
632 			 * have sane assumptions.
633 			 *
634 			 * Note that pfunc->len now no longer matches
635 			 * pfunc->sym.st_size.
636 			 */
637 			if (sym->sec == pfunc->sec &&
638 			    sym->offset >= pfunc->offset &&
639 			    sym->offset + sym->len == pfunc->offset + pfunc->len) {
640 				pfunc->len -= sym->len;
641 			}
642 		}
643 	}
644 
645 	return 0;
646 }
647 
648 static int mark_group_syms(struct elf *elf)
649 {
650 	struct section *symtab, *sec;
651 	struct symbol *sym;
652 
653 	symtab = find_section_by_name(elf, ".symtab");
654 	if (!symtab) {
655 		ERROR("no .symtab");
656 		return -1;
657 	}
658 
659 	for_each_sec(elf, sec) {
660 		if (sec->sh.sh_type == SHT_GROUP &&
661 		    sec->sh.sh_link == symtab->idx) {
662 			sym = find_symbol_by_index(elf, sec->sh.sh_info);
663 			if (!sym) {
664 				ERROR("%s: can't find SHT_GROUP signature symbol",
665 				      sec->name);
666 				return -1;
667 			}
668 
669 			sym->group_sec = sec;
670 		}
671 	}
672 
673 	return 0;
674 }
675 
676 /*
677  * @sym's idx has changed.  Update the relocs which reference it.
678  */
679 static int elf_update_sym_relocs(struct elf *elf, struct symbol *sym)
680 {
681 	struct reloc *reloc;
682 
683 	for (reloc = sym->relocs; reloc; reloc = sym_next_reloc(reloc))
684 		set_reloc_sym(elf, reloc, reloc->sym->idx);
685 
686 	return 0;
687 }
688 
689 /*
690  * The libelf API is terrible; gelf_update_sym*() takes a data block relative
691  * index value, *NOT* the symbol index. As such, iterate the data blocks and
692  * adjust index until it fits.
693  *
694  * If no data block is found, allow adding a new data block provided the index
695  * is only one past the end.
696  */
697 static int elf_update_symbol(struct elf *elf, struct section *symtab,
698 			     struct section *symtab_shndx, struct symbol *sym)
699 {
700 	Elf32_Word shndx;
701 	Elf_Data *symtab_data = NULL, *shndx_data = NULL;
702 	Elf64_Xword entsize = symtab->sh.sh_entsize;
703 	int max_idx, idx = sym->idx;
704 	Elf_Scn *s, *t = NULL;
705 	bool is_special_shndx = sym->sym.st_shndx >= SHN_LORESERVE &&
706 				sym->sym.st_shndx != SHN_XINDEX;
707 
708 	shndx = is_special_shndx ? sym->sym.st_shndx : sym->sec->idx;
709 
710 	s = elf_getscn(elf->elf, symtab->idx);
711 	if (!s) {
712 		ERROR_ELF("elf_getscn");
713 		return -1;
714 	}
715 
716 	if (symtab_shndx) {
717 		t = elf_getscn(elf->elf, symtab_shndx->idx);
718 		if (!t) {
719 			ERROR_ELF("elf_getscn");
720 			return -1;
721 		}
722 	}
723 
724 	for (;;) {
725 		/* get next data descriptor for the relevant sections */
726 		symtab_data = elf_getdata(s, symtab_data);
727 		if (t)
728 			shndx_data = elf_getdata(t, shndx_data);
729 
730 		/* end-of-list */
731 		if (!symtab_data) {
732 			/*
733 			 * Over-allocate to avoid O(n^2) symbol creation
734 			 * behaviour.  The down side is that libelf doesn't
735 			 * like this; see elf_truncate_section() for the fixup.
736 			 */
737 			int num = max(1U, sym->idx/3);
738 			void *buf;
739 
740 			if (idx) {
741 				/* we don't do holes in symbol tables */
742 				ERROR("index out of range");
743 				return -1;
744 			}
745 
746 			/* if @idx == 0, it's the next contiguous entry, create it */
747 			symtab_data = elf_newdata(s);
748 			if (t)
749 				shndx_data = elf_newdata(t);
750 
751 			buf = calloc(num, entsize);
752 			if (!buf) {
753 				ERROR_GLIBC("calloc");
754 				return -1;
755 			}
756 
757 			symtab_data->d_buf = buf;
758 			symtab_data->d_size = num * entsize;
759 			symtab_data->d_align = 1;
760 			symtab_data->d_type = ELF_T_SYM;
761 
762 			mark_sec_changed(elf, symtab, true);
763 			symtab->truncate = true;
764 
765 			if (t) {
766 				buf = calloc(num, sizeof(Elf32_Word));
767 				if (!buf) {
768 					ERROR_GLIBC("calloc");
769 					return -1;
770 				}
771 
772 				shndx_data->d_buf = buf;
773 				shndx_data->d_size = num * sizeof(Elf32_Word);
774 				shndx_data->d_align = sizeof(Elf32_Word);
775 				shndx_data->d_type = ELF_T_WORD;
776 
777 				mark_sec_changed(elf, symtab_shndx, true);
778 				symtab_shndx->truncate = true;
779 			}
780 
781 			break;
782 		}
783 
784 		/* empty blocks should not happen */
785 		if (!symtab_data->d_size) {
786 			ERROR("zero size data");
787 			return -1;
788 		}
789 
790 		/* is this the right block? */
791 		max_idx = symtab_data->d_size / entsize;
792 		if (idx < max_idx)
793 			break;
794 
795 		/* adjust index and try again */
796 		idx -= max_idx;
797 	}
798 
799 	/* something went side-ways */
800 	if (idx < 0) {
801 		ERROR("negative index");
802 		return -1;
803 	}
804 
805 	/* setup extended section index magic and write the symbol */
806 	if (shndx < SHN_LORESERVE || is_special_shndx) {
807 		sym->sym.st_shndx = shndx;
808 		if (!shndx_data)
809 			shndx = 0;
810 	} else {
811 		sym->sym.st_shndx = SHN_XINDEX;
812 		if (!shndx_data) {
813 			ERROR("no .symtab_shndx");
814 			return -1;
815 		}
816 	}
817 
818 	if (!gelf_update_symshndx(symtab_data, shndx_data, idx, &sym->sym, shndx)) {
819 		ERROR_ELF("gelf_update_symshndx");
820 		return -1;
821 	}
822 
823 	return 0;
824 }
825 
826 struct symbol *elf_create_symbol(struct elf *elf, const char *name,
827 				 struct section *sec, unsigned int bind,
828 				 unsigned int type, unsigned long offset,
829 				 size_t size)
830 {
831 	struct section *symtab, *symtab_shndx;
832 	Elf32_Word first_non_local, new_idx;
833 	struct symbol *old, *sym;
834 
835 	sym = calloc(1, sizeof(*sym));
836 	if (!sym) {
837 		ERROR_GLIBC("calloc");
838 		return NULL;
839 	}
840 
841 	sym->name = strdup(name);
842 	if (!sym->name) {
843 		ERROR_GLIBC("strdup");
844 		return NULL;
845 	}
846 
847 	if (type != STT_SECTION) {
848 		sym->sym.st_name = elf_add_string(elf, NULL, sym->name);
849 		if (sym->sym.st_name == -1)
850 			return NULL;
851 	}
852 
853 	if (sec) {
854 		sym->sec = sec;
855 	} else {
856 		sym->sec = find_section_by_index(elf, 0);
857 		if (!sym->sec) {
858 			ERROR("no NULL section");
859 			return NULL;
860 		}
861 	}
862 
863 	sym->sym.st_info  = GELF_ST_INFO(bind, type);
864 	sym->sym.st_value = offset;
865 	sym->sym.st_size  = size;
866 
867 	symtab = find_section_by_name(elf, ".symtab");
868 	if (!symtab) {
869 		ERROR("no .symtab");
870 		return NULL;
871 	}
872 
873 	symtab_shndx = find_section_by_name(elf, ".symtab_shndx");
874 
875 	new_idx = sec_num_entries(symtab);
876 
877 	if (bind != STB_LOCAL)
878 		goto non_local;
879 
880 	/*
881 	 * Move the first global symbol, as per sh_info, into a new, higher
882 	 * symbol index. This frees up a spot for a new local symbol.
883 	 */
884 	first_non_local = symtab->sh.sh_info;
885 	old = find_symbol_by_index(elf, first_non_local);
886 	if (old) {
887 
888 		elf_hash_del(symbol, &old->hash, old->idx);
889 		elf_hash_add(symbol, &old->hash, new_idx);
890 		old->idx = new_idx;
891 
892 		if (elf_update_symbol(elf, symtab, symtab_shndx, old)) {
893 			ERROR("elf_update_symbol move");
894 			return NULL;
895 		}
896 
897 		if (elf_update_sym_relocs(elf, old))
898 			return NULL;
899 
900 		if (old->group_sec) {
901 			old->group_sec->sh.sh_info = new_idx;
902 			mark_sec_changed(elf, old->group_sec, true);
903 		}
904 
905 		new_idx = first_non_local;
906 	}
907 
908 	/*
909 	 * Either way, we will add a LOCAL symbol.
910 	 */
911 	symtab->sh.sh_info += 1;
912 
913 non_local:
914 	sym->idx = new_idx;
915 	if (sym->idx && elf_update_symbol(elf, symtab, symtab_shndx, sym))
916 		return NULL;
917 
918 	symtab->sh.sh_size += symtab->sh.sh_entsize;
919 	mark_sec_changed(elf, symtab, true);
920 
921 	if (symtab_shndx) {
922 		symtab_shndx->sh.sh_size += sizeof(Elf32_Word);
923 		mark_sec_changed(elf, symtab_shndx, true);
924 	}
925 
926 	if (elf_add_symbol(elf, sym))
927 		return NULL;
928 
929 	return sym;
930 }
931 
932 struct symbol *elf_create_section_symbol(struct elf *elf, struct section *sec)
933 {
934 	struct symbol *sym = calloc(1, sizeof(*sym));
935 
936 	sym = elf_create_symbol(elf, sec->name, sec, STB_LOCAL, STT_SECTION, 0, 0);
937 	if (!sym)
938 		return NULL;
939 
940 	sec->sym = sym;
941 
942 	return sym;
943 }
944 
945 struct reloc *elf_init_reloc(struct elf *elf, struct section *rsec,
946 			     unsigned int reloc_idx, unsigned long offset,
947 			     struct symbol *sym, s64 addend, unsigned int type)
948 {
949 	struct reloc *reloc, empty = { 0 };
950 
951 	if (reloc_idx >= sec_num_entries(rsec)) {
952 		ERROR("%s: bad reloc_idx %u for %s with %d relocs",
953 		      __func__, reloc_idx, rsec->name, sec_num_entries(rsec));
954 		return NULL;
955 	}
956 
957 	reloc = &rsec->relocs[reloc_idx];
958 
959 	if (memcmp(reloc, &empty, sizeof(empty))) {
960 		ERROR("%s: %s: reloc %d already initialized!",
961 		      __func__, rsec->name, reloc_idx);
962 		return NULL;
963 	}
964 
965 	reloc->sec = rsec;
966 	reloc->sym = sym;
967 
968 	set_reloc_offset(elf, reloc, offset);
969 	set_reloc_sym(elf, reloc, sym->idx);
970 	set_reloc_type(elf, reloc, type);
971 	set_reloc_addend(elf, reloc, addend);
972 
973 	elf_hash_add(reloc, &reloc->hash, reloc_hash(reloc));
974 	set_sym_next_reloc(reloc, sym->relocs);
975 	sym->relocs = reloc;
976 
977 	return reloc;
978 }
979 
980 struct reloc *elf_init_reloc_text_sym(struct elf *elf, struct section *sec,
981 				      unsigned long offset,
982 				      unsigned int reloc_idx,
983 				      struct section *insn_sec,
984 				      unsigned long insn_off)
985 {
986 	struct symbol *sym = insn_sec->sym;
987 	s64 addend = insn_off;
988 
989 	if (!is_text_sec(insn_sec)) {
990 		ERROR("bad call to %s() for data symbol %s", __func__, sym->name);
991 		return NULL;
992 	}
993 
994 	if (!sym) {
995 		/*
996 		 * Due to how weak functions work, we must use section based
997 		 * relocations. Symbol based relocations would result in the
998 		 * weak and non-weak function annotations being overlaid on the
999 		 * non-weak function after linking.
1000 		 */
1001 		sym = elf_create_section_symbol(elf, insn_sec);
1002 		if (!sym)
1003 			return NULL;
1004 	}
1005 
1006 	return elf_init_reloc(elf, sec->rsec, reloc_idx, offset, sym, addend,
1007 			      elf_text_rela_type(elf));
1008 }
1009 
1010 struct reloc *elf_init_reloc_data_sym(struct elf *elf, struct section *sec,
1011 				      unsigned long offset,
1012 				      unsigned int reloc_idx,
1013 				      struct symbol *sym,
1014 				      s64 addend)
1015 {
1016 	if (is_text_sec(sec)) {
1017 		ERROR("bad call to %s() for text symbol %s", __func__, sym->name);
1018 		return NULL;
1019 	}
1020 
1021 	return elf_init_reloc(elf, sec->rsec, reloc_idx, offset, sym, addend,
1022 			      elf_data_rela_type(elf));
1023 }
1024 
1025 static int read_relocs(struct elf *elf)
1026 {
1027 	unsigned long nr_reloc, max_reloc = 0;
1028 	struct section *rsec;
1029 	struct reloc *reloc;
1030 	unsigned int symndx;
1031 	struct symbol *sym;
1032 	int i;
1033 
1034 	if (!elf_alloc_hash(reloc, elf->num_relocs))
1035 		return -1;
1036 
1037 	list_for_each_entry(rsec, &elf->sections, list) {
1038 		if (!is_reloc_sec(rsec))
1039 			continue;
1040 
1041 		rsec->base = find_section_by_index(elf, rsec->sh.sh_info);
1042 		if (!rsec->base) {
1043 			ERROR("can't find base section for reloc section %s", rsec->name);
1044 			return -1;
1045 		}
1046 
1047 		rsec->base->rsec = rsec;
1048 
1049 		/* nr_alloc_relocs=0: libelf owns d_buf */
1050 		rsec->nr_alloc_relocs = 0;
1051 
1052 		rsec->relocs = calloc(sec_num_entries(rsec), sizeof(*reloc));
1053 		if (!rsec->relocs) {
1054 			ERROR_GLIBC("calloc");
1055 			return -1;
1056 		}
1057 
1058 		nr_reloc = 0;
1059 		for (i = 0; i < sec_num_entries(rsec); i++) {
1060 			reloc = &rsec->relocs[i];
1061 
1062 			reloc->sec = rsec;
1063 			symndx = reloc_sym(reloc);
1064 			reloc->sym = sym = find_symbol_by_index(elf, symndx);
1065 			if (!reloc->sym) {
1066 				ERROR("can't find reloc entry symbol %d for %s", symndx, rsec->name);
1067 				return -1;
1068 			}
1069 
1070 			elf_hash_add(reloc, &reloc->hash, reloc_hash(reloc));
1071 			set_sym_next_reloc(reloc, sym->relocs);
1072 			sym->relocs = reloc;
1073 
1074 			nr_reloc++;
1075 		}
1076 		max_reloc = max(max_reloc, nr_reloc);
1077 	}
1078 
1079 	if (opts.stats) {
1080 		printf("max_reloc: %lu\n", max_reloc);
1081 		printf("num_relocs: %lu\n", elf->num_relocs);
1082 		printf("reloc_bits: %d\n", elf->reloc_bits);
1083 	}
1084 
1085 	return 0;
1086 }
1087 
1088 struct elf *elf_open_read(const char *name, int flags)
1089 {
1090 	struct elf *elf;
1091 	Elf_Cmd cmd;
1092 
1093 	elf_version(EV_CURRENT);
1094 
1095 	elf = malloc(sizeof(*elf));
1096 	if (!elf) {
1097 		ERROR_GLIBC("malloc");
1098 		return NULL;
1099 	}
1100 	memset(elf, 0, sizeof(*elf));
1101 
1102 	INIT_LIST_HEAD(&elf->sections);
1103 
1104 	elf->fd = open(name, flags);
1105 	if (elf->fd == -1) {
1106 		fprintf(stderr, "objtool: Can't open '%s': %s\n",
1107 			name, strerror(errno));
1108 		goto err;
1109 	}
1110 
1111 	elf->name = strdup(name);
1112 	if (!elf->name) {
1113 		ERROR_GLIBC("strdup");
1114 		return NULL;
1115 	}
1116 
1117 	if ((flags & O_ACCMODE) == O_RDONLY)
1118 		cmd = ELF_C_READ_MMAP;
1119 	else if ((flags & O_ACCMODE) == O_RDWR)
1120 		cmd = ELF_C_RDWR;
1121 	else /* O_WRONLY */
1122 		cmd = ELF_C_WRITE;
1123 
1124 	elf->elf = elf_begin(elf->fd, cmd, NULL);
1125 	if (!elf->elf) {
1126 		ERROR_ELF("elf_begin");
1127 		goto err;
1128 	}
1129 
1130 	if (!gelf_getehdr(elf->elf, &elf->ehdr)) {
1131 		ERROR_ELF("gelf_getehdr");
1132 		goto err;
1133 	}
1134 
1135 	if (read_sections(elf))
1136 		goto err;
1137 
1138 	if (read_symbols(elf))
1139 		goto err;
1140 
1141 	if (mark_group_syms(elf))
1142 		goto err;
1143 
1144 	if (read_relocs(elf))
1145 		goto err;
1146 
1147 	return elf;
1148 
1149 err:
1150 	elf_close(elf);
1151 	return NULL;
1152 }
1153 
1154 struct elf *elf_create_file(GElf_Ehdr *ehdr, const char *name)
1155 {
1156 	struct section *null, *symtab, *strtab, *shstrtab;
1157 	char *dir, *base, *tmp_name;
1158 	struct symbol *sym;
1159 	struct elf *elf;
1160 
1161 	elf_version(EV_CURRENT);
1162 
1163 	elf = calloc(1, sizeof(*elf));
1164 	if (!elf) {
1165 		ERROR_GLIBC("calloc");
1166 		return NULL;
1167 	}
1168 
1169 	INIT_LIST_HEAD(&elf->sections);
1170 
1171 	dir = strdup(name);
1172 	if (!dir) {
1173 		ERROR_GLIBC("strdup");
1174 		return NULL;
1175 	}
1176 
1177 	dir = dirname(dir);
1178 
1179 	base = strdup(name);
1180 	if (!base) {
1181 		ERROR_GLIBC("strdup");
1182 		return NULL;
1183 	}
1184 
1185 	base = basename(base);
1186 
1187 	tmp_name = malloc(256);
1188 	if (!tmp_name) {
1189 		ERROR_GLIBC("malloc");
1190 		return NULL;
1191 	}
1192 
1193 	snprintf(tmp_name, 256, "%s/%s.XXXXXX", dir, base);
1194 
1195 	elf->fd = mkstemp(tmp_name);
1196 	if (elf->fd == -1) {
1197 		ERROR_GLIBC("can't create tmp file");
1198 		exit(1);
1199 	}
1200 
1201 	elf->tmp_name = tmp_name;
1202 
1203 	elf->name = strdup(name);
1204 	if (!elf->name) {
1205 		ERROR_GLIBC("strdup");
1206 		return NULL;
1207 	}
1208 
1209 	elf->elf = elf_begin(elf->fd, ELF_C_WRITE, NULL);
1210 	if (!elf->elf) {
1211 		ERROR_ELF("elf_begin");
1212 		return NULL;
1213 	}
1214 
1215 	if (!gelf_newehdr(elf->elf, ELFCLASS64)) {
1216 		ERROR_ELF("gelf_newehdr");
1217 		return NULL;
1218 	}
1219 
1220 	memcpy(&elf->ehdr, ehdr, sizeof(elf->ehdr));
1221 
1222 	if (!gelf_update_ehdr(elf->elf, &elf->ehdr)) {
1223 		ERROR_ELF("gelf_update_ehdr");
1224 		return NULL;
1225 	}
1226 
1227 	INIT_LIST_HEAD(&elf->symbols);
1228 
1229 	if (!elf_alloc_hash(section,		1000) ||
1230 	    !elf_alloc_hash(section_name,	1000) ||
1231 	    !elf_alloc_hash(symbol,		10000) ||
1232 	    !elf_alloc_hash(symbol_name,	10000) ||
1233 	    !elf_alloc_hash(reloc,		100000))
1234 		return NULL;
1235 
1236 	null		= elf_create_section(elf, NULL, 0, 0, SHT_NULL, 0, 0);
1237 	shstrtab	= elf_create_section(elf, NULL, 0, 0, SHT_STRTAB, 1, 0);
1238 	strtab		= elf_create_section(elf, NULL, 0, 0, SHT_STRTAB, 1, 0);
1239 
1240 	if (!null || !shstrtab || !strtab)
1241 		return NULL;
1242 
1243 	null->name	= "";
1244 	shstrtab->name	= ".shstrtab";
1245 	strtab->name	= ".strtab";
1246 
1247 	null->sh.sh_name	= elf_add_string(elf, shstrtab, null->name);
1248 	shstrtab->sh.sh_name	= elf_add_string(elf, shstrtab, shstrtab->name);
1249 	strtab->sh.sh_name	= elf_add_string(elf, shstrtab, strtab->name);
1250 
1251 	if (null->sh.sh_name == -1 || shstrtab->sh.sh_name == -1 || strtab->sh.sh_name == -1)
1252 		return NULL;
1253 
1254 	elf_hash_add(section_name, &null->name_hash,		str_hash(null->name));
1255 	elf_hash_add(section_name, &strtab->name_hash,		str_hash(strtab->name));
1256 	elf_hash_add(section_name, &shstrtab->name_hash,	str_hash(shstrtab->name));
1257 
1258 	if (elf_add_string(elf, strtab, "") == -1)
1259 		return NULL;
1260 
1261 	symtab = elf_create_section(elf, ".symtab", 0x18, 0x18, SHT_SYMTAB, 0x8, 0);
1262 	if (!symtab)
1263 		return NULL;
1264 
1265 	symtab->sh.sh_link = strtab->idx;
1266 	symtab->sh.sh_info = 1;
1267 
1268 	elf->ehdr.e_shstrndx = shstrtab->idx;
1269 	if (!gelf_update_ehdr(elf->elf, &elf->ehdr)) {
1270 		ERROR_ELF("gelf_update_ehdr");
1271 		return NULL;
1272 	}
1273 
1274 	sym = calloc(1, sizeof(*sym));
1275 	if (!sym) {
1276 		ERROR_GLIBC("calloc");
1277 		return NULL;
1278 	}
1279 
1280 	sym->name = "";
1281 	sym->sec = null;
1282 	elf_add_symbol(elf, sym);
1283 
1284 	return elf;
1285 }
1286 
1287 unsigned int elf_add_string(struct elf *elf, struct section *strtab, const char *str)
1288 {
1289 	unsigned int offset;
1290 
1291 	if (!strtab)
1292 		strtab = find_section_by_name(elf, ".strtab");
1293 	if (!strtab) {
1294 		ERROR("can't find .strtab section");
1295 		return -1;
1296 	}
1297 
1298 	if (!strtab->sh.sh_addralign) {
1299 		ERROR("'%s': invalid sh_addralign", strtab->name);
1300 		return -1;
1301 	}
1302 
1303 	offset = ALIGN_UP(strtab->sh.sh_size, strtab->sh.sh_addralign);
1304 
1305 	if (!elf_add_data(elf, strtab, str, strlen(str) + 1))
1306 		return -1;
1307 
1308 	return offset;
1309 }
1310 
1311 void *elf_add_data(struct elf *elf, struct section *sec, const void *data, size_t size)
1312 {
1313 	unsigned long offset;
1314 	Elf_Scn *s;
1315 
1316 	if (!sec->sh.sh_addralign) {
1317 		ERROR("'%s': invalid sh_addralign", sec->name);
1318 		return NULL;
1319 	}
1320 
1321 	s = elf_getscn(elf->elf, sec->idx);
1322 	if (!s) {
1323 		ERROR_ELF("elf_getscn");
1324 		return NULL;
1325 	}
1326 
1327 	sec->data = elf_newdata(s);
1328 	if (!sec->data) {
1329 		ERROR_ELF("elf_newdata");
1330 		return NULL;
1331 	}
1332 
1333 	sec->data->d_buf = calloc(1, size);
1334 	if (!sec->data->d_buf) {
1335 		ERROR_GLIBC("calloc");
1336 		return NULL;
1337 	}
1338 
1339 	if (data)
1340 		memcpy(sec->data->d_buf, data, size);
1341 
1342 	sec->data->d_size = size;
1343 	sec->data->d_align = 1;
1344 
1345 	offset = ALIGN_UP(sec->sh.sh_size, sec->sh.sh_addralign);
1346 	sec->sh.sh_size = offset + size;
1347 
1348 	mark_sec_changed(elf, sec, true);
1349 
1350 	return sec->data->d_buf;
1351 }
1352 
1353 struct section *elf_create_section(struct elf *elf, const char *name,
1354 				   size_t size, size_t entsize,
1355 				   unsigned int type, unsigned int align,
1356 				   unsigned int flags)
1357 {
1358 	struct section *sec, *shstrtab;
1359 	Elf_Scn *s;
1360 
1361 	if (name && find_section_by_name(elf, name)) {
1362 		ERROR("section '%s' already exists", name);
1363 		return NULL;
1364 	}
1365 
1366 	sec = calloc(1, sizeof(*sec));
1367 	if (!sec) {
1368 		ERROR_GLIBC("calloc");
1369 		return NULL;
1370 	}
1371 
1372 	INIT_LIST_HEAD(&sec->symbol_list);
1373 
1374 	/* don't actually create the section, just the data structures */
1375 	if (type == SHT_NULL)
1376 		goto add;
1377 
1378 	s = elf_newscn(elf->elf);
1379 	if (!s) {
1380 		ERROR_ELF("elf_newscn");
1381 		return NULL;
1382 	}
1383 
1384 	sec->idx = elf_ndxscn(s);
1385 
1386 	if (size) {
1387 		sec->data = elf_newdata(s);
1388 		if (!sec->data) {
1389 			ERROR_ELF("elf_newdata");
1390 			return NULL;
1391 		}
1392 
1393 		sec->data->d_size = size;
1394 		sec->data->d_align = 1;
1395 
1396 		sec->data->d_buf = calloc(1, size);
1397 		if (!sec->data->d_buf) {
1398 			ERROR_GLIBC("calloc");
1399 			return NULL;
1400 		}
1401 	}
1402 
1403 	if (!gelf_getshdr(s, &sec->sh)) {
1404 		ERROR_ELF("gelf_getshdr");
1405 		return NULL;
1406 	}
1407 
1408 	sec->sh.sh_size = size;
1409 	sec->sh.sh_entsize = entsize;
1410 	sec->sh.sh_type = type;
1411 	sec->sh.sh_addralign = align;
1412 	sec->sh.sh_flags = flags;
1413 
1414 	if (name) {
1415 		sec->name = strdup(name);
1416 		if (!sec->name) {
1417 			ERROR("strdup");
1418 			return NULL;
1419 		}
1420 
1421 		/* Add section name to .shstrtab (or .strtab for Clang) */
1422 		shstrtab = find_section_by_name(elf, ".shstrtab");
1423 		if (!shstrtab) {
1424 			shstrtab = find_section_by_name(elf, ".strtab");
1425 			if (!shstrtab) {
1426 				ERROR("can't find .shstrtab or .strtab");
1427 				return NULL;
1428 			}
1429 		}
1430 		sec->sh.sh_name = elf_add_string(elf, shstrtab, sec->name);
1431 		if (sec->sh.sh_name == -1)
1432 			return NULL;
1433 
1434 		elf_hash_add(section_name, &sec->name_hash, str_hash(sec->name));
1435 	}
1436 
1437 add:
1438 	list_add_tail(&sec->list, &elf->sections);
1439 	elf_hash_add(section, &sec->hash, sec->idx);
1440 
1441 	mark_sec_changed(elf, sec, true);
1442 
1443 	return sec;
1444 }
1445 
1446 static int elf_alloc_reloc(struct elf *elf, struct section *rsec)
1447 {
1448 	struct reloc *old_relocs, *old_relocs_end, *new_relocs;
1449 	unsigned int nr_relocs_old = sec_num_entries(rsec);
1450 	unsigned int nr_relocs_new = nr_relocs_old + 1;
1451 	unsigned long nr_alloc;
1452 	struct symbol *sym;
1453 
1454 	if (!rsec->data) {
1455 		rsec->data = elf_newdata(elf_getscn(elf->elf, rsec->idx));
1456 		if (!rsec->data) {
1457 			ERROR_ELF("elf_newdata");
1458 			return -1;
1459 		}
1460 
1461 		rsec->data->d_align = 1;
1462 		rsec->data->d_type = ELF_T_RELA;
1463 		rsec->data->d_buf = NULL;
1464 	}
1465 
1466 	rsec->data->d_size = nr_relocs_new * elf_rela_size(elf);
1467 	rsec->sh.sh_size   = rsec->data->d_size;
1468 
1469 	nr_alloc = MAX(64, ALIGN_UP_POW2(nr_relocs_new));
1470 	if (nr_alloc <= rsec->nr_alloc_relocs)
1471 		return 0;
1472 
1473 	if (rsec->data->d_buf && !rsec->nr_alloc_relocs) {
1474 		void *orig_buf = rsec->data->d_buf;
1475 
1476 		/*
1477 		 * The original d_buf is owned by libelf so it can't be
1478 		 * realloced.
1479 		 */
1480 		rsec->data->d_buf = malloc(nr_alloc * elf_rela_size(elf));
1481 		if (!rsec->data->d_buf) {
1482 			ERROR_GLIBC("malloc");
1483 			return -1;
1484 		}
1485 		memcpy(rsec->data->d_buf, orig_buf,
1486 		       nr_relocs_old * elf_rela_size(elf));
1487 	} else {
1488 		rsec->data->d_buf = realloc(rsec->data->d_buf,
1489 					    nr_alloc * elf_rela_size(elf));
1490 		if (!rsec->data->d_buf) {
1491 			ERROR_GLIBC("realloc");
1492 			return -1;
1493 		}
1494 	}
1495 
1496 	rsec->nr_alloc_relocs = nr_alloc;
1497 
1498 	old_relocs = rsec->relocs;
1499 	new_relocs = calloc(nr_alloc, sizeof(struct reloc));
1500 	if (!new_relocs) {
1501 		ERROR_GLIBC("calloc");
1502 		return -1;
1503 	}
1504 
1505 	if (!old_relocs)
1506 		goto done;
1507 
1508 	/*
1509 	 * The struct reloc's address has changed.  Update all the symbols and
1510 	 * relocs which reference it.
1511 	 */
1512 
1513 	old_relocs_end = &old_relocs[nr_relocs_old];
1514 	for_each_sym(elf, sym) {
1515 		struct reloc *reloc;
1516 
1517 		reloc = sym->relocs;
1518 		if (!reloc)
1519 			continue;
1520 
1521 		if (reloc >= old_relocs && reloc < old_relocs_end)
1522 			sym->relocs = &new_relocs[reloc - old_relocs];
1523 
1524 		while (1) {
1525 			struct reloc *next_reloc = sym_next_reloc(reloc);
1526 
1527 			if (!next_reloc)
1528 				break;
1529 
1530 			if (next_reloc >= old_relocs && next_reloc < old_relocs_end)
1531 				set_sym_next_reloc(reloc, &new_relocs[next_reloc - old_relocs]);
1532 
1533 			reloc = next_reloc;
1534 		}
1535 	}
1536 
1537 	memcpy(new_relocs, old_relocs, nr_relocs_old * sizeof(struct reloc));
1538 
1539 	for (int i = 0; i < nr_relocs_old; i++) {
1540 		struct reloc *old = &old_relocs[i];
1541 		struct reloc *new = &new_relocs[i];
1542 		u32 key = reloc_hash(old);
1543 
1544 		elf_hash_del(reloc, &old->hash, key);
1545 		elf_hash_add(reloc, &new->hash, key);
1546 	}
1547 
1548 	free(old_relocs);
1549 done:
1550 	rsec->relocs = new_relocs;
1551 	return 0;
1552 }
1553 
1554 struct section *elf_create_rela_section(struct elf *elf, struct section *sec,
1555 					unsigned int nr_relocs)
1556 {
1557 	struct section *rsec;
1558 	char *rsec_name;
1559 
1560 	rsec_name = malloc(strlen(sec->name) + strlen(".rela") + 1);
1561 	if (!rsec_name) {
1562 		ERROR_GLIBC("malloc");
1563 		return NULL;
1564 	}
1565 	strcpy(rsec_name, ".rela");
1566 	strcat(rsec_name, sec->name);
1567 
1568 	rsec = elf_create_section(elf, rsec_name, nr_relocs * elf_rela_size(elf),
1569 				  elf_rela_size(elf), SHT_RELA, elf_addr_size(elf),
1570 				  SHF_INFO_LINK);
1571 	free(rsec_name);
1572 	if (!rsec)
1573 		return NULL;
1574 
1575 	if (nr_relocs) {
1576 		rsec->data->d_type = ELF_T_RELA;
1577 
1578 		rsec->nr_alloc_relocs = nr_relocs;
1579 		rsec->relocs = calloc(nr_relocs, sizeof(struct reloc));
1580 		if (!rsec->relocs) {
1581 			ERROR_GLIBC("calloc");
1582 			return NULL;
1583 		}
1584 	}
1585 
1586 	rsec->sh.sh_link = find_section_by_name(elf, ".symtab")->idx;
1587 	rsec->sh.sh_info = sec->idx;
1588 
1589 	sec->rsec = rsec;
1590 	rsec->base = sec;
1591 
1592 	return rsec;
1593 }
1594 
1595 struct reloc *elf_create_reloc(struct elf *elf, struct section *sec,
1596 			       unsigned long offset,
1597 			       struct symbol *sym, s64 addend,
1598 			       unsigned int type)
1599 {
1600 	struct section *rsec = sec->rsec;
1601 
1602 	if (!rsec) {
1603 		rsec = elf_create_rela_section(elf, sec, 0);
1604 		if (!rsec)
1605 			return NULL;
1606 	}
1607 
1608 	if (find_reloc_by_dest(elf, sec, offset)) {
1609 		ERROR_FUNC(sec, offset, "duplicate reloc");
1610 		return NULL;
1611 	}
1612 
1613 	if (elf_alloc_reloc(elf, rsec))
1614 		return NULL;
1615 
1616 	mark_sec_changed(elf, rsec, true);
1617 
1618 	return elf_init_reloc(elf, rsec, sec_num_entries(rsec) - 1, offset, sym,
1619 			      addend, type);
1620 }
1621 
1622 struct section *elf_create_section_pair(struct elf *elf, const char *name,
1623 					size_t entsize, unsigned int nr,
1624 					unsigned int nr_relocs)
1625 {
1626 	struct section *sec;
1627 
1628 	sec = elf_create_section(elf, name, nr * entsize, entsize,
1629 				 SHT_PROGBITS, 1, SHF_ALLOC);
1630 	if (!sec)
1631 		return NULL;
1632 
1633 	if (!elf_create_rela_section(elf, sec, nr_relocs))
1634 		return NULL;
1635 
1636 	return sec;
1637 }
1638 
1639 int elf_write_insn(struct elf *elf, struct section *sec,
1640 		   unsigned long offset, unsigned int len,
1641 		   const char *insn)
1642 {
1643 	Elf_Data *data = sec->data;
1644 
1645 	if (data->d_type != ELF_T_BYTE || data->d_off) {
1646 		ERROR("write to unexpected data for section: %s", sec->name);
1647 		return -1;
1648 	}
1649 
1650 	memcpy(data->d_buf + offset, insn, len);
1651 
1652 	mark_sec_changed(elf, sec, true);
1653 
1654 	return 0;
1655 }
1656 
1657 /*
1658  * When Elf_Scn::sh_size is smaller than the combined Elf_Data::d_size
1659  * do you:
1660  *
1661  *   A) adhere to the section header and truncate the data, or
1662  *   B) ignore the section header and write out all the data you've got?
1663  *
1664  * Yes, libelf sucks and we need to manually truncate if we over-allocate data.
1665  */
1666 static int elf_truncate_section(struct elf *elf, struct section *sec)
1667 {
1668 	u64 size = sec_size(sec);
1669 	bool truncated = false;
1670 	Elf_Data *data = NULL;
1671 	Elf_Scn *s;
1672 
1673 	s = elf_getscn(elf->elf, sec->idx);
1674 	if (!s) {
1675 		ERROR_ELF("elf_getscn");
1676 		return -1;
1677 	}
1678 
1679 	for (;;) {
1680 		/* get next data descriptor for the relevant section */
1681 		data = elf_getdata(s, data);
1682 		if (!data) {
1683 			if (size) {
1684 				ERROR("end of section data but non-zero size left\n");
1685 				return -1;
1686 			}
1687 			return 0;
1688 		}
1689 
1690 		if (truncated) {
1691 			/* when we remove symbols */
1692 			ERROR("truncated; but more data\n");
1693 			return -1;
1694 		}
1695 
1696 		if (!data->d_size) {
1697 			ERROR("zero size data");
1698 			return -1;
1699 		}
1700 
1701 		if (data->d_size > size) {
1702 			truncated = true;
1703 			data->d_size = size;
1704 		}
1705 
1706 		size -= data->d_size;
1707 	}
1708 }
1709 
1710 int elf_write(struct elf *elf)
1711 {
1712 	struct section *sec;
1713 	Elf_Scn *s;
1714 
1715 	/* Update changed relocation sections and section headers: */
1716 	list_for_each_entry(sec, &elf->sections, list) {
1717 		if (sec->truncate && elf_truncate_section(elf, sec))
1718 			return -1;
1719 
1720 		if (sec_changed(sec)) {
1721 			s = elf_getscn(elf->elf, sec->idx);
1722 			if (!s) {
1723 				ERROR_ELF("elf_getscn");
1724 				return -1;
1725 			}
1726 
1727 			/* Note this also flags the section dirty */
1728 			if (!gelf_update_shdr(s, &sec->sh)) {
1729 				ERROR_ELF("gelf_update_shdr");
1730 				return -1;
1731 			}
1732 
1733 			mark_sec_changed(elf, sec, false);
1734 		}
1735 	}
1736 
1737 	/* Make sure the new section header entries get updated properly. */
1738 	elf_flagelf(elf->elf, ELF_C_SET, ELF_F_DIRTY);
1739 
1740 	/* Write all changes to the file. */
1741 	if (elf_update(elf->elf, ELF_C_WRITE) < 0) {
1742 		ERROR_ELF("elf_update");
1743 		return -1;
1744 	}
1745 
1746 	elf->changed = false;
1747 
1748 	return 0;
1749 }
1750 
1751 int elf_close(struct elf *elf)
1752 {
1753 	if (elf->elf)
1754 		elf_end(elf->elf);
1755 
1756 	if (elf->fd > 0)
1757 		close(elf->fd);
1758 
1759 	if (elf->tmp_name && rename(elf->tmp_name, elf->name))
1760 		return -1;
1761 
1762 	/*
1763 	 * NOTE: All remaining allocations are leaked on purpose.  Objtool is
1764 	 * about to exit anyway.
1765 	 */
1766 	return 0;
1767 }
1768