summaryrefslogtreecommitdiffstats
path: root/src/findtextrel.c
blob: 642c0237faa2bca8b5c7d6c245ec570d91604aa9 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
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
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
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
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
/* Locate source files or functions which caused text relocations.
   Copyright (C) 2005-2010, 2012, 2014 Red Hat, Inc.
   This file is part of elfutils.
   Written by Ulrich Drepper <drepper@redhat.com>, 2005.

   This file is free software; you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
   the Free Software Foundation; either version 3 of the License, or
   (at your option) any later version.

   elfutils is distributed in the hope that it will be useful, but
   WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.

   You should have received a copy of the GNU General Public License
   along with this program.  If not, see <http://www.gnu.org/licenses/>.  */

#ifdef HAVE_CONFIG_H
# include <config.h>
#endif

#include <argp.h>
#include <assert.h>
#include <errno.h>
#include <error.h>
#include <fcntl.h>
#include <gelf.h>
#include <libdw.h>
#include <libintl.h>
#include <locale.h>
#include <search.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

#include <printversion.h>


struct segments
{
  GElf_Addr from;
  GElf_Addr to;
};


/* Name and version of program.  */
ARGP_PROGRAM_VERSION_HOOK_DEF = print_version;

/* Bug report address.  */
ARGP_PROGRAM_BUG_ADDRESS_DEF = PACKAGE_BUGREPORT;

/* Values for the parameters which have no short form.  */
#define OPT_DEBUGINFO 0x100

/* Definitions of arguments for argp functions.  */
static const struct argp_option options[] =
{
  { NULL, 0, NULL, 0, N_("Input Selection:"), 0 },
  { "root", 'r', "PATH", 0, N_("Prepend PATH to all file names"), 0 },
  { "debuginfo", OPT_DEBUGINFO, "PATH", 0,
    N_("Use PATH as root of debuginfo hierarchy"), 0 },

  { NULL, 0, NULL, 0, N_("Miscellaneous:"), 0 },
  { NULL, 0, NULL, 0, NULL, 0 }
};

/* Short description of program.  */
static const char doc[] = N_("\
Locate source of text relocations in FILEs (a.out by default).");

/* Strings for arguments in help texts.  */
static const char args_doc[] = N_("[FILE...]");

/* Prototype for option handler.  */
static error_t parse_opt (int key, char *arg, struct argp_state *state);

/* Data structure to communicate with argp functions.  */
static struct argp argp =
{
  options, parse_opt, args_doc, doc, NULL, NULL, NULL
};


/* Print symbols in file named FNAME.  */
static int process_file (const char *fname, bool more_than_one);

/* Check for text relocations in the given file.  The segment
   information is known.  */
static void check_rel (size_t nsegments, struct segments segments[nsegments],
		       GElf_Addr addr, Elf *elf, Elf_Scn *symscn, Dwarf *dw,
		       const char *fname, bool more_than_one,
		       void **knownsrcs);



/* User-provided root directory.  */
static const char *rootdir = "/";

/* Root of debuginfo directory hierarchy.  */
static const char *debuginfo_root;


int
main (int argc, char *argv[])
{
  int remaining;
  int result = 0;

  /* Set locale.  */
  (void) setlocale (LC_ALL, "");

  /* Make sure the message catalog can be found.  */
  (void) bindtextdomain (PACKAGE_TARNAME, LOCALEDIR);

  /* Initialize the message catalog.  */
  (void) textdomain (PACKAGE_TARNAME);

  /* Parse and process arguments.  */
  (void) argp_parse (&argp, argc, argv, 0, &remaining, NULL);

  /* Tell the library which version we are expecting.  */
  elf_version (EV_CURRENT);

  /* If the user has not specified the root directory for the
     debuginfo hierarchy, we have to determine it ourselves.  */
  if (debuginfo_root == NULL)
    {
      // XXX The runtime should provide this information.
#if defined __ia64__ || defined __alpha__
      debuginfo_root = "/usr/lib/debug";
#else
      debuginfo_root = (sizeof (long int) == 4
			? "/usr/lib/debug" : "/usr/lib64/debug");
#endif
    }

  if (remaining == argc)
    result = process_file ("a.out", false);
  else
    {
      /* Process all the remaining files.  */
      const bool more_than_one = remaining + 1 < argc;

      do
	result |= process_file (argv[remaining], more_than_one);
      while (++remaining < argc);
    }

  return result;
}


/* Handle program arguments.  */
static error_t
parse_opt (int key, char *arg,
	   struct argp_state *state __attribute__ ((unused)))
{
  switch (key)
    {
    case 'r':
      rootdir = arg;
      break;

    case OPT_DEBUGINFO:
      debuginfo_root = arg;
      break;

    default:
      return ARGP_ERR_UNKNOWN;
    }
  return 0;
}


