elf.c 14.6 KB
Newer Older
1
// SPDX-License-Identifier: GPL-2.0-or-later
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
/*
 * elf.c - ELF access library
 *
 * Adapted from kpatch (https://github.com/dynup/kpatch):
 * Copyright (C) 2013-2015 Josh Poimboeuf <jpoimboe@redhat.com>
 * Copyright (C) 2014 Seth Jennings <sjenning@redhat.com>
 */

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
17
#include <errno.h>
P
Peter Zijlstra 已提交
18
#include "builtin.h"
19 20 21 22

#include "elf.h"
#include "warn.h"

23 24
#define MAX_NAME_LEN 128

25 26 27 28 29
static inline u32 str_hash(const char *str)
{
	return jhash(str, strlen(str), 0);
}

30 31 32 33
struct section *find_section_by_name(struct elf *elf, const char *name)
{
	struct section *sec;

34
	hash_for_each_possible(elf->section_name_hash, sec, name_hash, str_hash(name))
35 36 37 38 39 40 41 42 43 44 45
		if (!strcmp(sec->name, name))
			return sec;

	return NULL;
}

static struct section *find_section_by_index(struct elf *elf,
					     unsigned int idx)
{
	struct section *sec;

46
	hash_for_each_possible(elf->section_hash, sec, hash, idx)
47 48 49 50 51 52 53 54 55 56
		if (sec->idx == idx)
			return sec;

	return NULL;
}

static struct symbol *find_symbol_by_index(struct elf *elf, unsigned int idx)
{
	struct symbol *sym;

57 58 59
	hash_for_each_possible(elf->symbol_hash, sym, hash, idx)
		if (sym->idx == idx)
			return sym;
60 61 62 63 64 65 66 67

	return NULL;
}

struct symbol *find_symbol_by_offset(struct section *sec, unsigned long offset)
{
	struct symbol *sym;

68
	list_for_each_entry(sym, &sec->symbol_list, list)
69 70 71 72 73 74 75 76 77 78 79 80
		if (sym->type != STT_SECTION && sym->offset == offset)
			return sym;

	return NULL;
}

struct symbol *find_func_by_offset(struct section *sec, unsigned long offset)
{
	struct symbol *sym;

	list_for_each_entry(sym, &sec->symbol_list, list)
		if (sym->type == STT_FUNC && sym->offset == offset)
81 82 83 84 85
			return sym;

	return NULL;
}

86 87 88 89 90 91 92 93 94 95 96 97 98
struct symbol *find_symbol_by_name(struct elf *elf, const char *name)
{
	struct section *sec;
	struct symbol *sym;

	list_for_each_entry(sec, &elf->sections, list)
		list_for_each_entry(sym, &sec->symbol_list, list)
			if (!strcmp(sym->name, name))
				return sym;

	return NULL;
}

99 100 101 102 103 104 105 106 107 108 109 110
struct symbol *find_symbol_containing(struct section *sec, unsigned long offset)
{
	struct symbol *sym;

	list_for_each_entry(sym, &sec->symbol_list, list)
		if (sym->type != STT_SECTION &&
		    offset >= sym->offset && offset < sym->offset + sym->len)
			return sym;

	return NULL;
}

111 112 113 114
struct rela *find_rela_by_dest_range(struct section *sec, unsigned long offset,
				     unsigned int len)
{
	struct rela *rela;
115
	unsigned long o;
116 117 118 119

	if (!sec->rela)
		return NULL;

120 121 122 123
	for (o = offset; o < offset + len; o++)
		hash_for_each_possible(sec->rela->rela_hash, rela, hash, o)
			if (rela->offset == o)
				return rela;
124 125 126 127 128 129 130 131 132 133 134 135 136

	return NULL;
}

struct rela *find_rela_by_dest(struct section *sec, unsigned long offset)
{
	return find_rela_by_dest_range(sec, offset, 1);
}

struct symbol *find_containing_func(struct section *sec, unsigned long offset)
{
	struct symbol *func;

137
	list_for_each_entry(func, &sec->symbol_list, list)
138 139 140 141 142 143 144 145 146 147 148 149 150 151 152
		if (func->type == STT_FUNC && offset >= func->offset &&
		    offset < func->offset + func->len)
			return func;

	return NULL;
}

