forked from llvm/llvm-project
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathllvm-jitlink.cpp
2023 lines (1713 loc) · 69.8 KB
/
llvm-jitlink.cpp
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
//===- llvm-jitlink.cpp -- Command line interface/tester for llvm-jitlink -===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
//
// This utility provides a simple command line interface to the llvm jitlink
// library, which makes relocatable object files executable in memory. Its
// primary function is as a testing utility for the jitlink library.
//
//===----------------------------------------------------------------------===//
#include "llvm-jitlink.h"
#include "llvm/BinaryFormat/Magic.h"
#include "llvm/ExecutionEngine/Orc/DebugObjectManagerPlugin.h"
#include "llvm/ExecutionEngine/Orc/DebuggerSupportPlugin.h"
#include "llvm/ExecutionEngine/Orc/ELFNixPlatform.h"
#include "llvm/ExecutionEngine/Orc/EPCDebugObjectRegistrar.h"
#include "llvm/ExecutionEngine/Orc/EPCDynamicLibrarySearchGenerator.h"
#include "llvm/ExecutionEngine/Orc/EPCEHFrameRegistrar.h"
#include "llvm/ExecutionEngine/Orc/ExecutionUtils.h"
#include "llvm/ExecutionEngine/Orc/IndirectionUtils.h"
#include "llvm/ExecutionEngine/Orc/MachOPlatform.h"
#include "llvm/ExecutionEngine/Orc/ObjectFileInterface.h"
#include "llvm/ExecutionEngine/Orc/TargetProcess/JITLoaderGDB.h"
#include "llvm/ExecutionEngine/Orc/TargetProcess/RegisterEHFrames.h"
#include "llvm/MC/MCAsmInfo.h"
#include "llvm/MC/MCContext.h"
#include "llvm/MC/MCDisassembler/MCDisassembler.h"
#include "llvm/MC/MCInstPrinter.h"
#include "llvm/MC/MCInstrAnalysis.h"
#include "llvm/MC/MCInstrInfo.h"
#include "llvm/MC/MCRegisterInfo.h"
#include "llvm/MC/MCSubtargetInfo.h"
#include "llvm/MC/MCTargetOptions.h"
#include "llvm/MC/TargetRegistry.h"
#include "llvm/Object/COFF.h"
#include "llvm/Object/MachO.h"
#include "llvm/Object/ObjectFile.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/InitLLVM.h"
#include "llvm/Support/MemoryBuffer.h"
#include "llvm/Support/Path.h"
#include "llvm/Support/Process.h"
#include "llvm/Support/TargetSelect.h"
#include "llvm/Support/Timer.h"
#include <cstring>
#include <list>
#include <string>
#ifdef LLVM_ON_UNIX
#include <netdb.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <unistd.h>
#endif // LLVM_ON_UNIX
#define DEBUG_TYPE "llvm_jitlink"
using namespace llvm;
using namespace llvm::jitlink;
using namespace llvm::orc;
static cl::OptionCategory JITLinkCategory("JITLink Options");
static cl::list<std::string> InputFiles(cl::Positional, cl::OneOrMore,
cl::desc("input files"),
cl::cat(JITLinkCategory));
static cl::list<std::string>
LibrarySearchPaths("L",
cl::desc("Add dir to the list of library search paths"),
cl::Prefix, cl::cat(JITLinkCategory));
static cl::list<std::string>
Libraries("l",
cl::desc("Link against library X in the library search paths"),
cl::Prefix, cl::cat(JITLinkCategory));
static cl::list<std::string>
LibrariesHidden("hidden-l",
cl::desc("Link against library X in the library search "
"paths with hidden visibility"),
cl::Prefix, cl::cat(JITLinkCategory));
static cl::list<std::string>
LoadHidden("load_hidden",
cl::desc("Link against library X with hidden visibility"),
cl::cat(JITLinkCategory));
static cl::opt<bool> NoExec("noexec", cl::desc("Do not execute loaded code"),
cl::init(false), cl::cat(JITLinkCategory));
static cl::list<std::string>
CheckFiles("check", cl::desc("File containing verifier checks"),
cl::ZeroOrMore, cl::cat(JITLinkCategory));
static cl::opt<std::string>
CheckName("check-name", cl::desc("Name of checks to match against"),
cl::init("jitlink-check"), cl::cat(JITLinkCategory));
static cl::opt<std::string>
EntryPointName("entry", cl::desc("Symbol to call as main entry point"),
cl::init(""), cl::cat(JITLinkCategory));
static cl::list<std::string> JITDylibs(
"jd",
cl::desc("Specifies the JITDylib to be used for any subsequent "
"input file, -L<seacrh-path>, and -l<library> arguments"),
cl::cat(JITLinkCategory));
static cl::list<std::string>
Dylibs("preload",
cl::desc("Pre-load dynamic libraries (e.g. language runtimes "
"required by the ORC runtime)"),
cl::ZeroOrMore, cl::cat(JITLinkCategory));
static cl::list<std::string> InputArgv("args", cl::Positional,
cl::desc("<program arguments>..."),
cl::ZeroOrMore, cl::PositionalEatsArgs,
cl::cat(JITLinkCategory));
static cl::opt<bool>
DebuggerSupport("debugger-support",
cl::desc("Enable debugger suppport (default = !-noexec)"),
cl::init(true), cl::Hidden, cl::cat(JITLinkCategory));
static cl::opt<bool>
NoProcessSymbols("no-process-syms",
cl::desc("Do not resolve to llvm-jitlink process symbols"),
cl::init(false), cl::cat(JITLinkCategory));
static cl::list<std::string> AbsoluteDefs(
"abs",
cl::desc("Inject absolute symbol definitions (syntax: <name>=<addr>)"),
cl::ZeroOrMore, cl::cat(JITLinkCategory));
static cl::list<std::string>
Aliases("alias", cl::desc("Inject symbol aliases (syntax: <name>=<addr>)"),
cl::ZeroOrMore, cl::cat(JITLinkCategory));
static cl::list<std::string> TestHarnesses("harness", cl::Positional,
cl::desc("Test harness files"),
cl::ZeroOrMore,
cl::PositionalEatsArgs,
cl::cat(JITLinkCategory));
static cl::opt<bool> ShowInitialExecutionSessionState(
"show-init-es",
cl::desc("Print ExecutionSession state before resolving entry point"),
cl::init(false), cl::cat(JITLinkCategory));
static cl::opt<bool> ShowEntryExecutionSessionState(
"show-entry-es",
cl::desc("Print ExecutionSession state after resolving entry point"),
cl::init(false), cl::cat(JITLinkCategory));
static cl::opt<bool> ShowAddrs(
"show-addrs",
cl::desc("Print registered symbol, section, got and stub addresses"),
cl::init(false), cl::cat(JITLinkCategory));
static cl::opt<bool> ShowLinkGraph(
"show-graph",
cl::desc("Print the link graph after fixups have been applied"),
cl::init(false), cl::cat(JITLinkCategory));
static cl::opt<bool> ShowSizes(
"show-sizes",
cl::desc("Show sizes pre- and post-dead stripping, and allocations"),
cl::init(false), cl::cat(JITLinkCategory));
static cl::opt<bool> ShowTimes("show-times",
cl::desc("Show times for llvm-jitlink phases"),
cl::init(false), cl::cat(JITLinkCategory));
static cl::opt<std::string> SlabAllocateSizeString(
"slab-allocate",
cl::desc("Allocate from a slab of the given size "
"(allowable suffixes: Kb, Mb, Gb. default = "
"Kb)"),
cl::init(""), cl::cat(JITLinkCategory));
static cl::opt<uint64_t> SlabAddress(
"slab-address",
cl::desc("Set slab target address (requires -slab-allocate and -noexec)"),
cl::init(~0ULL), cl::cat(JITLinkCategory));
static cl::opt<uint64_t> SlabPageSize(
"slab-page-size",
cl::desc("Set page size for slab (requires -slab-allocate and -noexec)"),
cl::init(0), cl::cat(JITLinkCategory));
static cl::opt<bool> ShowRelocatedSectionContents(
"show-relocated-section-contents",
cl::desc("show section contents after fixups have been applied"),
cl::init(false), cl::cat(JITLinkCategory));
static cl::opt<bool> PhonyExternals(
"phony-externals",
cl::desc("resolve all otherwise unresolved externals to null"),
cl::init(false), cl::cat(JITLinkCategory));
static cl::opt<std::string> OutOfProcessExecutor(
"oop-executor", cl::desc("Launch an out-of-process executor to run code"),
cl::ValueOptional, cl::cat(JITLinkCategory));
static cl::opt<std::string> OutOfProcessExecutorConnect(
"oop-executor-connect",
cl::desc("Connect to an out-of-process executor via TCP"),
cl::cat(JITLinkCategory));
static cl::opt<std::string>
OrcRuntime("orc-runtime", cl::desc("Use ORC runtime from given path"),
cl::init(""), cl::cat(JITLinkCategory));
static cl::opt<bool> AddSelfRelocations(
"add-self-relocations",
cl::desc("Add relocations to function pointers to the current function"),
cl::init(false), cl::cat(JITLinkCategory));
ExitOnError ExitOnErr;
LLVM_ATTRIBUTE_USED void linkComponents() {
errs() << (void *)&llvm_orc_registerEHFrameSectionWrapper
<< (void *)&llvm_orc_deregisterEHFrameSectionWrapper
<< (void *)&llvm_orc_registerJITLoaderGDBWrapper;
}
static bool UseTestResultOverride = false;
static int64_t TestResultOverride = 0;
extern "C" LLVM_ATTRIBUTE_USED void
llvm_jitlink_setTestResultOverride(int64_t Value) {
TestResultOverride = Value;
UseTestResultOverride = true;
}
static Error addSelfRelocations(LinkGraph &G);
namespace llvm {
static raw_ostream &
operator<<(raw_ostream &OS, const Session::MemoryRegionInfo &MRI) {
return OS << "target addr = "
<< format("0x%016" PRIx64, MRI.getTargetAddress())
<< ", content: " << (const void *)MRI.getContent().data() << " -- "
<< (const void *)(MRI.getContent().data() + MRI.getContent().size())
<< " (" << MRI.getContent().size() << " bytes)";
}
static raw_ostream &
operator<<(raw_ostream &OS, const Session::SymbolInfoMap &SIM) {
OS << "Symbols:\n";
for (auto &SKV : SIM)
OS << " \"" << SKV.first() << "\" " << SKV.second << "\n";
return OS;
}
static raw_ostream &
operator<<(raw_ostream &OS, const Session::FileInfo &FI) {
for (auto &SIKV : FI.SectionInfos)
OS << " Section \"" << SIKV.first() << "\": " << SIKV.second << "\n";
for (auto &GOTKV : FI.GOTEntryInfos)
OS << " GOT \"" << GOTKV.first() << "\": " << GOTKV.second << "\n";
for (auto &StubKV : FI.StubInfos)
OS << " Stub \"" << StubKV.first() << "\": " << StubKV.second << "\n";
return OS;
}
static raw_ostream &
operator<<(raw_ostream &OS, const Session::FileInfoMap &FIM) {
for (auto &FIKV : FIM)
OS << "File \"" << FIKV.first() << "\":\n" << FIKV.second;
return OS;
}
static Error applyHarnessPromotions(Session &S, LinkGraph &G) {
// If this graph is part of the test harness there's nothing to do.
if (S.HarnessFiles.empty() || S.HarnessFiles.count(G.getName()))
return Error::success();
LLVM_DEBUG(dbgs() << "Applying promotions to graph " << G.getName() << "\n");
// If this graph is part of the test then promote any symbols referenced by
// the harness to default scope, remove all symbols that clash with harness
// definitions.
std::vector<Symbol *> DefinitionsToRemove;
for (auto *Sym : G.defined_symbols()) {
if (!Sym->hasName())
continue;
if (Sym->getLinkage() == Linkage::Weak) {
if (!S.CanonicalWeakDefs.count(Sym->getName()) ||
S.CanonicalWeakDefs[Sym->getName()] != G.getName()) {
LLVM_DEBUG({
dbgs() << " Externalizing weak symbol " << Sym->getName() << "\n";
});
DefinitionsToRemove.push_back(Sym);
} else {
LLVM_DEBUG({
dbgs() << " Making weak symbol " << Sym->getName() << " strong\n";
});
if (S.HarnessExternals.count(Sym->getName()))
Sym->setScope(Scope::Default);
else
Sym->setScope(Scope::Hidden);
Sym->setLinkage(Linkage::Strong);
}
} else if (S.HarnessExternals.count(Sym->getName())) {
LLVM_DEBUG(dbgs() << " Promoting " << Sym->getName() << "\n");
Sym->setScope(Scope::Default);
Sym->setLive(true);
continue;
} else if (S.HarnessDefinitions.count(Sym->getName())) {
LLVM_DEBUG(dbgs() << " Externalizing " << Sym->getName() << "\n");
DefinitionsToRemove.push_back(Sym);
}
}
for (auto *Sym : DefinitionsToRemove)
G.makeExternal(*Sym);
return Error::success();
}
static uint64_t computeTotalBlockSizes(LinkGraph &G) {
uint64_t TotalSize = 0;
for (auto *B : G.blocks())
TotalSize += B->getSize();
return TotalSize;
}
static void dumpSectionContents(raw_ostream &OS, LinkGraph &G) {
constexpr orc::ExecutorAddrDiff DumpWidth = 16;
static_assert(isPowerOf2_64(DumpWidth), "DumpWidth must be a power of two");
// Put sections in address order.
std::vector<Section *> Sections;
for (auto &S : G.sections())
Sections.push_back(&S);
llvm::sort(Sections, [](const Section *LHS, const Section *RHS) {
if (llvm::empty(LHS->symbols()) && llvm::empty(RHS->symbols()))
return false;
if (llvm::empty(LHS->symbols()))
return false;
if (llvm::empty(RHS->symbols()))
return true;
SectionRange LHSRange(*LHS);
SectionRange RHSRange(*RHS);
return LHSRange.getStart() < RHSRange.getStart();
});
for (auto *S : Sections) {
OS << S->getName() << " content:";
if (llvm::empty(S->symbols())) {
OS << "\n section empty\n";
continue;
}
// Sort symbols into order, then render.
std::vector<Symbol *> Syms(S->symbols().begin(), S->symbols().end());
llvm::sort(Syms, [](const Symbol *LHS, const Symbol *RHS) {
return LHS->getAddress() < RHS->getAddress();
});
orc::ExecutorAddr NextAddr(Syms.front()->getAddress().getValue() &
~(DumpWidth - 1));
for (auto *Sym : Syms) {
bool IsZeroFill = Sym->getBlock().isZeroFill();
auto SymStart = Sym->getAddress();
auto SymSize = Sym->getSize();
auto SymEnd = SymStart + SymSize;
const uint8_t *SymData = IsZeroFill ? nullptr
: reinterpret_cast<const uint8_t *>(
Sym->getSymbolContent().data());
// Pad any space before the symbol starts.
while (NextAddr != SymStart) {
if (NextAddr % DumpWidth == 0)
OS << formatv("\n{0:x16}:", NextAddr);
OS << " ";
++NextAddr;
}
// Render the symbol content.
while (NextAddr != SymEnd) {
if (NextAddr % DumpWidth == 0)
OS << formatv("\n{0:x16}:", NextAddr);
if (IsZeroFill)
OS << " 00";
else
OS << formatv(" {0:x-2}", SymData[NextAddr - SymStart]);
++NextAddr;
}
}
OS << "\n";
}
}
class JITLinkSlabAllocator final : public JITLinkMemoryManager {
private:
struct FinalizedAllocInfo {
FinalizedAllocInfo(sys::MemoryBlock Mem,
std::vector<shared::WrapperFunctionCall> DeallocActions)
: Mem(Mem), DeallocActions(std::move(DeallocActions)) {}
sys::MemoryBlock Mem;
std::vector<shared::WrapperFunctionCall> DeallocActions;
};
public:
static Expected<std::unique_ptr<JITLinkSlabAllocator>>
Create(uint64_t SlabSize) {
Error Err = Error::success();
std::unique_ptr<JITLinkSlabAllocator> Allocator(
new JITLinkSlabAllocator(SlabSize, Err));
if (Err)
return std::move(Err);
return std::move(Allocator);
}
void allocate(const JITLinkDylib *JD, LinkGraph &G,
OnAllocatedFunction OnAllocated) override {
// Local class for allocation.
class IPMMAlloc : public InFlightAlloc {
public:
IPMMAlloc(JITLinkSlabAllocator &Parent, BasicLayout BL,
sys::MemoryBlock StandardSegs, sys::MemoryBlock FinalizeSegs)
: Parent(Parent), BL(std::move(BL)),
StandardSegs(std::move(StandardSegs)),
FinalizeSegs(std::move(FinalizeSegs)) {}
void finalize(OnFinalizedFunction OnFinalized) override {
if (auto Err = applyProtections()) {
OnFinalized(std::move(Err));
return;
}
auto DeallocActions = runFinalizeActions(BL.graphAllocActions());
if (!DeallocActions) {
OnFinalized(DeallocActions.takeError());
return;
}
if (auto Err = Parent.freeBlock(FinalizeSegs)) {
OnFinalized(
joinErrors(std::move(Err), runDeallocActions(*DeallocActions)));
return;
}
OnFinalized(FinalizedAlloc(ExecutorAddr::fromPtr(
new FinalizedAllocInfo(StandardSegs, std::move(*DeallocActions)))));
}
void abandon(OnAbandonedFunction OnAbandoned) override {
OnAbandoned(joinErrors(Parent.freeBlock(StandardSegs),
Parent.freeBlock(FinalizeSegs)));
}
private:
Error applyProtections() {
for (auto &KV : BL.segments()) {
const auto &Group = KV.first;
auto &Seg = KV.second;
auto Prot = toSysMemoryProtectionFlags(Group.getMemProt());
uint64_t SegSize =
alignTo(Seg.ContentSize + Seg.ZeroFillSize, Parent.PageSize);
sys::MemoryBlock MB(Seg.WorkingMem, SegSize);
if (auto EC = sys::Memory::protectMappedMemory(MB, Prot))
return errorCodeToError(EC);
if (Prot & sys::Memory::MF_EXEC)
sys::Memory::InvalidateInstructionCache(MB.base(),
MB.allocatedSize());
}
return Error::success();
}
JITLinkSlabAllocator &Parent;
BasicLayout BL;
sys::MemoryBlock StandardSegs;
sys::MemoryBlock FinalizeSegs;
};
BasicLayout BL(G);
auto SegsSizes = BL.getContiguousPageBasedLayoutSizes(PageSize);
if (!SegsSizes) {
OnAllocated(SegsSizes.takeError());
return;
}
char *AllocBase = nullptr;
{
std::lock_guard<std::mutex> Lock(SlabMutex);
if (SegsSizes->total() > SlabRemaining.allocatedSize()) {
OnAllocated(make_error<StringError>(
"Slab allocator out of memory: request for " +
formatv("{0:x}", SegsSizes->total()) +
" bytes exceeds remaining capacity of " +
formatv("{0:x}", SlabRemaining.allocatedSize()) + " bytes",
inconvertibleErrorCode()));
return;
}
AllocBase = reinterpret_cast<char *>(SlabRemaining.base());
SlabRemaining =
sys::MemoryBlock(AllocBase + SegsSizes->total(),
SlabRemaining.allocatedSize() - SegsSizes->total());
}
sys::MemoryBlock StandardSegs(AllocBase, SegsSizes->StandardSegs);
sys::MemoryBlock FinalizeSegs(AllocBase + SegsSizes->StandardSegs,
SegsSizes->FinalizeSegs);
auto NextStandardSegAddr = ExecutorAddr::fromPtr(StandardSegs.base());
auto NextFinalizeSegAddr = ExecutorAddr::fromPtr(FinalizeSegs.base());
LLVM_DEBUG({
dbgs() << "JITLinkSlabAllocator allocated:\n";
if (SegsSizes->StandardSegs)
dbgs() << formatv(" [ {0:x16} -- {1:x16} ]", NextStandardSegAddr,
NextStandardSegAddr + StandardSegs.allocatedSize())
<< " to stardard segs\n";
else
dbgs() << " no standard segs\n";
if (SegsSizes->FinalizeSegs)
dbgs() << formatv(" [ {0:x16} -- {1:x16} ]", NextFinalizeSegAddr,
NextFinalizeSegAddr + FinalizeSegs.allocatedSize())
<< " to finalize segs\n";
else
dbgs() << " no finalize segs\n";
});
for (auto &KV : BL.segments()) {
auto &Group = KV.first;
auto &Seg = KV.second;
auto &SegAddr =
(Group.getMemDeallocPolicy() == MemDeallocPolicy::Standard)
? NextStandardSegAddr
: NextFinalizeSegAddr;
LLVM_DEBUG({
dbgs() << " " << Group << " -> " << formatv("{0:x16}", SegAddr)
<< "\n";
});
Seg.WorkingMem = SegAddr.toPtr<char *>();
Seg.Addr = SegAddr + NextSlabDelta;
SegAddr += alignTo(Seg.ContentSize + Seg.ZeroFillSize, PageSize);
// Zero out the zero-fill memory.
if (Seg.ZeroFillSize != 0)
memset(Seg.WorkingMem + Seg.ContentSize, 0, Seg.ZeroFillSize);
}
NextSlabDelta += SegsSizes->total();
if (auto Err = BL.apply()) {
OnAllocated(std::move(Err));
return;
}
OnAllocated(std::unique_ptr<InProcessMemoryManager::InFlightAlloc>(
new IPMMAlloc(*this, std::move(BL), std::move(StandardSegs),
std::move(FinalizeSegs))));
}
void deallocate(std::vector<FinalizedAlloc> FinalizedAllocs,
OnDeallocatedFunction OnDeallocated) override {
Error Err = Error::success();
for (auto &FA : FinalizedAllocs) {
std::unique_ptr<FinalizedAllocInfo> FAI(
FA.release().toPtr<FinalizedAllocInfo *>());
// FIXME: Run dealloc actions.
Err = joinErrors(std::move(Err), freeBlock(FAI->Mem));
}
OnDeallocated(std::move(Err));
}
private:
JITLinkSlabAllocator(uint64_t SlabSize, Error &Err) {
ErrorAsOutParameter _(&Err);
if (!SlabPageSize) {
if (auto PageSizeOrErr = sys::Process::getPageSize())
PageSize = *PageSizeOrErr;
else {
Err = PageSizeOrErr.takeError();
return;
}
if (PageSize == 0) {
Err = make_error<StringError>("Page size is zero",
inconvertibleErrorCode());
return;
}
} else
PageSize = SlabPageSize;
if (!isPowerOf2_64(PageSize)) {
Err = make_error<StringError>("Page size is not a power of 2",
inconvertibleErrorCode());
return;
}
// Round slab request up to page size.
SlabSize = (SlabSize + PageSize - 1) & ~(PageSize - 1);
const sys::Memory::ProtectionFlags ReadWrite =
static_cast<sys::Memory::ProtectionFlags>(sys::Memory::MF_READ |
sys::Memory::MF_WRITE);
std::error_code EC;
SlabRemaining =
sys::Memory::allocateMappedMemory(SlabSize, nullptr, ReadWrite, EC);
if (EC) {
Err = errorCodeToError(EC);
return;
}
// Calculate the target address delta to link as-if slab were at
// SlabAddress.
if (SlabAddress != ~0ULL)
NextSlabDelta = ExecutorAddr(SlabAddress) -
ExecutorAddr::fromPtr(SlabRemaining.base());
}
Error freeBlock(sys::MemoryBlock MB) {
// FIXME: Return memory to slab.
return Error::success();
}
std::mutex SlabMutex;
sys::MemoryBlock SlabRemaining;
uint64_t PageSize = 0;
int64_t NextSlabDelta = 0;
};
Expected<uint64_t> getSlabAllocSize(StringRef SizeString) {
SizeString = SizeString.trim();
uint64_t Units = 1024;
if (SizeString.endswith_insensitive("kb"))
SizeString = SizeString.drop_back(2).rtrim();
else if (SizeString.endswith_insensitive("mb")) {
Units = 1024 * 1024;
SizeString = SizeString.drop_back(2).rtrim();
} else if (SizeString.endswith_insensitive("gb")) {
Units = 1024 * 1024 * 1024;
SizeString = SizeString.drop_back(2).rtrim();
}
uint64_t SlabSize = 0;
if (SizeString.getAsInteger(10, SlabSize))
return make_error<StringError>("Invalid numeric format for slab size",
inconvertibleErrorCode());
return SlabSize * Units;
}
static std::unique_ptr<JITLinkMemoryManager> createMemoryManager() {
if (!SlabAllocateSizeString.empty()) {
auto SlabSize = ExitOnErr(getSlabAllocSize(SlabAllocateSizeString));
return ExitOnErr(JITLinkSlabAllocator::Create(SlabSize));
}
return ExitOnErr(InProcessMemoryManager::Create());
}
static Expected<MaterializationUnit::Interface>
getTestObjectFileInterface(Session &S, MemoryBufferRef O) {
// Get the standard interface for this object, but ignore the symbols field.
// We'll handle that manually to include promotion.
auto I = getObjectFileInterface(S.ES, O);
if (!I)
return I.takeError();
I->SymbolFlags.clear();
// If creating an object file was going to fail it would have happened above,
// so we can 'cantFail' this.
auto Obj = cantFail(object::ObjectFile::createObjectFile(O));
// The init symbol must be included in the SymbolFlags map if present.
if (I->InitSymbol)
I->SymbolFlags[I->InitSymbol] =
JITSymbolFlags::MaterializationSideEffectsOnly;
for (auto &Sym : Obj->symbols()) {
Expected<uint32_t> SymFlagsOrErr = Sym.getFlags();
if (!SymFlagsOrErr)
// TODO: Test this error.
return SymFlagsOrErr.takeError();
// Skip symbols not defined in this object file.
if ((*SymFlagsOrErr & object::BasicSymbolRef::SF_Undefined))
continue;
auto Name = Sym.getName();
if (!Name)
return Name.takeError();
// Skip symbols that have type SF_File.
if (auto SymType = Sym.getType()) {
if (*SymType == object::SymbolRef::ST_File)
continue;
} else
return SymType.takeError();
auto SymFlags = JITSymbolFlags::fromObjectSymbol(Sym);
if (!SymFlags)
return SymFlags.takeError();
if (SymFlags->isWeak()) {
// If this is a weak symbol that's not defined in the harness then we
// need to either mark it as strong (if this is the first definition
// that we've seen) or discard it.
if (S.HarnessDefinitions.count(*Name) || S.CanonicalWeakDefs.count(*Name))
continue;
S.CanonicalWeakDefs[*Name] = O.getBufferIdentifier();
*SymFlags &= ~JITSymbolFlags::Weak;
if (!S.HarnessExternals.count(*Name))
*SymFlags &= ~JITSymbolFlags::Exported;
} else if (S.HarnessExternals.count(*Name)) {
*SymFlags |= JITSymbolFlags::Exported;
} else if (S.HarnessDefinitions.count(*Name) ||
!(*SymFlagsOrErr & object::BasicSymbolRef::SF_Global))
continue;
auto InternedName = S.ES.intern(*Name);
I->SymbolFlags[InternedName] = std::move(*SymFlags);
}
return I;
}
static Error loadProcessSymbols(Session &S) {
auto FilterMainEntryPoint =
[EPName = S.ES.intern(EntryPointName)](SymbolStringPtr Name) {
return Name != EPName;
};
S.MainJD->addGenerator(
ExitOnErr(orc::EPCDynamicLibrarySearchGenerator::GetForTargetProcess(
S.ES, std::move(FilterMainEntryPoint))));
return Error::success();
}
static Error loadDylibs(Session &S) {
LLVM_DEBUG(dbgs() << "Loading dylibs...\n");
for (const auto &Dylib : Dylibs) {
LLVM_DEBUG(dbgs() << " " << Dylib << "\n");
auto G = orc::EPCDynamicLibrarySearchGenerator::Load(S.ES, Dylib.c_str());
if (!G)
return G.takeError();
S.MainJD->addGenerator(std::move(*G));
}
return Error::success();
}
static Expected<std::unique_ptr<ExecutorProcessControl>> launchExecutor() {
#ifndef LLVM_ON_UNIX
// FIXME: Add support for Windows.
return make_error<StringError>("-" + OutOfProcessExecutor.ArgStr +
" not supported on non-unix platforms",
inconvertibleErrorCode());
#elif !LLVM_ENABLE_THREADS
// Out of process mode using SimpleRemoteEPC depends on threads.
return make_error<StringError>(
"-" + OutOfProcessExecutor.ArgStr +
" requires threads, but LLVM was built with "
"LLVM_ENABLE_THREADS=Off",
inconvertibleErrorCode());
#else
constexpr int ReadEnd = 0;
constexpr int WriteEnd = 1;
// Pipe FDs.
int ToExecutor[2];
int FromExecutor[2];
pid_t ChildPID;
// Create pipes to/from the executor..
if (pipe(ToExecutor) != 0 || pipe(FromExecutor) != 0)
return make_error<StringError>("Unable to create pipe for executor",
inconvertibleErrorCode());
ChildPID = fork();
if (ChildPID == 0) {
// In the child...
// Close the parent ends of the pipes
close(ToExecutor[WriteEnd]);
close(FromExecutor[ReadEnd]);
// Execute the child process.
std::unique_ptr<char[]> ExecutorPath, FDSpecifier;
{
ExecutorPath = std::make_unique<char[]>(OutOfProcessExecutor.size() + 1);
strcpy(ExecutorPath.get(), OutOfProcessExecutor.data());
std::string FDSpecifierStr("filedescs=");
FDSpecifierStr += utostr(ToExecutor[ReadEnd]);
FDSpecifierStr += ',';
FDSpecifierStr += utostr(FromExecutor[WriteEnd]);
FDSpecifier = std::make_unique<char[]>(FDSpecifierStr.size() + 1);
strcpy(FDSpecifier.get(), FDSpecifierStr.c_str());
}
char *const Args[] = {ExecutorPath.get(), FDSpecifier.get(), nullptr};
int RC = execvp(ExecutorPath.get(), Args);
if (RC != 0) {
errs() << "unable to launch out-of-process executor \""
<< ExecutorPath.get() << "\"\n";
exit(1);
}
}
// else we're the parent...
// Close the child ends of the pipes
close(ToExecutor[ReadEnd]);
close(FromExecutor[WriteEnd]);
return SimpleRemoteEPC::Create<FDSimpleRemoteEPCTransport>(
std::make_unique<DynamicThreadPoolTaskDispatcher>(),
SimpleRemoteEPC::Setup(), FromExecutor[ReadEnd], ToExecutor[WriteEnd]);
#endif
}
#if LLVM_ON_UNIX && LLVM_ENABLE_THREADS
static Error createTCPSocketError(Twine Details) {
return make_error<StringError>(
formatv("Failed to connect TCP socket '{0}': {1}",
OutOfProcessExecutorConnect, Details),
inconvertibleErrorCode());
}
static Expected<int> connectTCPSocket(std::string Host, std::string PortStr) {
addrinfo *AI;
addrinfo Hints{};
Hints.ai_family = AF_INET;
Hints.ai_socktype = SOCK_STREAM;
Hints.ai_flags = AI_NUMERICSERV;
if (int EC = getaddrinfo(Host.c_str(), PortStr.c_str(), &Hints, &AI))
return createTCPSocketError("Address resolution failed (" +
StringRef(gai_strerror(EC)) + ")");
// Cycle through the returned addrinfo structures and connect to the first
// reachable endpoint.
int SockFD;
addrinfo *Server;
for (Server = AI; Server != nullptr; Server = Server->ai_next) {
// socket might fail, e.g. if the address family is not supported. Skip to
// the next addrinfo structure in such a case.
if ((SockFD = socket(AI->ai_family, AI->ai_socktype, AI->ai_protocol)) < 0)
continue;
// If connect returns null, we exit the loop with a working socket.
if (connect(SockFD, Server->ai_addr, Server->ai_addrlen) == 0)
break;
close(SockFD);
}
freeaddrinfo(AI);
// If we reached the end of the loop without connecting to a valid endpoint,
// dump the last error that was logged in socket() or connect().
if (Server == nullptr)
return createTCPSocketError(std::strerror(errno));
return SockFD;
}
#endif
static Expected<std::unique_ptr<ExecutorProcessControl>> connectToExecutor() {
#ifndef LLVM_ON_UNIX
// FIXME: Add TCP support for Windows.
return make_error<StringError>("-" + OutOfProcessExecutorConnect.ArgStr +
" not supported on non-unix platforms",
inconvertibleErrorCode());
#elif !LLVM_ENABLE_THREADS
// Out of process mode using SimpleRemoteEPC depends on threads.
return make_error<StringError>(
"-" + OutOfProcessExecutorConnect.ArgStr +
" requires threads, but LLVM was built with "
"LLVM_ENABLE_THREADS=Off",
inconvertibleErrorCode());
#else
StringRef Host, PortStr;
std::tie(Host, PortStr) = StringRef(OutOfProcessExecutorConnect).split(':');
if (Host.empty())
return createTCPSocketError("Host name for -" +
OutOfProcessExecutorConnect.ArgStr +
" can not be empty");
if (PortStr.empty())
return createTCPSocketError("Port number in -" +
OutOfProcessExecutorConnect.ArgStr +
" can not be empty");
int Port = 0;
if (PortStr.getAsInteger(10, Port))
return createTCPSocketError("Port number '" + PortStr +
"' is not a valid integer");
Expected<int> SockFD = connectTCPSocket(Host.str(), PortStr.str());
if (!SockFD)
return SockFD.takeError();
return SimpleRemoteEPC::Create<FDSimpleRemoteEPCTransport>(
std::make_unique<DynamicThreadPoolTaskDispatcher>(),
SimpleRemoteEPC::Setup(), *SockFD, *SockFD);
#endif
}
class PhonyExternalsGenerator : public DefinitionGenerator {
public:
Error tryToGenerate(LookupState &LS, LookupKind K, JITDylib &JD,
JITDylibLookupFlags JDLookupFlags,
const SymbolLookupSet &LookupSet) override {
SymbolMap PhonySymbols;
for (auto &KV : LookupSet)
PhonySymbols[KV.first] = JITEvaluatedSymbol(0, JITSymbolFlags::Exported);
return JD.define(absoluteSymbols(std::move(PhonySymbols)));
}
};
Expected<std::unique_ptr<Session>> Session::Create(Triple TT) {
std::unique_ptr<ExecutorProcessControl> EPC;
if (OutOfProcessExecutor.getNumOccurrences()) {
/// If -oop-executor is passed then launch the executor.
if (auto REPC = launchExecutor())
EPC = std::move(*REPC);
else
return REPC.takeError();
} else if (OutOfProcessExecutorConnect.getNumOccurrences()) {
/// If -oop-executor-connect is passed then connect to the executor.
if (auto REPC = connectToExecutor())
EPC = std::move(*REPC);
else
return REPC.takeError();
} else {
/// Otherwise use SelfExecutorProcessControl to target the current process.
auto PageSize = sys::Process::getPageSize();
if (!PageSize)
return PageSize.takeError();
EPC = std::make_unique<SelfExecutorProcessControl>(
std::make_shared<SymbolStringPool>(),
std::make_unique<InPlaceTaskDispatcher>(), std::move(TT), *PageSize,
createMemoryManager());
}
Error Err = Error::success();
std::unique_ptr<Session> S(new Session(std::move(EPC), Err));
if (Err)
return std::move(Err);
return std::move(S);
}
Session::~Session() {
if (auto Err = ES.endSession())
ES.reportError(std::move(Err));
}
Session::Session(std::unique_ptr<ExecutorProcessControl> EPC, Error &Err)
: ES(std::move(EPC)),
ObjLayer(ES, ES.getExecutorProcessControl().getMemMgr()) {
/// Local ObjectLinkingLayer::Plugin class to forward modifyPassConfig to the
/// Session.
class JITLinkSessionPlugin : public ObjectLinkingLayer::Plugin {
public:
JITLinkSessionPlugin(Session &S) : S(S) {}
void modifyPassConfig(MaterializationResponsibility &MR, LinkGraph &G,
PassConfiguration &PassConfig) override {
S.modifyPassConfig(G.getTargetTriple(), PassConfig);
}
Error notifyFailed(MaterializationResponsibility &MR) override {