static void
noop (void *arg __attribute__ ((unused)))
{
}


static int
process_file (const char *fname, bool more_than_one)
{
  int result = 0;
  void *knownsrcs = NULL;

  size_t fname_len = strlen (fname);
  size_t rootdir_len = strlen (rootdir);
  const char *real_fname = fname;
  if (fname[0] == '/' && (rootdir[0] != '/' || rootdir[1] != '\0'))
    {
      /* Prepend the user-provided root directory.  */
      char *new_fname = alloca (rootdir_len + fname_len + 2);
      *((char *) mempcpy (stpcpy (mempcpy (new_fname, rootdir, rootdir_len),
				  "/"),
			  fname, fname_len)) = '\0';
      real_fname = new_fname;
    }

  int fd = open (real_fname, O_RDONLY | O_BINARY);
  if (fd == -1)
    {
      error (0, errno, gettext ("cannot open '%s'"), fname);
      return 1;
    }

  Elf *elf = elf_begin (fd, ELF_C_READ_MMAP, NULL);
  if (elf == NULL)
    {
      error (0, 0, gettext ("cannot create ELF descriptor for '%s': %s"),
	     fname, elf_errmsg (-1));
      goto err_close;
    }

  /* Make sure the file is a DSO.  */
  GElf_Ehdr ehdr_mem;
  GElf_Ehdr *ehdr = gelf_getehdr (elf, &ehdr_mem);
  if (ehdr == NULL)
    {
      error (0, 0, gettext ("cannot get ELF header '%s': %s"),
	     fname, elf_errmsg (-1));
    err_elf_close:
      elf_end (elf);
    err_close:
      close (fd);
      return 1;
    }

  if (ehdr->e_type != ET_DYN)
    {
      error (0, 0, gettext ("'%s' is not a DSO or PIE"), fname);
      goto err_elf_close;
    }

  /* Determine whether the DSO has text relocations at all and locate
     the symbol table.  */
  Elf_Scn *symscn = NULL;
  Elf_Scn *scn = NULL;
  bool seen_dynamic = false;
  bool have_textrel = false;
  while ((scn = elf_nextscn (elf, scn)) != NULL
	 && (!seen_dynamic || symscn == NULL))
    {
      /* Handle the section if it is a symbol table.  */
      GElf_Shdr shdr_mem;
      GElf_Shdr *shdr = gelf_getshdr (scn, &shdr_mem);

      if (shdr == NULL)
	{
	  error (0, 0,
		 gettext ("getting get section header of section %zu: %s"),
		 elf_ndxscn (scn), elf_errmsg (-1));
	  goto err_elf_close;
	}

      switch (shdr->sh_type)
	{
	case SHT_DYNAMIC:
	  if (!seen_dynamic)
	    {
	      seen_dynamic = true;

	      Elf_Data *data = elf_getdata (scn, NULL);

	      for (size_t cnt = 0; cnt < shdr->sh_size / shdr->sh_entsize;
		   ++cnt)
		{
		  GElf_Dyn dynmem;
		  GElf_Dyn *dyn;

		  dyn = gelf_getdyn (data, cnt, &dynmem);
		  if (dyn == NULL)
		    {
		      error (0, 0, gettext ("cannot read dynamic section: %s"),
			     elf_errmsg (-1));
		      goto err_elf_close;
		    }

		  if (dyn->d_tag == DT_TEXTREL
		      || (dyn->d_tag == DT_FLAGS
			  && (dyn->d_un.d_val & DF_TEXTREL) != 0))
		    have_textrel = true;
		}
	    }
	  break;

	case SHT_SYMTAB:
	  symscn = scn;
	  break;
	}
    }

  if (!have_textrel)
    {
      error (0, 0, gettext ("no text relocations reported in '%s'"), fname);
      goto err_elf_close;
    }

  int fd2 = -1;
  Elf *elf2 = NULL;
  /* Get the address ranges for the loaded segments.  */
  size_t nsegments_max = 10;
  size_t nsegments = 0;
  struct segments *segments
    = (struct segments *) malloc (nsegments_max * sizeof (segments[0]));
  if (segments == NULL)
    error (1, errno, gettext ("while reading ELF file"));

  size_t phnum;
  if (elf_getphdrnum (elf, &phnum) != 0)
    error (1, 0, gettext ("cannot get program header count: %s"),
           elf_errmsg (-1));


  for (size_t i = 0; i < phnum; ++i)
    {
      GElf_Phdr phdr_mem;
      GElf_Phdr *phdr = gelf_getphdr (elf, i, &phdr_mem);
      if (phdr == NULL)
	{
	  error (0, 0,
		 gettext ("cannot get program header index at offset %zd: %s"),
		 i, elf_errmsg (-1));
	  result = 1;
	  goto next;
	}

      if (phdr->p_type == PT_LOAD && (phdr->p_flags & PF_W) == 0)
	{
	  if (nsegments == nsegments_max)
	    {
	      nsegments_max *= 2;
	      segments
		= (struct segments *) realloc (segments,
					       nsegments_max
					       * sizeof (segments[0]));
	      if (segments == NULL)
		{
		  error (0, 0, gettext ("\
cannot get program header index at offset %zd: %s"),
			 i, elf_errmsg (-1));
		  result = 1;
		  goto next;
		}
	    }

	  segments[nsegments].from = phdr->p_vaddr;
	  segments[nsegments].to = phdr->p_vaddr + phdr->p_memsz;
	  ++nsegments;
	}
    }

  if (nsegments > 0)
    {

      Dwarf *dw = dwarf_begin_elf (elf, DWARF_C_READ, NULL);
      /* Look for debuginfo files if the information is not the in
	 opened file itself.  This makes only sense if the input file
	 is specified with an absolute path.  */
      if (dw == NULL && fname[0] == '/')
	{
	  size_t debuginfo_rootlen = strlen (debuginfo_root);
	  char *difname = (char *) alloca (rootdir_len + debuginfo_rootlen
					   + fname_len + 8);
	  strcpy (mempcpy (stpcpy (mempcpy (mempcpy (difname, rootdir,
						     rootdir_len),
					    debuginfo_root,
					    debuginfo_rootlen),
				   "/"),
			   fname, fname_len),
		  ".debug");

	  fd2 = open (difname, O_RDONLY | O_BINARY);
	  if (fd2 != -1
	      && (elf2 = elf_begin (fd2, ELF_C_READ_MMAP, NULL)) != NULL)
	    dw = dwarf_begin_elf (elf2, DWARF_C_READ, NULL);
	}

      /* Look at all relocations and determine which modify
	 write-protected segments.  */
      scn = NULL;
      while ((scn = elf_nextscn (elf, scn)) != NULL)
	{
	  /* Handle the section if it is a symbol table.  */
	  GElf_Shdr shdr_mem;
	  GElf_Shdr *shdr = gelf_getshdr (scn, &shdr_mem);

	  if (shdr == NULL)
	    {
	      error (0, 0,
		     gettext ("cannot get section header of section %zu: %s"),
		     elf_ndxscn (scn), elf_errmsg (-1));
	      result = 1;
	      goto next;
	    }

	  if ((shdr->sh_type == SHT_REL || shdr->sh_type == SHT_RELA)
	      && symscn == NULL)
	    {
	      symscn = elf_getscn (elf, shdr->sh_link);
	      if (symscn == NULL)
		{
		  error (0, 0, gettext ("\
cannot get symbol table section %zu in '%s': %s"),
			 (size_t) shdr->sh_link, fname, elf_errmsg (-1));
		  result = 1;
		  goto next;
		}
	    }

	  if (shdr->sh_type == SHT_REL)
	    {
	      Elf_Data *data = elf_getdata (scn, NULL);

	      for (int cnt = 0;
		   (size_t) cnt < shdr->sh_size / shdr->sh_entsize;
		   ++cnt)
		{
		  GElf_Rel rel_mem;
		  GElf_Rel *rel = gelf_getrel (data, cnt, &rel_mem);
		  if (rel == NULL)
		    {
		      error (0, 0, gettext ("\
cannot get relocation at index %d in section %zu in '%s': %s"),
			     cnt, elf_ndxscn (scn), fname, elf_errmsg (-1));
		      result = 1;
		      goto next;
		    }

		  check_rel (nsegments, segments, rel->r_offset, elf,
			     symscn, dw, fname, more_than_one, &knownsrcs);
		}
	    }
	  else if (shdr->sh_type == SHT_RELA)
	    {
	      Elf_Data *data = elf_getdata (scn, NULL);

	      for (int cnt = 0;
		   (size_t) cnt < shdr->sh_size / shdr->sh_entsize;
		   ++cnt)
		{
		  GElf_Rela rela_mem;
		  GElf_Rela *rela = gelf_getrela (data, cnt, &rela_mem);
		  if (rela == NULL)
		    {
		      error (0, 0, gettext ("\
cannot get relocation at index %d in section %zu in '%s': %s"),
			     cnt, elf_ndxscn (scn), fname, elf_errmsg (-1));
		      result = 1;
		      goto next;
		    }

		  check_rel (nsegments, segments, rela->r_offset, elf,
			     symscn, dw, fname, more_than_one, &knownsrcs);
		}
	    }
	}

      dwarf_end (dw);
    }

 next:
  elf_end (elf);
  elf_end (elf2);
  close (fd);
  if (fd2 != -1)
    close (fd2);

  free (segments);
  tdestroy (knownsrcs, noop);

  return result;
}


