elf.c 25.0 KB
Newer Older
1
// SPDX-License-Identifier: GPL-2.0-or-later
2 3 4 5 6 7 8 9 10 11
/*
 * 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>
12
#include <sys/mman.h>
13 14 15 16 17
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
18
#include <errno.h>
19
#include <objtool/builtin.h>
20

21 22
#include <objtool/elf.h>
#include <objtool/warn.h>
23

24 25
#define MAX_NAME_LEN 128

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

31 32
#define __elf_table(name)	(elf->name##_hash)
#define __elf_bits(name)	(elf->name##_bits)
33

34 35
#define elf_hash_add(name, node, key) \
	hlist_add_head(node, &__elf_table(name)[hash_min(key, __elf_bits(name))])
36

37 38
#define elf_hash_for_each_possible(name, obj, member, key) \
	hlist_for_each_entry(obj, &__elf_table(name)[hash_min(key, __elf_bits(name))], member)
39

40 41 42 43 44 45 46 47 48 49 50 51
#define elf_alloc_hash(name, size) \
({ \
	__elf_bits(name) = max(10, ilog2(size)); \
	__elf_table(name) = mmap(NULL, sizeof(struct hlist_head) << __elf_bits(name), \
				 PROT_READ|PROT_WRITE, \
				 MAP_PRIVATE|MAP_ANON, -1, 0); \
	if (__elf_table(name) == (void *)-1L) { \
		WARN("mmap fail " #name); \
		__elf_table(name) = NULL; \
	} \
	__elf_table(name); \
})
52

53
static bool symbol_to_offset(struct rb_node *a, const struct rb_node *b)
54 55 56 57 58
{
	struct symbol *sa = rb_entry(a, struct symbol, node);
	struct symbol *sb = rb_entry(b, struct symbol, node);

	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 69

	sa->alias = sb;

70
	return false;
71 72 73 74 75 76 77 78 79
}

static int symbol_by_offset(const void *key, const struct rb_node *node)
{
	const struct symbol *s = rb_entry(node, struct symbol, node);
	const unsigned long *o = key;

	if (*o < s->offset)
		return -1;
80
	if (*o >= s->offset + s->len)
81 82 83 84 85
		return 1;

	return 0;
}

86
struct section *find_section_by_name(const struct elf *elf, const char *name)
87 88 89
{
	struct section *sec;

90
	elf_hash_for_each_possible(section_name, sec, name_hash, str_hash(name)) {
91 92
		if (!strcmp(sec->name, name))
			return sec;
93
	}
94 95 96 97 98 99 100 101 102

	return NULL;
}

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

103
	elf_hash_for_each_possible(section, sec, hash, idx) {
104 105
		if (sec->idx == idx)
			return sec;
106
	}
107 108 109 110 111 112 113 114

	return NULL;
}

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

115
	elf_hash_for_each_possible(symbol, sym, hash, idx) {
116 117
		if (sym->idx == idx)
			return sym;
118
	}
119 120 121 122 123 124

	return NULL;
}

struct symbol *find_symbol_by_offset(struct section *sec, unsigned long offset)
{
125
	struct rb_node *node;
126

127
	rb_for_each(node, &offset, &sec->symbol_tree, symbol_by_offset) {
128 129 130 131 132
		struct symbol *s = rb_entry(node, struct symbol, node);

		if (s->offset == offset && s->type != STT_SECTION)
			return s;
	}
133 134 135 136 137 138

	return NULL;
}

struct symbol *find_func_by_offset(struct section *sec, unsigned long offset)
{
139
	struct rb_node *node;
140

141
	rb_for_each(node, &offset, &sec->symbol_tree, symbol_by_offset) {
142 143 144 145 146
		struct symbol *s = rb_entry(node, struct symbol, node);

		if (s->offset == offset && s->type == STT_FUNC)
			return s;
	}
147 148 149 150

	return NULL;
}

151
struct symbol *find_symbol_containing(const struct section *sec, unsigned long offset)
152
{
153
	struct rb_node *node;
154

155
	rb_for_each(node, &offset, &sec->symbol_tree, symbol_by_offset) {
156 157 158 159 160
		struct symbol *s = rb_entry(node, struct symbol, node);

		if (s->type != STT_SECTION)
			return s;
	}
161 162 163 164

	return NULL;
}

165
struct symbol *find_func_containing(struct section *sec, unsigned long offset)
166 167 168
{
	struct rb_node *node;

169
	rb_for_each(node, &offset, &sec->symbol_tree, symbol_by_offset) {
170 171 172 173 174 175 176 177 178
		struct symbol *s = rb_entry(node, struct symbol, node);

		if (s->type == STT_FUNC)
			return s;
	}

	return NULL;
}

179
struct symbol *find_symbol_by_name(const struct elf *elf, const char *name)
180 181 182
{
	struct symbol *sym;

183
	elf_hash_for_each_possible(symbol_name, sym, name_hash, str_hash(name)) {
184 185
		if (!strcmp(sym->name, name))
			return sym;
186
	}
187 188 189 190

	return NULL;
}

M
Matt Helsley 已提交
191
struct reloc *find_reloc_by_dest_range(const struct elf *elf, struct section *sec,
192
				     unsigned long offset, unsigned int len)
193
{
M
Matt Helsley 已提交
194
	struct reloc *reloc, *r = NULL;
195
	unsigned long o;
196

M
Matt Helsley 已提交
197
	if (!sec->reloc)
198 199
		return NULL;

M
Matt Helsley 已提交
200
	sec = sec->reloc;
201

202
	for_offset_range(o, offset, offset + len) {
203 204
		elf_hash_for_each_possible(reloc, reloc, hash,
					   sec_offset_hash(sec, o)) {
M
Matt Helsley 已提交
205
			if (reloc->sec != sec)
206 207
				continue;

M
Matt Helsley 已提交
208 209 210
			if (reloc->offset >= offset && reloc->offset < offset + len) {
				if (!r || reloc->offset < r->offset)
					r = reloc;
211
			}
212
		}
213 214
		if (r)
			return r;
215
	}
216 217 218 219

	return NULL;
}

M
Matt Helsley 已提交
220
struct reloc *find_reloc_by_dest(const struct elf *elf, struct section *sec, unsigned long offset)
221
{
M
Matt Helsley 已提交
222
	return find_reloc_by_dest_range(elf, sec, offset, 1);
223 224 225 226 227 228 229 230 231 232
}

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)) {
233
		WARN_ELF("elf_getshdrnum");
234 235 236 237
		return -1;
	}

	if (elf_getshdrstrndx(elf->elf, &shstrndx)) {
238
		WARN_ELF("elf_getshdrstrndx");
239 240 241
		return -1;
	}

242 243 244 245
	if (!elf_alloc_hash(section, sections_nr) ||
	    !elf_alloc_hash(section_name, sections_nr))
		return -1;

246 247 248 249 250 251 252 253
	for (i = 0; i < sections_nr; i++) {
		sec = malloc(sizeof(*sec));
		if (!sec) {
			perror("malloc");
			return -1;
		}
		memset(sec, 0, sizeof(*sec));

254
		INIT_LIST_HEAD(&sec->symbol_list);
M
Matt Helsley 已提交
255
		INIT_LIST_HEAD(&sec->reloc_list);
256 257 258

		s = elf_getscn(elf->elf, i);
		if (!s) {
259
			WARN_ELF("elf_getscn");
260 261 262 263 264 265
			return -1;
		}

		sec->idx = elf_ndxscn(s);

		if (!gelf_getshdr(s, &sec->sh)) {
266
			WARN_ELF("gelf_getshdr");
267 268 269 270 271
			return -1;
		}

		sec->name = elf_strptr(elf->elf, shstrndx, sec->sh.sh_name);
		if (!sec->name) {
272
			WARN_ELF("elf_strptr");
273 274 275
			return -1;
		}

276 277 278 279 280 281 282 283 284 285 286 287
		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;
			}
288
		}
289

290
		if (sec->sh.sh_flags & SHF_EXECINSTR)
291
			elf->text_size += sec->sh.sh_size;
292

293
		list_add_tail(&sec->list, &elf->sections);
294 295
		elf_hash_add(section, &sec->hash, sec->idx);
		elf_hash_add(section_name, &sec->name_hash, str_hash(sec->name));
296 297
	}

298
	if (stats) {
P
Peter Zijlstra 已提交
299
		printf("nr_sections: %lu\n", (unsigned long)sections_nr);
300 301
		printf("section_bits: %d\n", elf->section_bits);
	}
P
Peter Zijlstra 已提交
302

303 304 305 306 307 308 309 310 311
	/* 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;
}

312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329
static void elf_add_symbol(struct elf *elf, struct symbol *sym)
{
	struct list_head *entry;
	struct rb_node *pnode;

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

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

	rb_add(&sym->node, &sym->sec->symbol_tree, symbol_to_offset);
	pnode = rb_prev(&sym->node);
	if (pnode)
		entry = &rb_entry(pnode, struct symbol, node)->list;
	else
		entry = &sym->sec->symbol_list;
	list_add(&sym->list, entry);
330 331
	elf_hash_add(symbol, &sym->hash, sym->idx);
	elf_hash_add(symbol_name, &sym->name_hash, str_hash(sym->name));
332 333 334 335 336 337 338 339 340

	/*
	 * Don't store empty STT_NOTYPE symbols in the rbtree.  They
	 * can exist within a function, confusing the sorting.
	 */
	if (!sym->len)
		rb_erase(&sym->node, &sym->sec->symbol_tree);
}

