-
-
Notifications
You must be signed in to change notification settings - Fork 35.4k
Expand file tree
/
Copy pathlayout_check.cpp
More file actions
1576 lines (1335 loc) Β· 51.5 KB
/
layout_check.cpp
File metadata and controls
1576 lines (1335 loc) Β· 51.5 KB
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
/* Copyright 2021 - 2025 R. Thomas
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <spdlog/fmt/fmt.h>
#include "MachO/Structures.hpp"
#include "LIEF/BinaryStream/SpanStream.hpp"
#include "LIEF/MachO/AtomInfo.hpp"
#include "LIEF/MachO/FatBinary.hpp"
#include "LIEF/MachO/Binary.hpp"
#include "LIEF/MachO/Routine.hpp"
#include "LIEF/MachO/CodeSignature.hpp"
#include "LIEF/MachO/CodeSignatureDir.hpp"
#include "LIEF/MachO/DataInCode.hpp"
#include "LIEF/MachO/DyldChainedFixups.hpp"
#include "LIEF/MachO/DyldExportsTrie.hpp"
#include "LIEF/MachO/DyldInfo.hpp"
#include "LIEF/MachO/DylibCommand.hpp"
#include "LIEF/MachO/DynamicSymbolCommand.hpp"
#include "LIEF/MachO/FunctionStarts.hpp"
#include "LIEF/MachO/FunctionVariants.hpp"
#include "LIEF/MachO/FunctionVariantFixups.hpp"
#include "LIEF/MachO/LinkerOptHint.hpp"
#include "LIEF/MachO/MainCommand.hpp"
#include "LIEF/MachO/RPathCommand.hpp"
#include "LIEF/MachO/Section.hpp"
#include "LIEF/MachO/SegmentCommand.hpp"
#include "LIEF/MachO/SegmentSplitInfo.hpp"
#include "LIEF/MachO/SymbolCommand.hpp"
#include "LIEF/MachO/ThreadCommand.hpp"
#include "LIEF/MachO/TwoLevelHints.hpp"
#include "LIEF/MachO/utils.hpp"
#include "LIEF/utils.hpp"
#include "MachO/ChainedFixup.hpp"
#include "logging.hpp"
#include "Object.tcc"
#include <string>
namespace LIEF::MachO {
template<typename T, typename U>
inline bool greater_than_add_or_overflow(T LHS, T RHS, U B) {
return (LHS > B) || (RHS > (B - LHS));
}
inline uint64_t rnd64(uint64_t v, uint64_t r) {
r--;
v += r;
v &= ~static_cast<int64_t>(r);
return v;
}
inline uint64_t rnd(uint64_t v, uint64_t r) {
return rnd64(v, r);
}
class LayoutChecker {
public:
LayoutChecker() = delete;
LayoutChecker(const Binary& macho) :
binary(macho)
{}
bool check();
bool error(std::string msg) {
error_msg = std::move(msg);
return false;
}
template <typename... Args>
bool error(const char *fmt, const Args &... args) {
error_msg = fmt::vformat(fmt, fmt::make_format_args(args...));
return false;
}
// Return true if segments overlap
bool check_overlapping();
// Mirror MachOAnalyzer::validLoadCommands
bool check_load_commands();
// Mirror of MachOAnalyzer::validMain
bool check_main();
// Mirror of MachOAnalyzer::validEmbeddedPaths
bool check_valid_paths();
// Mirror of Image::validStructureLinkedit (version: dyld-1235.2)
bool check_linkedit();
// Mirror of MachOFile::validSegments
bool check_segments();
// Mirror Image::validInitializers
bool check_initializers();
// Mirror ChainedFixups::valid
bool check_chained_fixups();
// Check from PR #1136
// See: https://github.com/lief-project/LIEF/pull/1136/files#r1882625692
bool check_section_contiguity();
// From FunctionVariants::valid()
bool check_function_variants();
bool check_linkedit_end();
size_t ptr_size() const {
return binary.header().is_32bit() ? sizeof(uint32_t) :
sizeof(uint64_t);
}
const std::string& get_error() const {
return error_msg;
}
private:
std::string error_msg;
const Binary& binary;
};
bool LayoutChecker::check_initializers() {
struct range_t {
uint64_t va_start = 0;
uint64_t va_end = 0;
uint64_t filesz = 0;
};
class ranges_t : public std::vector<range_t> {
public:
using base_t = std::vector<range_t>;
using base_t::base_t;
bool contain(uint64_t addr) const {
return std::find_if(begin(), end(), [addr] (const range_t& R) {
return R.va_start <= addr && addr < (R.va_start + R.va_end);
}) != end();
}
};
const size_t ptr_size = this->ptr_size();
const uint64_t imagebase = binary.imagebase();
ranges_t ranges;
ranges.reserve(binary.segments().size());
for (const SegmentCommand& segment : binary.segments()) {
if (segment.is(SegmentCommand::VM_PROTECTIONS::EXECUTE)) {
ranges.push_back({
segment.virtual_address(), segment.virtual_address() + segment.virtual_size(),
segment.file_size()
});
}
}
if (ranges.empty()) {
return error("no executable segments");
}
for (const LoadCommand& cmd : binary.commands()) {
const auto* routines = cmd.cast<Routine>();
if (routines == nullptr) {
continue;
}
uint64_t init_addr = routines->init_address();
if (!ranges.contain(init_addr)) {
return error("LC_ROUTINE/64 initializer 0x{:016x} is not an offset "
"to an executable segment", init_addr);
}
}
for (const Section& section : binary.sections()) {
const bool contains_init_ptr =
section.type() == Section::TYPE::MOD_INIT_FUNC_POINTERS ||
section.type() == Section::TYPE::MOD_TERM_FUNC_POINTERS;
if (!contains_init_ptr) {
continue;
}
if (section.size() % ptr_size != 0) {
return error("Section '{}' size (0x{:08x}) is not a multiple of pointer-size",
section.name(), section.size());
}
if (section.address() % ptr_size != 0) {
return error("Section '{}' address (0x{:08x}) is not pointer aligned",
section.name(), section.address());
}
SpanStream stream(section.content());
while (stream) {
uint64_t ptr = 0;
if (ptr_size == sizeof(uint32_t)) {
auto res = stream.read<uint32_t>();
if (!res) {
return error("Can't read pointer at 0x{:04x} in {}",
stream.pos(), section.name());
}
// As mentioned in the dyld documentation:
// > FIXME: as a quick hack, the low 32-bits with either rebase opcodes
// > or chained fixups is offset in image
ptr = (uint32_t)*res;
} else {
auto res = stream.read<uint64_t>();
if (!res) {
return error("Can't read pointer at 0x{:04x} in {}",
stream.pos(), section.name());
}
// As mentioned in the dyld documentation:
// > FIXME: as a quick hack, the low 32-bits with either rebase opcodes
// > or chained fixups is offset in image
ptr = *res & 0x03FFFFFF;
}
if (!ranges.contain(imagebase + ptr)) {
return error("initializer at 0x{:06x} in {} is not in an executable segment",
stream.pos(), section.name());
}
}
}
for (const Section& section : binary.sections()) {
if (section.type() != Section::TYPE::INIT_FUNC_OFFSETS) {
continue;
}
if (section.segment()->is(SegmentCommand::VM_PROTECTIONS::WRITE)) {
return error("initializer offsets section {}/{} must be in read-only segment",
section.segment_name(), section.name());
}
if (section.size() % 4 != 0) {
return error("initializer offsets section {}/{} has bad size",
section.segment_name(), section.name());
}
if (section.address() % 4 != 0) {
return error("initializer offsets section {}/{} is not 4-byte aligned",
section.segment_name(), section.name());
}
SpanStream stream(section.content());
while (stream) {
auto res = stream.read<uint32_t>();
if (!res) {
return error("Can't read pointer at 0x{:04} in {}",
stream.pos(), section.name());
}
if (!ranges.contain(imagebase + *res)) {
return error("initializer 0x{:08x} is not an offset to an executable "
"segment", *res);
}
}
}
return true;
}
bool LayoutChecker::check_segments() {
const size_t sizeof_segment_hdr = binary.header().is_32bit() ?
sizeof(details::segment_command_32) : sizeof(details::segment_command_64);
const size_t sizeof_section_hdr = binary.header().is_32bit() ?
sizeof(details::section_32) : sizeof(details::section_64);
for (const SegmentCommand& segment : binary.segments()) {
int32_t section_space = segment.size() - sizeof_segment_hdr;
if (section_space < 0) {
return error("load command is too small for LC_SEGMENT/64: {}",
segment.name());
}
if ((section_space % sizeof_section_hdr) != 0) {
return error("segment load command size {}: 0x{:04x} will not fit "
"whole number of sections", segment.name(), segment.size());
}
if ((uint32_t)section_space != segment.numberof_sections() * sizeof_section_hdr) {
return error("segment {} does not match nsects", segment.name(),
segment.numberof_sections());
}
if ((segment.file_size() > segment.virtual_size()) &&
(segment.virtual_size() != 0 || (segment.flags() & (uint32_t)SegmentCommand::FLAGS::NORELOC) != 0))
{
return error("in segment {}, filesize exceeds vmsize", segment.name());
}
if ((segment.init_protection() & 0xFFFFFFF8) != 0) {
return error("{} segment permissions has invalid bits set", segment.name());
}
}
if (const SegmentCommand* text_seg = binary.get_segment("__TEXT")) {
static constexpr auto R_X = (uint32_t)SegmentCommand::VM_PROTECTIONS::READ |
(uint32_t)SegmentCommand::VM_PROTECTIONS::EXECUTE;
if (text_seg->init_protection() != R_X) {
return error("__TEXT segment must be r-x");
}
}
if (const SegmentCommand* lnk_seg = binary.get_segment("__LINKEDIT")) {
static constexpr auto RO = (uint32_t)SegmentCommand::VM_PROTECTIONS::READ;
if (lnk_seg->init_protection() != RO) {
return error("__LINKEDIT segment must be read only");
}
}
return true;
}
bool LayoutChecker::check_overlapping() {
for (const SegmentCommand& lhs : binary.segments()) {
const uint64_t lhs_vm_end = lhs.virtual_address() + lhs.virtual_size();
const uint64_t lhs_file_end = lhs.file_offset() + lhs.file_size();
for (const SegmentCommand& rhs : binary.segments()) {
if (lhs.index() == rhs.index()) {
continue;
}
const uint64_t rhs_vm_end = rhs.virtual_address() + rhs.virtual_size();
const uint64_t rhs_file_end = rhs.file_offset() + rhs.file_size();
const bool vm_overalp = (rhs.virtual_address() <= lhs.virtual_address() && rhs_vm_end > lhs.virtual_address() && lhs_vm_end > lhs.virtual_address()) ||
(rhs.virtual_address() >= lhs.virtual_address() && rhs.virtual_address() < lhs_vm_end && rhs_vm_end > rhs.virtual_address());
if (vm_overalp) {
error(R"delim(
Segments '{}' and '{}' overlap (virtual addresses):
[0x{:08x}, 0x{:08x}] [0x{:08x}, 0x{:08x}]
)delim", lhs.name(), rhs.name(),
lhs.virtual_address(), lhs_vm_end, rhs.virtual_address(), rhs_vm_end);
return true;
}
const bool file_overlap = (rhs.file_offset() <= lhs.file_offset() && rhs_file_end > lhs.file_offset() && lhs_file_end > lhs.file_offset()) ||
(rhs.file_offset() >= lhs.file_offset() && rhs.file_offset() < lhs_file_end && rhs_file_end > rhs.file_offset());
if (file_overlap) {
error(R"delim(
Segments '{}' and '{}' overlap (file offsets):
[0x{:08x}, 0x{:08x}] [0x{:08x}, 0x{:08x}]
)delim", lhs.name(), rhs.name(),
lhs.file_offset(), lhs_file_end, rhs.file_offset(), rhs_file_end);
return true;
}
if (lhs.index() < rhs.index()) {
const bool wrong_order = lhs.virtual_address() > rhs.virtual_address() ||
(lhs.file_offset() > rhs.file_offset() && lhs.file_offset() != 0 && rhs.file_offset() != 0);
if (wrong_order) {
error(R"delim(
Segments '{}' and '{}' are wrongly ordered
)delim", lhs.name(), rhs.name());
return true;
}
}
}
}
return false;
}
// Mirror MachOAnalyzer::validLoadCommands
bool LayoutChecker::check_load_commands() {
const size_t sizeof_header =
binary.header().is_32bit() ? sizeof(details::mach_header) :
sizeof(details::mach_header_64);
const size_t last_cmd_offset = sizeof_header + binary.header().sizeof_cmds();
if (last_cmd_offset > binary.original_size()) {
return error("Load commands exceed length of file");
}
const auto& commands = binary.commands();
for (size_t i = 0; i < commands.size(); ++i) {
const LoadCommand& cmd = commands[i];
if (cmd.command_offset() > last_cmd_offset ||
(cmd.command_offset() + cmd.size()) > last_cmd_offset)
{
return error("Command #{} ({}) pasts the end of the commands", i,
to_string(cmd.command()));
}
if (const auto* lib = cmd.cast<DylibCommand>()) {
if (lib->name_offset() > lib->size()) {
return error("{}: load command {} name offset ({}) outside its size ({})",
lib->name(), to_string(cmd.command()), lib->name_offset(),
lib->size());
}
span<const uint8_t> raw = cmd.data();
const auto start = raw.begin() + lib->name_offset();
auto it = std::find(start, raw.end(), '\0');
if (it == raw.end()) {
return error("{}: string extends beyond end of load command", lib->name());
}
}
if (const auto* rpath = cmd.cast<RPathCommand>()) {
if (rpath->path_offset() > rpath->size()) {
return error("{}: load command {} name offset ({}) outside its size ({})",
rpath->path(), to_string(cmd.command()), rpath->path_offset(),
rpath->size());
}
span<const uint8_t> raw = cmd.data();
const auto start = raw.begin() + rpath->path_offset();
auto it = std::find(start, raw.end(), '\0');
if (it == raw.end()) {
return error("{}: string extends beyond end of load command", rpath->path());
}
}
}
return true;
}
// Mirror of MachOAnalyzer::validMain
bool LayoutChecker::check_main() {
if (binary.header().file_type() != Header::FILE_TYPE::EXECUTE) {
return true;
}
bool has_main = false;
bool has_thread = false;
if (const MainCommand* cmd = binary.main_command()) {
has_main = true;
uint64_t start_address = binary.imagebase() + cmd->entrypoint();
const SegmentCommand* segment = binary.segment_from_virtual_address(start_address);
if (segment == nullptr) {
return error("LC_MAIN entryoff is out of range");
}
if (!segment->is(SegmentCommand::VM_PROTECTIONS::EXECUTE)) {
return error("LC_MAIN points to non-executable segment");
}
}
if (const ThreadCommand* cmd = binary.thread_command()) {
has_thread = true;
uint64_t start_address = cmd->pc();
if (start_address == 0) {
return error("LC_UNIXTHREAD not valid for the current arch");
}
const SegmentCommand* segment = binary.segment_from_virtual_address(start_address);
if (segment == nullptr) {
return error("LC_MAIN entryoff is out of range");
}
if (!segment->is(SegmentCommand::VM_PROTECTIONS::EXECUTE)) {
return error("LC_MAIN points to non-executable segment");
}
}
if (has_main || has_thread) {
return true;
}
if (!has_main && !has_thread) {
return error("Missing LC_MAIN or LC_UNIXTHREAD command");
}
return error("only one LC_MAIN or LC_UNIXTHREAD is allowed");
}
// Mirror of MachOAnalyzer::validEmbeddedPaths
bool LayoutChecker::check_valid_paths() {
bool has_install_name = false;
int dependents_count = 0;
for (const LoadCommand& cmd : binary.commands()) {
switch (cmd.command()) {
case LoadCommand::TYPE::ID_DYLIB:
{
has_install_name = true;
[[fallthrough]];
}
case LoadCommand::TYPE::LOAD_DYLIB:
case LoadCommand::TYPE::LOAD_WEAK_DYLIB:
case LoadCommand::TYPE::REEXPORT_DYLIB:
case LoadCommand::TYPE::LOAD_UPWARD_DYLIB:
{
if (!DylibCommand::classof(&cmd)) {
LIEF_ERR("{} is not associated with a DylibCommand which should be the case",
to_string(cmd.command()));
break;
}
auto& dylib = *cmd.as<DylibCommand>();
if (dylib.command() != LoadCommand::TYPE::ID_DYLIB) {
++dependents_count;
}
break;
}
default: {}
}
}
const Header::FILE_TYPE ftype = binary.header().file_type();
if (ftype == Header::FILE_TYPE::DYLIB) {
if (!has_install_name) {
return error("Missing a LC_ID_DYLIB command for a MH_DYLIB file");
}
} else {
if (has_install_name) {
return error("LC_ID_DYLIB command found in a non MH_DYLIB file");
}
}
const bool is_dynamic_exe =
ftype == Header::FILE_TYPE::EXECUTE && binary.has(LoadCommand::TYPE::LOAD_DYLINKER);
if (dependents_count == 0 && is_dynamic_exe) {
return error("Missing libraries. It must link with at least one library "
"(like libSystem.dylib)");
}
return true;
}
// Mirror of Image::validStructureLinkedit (version: dyld-1235.2)
bool LayoutChecker::check_linkedit() {
struct chunk_t {
enum class KIND {
UNKNOWN = 0,
SYMTAB, SYMTAB_STR,
DYSYMTAB_LOC_REL, DYSYMTAB_EXT_REL, DYSYMTAB_INDIRECT_SYM,
DYLD_INFO_REBASES, DYLD_INFO_BIND,
DYLD_INFO_WEAK_BIND, DYLD_INFO_LAZY_BIND,
DYLD_INFO_EXPORT,
SEGMENT_SPLIT_INFO,
ATOM_INFO,
FUNCTION_STARTS,
DATA_IN_CODE,
CODE_SIGNATURE,
DYLD_EXPORT_TRIE,
DYLD_CHAINED_FIXUPS
};
static const char* to_string(KIND kind) {
switch (kind) {
case KIND::UNKNOWN: return "UNKNOWN";
case KIND::SYMTAB: return "SYMTAB";
case KIND::SYMTAB_STR: return "SYMTAB_STR";
case KIND::DYSYMTAB_LOC_REL: return "DYSYMTAB_LOC_REL";
case KIND::DYSYMTAB_EXT_REL: return "DYSYMTAB_EXT_REL";
case KIND::DYSYMTAB_INDIRECT_SYM: return "DYSYMTAB_INDIRECT_SYM";
case KIND::DYLD_INFO_REBASES: return "DYLD_INFO_REBASES";
case KIND::DYLD_INFO_BIND: return "DYLD_INFO_BIND";
case KIND::DYLD_INFO_WEAK_BIND: return "DYLD_INFO_WEAK_BIND";
case KIND::DYLD_INFO_LAZY_BIND: return "DYLD_INFO_LAZY_BIND";
case KIND::DYLD_INFO_EXPORT: return "DYLD_INFO_EXPORT";
case KIND::SEGMENT_SPLIT_INFO: return "SEGMENT_SPLIT_INFO";
case KIND::ATOM_INFO: return "ATOM_INFO";
case KIND::FUNCTION_STARTS: return "FUNCTION_STARTS";
case KIND::DATA_IN_CODE: return "DATA_IN_CODE";
case KIND::CODE_SIGNATURE: return "CODE_SIGNATURE";
case KIND::DYLD_EXPORT_TRIE: return "DYLD_EXPORT_TRIE";
case KIND::DYLD_CHAINED_FIXUPS: return "DYLD_CHAINED_FIXUPS";
}
return "UNKNOWN";
}
chunk_t() = delete;
chunk_t(KIND kind, uint32_t align, uint32_t off, size_t size) :
kind(kind), alignment(align), file_offset(off), size(size)
{}
chunk_t(const chunk_t&) = default;
chunk_t& operator=(const chunk_t&) = default;
chunk_t(chunk_t&&) = default;
chunk_t& operator=(chunk_t&&) = default;
KIND kind = KIND::UNKNOWN;
uint32_t alignment = 0;
uint32_t file_offset = 0;
size_t size = 0;
};
using chunks_t = std::vector<chunk_t>;
chunks_t chunks;
chunks.reserve(binary.commands().size());
static const auto sort_chunks = [] (chunks_t& chunks) {
const size_t count = chunks.size();
for (size_t i = 0; i < count; ++i) {
bool done = true;
for (size_t j = 0; j < count - i - 1; ++j) {
if (chunks[j].file_offset > chunks[j + 1].file_offset) {
std::swap(chunks[j], chunks[j + 1]);
done = false;
}
}
if (done) {
break;
}
}
};
bool has_external_relocs = false;
bool has_local_relocs = false;
uint32_t sym_count = 0;
uint32_t ind_sym_count = 0;
bool has_ind_sym_tab = false;
const size_t ptr_size = this->ptr_size();
for (const LoadCommand& cmd : binary.commands()) {
// LC_SYMTAB
if (const auto* symtab = cmd.cast<SymbolCommand>()) {
sym_count = symtab->numberof_symbols();
if (sym_count > 0x10000000) {
return error("LC_SYMTAB: symbol table too large ({})", sym_count);
}
chunks.emplace_back(chunk_t::KIND::SYMTAB, ptr_size,
symtab->symbol_offset(), symtab->symbol_table().size());
if (symtab->strings_size() > 0) {
chunks.emplace_back(chunk_t::KIND::SYMTAB_STR, 1,
symtab->strings_offset(), symtab->strings_size());
}
}
// LC_DYSYMTAB
if (const auto* dynsym = cmd.cast<DynamicSymbolCommand>()) {
has_ind_sym_tab = true;
has_external_relocs = dynsym->nb_external_relocations() != 0;
has_local_relocs = dynsym->nb_local_relocations() != 0;
if (size_t cnt = dynsym->nb_indirect_symbols(); cnt > 0x10000000) {
return error("LC_DYSYMTAB: indirect symbol table too large ({})", cnt);
}
if (size_t idx = dynsym->idx_local_symbol(); idx != 0) {
return error("LC_DYSYMTAB: indirect symbol table ilocalsym != 0");
}
if (dynsym->idx_external_define_symbol() != dynsym->nb_local_symbols()) {
return error("LC_DYSYMTAB: indirect symbol table ilocalsym != 0");
}
if (dynsym->idx_external_define_symbol() != dynsym->nb_local_symbols()) {
return error("LC_DYSYMTAB: indirect symbol table ilocalsym != 0");
}
if (dynsym->idx_undefined_symbol() != (dynsym->idx_external_define_symbol() +
dynsym->nb_external_define_symbols()))
{
return error("LC_DYSYMTAB: indirect symbol table "
"iundefsym != iextdefsym+nextdefsym");
}
ind_sym_count = dynsym->idx_undefined_symbol() + dynsym->nb_undefined_symbols();
if (dynsym->nb_local_relocations() != 0) {
chunks.emplace_back(chunk_t::KIND::DYSYMTAB_LOC_REL, ptr_size,
dynsym->local_relocation_offset(),
dynsym->nb_local_relocations() * sizeof(details::relocation_info));
}
if (dynsym->nb_external_relocations() != 0) {
chunks.emplace_back(chunk_t::KIND::DYSYMTAB_EXT_REL, ptr_size,
dynsym->external_relocation_offset(),
dynsym->nb_external_relocations() * sizeof(details::relocation_info));
}
if (dynsym->nb_indirect_symbols() != 0) {
chunks.emplace_back(chunk_t::KIND::DYSYMTAB_INDIRECT_SYM, 4,
dynsym->indirect_symbol_offset(),
dynsym->nb_indirect_symbols() * 4);
}
}
if (const auto* dyldinfo = cmd.cast<DyldInfo>()) {
if (auto info = dyldinfo->rebase(); info.second != 0) {
chunks.emplace_back(chunk_t::KIND::DYLD_INFO_REBASES, ptr_size,
info.first, info.second);
}
if (auto info = dyldinfo->bind(); info.second != 0) {
chunks.emplace_back(chunk_t::KIND::DYLD_INFO_BIND, ptr_size,
info.first, info.second);
}
if (auto info = dyldinfo->weak_bind(); info.second != 0) {
chunks.emplace_back(chunk_t::KIND::DYLD_INFO_WEAK_BIND, ptr_size,
info.first, info.second);
}
if (auto info = dyldinfo->lazy_bind(); info.second != 0) {
chunks.emplace_back(chunk_t::KIND::DYLD_INFO_LAZY_BIND, ptr_size,
info.first, info.second);
}
if (auto info = dyldinfo->export_info(); info.second != 0) {
chunks.emplace_back(chunk_t::KIND::DYLD_INFO_EXPORT, ptr_size,
info.first, info.second);
}
}
if (const auto* split_info = cmd.cast<SegmentSplitInfo>()) {
if (split_info->data_size() != 0) {
chunks.emplace_back(chunk_t::KIND::SEGMENT_SPLIT_INFO, ptr_size,
split_info->data_offset(), split_info->data_size());
}
}
if (const auto* info = cmd.cast<AtomInfo>()) {
if (info->data_size() != 0) {
chunks.emplace_back(chunk_t::KIND::ATOM_INFO, ptr_size,
info->data_offset(), info->data_size());
}
}
if (const auto* lnk_cmd = cmd.cast<FunctionStarts>()) {
if (lnk_cmd->data_size() != 0) {
chunks.emplace_back(chunk_t::KIND::FUNCTION_STARTS, ptr_size,
lnk_cmd->data_offset(), lnk_cmd->data_size());
}
}
if (const auto* lnk_cmd = cmd.cast<DataInCode>()) {
if (lnk_cmd->data_size() != 0) {
chunks.emplace_back(chunk_t::KIND::DATA_IN_CODE, ptr_size,
lnk_cmd->data_offset(), lnk_cmd->data_size());
}
}
if (const auto* lnk_cmd = cmd.cast<CodeSignature>()) {
if (lnk_cmd->data_size() != 0) {
chunks.emplace_back(chunk_t::KIND::CODE_SIGNATURE, ptr_size,
lnk_cmd->data_offset(), lnk_cmd->data_size());
}
}
if (const auto* lnk_cmd = cmd.cast<DyldExportsTrie>()) {
if (lnk_cmd->data_size() != 0) {
chunks.emplace_back(chunk_t::KIND::DYLD_EXPORT_TRIE, ptr_size,
lnk_cmd->data_offset(), lnk_cmd->data_size());
}
}
if (const auto* lnk_cmd = cmd.cast<DyldChainedFixups>()) {
if (lnk_cmd->data_size() != 0) {
chunks.emplace_back(chunk_t::KIND::DYLD_CHAINED_FIXUPS, ptr_size,
lnk_cmd->data_offset(), lnk_cmd->data_size());
}
}
}
if (has_ind_sym_tab && sym_count != ind_sym_count) {
return error("symbol count from symbol table and dynamic symbol table differ.");
}
const bool has_dyld_info = binary.has(LoadCommand::TYPE::DYLD_INFO_ONLY);
const bool has_dyld_chained_fixups = binary.has(LoadCommand::TYPE::DYLD_CHAINED_FIXUPS);
if (has_dyld_info && has_dyld_chained_fixups) {
return error("Contains LC_DYLD_INFO and LC_DYLD_CHAINED_FIXUPS.");
}
if (has_dyld_chained_fixups) {
if (has_local_relocs) {
return error("Contains LC_DYLD_CHAINED_FIXUPS and local relocations.");
}
if (has_external_relocs) {
return error("Contains LC_DYLD_CHAINED_FIXUPS and external relocations.");
}
}
uint64_t linkedit_file_offset_start = 0;
uint64_t linkedit_file_offset_end = 0;
if (binary.header().file_type() == Header::FILE_TYPE::OBJECT ||
binary.header().file_type() == Header::FILE_TYPE::PRELOAD)
{
for (const Section& section : binary.sections()) {
const bool is_zero_fill = section.type() == Section::TYPE::ZEROFILL ||
section.type() == Section::TYPE::THREAD_LOCAL_ZEROFILL;
if (is_zero_fill) {
continue;
}
const uint64_t section_end = section.offset() + section.size();
if (section_end > linkedit_file_offset_start) {
linkedit_file_offset_start = section_end;
}
linkedit_file_offset_end = binary.original_size();
if (linkedit_file_offset_start == 0) {
if (const auto* cmd = binary.get(LoadCommand::TYPE::SYMTAB)->cast<SymbolCommand>()) {
linkedit_file_offset_start = cmd->symbol_offset();
}
}
}
}
else {
if (const SegmentCommand* segment = binary.get_segment("__LINKEDIT")) {
linkedit_file_offset_start = segment->file_offset();
linkedit_file_offset_end = segment->file_offset() + segment->file_size();
}
if (linkedit_file_offset_start == 0 || linkedit_file_offset_end == 0) {
return error("bad or unknown fileoffset/size for LINKEDIT");
}
}
if (chunks.empty()) {
if (binary.header().file_type() == Header::FILE_TYPE::OBJECT) {
return true;
}
return error("Missing __LINKEDIT data");
}
sort_chunks(chunks);
uint64_t prev_end = linkedit_file_offset_start;
const char* prev_name = "start of __LINKEDIT";
for (size_t i = 0; i < chunks.size(); ++i) {
const chunk_t& chunk = chunks[i];
if (chunk.file_offset < prev_end) {
return error("LINKEDIT overlap of {} and {}",
prev_name, chunk_t::to_string(chunk.kind));
}
if (greater_than_add_or_overflow<uint64_t>(
chunk.file_offset, chunk.size, linkedit_file_offset_end))
{
return error("LINKEDIT content '{}' extends beyond end of segment",
chunk_t::to_string(chunk.kind));
}
if (chunk.file_offset & (chunk.alignment - 1)) {
// In the source code of dyld this is enforced only the provided
// policy ask to, but we might want to enforce it by default
return error("mis-aligned LINKEDIT content: {}", chunk_t::to_string(chunk.kind));
}
prev_end = chunk.file_offset + chunk.size;
prev_name = chunk_t::to_string(chunk.kind);
}
return true;
}
bool LayoutChecker::check_linkedit_end() {
if (binary.header().file_type() == Header::FILE_TYPE::OBJECT) {
return true;
}
const SegmentCommand* linkedit = binary.get_segment("__LINKEDIT");
if (linkedit == nullptr) {
return error("Missing __LINKEDIT segment");
}
if (linkedit->file_offset() + linkedit->file_size() != binary.original_size()) {
return error("__LINKEDIT segment does not wrap the end of the binary");
}
return true;
}
bool LayoutChecker::check_section_contiguity() {
if (binary.header().file_type() == Header::FILE_TYPE::OBJECT) {
// Skip this check for object file
return true;
}
// LIEF allocates space for new/extended sections between the last load command
// and the first section in the first segment.
// We are not willing to change the distance between the end of the `__text` section
// and start of `__DATA` segment, keeping `__text` section in a "fixed" position.
// Due to above there might happen a "reverse" alignment gap between `__text` section
// and a section that was allocated in front of it.
auto is_gap_reversed = [](const Section* LHS, const Section* RHS) {
return align_down(RHS->offset() - LHS->size(), LHS->alignment());
};
for (const SegmentCommand& segment : binary.segments()) {
std::vector<const Section*> sections_vec;
auto sections = segment.sections();
if (sections.empty()) {
continue;
}
sections_vec.reserve(segment.sections().size());
for (const Section& sec : sections) {
const Section::TYPE ty = sec.type();
if (ty == Section::TYPE::ZEROFILL ||
ty == Section::TYPE::THREAD_LOCAL_ZEROFILL ||
ty == Section::TYPE::GB_ZEROFILL)
{
continue;
}
sections_vec.push_back(&sec);
}
if (sections_vec.empty()) {
return true;
}
std::sort(sections_vec.begin(), sections_vec.end(),
[] (const Section* LHS, const Section* RHS) {
return LHS->offset() < RHS->offset();
});
uint64_t next_expected_offset = sections_vec[0]->offset();
for (auto it = sections_vec.begin(); it != sections_vec.end(); ++it) {
const Section* section = *it;
const uint32_t alignment = 1 << section->alignment();
if ((section->offset() % alignment) != 0) {
return error("section '{}' offset ({:#06x}) is misaligned (align={:#06x})",
section->name(), section->virtual_address(),
alignment);
}
next_expected_offset = align(next_expected_offset, alignment);
if (section->offset() != next_expected_offset) {
auto message = fmt::format("section '{}' is not at the expected offset: {:#06x} "
"(expected={:#06x}, align={:#06x})",
section->name(), section->offset(),
next_expected_offset, alignment);
if (it != sections_vec.begin() && is_gap_reversed(*std::prev(it), *it) && section->name() == "__text") {
LIEF_WARN("Permitting section gap which could be caused by LIEF add_section/extend_section: {}", message);
next_expected_offset = section->offset();
} else {
return error(message);
}
}
next_expected_offset += section->size();
}
}
return true;
}
bool LayoutChecker::check() {
if (binary.header().magic() == MACHO_TYPES::NEURAL_MODEL) {
return true;
}
if (check_overlapping()) {
return false;
}
if (!check_valid_paths()) {
return false;
}
if (!check_linkedit()) {
return false;
}
if (!check_segments()) {
return false;
}
if (!check_load_commands()) {
return false;
}
if (!check_main()) {
return false;
}
if (!check_initializers()) {
return false;
}
if (!check_chained_fixups()) {
return false;
}
if (!check_function_variants()) {
return false;
}
if (!check_section_contiguity()) {
return false;
}
if (!check_linkedit_end()) {
return false;
}
// The following checks are only relevant for non-object files
if (binary.header().file_type() == Header::FILE_TYPE::OBJECT) {
return true;