static int read_sections(struct elf *elf)
{
	Elf_Scn *s = NULL;
	struct section *sec;
	size_t shstrndx, sections_nr;
	int i;

	if (elf_getshdrnum(elf->elf, &sections_nr)) {
153
		WARN_ELF("elf_getshdrnum");
154 155 156 157
		return -1;
	}

	if (elf_getshdrstrndx(elf->elf, &shstrndx)) {
158
		WARN_ELF("elf_getshdrstrndx");
159 160 161 162 163 164 165 166 167 168 169
		return -1;
	}

	for (i = 0; i < sections_nr; i++) {
		sec = malloc(sizeof(*sec));
		if (!sec) {
			perror("malloc");
			return -1;
		}
		memset(sec, 0, sizeof(*sec));

170 171
		INIT_LIST_HEAD(&sec->symbol_list);
		INIT_LIST_HEAD(&sec->rela_list);
172
		hash_init(sec->rela_hash);
173 174 175

		s = elf_getscn(elf->elf, i);
		if (!s) {
176
			WARN_ELF("elf_getscn");
177 178 179 180 181 182
			return -1;
		}

		sec->idx = elf_ndxscn(s);

		if (!gelf_getshdr(s, &sec->sh)) {
183
			WARN_ELF("gelf_getshdr");
184 185 186 187 188
			return -1;
		}

		sec->name = elf_strptr(elf->elf, shstrndx, sec->sh.sh_name);
		if (!sec->name) {
189
			WARN_ELF("elf_strptr");
190 191 192
			return -1;
		}

193 194 195 196 197 198 199 200 201 202 203 204
		if (sec->sh.sh_size != 0) {
			sec->data = elf_getdata(s, NULL);
			if (!sec->data) {
				WARN_ELF("elf_getdata");
				return -1;
			}
			if (sec->data->d_off != 0 ||
			    sec->data->d_size != sec->sh.sh_size) {
				WARN("unexpected data attributes for %s",
				     sec->name);
				return -1;
			}
205
		}
206
		sec->len = sec->sh.sh_size;
207 208 209

		list_add_tail(&sec->list, &elf->sections);
		hash_add(elf->section_hash, &sec->hash, sec->idx);
210
		hash_add(elf->section_name_hash, &sec->name_hash, str_hash(sec->name));
211 212
	}

P
Peter Zijlstra 已提交
213 214 215
	if (stats)
		printf("nr_sections: %lu\n", (unsigned long)sections_nr);

216 217 218 219 220 221 222 223 224 225 226
	/* sanity check, one more call to elf_nextscn() should return NULL */
	if (elf_nextscn(elf->elf, s)) {
		WARN("section entry mismatch");
		return -1;
	}

	return 0;
}