341 342
static int read_symbols(struct elf *elf)
{
343
	struct section *symtab, *symtab_shndx, *sec;
344
	struct symbol *sym, *pfunc;
345
	int symbols_nr, i;
346
	char *coldstr;
347 348
	Elf_Data *shndx_data = NULL;
	Elf32_Word shndx;
349 350

	symtab = find_section_by_name(elf, ".symtab");
351 352 353 354 355 356 357
	if (symtab) {
		symtab_shndx = find_section_by_name(elf, ".symtab_shndx");
		if (symtab_shndx)
			shndx_data = symtab_shndx->data;

		symbols_nr = symtab->sh.sh_size / symtab->sh.sh_entsize;
	} else {
358 359
		/*
		 * A missing symbol table is actually possible if it's an empty
360 361 362
		 * .o file. This can happen for thunk_64.o. Make sure to at
		 * least allocate the symbol hash tables so we can do symbol
		 * lookups without crashing.
363
		 */
364
		symbols_nr = 0;
365 366
	}

367 368 369
	if (!elf_alloc_hash(symbol, symbols_nr) ||
	    !elf_alloc_hash(symbol_name, symbols_nr))
		return -1;
370 371 372 373 374 375 376 377

	for (i = 0; i < symbols_nr; i++) {
		sym = malloc(sizeof(*sym));
		if (!sym) {
			perror("malloc");
			return -1;
		}
		memset(sym, 0, sizeof(*sym));
378
		sym->alias = sym;
379 380 381

		sym->idx = i;

382 383 384
		if (!gelf_getsymshndx(symtab->data, shndx_data, i, &sym->sym,
				      &shndx)) {
			WARN_ELF("gelf_getsymshndx");
385 386 387 388 389 390
			goto err;
		}

		sym->name = elf_strptr(elf->elf, symtab->sh.sh_link,
				       sym->sym.st_name);
		if (!sym->name) {
391
			WARN_ELF("elf_strptr");
392 393 394
			goto err;
		}

395 396 397 398 399 400 401
		if ((sym->sym.st_shndx > SHN_UNDEF &&
		     sym->sym.st_shndx < SHN_LORESERVE) ||
		    (shndx_data && sym->sym.st_shndx == SHN_XINDEX)) {
			if (sym->sym.st_shndx != SHN_XINDEX)
				shndx = sym->sym.st_shndx;

			sym->sec = find_section_by_index(elf, shndx);
402 403 404 405 406
			if (!sym->sec) {
				WARN("couldn't find section for symbol %s",
				     sym->name);
				goto err;
			}
407
			if (GELF_ST_TYPE(sym->sym.st_info) == STT_SECTION) {
408 409 410 411 412 413
				sym->name = sym->sec->name;
				sym->sec->sym = sym;
			}
		} else
			sym->sec = find_section_by_index(elf, 0);

414
		elf_add_symbol(elf, sym);
415 416
	}

417
	if (stats) {
P
Peter Zijlstra 已提交
418
		printf("nr_symbols: %lu\n", (unsigned long)symbols_nr);
419 420
		printf("symbol_bits: %d\n", elf->symbol_bits);
	}
P
Peter Zijlstra 已提交
421

422 423 424
	/* 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) {
425 426
			char pname[MAX_NAME_LEN + 1];
			size_t pnamelen;
427 428
			if (sym->type != STT_FUNC)
				continue;
429 430 431 432 433 434 435

			if (sym->pfunc == NULL)
				sym->pfunc = sym;

			if (sym->cfunc == NULL)
				sym->cfunc = sym;

436
			coldstr = strstr(sym->name, ".cold");
437 438 439
			if (!coldstr)
				continue;

440 441 442 443 444 445 446 447 448 449
			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);
450 451 452 453

			if (!pfunc) {
				WARN("%s(): can't find parent function",
				     sym->name);
454
				return -1;
455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471
			}

			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;
472 473 474 475
			}
		}
	}

476 477 478 479 480 481 482
	return 0;

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

483 484 485 486
static struct section *elf_create_reloc_section(struct elf *elf,
						struct section *base,
						int reltype);

487 488
int elf_add_reloc(struct elf *elf, struct section *sec, unsigned long offset,
		  unsigned int type, struct symbol *sym, int addend)
489
{
490 491
	struct reloc *reloc;

492 493 494
	if (!sec->reloc && !elf_create_reloc_section(elf, sec, SHT_RELA))
		return -1;

495 496 497 498 499 500 501 502 503 504 505 506
	reloc = malloc(sizeof(*reloc));
	if (!reloc) {
		perror("malloc");
		return -1;
	}
	memset(reloc, 0, sizeof(*reloc));

	reloc->sec = sec->reloc;
	reloc->offset = offset;
	reloc->type = type;
	reloc->sym = sym;
	reloc->addend = addend;
507

508
	list_add_tail(&reloc->list, &sec->reloc->reloc_list);
509
	elf_hash_add(reloc, &reloc->hash, reloc_hash(reloc));
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
	sec->reloc->changed = true;

	return 0;
}

int elf_add_reloc_to_insn(struct elf *elf, struct section *sec,
			  unsigned long offset, unsigned int type,
			  struct section *insn_sec, unsigned long insn_off)
{
	struct symbol *sym;
	int addend;

	if (insn_sec->sym) {
		sym = insn_sec->sym;
		addend = insn_off;

	} else {
		/*
		 * The Clang assembler strips section symbols, so we have to
		 * reference the function symbol instead:
		 */
		sym = find_symbol_containing(insn_sec, insn_off);
		if (!sym) {
			/*
			 * Hack alert.  This happens when we need to reference
			 * the NOP pad insn immediately after the function.
			 */
			sym = find_symbol_containing(insn_sec, insn_off - 1);
		}

		if (!sym) {
			WARN("can't find symbol containing %s+0x%lx", insn_sec->name, insn_off);
			return -1;
		}

		addend = insn_off - sym->offset;
	}

	return elf_add_reloc(elf, sec, offset, type, sym, addend);
