forked from graalvm/mx
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmx_jardistribution.py
executable file
·1451 lines (1270 loc) · 67.7 KB
/
mx_jardistribution.py
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) 2019, 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.
#
# 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.
#
# ----------------------------------------------------------------------------------------------------
#
r"""
mx is a command line tool for managing the development of Java code organized as suites of projects.
"""
from __future__ import print_function
import os
import shutil
import zipfile
import time
import re
import pickle
from os.path import join, exists, basename, dirname, isdir, islink
from argparse import ArgumentTypeError
from stat import S_IMODE
import mx
import mx_subst
# ProGuard version used for stripping/unstripping
_proguard_supported_jdk_version = 17
_proguard_libs = {
'BASE':'7_2_0_beta1',
'RETRACE':'7_2_0_beta1'
}
class JARDistribution(mx.Distribution, mx.ClasspathDependency):
"""
Represents a jar file built from the class files and resources defined by a set of
`JavaProject`s and Java libraries plus an optional zip containing the Java source files
corresponding to the class files.
:param Suite suite: the suite in which the distribution is defined
:param str name: the name of the distribution which must be unique across all suites
:param list stripConfigFileNames: names of stripping configurations that are located in `<mx_dir>/proguard/` and suffixed with `.proguard`
:param list stripMappingFileNames: names of stripping maps that are located in `<mx_dir>/proguard/` and suffixed with `.map`
:param str | None subDir: a path relative to `suite.dir` in which the IDE project configuration for this distribution is generated
:param str path: the path of the jar file created for this distribution. If this is not an absolute path,
it is interpreted to be relative to `suite.dir`.
:param str | None sourcesPath: the path of the zip file created for the source files corresponding to the class files of this distribution.
If this is not an absolute path, it is interpreted to be relative to `suite.dir`.
:param list deps: the `JavaProject` and `Library` dependencies that are the root sources for this distribution's jar
:param str | None mainClass: the class name representing application entry point for this distribution's executable jar. This
value (if not None) is written to the ``Main-Class`` header in the jar's manifest.
:param list excludedLibs: libraries whose contents should be excluded from this distribution's jar
:param list distDependencies: the `JARDistribution` dependencies that must be on the class path when this distribution
is on the class path (at compile or run time)
:param str | None javaCompliance:
:param bool platformDependent: specifies if the built artifact is platform dependent
:param str | None theLicense: license applicable when redistributing the built artifact of the distribution
:param str javadocType: specifies if the javadoc generated for this distribution should include implementation documentation
or only API documentation. Accepted values are "implementation" and "API".
:param bool allowsJavadocWarnings: specifies whether warnings are fatal when javadoc is generated
:param bool maven:
:param dict[str, str] | None manifestEntries: Entries for the `META-INF/MANIFEST.MF` file.
"""
def __init__(self, suite, name, subDir, path, sourcesPath, deps, mainClass, excludedLibs, distDependencies, javaCompliance, platformDependent, theLicense,
javadocType="implementation", allowsJavadocWarnings=False, maven=True, stripConfigFileNames=None,
stripMappingFileNames=None, manifestEntries=None, alwaysStrip=None, **kwArgs):
assert manifestEntries is None or isinstance(manifestEntries, dict)
mx.Distribution.__init__(self, suite, name, deps + distDependencies, excludedLibs, platformDependent, theLicense, **kwArgs)
mx.ClasspathDependency.__init__(self, **kwArgs)
self.subDir = subDir
if path:
path = mx_subst.path_substitutions.substitute(path)
self._path = mx._make_absolute(path.replace('/', os.sep), self.suite.dir)
else:
self._path = None
if sourcesPath == '<none>':
# `<none>` is used in the `suite.py` is used to specify that there should be no source zip.
self._sources_path = None
elif sourcesPath:
sources_path = mx_subst.path_substitutions.substitute(sourcesPath)
self._sources_path = mx._make_absolute(sources_path.replace('/', os.sep), self.suite.dir)
else:
self._sources_path = '<uninitialized>'
self.archiveparticipants = []
self.mainClass = mainClass
self.javaCompliance = mx.JavaCompliance(javaCompliance) if javaCompliance else None
self.definedAnnotationProcessors = []
self.javadocType = javadocType
self.allowsJavadocWarnings = allowsJavadocWarnings
self.maven = maven
self.manifestEntries = dict([]) if manifestEntries is None else manifestEntries
if stripConfigFileNames and alwaysStrip:
mx.abort('At most one of the "strip" and "alwaysStrip" properties can be used on a distribution', context=self)
if stripConfigFileNames:
self.stripConfig = [join(suite.mxDir, 'proguard', stripConfigFileName + '.proguard') for stripConfigFileName in stripConfigFileNames]
self.strip_mode = 'optional'
elif alwaysStrip:
self.stripConfig = [join(suite.mxDir, 'proguard', stripConfigFileName + '.proguard') for stripConfigFileName in alwaysStrip]
self.strip_mode = 'always'
else:
self.strip_mode = 'none'
self.stripConfig = None
if stripMappingFileNames:
self.stripMapping = [join(suite.mxDir, 'proguard', stripMappingFileName + '.map') for stripMappingFileName in stripMappingFileNames]
else:
self.stripMapping = []
if self.is_stripped() and mx.get_opts().proguard_cp is None:
# Make this a build dependency to avoid concurrency issues that can arise
# when the library is lazily resolved by build tasks (which can be running
# concurrently).
self.buildDependencies.extend((l.suite.name + ':' + l.name for l in mx.classpath_entries('PROGUARD_BASE_' + _proguard_libs['BASE'])))
def post_init(self):
# paths are initialized late to be able to figure out the max jdk
if self._path is None:
self._path = mx._make_absolute(self._default_path(), self.suite.dir)
if self._sources_path == '<uninitialized>':
# self._sources_path== '<uninitialized>' denotes that no sourcesPath was specified in `suite.py` and we should generate one.
self._sources_path = mx._make_absolute(self._default_source_path(), self.suite.dir)
assert self.path.endswith(self.localExtension())
def default_source_filename(self):
return mx._map_to_maven_dist_name(self.name) + '.src.zip'
def _default_source_path(self):
return join(dirname(self._default_path()), self.default_source_filename())
def _extra_artifact_discriminant(self):
if self.suite.isBinarySuite() or not self.suite.getMxCompatibility().jarsUseJDKDiscriminant():
return ''
compliance = self._compliance_for_build()
if compliance:
return 'jdk{}'.format(compliance)
return ''
def _compliance_for_build(self):
# This JAR will contain class files up to maxJavaCompliance
compliance = self.maxJavaCompliance()
if compliance is not None and compliance < '9' and mx.get_module_name(self):
# if it is modular, bump compliance to 9+ to get a module-info file
jdk9 = mx.get_jdk('9+', cancel='No module-info will be generated for modular JAR distributions')
if jdk9:
compliance = max(compliance, jdk9.javaCompliance)
return compliance
@property
def path(self):
if self.is_stripped():
return self._stripped_path()
else:
return self.original_path()
def _stripped_path(self):
"""
Gets the path to the ProGuard stripped version of the jar. Due to a limitation in ProGuard
handling of multi-release jars (https://sourceforge.net/p/proguard/bugs/671), the stripped
jar is specific to the default JDK (i.e. defined by JAVA_HOME/--java-home).
"""
assert self._path is not None, self.name
res = getattr(self, '.stripped_path', None)
if res is None:
jdk = mx.get_jdk(tag='default')
res = join(mx.ensure_dir_exists(join(dirname(self._path), 'stripped', str(jdk.javaCompliance))), basename(self._path))
setattr(self, '.stripped_path', res)
return res
def original_path(self):
assert self._path is not None, self.name
return self._path
@property
def sourcesPath(self):
assert self._sources_path != '<uninitialized>'
return self._sources_path
def maxJavaCompliance(self):
""":rtype : JavaCompliance"""
assert not self.suite.isBinarySuite()
if not hasattr(self, '.maxJavaCompliance'):
javaCompliances = [p.javaCompliance for p in self.archived_deps() if p.isJavaProject()]
if self.javaCompliance is not None:
javaCompliances.append(self.javaCompliance)
if len(javaCompliances) > 0:
setattr(self, '.maxJavaCompliance', max(javaCompliances))
else:
setattr(self, '.maxJavaCompliance', None)
return getattr(self, '.maxJavaCompliance')
def paths_to_clean(self):
paths = [
self.original_path(),
self.sourcesPath,
self.original_path() + _staging_dir_suffix,
self.sourcesPath + _staging_dir_suffix,
self._stripped_path(),
self.strip_mapping_file()
]
jdk = mx.get_jdk(tag='default')
if jdk.javaCompliance >= '9':
info = mx.get_java_module_info(self)
if info:
_, pickle_path, _ = info # pylint: disable=unpacking-non-sequence
paths.append(pickle_path)
return paths
def is_stripped(self):
return self.stripConfig is not None and (mx._opts.strip_jars or self.strip_mode == 'always')
def set_archiveparticipant(self, archiveparticipant):
"""
Adds an object that participates in the `make_archive` method of this distribution.
:param archiveparticipant: an object for which the following methods, if defined, will be called by `make_archive`:
__opened__(arc, srcArc, services)
Called when archiving starts. The `arc` and `srcArc` values are objects that have a `path` field
which is the path of the binary and source jars respectively for the distribution. The `services`
dict is for collating the files that will be written to ``META-INF/services`` in the binary jar.
It is a map from service names to a list of providers for the named service. If services should
be versioned, an integer can be used as a key instead and the value is a map from service names to a list
of providers for the version denoted by the integer.
__process__(arcname, contents_supplier, is_source)
Notifies of an entry destined for the binary (`is_source` is False) or source archive (`is_source` is True).
Returns True if this object consumes the contents supplied by `contents_supplier`,
False if the caller should add the contents to the relevant archive.
# Deprecated: Define __process__ instead
__add__(arcname, contents)
Notifies of an entry that is about to be added to the binary archive.
Returns True if this object consumes `contents`,
False if the caller should add `contents` to the binary archive.
# Deprecated: Define __process__ instead
__addsrc__(arcname, contents)
Notifies of an entry that is about to be added to the source archive.
Returns True if this object consumes `contents`,
False if the caller should add `contents` to the source archive.
__closing__()
Called just before the `services` are written to the binary archive and both archives are finalized.
If the archive participant wants to add extra entries to the archive, it returns a 2-tuple
with each value being a dict of (arcname, contents) describing the extra entries.
"""
ap_type = archiveparticipant.__class__.__name__
if ap_type == 'FastRArchiveParticipant':
# This archive participant deletes directories that are assumed
# to have been already added to fastr-release.jar. It is removed
# in FastR by GR-30568 but this workaround allows mx to keep working
# with older versions.
mx.warn('Ignoring registration of {} object for {}'.format(ap_type, self))
return
if archiveparticipant not in self.archiveparticipants:
if not hasattr(archiveparticipant, '__opened__'):
mx.abort(str(archiveparticipant) + ' must define __opened__')
_patch_archiveparticipant(archiveparticipant.__class__)
self.archiveparticipants.append(archiveparticipant)
else:
mx.warn('registering archive participant ' + str(archiveparticipant) + ' for ' + str(self) + ' twice')
def origin(self):
return mx.Dependency.origin(self)
def classpath_repr(self, resolve=True):
if resolve and not exists(self.path):
if exists(self.original_path()):
jdk = mx.get_jdk(tag='default')
msg = "The Java {} stripped jar for {} does not exist: {}{}".format(jdk.javaCompliance, self, self.path, os.linesep)
msg += "This might be solved by running: mx --java-home={} --strip build --dependencies={}".format(jdk.home, self)
mx.abort(msg)
msg = "The jar for {} does not exist: {}{}".format(self, self.path, os.linesep)
msg += "This might be solved by running: mx build --dependencies={}".format(self)
mx.abort(msg)
return self.path
def get_ide_project_dir(self):
"""
Gets the directory in which the IDE project configuration for this distribution is generated.
"""
if self.subDir:
return join(self.suite.dir, self.subDir, self.name + '.dist')
else:
return join(self.suite.dir, self.name + '.dist')
def make_archive(self, javac_daemon=None):
"""
Creates the jar file(s) defined by this JARDistribution.
"""
if isinstance(self.suite, mx.BinarySuite):
return
# are sources combined into main archive?
unified = self.original_path() == self.sourcesPath
exploded = self._is_exploded()
bin_archive = _Archive(self, self.original_path(), exploded)
src_archive = _Archive(self, self.sourcesPath, exploded) if not unified else bin_archive
bin_archive.clean()
src_archive.clean()
stager = _ArchiveStager(bin_archive, src_archive, exploded)
# GR-31142
latest_bin_archive = join(self.suite.get_output_root(False, False), "dists", os.path.basename(bin_archive.path))
_stage_file_impl(bin_archive.path, latest_bin_archive)
self.notify_updated()
compliance = self._compliance_for_build()
if compliance is not None and compliance >= '9':
jdk = mx.get_jdk(compliance)
jmd = mx.make_java_module(self, jdk, stager.bin_archive, javac_daemon=javac_daemon)
if jmd:
setattr(self, '.javaModule', jmd)
dependency_file = self._jmod_build_jdk_dependency_file()
with mx.open(dependency_file, 'w') as fp:
fp.write(jdk.home)
if self.is_stripped():
self.strip_jar()
# See https://docs.oracle.com/en/java/javase/16/docs/api/java.instrument/java/lang/instrument/package-summary.html
_javaagent_manifest_attributes = ('Premain-Class', 'Agent-Class')
def _can_be_exploded(self):
"""
Determines if `self` can have its artifact be a directory instead of a jar.
This is true if `self` does not:
- Define an annotation processor. Eclipse only supports annotation processors packaged as jars.
- Define an Java agent since Java agents can only be deployed as jars.
"""
if 'Premain-Class' in self.manifestEntries or 'Agent-Class' in self.manifestEntries or self.definedAnnotationProcessors:
return False
return True
def _is_exploded(self):
"""
Determines if the result of `self.make_archive` is (or would be) a directory instead of a jar.
"""
return self._can_be_exploded() and _use_exploded_build()
_strip_map_file_suffix = '.map'
_strip_cfg_deps_file_suffix = '.conf.d'
def strip_mapping_file(self):
return self._stripped_path() + JARDistribution._strip_map_file_suffix
def strip_config_dependency_file(self):
return self._stripped_path() + JARDistribution._strip_cfg_deps_file_suffix
def strip_jar(self):
assert self.is_stripped()
jdk = mx.get_jdk(tag='default')
if jdk.javaCompliance.value > _proguard_supported_jdk_version and mx.get_opts().proguard_cp is None:
mx.abort('Cannot strip {} - ProGuard does not yet support JDK {}'.format(self, jdk.javaCompliance))
mx.logv('Stripping {}...'.format(self.name))
jdk9_or_later = jdk.javaCompliance >= '9'
# add config files from projects
assert all((os.path.isabs(f) for f in self.stripConfig))
# add mapping files
assert all((os.path.isabs(f) for f in self.stripMapping))
proguard = ['-cp', _get_proguard_cp(), 'proguard.ProGuard']
prefix = [
'-dontusemixedcaseclassnames', # https://sourceforge.net/p/proguard/bugs/762/
'-adaptclassstrings',
'-adaptresourcefilecontents META-INF/services/*',
'-adaptresourcefilenames META-INF/services/*',
'-renamesourcefileattribute stripped',
'-keepattributes Exceptions,InnerClasses,Signature,Deprecated,SourceFile,LineNumberTable,RuntimeVisible*Annotations,EnclosingMethod,AnnotationDefault',
'-keepclassmembernames class ** { static boolean $assertionsDisabled; }',
# options for incremental stripping
'-dontoptimize -dontshrink -useuniqueclassmembernames']
# add configs
for file_name in self.stripConfig:
with mx.open(file_name, 'r') as fp:
prefix.extend((l.strip() for l in fp.readlines()))
def _create_derived_file(base_file, suffix, lines):
derived_file = mx._derived_path(base_file, suffix)
with mx.open(derived_file, 'w') as fp:
for line in lines:
print(line, file=fp)
return derived_file
# add mappings of all stripped dependencies (must be one file)
input_maps = self.stripMapping + [d.strip_mapping_file() for d in mx.classpath_entries(self, includeSelf=False) if d.isJARDistribution() and d.is_stripped()]
if input_maps:
input_maps_file = mx._derived_path(self.path, '.input_maps')
with mx.open(input_maps_file, 'w') as fp_out:
for file_name in input_maps:
with mx.open(file_name, 'r') as fp_in:
fp_out.write(fp_in.read())
prefix += ['-applymapping ' + input_maps_file]
# Create flattened input jar
flattened_jar = mx._derived_path(self.path, '', prefix='flattened_')
flattened_entries = {}
with zipfile.ZipFile(self.original_path(), 'r') as in_zf:
compression = in_zf.compression
versions = {}
for info in in_zf.infolist():
if not info.filename.startswith('META-INF/versions/'):
flattened_entries[info.filename] = (info, in_zf.read(info))
for info in in_zf.infolist():
if info.filename.startswith('META-INF/versions/'):
if jdk9_or_later:
import mx_javamodules
m = mx_javamodules._versioned_re.match(info.filename)
if m:
version = int(m.group(1))
unversioned_name = m.group(2)
if version <= jdk.javaCompliance.value:
contents = in_zf.read(info)
info.filename = unversioned_name
versions.setdefault(version, {})[unversioned_name] = (info, contents)
else:
# Omit versioned resource whose version is too high
pass
else:
# Omit versioned resources when flattening for JDK 8
pass
elif info.filename.startswith('META-INF/services/') and jdk9_or_later:
# Omit JDK 8 style service descriptors when flattening for 9+
pass
else:
flattened_entries[info.filename] = (info, in_zf.read(info))
if versions:
for version, entries in sorted(versions.items()):
flattened_entries.update(entries)
with mx.SafeFileCreation(flattened_jar) as sfc:
with zipfile.ZipFile(sfc.tmpPath, 'w', compression) as out_zf:
for name, ic in sorted(flattened_entries.items()):
info, contents = ic
assert info.filename == name
out_zf.writestr(info, contents)
if jdk9_or_later:
prefix += [
'-keepattributes Module*',
# https://sourceforge.net/p/proguard/bugs/704/#d392
'-keep class module-info',
# Must keep package names due to https://sourceforge.net/p/proguard/bugs/763/
'-keeppackagenames **'
]
if mx.get_opts().very_verbose:
prefix += ['-verbose']
elif not mx.get_opts().verbose:
prefix += ['-dontnote **']
# https://sourceforge.net/p/proguard/bugs/671/#56b4
jar_filter = '(!META-INF/versions/**,!module-info.class)'
if not jdk9_or_later:
libraryjars = mx.classpath(self, includeSelf=False, includeBootClasspath=True, jdk=jdk, unique=True, ignoreStripped=True).split(os.pathsep)
include_file = _create_derived_file(self.path, '.proguard', prefix + [
'-injars ' + flattened_jar,
'-outjars ' + self.path,
'-libraryjars ' + os.pathsep.join((e + jar_filter for e in libraryjars)),
'-printmapping ' + self.strip_mapping_file(),
])
strip_command = proguard + ['-include', include_file]
mx.run_java(strip_command, jdk=jdk)
with mx.open(self.strip_config_dependency_file(), 'w') as f:
f.writelines((l + os.linesep for l in self.stripConfig))
else:
cp_entries = mx.classpath_entries(self, includeSelf=False)
self_jmd = mx.as_java_module(self, jdk) if mx.get_java_module_info(self) else None
dep_modules = frozenset(e for e in cp_entries if e.isJARDistribution() and mx.get_java_module_info(e))
dep_module_names = frozenset((mx.get_java_module_info(e)[0] for e in dep_modules))
dep_jmds = frozenset((mx.as_java_module(e, jdk) for e in cp_entries if e.isJARDistribution() and mx.get_java_module_info(e)))
dep_jars = mx.classpath(self, includeSelf=False, includeBootClasspath=False, jdk=jdk, unique=True, ignoreStripped=True).split(os.pathsep)
# Add jmods from the JDK except those overridden by dependencies
jdk_jmods = [m.get_jmod_path(respect_stripping=False) for m in jdk.get_modules() if m.name not in dep_module_names]
# Make stripped jar
include_file = _create_derived_file(self.path, '.proguard', prefix + [
'-injars ' + flattened_jar,
'-outjars ' + self.path,
'-libraryjars ' + os.pathsep.join((e + jar_filter for e in dep_jars + jdk_jmods)),
'-printmapping ' + self.path + JARDistribution._strip_map_file_suffix,
])
strip_commands = [proguard + ['-include', include_file]]
if self_jmd:
# Make stripped jmod
stripped_jmod = self_jmd.get_jmod_path(respect_stripping=True)
dep_jmods = [jmd.get_jmod_path(respect_stripping=False) for jmd in dep_jmds]
dep_lib_modules = [module_lib.lib.get_path(resolve=True) for module_lib in self_jmd.modulepath if module_lib.lib]
include_file = _create_derived_file(stripped_jmod, '.proguard', prefix + [
'-injars ' + self_jmd.get_jmod_path(respect_stripping=False),
'-outjars ' + stripped_jmod,
'-libraryjars ' + os.pathsep.join((e + jar_filter for e in dep_lib_modules + dep_jmods + jdk_jmods)),
'-printmapping ' + stripped_jmod + JARDistribution._strip_map_file_suffix,
])
strip_commands.append(proguard + ['-include', include_file])
for command in strip_commands:
mx.run_java(command, jdk=jdk)
with mx.open(self.strip_config_dependency_file(), 'w') as f:
f.writelines((l + os.linesep for l in self.stripConfig))
def remoteName(self, platform=None):
base_name = super(JARDistribution, self).remoteName(platform=platform)
if self.is_stripped():
return base_name + "_stripped"
else:
return base_name
def getBuildTask(self, args):
return mx.JARArchiveTask(args, self)
def exists(self):
return exists(self.path) and not self.sourcesPath or exists(self.sourcesPath) #pylint: disable=consider-using-ternary
def remoteExtension(self):
return 'jar'
def localExtension(self):
return 'jar'
def getArchivableResults(self, use_relpath=True, single=False):
yield self.path, self.default_filename()
if not single:
if self.sourcesPath:
yield self.sourcesPath, self.default_source_filename()
if self.is_stripped():
yield self.strip_mapping_file(), self.default_filename() + JARDistribution._strip_map_file_suffix
def _jmod_build_jdk_dependency_file(self):
"""
Gets the path to the file recording the JAVA_HOME of the JDK last used to
build the modular jar for this distribution.
"""
return self.original_path() + '.jdk'
def needsUpdate(self, newestInput):
res = mx._needsUpdate(newestInput, self.path)
if res:
return res
if self.sourcesPath:
res = mx._needsUpdate(newestInput, self.sourcesPath)
if res:
return res
if self.suite.isBinarySuite():
return None
if exists(self.path):
# Re-build if switching to/from exploded builds
if _use_exploded_build() != isdir(self.path):
if self._can_be_exploded():
return 'MX_BUILD_EXPLODED value has changed'
compliance = self._compliance_for_build()
if compliance is not None and compliance >= '9':
info = mx.get_java_module_info(self)
if info:
_, pickle_path, _ = info # pylint: disable=unpacking-non-sequence
res = mx._needsUpdate(newestInput, pickle_path)
if res:
return res
res = mx._needsUpdate(self.original_path(), pickle_path)
if res:
return res
# Rebuild the jmod file if different JDK used previously
jdk = mx.get_jdk(compliance)
dependency_file = self._jmod_build_jdk_dependency_file()
if exists(dependency_file):
with mx.open(dependency_file) as fp:
last_build_jdk = fp.read()
if last_build_jdk != jdk.home:
return 'build JDK changed from {} to {}'.format(last_build_jdk, jdk.home)
try:
with open(pickle_path, 'rb') as fp:
pickle.load(fp)
except ValueError as e:
return 'Bad or incompatible module pickle: {}'.format(e)
if self.is_stripped():
previous_strip_configs = []
dependency_file = self.strip_config_dependency_file()
if exists(dependency_file):
with mx.open(dependency_file) as f:
previous_strip_configs = (l.rstrip('\r\n') for l in f.readlines())
if set(previous_strip_configs) != set(self.stripConfig):
return 'strip config files changed'
for f in self.stripConfig:
ts = mx.TimeStampFile(f)
if ts.isNewerThan(self.path):
return '{} is newer than {}'.format(ts, self.path)
return None
def get_declaring_module_name(self):
return mx.get_module_name(self)
def _get_proguard_cp():
"""
Gets the class path required to run ProGuard (either the main app or the retrace app).
"""
proguard_cp = mx.get_opts().proguard_cp
if not proguard_cp:
proguard_cp = mx.classpath(['PROGUARD_' + name + '_' + version for name, version in _proguard_libs.items()])
return proguard_cp
class _StagingGuard:
"""
A context manager implementing a predicate for whether a file should be staged.
The staging should only be performed if the context manager does not return None when entered:
```
with _StagingGuard(entry) as guard:
if guard:
<stage_file>
```
"""
def __init__(self, entry):
self.entry = entry
self.entries = entry.archive.entries
self._can_write = False
def __enter__(self):
arcname = self.entry.name
origin = self.entry.origin
if os.path.basename(arcname).startswith('.'):
mx.logv('Excluding dotfile: ' + origin)
return None
elif arcname == "META-INF/MANIFEST.MF":
if self.entry.origin_is_archive:
# Do not inherit the manifest from other jars
mx.logv('Excluding META-INF/MANIFEST.MF from ' + origin)
return None
existing_entry = self.entries.get(arcname, None)
if existing_entry and existing_entry.origin != origin:
entry = existing_entry.resolve_origin_conflict(self.entry)
if entry is None:
return
if entry is existing_entry:
mx.warn('{}: skipping update of {}\n using: {}\n ignoring: {}'.format(self.entry.archive.path, arcname, existing_entry.origin, origin))
return None
else:
mx.logv('{}: replacing contents of {}\n replacing: {}\n with: {}'.format(self.entry.archive.path, arcname, existing_entry.origin, origin))
self._can_write = True
return self
def __exit__(self, exc_type, exc_value, traceback):
if self._can_write:
if exists(self.entry.staged):
self.entries[self.entry.name] = self.entry
class _ArchiveStager(object):
"""
Object used to create and populate the staging directory for a distribution's archive(s).
"""
# Pattern for a versioned META-INF directory
versioned_meta_inf_re = re.compile(r'META-INF/versions/([1-9][0-9]*)/META-INF/')
def __init__(self, bin_archive, src_archive, exploded):
"""
:param JARDistribution dist: the distribution whose archive contents are being staged
:param _Archive bin_archive: the distribution's binary archive
:param _Archive src_archive: the distribution's source archive
"""
self.dist = bin_archive.dist
self.bin_archive = bin_archive
self.src_archive = src_archive
self.exploded = exploded
self.services = {}
self.manifest = self.dist.manifestEntries.copy()
self.snippetsPattern = None
if hasattr(self.dist.suite, 'snippetsPattern'):
self.snippetsPattern = re.compile(self.dist.suite.snippetsPattern)
# Map from overlays to the projects that define them
self.overlays = {}
self.stage_archive()
def stage_archive(self):
"""
Creates and populates the archive staging directories.
For efficiency, symbolic links are used where possible.
"""
dist = self.dist
for a in dist.archiveparticipants:
a.__opened__(self.bin_archive, self.src_archive, self.services)
# Overlay projects whose JDK version is less than 9 must be processed before the overlayed projects
# as the overlay classes must be added to the jar instead of the overlayed classes. Overlays for
# JDK 9 or later use the multi-release jar layout.
head = [d for d in dist.archived_deps() if d.isJavaProject() and (self.exploded or d.javaCompliance.value < 9) and hasattr(d, 'overlayTarget')]
tail = [d for d in dist.archived_deps() if d not in head]
mainClass = dist.mainClass
if mainClass:
if 'Main-Class' in self.manifest:
mx.abort("Main-Class is defined both as the 'mainClass': '" + mainClass + "' argument and in 'manifestEntries' as "
+ self.manifest['Main-Class'] + " of the " + dist.name + " distribution. There should be only one definition.")
self.manifest['Main-Class'] = mainClass
for dep in head + tail:
self.stage_dep(dep)
for a in dist.archiveparticipants:
self.close_archiveparticipant(a)
_accumulate_services(self.services)
for service_or_version, providers in self.services.items():
if isinstance(service_or_version, int):
services_version = service_or_version
for service, providers_ in sorted(providers.items()):
self.add_service_providers(service, providers_, 'META-INF/_versions/' + str(services_version) + '/')
else:
self.add_service_providers(service_or_version, providers)
self.bin_archive.finalize_archive_or_directory(self.manifest, zipfile.ZIP_STORED)
if self.bin_archive is not self.src_archive:
self.src_archive.finalize_archive_or_directory(None, zipfile.ZIP_DEFLATED)
def close_archiveparticipant(self, a):
"""
Closes the archive participant `a` just prior to finalizing the archive (see `_Archive.finalize_archive_or_directory`).
"""
closing = getattr(a, '__closing__', None)
if closing is not None:
extra = a.__closing__()
if extra:
try:
bin_archive_extra, src_archive_extra = extra
except (TypeError, ValueError) as e:
mx.abort('Value returned by __closing__ ({}) must be None or a 2-tuple: {}'.format(_source_pos(closing), e))
def stage_extra(extra, archive):
if extra is None:
return
if not isinstance(extra, dict):
index = 0 if extra is bin_archive_extra else 1
mx.abort('Type of value {} in tuple returned by __closing__ ({}) must be None or a dict, not {}'.format(index, _source_pos(closing), extra.__class__.__name__))
for arcname, content in extra.items():
self.add_contents(archive, arcname, content)
stage_extra(bin_archive_extra, self.bin_archive)
stage_extra(src_archive_extra, self.src_archive)
def add_service_providers(self, service, providers, archive_prefix=''):
arcname = archive_prefix + 'META-INF/services/' + service
# Convert providers to a set before printing to remove duplicates
contents = '\n'.join(sorted(frozenset(providers))) + '\n'
self.add_contents(self.bin_archive, arcname, contents)
def add_contents(self, archive, arcname, contents):
"""
Creates a file at `arcname` under `archive.staging_dir` with the data in `contents`
and adds an entry to `archive.entries`.
"""
origin = _FileContentsSupplier(join(archive.staging_dir, arcname))
entry = _ArchiveEntry(None, arcname, archive, origin)
staged = entry.staged
mx.ensure_dir_exists(dirname(staged))
if callable(contents):
contents = contents()
with open(staged, 'w' if isinstance(contents, str) else 'wb') as fp:
assert arcname not in archive.entries, (arcname, archive.path)
fp.write(contents)
archive.entries[arcname] = entry
def add_jar(self, dep, jar_path, is_sources_jar=False):
"""
Adds the contents of `jar_path` to the relevant staging directory.
:param Dependency dep: the Dependency owning the jar file
:param str jar_path: path to the jar file to be extracted
:param is_sources_jar: False if the contents are to be extracted to the primary staging directory,
True if they should be extracted to the sources staging directory
"""
jar_timestamp = mx.TimeStampFile(jar_path)
archive = self.src_archive if is_sources_jar else self.bin_archive
with zipfile.ZipFile(jar_path, 'r') as zf:
for arcname in zf.namelist():
if arcname.endswith('/'):
if not self.exploded:
# Use a self reference for a directory that needs an explicit entry in the archive
archive.entries[arcname] = arcname
continue
if not is_sources_jar and arcname == 'module-info.class':
mx.logv(jar_path + ' contains ' + arcname + '. It will not be included in ' + self.bin_archive.path)
elif not is_sources_jar and arcname.startswith('META-INF/services/') and not arcname == 'META-INF/services/':
service = arcname[len('META-INF/services/'):]
assert '/' not in service
self.services.setdefault(service, []).extend(mx._decode(zf.read(arcname)).splitlines())
else:
entry = _ArchiveEntry(dep, arcname, archive, jar_path + '!' + arcname)
with _StagingGuard(entry) as guard:
if guard:
staged = entry.staged
if not exists(staged) or jar_timestamp.isNewerThan(staged):
zf.extract(arcname, entry.archive.staging_dir)
contents = _FileContentsSupplier(staged)
if not _process_archiveparticipants(self.dist, entry.archive, arcname, contents.get, staged, is_source=is_sources_jar):
if self.versioned_meta_inf_re.match(arcname):
mx.warn("META-INF resources can not be versioned ({} from {}). The resulting JAR will be invalid.".format(arcname, jar_path))
def add_file(self, dep, base_dir, relpath, archivePrefix, arcnameCheck=None, includeServices=False):
"""
Adds the contents of the file `base_dir`/`relpath` to `self.bin_archive.staging_dir`
under the path formed by concatenating `archivePrefix` with `relpath`.
:param Dependency dep: the Dependency owning the file
"""
filepath = join(base_dir, relpath)
arcname = join(archivePrefix, relpath).replace(os.sep, '/')
assert arcname[-1] != '/'
if arcnameCheck is not None and not arcnameCheck(arcname):
return
if relpath.startswith(join('META-INF', 'services')):
if includeServices:
service = basename(relpath)
assert dirname(relpath) == join('META-INF', 'services')
m = self.versioned_meta_inf_re.match(arcname)
if m:
service_version = int(m.group(1))
services_dict = self.services.setdefault(service_version, {})
else:
services_dict = self.services
with mx.open(filepath, 'r') as fp:
services_dict.setdefault(service, []).extend([provider.strip() for provider in fp.readlines()])
else:
if self.snippetsPattern and self.snippetsPattern.match(relpath):
return
contents = _FileContentsSupplier(filepath)
entry = _ArchiveEntry(dep, arcname, self.bin_archive, filepath)
with _StagingGuard(entry) as guard:
if guard:
staged = entry.staged
if not _process_archiveparticipants(self.dist, self.bin_archive, arcname, contents.get, staged):
self.stage_file(filepath, staged)
if self.versioned_meta_inf_re.match(arcname):
mx.warn("META-INF resources can not be versioned ({}). The resulting JAR will be invalid.".format(filepath))
def add_java_sources(self, dep, srcDir, archivePrefix='', arcnameCheck=None):
"""
Adds the contents of the Java source files under `srcDir` to the sources archive staging directory.
:param Dependency dep: the Dependency owning the Java sources
"""
for root, _, files in os.walk(srcDir):
relpath = root[len(srcDir) + 1:]
for f in files:
if f.endswith('.java'):
arcname = join(archivePrefix, relpath, f).replace(os.sep, '/')
if arcnameCheck is None or arcnameCheck(arcname):
contents = _FileContentsSupplier(join(root, f))
entry = _ArchiveEntry(dep, arcname, self.src_archive, contents.path)
with _StagingGuard(entry) as guard:
staged = entry.staged
if guard:
if not _process_archiveparticipants(self.dist, self.src_archive, arcname, contents.get, staged, is_source=True):
self.stage_file(contents.path, staged)
def stage_file(self, src, dst):
_stage_file_impl(src, dst)
def stage_dep(self, dep):
"""
Copies or symlinks the content from `dep` into the appropriate staging directories.
"""
dist = self.dist
original_path = dist.original_path()
if hasattr(dep, "doNotArchive") and dep.doNotArchive:
mx.logv('[' + original_path + ': ignoring project ' + dep.name + ']')
return
if dist.theLicense is not None and set(dist.theLicense or []) < set(dep.theLicense or []):
if dep.suite.getMxCompatibility().supportsLicenses() and dist.suite.getMxCompatibility().supportsLicenses():
report = mx.abort
else:
report = mx.warn
depLicense = [l.name for l in dep.theLicense] if dep.theLicense else ['??']
selfLicense = [l.name for l in dist.theLicense] if dist.theLicense else ['??']
report('Incompatible licenses: distribution {} ({}) can not contain {} ({})'.format(dist, ', '.join(selfLicense), dep, ', '.join(depLicense)))
if dep.isLibrary() or dep.isJARDistribution():
if dep.isLibrary():
l = dep
# optional libraries and their dependents should already have been removed
assert not l.optional or l.is_available()
# merge library jar into distribution jar
mx.logv('[' + original_path + ': adding library ' + l.name + ']')
jarPath = l.get_path(resolve=True)
jarSourcePath = l.get_source_path(resolve=True)
elif dep.isJARDistribution():
mx.logv('[' + original_path + ': adding distribution ' + dep.name + ']')
jarPath = dep.path
jarSourcePath = dep.sourcesPath
else:
raise mx.abort('Dependency not supported: {} ({})'.format(dep.name, dep.__class__.__name__))
if jarPath:
self.add_jar(dep, jarPath)
if jarSourcePath:
self.add_jar(dep, jarSourcePath, True)
elif dep.isMavenProject():
mx.logv('[' + original_path + ': adding jar from Maven project ' + dep.name + ']')
self.add_jar(dep, dep.classpath_repr())
for srcDir in dep.source_dirs():
self.add_java_sources(dep, srcDir)
elif dep.isJavaProject():
p = dep
javaCompliance = dist.maxJavaCompliance()
if javaCompliance:
if p.javaCompliance > javaCompliance:
mx.abort("Compliance level doesn't match: Distribution {0} requires {1}, but {2} is {3}.".format(dist, javaCompliance, p, p.javaCompliance), context=dist)
mx.logv('[' + original_path + ': adding project ' + p.name + ']')
outputDir = p.output_dir()
archivePrefix = p.archive_prefix() if hasattr(p, 'archive_prefix') else ''
mrjVersion = getattr(p, 'multiReleaseJarVersion', None)
is_overlay = False
if mrjVersion is not None:
if p.javaCompliance.value < 9:
mx.abort('Project with "multiReleaseJarVersion" attribute must have javaCompliance >= 9', context=p)
if archivePrefix:
mx.abort("Project cannot have a 'multiReleaseJarVersion' attribute if it has an 'archivePrefix' attribute", context=p)
if self.exploded:
is_overlay = True
else:
try:
mrjVersion = mx._parse_multireleasejar_version(mrjVersion)
except ArgumentTypeError as e:
mx.abort(str(e), context=p)
archivePrefix = 'META-INF/versions/{}/'.format(mrjVersion)
self.manifest['Multi-Release'] = 'true'
elif hasattr(p, 'overlayTarget'):
if p.javaCompliance.value > 8:
if p.suite.getMxCompatibility().automatic_overlay_distribution_deps:
mx.abort('Project with an "overlayTarget" attribute and javaCompliance >= 9 must also have a "multiReleaseJarVersion" attribute', context=p)
mx.abort('Project with an "overlayTarget" attribute must have javaCompliance < 9', context=p)
is_overlay = True
if archivePrefix:
mx.abort("Project cannot have a 'overlayTarget' attribute if it has an 'archivePrefix' attribute", context=p)
def overlay_check(arcname):
if is_overlay:
current_overlayer = self.overlays.get(arcname)
if current_overlayer:
if mrjVersion is None and getattr(p, 'multiReleaseJarVersion', current_overlayer) is None:
mx.abort('Overlay for {} is defined by more than one project: {} and {}'.format(arcname, current_overlayer, p))
else:
if current_overlayer.javaCompliance.highest_specified_value() > p.javaCompliance.highest_specified_value():
# Overlay from project with highest javaCompliance wins
return False
self.overlays[arcname] = p
return True
else:
return arcname not in self.overlays
def add_classes(archivePrefix, includeServices):
for root, _, files in os.walk(outputDir):
reldir = root[len(outputDir) + 1:]