xref: /openbmc/linux/arch/x86/tools/relocs.c (revision ca79522c)
1 /* This is included from relocs_32/64.c */
2 
3 #define ElfW(type)		_ElfW(ELF_BITS, type)
4 #define _ElfW(bits, type)	__ElfW(bits, type)
5 #define __ElfW(bits, type)	Elf##bits##_##type
6 
7 #define Elf_Addr		ElfW(Addr)
8 #define Elf_Ehdr		ElfW(Ehdr)
9 #define Elf_Phdr		ElfW(Phdr)
10 #define Elf_Shdr		ElfW(Shdr)
11 #define Elf_Sym			ElfW(Sym)
12 
13 static Elf_Ehdr ehdr;
14 
15 struct relocs {
16 	uint32_t	*offset;
17 	unsigned long	count;
18 	unsigned long	size;
19 };
20 
21 static struct relocs relocs16;
22 static struct relocs relocs32;
23 static struct relocs relocs64;
24 
25 struct section {
26 	Elf_Shdr       shdr;
27 	struct section *link;
28 	Elf_Sym        *symtab;
29 	Elf_Rel        *reltab;
30 	char           *strtab;
31 };
32 static struct section *secs;
33 
34 static const char * const sym_regex_kernel[S_NSYMTYPES] = {
35 /*
36  * Following symbols have been audited. There values are constant and do
37  * not change if bzImage is loaded at a different physical address than
38  * the address for which it has been compiled. Don't warn user about
39  * absolute relocations present w.r.t these symbols.
40  */
41 	[S_ABS] =
42 	"^(xen_irq_disable_direct_reloc$|"
43 	"xen_save_fl_direct_reloc$|"
44 	"VDSO|"
45 #if ELF_BITS == 64
46 	"__vvar_page|"
47 #endif
48 	"__crc_)",
49 
50 /*
51  * These symbols are known to be relative, even if the linker marks them
52  * as absolute (typically defined outside any section in the linker script.)
53  */
54 	[S_REL] =
55 	"^(__init_(begin|end)|"
56 	"__x86_cpu_dev_(start|end)|"
57 	"(__parainstructions|__alt_instructions)(|_end)|"
58 	"(__iommu_table|__apicdrivers|__smp_locks)(|_end)|"
59 	"__(start|end)_pci_.*|"
60 	"__(start|end)_builtin_fw|"
61 	"__(start|stop)___ksymtab(|_gpl|_unused|_unused_gpl|_gpl_future)|"
62 	"__(start|stop)___kcrctab(|_gpl|_unused|_unused_gpl|_gpl_future)|"
63 	"__(start|stop)___param|"
64 	"__(start|stop)___modver|"
65 	"__(start|stop)___bug_table|"
66 	"__tracedata_(start|end)|"
67 	"__(start|stop)_notes|"
68 	"__end_rodata|"
69 	"__initramfs_start|"
70 	"(jiffies|jiffies_64)|"
71 #if ELF_BITS == 64
72 	"__per_cpu_load|"
73 	"init_per_cpu__.*|"
74 	"__end_rodata_hpage_align|"
75 #endif
76 	"_end)$"
77 };
78 
79 
80 static const char * const sym_regex_realmode[S_NSYMTYPES] = {
81 /*
82  * These symbols are known to be relative, even if the linker marks them
83  * as absolute (typically defined outside any section in the linker script.)
84  */
85 	[S_REL] =
86 	"^pa_",
87 
88 /*
89  * These are 16-bit segment symbols when compiling 16-bit code.
90  */
91 	[S_SEG] =
92 	"^real_mode_seg$",
93 
94 /*
95  * These are offsets belonging to segments, as opposed to linear addresses,
96  * when compiling 16-bit code.
97  */
98 	[S_LIN] =
99 	"^pa_",
100 };
101 
102 static const char * const *sym_regex;
103 
104 static regex_t sym_regex_c[S_NSYMTYPES];
105 static int is_reloc(enum symtype type, const char *sym_name)
106 {
107 	return sym_regex[type] &&
108 		!regexec(&sym_regex_c[type], sym_name, 0, NULL, 0);
109 }
110 
111 static void regex_init(int use_real_mode)
112 {
113         char errbuf[128];
114         int err;
115 	int i;
116 
117 	if (use_real_mode)
118 		sym_regex = sym_regex_realmode;
119 	else
120 		sym_regex = sym_regex_kernel;
121 
122 	for (i = 0; i < S_NSYMTYPES; i++) {
123 		if (!sym_regex[i])
124 			continue;
125 
126 		err = regcomp(&sym_regex_c[i], sym_regex[i],
127 			      REG_EXTENDED|REG_NOSUB);
128 
129 		if (err) {
130 			regerror(err, &sym_regex_c[i], errbuf, sizeof errbuf);
131 			die("%s", errbuf);
132 		}
133         }
134 }
135 
136 static const char *sym_type(unsigned type)
137 {
138 	static const char *type_name[] = {
139 #define SYM_TYPE(X) [X] = #X
140 		SYM_TYPE(STT_NOTYPE),
141 		SYM_TYPE(STT_OBJECT),
142 		SYM_TYPE(STT_FUNC),
143 		SYM_TYPE(STT_SECTION),
144 		SYM_TYPE(STT_FILE),
145 		SYM_TYPE(STT_COMMON),
146 		SYM_TYPE(STT_TLS),
147 #undef SYM_TYPE
148 	};
149 	const char *name = "unknown sym type name";
150 	if (type < ARRAY_SIZE(type_name)) {
151 		name = type_name[type];
152 	}
153 	return name;
154 }
155 
156 static const char *sym_bind(unsigned bind)
157 {
158 	static const char *bind_name[] = {
159 #define SYM_BIND(X) [X] = #X
160 		SYM_BIND(STB_LOCAL),
161 		SYM_BIND(STB_GLOBAL),
162 		SYM_BIND(STB_WEAK),
163 #undef SYM_BIND
164 	};
165 	const char *name = "unknown sym bind name";
166 	if (bind < ARRAY_SIZE(bind_name)) {
167 		name = bind_name[bind];
168 	}
169 	return name;
170 }
171 
172 static const char *sym_visibility(unsigned visibility)
173 {
174 	static const char *visibility_name[] = {
175 #define SYM_VISIBILITY(X) [X] = #X
176 		SYM_VISIBILITY(STV_DEFAULT),
177 		SYM_VISIBILITY(STV_INTERNAL),
178 		SYM_VISIBILITY(STV_HIDDEN),
179 		SYM_VISIBILITY(STV_PROTECTED),
180 #undef SYM_VISIBILITY
181 	};
182 	const char *name = "unknown sym visibility name";
183 	if (visibility < ARRAY_SIZE(visibility_name)) {
184 		name = visibility_name[visibility];
185 	}
186 	return name;
187 }
188 
189 static const char *rel_type(unsigned type)
190 {
191 	static const char *type_name[] = {
192 #define REL_TYPE(X) [X] = #X
193 #if ELF_BITS == 64
194 		REL_TYPE(R_X86_64_NONE),
195 		REL_TYPE(R_X86_64_64),
196 		REL_TYPE(R_X86_64_PC32),
197 		REL_TYPE(R_X86_64_GOT32),
198 		REL_TYPE(R_X86_64_PLT32),
199 		REL_TYPE(R_X86_64_COPY),
200 		REL_TYPE(R_X86_64_GLOB_DAT),
201 		REL_TYPE(R_X86_64_JUMP_SLOT),
202 		REL_TYPE(R_X86_64_RELATIVE),
203 		REL_TYPE(R_X86_64_GOTPCREL),
204 		REL_TYPE(R_X86_64_32),
205 		REL_TYPE(R_X86_64_32S),
206 		REL_TYPE(R_X86_64_16),
207 		REL_TYPE(R_X86_64_PC16),
208 		REL_TYPE(R_X86_64_8),
209 		REL_TYPE(R_X86_64_PC8),
210 #else
211 		REL_TYPE(R_386_NONE),
212 		REL_TYPE(R_386_32),
213 		REL_TYPE(R_386_PC32),
214 		REL_TYPE(R_386_GOT32),
215 		REL_TYPE(R_386_PLT32),
216 		REL_TYPE(R_386_COPY),
217 		REL_TYPE(R_386_GLOB_DAT),
218 		REL_TYPE(R_386_JMP_SLOT),
219 		REL_TYPE(R_386_RELATIVE),
220 		REL_TYPE(R_386_GOTOFF),
221 		REL_TYPE(R_386_GOTPC),
222 		REL_TYPE(R_386_8),
223 		REL_TYPE(R_386_PC8),
224 		REL_TYPE(R_386_16),
225 		REL_TYPE(R_386_PC16),
226 #endif
227 #undef REL_TYPE
228 	};
229 	const char *name = "unknown type rel type name";
230 	if (type < ARRAY_SIZE(type_name) && type_name[type]) {
231 		name = type_name[type];
232 	}
233 	return name;
234 }
235 
236 static const char *sec_name(unsigned shndx)
237 {
238 	const char *sec_strtab;
239 	const char *name;
240 	sec_strtab = secs[ehdr.e_shstrndx].strtab;
241 	name = "<noname>";
242 	if (shndx < ehdr.e_shnum) {
243 		name = sec_strtab + secs[shndx].shdr.sh_name;
244 	}
245 	else if (shndx == SHN_ABS) {
246 		name = "ABSOLUTE";
247 	}
248 	else if (shndx == SHN_COMMON) {
249 		name = "COMMON";
250 	}
251 	return name;
252 }
253 
254 static const char *sym_name(const char *sym_strtab, Elf_Sym *sym)
255 {
256 	const char *name;
257 	name = "<noname>";
258 	if (sym->st_name) {
259 		name = sym_strtab + sym->st_name;
260 	}
261 	else {
262 		name = sec_name(sym->st_shndx);
263 	}
264 	return name;
265 }
266 
267 static Elf_Sym *sym_lookup(const char *symname)
268 {
269 	int i;
270 	for (i = 0; i < ehdr.e_shnum; i++) {
271 		struct section *sec = &secs[i];
272 		long nsyms;
273 		char *strtab;
274 		Elf_Sym *symtab;
275 		Elf_Sym *sym;
276 
277 		if (sec->shdr.sh_type != SHT_SYMTAB)
278 			continue;
279 
280 		nsyms = sec->shdr.sh_size/sizeof(Elf_Sym);
281 		symtab = sec->symtab;
282 		strtab = sec->link->strtab;
283 
284 		for (sym = symtab; --nsyms >= 0; sym++) {
285 			if (!sym->st_name)
286 				continue;
287 			if (strcmp(symname, strtab + sym->st_name) == 0)
288 				return sym;
289 		}
290 	}
291 	return 0;
292 }
293 
294 #if BYTE_ORDER == LITTLE_ENDIAN
295 #define le16_to_cpu(val) (val)
296 #define le32_to_cpu(val) (val)
297 #define le64_to_cpu(val) (val)
298 #endif
299 #if BYTE_ORDER == BIG_ENDIAN
300 #define le16_to_cpu(val) bswap_16(val)
301 #define le32_to_cpu(val) bswap_32(val)
302 #define le64_to_cpu(val) bswap_64(val)
303 #endif
304 
305 static uint16_t elf16_to_cpu(uint16_t val)
306 {
307 	return le16_to_cpu(val);
308 }
309 
310 static uint32_t elf32_to_cpu(uint32_t val)
311 {
312 	return le32_to_cpu(val);
313 }
314 
315 #define elf_half_to_cpu(x)	elf16_to_cpu(x)
316 #define elf_word_to_cpu(x)	elf32_to_cpu(x)
317 
318 #if ELF_BITS == 64
319 static uint64_t elf64_to_cpu(uint64_t val)
320 {
321         return le64_to_cpu(val);
322 }
323 #define elf_addr_to_cpu(x)	elf64_to_cpu(x)
324 #define elf_off_to_cpu(x)	elf64_to_cpu(x)
325 #define elf_xword_to_cpu(x)	elf64_to_cpu(x)
326 #else
327 #define elf_addr_to_cpu(x)	elf32_to_cpu(x)
328 #define elf_off_to_cpu(x)	elf32_to_cpu(x)
329 #define elf_xword_to_cpu(x)	elf32_to_cpu(x)
330 #endif
331 
332 static void read_ehdr(FILE *fp)
333 {
334 	if (fread(&ehdr, sizeof(ehdr), 1, fp) != 1) {
335 		die("Cannot read ELF header: %s\n",
336 			strerror(errno));
337 	}
338 	if (memcmp(ehdr.e_ident, ELFMAG, SELFMAG) != 0) {
339 		die("No ELF magic\n");
340 	}
341 	if (ehdr.e_ident[EI_CLASS] != ELF_CLASS) {
342 		die("Not a %d bit executable\n", ELF_BITS);
343 	}
344 	if (ehdr.e_ident[EI_DATA] != ELFDATA2LSB) {
345 		die("Not a LSB ELF executable\n");
346 	}
347 	if (ehdr.e_ident[EI_VERSION] != EV_CURRENT) {
348 		die("Unknown ELF version\n");
349 	}
350 	/* Convert the fields to native endian */
351 	ehdr.e_type      = elf_half_to_cpu(ehdr.e_type);
352 	ehdr.e_machine   = elf_half_to_cpu(ehdr.e_machine);
353 	ehdr.e_version   = elf_word_to_cpu(ehdr.e_version);
354 	ehdr.e_entry     = elf_addr_to_cpu(ehdr.e_entry);
355 	ehdr.e_phoff     = elf_off_to_cpu(ehdr.e_phoff);
356 	ehdr.e_shoff     = elf_off_to_cpu(ehdr.e_shoff);
357 	ehdr.e_flags     = elf_word_to_cpu(ehdr.e_flags);
358 	ehdr.e_ehsize    = elf_half_to_cpu(ehdr.e_ehsize);
359 	ehdr.e_phentsize = elf_half_to_cpu(ehdr.e_phentsize);
360 	ehdr.e_phnum     = elf_half_to_cpu(ehdr.e_phnum);
361 	ehdr.e_shentsize = elf_half_to_cpu(ehdr.e_shentsize);
362 	ehdr.e_shnum     = elf_half_to_cpu(ehdr.e_shnum);
363 	ehdr.e_shstrndx  = elf_half_to_cpu(ehdr.e_shstrndx);
364 
365 	if ((ehdr.e_type != ET_EXEC) && (ehdr.e_type != ET_DYN)) {
366 		die("Unsupported ELF header type\n");
367 	}
368 	if (ehdr.e_machine != ELF_MACHINE) {
369 		die("Not for %s\n", ELF_MACHINE_NAME);
370 	}
371 	if (ehdr.e_version != EV_CURRENT) {
372 		die("Unknown ELF version\n");
373 	}
374 	if (ehdr.e_ehsize != sizeof(Elf_Ehdr)) {
375 		die("Bad Elf header size\n");
376 	}
377 	if (ehdr.e_phentsize != sizeof(Elf_Phdr)) {
378 		die("Bad program header entry\n");
379 	}
380 	if (ehdr.e_shentsize != sizeof(Elf_Shdr)) {
381 		die("Bad section header entry\n");
382 	}
383 	if (ehdr.e_shstrndx >= ehdr.e_shnum) {
384 		die("String table index out of bounds\n");
385 	}
386 }
387 
388 static void read_shdrs(FILE *fp)
389 {
390 	int i;
391 	Elf_Shdr shdr;
392 
393 	secs = calloc(ehdr.e_shnum, sizeof(struct section));
394 	if (!secs) {
395 		die("Unable to allocate %d section headers\n",
396 		    ehdr.e_shnum);
397 	}
398 	if (fseek(fp, ehdr.e_shoff, SEEK_SET) < 0) {
399 		die("Seek to %d failed: %s\n",
400 			ehdr.e_shoff, strerror(errno));
401 	}
402 	for (i = 0; i < ehdr.e_shnum; i++) {
403 		struct section *sec = &secs[i];
404 		if (fread(&shdr, sizeof shdr, 1, fp) != 1)
405 			die("Cannot read ELF section headers %d/%d: %s\n",
406 			    i, ehdr.e_shnum, strerror(errno));
407 		sec->shdr.sh_name      = elf_word_to_cpu(shdr.sh_name);
408 		sec->shdr.sh_type      = elf_word_to_cpu(shdr.sh_type);
409 		sec->shdr.sh_flags     = elf_xword_to_cpu(shdr.sh_flags);
410 		sec->shdr.sh_addr      = elf_addr_to_cpu(shdr.sh_addr);
411 		sec->shdr.sh_offset    = elf_off_to_cpu(shdr.sh_offset);
412 		sec->shdr.sh_size      = elf_xword_to_cpu(shdr.sh_size);
413 		sec->shdr.sh_link      = elf_word_to_cpu(shdr.sh_link);
414 		sec->shdr.sh_info      = elf_word_to_cpu(shdr.sh_info);
415 		sec->shdr.sh_addralign = elf_xword_to_cpu(shdr.sh_addralign);
416 		sec->shdr.sh_entsize   = elf_xword_to_cpu(shdr.sh_entsize);
417 		if (sec->shdr.sh_link < ehdr.e_shnum)
418 			sec->link = &secs[sec->shdr.sh_link];
419 	}
420 
421 }
422 
423 static void read_strtabs(FILE *fp)
424 {
425 	int i;
426 	for (i = 0; i < ehdr.e_shnum; i++) {
427 		struct section *sec = &secs[i];
428 		if (sec->shdr.sh_type != SHT_STRTAB) {
429 			continue;
430 		}
431 		sec->strtab = malloc(sec->shdr.sh_size);
432 		if (!sec->strtab) {
433 			die("malloc of %d bytes for strtab failed\n",
434 				sec->shdr.sh_size);
435 		}
436 		if (fseek(fp, sec->shdr.sh_offset, SEEK_SET) < 0) {
437 			die("Seek to %d failed: %s\n",
438 				sec->shdr.sh_offset, strerror(errno));
439 		}
440 		if (fread(sec->strtab, 1, sec->shdr.sh_size, fp)
441 		    != sec->shdr.sh_size) {
442 			die("Cannot read symbol table: %s\n",
443 				strerror(errno));
444 		}
445 	}
446 }
447 
448 static void read_symtabs(FILE *fp)
449 {
450 	int i,j;
451 	for (i = 0; i < ehdr.e_shnum; i++) {
452 		struct section *sec = &secs[i];
453 		if (sec->shdr.sh_type != SHT_SYMTAB) {
454 			continue;
455 		}
456 		sec->symtab = malloc(sec->shdr.sh_size);
457 		if (!sec->symtab) {
458 			die("malloc of %d bytes for symtab failed\n",
459 				sec->shdr.sh_size);
460 		}
461 		if (fseek(fp, sec->shdr.sh_offset, SEEK_SET) < 0) {
462 			die("Seek to %d failed: %s\n",
463 				sec->shdr.sh_offset, strerror(errno));
464 		}
465 		if (fread(sec->symtab, 1, sec->shdr.sh_size, fp)
466 		    != sec->shdr.sh_size) {
467 			die("Cannot read symbol table: %s\n",
468 				strerror(errno));
469 		}
470 		for (j = 0; j < sec->shdr.sh_size/sizeof(Elf_Sym); j++) {
471 			Elf_Sym *sym = &sec->symtab[j];
472 			sym->st_name  = elf_word_to_cpu(sym->st_name);
473 			sym->st_value = elf_addr_to_cpu(sym->st_value);
474 			sym->st_size  = elf_xword_to_cpu(sym->st_size);
475 			sym->st_shndx = elf_half_to_cpu(sym->st_shndx);
476 		}
477 	}
478 }
479 
480 
481 static void read_relocs(FILE *fp)
482 {
483 	int i,j;
484 	for (i = 0; i < ehdr.e_shnum; i++) {
485 		struct section *sec = &secs[i];
486 		if (sec->shdr.sh_type != SHT_REL_TYPE) {
487 			continue;
488 		}
489 		sec->reltab = malloc(sec->shdr.sh_size);
490 		if (!sec->reltab) {
491 			die("malloc of %d bytes for relocs failed\n",
492 				sec->shdr.sh_size);
493 		}
494 		if (fseek(fp, sec->shdr.sh_offset, SEEK_SET) < 0) {
495 			die("Seek to %d failed: %s\n",
496 				sec->shdr.sh_offset, strerror(errno));
497 		}
498 		if (fread(sec->reltab, 1, sec->shdr.sh_size, fp)
499 		    != sec->shdr.sh_size) {
500 			die("Cannot read symbol table: %s\n",
501 				strerror(errno));
502 		}
503 		for (j = 0; j < sec->shdr.sh_size/sizeof(Elf_Rel); j++) {
504 			Elf_Rel *rel = &sec->reltab[j];
505 			rel->r_offset = elf_addr_to_cpu(rel->r_offset);
506 			rel->r_info   = elf_xword_to_cpu(rel->r_info);
507 #if (SHT_REL_TYPE == SHT_RELA)
508 			rel->r_addend = elf_xword_to_cpu(rel->r_addend);
509 #endif
510 		}
511 	}
512 }
513 
514 
515 static void print_absolute_symbols(void)
516 {
517 	int i;
518 	const char *format;
519 
520 	if (ELF_BITS == 64)
521 		format = "%5d %016"PRIx64" %5"PRId64" %10s %10s %12s %s\n";
522 	else
523 		format = "%5d %08"PRIx32"  %5"PRId32" %10s %10s %12s %s\n";
524 
525 	printf("Absolute symbols\n");
526 	printf(" Num:    Value Size  Type       Bind        Visibility  Name\n");
527 	for (i = 0; i < ehdr.e_shnum; i++) {
528 		struct section *sec = &secs[i];
529 		char *sym_strtab;
530 		int j;
531 
532 		if (sec->shdr.sh_type != SHT_SYMTAB) {
533 			continue;
534 		}
535 		sym_strtab = sec->link->strtab;
536 		for (j = 0; j < sec->shdr.sh_size/sizeof(Elf_Sym); j++) {
537 			Elf_Sym *sym;
538 			const char *name;
539 			sym = &sec->symtab[j];
540 			name = sym_name(sym_strtab, sym);
541 			if (sym->st_shndx != SHN_ABS) {
542 				continue;
543 			}
544 			printf(format,
545 				j, sym->st_value, sym->st_size,
546 				sym_type(ELF_ST_TYPE(sym->st_info)),
547 				sym_bind(ELF_ST_BIND(sym->st_info)),
548 				sym_visibility(ELF_ST_VISIBILITY(sym->st_other)),
549 				name);
550 		}
551 	}
552 	printf("\n");
553 }
554 
555 static void print_absolute_relocs(void)
556 {
557 	int i, printed = 0;
558 	const char *format;
559 
560 	if (ELF_BITS == 64)
561 		format = "%016"PRIx64" %016"PRIx64" %10s %016"PRIx64"  %s\n";
562 	else
563 		format = "%08"PRIx32" %08"PRIx32" %10s %08"PRIx32"  %s\n";
564 
565 	for (i = 0; i < ehdr.e_shnum; i++) {
566 		struct section *sec = &secs[i];
567 		struct section *sec_applies, *sec_symtab;
568 		char *sym_strtab;
569 		Elf_Sym *sh_symtab;
570 		int j;
571 		if (sec->shdr.sh_type != SHT_REL_TYPE) {
572 			continue;
573 		}
574 		sec_symtab  = sec->link;
575 		sec_applies = &secs[sec->shdr.sh_info];
576 		if (!(sec_applies->shdr.sh_flags & SHF_ALLOC)) {
577 			continue;
578 		}
579 		sh_symtab  = sec_symtab->symtab;
580 		sym_strtab = sec_symtab->link->strtab;
581 		for (j = 0; j < sec->shdr.sh_size/sizeof(Elf_Rel); j++) {
582 			Elf_Rel *rel;
583 			Elf_Sym *sym;
584 			const char *name;
585 			rel = &sec->reltab[j];
586 			sym = &sh_symtab[ELF_R_SYM(rel->r_info)];
587 			name = sym_name(sym_strtab, sym);
588 			if (sym->st_shndx != SHN_ABS) {
589 				continue;
590 			}
591 
592 			/* Absolute symbols are not relocated if bzImage is
593 			 * loaded at a non-compiled address. Display a warning
594 			 * to user at compile time about the absolute
595 			 * relocations present.
596 			 *
597 			 * User need to audit the code to make sure
598 			 * some symbols which should have been section
599 			 * relative have not become absolute because of some
600 			 * linker optimization or wrong programming usage.
601 			 *
602 			 * Before warning check if this absolute symbol
603 			 * relocation is harmless.
604 			 */
605 			if (is_reloc(S_ABS, name) || is_reloc(S_REL, name))
606 				continue;
607 
608 			if (!printed) {
609 				printf("WARNING: Absolute relocations"
610 					" present\n");
611 				printf("Offset     Info     Type     Sym.Value "
612 					"Sym.Name\n");
613 				printed = 1;
614 			}
615 
616 			printf(format,
617 				rel->r_offset,
618 				rel->r_info,
619 				rel_type(ELF_R_TYPE(rel->r_info)),
620 				sym->st_value,
621 				name);
622 		}
623 	}
624 
625 	if (printed)
626 		printf("\n");
627 }
628 
629 static void add_reloc(struct relocs *r, uint32_t offset)
630 {
631 	if (r->count == r->size) {
632 		unsigned long newsize = r->size + 50000;
633 		void *mem = realloc(r->offset, newsize * sizeof(r->offset[0]));
634 
635 		if (!mem)
636 			die("realloc of %ld entries for relocs failed\n",
637                                 newsize);
638 		r->offset = mem;
639 		r->size = newsize;
640 	}
641 	r->offset[r->count++] = offset;
642 }
643 
644 static void walk_relocs(int (*process)(struct section *sec, Elf_Rel *rel,
645 			Elf_Sym *sym, const char *symname))
646 {
647 	int i;
648 	/* Walk through the relocations */
649 	for (i = 0; i < ehdr.e_shnum; i++) {
650 		char *sym_strtab;
651 		Elf_Sym *sh_symtab;
652 		struct section *sec_applies, *sec_symtab;
653 		int j;
654 		struct section *sec = &secs[i];
655 
656 		if (sec->shdr.sh_type != SHT_REL_TYPE) {
657 			continue;
658 		}
659 		sec_symtab  = sec->link;
660 		sec_applies = &secs[sec->shdr.sh_info];
661 		if (!(sec_applies->shdr.sh_flags & SHF_ALLOC)) {
662 			continue;
663 		}
664 		sh_symtab = sec_symtab->symtab;
665 		sym_strtab = sec_symtab->link->strtab;
666 		for (j = 0; j < sec->shdr.sh_size/sizeof(Elf_Rel); j++) {
667 			Elf_Rel *rel = &sec->reltab[j];
668 			Elf_Sym *sym = &sh_symtab[ELF_R_SYM(rel->r_info)];
669 			const char *symname = sym_name(sym_strtab, sym);
670 
671 			process(sec, rel, sym, symname);
672 		}
673 	}
674 }
675 
676 /*
677  * The .data..percpu section is a special case for x86_64 SMP kernels.
678  * It is used to initialize the actual per_cpu areas and to provide
679  * definitions for the per_cpu variables that correspond to their offsets
680  * within the percpu area. Since the values of all of the symbols need
681  * to be offsets from the start of the per_cpu area the virtual address
682  * (sh_addr) of .data..percpu is 0 in SMP kernels.
683  *
684  * This means that:
685  *
686  *	Relocations that reference symbols in the per_cpu area do not
687  *	need further relocation (since the value is an offset relative
688  *	to the start of the per_cpu area that does not change).
689  *
690  *	Relocations that apply to the per_cpu area need to have their
691  *	offset adjusted by by the value of __per_cpu_load to make them
692  *	point to the correct place in the loaded image (because the
693  *	virtual address of .data..percpu is 0).
694  *
695  * For non SMP kernels .data..percpu is linked as part of the normal
696  * kernel data and does not require special treatment.
697  *
698  */
699 static int per_cpu_shndx	= -1;
700 Elf_Addr per_cpu_load_addr;
701 
702 static void percpu_init(void)
703 {
704 	int i;
705 	for (i = 0; i < ehdr.e_shnum; i++) {
706 		ElfW(Sym) *sym;
707 		if (strcmp(sec_name(i), ".data..percpu"))
708 			continue;
709 
710 		if (secs[i].shdr.sh_addr != 0)	/* non SMP kernel */
711 			return;
712 
713 		sym = sym_lookup("__per_cpu_load");
714 		if (!sym)
715 			die("can't find __per_cpu_load\n");
716 
717 		per_cpu_shndx = i;
718 		per_cpu_load_addr = sym->st_value;
719 		return;
720 	}
721 }
722 
723 #if ELF_BITS == 64
724 
725 /*
726  * Check to see if a symbol lies in the .data..percpu section.
727  * For some as yet not understood reason the "__init_begin"
728  * symbol which immediately preceeds the .data..percpu section
729  * also shows up as it it were part of it so we do an explict
730  * check for that symbol name and ignore it.
731  */
732 static int is_percpu_sym(ElfW(Sym) *sym, const char *symname)
733 {
734 	return (sym->st_shndx == per_cpu_shndx) &&
735 		strcmp(symname, "__init_begin");
736 }
737 
738 
739 static int do_reloc64(struct section *sec, Elf_Rel *rel, ElfW(Sym) *sym,
740 		      const char *symname)
741 {
742 	unsigned r_type = ELF64_R_TYPE(rel->r_info);
743 	ElfW(Addr) offset = rel->r_offset;
744 	int shn_abs = (sym->st_shndx == SHN_ABS) && !is_reloc(S_REL, symname);
745 
746 	if (sym->st_shndx == SHN_UNDEF)
747 		return 0;
748 
749 	/*
750 	 * Adjust the offset if this reloc applies to the percpu section.
751 	 */
752 	if (sec->shdr.sh_info == per_cpu_shndx)
753 		offset += per_cpu_load_addr;
754 
755 	switch (r_type) {
756 	case R_X86_64_NONE:
757 	case R_X86_64_PC32:
758 		/*
759 		 * NONE can be ignored and PC relative relocations don't
760 		 * need to be adjusted.
761 		 */
762 		break;
763 
764 	case R_X86_64_32:
765 	case R_X86_64_32S:
766 	case R_X86_64_64:
767 		/*
768 		 * References to the percpu area don't need to be adjusted.
769 		 */
770 		if (is_percpu_sym(sym, symname))
771 			break;
772 
773 		if (shn_abs) {
774 			/*
775 			 * Whitelisted absolute symbols do not require
776 			 * relocation.
777 			 */
778 			if (is_reloc(S_ABS, symname))
779 				break;
780 
781 			die("Invalid absolute %s relocation: %s\n",
782 			    rel_type(r_type), symname);
783 			break;
784 		}
785 
786 		/*
787 		 * Relocation offsets for 64 bit kernels are output
788 		 * as 32 bits and sign extended back to 64 bits when
789 		 * the relocations are processed.
790 		 * Make sure that the offset will fit.
791 		 */
792 		if ((int32_t)offset != (int64_t)offset)
793 			die("Relocation offset doesn't fit in 32 bits\n");
794 
795 		if (r_type == R_X86_64_64)
796 			add_reloc(&relocs64, offset);
797 		else
798 			add_reloc(&relocs32, offset);
799 		break;
800 
801 	default:
802 		die("Unsupported relocation type: %s (%d)\n",
803 		    rel_type(r_type), r_type);
804 		break;
805 	}
806 
807 	return 0;
808 }
809 
810 #else
811 
812 static int do_reloc32(struct section *sec, Elf_Rel *rel, Elf_Sym *sym,
813 		      const char *symname)
814 {
815 	unsigned r_type = ELF32_R_TYPE(rel->r_info);
816 	int shn_abs = (sym->st_shndx == SHN_ABS) && !is_reloc(S_REL, symname);
817 
818 	switch (r_type) {
819 	case R_386_NONE:
820 	case R_386_PC32:
821 	case R_386_PC16:
822 	case R_386_PC8:
823 		/*
824 		 * NONE can be ignored and PC relative relocations don't
825 		 * need to be adjusted.
826 		 */
827 		break;
828 
829 	case R_386_32:
830 		if (shn_abs) {
831 			/*
832 			 * Whitelisted absolute symbols do not require
833 			 * relocation.
834 			 */
835 			if (is_reloc(S_ABS, symname))
836 				break;
837 
838 			die("Invalid absolute %s relocation: %s\n",
839 			    rel_type(r_type), symname);
840 			break;
841 		}
842 
843 		add_reloc(&relocs32, rel->r_offset);
844 		break;
845 
846 	default:
847 		die("Unsupported relocation type: %s (%d)\n",
848 		    rel_type(r_type), r_type);
849 		break;
850 	}
851 
852 	return 0;
853 }
854 
855 static int do_reloc_real(struct section *sec, Elf_Rel *rel, Elf_Sym *sym,
856 			 const char *symname)
857 {
858 	unsigned r_type = ELF32_R_TYPE(rel->r_info);
859 	int shn_abs = (sym->st_shndx == SHN_ABS) && !is_reloc(S_REL, symname);
860 
861 	switch (r_type) {
862 	case R_386_NONE:
863 	case R_386_PC32:
864 	case R_386_PC16:
865 	case R_386_PC8:
866 		/*
867 		 * NONE can be ignored and PC relative relocations don't
868 		 * need to be adjusted.
869 		 */
870 		break;
871 
872 	case R_386_16:
873 		if (shn_abs) {
874 			/*
875 			 * Whitelisted absolute symbols do not require
876 			 * relocation.
877 			 */
878 			if (is_reloc(S_ABS, symname))
879 				break;
880 
881 			if (is_reloc(S_SEG, symname)) {
882 				add_reloc(&relocs16, rel->r_offset);
883 				break;
884 			}
885 		} else {
886 			if (!is_reloc(S_LIN, symname))
887 				break;
888 		}
889 		die("Invalid %s %s relocation: %s\n",
890 		    shn_abs ? "absolute" : "relative",
891 		    rel_type(r_type), symname);
892 		break;
893 
894 	case R_386_32:
895 		if (shn_abs) {
896 			/*
897 			 * Whitelisted absolute symbols do not require
898 			 * relocation.
899 			 */
900 			if (is_reloc(S_ABS, symname))
901 				break;
902 
903 			if (is_reloc(S_REL, symname)) {
904 				add_reloc(&relocs32, rel->r_offset);
905 				break;
906 			}
907 		} else {
908 			if (is_reloc(S_LIN, symname))
909 				add_reloc(&relocs32, rel->r_offset);
910 			break;
911 		}
912 		die("Invalid %s %s relocation: %s\n",
913 		    shn_abs ? "absolute" : "relative",
914 		    rel_type(r_type), symname);
915 		break;
916 
917 	default:
918 		die("Unsupported relocation type: %s (%d)\n",
919 		    rel_type(r_type), r_type);
920 		break;
921 	}
922 
923 	return 0;
924 }
925 
926 #endif
927 
928 static int cmp_relocs(const void *va, const void *vb)
929 {
930 	const uint32_t *a, *b;
931 	a = va; b = vb;
932 	return (*a == *b)? 0 : (*a > *b)? 1 : -1;
933 }
934 
935 static void sort_relocs(struct relocs *r)
936 {
937 	qsort(r->offset, r->count, sizeof(r->offset[0]), cmp_relocs);
938 }
939 
940 static int write32(uint32_t v, FILE *f)
941 {
942 	unsigned char buf[4];
943 
944 	put_unaligned_le32(v, buf);
945 	return fwrite(buf, 1, 4, f) == 4 ? 0 : -1;
946 }
947 
948 static int write32_as_text(uint32_t v, FILE *f)
949 {
950 	return fprintf(f, "\t.long 0x%08"PRIx32"\n", v) > 0 ? 0 : -1;
951 }
952 
953 static void emit_relocs(int as_text, int use_real_mode)
954 {
955 	int i;
956 	int (*write_reloc)(uint32_t, FILE *) = write32;
957 	int (*do_reloc)(struct section *sec, Elf_Rel *rel, Elf_Sym *sym,
958 			const char *symname);
959 
960 #if ELF_BITS == 64
961 	if (!use_real_mode)
962 		do_reloc = do_reloc64;
963 	else
964 		die("--realmode not valid for a 64-bit ELF file");
965 #else
966 	if (!use_real_mode)
967 		do_reloc = do_reloc32;
968 	else
969 		do_reloc = do_reloc_real;
970 #endif
971 
972 	/* Collect up the relocations */
973 	walk_relocs(do_reloc);
974 
975 	if (relocs16.count && !use_real_mode)
976 		die("Segment relocations found but --realmode not specified\n");
977 
978 	/* Order the relocations for more efficient processing */
979 	sort_relocs(&relocs16);
980 	sort_relocs(&relocs32);
981 	sort_relocs(&relocs64);
982 
983 	/* Print the relocations */
984 	if (as_text) {
985 		/* Print the relocations in a form suitable that
986 		 * gas will like.
987 		 */
988 		printf(".section \".data.reloc\",\"a\"\n");
989 		printf(".balign 4\n");
990 		write_reloc = write32_as_text;
991 	}
992 
993 	if (use_real_mode) {
994 		write_reloc(relocs16.count, stdout);
995 		for (i = 0; i < relocs16.count; i++)
996 			write_reloc(relocs16.offset[i], stdout);
997 
998 		write_reloc(relocs32.count, stdout);
999 		for (i = 0; i < relocs32.count; i++)
1000 			write_reloc(relocs32.offset[i], stdout);
1001 	} else {
1002 		if (ELF_BITS == 64) {
1003 			/* Print a stop */
1004 			write_reloc(0, stdout);
1005 
1006 			/* Now print each relocation */
1007 			for (i = 0; i < relocs64.count; i++)
1008 				write_reloc(relocs64.offset[i], stdout);
1009 		}
1010 
1011 		/* Print a stop */
1012 		write_reloc(0, stdout);
1013 
1014 		/* Now print each relocation */
1015 		for (i = 0; i < relocs32.count; i++)
1016 			write_reloc(relocs32.offset[i], stdout);
1017 	}
1018 }
1019 
1020 #if ELF_BITS == 64
1021 # define process process_64
1022 #else
1023 # define process process_32
1024 #endif
1025 
1026 void process(FILE *fp, int use_real_mode, int as_text,
1027 	     int show_absolute_syms, int show_absolute_relocs)
1028 {
1029 	regex_init(use_real_mode);
1030 	read_ehdr(fp);
1031 	read_shdrs(fp);
1032 	read_strtabs(fp);
1033 	read_symtabs(fp);
1034 	read_relocs(fp);
1035 	if (ELF_BITS == 64)
1036 		percpu_init();
1037 	if (show_absolute_syms) {
1038 		print_absolute_symbols();
1039 		return;
1040 	}
1041 	if (show_absolute_relocs) {
1042 		print_absolute_relocs();
1043 		return;
1044 	}
1045 	emit_relocs(as_text, use_real_mode);
1046 }
1047