550 551
}

552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577
static int read_rel_reloc(struct section *sec, int i, struct reloc *reloc, unsigned int *symndx)
{
	if (!gelf_getrel(sec->data, i, &reloc->rel)) {
		WARN_ELF("gelf_getrel");
		return -1;
	}
	reloc->type = GELF_R_TYPE(reloc->rel.r_info);
	reloc->addend = 0;
	reloc->offset = reloc->rel.r_offset;
	*symndx = GELF_R_SYM(reloc->rel.r_info);
	return 0;
}

static int read_rela_reloc(struct section *sec, int i, struct reloc *reloc, unsigned int *symndx)
{
	if (!gelf_getrela(sec->data, i, &reloc->rela)) {
		WARN_ELF("gelf_getrela");
		return -1;
	}
	reloc->type = GELF_R_TYPE(reloc->rela.r_info);
	reloc->addend = reloc->rela.r_addend;
	reloc->offset = reloc->rela.r_offset;
	*symndx = GELF_R_SYM(reloc->rela.r_info);
	return 0;
}

M
Matt Helsley 已提交
578
static int read_relocs(struct elf *elf)
579 580
{
	struct section *sec;
M
Matt Helsley 已提交
581
	struct reloc *reloc;
582 583
	int i;
	unsigned int symndx;
M
Matt Helsley 已提交
584
	unsigned long nr_reloc, max_reloc = 0, tot_reloc = 0;
585

586
	if (!elf_alloc_hash(reloc, elf->text_size / 16))
587 588
		return -1;

589
	list_for_each_entry(sec, &elf->sections, list) {
590 591
		if ((sec->sh.sh_type != SHT_RELA) &&
		    (sec->sh.sh_type != SHT_REL))
592 593
			continue;

594
		sec->base = find_section_by_index(elf, sec->sh.sh_info);
595
		if (!sec->base) {
M
Matt Helsley 已提交
596
			WARN("can't find base section for reloc section %s",
597 598 599 600
			     sec->name);
			return -1;
		}

M
Matt Helsley 已提交
601
		sec->base->reloc = sec;
602

M
Matt Helsley 已提交
603
		nr_reloc = 0;
604
		for (i = 0; i < sec->sh.sh_size / sec->sh.sh_entsize; i++) {
M
Matt Helsley 已提交
605 606
			reloc = malloc(sizeof(*reloc));
			if (!reloc) {
607 608 609
				perror("malloc");
				return -1;
			}
M
Matt Helsley 已提交
610
			memset(reloc, 0, sizeof(*reloc));
611 612 613 614 615 616 617 618 619 620
			switch (sec->sh.sh_type) {
			case SHT_REL:
				if (read_rel_reloc(sec, i, reloc, &symndx))
					return -1;
				break;
			case SHT_RELA:
				if (read_rela_reloc(sec, i, reloc, &symndx))
					return -1;
				break;
			default: return -1;
621 622
			}

M
Matt Helsley 已提交
623
			reloc->sec = sec;
624 625
			reloc->idx = i;
			reloc->sym = find_symbol_by_index(elf, symndx);
M
Matt Helsley 已提交
626 627
			if (!reloc->sym) {
				WARN("can't find reloc entry symbol %d for %s",
628 629 630
				     symndx, sec->name);
				return -1;
			}
631

632
			list_add_tail(&reloc->list, &sec->reloc_list);
633
			elf_hash_add(reloc, &reloc->hash, reloc_hash(reloc));
634

M
Matt Helsley 已提交
635
			nr_reloc++;
636
		}
M
Matt Helsley 已提交
637 638
		max_reloc = max(max_reloc, nr_reloc);
		tot_reloc += nr_reloc;
P
Peter Zijlstra 已提交
639 640 641
	}

	if (stats) {
M
Matt Helsley 已提交
642 643
		printf("max_reloc: %lu\n", max_reloc);
		printf("tot_reloc: %lu\n", tot_reloc);
644
		printf("reloc_bits: %d\n", elf->reloc_bits);
645 646 647 648 649
	}

	return 0;
}

