-
-
Notifications
You must be signed in to change notification settings - Fork 490
/
patchelf.cc
2635 lines (2210 loc) · 93.4 KB
/
patchelf.cc
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
/*
* PatchELF is a utility to modify properties of ELF executables and libraries
* Copyright (C) 2004-2016 Eelco Dolstra <[email protected]>
*
* 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, either version 3 of the License, or (at
* your option) any later version.
*
* 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, see <http://www.gnu.org/licenses/>.
*/
#include <algorithm>
#include <fstream>
#include <limits>
#include <map>
#include <memory>
#include <optional>
#include <set>
#include <sstream>
#include <stdexcept>
#include <string>
#include <string_view>
#include <unordered_map>
#include <unordered_set>
#include <vector>
#include <cassert>
#include <cerrno>
#include <cstdarg>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#include "elf.h"
#include "patchelf.h"
#ifndef PACKAGE_STRING
#define PACKAGE_STRING "patchelf"
#endif
// This is needed for Windows/mingw
#ifndef O_BINARY
#define O_BINARY 0
#endif
static bool debugMode = false;
static bool forceRPath = false;
static std::vector<std::string> fileNames;
static std::string outputFileName;
static bool alwaysWrite = false;
#ifdef DEFAULT_PAGESIZE
static int forcedPageSize = DEFAULT_PAGESIZE;
#else
static int forcedPageSize = -1;
#endif
#ifndef EM_LOONGARCH
#define EM_LOONGARCH 258
#endif
[[nodiscard]] static std::vector<std::string> splitColonDelimitedString(std::string_view s)
{
std::vector<std::string> parts;
size_t pos;
while ((pos = s.find(':')) != std::string_view::npos) {
parts.emplace_back(s.substr(0, pos));
s = s.substr(pos + 1);
}
if (!s.empty())
parts.emplace_back(s);
return parts;
}
static bool hasAllowedPrefix(const std::string & s, const std::vector<std::string> & allowedPrefixes)
{
return std::any_of(allowedPrefixes.begin(), allowedPrefixes.end(), [&](const std::string & i) { return !s.compare(0, i.size(), i); });
}
static std::string trim(std::string s)
{
s.erase(s.begin(), std::find_if(s.begin(), s.end(), [](unsigned char ch) { return !std::isspace(ch); }));
s.erase(std::find_if(s.rbegin(), s.rend(), [](unsigned char ch) { return !std::isspace(ch); }).base(), s.end());
return s;
}
static std::string downcase(std::string s)
{
std::transform(s.begin(), s.end(), s.begin(), [](unsigned char c){ return std::tolower(c); });
return s;
}
/* !!! G++ creates broken code if this function is inlined, don't know
why... */
template<ElfFileParams>
template<class I>
constexpr I ElfFile<ElfFileParamNames>::rdi(I i) const noexcept
{
I r = 0;
if (littleEndian) {
for (unsigned int n = 0; n < sizeof(I); ++n) {
r |= ((I) *(((unsigned char *) &i) + n)) << (n * 8);
}
} else {
for (unsigned int n = 0; n < sizeof(I); ++n) {
r |= ((I) *(((unsigned char *) &i) + n)) << ((sizeof(I) - n - 1) * 8);
}
}
return r;
}
static void debug(const char * format, ...)
{
if (debugMode) {
va_list ap;
va_start(ap, format);
vfprintf(stderr, format, ap);
va_end(ap);
}
}
static void fmt2([[maybe_unused]] std::ostringstream & out)
{
}
template<typename T, typename... Args>
void fmt2(std::ostringstream & out, T x, Args... args)
{
out << x;
fmt2(out, args...);
}
template<typename... Args>
std::string fmt(Args... args)
{
std::ostringstream out;
fmt2(out, args...);
return out.str();
}
struct SysError : std::runtime_error
{
int errNo;
explicit SysError(const std::string & msg)
: std::runtime_error(fmt(msg + ": " + strerror(errno)))
, errNo(errno)
{ }
};
[[noreturn]] static void error(const std::string & msg)
{
if (errno)
throw SysError(msg);
throw std::runtime_error(msg);
}
static FileContents readFile(const std::string & fileName,
size_t cutOff = std::numeric_limits<size_t>::max())
{
struct stat st;
if (stat(fileName.c_str(), &st) != 0)
throw SysError(fmt("getting info about '", fileName, "'"));
if (static_cast<uint64_t>(st.st_size) > static_cast<uint64_t>(std::numeric_limits<size_t>::max()))
throw SysError(fmt("cannot read file of size ", st.st_size, " into memory"));
size_t size = std::min(cutOff, static_cast<size_t>(st.st_size));
FileContents contents = std::make_shared<std::vector<unsigned char>>(size);
int fd = open(fileName.c_str(), O_RDONLY | O_BINARY);
if (fd == -1) throw SysError(fmt("opening '", fileName, "'"));
size_t bytesRead = 0;
ssize_t portion;
while ((portion = read(fd, contents->data() + bytesRead, size - bytesRead)) > 0)
bytesRead += portion;
close(fd);
if (bytesRead != size)
throw SysError(fmt("reading '", fileName, "'"));
return contents;
}
struct ElfType
{
bool is32Bit;
int machine; // one of EM_*
};
[[nodiscard]] static ElfType getElfType(const FileContents & fileContents)
{
/* Check the ELF header for basic validity. */
if (fileContents->size() < sizeof(Elf32_Ehdr))
error("missing ELF header");
auto contents = fileContents->data();
if (memcmp(contents, ELFMAG, SELFMAG) != 0)
error("not an ELF executable");
if (contents[EI_VERSION] != EV_CURRENT)
error("unsupported ELF version");
if (contents[EI_CLASS] != ELFCLASS32 && contents[EI_CLASS] != ELFCLASS64)
error("ELF executable is not 32 or 64 bit");
bool is32Bit = contents[EI_CLASS] == ELFCLASS32;
// FIXME: endianness
return ElfType { is32Bit, is32Bit ? (reinterpret_cast<Elf32_Ehdr *>(contents))->e_machine : (reinterpret_cast<Elf64_Ehdr *>(contents))->e_machine };
}
static void checkPointer(const FileContents & contents, const void * p, size_t size)
{
if (p < contents->data() || size > contents->size() || p > contents->data() + contents->size() - size)
error("data region extends past file end");
}
static void checkOffset(const FileContents & contents, size_t offset, size_t size)
{
size_t end;
if (offset > contents->size()
|| size > contents->size()
|| __builtin_add_overflow(offset, size, &end)
|| end > contents->size())
error("data offset extends past file end");
}
static std::string extractString(const FileContents & contents, size_t offset, size_t size)
{
checkOffset(contents, offset, size);
return { reinterpret_cast<const char *>(contents->data()) + offset, size };
}
template<ElfFileParams>
ElfFile<ElfFileParamNames>::ElfFile(FileContents fContents)
: fileContents(fContents)
{
/* Check the ELF header for basic validity. */
if (fileContents->size() < (off_t) sizeof(Elf_Ehdr)) error("missing ELF header");
if (memcmp(hdr()->e_ident, ELFMAG, SELFMAG) != 0)
error("not an ELF executable");
littleEndian = hdr()->e_ident[EI_DATA] == ELFDATA2LSB;
if (rdi(hdr()->e_type) != ET_EXEC && rdi(hdr()->e_type) != ET_DYN)
error("wrong ELF type");
{
auto ph_offset = rdi(hdr()->e_phoff);
auto ph_num = rdi(hdr()->e_phnum);
auto ph_entsize = rdi(hdr()->e_phentsize);
size_t ph_size, ph_end;
if (__builtin_mul_overflow(ph_num, ph_entsize, &ph_size)
|| __builtin_add_overflow(ph_offset, ph_size, &ph_end)
|| ph_end > fileContents->size()) {
error("program header table out of bounds");
}
}
if (rdi(hdr()->e_shnum) == 0)
error("no section headers. The input file is probably a statically linked, self-decompressing binary");
{
auto sh_offset = rdi(hdr()->e_shoff);
auto sh_num = rdi(hdr()->e_shnum);
auto sh_entsize = rdi(hdr()->e_shentsize);
size_t sh_size, sh_end;
if (__builtin_mul_overflow(sh_num, sh_entsize, &sh_size)
|| __builtin_add_overflow(sh_offset, sh_size, &sh_end)
|| sh_end > fileContents->size()) {
error("section header table out of bounds");
}
}
if (rdi(hdr()->e_phentsize) != sizeof(Elf_Phdr))
error("program headers have wrong size");
/* Copy the program and section headers. */
for (int i = 0; i < rdi(hdr()->e_phnum); ++i) {
Elf_Phdr *phdr = (Elf_Phdr *) (fileContents->data() + rdi(hdr()->e_phoff)) + i;
checkPointer(fileContents, phdr, sizeof(*phdr));
phdrs.push_back(*phdr);
if (rdi(phdrs[i].p_type) == PT_INTERP) isExecutable = true;
}
for (int i = 0; i < rdi(hdr()->e_shnum); ++i) {
Elf_Shdr *shdr = (Elf_Shdr *) (fileContents->data() + rdi(hdr()->e_shoff)) + i;
checkPointer(fileContents, shdr, sizeof(*shdr));
shdrs.push_back(*shdr);
}
/* Get the section header string table section (".shstrtab"). Its
index in the section header table is given by e_shstrndx field
of the ELF header. */
auto shstrtabIndex = rdi(hdr()->e_shstrndx);
if (shstrtabIndex >= shdrs.size())
error("string table index out of bounds");
auto shstrtabSize = rdi(shdrs[shstrtabIndex].sh_size);
size_t shstrtabptr;
if (__builtin_add_overflow(reinterpret_cast<size_t>(fileContents->data()), rdi(shdrs[shstrtabIndex].sh_offset), &shstrtabptr))
error("string table overflow");
const char *shstrtab = reinterpret_cast<const char *>(shstrtabptr);
checkPointer(fileContents, shstrtab, shstrtabSize);
if (shstrtabSize == 0)
error("string table size is zero");
if (shstrtab[shstrtabSize - 1] != 0)
error("string table is not zero terminated");
sectionNames = std::string(shstrtab, shstrtabSize);
sectionsByOldIndex.resize(shdrs.size());
for (size_t i = 1; i < shdrs.size(); ++i)
sectionsByOldIndex.at(i) = getSectionName(shdrs.at(i));
}
template<ElfFileParams>
unsigned int ElfFile<ElfFileParamNames>::getPageSize() const noexcept
{
if (forcedPageSize > 0)
return forcedPageSize;
// Architectures (and ABIs) can have different minimum section alignment
// requirements. There is no authoritative list of these values. The
// current list is extracted from GNU gold's source code (abi_pagesize).
switch (rdi(hdr()->e_machine)) {
case EM_IA_64:
case EM_MIPS:
case EM_PPC:
case EM_PPC64:
case EM_AARCH64:
case EM_TILEGX:
case EM_LOONGARCH:
return 0x10000;
case EM_SPARC: // This should be sparc 32-bit. According to the linux
// kernel 4KB should be also fine, but it seems that solaris is doing 8KB
case EM_SPARCV9: /* SPARC64 support */
return 0x2000;
default:
return 0x1000;
}
}
template<ElfFileParams>
void ElfFile<ElfFileParamNames>::sortPhdrs()
{
/* Sort the segments by offset. */
CompPhdr comp;
comp.elfFile = this;
stable_sort(phdrs.begin(), phdrs.end(), comp);
}
template<ElfFileParams>
void ElfFile<ElfFileParamNames>::sortShdrs()
{
/* Translate sh_link mappings to section names, since sorting the
sections will invalidate the sh_link fields. */
std::map<SectionName, SectionName> linkage;
for (unsigned int i = 1; i < rdi(hdr()->e_shnum); ++i)
if (rdi(shdrs.at(i).sh_link) != 0)
linkage[getSectionName(shdrs.at(i))] = getSectionName(shdrs.at(rdi(shdrs.at(i).sh_link)));
/* Idem for sh_info on certain sections. */
std::map<SectionName, SectionName> info;
for (unsigned int i = 1; i < rdi(hdr()->e_shnum); ++i)
if (rdi(shdrs.at(i).sh_info) != 0 &&
(rdi(shdrs.at(i).sh_type) == SHT_REL || rdi(shdrs.at(i).sh_type) == SHT_RELA))
info[getSectionName(shdrs.at(i))] = getSectionName(shdrs.at(rdi(shdrs.at(i).sh_info)));
/* Idem for the index of the .shstrtab section in the ELF header. */
Elf_Shdr shstrtab = shdrs.at(rdi(hdr()->e_shstrndx));
/* Sort the sections by offset. */
CompShdr comp;
comp.elfFile = this;
stable_sort(shdrs.begin() + 1, shdrs.end(), comp);
/* Restore the sh_link mappings. */
for (unsigned int i = 1; i < rdi(hdr()->e_shnum); ++i)
if (rdi(shdrs[i].sh_link) != 0)
wri(shdrs[i].sh_link,
getSectionIndex(linkage[getSectionName(shdrs[i])]));
/* And the st_info mappings. */
for (unsigned int i = 1; i < rdi(hdr()->e_shnum); ++i)
if (rdi(shdrs.at(i).sh_info) != 0 &&
(rdi(shdrs.at(i).sh_type) == SHT_REL || rdi(shdrs.at(i).sh_type) == SHT_RELA))
wri(shdrs.at(i).sh_info,
getSectionIndex(info.at(getSectionName(shdrs.at(i)))));
/* And the .shstrtab index. Note: the match here is done by checking the offset as searching
* by name can yield incorrect results in case there are multiple sections with the same
* name as the one initially pointed by hdr()->e_shstrndx */
for (unsigned int i = 1; i < rdi(hdr()->e_shnum); ++i) {
if (shdrs.at(i).sh_offset == shstrtab.sh_offset) {
wri(hdr()->e_shstrndx, i);
}
}
}
static void writeFile(const std::string & fileName, const FileContents & contents)
{
debug("writing %s\n", fileName.c_str());
int fd = open(fileName.c_str(), O_CREAT | O_TRUNC | O_WRONLY | O_BINARY, 0777);
if (fd == -1)
error("open");
size_t bytesWritten = 0;
ssize_t portion;
while (bytesWritten < contents->size()) {
if ((portion = write(fd, contents->data() + bytesWritten, contents->size() - bytesWritten)) < 0) {
if (errno == EINTR)
continue;
error("write");
}
bytesWritten += portion;
}
if (close(fd) >= 0)
return;
/*
* Just ignore EINTR; a retry loop is the wrong thing to do.
*
* http://lkml.indiana.edu/hypermail/linux/kernel/0509.1/0877.html
* https://bugzilla.gnome.org/show_bug.cgi?id=682819
* http://utcc.utoronto.ca/~cks/space/blog/unix/CloseEINTR
* https://sites.google.com/site/michaelsafyan/software-engineering/checkforeintrwheninvokingclosethinkagain
*/
if (errno == EINTR)
return;
error("close");
}
static uint64_t roundUp(uint64_t n, uint64_t m)
{
if (n == 0)
return m;
return ((n - 1) / m + 1) * m;
}
template<ElfFileParams>
void ElfFile<ElfFileParamNames>::shiftFile(unsigned int extraPages, size_t startOffset, size_t extraBytes)
{
assert(startOffset >= sizeof(Elf_Ehdr));
unsigned int oldSize = fileContents->size();
assert(oldSize > startOffset);
/* Move the entire contents of the file after 'startOffset' by 'extraPages' pages further. */
unsigned int shift = extraPages * getPageSize();
fileContents->resize(oldSize + shift, 0);
memmove(fileContents->data() + startOffset + shift, fileContents->data() + startOffset, oldSize - startOffset);
memset(fileContents->data() + startOffset, 0, shift);
/* Adjust the ELF header. */
wri(hdr()->e_phoff, sizeof(Elf_Ehdr));
if (rdi(hdr()->e_shoff) >= startOffset)
wri(hdr()->e_shoff, rdi(hdr()->e_shoff) + shift);
/* Update the offsets in the section headers. */
for (int i = 1; i < rdi(hdr()->e_shnum); ++i) {
size_t sh_offset = rdi(shdrs.at(i).sh_offset);
if (sh_offset >= startOffset)
wri(shdrs.at(i).sh_offset, sh_offset + shift);
}
int splitIndex = -1;
size_t splitShift = 0;
/* Update the offsets in the program headers. */
for (int i = 0; i < rdi(hdr()->e_phnum); ++i) {
Elf_Off p_start = rdi(phdrs.at(i).p_offset);
if (p_start <= startOffset && p_start + rdi(phdrs.at(i).p_filesz) > startOffset && rdi(phdrs.at(i).p_type) == PT_LOAD) {
assert(splitIndex == -1);
splitIndex = i;
splitShift = startOffset - p_start;
/* This is the load segment we're currently extending within, so we split it. */
wri(phdrs.at(i).p_offset, startOffset);
wri(phdrs.at(i).p_memsz, rdi(phdrs.at(i).p_memsz) - splitShift);
wri(phdrs.at(i).p_filesz, rdi(phdrs.at(i).p_filesz) - splitShift);
wri(phdrs.at(i).p_paddr, rdi(phdrs.at(i).p_paddr) + splitShift);
wri(phdrs.at(i).p_vaddr, rdi(phdrs.at(i).p_vaddr) + splitShift);
p_start = startOffset;
}
if (p_start >= startOffset) {
wri(phdrs.at(i).p_offset, p_start + shift);
if (rdi(phdrs.at(i).p_align) != 0 &&
(rdi(phdrs.at(i).p_vaddr) - rdi(phdrs.at(i).p_offset)) % rdi(phdrs.at(i).p_align) != 0) {
debug("changing alignment of program header %d from %d to %d\n", i,
rdi(phdrs.at(i).p_align), getPageSize());
wri(phdrs.at(i).p_align, getPageSize());
}
} else {
/* If we're not physically shifting, shift back virtual memory. */
if (rdi(phdrs.at(i).p_paddr) >= shift)
wri(phdrs.at(i).p_paddr, rdi(phdrs.at(i).p_paddr) - shift);
if (rdi(phdrs.at(i).p_vaddr) >= shift)
wri(phdrs.at(i).p_vaddr, rdi(phdrs.at(i).p_vaddr) - shift);
}
}
assert(splitIndex != -1);
/* Add a segment that maps the new program/section headers and
PT_INTERP segment into memory. Otherwise glibc will choke. */
phdrs.resize(rdi(hdr()->e_phnum) + 1);
wri(hdr()->e_phnum, rdi(hdr()->e_phnum) + 1);
Elf_Phdr & phdr = phdrs.at(rdi(hdr()->e_phnum) - 1);
wri(phdr.p_type, PT_LOAD);
wri(phdr.p_offset, phdrs.at(splitIndex).p_offset - splitShift - shift);
wri(phdr.p_paddr, phdrs.at(splitIndex).p_paddr - splitShift - shift);
wri(phdr.p_vaddr, phdrs.at(splitIndex).p_vaddr - splitShift - shift);
wri(phdr.p_filesz, wri(phdr.p_memsz, splitShift + extraBytes));
wri(phdr.p_flags, PF_R | PF_W);
wri(phdr.p_align, getPageSize());
}
template<ElfFileParams>
std::string ElfFile<ElfFileParamNames>::getSectionName(const Elf_Shdr & shdr) const
{
const size_t name_off = rdi(shdr.sh_name);
if (name_off >= sectionNames.size())
error("section name offset out of bounds");
return std::string(sectionNames.c_str() + name_off);
}
template<ElfFileParams>
const Elf_Shdr & ElfFile<ElfFileParamNames>::findSectionHeader(const SectionName & sectionName) const
{
auto shdr = tryFindSectionHeader(sectionName);
if (!shdr) {
std::string extraMsg;
if (sectionName == ".interp" || sectionName == ".dynamic" || sectionName == ".dynstr")
extraMsg = ". The input file is most likely statically linked";
error("cannot find section '" + sectionName + "'" + extraMsg);
}
return *shdr;
}
template<ElfFileParams>
std::optional<std::reference_wrapper<const Elf_Shdr>> ElfFile<ElfFileParamNames>::tryFindSectionHeader(const SectionName & sectionName) const
{
auto i = getSectionIndex(sectionName);
if (i)
return shdrs.at(i);
return {};
}
template<ElfFileParams>
template<class T>
span<T> ElfFile<ElfFileParamNames>::getSectionSpan(const Elf_Shdr & shdr) const
{
return span((T*)(fileContents->data() + rdi(shdr.sh_offset)), rdi(shdr.sh_size)/sizeof(T));
}
template<ElfFileParams>
template<class T>
span<T> ElfFile<ElfFileParamNames>::getSectionSpan(const SectionName & sectionName)
{
return getSectionSpan<T>(findSectionHeader(sectionName));
}
template<ElfFileParams>
template<class T>
span<T> ElfFile<ElfFileParamNames>::tryGetSectionSpan(const SectionName & sectionName)
{
auto shdrOpt = tryFindSectionHeader(sectionName);
return shdrOpt ? getSectionSpan<T>(*shdrOpt) : span<T>();
}
template<ElfFileParams>
unsigned int ElfFile<ElfFileParamNames>::getSectionIndex(const SectionName & sectionName) const
{
for (unsigned int i = 1; i < rdi(hdr()->e_shnum); ++i)
if (getSectionName(shdrs.at(i)) == sectionName) return i;
return 0;
}
template<ElfFileParams>
bool ElfFile<ElfFileParamNames>::haveReplacedSection(const SectionName & sectionName) const
{
return replacedSections.count(sectionName);
}
template<ElfFileParams>
std::string & ElfFile<ElfFileParamNames>::replaceSection(const SectionName & sectionName,
unsigned int size)
{
auto i = replacedSections.find(sectionName);
std::string s;
if (i != replacedSections.end()) {
s = std::string(i->second);
} else {
auto shdr = findSectionHeader(sectionName);
s = extractString(fileContents, rdi(shdr.sh_offset), rdi(shdr.sh_size));
}
s.resize(size);
replacedSections[sectionName] = s;
return replacedSections[sectionName];
}
template<ElfFileParams>
void ElfFile<ElfFileParamNames>::writeReplacedSections(Elf_Off & curOff,
Elf_Addr startAddr, Elf_Off startOffset)
{
/* Overwrite the old section contents with 'X's. Do this
*before* writing the new section contents (below) to prevent
clobbering previously written new section contents. */
for (auto & i : replacedSections) {
const std::string & sectionName = i.first;
const Elf_Shdr & shdr = findSectionHeader(sectionName);
if (rdi(shdr.sh_type) != SHT_NOBITS)
memset(fileContents->data() + rdi(shdr.sh_offset), 'X', rdi(shdr.sh_size));
}
std::set<unsigned int> noted_phdrs = {};
/* We iterate over the sorted section headers here, so that the relative
position between replaced sections stays the same. */
for (auto & shdr : shdrs) {
std::string sectionName = getSectionName(shdr);
auto i = replacedSections.find(sectionName);
if (i == replacedSections.end())
continue;
Elf_Shdr orig_shdr = shdr;
debug("rewriting section '%s' from offset 0x%x (size %d) to offset 0x%x (size %d)\n",
sectionName.c_str(), rdi(shdr.sh_offset), rdi(shdr.sh_size), curOff, i->second.size());
memcpy(fileContents->data() + curOff, i->second.c_str(),
i->second.size());
/* Update the section header for this section. */
wri(shdr.sh_offset, curOff);
wri(shdr.sh_addr, startAddr + (curOff - startOffset));
wri(shdr.sh_size, i->second.size());
wri(shdr.sh_addralign, sectionAlignment);
/* If this is the .interp section, then the PT_INTERP segment
must be sync'ed with it. */
if (sectionName == ".interp") {
for (auto & phdr : phdrs) {
if (rdi(phdr.p_type) == PT_INTERP) {
phdr.p_offset = shdr.sh_offset;
phdr.p_vaddr = phdr.p_paddr = shdr.sh_addr;
phdr.p_filesz = phdr.p_memsz = shdr.sh_size;
}
}
}
/* If this is the .dynamic section, then the PT_DYNAMIC segment
must be sync'ed with it. */
else if (sectionName == ".dynamic") {
for (auto & phdr : phdrs) {
if (rdi(phdr.p_type) == PT_DYNAMIC) {
phdr.p_offset = shdr.sh_offset;
phdr.p_vaddr = phdr.p_paddr = shdr.sh_addr;
phdr.p_filesz = phdr.p_memsz = shdr.sh_size;
}
}
}
/* If this is a note section, there might be a PT_NOTE segment that
must be sync'ed with it. Note that normalizeNoteSegments() will have
already taken care of PT_NOTE segments containing multiple note
sections. At this point, we can assume that the segment will map to
exactly one section.
Note sections also have particular alignment constraints: the
data inside the section is formatted differently depending on the
section alignment. Keep the original alignment if possible. */
if (rdi(shdr.sh_type) == SHT_NOTE) {
if (orig_shdr.sh_addralign < sectionAlignment)
shdr.sh_addralign = orig_shdr.sh_addralign;
for (unsigned int j = 0; j < phdrs.size(); ++j) {
auto &phdr = phdrs.at(j);
if (rdi(phdr.p_type) == PT_NOTE && !noted_phdrs.count(j)) {
Elf_Off p_start = rdi(phdr.p_offset);
Elf_Off p_end = p_start + rdi(phdr.p_filesz);
Elf_Off s_start = rdi(orig_shdr.sh_offset);
Elf_Off s_end = s_start + rdi(orig_shdr.sh_size);
/* Skip if no overlap. */
if (!(s_start >= p_start && s_start < p_end) &&
!(s_end > p_start && s_end <= p_end))
continue;
/* We only support exact matches. */
if (p_start != s_start || p_end != s_end)
error("unsupported overlap of SHT_NOTE and PT_NOTE");
phdr.p_offset = shdr.sh_offset;
phdr.p_vaddr = phdr.p_paddr = shdr.sh_addr;
phdr.p_filesz = phdr.p_memsz = shdr.sh_size;
noted_phdrs.insert(j);
}
}
}
/* If there is .MIPS.abiflags section, then the PT_MIPS_ABIFLAGS
segment must be sync'ed with it. */
if (sectionName == ".MIPS.abiflags") {
for (auto & phdr : phdrs) {
if (rdi(phdr.p_type) == PT_MIPS_ABIFLAGS) {
phdr.p_offset = shdr.sh_offset;
phdr.p_vaddr = phdr.p_paddr = shdr.sh_addr;
phdr.p_filesz = phdr.p_memsz = shdr.sh_size;
}
}
}
/* If there is .note.gnu.property section, then the PT_GNU_PROPERTY
segment must be sync'ed with it. */
if (sectionName == ".note.gnu.property") {
for (auto & phdr : phdrs) {
if (rdi(phdr.p_type) == PT_GNU_PROPERTY) {
phdr.p_offset = shdr.sh_offset;
phdr.p_vaddr = phdr.p_paddr = shdr.sh_addr;
phdr.p_filesz = phdr.p_memsz = shdr.sh_size;
}
}
}
curOff += roundUp(i->second.size(), sectionAlignment);
}
replacedSections.clear();
}
template<ElfFileParams>
void ElfFile<ElfFileParamNames>::rewriteSectionsLibrary()
{
/* For dynamic libraries, we just place the replacement sections
at the end of the file. They're mapped into memory by a
PT_LOAD segment located directly after the last virtual address
page of other segments. */
Elf_Addr startPage = 0;
Elf_Addr firstPage = 0;
unsigned alignStartPage = getPageSize();
for (auto & phdr : phdrs) {
Elf_Addr thisPage = rdi(phdr.p_vaddr) + rdi(phdr.p_memsz);
if (thisPage > startPage) startPage = thisPage;
if (rdi(phdr.p_type) == PT_PHDR) firstPage = rdi(phdr.p_vaddr) - rdi(phdr.p_offset);
unsigned thisAlign = rdi(phdr.p_align);
alignStartPage = std::max(alignStartPage, thisAlign);
}
startPage = roundUp(startPage, alignStartPage);
debug("last page is 0x%llx\n", (unsigned long long) startPage);
debug("first page is 0x%llx\n", (unsigned long long) firstPage);
/* When normalizing note segments we will in the worst case be adding
1 program header for each SHT_NOTE section. */
unsigned int num_notes = std::count_if(shdrs.begin(), shdrs.end(),
[this](Elf_Shdr shdr) { return rdi(shdr.sh_type) == SHT_NOTE; });
/* Because we're adding a new section header, we're necessarily increasing
the size of the program header table. This can cause the first section
to overlap the program header table in memory; we need to shift the first
few segments to someplace else. */
/* Some sections may already be replaced so account for that */
unsigned int i = 1;
Elf_Addr pht_size = sizeof(Elf_Ehdr) + (phdrs.size() + num_notes + 1)*sizeof(Elf_Phdr);
while( i < rdi(hdr()->e_shnum) && rdi(shdrs.at(i).sh_offset) <= pht_size ) {
if (not haveReplacedSection(getSectionName(shdrs.at(i))))
replaceSection(getSectionName(shdrs.at(i)), rdi(shdrs.at(i).sh_size));
i++;
}
bool moveHeaderTableToTheEnd = rdi(hdr()->e_shoff) < pht_size;
/* Compute the total space needed for the replaced sections */
off_t neededSpace = 0;
for (auto & s : replacedSections)
neededSpace += roundUp(s.second.size(), sectionAlignment);
off_t headerTableSpace = roundUp(rdi(hdr()->e_shnum) * rdi(hdr()->e_shentsize), sectionAlignment);
if (moveHeaderTableToTheEnd)
neededSpace += headerTableSpace;
debug("needed space is %d\n", neededSpace);
Elf_Off startOffset = roundUp(fileContents->size(), getPageSize());
// In older version of binutils (2.30), readelf would check if the dynamic
// section segment is strictly smaller than the file (and not same size).
// By making it one byte larger, we don't break readelf.
off_t binutilsQuirkPadding = 1;
fileContents->resize(startOffset + neededSpace + binutilsQuirkPadding, 0);
/* Even though this file is of type ET_DYN, it could actually be
an executable. For instance, Gold produces executables marked
ET_DYN as does LD when linking with pie. If we move PT_PHDR, it
has to stay in the first PT_LOAD segment or any subsequent ones
if they're continuous in memory due to linux kernel constraints
(see BUGS). Since the end of the file would be after bss, we can't
move PHDR there, we therefore choose to leave PT_PHDR where it is but
move enough following sections such that we can add the extra PT_LOAD
section to it. This PT_LOAD segment ensures the sections at the end of
the file are mapped into memory for ld.so to process.
We can't use the approach in rewriteSectionsExecutable()
since DYN executables tend to start at virtual address 0, so
rewriteSectionsExecutable() won't work because it doesn't have
any virtual address space to grow downwards into. */
if (isExecutable && startOffset > startPage) {
debug("shifting new PT_LOAD segment by %d bytes to work around a Linux kernel bug\n", startOffset - startPage);
startPage = startOffset;
}
wri(hdr()->e_phoff, sizeof(Elf_Ehdr));
bool needNewSegment = true;
auto& lastSeg = phdrs.back();
/* Try to extend the last segment to include replaced sections */
if (!phdrs.empty() &&
rdi(lastSeg.p_type) == PT_LOAD &&
rdi(lastSeg.p_flags) == (PF_R | PF_W) &&
rdi(lastSeg.p_align) == alignStartPage) {
auto segEnd = roundUp(rdi(lastSeg.p_offset) + rdi(lastSeg.p_memsz), getPageSize());
if (segEnd == startOffset) {
auto newSz = startOffset + neededSpace - rdi(lastSeg.p_offset);
wri(lastSeg.p_filesz, wri(lastSeg.p_memsz, newSz));
needNewSegment = false;
}
}
if (needNewSegment) {
/* Add a segment that maps the replaced sections into memory. */
phdrs.resize(rdi(hdr()->e_phnum) + 1);
wri(hdr()->e_phnum, rdi(hdr()->e_phnum) + 1);
Elf_Phdr & phdr = phdrs.at(rdi(hdr()->e_phnum) - 1);
wri(phdr.p_type, PT_LOAD);
wri(phdr.p_offset, startOffset);
wri(phdr.p_vaddr, wri(phdr.p_paddr, startPage));
wri(phdr.p_filesz, wri(phdr.p_memsz, neededSpace));
wri(phdr.p_flags, PF_R | PF_W);
wri(phdr.p_align, alignStartPage);
}
normalizeNoteSegments();
/* Write out the replaced sections. */
Elf_Off curOff = startOffset;
if (moveHeaderTableToTheEnd) {
debug("Moving the shtable to offset %d\n", curOff);
wri(hdr()->e_shoff, curOff);
curOff += headerTableSpace;
}
writeReplacedSections(curOff, startPage, startOffset);
assert(curOff == startOffset + neededSpace);
/* Write out the updated program and section headers */
rewriteHeaders(firstPage + rdi(hdr()->e_phoff));
}
static bool noSort = false;
template<ElfFileParams>
void ElfFile<ElfFileParamNames>::rewriteSectionsExecutable()
{
if (!noSort) {
/* Sort the sections by offset, otherwise we won't correctly find
all the sections before the last replaced section. */
sortShdrs();
}
/* What is the index of the last replaced section? */
unsigned int lastReplaced = 0;
for (unsigned int i = 1; i < rdi(hdr()->e_shnum); ++i) {
std::string sectionName = getSectionName(shdrs.at(i));
if (replacedSections.count(sectionName)) {
debug("using replaced section '%s'\n", sectionName.c_str());
lastReplaced = i;
}
}
assert(lastReplaced != 0);
debug("last replaced is %d\n", lastReplaced);
/* Try to replace all sections before that, as far as possible.
Stop when we reach an irreplacable section (such as one of type
SHT_PROGBITS). These cannot be moved in virtual address space
since that would invalidate absolute references to them. */
assert(lastReplaced + 1 < shdrs.size()); /* !!! I'm lazy. */
size_t startOffset = rdi(shdrs.at(lastReplaced + 1).sh_offset);
Elf_Addr startAddr = rdi(shdrs.at(lastReplaced + 1).sh_addr);
std::string prevSection;
for (unsigned int i = 1; i <= lastReplaced; ++i) {
Elf_Shdr & shdr(shdrs.at(i));
std::string sectionName = getSectionName(shdr);
debug("looking at section '%s'\n", sectionName.c_str());
/* !!! Why do we stop after a .dynstr section? I can't
remember! */
if ((rdi(shdr.sh_type) == SHT_PROGBITS && sectionName != ".interp")
|| prevSection == ".dynstr")
{
startOffset = rdi(shdr.sh_offset);
startAddr = rdi(shdr.sh_addr);
lastReplaced = i - 1;
break;
}
if (!replacedSections.count(sectionName)) {
debug("replacing section '%s' which is in the way\n", sectionName.c_str());
replaceSection(sectionName, rdi(shdr.sh_size));
}
prevSection = std::move(sectionName);
}
debug("first reserved offset/addr is 0x%x/0x%llx\n",
startOffset, (unsigned long long) startAddr);
assert(startAddr % getPageSize() == startOffset % getPageSize());
Elf_Addr firstPage = startAddr - startOffset;
debug("first page is 0x%llx\n", (unsigned long long) firstPage);
if (rdi(hdr()->e_shoff) < startOffset) {
/* The section headers occur too early in the file and would be
overwritten by the replaced sections. Move them to the end of the file
before proceeding. */
off_t shoffNew = fileContents->size();
off_t shSize = rdi(hdr()->e_shoff) + rdi(hdr()->e_shnum) * rdi(hdr()->e_shentsize);
fileContents->resize(fileContents->size() + shSize, 0);
wri(hdr()->e_shoff, shoffNew);
/* Rewrite the section header table. For neatness, keep the
sections sorted. */
assert(rdi(hdr()->e_shnum) == shdrs.size());
sortShdrs();
for (unsigned int i = 1; i < rdi(hdr()->e_shnum); ++i)
* ((Elf_Shdr *) (fileContents->data() + rdi(hdr()->e_shoff)) + i) = shdrs.at(i);
}