-
Notifications
You must be signed in to change notification settings - Fork 1.6k
/
NativeImageGenerator.java
2033 lines (1800 loc) 路 113 KB
/
NativeImageGenerator.java
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 (c) 2012, 2023, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.oracle.svm.hosted;
import static com.oracle.graal.pointsto.api.PointstoOptions.UseExperimentalReachabilityAnalysis;
import static com.oracle.svm.hosted.NativeImageOptions.DiagnosticsDir;
import static com.oracle.svm.hosted.NativeImageOptions.DiagnosticsMode;
import static jdk.graal.compiler.hotspot.JVMCIVersionCheck.OPEN_LABSJDK_RELEASE_URL_PATTERN;
import static jdk.graal.compiler.replacements.StandardGraphBuilderPlugins.registerInvocationPlugins;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.annotation.Annotation;
import java.lang.reflect.Executable;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.lang.reflect.Type;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.EnumMap;
import java.util.EnumSet;
import java.util.List;
import java.util.ListIterator;
import java.util.Locale;
import java.util.Map;
import java.util.ServiceLoader;
import java.util.Set;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.function.BooleanSupplier;
import java.util.function.Function;
import org.graalvm.collections.EconomicMap;
import org.graalvm.collections.EconomicSet;
import org.graalvm.collections.MapCursor;
import org.graalvm.collections.Pair;
import org.graalvm.nativeimage.AnnotationAccess;
import org.graalvm.nativeimage.ImageInfo;
import org.graalvm.nativeimage.ImageSingletons;
import org.graalvm.nativeimage.Platform;
import org.graalvm.nativeimage.Platforms;
import org.graalvm.nativeimage.c.CContext;
import org.graalvm.nativeimage.c.constant.CConstant;
import org.graalvm.nativeimage.c.constant.CEnum;
import org.graalvm.nativeimage.c.function.CEntryPoint;
import org.graalvm.nativeimage.c.function.CFunction;
import org.graalvm.nativeimage.c.function.CFunctionPointer;
import org.graalvm.nativeimage.c.struct.CPointerTo;
import org.graalvm.nativeimage.c.struct.CStruct;
import org.graalvm.nativeimage.c.struct.RawPointerTo;
import org.graalvm.nativeimage.c.struct.RawStructure;
import org.graalvm.nativeimage.hosted.Feature;
import org.graalvm.nativeimage.hosted.Feature.OnAnalysisExitAccess;
import org.graalvm.nativeimage.impl.AnnotationExtractor;
import org.graalvm.nativeimage.impl.CConstantValueSupport;
import org.graalvm.nativeimage.impl.RuntimeClassInitializationSupport;
import org.graalvm.nativeimage.impl.SizeOfSupport;
import org.graalvm.word.PointerBase;
import com.oracle.graal.pointsto.AnalysisObjectScanningObserver;
import com.oracle.graal.pointsto.AnalysisPolicy;
import com.oracle.graal.pointsto.BigBang;
import com.oracle.graal.pointsto.ClassInclusionPolicy;
import com.oracle.graal.pointsto.ObjectScanningObserver;
import com.oracle.graal.pointsto.api.PointstoOptions;
import com.oracle.graal.pointsto.constraints.UnsupportedFeatureException;
import com.oracle.graal.pointsto.flow.MethodTypeFlowBuilder;
import com.oracle.graal.pointsto.flow.context.bytecode.BytecodeSensitiveAnalysisPolicy;
import com.oracle.graal.pointsto.heap.HeapSnapshotVerifier;
import com.oracle.graal.pointsto.heap.HostedValuesProvider;
import com.oracle.graal.pointsto.heap.ImageHeap;
import com.oracle.graal.pointsto.heap.ImageHeapScanner;
import com.oracle.graal.pointsto.heap.ImageLayerLoader;
import com.oracle.graal.pointsto.heap.ImageLayerSnapshotUtil;
import com.oracle.graal.pointsto.infrastructure.SubstitutionProcessor;
import com.oracle.graal.pointsto.infrastructure.WrappedJavaMethod;
import com.oracle.graal.pointsto.meta.AnalysisFactory;
import com.oracle.graal.pointsto.meta.AnalysisField;
import com.oracle.graal.pointsto.meta.AnalysisMetaAccess;
import com.oracle.graal.pointsto.meta.AnalysisMethod;
import com.oracle.graal.pointsto.meta.AnalysisType;
import com.oracle.graal.pointsto.meta.AnalysisUniverse;
import com.oracle.graal.pointsto.meta.HostedProviders;
import com.oracle.graal.pointsto.meta.PointsToAnalysisFactory;
import com.oracle.graal.pointsto.reports.AnalysisReporter;
import com.oracle.graal.pointsto.reports.ReportUtils;
import com.oracle.graal.pointsto.typestate.DefaultAnalysisPolicy;
import com.oracle.graal.pointsto.util.AnalysisError;
import com.oracle.graal.pointsto.util.GraalAccess;
import com.oracle.graal.pointsto.util.Timer.StopTimer;
import com.oracle.graal.pointsto.util.TimerCollection;
import com.oracle.graal.reachability.DirectMethodProcessingHandler;
import com.oracle.graal.reachability.MethodSummaryBasedHandler;
import com.oracle.graal.reachability.MethodSummaryProvider;
import com.oracle.graal.reachability.ReachabilityAnalysisFactory;
import com.oracle.graal.reachability.ReachabilityMethodProcessingHandler;
import com.oracle.graal.reachability.ReachabilityObjectScanner;
import com.oracle.graal.reachability.SimpleInMemoryMethodSummaryProvider;
import com.oracle.svm.common.meta.MultiMethod;
import com.oracle.svm.core.BuildArtifacts;
import com.oracle.svm.core.BuildArtifacts.ArtifactType;
import com.oracle.svm.core.BuildPhaseProvider;
import com.oracle.svm.core.ClassLoaderSupport;
import com.oracle.svm.core.JavaMainWrapper.JavaMainSupport;
import com.oracle.svm.core.LinkerInvocation;
import com.oracle.svm.core.MissingRegistrationSupport;
import com.oracle.svm.core.OS;
import com.oracle.svm.core.ParsingReason;
import com.oracle.svm.core.SubstrateOptions;
import com.oracle.svm.core.SubstrateTargetDescription;
import com.oracle.svm.core.SubstrateUtil;
import com.oracle.svm.core.aarch64.AArch64CPUFeatureAccess;
import com.oracle.svm.core.amd64.AMD64CPUFeatureAccess;
import com.oracle.svm.core.c.libc.LibCBase;
import com.oracle.svm.core.c.libc.NoLibC;
import com.oracle.svm.core.c.libc.TemporaryBuildDirectoryProvider;
import com.oracle.svm.core.c.struct.OffsetOf;
import com.oracle.svm.core.config.ConfigurationValues;
import com.oracle.svm.core.cpufeature.RuntimeCPUFeatureCheck;
import com.oracle.svm.core.graal.EconomyGraalConfiguration;
import com.oracle.svm.core.graal.GraalConfiguration;
import com.oracle.svm.core.graal.code.SubstrateBackend;
import com.oracle.svm.core.graal.code.SubstratePlatformConfigurationProvider;
import com.oracle.svm.core.graal.jdk.SubstrateArraycopySnippets;
import com.oracle.svm.core.graal.lir.VerifyCFunctionReferenceMapsLIRPhase;
import com.oracle.svm.core.graal.meta.RuntimeConfiguration;
import com.oracle.svm.core.graal.meta.SubstrateForeignCallsProvider;
import com.oracle.svm.core.graal.meta.SubstrateLoweringProvider;
import com.oracle.svm.core.graal.meta.SubstrateReplacements;
import com.oracle.svm.core.graal.meta.SubstrateStampProvider;
import com.oracle.svm.core.graal.phases.CollectDeoptimizationSourcePositionsPhase;
import com.oracle.svm.core.graal.phases.DeadStoreRemovalPhase;
import com.oracle.svm.core.graal.phases.OptimizeExceptionPathsPhase;
import com.oracle.svm.core.graal.phases.RemoveUnwindPhase;
import com.oracle.svm.core.graal.phases.SubstrateSafepointInsertionPhase;
import com.oracle.svm.core.graal.snippets.DeoptTester;
import com.oracle.svm.core.graal.snippets.NodeLoweringProvider;
import com.oracle.svm.core.graal.snippets.OpenTypeWorldDispatchTableSnippets;
import com.oracle.svm.core.graal.snippets.OpenTypeWorldSnippets;
import com.oracle.svm.core.graal.snippets.TypeSnippets;
import com.oracle.svm.core.graal.word.SubstrateWordOperationPlugins;
import com.oracle.svm.core.graal.word.SubstrateWordTypes;
import com.oracle.svm.core.heap.BarrierSetProvider;
import com.oracle.svm.core.heap.RestrictHeapAccessCallees;
import com.oracle.svm.core.hub.DynamicHub;
import com.oracle.svm.core.hub.LayoutEncoding;
import com.oracle.svm.core.image.ImageHeapLayouter;
import com.oracle.svm.core.jdk.ServiceCatalogSupport;
import com.oracle.svm.core.option.HostedOptionValues;
import com.oracle.svm.core.option.OptionClassFilter;
import com.oracle.svm.core.option.RuntimeOptionValues;
import com.oracle.svm.core.option.SubstrateOptionsParser;
import com.oracle.svm.core.riscv64.RISCV64CPUFeatureAccess;
import com.oracle.svm.core.snippets.SnippetRuntime;
import com.oracle.svm.core.util.InterruptImageBuilding;
import com.oracle.svm.core.util.ObservableImageHeapMapProvider;
import com.oracle.svm.core.util.UserError;
import com.oracle.svm.core.util.VMError;
import com.oracle.svm.hosted.FeatureImpl.AfterAnalysisAccessImpl;
import com.oracle.svm.hosted.FeatureImpl.AfterCompilationAccessImpl;
import com.oracle.svm.hosted.FeatureImpl.AfterHeapLayoutAccessImpl;
import com.oracle.svm.hosted.FeatureImpl.AfterImageWriteAccessImpl;
import com.oracle.svm.hosted.FeatureImpl.AfterRegistrationAccessImpl;
import com.oracle.svm.hosted.FeatureImpl.BeforeAnalysisAccessImpl;
import com.oracle.svm.hosted.FeatureImpl.BeforeCompilationAccessImpl;
import com.oracle.svm.hosted.FeatureImpl.BeforeHeapLayoutAccessImpl;
import com.oracle.svm.hosted.FeatureImpl.BeforeImageWriteAccessImpl;
import com.oracle.svm.hosted.FeatureImpl.BeforeUniverseBuildingAccessImpl;
import com.oracle.svm.hosted.FeatureImpl.ConcurrentAnalysisAccessImpl;
import com.oracle.svm.hosted.FeatureImpl.DuringAnalysisAccessImpl;
import com.oracle.svm.hosted.FeatureImpl.OnAnalysisExitAccessImpl;
import com.oracle.svm.hosted.ProgressReporter.ReporterClosable;
import com.oracle.svm.hosted.ameta.AnalysisConstantFieldProvider;
import com.oracle.svm.hosted.ameta.AnalysisConstantReflectionProvider;
import com.oracle.svm.hosted.ameta.SVMHostedValueProvider;
import com.oracle.svm.hosted.analysis.Inflation;
import com.oracle.svm.hosted.analysis.NativeImagePointsToAnalysis;
import com.oracle.svm.hosted.analysis.NativeImageReachabilityAnalysisEngine;
import com.oracle.svm.hosted.analysis.ReachabilityTracePrinter;
import com.oracle.svm.hosted.analysis.SVMAnalysisMetaAccess;
import com.oracle.svm.hosted.analysis.SubstrateUnsupportedFeatures;
import com.oracle.svm.hosted.annotation.SubstrateAnnotationExtractor;
import com.oracle.svm.hosted.c.CAnnotationProcessorCache;
import com.oracle.svm.hosted.c.CConstantValueSupportImpl;
import com.oracle.svm.hosted.c.NativeLibraries;
import com.oracle.svm.hosted.c.OffsetOfSupportImpl;
import com.oracle.svm.hosted.c.SizeOfSupportImpl;
import com.oracle.svm.hosted.c.codegen.CCompilerInvoker;
import com.oracle.svm.hosted.c.libc.HostedLibCBase;
import com.oracle.svm.hosted.cenum.CEnumCallWrapperSubstitutionProcessor;
import com.oracle.svm.hosted.classinitialization.ClassInitializationFeature;
import com.oracle.svm.hosted.classinitialization.ClassInitializationSupport;
import com.oracle.svm.hosted.classinitialization.SimulateClassInitializerSupport;
import com.oracle.svm.hosted.code.CEntryPointCallStubSupport;
import com.oracle.svm.hosted.code.CEntryPointData;
import com.oracle.svm.hosted.code.CFunctionSubstitutionProcessor;
import com.oracle.svm.hosted.code.CompileQueue;
import com.oracle.svm.hosted.code.DynamicMethodAddressResolutionHostedSupport;
import com.oracle.svm.hosted.code.HostedRuntimeConfigurationBuilder;
import com.oracle.svm.hosted.code.NativeMethodSubstitutionProcessor;
import com.oracle.svm.hosted.code.RestrictHeapAccessCalleesImpl;
import com.oracle.svm.hosted.code.SubstrateGraphMakerFactory;
import com.oracle.svm.hosted.heap.ObservableImageHeapMapProviderImpl;
import com.oracle.svm.hosted.heap.SVMImageHeapScanner;
import com.oracle.svm.hosted.heap.SVMImageHeapVerifier;
import com.oracle.svm.hosted.image.AbstractImage;
import com.oracle.svm.hosted.image.AbstractImage.NativeImageKind;
import com.oracle.svm.hosted.image.NativeImageCodeCache;
import com.oracle.svm.hosted.image.NativeImageCodeCacheFactory;
import com.oracle.svm.hosted.image.NativeImageHeap;
import com.oracle.svm.hosted.jdk.localization.LocalizationFeature;
import com.oracle.svm.hosted.meta.HostedConstantReflectionProvider;
import com.oracle.svm.hosted.meta.HostedField;
import com.oracle.svm.hosted.meta.HostedInterface;
import com.oracle.svm.hosted.meta.HostedMetaAccess;
import com.oracle.svm.hosted.meta.HostedMethod;
import com.oracle.svm.hosted.meta.HostedSnippetReflectionProvider;
import com.oracle.svm.hosted.meta.HostedType;
import com.oracle.svm.hosted.meta.HostedUniverse;
import com.oracle.svm.hosted.meta.UniverseBuilder;
import com.oracle.svm.hosted.option.HostedOptionProvider;
import com.oracle.svm.hosted.phases.CInterfaceInvocationPlugin;
import com.oracle.svm.hosted.phases.ConstantFoldLoadFieldPlugin;
import com.oracle.svm.hosted.phases.EarlyConstantFoldLoadFieldPlugin;
import com.oracle.svm.hosted.phases.ImageBuildStatisticsCounterPhase;
import com.oracle.svm.hosted.phases.InjectedAccessorsPlugin;
import com.oracle.svm.hosted.phases.SubstrateClassInitializationPlugin;
import com.oracle.svm.hosted.phases.VerifyDeoptLIRFrameStatesPhase;
import com.oracle.svm.hosted.phases.VerifyNoGuardsPhase;
import com.oracle.svm.hosted.reflect.proxy.ProxyRenamingSubstitutionProcessor;
import com.oracle.svm.hosted.snippets.SubstrateGraphBuilderPlugins;
import com.oracle.svm.hosted.substitute.AnnotationSubstitutionProcessor;
import com.oracle.svm.hosted.substitute.DeletedFieldsPlugin;
import com.oracle.svm.hosted.util.CPUTypeAArch64;
import com.oracle.svm.hosted.util.CPUTypeAMD64;
import com.oracle.svm.hosted.util.CPUTypeRISCV64;
import com.oracle.svm.util.ClassUtil;
import com.oracle.svm.util.ImageBuildStatistics;
import com.oracle.svm.util.ReflectionUtil;
import com.oracle.svm.util.ReflectionUtil.ReflectionUtilError;
import com.oracle.svm.util.StringUtil;
import jdk.graal.compiler.api.replacements.Fold;
import jdk.graal.compiler.api.replacements.SnippetReflectionProvider;
import jdk.graal.compiler.bytecode.BytecodeProvider;
import jdk.graal.compiler.bytecode.ResolvedJavaMethodBytecodeProvider;
import jdk.graal.compiler.core.common.GraalOptions;
import jdk.graal.compiler.core.common.spi.ForeignCallsProvider;
import jdk.graal.compiler.core.common.spi.MetaAccessExtensionProvider;
import jdk.graal.compiler.core.common.util.CompilationAlarm;
import jdk.graal.compiler.debug.DebugCloseable;
import jdk.graal.compiler.debug.DebugContext;
import jdk.graal.compiler.debug.DebugContext.Builder;
import jdk.graal.compiler.debug.DebugDumpScope;
import jdk.graal.compiler.debug.Indent;
import jdk.graal.compiler.graph.Node;
import jdk.graal.compiler.hotspot.GraalHotSpotVMConfig;
import jdk.graal.compiler.hotspot.HotSpotGraalCompiler;
import jdk.graal.compiler.hotspot.HotSpotGraalRuntimeProvider;
import jdk.graal.compiler.java.BciBlockMapping;
import jdk.graal.compiler.lir.phases.LIRSuites;
import jdk.graal.compiler.loop.phases.ConvertDeoptimizeToGuardPhase;
import jdk.graal.compiler.nodes.GraphEncoder;
import jdk.graal.compiler.nodes.StructuredGraph;
import jdk.graal.compiler.nodes.gc.BarrierSet;
import jdk.graal.compiler.nodes.graphbuilderconf.ClassInitializationPlugin;
import jdk.graal.compiler.nodes.graphbuilderconf.GeneratedPluginFactory;
import jdk.graal.compiler.nodes.graphbuilderconf.GraphBuilderConfiguration;
import jdk.graal.compiler.nodes.graphbuilderconf.InvocationPlugin;
import jdk.graal.compiler.nodes.graphbuilderconf.InvocationPlugins;
import jdk.graal.compiler.nodes.spi.CoreProviders;
import jdk.graal.compiler.nodes.spi.LoweringProvider;
import jdk.graal.compiler.nodes.spi.StampProvider;
import jdk.graal.compiler.options.OptionValues;
import jdk.graal.compiler.phases.BasePhase;
import jdk.graal.compiler.phases.FloatingGuardPhase;
import jdk.graal.compiler.phases.PhaseSuite;
import jdk.graal.compiler.phases.Speculative;
import jdk.graal.compiler.phases.common.AddressLoweringPhase;
import jdk.graal.compiler.phases.common.CanonicalizerPhase;
import jdk.graal.compiler.phases.common.DeoptimizationGroupingPhase;
import jdk.graal.compiler.phases.common.FrameStateAssignmentPhase;
import jdk.graal.compiler.phases.common.LoopSafepointInsertionPhase;
import jdk.graal.compiler.phases.common.inlining.InliningPhase;
import jdk.graal.compiler.phases.tiers.HighTierContext;
import jdk.graal.compiler.phases.tiers.LowTierContext;
import jdk.graal.compiler.phases.tiers.MidTierContext;
import jdk.graal.compiler.phases.tiers.Suites;
import jdk.graal.compiler.phases.util.Providers;
import jdk.graal.compiler.printer.GraalDebugHandlersFactory;
import jdk.graal.compiler.replacements.MethodHandleWithExceptionPlugin;
import jdk.graal.compiler.replacements.NodeIntrinsificationProvider;
import jdk.graal.compiler.replacements.TargetGraphBuilderPlugins;
import jdk.graal.compiler.word.WordOperationPlugin;
import jdk.graal.compiler.word.WordTypes;
import jdk.vm.ci.aarch64.AArch64;
import jdk.vm.ci.amd64.AMD64;
import jdk.vm.ci.code.Architecture;
import jdk.vm.ci.code.CodeCacheProvider;
import jdk.vm.ci.code.TargetDescription;
import jdk.vm.ci.hotspot.HotSpotJVMCIRuntime;
import jdk.vm.ci.meta.Constant;
import jdk.vm.ci.meta.ConstantReflectionProvider;
import jdk.vm.ci.meta.JavaKind;
import jdk.vm.ci.meta.MetaAccessProvider;
import jdk.vm.ci.meta.ResolvedJavaMethod;
import jdk.vm.ci.meta.ResolvedJavaType;
import jdk.vm.ci.riscv64.RISCV64;
public class NativeImageGenerator {
protected final FeatureHandler featureHandler;
protected final ImageClassLoader loader;
protected final HostedOptionProvider optionProvider;
protected final ProgressReporter reporter;
protected AnalysisUniverse aUniverse;
protected HostedUniverse hUniverse;
protected Inflation bb;
protected NativeLibraries nativeLibraries;
protected AbstractImage image;
protected AtomicBoolean buildStarted = new AtomicBoolean();
protected Pair<Method, CEntryPointData> mainEntryPoint;
protected final Map<ArtifactType, List<Path>> buildArtifacts = new EnumMap<>(ArtifactType.class);
public NativeImageGenerator(ImageClassLoader loader, HostedOptionProvider optionProvider, Pair<Method, CEntryPointData> mainEntryPoint, ProgressReporter reporter) {
this.loader = loader;
this.mainEntryPoint = mainEntryPoint;
this.featureHandler = new FeatureHandler();
this.optionProvider = optionProvider;
this.reporter = reporter;
/*
* Substrate VM parses all graphs, including snippets, early. We do not support bytecode
* parsing at run time.
*/
optionProvider.getHostedValues().put(GraalOptions.EagerSnippets, true);
optionProvider.getHostedValues().put(CompilationAlarm.Options.CompilationNoProgressPeriod, 0D);
optionProvider.getRuntimeValues().put(GraalOptions.EagerSnippets, true);
if (!optionProvider.getHostedValues().containsKey(BciBlockMapping.Options.MaxDuplicationFactor)) {
/*
* Not being able to parse irreducible loops and jsr/ret structures means that image
* generation fails. We therefore allow a good bit of duplication.
*/
optionProvider.getHostedValues().put(BciBlockMapping.Options.MaxDuplicationFactor, 10.0);
}
}
public static Platform loadPlatform(ClassLoader classLoader, String platformClassName) throws ClassNotFoundException {
Class<?> platformClass;
platformClass = classLoader.loadClass(platformClassName);
Object result;
try {
result = ReflectionUtil.newInstance(platformClass);
} catch (ReflectionUtilError ex) {
throw UserError.abort(ex.getCause(), "Could not instantiate platform class %s. Ensure the class is not abstract and has a no-argument constructor.", platformClassName);
}
if (!(result instanceof Platform)) {
throw UserError.abort("Platform class %s does not implement %s", platformClassName, Platform.class.getTypeName());
}
return (Platform) result;
}
public static Platform loadPlatform(String os, String arch) {
ServiceLoader<Platform> loader = ServiceLoader.load(Platform.class);
for (Platform platform : loader) {
if (platform.getOS().equals(os) && platform.getArchitecture().equals(arch)) {
return platform;
}
}
throw UserError.abort("Platform specified as " + os + "-" + arch + " isn't supported.");
}
public static Platform getTargetPlatform(ClassLoader classLoader) {
/*
* We cannot use a regular hosted option for the platform class: The code that instantiates
* the platform class runs before options are parsed, because option parsing depends on the
* platform (there can be platform-specific options). So we need to use a regular system
* property to specify a platform class explicitly on the command line.
*/
String platformClassName = System.getProperty(Platform.PLATFORM_PROPERTY_NAME);
if (platformClassName != null) {
try {
return loadPlatform(classLoader, platformClassName);
} catch (ClassNotFoundException ex) {
throw UserError.abort("Could not find platform class %s that was specified explicitly on the command line using the system property %s",
platformClassName, Platform.PLATFORM_PROPERTY_NAME);
}
}
String os = System.getProperty("svm.targetPlatformOS");
if (os == null) {
os = OS.getCurrent().className.toLowerCase(Locale.ROOT);
}
String arch = System.getProperty("svm.targetPlatformArch");
if (arch == null) {
arch = SubstrateUtil.getArchitectureName();
}
return loadPlatform(os, arch);
}
/**
* Duplicates the logic in {@link Platform#includedIn(Class)}, but can be used in cases where
* the VMConfiguration is not yet set up.
*/
public static boolean includedIn(Platform platform, Class<? extends Platform> platformGroup) {
return platformGroup.isInstance(platform);
}
/**
* Returns true if the provided platform is included in at least one of the provided platform
* groups defined by the annotation. Also returns true if no annotation is provided.
*/
public static boolean includedIn(Platform platform, Platforms platformsAnnotation) {
if (platformsAnnotation == null) {
return true;
}
for (Class<? extends Platform> platformGroup : platformsAnnotation.value()) {
if (includedIn(platform, platformGroup)) {
return true;
}
}
return false;
}
protected SubstrateTargetDescription createTarget() {
return createTarget(loader.platform);
}
public static SubstrateTargetDescription createTarget(Platform platform) {
if (includedIn(platform, Platform.AMD64.class)) {
EnumSet<AMD64.CPUFeature> features = CPUTypeAMD64.getSelectedFeatures();
features.addAll(parseCSVtoEnum(AMD64.CPUFeature.class, NativeImageOptions.CPUFeatures.getValue().values(), AMD64.CPUFeature.values()));
// GR-33542 RTM is only intermittently detected and is not used by Graal
features.remove(AMD64.CPUFeature.RTM);
// set up the runtime checked cpu features
EnumSet<AMD64.CPUFeature> runtimeCheckedFeatures = features.clone();
if (NativeImageOptions.RuntimeCheckedCPUFeatures.hasBeenSet()) {
runtimeCheckedFeatures.addAll(parseCSVtoEnum(AMD64.CPUFeature.class, NativeImageOptions.RuntimeCheckedCPUFeatures.getValue().values(), AMD64.CPUFeature.values()));
} else {
var disabledFeatures = RuntimeCPUFeatureCheck.getDefaultDisabledFeatures(GraalAccess.getOriginalTarget().arch);
for (Enum<?> feature : RuntimeCPUFeatureCheck.getSupportedFeatures(GraalAccess.getOriginalTarget().arch)) {
if (!disabledFeatures.contains(feature)) {
runtimeCheckedFeatures.add((AMD64.CPUFeature) feature);
}
}
}
AMD64 architecture = new AMD64(features, AMD64CPUFeatureAccess.allAMD64Flags());
return new SubstrateTargetDescription(architecture, true, 16, 0, runtimeCheckedFeatures);
} else if (includedIn(platform, Platform.AARCH64.class)) {
EnumSet<AArch64.CPUFeature> features = CPUTypeAArch64.getSelectedFeatures();
features.addAll(parseCSVtoEnum(AArch64.CPUFeature.class, NativeImageOptions.CPUFeatures.getValue().values(), AArch64.CPUFeature.values()));
AArch64 architecture = new AArch64(features, AArch64CPUFeatureAccess.enabledAArch64Flags());
// runtime checked features are the same as static features on AArch64 for now
EnumSet<AArch64.CPUFeature> runtimeCheckedFeatures = architecture.getFeatures().clone();
return new SubstrateTargetDescription(architecture, true, 16, 0, runtimeCheckedFeatures);
} else if (includedIn(platform, Platform.RISCV64.class)) {
EnumSet<RISCV64.CPUFeature> features = CPUTypeRISCV64.getSelectedFeatures();
features.addAll(parseCSVtoEnum(RISCV64.CPUFeature.class, NativeImageOptions.CPUFeatures.getValue().values(), RISCV64.CPUFeature.values()));
RISCV64 architecture = new RISCV64(features, RISCV64CPUFeatureAccess.enabledRISCV64Flags());
// runtime checked features are the same as static features on RISCV64 for now
EnumSet<RISCV64.CPUFeature> runtimeCheckedFeatures = architecture.getFeatures().clone();
return new SubstrateTargetDescription(architecture, true, 16, 0, runtimeCheckedFeatures);
} else {
throw UserError.abort("Architecture specified by platform is not supported: %s", platform.getClass().getTypeName());
}
}
/**
* Executes the image build. Only one image can be built with this generator.
*/
public void run(Map<Method, CEntryPointData> entryPoints,
JavaMainSupport javaMainSupport, String imageName,
NativeImageKind k,
SubstitutionProcessor harnessSubstitutions,
EconomicSet<String> allOptionNames, TimerCollection timerCollection) {
if (!buildStarted.compareAndSet(false, true)) {
throw UserError.abort("An image build has already been performed with this generator.");
}
try {
/*
* JVMCI 20.2-b01 introduced new methods for linking and querying whether an interface
* has default methods. Fail early if these methods are missing.
*/
ResolvedJavaType.class.getDeclaredMethod("link");
} catch (ReflectiveOperationException ex) {
throw UserError.abort("JVMCI version provided %s is missing the 'ResolvedJavaType.link()' method added in jvmci-20.2-b01. " +
"Please use the latest JVMCI JDK from %s.", System.getProperty("java.home"), OPEN_LABSJDK_RELEASE_URL_PATTERN);
}
setSystemPropertiesForImageLate(k);
var hostedOptionValues = new HostedOptionValues(optionProvider.getHostedValues());
SVMImageLayerSupport imageLayerSupport = SVMImageLayerSupport.initialize(hostedOptionValues);
ImageSingletonsSupportImpl.HostedManagement.install(new ImageSingletonsSupportImpl.HostedManagement(), imageLayerSupport);
ImageSingletons.add(SVMImageLayerSupport.class, imageLayerSupport);
ImageSingletons.add(ProgressReporter.class, reporter);
ImageSingletons.add(DeadlockWatchdog.class, loader.watchdog);
ImageSingletons.add(TimerCollection.class, timerCollection);
ImageSingletons.add(ImageBuildStatistics.TimerCollectionPrinter.class, timerCollection);
ImageSingletons.add(AnnotationExtractor.class, loader.classLoaderSupport.annotationExtractor);
ImageSingletons.add(BuildArtifacts.class, (type, artifact) -> buildArtifacts.computeIfAbsent(type, t -> new ArrayList<>()).add(artifact));
ImageSingletons.add(HostedOptionValues.class, hostedOptionValues);
ImageSingletons.add(RuntimeOptionValues.class, new RuntimeOptionValues(optionProvider.getRuntimeValues(), allOptionNames));
try (TemporaryBuildDirectoryProviderImpl tempDirectoryProvider = new TemporaryBuildDirectoryProviderImpl()) {
ImageSingletons.add(TemporaryBuildDirectoryProvider.class, tempDirectoryProvider);
if (imageLayerSupport.hasWriter()) {
setupImageLayerArtifact(imageName);
}
doRun(entryPoints, javaMainSupport, imageName, k, harnessSubstitutions);
if (imageLayerSupport.persistImageSingletons()) {
ImageSingletonsSupportImpl.HostedManagement.persist();
}
if (imageLayerSupport.hasWriter()) {
imageLayerSupport.getWriter().dumpFile();
}
} finally {
reporter.ensureCreationStageEndCompleted();
}
}
protected static void setSystemPropertiesForImageEarly() {
System.setProperty(ImageInfo.PROPERTY_IMAGE_CODE_KEY, ImageInfo.PROPERTY_IMAGE_CODE_VALUE_BUILDTIME);
}
private static void setSystemPropertiesForImageLate(NativeImageKind imageKind) {
VMError.guarantee(ImageInfo.inImageBuildtimeCode(), "System property to indicate image build time is set earlier, before listing classes");
if (imageKind.isExecutable) {
System.setProperty(ImageInfo.PROPERTY_IMAGE_KIND_KEY, ImageInfo.PROPERTY_IMAGE_KIND_VALUE_EXECUTABLE);
} else {
System.setProperty(ImageInfo.PROPERTY_IMAGE_KIND_KEY, ImageInfo.PROPERTY_IMAGE_KIND_VALUE_SHARED_LIBRARY);
}
}
public static void clearSystemPropertiesForImage() {
System.clearProperty(ImageInfo.PROPERTY_IMAGE_CODE_KEY);
System.clearProperty(ImageInfo.PROPERTY_IMAGE_KIND_KEY);
}
@SuppressWarnings("try")
protected void doRun(Map<Method, CEntryPointData> entryPoints, JavaMainSupport javaMainSupport, String imageName, NativeImageKind k, SubstitutionProcessor harnessSubstitutions) {
List<HostedMethod> hostedEntryPoints = new ArrayList<>();
OptionValues options = HostedOptionValues.singleton();
try (DebugContext debug = new Builder(options, new GraalDebugHandlersFactory(GraalAccess.getOriginalSnippetReflection())).build();
DebugCloseable featureCleanup = () -> featureHandler.forEachFeature(Feature::cleanup)) {
setupNativeImage(options, entryPoints, javaMainSupport, harnessSubstitutions, debug);
boolean returnAfterAnalysis = runPointsToAnalysis(imageName, options, debug);
if (returnAfterAnalysis) {
return;
}
NativeImageHeap heap;
HostedMetaAccess hMetaAccess;
RuntimeConfiguration runtimeConfiguration;
try (ReporterClosable c = reporter.printUniverse()) {
loader.watchdog.recordActivity();
hUniverse = new HostedUniverse(bb);
hMetaAccess = new HostedMetaAccess(hUniverse, bb.getMetaAccess());
BeforeUniverseBuildingAccessImpl beforeUniverseBuildingConfig = new BeforeUniverseBuildingAccessImpl(featureHandler, loader, debug, hMetaAccess);
featureHandler.forEachFeature(feature -> feature.beforeUniverseBuilding(beforeUniverseBuildingConfig));
new UniverseBuilder(aUniverse, bb.getMetaAccess(), hUniverse, hMetaAccess, HostedConfiguration.instance().createStrengthenGraphs(bb, hUniverse),
bb.getUnsupportedFeatures()).build(debug);
BuildPhaseProvider.markHostedUniverseBuilt();
ClassInitializationSupport classInitializationSupport = bb.getHostVM().getClassInitializationSupport();
SubstratePlatformConfigurationProvider platformConfig = getPlatformConfig(hMetaAccess);
runtimeConfiguration = new HostedRuntimeConfigurationBuilder(options, bb.getHostVM(), hUniverse, hMetaAccess,
bb.getProviders(MultiMethod.ORIGINAL_METHOD), classInitializationSupport, GraalAccess.getOriginalProviders().getLoopsDataProvider(), platformConfig,
bb.getSnippetReflectionProvider()).build();
registerGraphBuilderPlugins(featureHandler, runtimeConfiguration, (HostedProviders) runtimeConfiguration.getProviders(), bb.getMetaAccess(), aUniverse,
nativeLibraries, loader, ParsingReason.AOTCompilation, bb.getAnnotationSubstitutionProcessor(),
new SubstrateClassInitializationPlugin((SVMHost) aUniverse.hostVM()),
ConfigurationValues.getTarget(), this.isStubBasedPluginsSupported());
if (NativeImageOptions.PrintUniverse.getValue()) {
printTypes();
}
/* Find the entry point methods in the hosted world. */
for (AnalysisMethod m : aUniverse.getMethods()) {
if (m.isEntryPoint()) {
HostedMethod found = hUniverse.lookup(m);
assert found != null;
hostedEntryPoints.add(found);
}
}
if (hostedEntryPoints.size() == 0) {
throw UserError.abort("No entry points found, i.e., no method annotated with @%s", CEntryPoint.class.getSimpleName());
}
bb.getUnsupportedFeatures().report(bb);
recordRestrictHeapAccessCallees(aUniverse.getMethods());
/*
* After this point, all TypeFlow (and therefore also TypeState) objects are
* unreachable and can be garbage collected. This is important to keep the overall
* memory footprint low. However, this also means we no longer have complete call
* chain information. Only the summarized information stored in the
* StaticAnalysisResult objects is available after this point.
*/
bb.cleanupAfterAnalysis();
} catch (UnsupportedFeatureException ufe) {
throw FallbackFeature.reportAsFallback(ufe);
}
var hConstantReflection = (HostedConstantReflectionProvider) runtimeConfiguration.getProviders().getConstantReflection();
heap = new NativeImageHeap(aUniverse, hUniverse, hMetaAccess, hConstantReflection, ImageSingletons.lookup(ImageHeapLayouter.class));
if (SVMImageLayerSupport.singleton().persistAnalysis()) {
SVMImageLayerSupport.singleton().getWriter().setNativeImageHeap(heap);
}
BeforeCompilationAccessImpl beforeCompilationConfig = new BeforeCompilationAccessImpl(featureHandler, loader, aUniverse, hUniverse, heap, debug, runtimeConfiguration, nativeLibraries);
featureHandler.forEachFeature(feature -> feature.beforeCompilation(beforeCompilationConfig));
BuildPhaseProvider.markReadyForCompilation();
NativeImageCodeCache codeCache;
CompileQueue compileQueue;
try (StopTimer t = TimerCollection.createTimerAndStart(TimerCollection.Registry.COMPILE_TOTAL)) {
compileQueue = HostedConfiguration.instance().createCompileQueue(debug, featureHandler, hUniverse, runtimeConfiguration, DeoptTester.enabled());
if (ImageSingletons.contains(RuntimeCompilationCallbacks.class)) {
ImageSingletons.lookup(RuntimeCompilationCallbacks.class).onCompileQueueCreation(bb, hUniverse, compileQueue);
}
compileQueue.finish(debug);
BuildPhaseProvider.markCompileQueueFinished();
/* release memory taken by graphs for the image writing */
hUniverse.getMethods().forEach(HostedMethod::clear);
try (ProgressReporter.ReporterClosable ac = reporter.printLayouting()) {
codeCache = NativeImageCodeCacheFactory.get().newCodeCache(compileQueue, heap, loader.platform,
ImageSingletons.lookup(TemporaryBuildDirectoryProvider.class).getTemporaryBuildDirectory());
codeCache.layoutConstants();
codeCache.layoutMethods(debug, bb);
codeCache.buildRuntimeMetadata(debug, bb.getSnippetReflectionProvider());
}
AfterCompilationAccessImpl config = new AfterCompilationAccessImpl(featureHandler, loader, aUniverse, hUniverse, compileQueue.getCompilations(), codeCache, heap, debug,
runtimeConfiguration, nativeLibraries);
featureHandler.forEachFeature(feature -> feature.afterCompilation(config));
BuildPhaseProvider.markCompilationFinished();
}
/* Re-run shadow heap verification after compilation. */
aUniverse.getHeapVerifier().checkHeapSnapshot(debug, hMetaAccess, "after compilation", bb.getUniverse().getEmbeddedRoots());
bb.getUnsupportedFeatures().report(bb);
CodeCacheProvider codeCacheProvider = runtimeConfiguration.getBackendForNormalMethod().getProviders().getCodeCache();
reporter.printCreationStart();
try (Indent indent = debug.logAndIndent("create native image")) {
try (DebugContext.Scope buildScope = debug.scope("CreateImage", codeCacheProvider)) {
try (StopTimer t = TimerCollection.createTimerAndStart(TimerCollection.Registry.IMAGE)) {
loader.watchdog.recordActivity();
BeforeHeapLayoutAccessImpl beforeLayoutConfig = new BeforeHeapLayoutAccessImpl(featureHandler, loader, aUniverse, hUniverse, heap, debug, runtimeConfiguration,
nativeLibraries);
featureHandler.forEachFeature(feature -> feature.beforeHeapLayout(beforeLayoutConfig));
verifyAndSealShadowHeap(codeCache, debug, heap);
buildNativeImageHeap(heap, codeCache);
AfterHeapLayoutAccessImpl config = new AfterHeapLayoutAccessImpl(featureHandler, loader, heap, hMetaAccess, debug);
featureHandler.forEachFeature(feature -> feature.afterHeapLayout(config));
createAbstractImage(k, hostedEntryPoints, heap, hMetaAccess, codeCache);
if (ImageSingletons.contains(DynamicMethodAddressResolutionHostedSupport.class)) {
ImageSingletons.lookup(DynamicMethodAddressResolutionHostedSupport.class).install(image.getObjectFile());
}
image.build(imageName, debug);
if (SVMImageLayerSupport.singleton().persistAnalysis()) {
SVMImageLayerSupport.singleton().getWriter().persistAnalysisInfo(hUniverse, bb.getUniverse());
}
if (NativeImageOptions.PrintUniverse.getValue()) {
/*
* This debug output must be printed _after_ and not _during_ image
* building, because it adds some PrintStream objects to static fields,
* which disrupts the heap.
*/
codeCache.printCompilationResults();
}
}
} catch (Throwable e) {
throw debug.handle(e);
}
}
compileQueue.purge();
int numCompilations = codeCache.getOrderedCompilations().size();
try (StopTimer t = TimerCollection.createTimerAndStart(TimerCollection.Registry.WRITE)) {
loader.watchdog.recordActivity();
BeforeImageWriteAccessImpl beforeConfig = new BeforeImageWriteAccessImpl(featureHandler, loader, imageName, image,
runtimeConfiguration, aUniverse, hUniverse, optionProvider, hMetaAccess, debug);
featureHandler.forEachFeature(feature -> feature.beforeImageWrite(beforeConfig));
/*
* This will write the debug info too -- i.e. we may be writing more than one file,
* if the debug info is in a separate file. We need to push writing the file to the
* image implementation, because whether the debug info and image share a file or
* not is an implementation detail of the image.
*/
Path tmpDir = ImageSingletons.lookup(TemporaryBuildDirectoryProvider.class).getTemporaryBuildDirectory();
LinkerInvocation inv = image.write(debug, generatedFiles(HostedOptionValues.singleton()), tmpDir, imageName, beforeConfig);
if (NativeImageOptions.ExitAfterRelocatableImageWrite.getValue()) {
return;
}
AfterImageWriteAccessImpl afterConfig = new AfterImageWriteAccessImpl(featureHandler, loader, hUniverse, inv, tmpDir, image.getImageKind(), debug);
featureHandler.forEachFeature(feature -> feature.afterImageWrite(afterConfig));
}
reporter.printCreationEnd(image.getImageFileSize(), heap.getObjectCount(), image.getImageHeapSize(), codeCache.getCodeAreaSize(), numCompilations, image.getDebugInfoSize());
}
}
/*
* Re-run shadow heap verification before heap layout. This time the verification uses the
* embedded roots discovered after compilation.
*/
private void verifyAndSealShadowHeap(NativeImageCodeCache codeCache, DebugContext debug, NativeImageHeap heap) {
/*
* Get the embedded constants after compilation to include everything, e.g., interned string
* from snippet lowering that would otherwise be missed.
*/
Map<Constant, Object> embeddedConstants = codeCache.initAndGetEmbeddedConstants();
bb.getUniverse().getHeapVerifier().checkHeapSnapshot(debug, heap.hMetaAccess, "before heap layout", embeddedConstants);
bb.getUnsupportedFeatures().report(bb);
/*
* Seal shadow heap after final verification. Any modification to the shadow heap after this
* point, i.e., registering a new ImageHeapConstant or materializing the hosted values
* reader of an existing ImageHeapConstant, will result in an error.
*/
bb.getUniverse().getHeapScanner().seal();
}
protected void buildNativeImageHeap(NativeImageHeap heap, NativeImageCodeCache codeCache) {
// Start building the model of the native image heap.
heap.addInitialObjects();
// Then build the model of the code cache, which can
// add objects to the native image heap.
codeCache.addConstantsToHeap();
// Finish building the model of the native image heap.
heap.addTrailingObjects();
}
private static void setupImageLayerArtifact(String imageName) {
int imageNameStart = imageName.lastIndexOf('/') + 1;
String fileName = ImageLayerSnapshotUtil.FILE_NAME_PREFIX + imageName.substring(imageNameStart);
String filePath = imageName.substring(0, imageNameStart) + fileName;
Path layerSnapshotPath = generatedFiles(HostedOptionValues.singleton()).resolve(filePath + ImageLayerSnapshotUtil.FILE_EXTENSION);
SVMImageLayerSupport.singleton().getWriter().setFileInfo(layerSnapshotPath, fileName, ImageLayerSnapshotUtil.FILE_EXTENSION);
BuildArtifacts.singleton().add(ArtifactType.LAYER_SNAPSHOT, layerSnapshotPath);
}
protected void createAbstractImage(NativeImageKind k, List<HostedMethod> hostedEntryPoints, NativeImageHeap heap, HostedMetaAccess hMetaAccess, NativeImageCodeCache codeCache) {
this.image = AbstractImage.create(k, hUniverse, hMetaAccess, nativeLibraries, heap, codeCache, hostedEntryPoints, loader.getClassLoader());
}
@SuppressWarnings("try")
protected boolean runPointsToAnalysis(String imageName, OptionValues options, DebugContext debug) {
try (Indent ignored = debug.logAndIndent("run analysis")) {
try (Indent ignored1 = debug.logAndIndent("process analysis initializers")) {
BeforeAnalysisAccessImpl config = new BeforeAnalysisAccessImpl(featureHandler, loader, bb, nativeLibraries, debug);
ServiceCatalogSupport.singleton().enableServiceCatalogMapTransformer(config);
featureHandler.forEachFeature(feature -> feature.beforeAnalysis(config));
ServiceCatalogSupport.singleton().seal();
bb.getHostVM().getClassInitializationSupport().setConfigurationSealed(true);
}
if (SVMImageLayerSupport.singleton().loadAnalysis()) {
SVMImageLayerSupport.singleton().getLoader().loadLayerConstants();
}
try (ReporterClosable c = ProgressReporter.singleton().printAnalysis(bb.getUniverse(), nativeLibraries.getLibraries())) {
DuringAnalysisAccessImpl config = new DuringAnalysisAccessImpl(featureHandler, loader, bb, nativeLibraries, debug);
try {
ConcurrentAnalysisAccessImpl concurrentConfig = new ConcurrentAnalysisAccessImpl(featureHandler, loader, bb, nativeLibraries, debug);
aUniverse.setConcurrentAnalysisAccess(concurrentConfig);
bb.runAnalysis(debug, (universe) -> {
try (StopTimer t2 = TimerCollection.createTimerAndStart(TimerCollection.Registry.FEATURES)) {
bb.getHostVM().notifyClassReachabilityListener(universe, config);
featureHandler.forEachFeature(feature -> feature.duringAnalysis(config));
}
return !config.getAndResetRequireAnalysisIteration();
});
} catch (Throwable t) {
if (ImageSingletons.contains(RuntimeCompilationCallbacks.class)) {
ImageSingletons.lookup(RuntimeCompilationCallbacks.class).reportAnalysisError(aUniverse, t);
}
if (t instanceof AnalysisError e) {
throw UserError.abort(e, "Analysis step failed. Reason: %s.", e.getMessage());
} else {
throw t;
}
}
assert verifyAssignableTypes();
/*
* Libraries defined via @CLibrary annotations are added at the end of the list of
* libraries so that the written object file AND the static JDK libraries can depend
* on them.
*/
nativeLibraries.processAnnotated();
BuildPhaseProvider.markAnalysisFinished();
AfterAnalysisAccessImpl postConfig = new AfterAnalysisAccessImpl(featureHandler, loader, bb, debug);
featureHandler.forEachFeature(feature -> feature.afterAnalysis(postConfig));
checkUniverse();
/* report the unsupported features by throwing UnsupportedFeatureException */
bb.getUnsupportedFeatures().report(bb);
bb.checkUserLimitations();
bb.afterAnalysis();
} catch (UnsupportedFeatureException ufe) {
throw FallbackFeature.reportAsFallback(ufe);
}
} catch (InterruptedException ie) {
throw new InterruptImageBuilding();
} finally {
OnAnalysisExitAccess onExitConfig = new OnAnalysisExitAccessImpl(featureHandler, loader, bb, debug);
featureHandler.forEachFeature(feature -> feature.onAnalysisExit(onExitConfig));
String reportsPath = SubstrateOptions.reportsPath();
/*
* Execute analysis reporting here. This code is executed even if unsupported features
* are reported or the analysis fails due to any other reasons.
*/
AnalysisReporter.printAnalysisReports(imageName, options, reportsPath, bb);
ReachabilityTracePrinter.report(imageName, options, reportsPath, bb);
}
if (NativeImageOptions.ReturnAfterAnalysis.getValue()) {
return true;
}
if (NativeImageOptions.ExitAfterAnalysis.getValue()) {
throw new InterruptImageBuilding("Exiting image generation because of " + SubstrateOptionsParser.commandArgument(NativeImageOptions.ExitAfterAnalysis, "+"));
}
return false;
}
@SuppressWarnings("try")
protected boolean verifyAssignableTypes() {
/*
* This verification has quadratic complexity, so do it only once after the static analysis
* has finished, and can be disabled with an option.
*/
if (SubstrateOptions.DisableTypeIdResultVerification.getValue()) {
return true;
}
try (StopTimer t = TimerCollection.createTimerAndStart("(verifyAssignableTypes)")) {
return AnalysisType.verifyAssignableTypes(bb);
}
}
@SuppressWarnings("try")
protected void setupNativeImage(OptionValues options, Map<Method, CEntryPointData> entryPoints, JavaMainSupport javaMainSupport,
SubstitutionProcessor harnessSubstitutions, DebugContext debug) {
try (Indent ignored = debug.logAndIndent("setup native-image builder")) {
try (StopTimer ignored1 = TimerCollection.createTimerAndStart(TimerCollection.Registry.SETUP)) {
SubstrateTargetDescription target = createTarget();
ImageSingletons.add(Platform.class, loader.platform);
ImageSingletons.add(SubstrateTargetDescription.class, target);
ImageSingletons.add(SubstrateOptions.ReportingSupport.class, new SubstrateOptions.ReportingSupport(
DiagnosticsMode.getValue() ? DiagnosticsDir.getValue().lastValue().get() : Path.of("reports")));
if (javaMainSupport != null) {
ImageSingletons.add(JavaMainSupport.class, javaMainSupport);
}
Providers originalProviders = GraalAccess.getOriginalProviders();
MetaAccessProvider originalMetaAccess = originalProviders.getMetaAccess();
ClassLoaderSupportImpl classLoaderSupport = new ClassLoaderSupportImpl(loader.classLoaderSupport);
ImageSingletons.add(ClassLoaderSupport.class, classLoaderSupport);
ImageSingletons.add(LinkAtBuildTimeSupport.class, new LinkAtBuildTimeSupport(loader, classLoaderSupport));
ImageSingletons.add(ObservableImageHeapMapProvider.class, new ObservableImageHeapMapProviderImpl());
ClassInitializationSupport classInitializationSupport = new ClassInitializationSupport(originalMetaAccess, loader);
ImageSingletons.add(RuntimeClassInitializationSupport.class, classInitializationSupport);
ClassInitializationFeature.processClassInitializationOptions(classInitializationSupport);
OptionClassFilter missingRegistrationClassFilter = OptionClassFilterBuilder.createFilter(loader, SubstrateOptions.ThrowMissingRegistrationErrors,
SubstrateOptions.ThrowMissingRegistrationErrorsPaths);
ImageSingletons.add(MissingRegistrationSupport.class, new MissingRegistrationSupport(missingRegistrationClassFilter));
if (ImageBuildStatistics.Options.CollectImageBuildStatistics.getValue(options)) {
ImageSingletons.add(ImageBuildStatistics.class, new ImageBuildStatistics());
}
if (SubstrateOptions.useEconomyCompilerConfig()) {
GraalConfiguration.setHostedInstanceIfEmpty(new EconomyGraalConfiguration());
}
/* Init the BuildPhaseProvider before any features need it. */
BuildPhaseProvider.init();
featureHandler.registerFeatures(loader, debug);
AfterRegistrationAccessImpl access = new AfterRegistrationAccessImpl(featureHandler, loader, originalMetaAccess, mainEntryPoint, debug);
featureHandler.forEachFeature(feature -> feature.afterRegistration(access));
setDefaultLibCIfMissing();
if (!Pair.<Method, CEntryPointData> empty().equals(access.getMainEntryPoint())) {
setAndVerifyMainEntryPoint(access, entryPoints);
}
registerEntryPoints(entryPoints);
setDefaultConfiguration();
AnnotationSubstitutionProcessor annotationSubstitutions = createAnnotationSubstitutionProcessor(originalMetaAccess, loader, classInitializationSupport);
CEnumCallWrapperSubstitutionProcessor cEnumProcessor = new CEnumCallWrapperSubstitutionProcessor();
aUniverse = createAnalysisUniverse(options, target, loader, originalMetaAccess, annotationSubstitutions, cEnumProcessor,
classInitializationSupport, Collections.singletonList(harnessSubstitutions));
ImageLayerLoader imageLayerLoader = null;
if (SVMImageLayerSupport.singleton().loadAnalysis()) {
imageLayerLoader = SVMImageLayerSupport.singleton().getLoader();
imageLayerLoader.setUniverse(aUniverse);
aUniverse.setImageLayerLoader(imageLayerLoader);
imageLayerLoader.loadLayerAnalysis();
}
AnalysisMetaAccess aMetaAccess = new SVMAnalysisMetaAccess(aUniverse, originalMetaAccess);
if (imageLayerLoader != null) {
imageLayerLoader.setMetaAccess(aMetaAccess);
}
HostedValuesProvider hostedValuesProvider = new SVMHostedValueProvider(aMetaAccess, aUniverse);
if (imageLayerLoader != null) {
imageLayerLoader.setHostedValuesProvider(hostedValuesProvider);
}
SubstratePlatformConfigurationProvider platformConfig = getPlatformConfig(aMetaAccess);
HostedProviders aProviders = createHostedProviders(target, aUniverse, originalProviders, platformConfig, aMetaAccess, classInitializationSupport);
aUniverse.hostVM().initializeProviders(aProviders);
ImageSingletons.add(SimulateClassInitializerSupport.class, ((SVMHost) aUniverse.hostVM()).createSimulateClassInitializerSupport(aMetaAccess));
bb = createBigBang(debug, options, aUniverse, aMetaAccess, aProviders, annotationSubstitutions);
aUniverse.setBigBang(bb);
/* Create the HeapScanner and install it into the universe. */
ImageHeap imageHeap = new ImageHeap();
ObjectScanningObserver aScanningObserver;
if (!UseExperimentalReachabilityAnalysis.getValue(options)) {
aScanningObserver = new AnalysisObjectScanningObserver(bb);
} else {
aScanningObserver = new ReachabilityObjectScanner(bb, aMetaAccess);