650
struct elf *elf_open_read(const char *name, int flags)
651 652
{
	struct elf *elf;
653
	Elf_Cmd cmd;
654 655 656 657 658 659 660 661

	elf_version(EV_CURRENT);

	elf = malloc(sizeof(*elf));
	if (!elf) {
		perror("malloc");
		return NULL;
	}
662
	memset(elf, 0, offsetof(struct elf, sections));
663 664 665

	INIT_LIST_HEAD(&elf->sections);

666
	elf->fd = open(name, flags);
667
	if (elf->fd == -1) {
668 669
		fprintf(stderr, "objtool: Can't open '%s': %s\n",
			name, strerror(errno));
670 671 672
		goto err;
	}

673 674 675 676 677 678 679 680
	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);
681
	if (!elf->elf) {
682
		WARN_ELF("elf_begin");
683 684 685 686
		goto err;
	}

	if (!gelf_getehdr(elf->elf, &elf->ehdr)) {
687
		WARN_ELF("gelf_getehdr");
688 689 690 691 692 693 694 695 696
		goto err;
	}

	if (read_sections(elf))
		goto err;

	if (read_symbols(elf))
		goto err;

M
Matt Helsley 已提交
697
	if (read_relocs(elf))
698 699 700 701 702 703 704 705 706
		goto err;

	return elf;

