summaryrefslogtreecommitdiffstats
path: root/libelf/elf_begin.c
blob: c4b335953fbfff955925afb29d0eb52025a0ec1e (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
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
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
736
737
738
739
740
741
742
743
744
745
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
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
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
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
/* Create descriptor for processing file.
   Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005 Red Hat, Inc.
   Written by Ulrich Drepper <drepper@redhat.com>, 1998.

   This program 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, version 2.

   This program 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, write to the Free Software Foundation,
   Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.  */

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

#include <assert.h>
#include <ctype.h>
#include <errno.h>
#include <fcntl.h>
#include <stdbool.h>
#include <stddef.h>
#include <string.h>
#include <unistd.h>
#include <sys/mman.h>
#include <sys/param.h>
#include <sys/stat.h>

#include "libelfP.h"
#include "common.h"


/* Create descriptor for archive in memory.  */
static inline Elf *
file_read_ar (int fildes, void *map_address, off_t offset, size_t maxsize,
	      Elf_Cmd cmd, Elf *parent)
{
  Elf *elf;

  /* Create a descriptor.  */
  elf = allocate_elf (fildes, map_address, offset, maxsize, cmd, parent,
                      ELF_K_AR, 0);
  if (elf != NULL)
    {
      /* We don't read all the symbol tables in advance.  All this will
	 happen on demand.  */
      elf->state.ar.offset = offset + SARMAG;

      elf->state.ar.elf_ar_hdr.ar_rawname = elf->state.ar.raw_name;
    }

  return elf;
}


static size_t
get_shnum (void *map_address, unsigned char *e_ident, int fildes, off_t offset,
	   size_t maxsize)
{
  size_t result;
  union
  {
    Elf32_Ehdr *e32;
    Elf64_Ehdr *e64;
    void *p;
  } ehdr;
  union
  {
    Elf32_Ehdr e32;
    Elf64_Ehdr e64;
  } ehdr_mem;
  bool is32 = e_ident[EI_CLASS] == ELFCLASS32;

  /* Make the ELF header available.  */
  if (likely (map_address != NULL) && e_ident[EI_DATA] == MY_ELFDATA
      && (ALLOW_UNALIGNED
	  || (((size_t) ((char *) map_address + offset))
	      & ((is32 ? __alignof__ (Elf32_Ehdr) : __alignof__ (Elf64_Ehdr))
		 - 1)) == 0))
    ehdr.p = (char *) map_address + offset;
  else
    {
      /* We have to read the data from the file.  */
      size_t len = is32 ? sizeof (Elf32_Ehdr) : sizeof (Elf64_Ehdr);

      if (likely (map_address != NULL))
	ehdr.p = memcpy (&ehdr_mem, (char *) map_address + offset, len);
      else
	{
	  /* Fill it.  */
	  if ((size_t) TEMP_FAILURE_RETRY (pread (fildes, &ehdr_mem, len,
						  offset)) != len)
	    /* Failed reading.  */
	    return (size_t) -1l;
	  ehdr.p = &ehdr_mem;
	}

      if (e_ident[EI_DATA] != MY_ELFDATA)
	{
	  if (is32)
	    {
	      CONVERT (ehdr.e32->e_shnum);
	      CONVERT (ehdr.e32->e_shoff);
	    }
	  else
	    {
	      CONVERT (ehdr.e64->e_shnum);
	      CONVERT (ehdr.e64->e_shoff);
	    }
	}
    }

  if (is32)
    {
      /* Get the number of sections from the ELF header.  */
      result = ehdr.e32->e_shnum;

      if (unlikely (result == 0) && ehdr.e32->e_shoff != 0)
	{
	  if (offset + ehdr.e32->e_shoff + sizeof (Elf32_Shdr) > maxsize)
	    /* Cannot read the first section header.  */
	    return (size_t) -1l;

	  if (likely (map_address != NULL) && e_ident[EI_DATA] == MY_ELFDATA
	      && (ALLOW_UNALIGNED
		  || (((size_t) ((char *) map_address + offset))
		      & (__alignof__ (Elf32_Ehdr) - 1)) == 0))
	    /* We can directly access the memory.  */
	    result = ((Elf32_Shdr *) ((char *) map_address + ehdr.e32->e_shoff
				      + offset))->sh_size;
	  else
	    {
	      Elf32_Word size;

	      if (likely (map_address != NULL))
		/* gcc will optimize the memcpy to a simple memory
		   access while taking care of alignment issues.  */
		memcpy (&size, &((Elf32_Shdr *) ((char *) map_address
						 + ehdr.e32->e_shoff
						 + offset))->sh_size,
			sizeof (Elf32_Word));
	      else
		if (TEMP_FAILURE_RETRY (pread (fildes, &size,
					       sizeof (Elf32_Word),
					       offset + ehdr.e32->e_shoff
					       + offsetof (Elf32_Shdr,
							   sh_size)))
		    != sizeof (Elf32_Word))
		  return (size_t) -1l;

	      if (e_ident[EI_DATA] != MY_ELFDATA)
		CONVERT (size);

	      result = size;
	    }
	}
    }
  else
    {
      /* Get the number of sections from the ELF header.  */
      result = ehdr.e64->e_shnum;

      if (unlikely (result == 0) && ehdr.e64->e_shoff != 0)
	{
	  if (offset + ehdr.e64->e_shoff + sizeof (Elf64_Shdr) > maxsize)
	    /* Cannot read the first section header.  */
	    return (size_t) -1l;

	  Elf64_Xword size;
	  if (likely (map_address != NULL) && e_ident[EI_DATA] == MY_ELFDATA
	      && (ALLOW_UNALIGNED
		  || (((size_t) ((char *) map_address + offset))
		      & (__alignof__ (Elf64_Ehdr) - 1)) == 0))
	    /* We can directly access the memory.  */
	    size = ((Elf64_Shdr *) ((char *) map_address + ehdr.e64->e_shoff
				    + offset))->sh_size;
	  else
	    {
	      if (likely (map_address != NULL))
		/* gcc will optimize the memcpy to a simple memory
		   access while taking care of alignment issues.  */
		memcpy (&size, &((Elf64_Shdr *) ((char *) map_address
						 + ehdr.e64->e_shoff
						 + offset))->sh_size,
			sizeof (Elf64_Xword));
	      else
		if (TEMP_FAILURE_RETRY (pread (fildes, &size,
					       sizeof (Elf64_Word),
					       offset + ehdr.e64->e_shoff
					       + offsetof (Elf64_Shdr,
							   sh_size)))
		    != sizeof (Elf64_Xword))
		  return (size_t) -1l;

	      if (e_ident[EI_DATA] != MY_ELFDATA)
		CONVERT (size);
	    }

	  if (size > ~((GElf_Word) 0))
	    /* Invalid value, it is too large.  */
	    return (size_t) -1l;

	  result = size;
	}
    }

  return result;
}


/* Create descriptor for ELF file in memory.  */
static Elf *
file_read_elf (int fildes, void *map_address, off_t offset, size_t maxsize,
	       Elf_Cmd cmd, Elf *parent)
{
  /* We only read the ELF header now.  */
  unsigned char *e_ident;
  unsigned char e_ident_mem[EI_NIDENT];
  size_t scncnt;
  Elf *elf;

  if (map_address != NULL)
    /* It's right at the beginning of the file.  No word access
       required, just bytes.  */
    e_ident = (unsigned char *) map_address + offset;
  else
    {
      e_ident = e_ident_mem;

      if (TEMP_FAILURE_RETRY (pread (fildes, e_ident, EI_NIDENT, offset))
	  != EI_NIDENT)
	{
	  __libelf_seterrno (ELF_E_READ_ERROR);
	  return NULL;
	}
    }

  /* Verify the binary is of the class we can handle.  */
  if ((e_ident[EI_CLASS] != ELFCLASS32
       && e_ident[EI_CLASS] != ELFCLASS64)
      /* We also can only handle two encodings.  */
      || (e_ident[EI_DATA] != ELFDATA2LSB
	  && e_ident[EI_DATA] != ELFDATA2MSB))
    {
      /* Cannot handle this.  */
      __libelf_seterrno (ELF_E_INVALID_FILE);
      return NULL;
    }

  /* Determine the number of sections.  */
  scncnt = get_shnum (map_address, e_ident, fildes, offset, maxsize);
  if (scncnt == (size_t) -1l)
    /* Could not determine the number of sections.  */
    return NULL;

  /* We can now allocate the memory.  */
  elf = allocate_elf (fildes, map_address, offset, maxsize, cmd, parent,
		      ELF_K_ELF, scncnt * sizeof (Elf_Scn));
  if (elf == NULL)
    /* Not enough memory.  */
    return NULL;

  /* Some more or less arbitrary value.  */
  elf->state.elf.scnincr = 10;

  if (e_ident[EI_CLASS] == ELFCLASS32)
    {
      /* This pointer might not be directly usable if the alignment is
	 not sufficient for the architecture.  */
      Elf32_Ehdr *ehdr = (Elf32_Ehdr *) ((char *) map_address + offset);

      assert ((unsigned int) scncnt == scncnt);
      elf->state.elf32.scns.cnt = elf->state.elf32.scns.max = scncnt;

      /* This is a 32-bit binary.  */
      if (map_address != NULL && e_ident[EI_DATA] == MY_ELFDATA
	  && (ALLOW_UNALIGNED
	      || ((((uintptr_t) ehdr) & (__alignof__ (Elf32_Ehdr) - 1)) == 0
		  && ((uintptr_t) ((char *) ehdr + ehdr->e_shoff)
		      & (__alignof__ (Elf32_Shdr) - 1)) == 0
		  && ((uintptr_t) ((char *) ehdr + ehdr->e_phoff)
		      & (__alignof__ (Elf32_Phdr) - 1)) == 0)))
	{
	  /* We can use the mmapped memory.  */
	  elf->state.elf32.ehdr =
	    (Elf32_Ehdr *) ((char *) map_address + offset);
	  elf->state.elf32.shdr =
	    (Elf32_Shdr *) ((char *) map_address + offset
			    + elf->state.elf32.ehdr->e_shoff);
	  if (elf->state.elf32.ehdr->e_phnum)
	    /* Assign a value only if there really is a program
	       header.  Otherwise the value remains NULL.  */
	    elf->state.elf32.phdr
	      = (Elf32_Phdr *) ((char *) map_address + offset
				+ elf->state.elf32.ehdr->e_phoff);

	  for (size_t cnt = 0; cnt < scncnt; ++cnt)
	    {
	      elf->state.elf32.scns.data[cnt].index = cnt;
	      elf->state.elf32.scns.data[cnt].elf = elf;
	      elf->state.elf32.scns.data[cnt].shdr.e32 =
		&elf->state.elf32.shdr[cnt];
	      elf->state.elf32.scns.data[cnt].rawdata_base =
		elf->state.elf32.scns.data[cnt].data_base =
		((char *) map_address + offset
		 + elf->state.elf32.shdr[cnt].sh_offset);
	      elf->state.elf32.scns.data[cnt].list = &elf->state.elf32.scns;
	    }
	}
      else
	{
	  if (likely (map_address != NULL))
	    /* Copy the data.  */
	    memcpy (&elf->state.elf32.ehdr_mem,
		    (char *) map_address + offset, sizeof (Elf32_Ehdr));
	  else
	    /* Read the data.  */
	    if (TEMP_FAILURE_RETRY (pread (elf->fildes,
					   &elf->state.elf32.ehdr_mem,
					   sizeof (Elf32_Ehdr), offset))
		!= sizeof (Elf32_Ehdr))
	      {
		/* We must be able to read the ELF header.  */
		__libelf_seterrno (ELF_E_INVALID_FILE);
		return NULL;
	      }

	  if (e_ident[EI_DATA] != MY_ELFDATA)
	    {
	      CONVERT (elf->state.elf32.ehdr_mem.e_type);
	      CONVERT (elf->state.elf32.ehdr_mem.e_machine);
	      CONVERT (elf->state.elf32.ehdr_mem.e_version);
	      CONVERT (elf->state.elf32.ehdr_mem.e_entry);
	      CONVERT (elf->state.elf32.ehdr_mem.e_phoff);
	      CONVERT (elf->state.elf32.ehdr_mem.e_shoff);
	      CONVERT (elf->state.elf32.ehdr_mem.e_flags);
	      CONVERT (elf->state.elf32.ehdr_mem.e_ehsize);
	      CONVERT (elf->state.elf32.ehdr_mem.e_phentsize);
	      CONVERT (elf->state.elf32.ehdr_mem.e_phnum);
	      CONVERT (elf->state.elf32.ehdr_mem.e_shentsize);
	      CONVERT (elf->state.elf32.ehdr_mem.e_shnum);
	      CONVERT (elf->state.elf32.ehdr_mem.e_shstrndx);
	    }

	  elf->state.elf32.ehdr = &elf->state.elf32.ehdr_mem;

	  for (size_t cnt = 0; cnt < scncnt; ++cnt)
	    {
	      elf->state.elf32.scns.data[cnt].index = cnt;
	      elf->state.elf32.scns.data[cnt].elf = elf;
	      elf->state.elf32.scns.data[cnt].list = &elf->state.elf32.scns;
	    }
	}

      /* So far only one block with sections.  */
      elf->state.elf32.scns_last = &elf->state.elf32.scns;
    }
  else
    {
      /* This pointer might not be directly usable if the alignment is
	 not sufficient for the architecture.  */
      Elf64_Ehdr *ehdr = (Elf64_Ehdr *) ((char *) map_address + offset);

      assert ((unsigned int) scncnt == scncnt);
      elf->state.elf64.scns.cnt = elf->state.elf64.scns.max = scncnt;

      /* This is a 64-bit binary.  */
      if (map_address != NULL && e_ident[EI_DATA] == MY_ELFDATA
	  && (ALLOW_UNALIGNED
	      || ((((uintptr_t) ehdr) & (__alignof__ (Elf64_Ehdr) - 1)) == 0
		  && ((uintptr_t) ((char *) ehdr + ehdr->e_shoff)
		      & (__alignof__ (Elf64_Shdr) - 1)) == 0
		  && ((uintptr_t) ((char *) ehdr + ehdr->e_phoff)
		      & (__alignof__ (Elf64_Phdr) - 1)) == 0)))
	{
	  /* We can use the mmapped memory.  */
	  elf->state.elf64.ehdr =
	    (Elf64_Ehdr *) ((char *) map_address + offset);
	  elf->state.elf64.shdr =
	    (Elf64_Shdr *) ((char *) map_address + offset
			    + elf->state.elf64.ehdr->e_shoff);
	  if (elf->state.elf64.ehdr->e_phnum)
	    /* Assign a value only if there really is a program
	       header.  Otherwise the value remains NULL.  */
	    elf->state.elf64.phdr
	      = (Elf64_Phdr *) ((char *) map_address + offset
				+ elf->state.elf64.ehdr->e_phoff);

	  for (size_t cnt = 0; cnt < scncnt; ++cnt)
	    {
	      elf->state.elf64.scns.data[cnt].index = cnt;
	      elf->state.elf64.scns.data[cnt].elf = elf;
	      elf->state.elf64.scns.data[cnt].shdr.e64 =
		&elf->state.elf64.shdr[cnt];
	      elf->state.elf64.scns.data[cnt].rawdata_base =
		elf->state.elf64.scns.data[cnt].data_base =
		((char *) map_address + offset
		 + elf->state.elf64.shdr[cnt].sh_offset);
	      elf->state.elf64.scns.data[cnt].list = &elf->state.elf64.scns;
	    }
	}
      else
	{
	  if (likely (map_address != NULL))
	    /* Copy the data.  */
	    memcpy (&elf->state.elf64.ehdr_mem,
		    (char *) map_address + offset, sizeof (Elf64_Ehdr));
	  else
	    /* Read the data.  */
	    if (TEMP_FAILURE_RETRY (pread (elf->fildes,
					   &elf->state.elf64.ehdr_mem,
					   sizeof (Elf64_Ehdr), offset))
		!= sizeof (Elf64_Ehdr))
	    {
	      /* We must be able to read the ELF header.  */
	      __libelf_seterrno (ELF_E_INVALID_FILE);
	      return NULL;
	    }

	  if (e_ident[EI_DATA] != MY_ELFDATA)
	    {
	      CONVERT (elf->state.elf64.ehdr_mem.e_type);
	      CONVERT (elf->state.elf64.ehdr_mem.e_machine);
	      CONVERT (elf->state.elf64.ehdr_mem.e_version);
	      CONVERT (elf->state.elf64.ehdr_mem.e_entry);
	      CONVERT (elf->state.elf64.ehdr_mem.e_phoff);
	      CONVERT (elf->state.elf64.ehdr_mem.e_shoff);
	      CONVERT (elf->state.elf64.ehdr_mem.e_flags);
	      CONVERT (elf->state.elf64.ehdr_mem.e_ehsize);
	      CONVERT (elf->state.elf64.ehdr_mem.e_phentsize);
	      CONVERT (elf->state.elf64.ehdr_mem.e_phnum);
	      CONVERT (elf->state.elf64.ehdr_mem.e_shentsize);
	      CONVERT (elf->state.elf64.ehdr_mem.e_shnum);
	      CONVERT (elf->state.elf64.ehdr_mem.e_shstrndx);
	    }

	  elf->state.elf64.ehdr = &elf->state.elf64.ehdr_mem;

	  for (size_t cnt = 0; cnt < scncnt; ++cnt)
	    {
	      elf->state.elf64.scns.data[cnt].index = cnt;
	      elf->state.elf64.scns.data[cnt].elf = elf;
	      elf->state.elf64.scns.data[cnt].list = &elf->state.elf64.scns;
	    }
	}

      /* So far only one block with sections.  */
      elf->state.elf64.scns_last = &elf->state.elf64.scns;
    }

  /* Make the class easily available.  */
  elf->class = e_ident[EI_CLASS];

  return elf;
}


Elf *
internal_function_def
__libelf_read_mmaped_file (int fildes, void *map_address,  off_t offset,
			   size_t maxsize, Elf_Cmd cmd, Elf *parent)
{
  /* We have to find out what kind of file this is.  We handle ELF
     files and archives.  To find out what we have we must look at the
     header.  The header for an ELF file is EI_NIDENT bytes in size,
     the header for an archive file SARMAG bytes long.  */
  Elf_Kind kind;

  /* See what kind of object we have here.  */
  kind = determine_kind (map_address + offset, maxsize);

  switch (kind)
    {
    case ELF_K_ELF:
      return file_read_elf (fildes, map_address, offset, maxsize, cmd, parent);

    case ELF_K_AR:
      return file_read_ar (fildes, map_address, offset, maxsize, cmd, parent);

    default:
      break;
    }

  /* This case is easy.  Since we cannot do anything with this file
     create a dummy descriptor.  */
  return allocate_elf (fildes, map_address, offset, maxsize, cmd, parent,
		       ELF_K_NONE, 0);
}


static Elf *
read_unmmaped_file (int fildes, off_t offset, size_t maxsize, Elf_Cmd cmd,
		    Elf *parent)
{
  /* We have to find out what kind of file this is.  We handle ELF
     files and archives.  To find out what we have we must read the
     header.  The header for an ELF file is EI_NIDENT bytes in size,
     the header for an archive file SARMAG bytes long.  Read the
     maximum of these numbers.

     XXX We have to change this for the extended `ar' format some day.  */
  unsigned char header[MAX (EI_NIDENT, SARMAG)];
  ssize_t nread;
  Elf_Kind kind;

  /* Read the head of the file.  */
  nread = pread (fildes, header, MIN (MAX (EI_NIDENT, SARMAG), maxsize),
		 offset);
  if (nread == -1)
    /* We cannot even read the head of the file.  Maybe FILDES is associated
       with an unseekable device.  This is nothing we can handle.  */
    return NULL;

  /* See what kind of object we have here.  */
  kind = determine_kind (header, nread);

  switch (kind)
    {
    case ELF_K_AR:
      return file_read_ar (fildes, NULL, offset, maxsize, cmd, parent);

    case ELF_K_ELF:
      /* Make sure at least the ELF header is contained in the file.  */
      if (maxsize >= (header[EI_CLASS] == ELFCLASS32
		      ? sizeof (Elf32_Ehdr) : sizeof (Elf64_Ehdr)))
	return file_read_elf (fildes, NULL, offset, maxsize, cmd, parent);
      /* FALLTHROUGH */

    default:
      break;
    }

  /* This case is easy.  Since we cannot do anything with this file
     create a dummy descriptor.  */
  return allocate_elf (fildes, NULL, offset, maxsize, cmd, parent,
		       ELF_K_NONE, 0);
}


/* Open a file for reading.  If possible we will try to mmap() the file.  */
static struct Elf *
read_file (int fildes, off_t offset, size_t maxsize,
	   Elf_Cmd cmd, Elf *parent)
{
  void *map_address = NULL;
  int use_mmap = (cmd == ELF_C_READ_MMAP || cmd == ELF_C_RDWR_MMAP
		  || cmd == ELF_C_WRITE_MMAP
		  || cmd == ELF_C_READ_MMAP_PRIVATE);

#if _MUDFLAP
  /* Mudflap doesn't grok that our mmap'd data is ok.  */
  use_mmap = 0;
#endif

  if (use_mmap)
    {
      if (parent == NULL)
	{
	  if (maxsize == ~((size_t) 0))
	    {
	      /* We don't know in the moment how large the file is.
		 Determine it now.  */
	      struct stat st;

	      if (fstat (fildes, &st) == 0
		  && (sizeof (size_t) >= sizeof (st.st_size)
		      || st.st_size <= ~((size_t) 0)))
		maxsize = (size_t) st.st_size;
	    }

	  /* We try to map the file ourself.  */
	  map_address = mmap (NULL, maxsize, (cmd == ELF_C_READ_MMAP
					      ? PROT_READ
					      : PROT_READ|PROT_WRITE),
			      cmd == ELF_C_READ_MMAP_PRIVATE
			      ? MAP_PRIVATE : MAP_SHARED,
			      fildes, offset);

	  if (map_address == MAP_FAILED)
	    map_address = NULL;
	}
      else
	{
	  /* The parent is already loaded.  Use it.  */
	  assert (maxsize != ~((size_t) 0));

	  map_address = parent->map_address;
	}
    }

  /* If we have the file in memory optimize the access.  */
  if (map_address != NULL)
    {
      struct Elf *result;

      result = __libelf_read_mmaped_file (fildes, map_address, offset, maxsize,
					  cmd, parent);

      /* If something went wrong during the initialization unmap the
	 memory if we mmaped here.  */
      if (result == NULL
	  && (parent == NULL
	      || parent->map_address != map_address))
	munmap (map_address, maxsize);
      else if (parent == NULL)
	/* Remember that we mmap()ed the memory.  */
	result->flags |= ELF_F_MMAPPED;

      return result;
    }

  /* Otherwise we have to do it the hard way.  We read as much as necessary
     from the file whenever we need information which is not available.  */
  return read_unmmaped_file (fildes, offset, maxsize, cmd, parent);
}


/* Find the entry with the long names for the content of this archive.  */
static const char *
read_long_names (Elf *elf)
{
  off_t offset = SARMAG;	/* This is the first entry.  */
  struct ar_hdr hdrm;
  struct ar_hdr *hdr;
  char *newp;
  size_t len;

  while (1)
    {
      if (elf->map_address != NULL)
	{
	  if (offset + sizeof (struct ar_hdr) > elf->maximum_size)
	    return NULL;

	  /* The data is mapped.  */
	  hdr = (struct ar_hdr *) (elf->map_address + offset);
	}
      else
	{
	  /* Read the header from the file.  */
	  if (pread (elf->fildes, &hdrm, sizeof (hdrm),
		     elf->start_offset + offset) != sizeof (hdrm))
	    return NULL;

	  hdr = &hdrm;
	}

      len = atol (hdr->ar_size);

      if (memcmp (hdr->ar_name, "//              ", 16) == 0)
	break;

      offset += sizeof (struct ar_hdr) + ((len + 1) & ~1l);
    }

  /* Due to the stupid format of the long name table entry (which are not
     NUL terminted) we have to provide an appropriate representation anyhow.
     Therefore we always make a copy which has the appropriate form.  */
  newp = (char *) malloc (len);
  if (newp != NULL)
    {
      char *runp;

      if (elf->map_address != NULL)
	/* Simply copy it over.  */
	elf->state.ar.long_names = (char *) memcpy (newp,
						    elf->map_address + offset
						    + sizeof (struct ar_hdr),
						    len);
      else
	{
	  if ((size_t) pread (elf->fildes, newp, len,
			      elf->start_offset + offset
			      + sizeof (struct ar_hdr))
	      != len)
	    {
	      /* We were not able to read all data.  */
	      free (newp);
	      elf->state.ar.long_names = NULL;
	      return NULL;
	    }
	  elf->state.ar.long_names = newp;
	}

      elf->state.ar.long_names_len = len;

      /* Now NUL-terminate the strings.  */
      runp = newp;
      while (1)
        {
	  runp = (char *) memchr (runp, '/', newp + len - runp);
	  if (runp == NULL)
	    /* This was the last entry.  */
	    break;

	  /* NUL-terminate the string.  */
	  *runp = '\0';

	  /* Skip the NUL bzte and the \012.  */
	  runp += 2;

	  /* A sanity check.  Somebody might have generated invalid
	     archive.  */
	  if (runp >= newp + len)
	    break;
	}
    }

  return newp;
}


/* Read the next archive header.  */
int
internal_function_def
__libelf_next_arhdr (elf)
     Elf *elf;
{
  struct ar_hdr *ar_hdr;
  Elf_Arhdr *elf_ar_hdr;

  if (elf->map_address != NULL)
    {
      /* See whether this entry is in the file.  */
      if (elf->state.ar.offset + sizeof (struct ar_hdr)
	  > elf->start_offset + elf->maximum_size)
	{
	  /* This record is not anymore in the file.  */
	  __libelf_seterrno (ELF_E_RANGE);
	  return -1;
	}
      ar_hdr = (struct ar_hdr *) (elf->map_address + elf->state.ar.offset);
    }
  else
    {
      ar_hdr = &elf->state.ar.ar_hdr;

      if (TEMP_FAILURE_RETRY (pread (elf->fildes, ar_hdr,
				     sizeof (struct ar_hdr),
				     elf->state.ar.offset))
	  != sizeof (struct ar_hdr))
	{
	  /* Something went wrong while reading the file.  */
	  __libelf_seterrno (ELF_E_RANGE);
	  return -1;
	}
    }

  /* One little consistency check.  */
  if (memcmp (ar_hdr->ar_fmag, ARFMAG, 2) != 0)
    {
      /* This is no valid archive.  */
      __libelf_seterrno (ELF_E_ARCHIVE_FMAG);
      return -1;
    }

  /* Copy the raw name over to a NUL terminated buffer.  */
  *((char *) __mempcpy (elf->state.ar.raw_name, ar_hdr->ar_name, 16)) = '\0';

  elf_ar_hdr = &elf->state.ar.elf_ar_hdr;

  /* Now convert the `struct ar_hdr' into `Elf_Arhdr'.
     Determine whether this is a special entry.  */
  if (ar_hdr->ar_name[0] == '/')
    {
      if (ar_hdr->ar_name[1] == ' '
	  && memcmp (ar_hdr->ar_name, "/               ", 16) == 0)
	/* This is the index.  */
	elf_ar_hdr->ar_name = memcpy (elf->state.ar.ar_name, "/", 2);
      else if (ar_hdr->ar_name[1] == '/'
	       && memcmp (ar_hdr->ar_name, "//              ", 16) == 0)
	/* This is the array with the long names.  */
	elf_ar_hdr->ar_name = memcpy (elf->state.ar.ar_name, "//", 3);
      else if (isdigit (ar_hdr->ar_name[1]))
	{
	  size_t offset;

	  /* This is a long name.  First we have to read the long name
	     table, if this hasn't happened already.  */
	  if (elf->state.ar.long_names == NULL
	      && read_long_names (elf) == NULL)
	    {
	      /* No long name table although it is reference.  The archive is
		 broken.  */
	      __libelf_seterrno (ELF_E_INVALID_ARCHIVE);
	      return -1;
	    }

	  offset = atol (ar_hdr->ar_name + 1);
	  if (offset >= elf->state.ar.long_names_len)
	    {
	      /* The index in the long name table is larger than the table.  */
	      __libelf_seterrno (ELF_E_INVALID_ARCHIVE);
	      return -1;
	    }
	  elf_ar_hdr->ar_name = elf->state.ar.long_names + offset;
	}
      else
	{
	  /* This is none of the known special entries.  */
	  __libelf_seterrno (ELF_E_INVALID_ARCHIVE);
	  return -1;
	}
    }
  else
    {
      char *endp;

      /* It is a normal entry.  Copy over the name.  */
      endp = (char *) memccpy (elf->state.ar.ar_name, ar_hdr->ar_name,
			       '/', 16);
      if (endp != NULL)
	endp[-1] = '\0';
      else
	elf->state.ar.raw_name[16] = '\0';

      elf_ar_hdr->ar_name = elf->state.ar.ar_name;
    }

  /* Since there are no specialized functions to convert ASCII to
     time_t, uid_t, gid_t, mode_t, and off_t we use either atol or
     atoll depending on the size of the types.  We are also prepared
     for the case where the whole field in the `struct ar_hdr' is
     filled in which case we cannot simply use atol/l but instead have
     to create a temporary copy.  */
  if (ar_hdr->ar_date[sizeof (ar_hdr->ar_date) - 1] == ' ')
    {
      if (ar_hdr->ar_date[0] == ' ')
	elf_ar_hdr->ar_date = 0;
      else
	elf_ar_hdr->ar_date = (sizeof (time_t) <= sizeof (long int)
			       ? (time_t) atol (ar_hdr->ar_date)
			       : (time_t) atoll (ar_hdr->ar_date));
    }
  else
    {
      char buf[sizeof (ar_hdr->ar_date) + 1];
      *((char *) __mempcpy (buf, ar_hdr->ar_date, sizeof (ar_hdr->ar_date)))
	= '\0';
      elf_ar_hdr->ar_date = (sizeof (time_t) <= sizeof (long int)
			     ? (time_t) atol (ar_hdr->ar_date)
			     : (time_t) atoll (ar_hdr->ar_date));
    }

  if (ar_hdr->ar_uid[sizeof (ar_hdr->ar_uid) - 1] == ' ')
    {
      if (ar_hdr->ar_uid[0] == ' ')
	elf_ar_hdr->ar_uid = 0;
      else
	elf_ar_hdr->ar_uid = (sizeof (uid_t) <= sizeof (long int)
			      ? (uid_t) atol (ar_hdr->ar_uid)
			      : (uid_t) atoll (ar_hdr->ar_uid));
    }
  else
    {
      char buf[sizeof (ar_hdr->ar_uid) + 1];
      *((char *) __mempcpy (buf, ar_hdr->ar_uid, sizeof (ar_hdr->ar_uid)))
	= '\0';
      elf_ar_hdr->ar_uid = (sizeof (uid_t) <= sizeof (long int)
			     ? (uid_t) atol (ar_hdr->ar_uid)
			     : (uid_t) atoll (ar_hdr->ar_uid));
    }

  if (ar_hdr->ar_gid[sizeof (ar_hdr->ar_gid) - 1] == ' ')
    {
      if (ar_hdr->ar_gid[0] == ' ')
	elf_ar_hdr->ar_gid = 0;
      else
	elf_ar_hdr->ar_gid = (sizeof (gid_t) <= sizeof (long int)
			      ? (gid_t) atol (ar_hdr->ar_gid)
			      : (gid_t) atoll (ar_hdr->ar_gid));
    }
  else
    {
      char buf[sizeof (ar_hdr->ar_gid) + 1];
      *((char *) __mempcpy (buf, ar_hdr->ar_gid, sizeof (ar_hdr->ar_gid)))
	= '\0';
      elf_ar_hdr->ar_gid = (sizeof (gid_t) <= sizeof (long int)
			     ? (gid_t) atol (ar_hdr->ar_gid)
			     : (gid_t) atoll (ar_hdr->ar_gid));
    }

  if (ar_hdr->ar_mode[sizeof (ar_hdr->ar_mode) - 1] == ' ')
    {
      if (ar_hdr->ar_mode[0] == ' ')
	elf_ar_hdr->ar_mode = 0;
      else
	elf_ar_hdr->ar_mode = (sizeof (mode_t) <= sizeof (long int)
			       ? (mode_t) strtol (ar_hdr->ar_mode, NULL, 8)
			       : (mode_t) strtoll (ar_hdr->ar_mode, NULL, 8));
    }
  else
    {
      char buf[sizeof (ar_hdr->ar_mode) + 1];
      *((char *) __mempcpy (buf, ar_hdr->ar_mode, sizeof (ar_hdr->ar_mode)))
	= '\0';
      elf_ar_hdr->ar_mode = (sizeof (mode_t) <= sizeof (long int)
			     ? (mode_t) strtol (ar_hdr->ar_mode, NULL, 8)
			     : (mode_t) strtoll (ar_hdr->ar_mode, NULL, 8));
    }

  if (ar_hdr->ar_size[sizeof (ar_hdr->ar_size) - 1] == ' ')
    {
      if (ar_hdr->ar_size[0] == ' ')
	/* Something is really wrong.  We cannot live without a size for
	   the member since it will not be possible to find the next
	   archive member.  */
	{
	  __libelf_seterrno (ELF_E_INVALID_ARCHIVE);
	  return -1;
	}
      else
	elf_ar_hdr->ar_size = (sizeof (time_t) == sizeof (long int)
			       ? (off_t) atol (ar_hdr->ar_size)
			       : (off_t) atoll (ar_hdr->ar_size));
    }
  else
    {
      char buf[sizeof (ar_hdr->ar_size) + 1];
      *((char *) __mempcpy (buf, ar_hdr->ar_size, sizeof (ar_hdr->ar_size)))
	= '\0';
      elf_ar_hdr->ar_size = (sizeof (time_t) == sizeof (long int)
			     ? (off_t) atol (ar_hdr->ar_size)
			     : (off_t) atoll (ar_hdr->ar_size));
    }

  return 0;
}


/* We were asked to return a clone of an existing descriptor.  This
   function must be called with the lock on the parent descriptor
   being held. */
static Elf *
dup_elf (int fildes, Elf_Cmd cmd, Elf *ref)
{
  struct Elf *result;

  if (fildes == -1)
    /* Allow the user to pass -1 as the file descriptor for the new file.  */
    fildes = ref->fildes;
  /* The file descriptor better should be the same.  If it was disconnected
     already (using `elf_cntl') we do not test it.  */
  else if (ref->fildes != -1 && fildes != ref->fildes)
    {
      __libelf_seterrno (ELF_E_FD_MISMATCH);
      return NULL;
    }

  /* The mode must allow reading.  I.e., a descriptor creating with a
     command different then ELF_C_READ, ELF_C_WRITE and ELF_C_RDWR is
     not allowed.  */
  if (ref->cmd != ELF_C_READ && ref->cmd != ELF_C_READ_MMAP
      && ref->cmd != ELF_C_WRITE && ref->cmd != ELF_C_WRITE_MMAP
      && ref->cmd != ELF_C_RDWR && ref->cmd != ELF_C_RDWR_MMAP
      && ref->cmd != ELF_C_READ_MMAP_PRIVATE)
    {
      __libelf_seterrno (ELF_E_INVALID_OP);
      return NULL;
    }

  /* Now it is time to distinguish between reading normal files and
     archives.  Normal files can easily be handled be incrementing the
     reference counter and return the same descriptor.  */
  if (ref->kind != ELF_K_AR)
    {
      ++ref->ref_count;
      return ref;
    }

  /* This is an archive.  We must create a descriptor for the archive
     member the internal pointer of the archive file desriptor is
     pointing to.  First read the header of the next member if this
     has not happened already.  */
  if (ref->state.ar.elf_ar_hdr.ar_name == NULL
      && __libelf_next_arhdr (ref) != 0)
    /* Something went wrong.  Maybe there is no member left.  */
    return NULL;

  /* We have all the information we need about the next archive member.
     Now create a descriptor for it.  */
  result = read_file (fildes, ref->state.ar.offset + sizeof (struct ar_hdr),
		      ref->state.ar.elf_ar_hdr.ar_size, cmd, ref);

  /* Enlist this new descriptor in the list of children.  */
  if (result != NULL)
    {
      result->next = ref->state.ar.children;
      ref->state.ar.children = result;
    }

  return result;
}


/* Return desriptor for empty file ready for writing.  */
static struct Elf *
write_file (int fd, Elf_Cmd cmd)
{
  /* We simply create an empty `Elf' structure.  */
#define NSCNSALLOC	10
  Elf *result = allocate_elf (fd, NULL, 0, 0, cmd, NULL, ELF_K_ELF,
			      NSCNSALLOC * sizeof (Elf_Scn));

  if (result != NULL)
    {
      /* We have to write to the file in any case.  */
      result->flags = ELF_F_DIRTY;

      /* Some more or less arbitrary value.  */
      result->state.elf.scnincr = NSCNSALLOC;

      /* We have allocated room for some sections.  */
      assert (offsetof (struct Elf, state.elf32.scns)
	      == offsetof (struct Elf, state.elf64.scns));
      result->state.elf.scns_last = &result->state.elf32.scns;
      result->state.elf32.scns.max = NSCNSALLOC;
    }

  return result;
}


/* Return a descriptor for the file belonging to FILDES.  */
Elf *
elf_begin (fildes, cmd, ref)
     int fildes;
     Elf_Cmd cmd;
     Elf *ref;
{
  Elf *retval;

  if (! __libelf_version_initialized)
    {
      /* Version wasn't set so far.  */
      __libelf_seterrno (ELF_E_NO_VERSION);
      return NULL;
    }

  if (ref != NULL)
    /* Make sure the descriptor is not suddenly going away.  */
    rwlock_rdlock (ref->lock);
  else if (fcntl (fildes, F_GETFL) == -1 && errno == EBADF)
    {
      /* We cannot do anything productive without a file descriptor.  */
      __libelf_seterrno (ELF_E_INVALID_FILE);
      return NULL;
    }

  switch (cmd)
    {
    case ELF_C_NULL:
      /* We simply return a NULL pointer.  */
      retval = NULL;
      break;

    case ELF_C_READ_MMAP_PRIVATE:
      /* If we have a reference it must also be opened this way.  */
      if (ref != NULL && ref->cmd != ELF_C_READ_MMAP_PRIVATE)
	{
	  __libelf_seterrno (ELF_E_INVALID_CMD);
	  retval = NULL;
	  break;
	}
      /* FALLTHROUGH */

    case ELF_C_READ:
    case ELF_C_READ_MMAP:
      if (ref != NULL)
	/* Duplicate the descriptor.  */
	retval = dup_elf (fildes, cmd, ref);
      else
	/* Create descriptor for existing file.  */
	retval = read_file (fildes, 0, ~((size_t) 0), cmd, NULL);
      break;

    case ELF_C_RDWR:
    case ELF_C_RDWR_MMAP:
      /* If we have a REF object it must also be opened using this
	 command.  */
      if (ref != NULL)
	{
	  if (ref->cmd != ELF_C_RDWR && ref->cmd != ELF_C_RDWR_MMAP
	      && ref->cmd != ELF_C_WRITE && ref->cmd != ELF_C_WRITE_MMAP)
	    {
	      /* This is not ok.  REF must also be opened for writing.  */
	      __libelf_seterrno (ELF_E_INVALID_CMD);
	      retval = NULL;
	    }
	  else
	    /* Duplicate this descriptor.  */
	    retval = dup_elf (fildes, cmd, ref);
	}
      else
	/* Create descriptor for existing file.  */
	retval = read_file (fildes, 0, ~((size_t) 0), cmd, NULL);
      break;

    case ELF_C_WRITE:
    case ELF_C_WRITE_MMAP:
      /* We ignore REF and prepare a descriptor to write a new file.  */
      retval = write_file (fildes, cmd);
      break;

    default:
      __libelf_seterrno (ELF_E_INVALID_CMD);
      retval = NULL;
      break;
    }

  /* Release the lock.  */
  if (ref != NULL)
    rwlock_unlock (ref->lock);

  return retval;
}
INTDEF(elf_begin)