1/*
2 * recordmcount.c: construct a table of the locations of calls to 'mcount'
3 * so that ftrace can find them quickly.
4 * Copyright 2009 John F. Reiser <jreiser@BitWagon.com>.  All rights reserved.
5 * Licensed under the GNU General Public License, version 2 (GPLv2).
6 *
7 * Restructured to fit Linux format, as well as other updates:
8 *  Copyright 2010 Steven Rostedt <srostedt@redhat.com>, Red Hat Inc.
9 */
10
11/*
12 * Strategy: alter the .o file in-place.
13 *
14 * Append a new STRTAB that has the new section names, followed by a new array
15 * ElfXX_Shdr[] that has the new section headers, followed by the section
16 * contents for __mcount_loc and its relocations.  The old shstrtab strings,
17 * and the old ElfXX_Shdr[] array, remain as "garbage" (commonly, a couple
18 * kilobytes.)  Subsequent processing by /bin/ld (or the kernel module loader)
19 * will ignore the garbage regions, because they are not designated by the
20 * new .e_shoff nor the new ElfXX_Shdr[].  [In order to remove the garbage,
21 * then use "ld -r" to create a new file that omits the garbage.]
22 */
23
24#include <sys/types.h>
25#include <sys/mman.h>
26#include <sys/stat.h>
27#include <getopt.h>
28#include <elf.h>
29#include <fcntl.h>
30#include <setjmp.h>
31#include <stdio.h>
32#include <stdlib.h>
33#include <string.h>
34#include <unistd.h>
35
36#ifndef EM_METAG
37/* Remove this when these make it to the standard system elf.h. */
38#define EM_METAG      174
39#define R_METAG_ADDR32                   2
40#define R_METAG_NONE                     3
41#endif
42
43#ifndef EM_AARCH64
44#define EM_AARCH64	183
45#define R_AARCH64_NONE		0
46#define R_AARCH64_ABS64	257
47#endif
48
49static int fd_map;	/* File descriptor for file being modified. */
50static int mmap_failed; /* Boolean flag. */
51static void *ehdr_curr; /* current ElfXX_Ehdr *  for resource cleanup */
52static char gpfx;	/* prefix for global symbol name (sometimes '_') */
53static struct stat sb;	/* Remember .st_size, etc. */
54static jmp_buf jmpenv;	/* setjmp/longjmp per-file error escape */
55static const char *altmcount;	/* alternate mcount symbol name */
56static int warn_on_notrace_sect; /* warn when section has mcount not being recorded */
57
58/* setjmp() return values */
59enum {
60	SJ_SETJMP = 0,  /* hardwired first return */
61	SJ_FAIL,
62	SJ_SUCCEED
63};
64
65/* Per-file resource cleanup when multiple files. */
66static void
67cleanup(void)
68{
69	if (!mmap_failed)
70		munmap(ehdr_curr, sb.st_size);
71	else
72		free(ehdr_curr);
73	close(fd_map);
74}
75
76static void __attribute__((noreturn))
77fail_file(void)
78{
79	cleanup();
80	longjmp(jmpenv, SJ_FAIL);
81}
82
83static void __attribute__((noreturn))
84succeed_file(void)
85{
86	cleanup();
87	longjmp(jmpenv, SJ_SUCCEED);
88}
89
90/* ulseek, uread, ...:  Check return value for errors. */
91
92static off_t
93ulseek(int const fd, off_t const offset, int const whence)
94{
95	off_t const w = lseek(fd, offset, whence);
96	if (w == (off_t)-1) {
97		perror("lseek");
98		fail_file();
99	}
100	return w;
101}
102
103static size_t
104uread(int const fd, void *const buf, size_t const count)
105{
106	size_t const n = read(fd, buf, count);
107	if (n != count) {
108		perror("read");
109		fail_file();
110	}
111	return n;
112}
113
114static size_t
115uwrite(int const fd, void const *const buf, size_t const count)
116{
117	size_t const n = write(fd, buf, count);
118	if (n != count) {
119		perror("write");
120		fail_file();
121	}
122	return n;
123}
124
125static void *
126umalloc(size_t size)
127{
128	void *const addr = malloc(size);
129	if (addr == 0) {
130		fprintf(stderr, "malloc failed: %zu bytes\n", size);
131		fail_file();
132	}
133	return addr;
134}
135
136static unsigned char ideal_nop5_x86_64[5] = { 0x0f, 0x1f, 0x44, 0x00, 0x00 };
137static unsigned char ideal_nop5_x86_32[5] = { 0x3e, 0x8d, 0x74, 0x26, 0x00 };
138static unsigned char *ideal_nop;
139
140static char rel_type_nop;
141
142static int (*make_nop)(void *map, size_t const offset);
143
144static int make_nop_x86(void *map, size_t const offset)
145{
146	uint32_t *ptr;
147	unsigned char *op;
148
149	/* Confirm we have 0xe8 0x0 0x0 0x0 0x0 */
150	ptr = map + offset;
151	if (*ptr != 0)
152		return -1;
153
154	op = map + offset - 1;
155	if (*op != 0xe8)
156		return -1;
157
158	/* convert to nop */
159	ulseek(fd_map, offset - 1, SEEK_SET);
160	uwrite(fd_map, ideal_nop, 5);
161	return 0;
162}
163
164static unsigned char ideal_nop4_arm64[4] = {0x1f, 0x20, 0x03, 0xd5};
165static int make_nop_arm64(void *map, size_t const offset)
166{
167	uint32_t *ptr;
168
169	ptr = map + offset;
170	/* bl <_mcount> is 0x94000000 before relocation */
171	if (*ptr != 0x94000000)
172		return -1;
173
174	/* Convert to nop */
175	ulseek(fd_map, offset, SEEK_SET);
176	uwrite(fd_map, ideal_nop, 4);
177	return 0;
178}
179
180/*
181 * Get the whole file as a programming convenience in order to avoid
182 * malloc+lseek+read+free of many pieces.  If successful, then mmap
183 * avoids copying unused pieces; else just read the whole file.
184 * Open for both read and write; new info will be appended to the file.
185 * Use MAP_PRIVATE so that a few changes to the in-memory ElfXX_Ehdr
186 * do not propagate to the file until an explicit overwrite at the last.
187 * This preserves most aspects of consistency (all except .st_size)
188 * for simultaneous readers of the file while we are appending to it.
189 * However, multiple writers still are bad.  We choose not to use
190 * locking because it is expensive and the use case of kernel build
191 * makes multiple writers unlikely.
192 */
193static void *mmap_file(char const *fname)
194{
195	void *addr;
196
197	fd_map = open(fname, O_RDWR);
198	if (fd_map < 0 || fstat(fd_map, &sb) < 0) {
199		perror(fname);
200		fail_file();
201	}
202	if (!S_ISREG(sb.st_mode)) {
203		fprintf(stderr, "not a regular file: %s\n", fname);
204		fail_file();
205	}
206	addr = mmap(0, sb.st_size, PROT_READ|PROT_WRITE, MAP_PRIVATE,
207		    fd_map, 0);
208	mmap_failed = 0;
209	if (addr == MAP_FAILED) {
210		mmap_failed = 1;
211		addr = umalloc(sb.st_size);
212		uread(fd_map, addr, sb.st_size);
213	}
214	return addr;
215}
216
217/* w8rev, w8nat, ...: Handle endianness. */
218
219static uint64_t w8rev(uint64_t const x)
220{
221	return   ((0xff & (x >> (0 * 8))) << (7 * 8))
222	       | ((0xff & (x >> (1 * 8))) << (6 * 8))
223	       | ((0xff & (x >> (2 * 8))) << (5 * 8))
224	       | ((0xff & (x >> (3 * 8))) << (4 * 8))
225	       | ((0xff & (x >> (4 * 8))) << (3 * 8))
226	       | ((0xff & (x >> (5 * 8))) << (2 * 8))
227	       | ((0xff & (x >> (6 * 8))) << (1 * 8))
228	       | ((0xff & (x >> (7 * 8))) << (0 * 8));
229}
230
231static uint32_t w4rev(uint32_t const x)
232{
233	return   ((0xff & (x >> (0 * 8))) << (3 * 8))
234	       | ((0xff & (x >> (1 * 8))) << (2 * 8))
235	       | ((0xff & (x >> (2 * 8))) << (1 * 8))
236	       | ((0xff & (x >> (3 * 8))) << (0 * 8));
237}
238
239static uint32_t w2rev(uint16_t const x)
240{
241	return   ((0xff & (x >> (0 * 8))) << (1 * 8))
242	       | ((0xff & (x >> (1 * 8))) << (0 * 8));
243}
244
245static uint64_t w8nat(uint64_t const x)
246{
247	return x;
248}
249
250static uint32_t w4nat(uint32_t const x)
251{
252	return x;
253}
254
255static uint32_t w2nat(uint16_t const x)
256{
257	return x;
258}
259
260static uint64_t (*w8)(uint64_t);
261static uint32_t (*w)(uint32_t);
262static uint32_t (*w2)(uint16_t);
263
264/* Names of the sections that could contain calls to mcount. */
265static int
266is_mcounted_section_name(char const *const txtname)
267{
268	return strcmp(".text",           txtname) == 0 ||
269		strcmp(".ref.text",      txtname) == 0 ||
270		strcmp(".sched.text",    txtname) == 0 ||
271		strcmp(".spinlock.text", txtname) == 0 ||
272		strcmp(".irqentry.text", txtname) == 0 ||
273		strcmp(".kprobes.text", txtname) == 0 ||
274		strcmp(".text.unlikely", txtname) == 0;
275}
276
277/* 32 bit and 64 bit are very similar */
278#include "recordmcount.h"
279#define RECORD_MCOUNT_64
280#include "recordmcount.h"
281
282/* 64-bit EM_MIPS has weird ELF64_Rela.r_info.
283 * http://techpubs.sgi.com/library/manuals/4000/007-4658-001/pdf/007-4658-001.pdf
284 * We interpret Table 29 Relocation Operation (Elf64_Rel, Elf64_Rela) [p.40]
285 * to imply the order of the members; the spec does not say so.
286 *	typedef unsigned char Elf64_Byte;
287 * fails on MIPS64 because their <elf.h> already has it!
288 */
289
290typedef uint8_t myElf64_Byte;		/* Type for a 8-bit quantity.  */
291
292union mips_r_info {
293	Elf64_Xword r_info;
294	struct {
295		Elf64_Word r_sym;		/* Symbol index.  */
296		myElf64_Byte r_ssym;		/* Special symbol.  */
297		myElf64_Byte r_type3;		/* Third relocation.  */
298		myElf64_Byte r_type2;		/* Second relocation.  */
299		myElf64_Byte r_type;		/* First relocation.  */
300	} r_mips;
301};
302
303static uint64_t MIPS64_r_sym(Elf64_Rel const *rp)
304{
305	return w(((union mips_r_info){ .r_info = rp->r_info }).r_mips.r_sym);
306}
307
308static void MIPS64_r_info(Elf64_Rel *const rp, unsigned sym, unsigned type)
309{
310	rp->r_info = ((union mips_r_info){
311		.r_mips = { .r_sym = w(sym), .r_type = type }
312	}).r_info;
313}
314
315static void
316do_file(char const *const fname)
317{
318	Elf32_Ehdr *const ehdr = mmap_file(fname);
319	unsigned int reltype = 0;
320
321	ehdr_curr = ehdr;
322	w = w4nat;
323	w2 = w2nat;
324	w8 = w8nat;
325	switch (ehdr->e_ident[EI_DATA]) {
326		static unsigned int const endian = 1;
327	default:
328		fprintf(stderr, "unrecognized ELF data encoding %d: %s\n",
329			ehdr->e_ident[EI_DATA], fname);
330		fail_file();
331		break;
332	case ELFDATA2LSB:
333		if (*(unsigned char const *)&endian != 1) {
334			/* main() is big endian, file.o is little endian. */
335			w = w4rev;
336			w2 = w2rev;
337			w8 = w8rev;
338		}
339		break;
340	case ELFDATA2MSB:
341		if (*(unsigned char const *)&endian != 0) {
342			/* main() is little endian, file.o is big endian. */
343			w = w4rev;
344			w2 = w2rev;
345			w8 = w8rev;
346		}
347		break;
348	}  /* end switch */
349	if (memcmp(ELFMAG, ehdr->e_ident, SELFMAG) != 0
350	||  w2(ehdr->e_type) != ET_REL
351	||  ehdr->e_ident[EI_VERSION] != EV_CURRENT) {
352		fprintf(stderr, "unrecognized ET_REL file %s\n", fname);
353		fail_file();
354	}
355
356	gpfx = 0;
357	switch (w2(ehdr->e_machine)) {
358	default:
359		fprintf(stderr, "unrecognized e_machine %d %s\n",
360			w2(ehdr->e_machine), fname);
361		fail_file();
362		break;
363	case EM_386:
364		reltype = R_386_32;
365		make_nop = make_nop_x86;
366		ideal_nop = ideal_nop5_x86_32;
367		mcount_adjust_32 = -1;
368		break;
369	case EM_ARM:	 reltype = R_ARM_ABS32;
370			 altmcount = "__gnu_mcount_nc";
371			 break;
372	case EM_AARCH64:
373			reltype = R_AARCH64_ABS64;
374			make_nop = make_nop_arm64;
375			rel_type_nop = R_AARCH64_NONE;
376			ideal_nop = ideal_nop4_arm64;
377			gpfx = '_';
378			break;
379	case EM_IA_64:	 reltype = R_IA64_IMM64;   gpfx = '_'; break;
380	case EM_METAG:	 reltype = R_METAG_ADDR32;
381			 altmcount = "_mcount_wrapper";
382			 rel_type_nop = R_METAG_NONE;
383			 /* We happen to have the same requirement as MIPS */
384			 is_fake_mcount32 = MIPS32_is_fake_mcount;
385			 break;
386	case EM_MIPS:	 /* reltype: e_class    */ gpfx = '_'; break;
387	case EM_PPC:	 reltype = R_PPC_ADDR32;   gpfx = '_'; break;
388	case EM_PPC64:	 reltype = R_PPC64_ADDR64; gpfx = '_'; break;
389	case EM_S390:    /* reltype: e_class    */ gpfx = '_'; break;
390	case EM_SH:	 reltype = R_SH_DIR32;                 break;
391	case EM_SPARCV9: reltype = R_SPARC_64;     gpfx = '_'; break;
392	case EM_X86_64:
393		make_nop = make_nop_x86;
394		ideal_nop = ideal_nop5_x86_64;
395		reltype = R_X86_64_64;
396		mcount_adjust_64 = -1;
397		break;
398	}  /* end switch */
399
400	switch (ehdr->e_ident[EI_CLASS]) {
401	default:
402		fprintf(stderr, "unrecognized ELF class %d %s\n",
403			ehdr->e_ident[EI_CLASS], fname);
404		fail_file();
405		break;
406	case ELFCLASS32:
407		if (w2(ehdr->e_ehsize) != sizeof(Elf32_Ehdr)
408		||  w2(ehdr->e_shentsize) != sizeof(Elf32_Shdr)) {
409			fprintf(stderr,
410				"unrecognized ET_REL file: %s\n", fname);
411			fail_file();
412		}
413		if (w2(ehdr->e_machine) == EM_MIPS) {
414			reltype = R_MIPS_32;
415			is_fake_mcount32 = MIPS32_is_fake_mcount;
416		}
417		do32(ehdr, fname, reltype);
418		break;
419	case ELFCLASS64: {
420		Elf64_Ehdr *const ghdr = (Elf64_Ehdr *)ehdr;
421		if (w2(ghdr->e_ehsize) != sizeof(Elf64_Ehdr)
422		||  w2(ghdr->e_shentsize) != sizeof(Elf64_Shdr)) {
423			fprintf(stderr,
424				"unrecognized ET_REL file: %s\n", fname);
425			fail_file();
426		}
427		if (w2(ghdr->e_machine) == EM_S390) {
428			reltype = R_390_64;
429			mcount_adjust_64 = -14;
430		}
431		if (w2(ghdr->e_machine) == EM_MIPS) {
432			reltype = R_MIPS_64;
433			Elf64_r_sym = MIPS64_r_sym;
434			Elf64_r_info = MIPS64_r_info;
435			is_fake_mcount64 = MIPS64_is_fake_mcount;
436		}
437		do64(ghdr, fname, reltype);
438		break;
439	}
440	}  /* end switch */
441
442	cleanup();
443}
444
445int
446main(int argc, char *argv[])
447{
448	const char ftrace[] = "/ftrace.o";
449	int ftrace_size = sizeof(ftrace) - 1;
450	int n_error = 0;  /* gcc-4.3.0 false positive complaint */
451	int c;
452	int i;
453
454	while ((c = getopt(argc, argv, "w")) >= 0) {
455		switch (c) {
456		case 'w':
457			warn_on_notrace_sect = 1;
458			break;
459		default:
460			fprintf(stderr, "usage: recordmcount [-w] file.o...\n");
461			return 0;
462		}
463	}
464
465	if ((argc - optind) < 1) {
466		fprintf(stderr, "usage: recordmcount [-w] file.o...\n");
467		return 0;
468	}
469
470	/* Process each file in turn, allowing deep failure. */
471	for (i = optind; i < argc; i++) {
472		char *file = argv[i];
473		int const sjval = setjmp(jmpenv);
474		int len;
475
476		/*
477		 * The file kernel/trace/ftrace.o references the mcount
478		 * function but does not call it. Since ftrace.o should
479		 * not be traced anyway, we just skip it.
480		 */
481		len = strlen(file);
482		if (len >= ftrace_size &&
483		    strcmp(file + (len - ftrace_size), ftrace) == 0)
484			continue;
485
486		switch (sjval) {
487		default:
488			fprintf(stderr, "internal error: %s\n", file);
489			exit(1);
490			break;
491		case SJ_SETJMP:    /* normal sequence */
492			/* Avoid problems if early cleanup() */
493			fd_map = -1;
494			ehdr_curr = NULL;
495			mmap_failed = 1;
496			do_file(file);
497			break;
498		case SJ_FAIL:    /* error in do_file or below */
499			++n_error;
500			break;
501		case SJ_SUCCEED:    /* premature success */
502			/* do nothing */
503			break;
504		}  /* end switch */
505	}
506	return !!n_error;
507}
508