err:
	elf_close(elf);
	return NULL;
}

707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735
static int elf_add_string(struct elf *elf, struct section *strtab, char *str)
{
	Elf_Data *data;
	Elf_Scn *s;
	int len;

	if (!strtab)
		strtab = find_section_by_name(elf, ".strtab");
	if (!strtab) {
		WARN("can't find .strtab section");
		return -1;
	}

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

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

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

736 737
	len = strtab->sh.sh_size;
	strtab->sh.sh_size += data->d_size;
738 739 740 741 742
	strtab->changed = true;

	return len;
}

743 744
struct symbol *elf_create_undef_symbol(struct elf *elf, const char *name)
{
745
	struct section *symtab, *symtab_shndx;
746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789
	struct symbol *sym;
	Elf_Data *data;
	Elf_Scn *s;

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

	sym->name = strdup(name);

	sym->sym.st_name = elf_add_string(elf, NULL, sym->name);
	if (sym->sym.st_name == -1)
		return NULL;

	sym->sym.st_info = GELF_ST_INFO(STB_GLOBAL, STT_NOTYPE);
	// st_other 0
	// st_shndx 0
	// st_value 0
	// st_size 0

	symtab = find_section_by_name(elf, ".symtab");
	if (!symtab) {
		WARN("can't find .symtab");
		return NULL;
	}

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

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