static int read_symbols(struct elf *elf)
{
227
	struct section *symtab, *sec;
228
	struct symbol *sym, *pfunc, *alias;
229 230
	struct list_head *entry, *tmp;
	int symbols_nr, i;
231
	char *coldstr;
232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247

	symtab = find_section_by_name(elf, ".symtab");
	if (!symtab) {
		WARN("missing symbol table");
		return -1;
	}

	symbols_nr = symtab->sh.sh_size / symtab->sh.sh_entsize;

	for (i = 0; i < symbols_nr; i++) {
		sym = malloc(sizeof(*sym));
		if (!sym) {
			perror("malloc");
			return -1;
		}
		memset(sym, 0, sizeof(*sym));
248
		alias = sym;
249 250 251

		sym->idx = i;

252 253
		if (!gelf_getsym(symtab->data, i, &sym->sym)) {
			WARN_ELF("gelf_getsym");
254 255 256 257 258 259
			goto err;
		}

		sym->name = elf_strptr(elf->elf, symtab->sh.sh_link,
				       sym->sym.st_name);
		if (!sym->name) {
260
			WARN_ELF("elf_strptr");
261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286
			goto err;
		}

		sym->type = GELF_ST_TYPE(sym->sym.st_info);
		sym->bind = GELF_ST_BIND(sym->sym.st_info);

		if (sym->sym.st_shndx > SHN_UNDEF &&
		    sym->sym.st_shndx < SHN_LORESERVE) {
			sym->sec = find_section_by_index(elf,
							 sym->sym.st_shndx);
			if (!sym->sec) {
				WARN("couldn't find section for symbol %s",
				     sym->name);
				goto err;
			}
			if (sym->type == STT_SECTION) {
				sym->name = sym->sec->name;
				sym->sec->sym = sym;
			}
		} else
			sym->sec = find_section_by_index(elf, 0);

		sym->offset = sym->sym.st_value;
		sym->len = sym->sym.st_size;

		/* sorted insert into a per-section list */
287 288
		entry = &sym->sec->symbol_list;
		list_for_each_prev(tmp, &sym->sec->symbol_list) {
289 290 291 292 293 294 295 296 297
			struct symbol *s;

			s = list_entry(tmp, struct symbol, list);

			if (sym->offset > s->offset) {
				entry = tmp;
				break;
			}

298
			if (sym->offset == s->offset) {
299
				if (sym->len && sym->len == s->len && alias == sym)
300 301 302 303 304 305
					alias = s;

				if (sym->len >= s->len) {
					entry = tmp;
					break;
				}
306 307
			}
		}
308
		sym->alias = alias;
309
		list_add(&sym->list, entry);
310
		hash_add(elf->symbol_hash, &sym->hash, sym->idx);
311 312
	}

P
Peter Zijlstra 已提交
313 314 315
	if (stats)
		printf("nr_symbols: %lu\n", (unsigned long)symbols_nr);

316 317 318
	/* Create parent/child links for any cold subfunctions */
	list_for_each_entry(sec, &elf->sections, list) {
		list_for_each_entry(sym, &sec->symbol_list, list) {
319 320
			char pname[MAX_NAME_LEN + 1];
			size_t pnamelen;
321 322 323
			if (sym->type != STT_FUNC)
				continue;
			sym->pfunc = sym->cfunc = sym;
324
			coldstr = strstr(sym->name, ".cold");
325 326 327
			if (!coldstr)
				continue;

328 329 330 331 332 333 334 335 336 337
			pnamelen = coldstr - sym->name;
			if (pnamelen > MAX_NAME_LEN) {
				WARN("%s(): parent function name exceeds maximum length of %d characters",
				     sym->name, MAX_NAME_LEN);
				return -1;
			}

			strncpy(pname, sym->name, pnamelen);
			pname[pnamelen] = '\0';
			pfunc = find_symbol_by_name(elf, pname);
338 339 340 341

			if (!pfunc) {
				WARN("%s(): can't find parent function",
				     sym->name);
342
				return -1;
343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359
			}

			sym->pfunc = pfunc;
			pfunc->cfunc = sym;

			/*
			 * Unfortunately, -fnoreorder-functions puts the child
			 * inside the parent.  Remove the overlap so we can
			 * have sane assumptions.
			 *
			 * Note that pfunc->len now no longer matches
			 * pfunc->sym.st_size.
			 */
			if (sym->sec == pfunc->sec &&
			    sym->offset >= pfunc->offset &&
			    sym->offset + sym->len == pfunc->offset + pfunc->len) {
				pfunc->len -= sym->len;
360 361 362 363
			}
		}
	}

364 365 366 367 368 369 370 371 372 373 374 375 376
	return 0;

err:
	free(sym);
	return -1;
}

static int read_relas(struct elf *elf)
{
	struct section *sec;
	struct rela *rela;
	int i;
	unsigned int symndx;
P
Peter Zijlstra 已提交
377
	unsigned long nr_rela, max_rela = 0, tot_rela = 0;
378 379 380 381 382 383 384 385 386 387 388 389 390 391

	list_for_each_entry(sec, &elf->sections, list) {
		if (sec->sh.sh_type != SHT_RELA)
			continue;

		sec->base = find_section_by_name(elf, sec->name + 5);
		if (!sec->base) {
			WARN("can't find base section for rela section %s",
			     sec->name);
			return -1;
		}

		sec->base->rela = sec;

P
Peter Zijlstra 已提交
392
		nr_rela = 0;
393 394 395 396 397 398 399 400
		for (i = 0; i < sec->sh.sh_size / sec->sh.sh_entsize; i++) {
			rela = malloc(sizeof(*rela));
			if (!rela) {
				perror("malloc");
				return -1;
			}
			memset(rela, 0, sizeof(*rela));

401 402
			if (!gelf_getrela(sec->data, i, &rela->rela)) {
				WARN_ELF("gelf_getrela");
403 404 405 406 407 408 409 410
				return -1;
			}

			rela->type = GELF_R_TYPE(rela->rela.r_info);
			rela->addend = rela->rela.r_addend;
			rela->offset = rela->rela.r_offset;
			symndx = GELF_R_SYM(rela->rela.r_info);
			rela->sym = find_symbol_by_index(elf, symndx);
411
			rela->sec = sec;
412 413 414 415 416
			if (!rela->sym) {
				WARN("can't find rela entry symbol %d for %s",
				     symndx, sec->name);
				return -1;
			}
417 418 419

			list_add_tail(&rela->list, &sec->rela_list);
			hash_add(sec->rela_hash, &rela->hash, rela->offset);
P
Peter Zijlstra 已提交
420
			nr_rela++;
421
		}
P
Peter Zijlstra 已提交
422 423 424 425 426 427 428
		max_rela = max(max_rela, nr_rela);
		tot_rela += nr_rela;
	}

	if (stats) {
		printf("max_rela: %lu\n", max_rela);
		printf("tot_rela: %lu\n", tot_rela);
429 430 431 432 433
	}

	return 0;
}