static int
ptrcompare (const void *p1, const void *p2)
{
  if ((uintptr_t) p1 < (uintptr_t) p2)
    return -1;
  if ((uintptr_t) p1 > (uintptr_t) p2)
    return 1;
  return 0;
}


static void
check_rel (size_t nsegments, struct segments segments[nsegments],
	   GElf_Addr addr, Elf *elf, Elf_Scn *symscn, Dwarf *dw,
	   const char *fname, bool more_than_one, void **knownsrcs)
{
  for (size_t cnt = 0; cnt < nsegments; ++cnt)
    if (segments[cnt].from <= addr && segments[cnt].to > addr)
      {
	Dwarf_Die die_mem;
	Dwarf_Die *die;
	Dwarf_Line *line;
	const char *src;

	if (more_than_one)
	  printf ("%s: ", fname);

	if ((die = dwarf_addrdie (dw, addr, &die_mem)) != NULL
	    && (line = dwarf_getsrc_die (die, addr)) != NULL
	    && (src = dwarf_linesrc (line, NULL, NULL)) != NULL)
	  {
	    /* There can be more than one relocation against one file.
	       Try to avoid multiple messages.  And yes, the code uses
	       pointer comparison.  */
	    if (tfind (src, knownsrcs, ptrcompare) == NULL)
	      {
		printf (gettext ("%s not compiled with -fpic/-fPIC\n"), src);
		tsearch (src, knownsrcs, ptrcompare);
	      }
	    return;
	  }
	else
	  {
	    /* At least look at the symbol table to see which function
	       the modified address is in.  */
	    Elf_Data *symdata = elf_getdata (symscn, NULL);
	    GElf_Shdr shdr_mem;
	    GElf_Shdr *shdr = gelf_getshdr (symscn, &shdr_mem);
	    if (shdr != NULL)
	      {
		GElf_Addr lowaddr = 0;
		int lowidx = -1;
		GElf_Addr highaddr = ~0ul;
		int highidx = -1;
		GElf_Sym sym_mem;
		GElf_Sym *sym;

		for (int i = 0; (size_t) i < shdr->sh_size / shdr->sh_entsize;
		     ++i)
		  {
		    sym = gelf_getsym (symdata, i, &sym_mem);
		    if (sym == NULL)
		      continue;

		    if (sym->st_value < addr && sym->st_value > lowaddr)
		      {
			lowaddr = sym->st_value;
			lowidx = i;
		      }
		    if (sym->st_value > addr && sym->st_value < highaddr)
		      {
			highaddr = sym->st_value;
			highidx = i;
		      }
		  }

		if (lowidx != -1)
		  {
		    sym = gelf_getsym (symdata, lowidx, &sym_mem);
		    assert (sym != NULL);

		    const char *lowstr = elf_strptr (elf, shdr->sh_link,
						     sym->st_name);

		    if (sym->st_value + sym->st_size > addr)
		      {
			/* It is this function.  */
			if (tfind (lowstr, knownsrcs, ptrcompare) == NULL)
			  {
			    printf (gettext ("\
the file containing the function '%s' is not compiled with -fpic/-fPIC\n"),
				    lowstr);
			    tsearch (lowstr, knownsrcs, ptrcompare);
			  }
		      }
		    else if (highidx == -1)
		      printf (gettext ("\
the file containing the function '%s' might not be compiled with -fpic/-fPIC\n"),
			      lowstr);
		    else
		      {
			sym = gelf_getsym (symdata, highidx, &sym_mem);
			assert (sym != NULL);

			printf (gettext ("\
either the file containing the function '%s' or the file containing the function '%s' is not compiled with -fpic/-fPIC\n"),
				lowstr, elf_strptr (elf, shdr->sh_link,
						    sym->st_name));
		      }
		    return;
		  }
		else if (highidx != -1)
		  {
		    sym = gelf_getsym (symdata, highidx, &sym_mem);
		    assert (sym != NULL);

		    printf (gettext ("\
the file containing the function '%s' might not be compiled with -fpic/-fPIC\n"),
			    elf_strptr (elf, shdr->sh_link, sym->st_name));
		    return;
		  }
	      }
	  }

	printf (gettext ("\
a relocation modifies memory at offset %llu in a write-protected segment\n"),
		(unsigned long long int) addr);
	break;
      }
}


#include "debugpred.h"