	data->d_buf = &sym->sym;
	data->d_size = sizeof(sym->sym);
	data->d_align = 1;
790
	data->d_type = ELF_T_SYM;
791

792
	sym->idx = symtab->sh.sh_size / sizeof(sym->sym);
793

794
	symtab->sh.sh_size += data->d_size;
795 796
	symtab->changed = true;

797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815
	symtab_shndx = find_section_by_name(elf, ".symtab_shndx");
	if (symtab_shndx) {
		s = elf_getscn(elf->elf, symtab_shndx->idx);
		if (!s) {
			WARN_ELF("elf_getscn");
			return NULL;
		}

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

		data->d_buf = &sym->sym.st_size; /* conveniently 0 */
		data->d_size = sizeof(Elf32_Word);
		data->d_align = 4;
		data->d_type = ELF_T_WORD;

816
		symtab_shndx->sh.sh_size += 4;
817 818 819
		symtab_shndx->changed = true;
	}

820 821 822 823 824 825 826
	sym->sec = find_section_by_index(elf, 0);

	elf_add_symbol(elf, sym);

	return sym;
}

827
struct section *elf_create_section(struct elf *elf, const char *name,
828
				   unsigned int sh_flags, size_t entsize, int nr)
829 830 831
{
	struct section *sec, *shstrtab;
	size_t size = entsize * nr;
832
	Elf_Scn *s;
833 834 835 836 837 838 839 840 841

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

	INIT_LIST_HEAD(&sec->symbol_list);
M
Matt Helsley 已提交
842
	INIT_LIST_HEAD(&sec->reloc_list);
843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885

	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->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;
886
	sec->sh.sh_flags = SHF_ALLOC | sh_flags;
887

888
	/* Add section name to .shstrtab (or .strtab for Clang) */
889
	shstrtab = find_section_by_name(elf, ".shstrtab");
890 891
	if (!shstrtab)
		shstrtab = find_section_by_name(elf, ".strtab");
892
	if (!shstrtab) {
893
		WARN("can't find .shstrtab or .strtab section");
894 895
		return NULL;
	}
896 897
	sec->sh.sh_name = elf_add_string(elf, shstrtab, sec->name);
	if (sec->sh.sh_name == -1)
898 899
		return NULL;

900
	list_add_tail(&sec->list, &elf->sections);
901 902
	elf_hash_add(section, &sec->hash, sec->idx);
	elf_hash_add(section_name, &sec->name_hash, str_hash(sec->name));
903

904 905
	elf->changed = true;

906 907 908
	return sec;
}