434
struct elf *elf_read(const char *name, int flags)
435 436
{
	struct elf *elf;
437
	Elf_Cmd cmd;
438 439 440 441 442 443 444 445 446 447

	elf_version(EV_CURRENT);

	elf = malloc(sizeof(*elf));
	if (!elf) {
		perror("malloc");
		return NULL;
	}
	memset(elf, 0, sizeof(*elf));

448
	hash_init(elf->symbol_hash);
449
	hash_init(elf->section_hash);
450
	hash_init(elf->section_name_hash);
451 452
	INIT_LIST_HEAD(&elf->sections);

453
	elf->fd = open(name, flags);
454
	if (elf->fd == -1) {
455 456
		fprintf(stderr, "objtool: Can't open '%s': %s\n",
			name, strerror(errno));
457 458 459
		goto err;
	}

460 461 462 463 464 465 466 467
	if ((flags & O_ACCMODE) == O_RDONLY)
		cmd = ELF_C_READ_MMAP;
	else if ((flags & O_ACCMODE) == O_RDWR)
		cmd = ELF_C_RDWR;
	else /* O_WRONLY */
		cmd = ELF_C_WRITE;

	elf->elf = elf_begin(elf->fd, cmd, NULL);
468
	if (!elf->elf) {
469
		WARN_ELF("elf_begin");
470 471 472 473
		goto err;
	}

	if (!gelf_getehdr(elf->elf, &elf->ehdr)) {
474
		WARN_ELF("gelf_getehdr");
475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493
		goto err;
	}

	if (read_sections(elf))
		goto err;

	if (read_symbols(elf))
		goto err;

	if (read_relas(elf))
		goto err;

	return elf;

err:
	elf_close(elf);
	return NULL;
}

494 495 496 497 498
struct section *elf_create_section(struct elf *elf, const char *name,
				   size_t entsize, int nr)
{
	struct section *sec, *shstrtab;
	size_t size = entsize * nr;
499
	Elf_Scn *s;
500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558
	Elf_Data *data;

	sec = malloc(sizeof(*sec));
	if (!sec) {
		perror("malloc");
		return NULL;
	}
	memset(sec, 0, sizeof(*sec));

	INIT_LIST_HEAD(&sec->symbol_list);
	INIT_LIST_HEAD(&sec->rela_list);
	hash_init(sec->rela_hash);

	s = elf_newscn(elf->elf);
	if (!s) {
		WARN_ELF("elf_newscn");
		return NULL;
	}

	sec->name = strdup(name);
	if (!sec->name) {
		perror("strdup");
		return NULL;
	}

	sec->idx = elf_ndxscn(s);
	sec->len = size;
	sec->changed = true;

	sec->data = elf_newdata(s);
	if (!sec->data) {
		WARN_ELF("elf_newdata");
		return NULL;
	}

	sec->data->d_size = size;
	sec->data->d_align = 1;

	if (size) {
		sec->data->d_buf = malloc(size);
		if (!sec->data->d_buf) {
			perror("malloc");
			return NULL;
		}
		memset(sec->data->d_buf, 0, size);
	}

	if (!gelf_getshdr(s, &sec->sh)) {
		WARN_ELF("gelf_getshdr");
		return NULL;
	}

	sec->sh.sh_size = size;
	sec->sh.sh_entsize = entsize;
	sec->sh.sh_type = SHT_PROGBITS;
	sec->sh.sh_addralign = 1;
	sec->sh.sh_flags = SHF_ALLOC;


559
	/* Add section name to .shstrtab (or .strtab for Clang) */
560
	shstrtab = find_section_by_name(elf, ".shstrtab");
561 562
	if (!shstrtab)
		shstrtab = find_section_by_name(elf, ".strtab");
563
	if (!shstrtab) {
564
		WARN("can't find .shstrtab or .strtab section");
565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588
		return NULL;
	}

	s = elf_getscn(elf->elf, shstrtab->idx);
	if (!s) {
		WARN_ELF("elf_getscn");
		return NULL;
	}

	data = elf_newdata(s);
	if (!data) {
		WARN_ELF("elf_newdata");
		return NULL;
	}

	data->d_buf = sec->name;
	data->d_size = strlen(name) + 1;
	data->d_align = 1;

	sec->sh.sh_name = shstrtab->len;

	shstrtab->len += strlen(name) + 1;
	shstrtab->changed = true;

589 590
	list_add_tail(&sec->list, &elf->sections);
	hash_add(elf->section_hash, &sec->hash, sec->idx);
591
	hash_add(elf->section_name_hash, &sec->name_hash, str_hash(sec->name));
592

593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609
	return sec;
}

