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