909 910 911 912 913 914 915 916 917 918 919 920 921
static struct section *elf_create_rel_reloc_section(struct elf *elf, struct section *base)
{
	char *relocname;
	struct section *sec;

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

922
	sec = elf_create_section(elf, relocname, 0, sizeof(GElf_Rel), 0);
923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939
	free(relocname);
	if (!sec)
		return NULL;

	base->reloc = sec;
	sec->base = base;

	sec->sh.sh_type = SHT_REL;
	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;
}

static struct section *elf_create_rela_reloc_section(struct elf *elf, struct section *base)
940
{
M
Matt Helsley 已提交
941
	char *relocname;
942 943
	struct section *sec;

M
Matt Helsley 已提交
944 945
	relocname = malloc(strlen(base->name) + strlen(".rela") + 1);
	if (!relocname) {
946 947 948
		perror("malloc");
		return NULL;
	}
M
Matt Helsley 已提交
949 950
	strcpy(relocname, ".rela");
	strcat(relocname, base->name);
951

952
	sec = elf_create_section(elf, relocname, 0, sizeof(GElf_Rela), 0);
M
Matt Helsley 已提交
953
	free(relocname);
954 955 956
	if (!sec)
		return NULL;

M
Matt Helsley 已提交
957
	base->reloc = sec;
958 959 960 961 962 963 964 965 966 967 968
	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;
}

969
static struct section *elf_create_reloc_section(struct elf *elf,
970 971 972 973 974 975 976 977 978 979 980
					 struct section *base,
					 int reltype)
{
	switch (reltype) {
	case SHT_REL:  return elf_create_rel_reloc_section(elf, base);
	case SHT_RELA: return elf_create_rela_reloc_section(elf, base);
	default:       return NULL;
	}
}

static int elf_rebuild_rel_reloc_section(struct section *sec, int nr)
981
{
M
Matt Helsley 已提交
982
	struct reloc *reloc;
983
	int idx = 0, size;
984
	void *buf;
985

986
	/* Allocate a buffer for relocations */
987 988 989
	size = nr * sizeof(GElf_Rel);
	buf = malloc(size);
	if (!buf) {
990 991 992 993
		perror("malloc");
		return -1;
	}

994
	sec->data->d_buf = buf;
995
	sec->data->d_size = size;
996
	sec->data->d_type = ELF_T_REL;
997 998 999 1000 1001

	sec->sh.sh_size = size;

	idx = 0;
	list_for_each_entry(reloc, &sec->reloc_list, list) {
1002 1003 1004
		reloc->rel.r_offset = reloc->offset;
		reloc->rel.r_info = GELF_R_INFO(reloc->sym->idx, reloc->type);
		gelf_update_rel(sec->data, idx, &reloc->rel);
1005 1006 1007 1008 1009
		idx++;
	}

	return 0;
}
1010

1011 1012 1013 1014
static int elf_rebuild_rela_reloc_section(struct section *sec, int nr)
{
	struct reloc *reloc;
	int idx = 0, size;
1015
	void *buf;
1016 1017

	/* Allocate a buffer for relocations with addends */
1018 1019 1020
	size = nr * sizeof(GElf_Rela);
	buf = malloc(size);
	if (!buf) {
1021 1022 1023 1024
		perror("malloc");
		return -1;
	}

1025
	sec->data->d_buf = buf;
1026
	sec->data->d_size = size;
1027
	sec->data->d_type = ELF_T_RELA;
1028 1029 1030 1031

	sec->sh.sh_size = size;

	idx = 0;
M
Matt Helsley 已提交
1032
	list_for_each_entry(reloc, &sec->reloc_list, list) {
1033 1034 1035 1036
		reloc->rela.r_offset = reloc->offset;
		reloc->rela.r_addend = reloc->addend;
		reloc->rela.r_info = GELF_R_INFO(reloc->sym->idx, reloc->type);
		gelf_update_rela(sec->data, idx, &reloc->rela);
1037 1038 1039 1040 1041 1042
		idx++;
	}

	return 0;
}