struct section *elf_create_rela_section(struct elf *elf, struct section *base)
{
	char *relaname;
	struct section *sec;

	relaname = malloc(strlen(base->name) + strlen(".rela") + 1);
	if (!relaname) {
		perror("malloc");
		return NULL;
	}
	strcpy(relaname, ".rela");
	strcat(relaname, base->name);

	sec = elf_create_section(elf, relaname, sizeof(GElf_Rela), 0);
610
	free(relaname);
611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663
	if (!sec)
		return NULL;

	base->rela = sec;
	sec->base = base;

	sec->sh.sh_type = SHT_RELA;
	sec->sh.sh_addralign = 8;
	sec->sh.sh_link = find_section_by_name(elf, ".symtab")->idx;
	sec->sh.sh_info = base->idx;
	sec->sh.sh_flags = SHF_INFO_LINK;

	return sec;
}

int elf_rebuild_rela_section(struct section *sec)
{
	struct rela *rela;
	int nr, idx = 0, size;
	GElf_Rela *relas;

	nr = 0;
	list_for_each_entry(rela, &sec->rela_list, list)
		nr++;

	size = nr * sizeof(*relas);
	relas = malloc(size);
	if (!relas) {
		perror("malloc");
		return -1;
	}

	sec->data->d_buf = relas;
	sec->data->d_size = size;

	sec->sh.sh_size = size;

	idx = 0;
	list_for_each_entry(rela, &sec->rela_list, list) {
		relas[idx].r_offset = rela->offset;
		relas[idx].r_addend = rela->addend;
		relas[idx].r_info = GELF_R_INFO(rela->sym->idx, rela->type);
		idx++;
	}

	return 0;
}

int elf_write(struct elf *elf)
{
	struct section *sec;
	Elf_Scn *s;

664
	/* Update section headers for changed sections: */
665 666 667 668 669 670 671
	list_for_each_entry(sec, &elf->sections, list) {
		if (sec->changed) {
			s = elf_getscn(elf->elf, sec->idx);
			if (!s) {
				WARN_ELF("elf_getscn");
				return -1;
			}
672
			if (!gelf_update_shdr(s, &sec->sh)) {
673 674 675 676 677 678
				WARN_ELF("gelf_update_shdr");
				return -1;
			}
		}
	}

679 680 681 682
	/* Make sure the new section header entries get updated properly. */
	elf_flagelf(elf->elf, ELF_C_SET, ELF_F_DIRTY);

	/* Write all changes to the file. */
683 684 685 686 687 688 689 690
	if (elf_update(elf->elf, ELF_C_WRITE) < 0) {
		WARN_ELF("elf_update");
		return -1;
	}

	return 0;
}

691 692 693 694 695 696
void elf_close(struct elf *elf)
{
	struct section *sec, *tmpsec;
	struct symbol *sym, *tmpsym;
	struct rela *rela, *tmprela;

697 698 699 700 701 702
	if (elf->elf)
		elf_end(elf->elf);

	if (elf->fd > 0)
		close(elf->fd);

703
	list_for_each_entry_safe(sec, tmpsec, &elf->sections, list) {
704
		list_for_each_entry_safe(sym, tmpsym, &sec->symbol_list, list) {
705
			list_del(&sym->list);
706
			hash_del(&sym->hash);
707 708
			free(sym);
		}
709
		list_for_each_entry_safe(rela, tmprela, &sec->rela_list, list) {
710
			list_del(&rela->list);
711
			hash_del(&rela->hash);
712 713 714 715 716
			free(rela);
		}
		list_del(&sec->list);
		free(sec);
	}
717

718 719
	free(elf);
}