1043
static int elf_rebuild_reloc_section(struct elf *elf, struct section *sec)
1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058
{
	struct reloc *reloc;
	int nr;

	nr = 0;
	list_for_each_entry(reloc, &sec->reloc_list, list)
		nr++;

	switch (sec->sh.sh_type) {
	case SHT_REL:  return elf_rebuild_rel_reloc_section(sec, nr);
	case SHT_RELA: return elf_rebuild_rela_reloc_section(sec, nr);
	default:       return -1;
	}
}

1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077
int elf_write_insn(struct elf *elf, struct section *sec,
		   unsigned long offset, unsigned int len,
		   const char *insn)
{
	Elf_Data *data = sec->data;

	if (data->d_type != ELF_T_BYTE || data->d_off) {
		WARN("write to unexpected data for section: %s", sec->name);
		return -1;
	}

	memcpy(data->d_buf + offset, insn, len);
	elf_flagdata(data, ELF_C_SET, ELF_F_DIRTY);

	elf->changed = true;

	return 0;
}

1078
int elf_write_reloc(struct elf *elf, struct reloc *reloc)
1079
{
1080
	struct section *sec = reloc->sec;
1081

1082 1083 1084
	if (sec->sh.sh_type == SHT_REL) {
		reloc->rel.r_info = GELF_R_INFO(reloc->sym->idx, reloc->type);
		reloc->rel.r_offset = reloc->offset;
1085

1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098
		if (!gelf_update_rel(sec->data, reloc->idx, &reloc->rel)) {
			WARN_ELF("gelf_update_rel");
			return -1;
		}
	} else {
		reloc->rela.r_info = GELF_R_INFO(reloc->sym->idx, reloc->type);
		reloc->rela.r_addend = reloc->addend;
		reloc->rela.r_offset = reloc->offset;

		if (!gelf_update_rela(sec->data, reloc->idx, &reloc->rela)) {
			WARN_ELF("gelf_update_rela");
			return -1;
		}
1099 1100 1101 1102 1103 1104 1105
	}

	elf->changed = true;

	return 0;
}

1106
int elf_write(struct elf *elf)
1107 1108 1109 1110
{
	struct section *sec;
	Elf_Scn *s;

1111
	/* Update changed relocation sections and section headers: */
1112 1113
	list_for_each_entry(sec, &elf->sections, list) {
		if (sec->changed) {
1114 1115 1116 1117 1118 1119
			if (sec->base &&
			    elf_rebuild_reloc_section(elf, sec)) {
				WARN("elf_rebuild_reloc_section");
				return -1;
			}

1120 1121 1122 1123 1124
			s = elf_getscn(elf->elf, sec->idx);
			if (!s) {
				WARN_ELF("elf_getscn");
				return -1;
			}
1125
			if (!gelf_update_shdr(s, &sec->sh)) {
1126 1127 1128
				WARN_ELF("gelf_update_shdr");
				return -1;
			}
1129 1130

			sec->changed = false;
1131
			elf->changed = true;
1132 1133 1134
		}
	}

1135 1136 1137 1138
	/* 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. */
1139 1140 1141 1142 1143
	if (elf_update(elf->elf, ELF_C_WRITE) < 0) {
		WARN_ELF("elf_update");
		return -1;
	}

1144 1145
	elf->changed = false;

1146 1147 1148
	return 0;
}

1149 1150 1151 1152
void elf_close(struct elf *elf)
{
	struct section *sec, *tmpsec;
	struct symbol *sym, *tmpsym;
M
Matt Helsley 已提交
1153
	struct reloc *reloc, *tmpreloc;
1154

1155 1156 1157 1158 1159 1160
	if (elf->elf)
		elf_end(elf->elf);

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

1161
	list_for_each_entry_safe(sec, tmpsec, &elf->sections, list) {
1162
		list_for_each_entry_safe(sym, tmpsym, &sec->symbol_list, list) {
1163
			list_del(&sym->list);
1164
			hash_del(&sym->hash);
1165 1166
			free(sym);
		}
M
Matt Helsley 已提交
1167 1168 1169 1170
		list_for_each_entry_safe(reloc, tmpreloc, &sec->reloc_list, list) {
			list_del(&reloc->list);
			hash_del(&reloc->hash);
			free(reloc);
1171 1172 1173 1174
		}
		list_del(&sec->list);
		free(sec);
	}
1175

1176 1177
	free(elf);
}