-
Notifications
You must be signed in to change notification settings - Fork 1.7k
/
mx_substratevm.py
2527 lines (2166 loc) · 109 KB
/
mx_substratevm.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) 2018, 2024, 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.
#
import os
import pathlib
import re
import shutil
import tempfile
import textwrap
from glob import glob
from contextlib import contextmanager
from itertools import islice
from os.path import join, exists, dirname
import shlex
from argparse import ArgumentParser
import fnmatch
import collections
from io import StringIO
import mx
import mx_compiler
import mx_gate
import mx_unittest
import mx_sdk_vm
import mx_sdk_vm_impl
import mx_javamodules
import mx_subst
import mx_util
import mx_substratevm_benchmark # pylint: disable=unused-import
import mx_substratevm_namespace # pylint: disable=unused-import
from mx_compiler import GraalArchiveParticipant
from mx_gate import Task
from mx_sdk_vm_impl import svm_experimental_options
from mx_unittest import _run_tests, _VMLauncher
import sys
suite = mx.suite('substratevm')
svmSuites = [suite]
def get_jdk():
return mx.get_jdk(tag='default')
def graal_compiler_flags():
version_tag = get_jdk().javaCompliance.value
compiler_flags = mx.dependency('substratevm:svm-compiler-flags-builder').compute_graal_compiler_flags_map()
if str(version_tag) not in compiler_flags:
missing_flags_message = 'Missing graal-compiler-flags for {0}.\n Did you forget to run "mx build"?'
mx.abort(missing_flags_message.format(version_tag))
def adjusted_exports(line):
"""
Turns e.g.
--add-exports=jdk.internal.vm.ci/jdk.vm.ci.code.stack=jdk.graal.compiler,org.graalvm.nativeimage.builder
into:
--add-exports=jdk.internal.vm.ci/jdk.vm.ci.code.stack=ALL-UNNAMED
"""
if line.startswith('--add-exports='):
before, sep, _ = line.rpartition('=')
return before + sep + 'ALL-UNNAMED'
else:
return line
return [adjusted_exports(line) for line in compiler_flags[str(version_tag)]]
def classpath(args):
if not args:
return [] # safeguard against mx.classpath(None) behaviour
transitive_excludes = set()
def include_in_excludes(dep, dep_edge):
# We need to exclude on the granularity of mx.Project entries so that classpath()
# can also give us a builder-free classpath if args contains mx.Project entries.
if dep.isJavaProject() or dep.isDistribution():
transitive_excludes.add(dep)
implicit_excludes_deps = [mx.dependency(entry) for entry in mx_sdk_vm_impl.NativePropertiesBuildTask.implicit_excludes]
mx.walk_deps(implicit_excludes_deps, visit=include_in_excludes)
cpEntries = mx.classpath_entries(names=args, includeSelf=True, preferProjects=False, excludes=transitive_excludes)
return mx._entries_to_classpath(cpEntries=cpEntries, resolve=True, includeBootClasspath=False, jdk=mx_compiler.jdk, unique=False, ignoreStripped=False)
def platform_name():
return mx.get_os() + "-" + mx.get_arch()
def svm_suite():
return svmSuites[-1]
def svmbuild_dir(suite=None):
if not suite:
suite = svm_suite()
return join(suite.dir, 'svmbuild')
def is_musl_supported():
jdk = get_jdk()
if mx.is_linux() and mx.get_arch() == "amd64" and jdk.javaCompliance == '11':
musl_library_path = join(jdk.home, 'lib', 'static', 'linux-amd64', 'musl')
return exists(musl_library_path)
return False
def build_native_image_agent(native_image):
agentfile = mx_subst.path_substitutions.substitute('<lib:native-image-agent>')
agentname = join(svmbuild_dir(), agentfile.rsplit('.', 1)[0]) # remove platform-specific file extension
native_image(['--macro:native-image-agent-library', '-o', agentname])
return svmbuild_dir() + '/' + agentfile
class GraalVMConfig(collections.namedtuple('GraalVMConfig', 'primary_suite_dir, dynamicimports, exclude_components, native_images')):
@classmethod
def build(cls, primary_suite_dir=None, dynamicimports=None,
exclude_components=None, native_images=None):
dynamicimports = list(dynamicimports or [])
for x, _ in mx.get_dynamic_imports():
if x not in dynamicimports:
dynamicimports.append(x)
new_config = cls(primary_suite_dir, tuple(dynamicimports),
tuple(exclude_components or ()), tuple(native_images or ()))
return new_config
def mx_args(self):
args = ['--disable-installables=true']
if self.dynamicimports:
args += ['--dynamicimports', ','.join(self.dynamicimports)]
if self.exclude_components:
args += ['--exclude-components=' + ','.join(self.exclude_components)]
if self.native_images:
args += ['--native-images=' + ','.join(self.native_images)]
else:
args += ['--native-images=false']
return args
def _run_graalvm_cmd(cmd_args, config, nonZeroIsFatal=True, out=None, err=None, timeout=None, env=None, quiet=False):
if config:
config_args = config.mx_args()
primary_suite_dir = config.primary_suite_dir
else:
config_args = []
if not mx_sdk_vm_impl._jlink_libraries():
config_args += ['--no-jlinking']
native_images = mx_sdk_vm_impl._parse_cmd_arg('native_images')
if native_images:
config_args += ['--native-images=' + ','.join(native_images)]
components = mx_sdk_vm_impl._components_include_list()
if components:
config_args += ['--components=' + ','.join(c.name for c in components)]
dynamic_imports = [('/' if subdir else '') + di for di, subdir in mx.get_dynamic_imports()]
if dynamic_imports:
config_args += ['--dynamicimports=' + ','.join(dynamic_imports)]
primary_suite_dir = mx.primary_suite().dir
args = config_args + cmd_args
suite = primary_suite_dir or svm_suite().dir
return mx.run_mx(args, suite=suite, nonZeroIsFatal=nonZeroIsFatal, out=out, err=err, timeout=timeout, env=env, quiet=quiet)
_vm_homes = {}
def _vm_home(config):
if config not in _vm_homes:
# get things initialized (e.g., cloning)
_run_graalvm_cmd(['graalvm-home'], config, out=mx.OutputCapture())
capture = mx.OutputCapture()
_run_graalvm_cmd(['graalvm-home'], config, out=capture, quiet=True)
_vm_homes[config] = capture.data.strip()
return _vm_homes[config]
def locale_US_args():
return ['-Duser.country=US', '-Duser.language=en']
class Tags(set):
def __getattr__(self, name):
if name in self:
return name
raise AttributeError
GraalTags = Tags([
'helloworld',
'debuginfotest',
'native_unittests',
'build',
'benchmarktest',
"nativeimagehelp",
'hellomodule',
'condconfig',
'truffle_unittests',
'check_libcontainer_annotations',
'check_libcontainer_namespace',
'java_agent'
])
def vm_native_image_path(config=None):
return vm_executable_path('native-image', config)
def vm_executable_path(executable, config=None):
if mx.get_os() == 'windows':
executable += '.cmd' # links are `.cmd` on windows
return join(_vm_home(config), 'bin', executable)
def _escape_for_args_file(arg):
if not (arg.startswith('\\Q') and arg.endswith('\\E')):
arg = arg.replace('\\', '\\\\')
if ' ' in arg:
arg = '\"' + arg + '\"'
return arg
def _maybe_convert_to_args_file(args):
total_command_line_args_length = sum([len(arg) for arg in args])
if total_command_line_args_length < 80:
# Do not use argument file when total command line length is reasonable,
# so that both code paths are exercised on all platforms
return args
else:
# Use argument file to avoid exceeding the command line length limit on Windows
with tempfile.NamedTemporaryFile(delete=False, mode='w', prefix='ni_args_', suffix='.args') as args_file:
args_file.write('\n'.join([_escape_for_args_file(a) for a in args]))
return ['@' + args_file.name]
@contextmanager
def native_image_context(common_args=None, hosted_assertions=True, native_image_cmd='', config=None, build_if_missing=False):
common_args = [] if common_args is None else common_args
base_args = [
'--no-fallback',
'-H:+ReportExceptionStackTraces',
] + svm_experimental_options([
'-H:+EnforceMaxRuntimeCompileMethods',
'-H:Path=' + svmbuild_dir(),
])
if mx.get_opts().verbose:
base_args += ['--verbose']
if mx.get_opts().very_verbose:
base_args += ['--verbose']
if hosted_assertions:
base_args += native_image_context.hosted_assertions
if native_image_cmd:
if not exists(native_image_cmd):
mx.abort('Given native_image_cmd does not exist')
else:
native_image_cmd = vm_native_image_path(config)
if not exists(native_image_cmd):
mx.log('Building GraalVM for config ' + str(config) + ' ...')
_run_graalvm_cmd(['build'], config)
native_image_cmd = vm_native_image_path(config)
if not exists(native_image_cmd):
raise mx.abort('The built GraalVM for config ' + str(config) + ' does not contain a native-image command')
def _native_image(args, **kwargs):
return mx.run([native_image_cmd] + _maybe_convert_to_args_file(args), **kwargs)
def is_launcher(launcher_path):
with open(launcher_path, 'rb') as fp:
first_two_bytes = fp.read(2)
first_two_bytes_launcher = b'::' if mx.is_windows() else b'#!'
return first_two_bytes == first_two_bytes_launcher
return False
if build_if_missing and is_launcher(native_image_cmd):
mx.log('Building image from launcher ' + native_image_cmd + ' ...')
verbose_image_build_option = ['--verbose'] if mx.get_opts().verbose else []
_native_image(verbose_image_build_option + ['--macro:native-image-launcher'])
def query_native_image(all_args):
stdoutdata = []
def stdout_collector(x):
stdoutdata.append(x.rstrip())
stderrdata = []
def stderr_collector(x):
stderrdata.append(x.rstrip())
exit_code = _native_image(['--dry-run', '--verbose'] + all_args, nonZeroIsFatal=False, out=stdout_collector, err=stderr_collector)
if exit_code != 0:
for line in stdoutdata:
print(line)
for line in stderrdata:
print(line)
mx.abort('Failed to query native-image.')
def remove_quotes(val):
if len(val) >= 2 and val.startswith("'") and val.endswith("'"):
return val[1:-1].replace("\\'", "'")
else:
return val
path_regex = re.compile(r'^-H:Path(@[^=]*)?=')
name_regex = re.compile(r'^-H:Name(@[^=]*)?=')
path = name = None
for line in stdoutdata:
arg = remove_quotes(line.rstrip('\\').strip())
path_matcher = path_regex.match(arg)
if path_matcher:
path = arg[path_matcher.end():]
name_matcher = name_regex.match(arg)
if name_matcher:
name = arg[name_matcher.end():]
assert path is not None and name is not None
return path, name
def native_image_func(args, **kwargs):
all_args = base_args + common_args + args
path, name = query_native_image(all_args)
image = join(path, name)
_native_image(all_args, **kwargs)
return image
yield native_image_func
native_image_context.hosted_assertions = ['-J-ea', '-J-esa']
_native_unittest_features = '--features=com.oracle.svm.test.ImageInfoTest$TestFeature,com.oracle.svm.test.services.ServiceLoaderTest$TestFeature,com.oracle.svm.test.services.SecurityServiceTest$TestFeature,com.oracle.svm.test.ReflectionRegistrationTest$TestFeature'
IMAGE_ASSERTION_FLAGS = svm_experimental_options(['-H:+VerifyGraalGraphs', '-H:+VerifyPhases'])
def image_demo_task(extra_image_args=None, flightrecorder=True):
image_args = ['--output-path', svmbuild_dir()]
if extra_image_args is not None:
image_args += extra_image_args
javac_image(image_args)
javac_command = ['--javac-command', ' '.join(javac_image_command(svmbuild_dir()))]
helloworld(image_args + javac_command)
if '--static' not in image_args:
helloworld(image_args + ['--shared']) # Build and run helloworld as shared library
if not mx.is_windows() and flightrecorder:
helloworld(image_args + ['-J-XX:StartFlightRecording=dumponexit=true']) # Build and run helloworld with FlightRecorder at image build time
if '--static' not in image_args:
cinterfacetutorial(extra_image_args)
clinittest(extra_image_args)
def truffle_args(extra_build_args):
assert isinstance(extra_build_args, list)
build_args = [
'--build-args', '--macro:truffle', '--language:nfi',
'--add-exports=java.base/jdk.internal.module=ALL-UNNAMED',
'-H:MaxRuntimeCompileMethods=5000',
]
run_args = ['--run-args', '--very-verbose', '--enable-timing']
return build_args + extra_build_args + run_args
def truffle_unittest_task(extra_build_args=None):
extra_build_args = extra_build_args or []
# ContextPreInitializationNativeImageTest can only run with its own image.
# See class javadoc for details.
truffle_context_pre_init_unittest_task(extra_build_args)
# Regular Truffle tests that can run with isolated compilation
truffle_tests = ['com.oracle.truffle.api.staticobject.test',
'com.oracle.truffle.api.test.polyglot.ContextPolicyTest']
if '-Ob' not in extra_build_args:
# GR-44492:
truffle_tests += ['com.oracle.truffle.api.test.TruffleSafepointTest']
native_unittest(truffle_tests + truffle_args(extra_build_args) + (['-Xss1m'] if '--libc=musl' in extra_build_args else []))
# White Box Truffle compilation tests that need access to compiler graphs.
if '-Ob' not in extra_build_args:
# GR-44492
native_unittest(['jdk.graal.compiler.truffle.test.ContextLookupCompilationTest'] + truffle_args(extra_build_args + svm_experimental_options(['-H:-SupportCompileInIsolates'])))
def truffle_context_pre_init_unittest_task(extra_build_args):
native_unittest(['com.oracle.truffle.api.test.polyglot.ContextPreInitializationNativeImageTest'] + truffle_args(extra_build_args))
def svm_gate_body(args, tasks):
with Task('image demos', tasks, tags=[GraalTags.helloworld]) as t:
if t:
with native_image_context(IMAGE_ASSERTION_FLAGS) as native_image:
image_demo_task(args.extra_image_builder_arguments)
helloworld(svm_experimental_options(['-H:+RunMainInNewThread']) + args.extra_image_builder_arguments)
with Task('image debuginfotest', tasks, tags=[GraalTags.debuginfotest]) as t:
if t:
if mx.is_windows():
mx.warn('debuginfotest does not work on Windows')
else:
with native_image_context(IMAGE_ASSERTION_FLAGS) as native_image:
debuginfotest(['--output-path', svmbuild_dir()] + args.extra_image_builder_arguments)
with Task('image debughelpertest', tasks, tags=[GraalTags.debuginfotest]) as t:
if t:
if mx.is_windows():
mx.warn('debughelpertest does not work on Windows')
else:
with native_image_context(IMAGE_ASSERTION_FLAGS) as native_image:
gdbdebughelperstest(['--output-path', svmbuild_dir()] + args.extra_image_builder_arguments)
with Task('native unittests', tasks, tags=[GraalTags.native_unittests]) as t:
if t:
with native_image_context(IMAGE_ASSERTION_FLAGS) as native_image:
native_unittests_task(args.extra_image_builder_arguments)
with Task('conditional configuration tests', tasks, tags=[GraalTags.condconfig]) as t:
if t:
with native_image_context(IMAGE_ASSERTION_FLAGS) as native_image:
conditional_config_task(native_image)
with Task('Run Truffle unittests with SVM image', tasks, tags=[GraalTags.truffle_unittests]) as t:
if t:
with native_image_context(IMAGE_ASSERTION_FLAGS) as native_image:
truffle_unittest_task(args.extra_image_builder_arguments)
with Task('Run Truffle NFI unittests with SVM image', tasks, tags=[GraalTags.truffle_unittests]) as t:
if t:
with native_image_context(IMAGE_ASSERTION_FLAGS) as native_image:
if '--static' in args.extra_image_builder_arguments:
mx.warn('NFI unittests use dlopen and thus do not work with statically linked executables')
else:
testlib = mx_subst.path_substitutions.substitute('-Dnative.test.path=<path:truffle:TRUFFLE_TEST_NATIVE>')
native_unittest_args = ['com.oracle.truffle.nfi.test', '--build-args',
'--macro:truffle',
'--language:nfi',
'--add-exports=java.base/jdk.internal.module=ALL-UNNAMED',
'-H:MaxRuntimeCompileMethods=2000',] + args.extra_image_builder_arguments + [
'--run-args', testlib, '--very-verbose', '--enable-timing']
native_unittest(native_unittest_args)
with Task('Check mx native-image --help', tasks, tags=[GraalTags.nativeimagehelp]) as t:
if t:
mx.log('Running mx native-image --help output check.')
# This check works by scanning stdout for the 'Usage' keyword. If that keyword does not appear, it means something broke mx native-image --help.
def help_stdout_check(output):
if 'Usage' in output:
help_stdout_check.found_usage = True
help_stdout_check.found_usage = False
# mx native-image --help is definitely broken if a non zero code is returned.
mx.run(['mx', 'native-image', '--help'], out=help_stdout_check, nonZeroIsFatal=True)
if not help_stdout_check.found_usage:
mx.abort('mx native-image --help does not seem to output the proper message. This can happen if you add extra arguments the mx native-image call without checking if an argument was --help or --help-extra.')
mx.log('mx native-image --help output check detected no errors.')
with Task('Check ContainerLibrary annotations', tasks, tags=[GraalTags.check_libcontainer_annotations]) as t:
if t:
mx.command_function("check-libcontainer-annotations")([])
with Task('Check libsvm_container namespace', tasks, tags=[GraalTags.check_libcontainer_namespace]) as t:
if t:
# verify that removing and reapplying the libcontainer namespaces does not lead to a diff
mx.command_function(LIBCONTAINER_NAMESPACE)(["remove"])
mx.command_function(LIBCONTAINER_NAMESPACE)(["add"])
git_output = suite.vc.git_command(suite.vc_dir, ["status", "--untracked-files=no", "--porcelain"])
if git_output != "":
mx.log_error(f"mx {LIBCONTAINER_NAMESPACE} remove/add modified files:")
mx.log_error(mx.colorize(git_output, color="magenta", bright=True, stream=sys.stderr))
mx.abort(textwrap.dedent(f"""
This means a change broke the automated libsvm_container namespace handling.
Be sure that this is intentional.
You can resolve this by
* reverting the change that causes the diff
* adopting mx {LIBCONTAINER_NAMESPACE} to handle the new case
* disable this gate if there is a good reason for it
"""))
with Task('module build demo', tasks, tags=[GraalTags.hellomodule]) as t:
if t:
hellomodule(args.extra_image_builder_arguments)
with Task('Validate JSON build info', tasks, tags=[GraalTags.helloworld]) as t:
if t:
import json
try:
from jsonschema import validate as json_validate
from jsonschema.exceptions import ValidationError, SchemaError
except ImportError:
mx.abort('Unable to import jsonschema')
json_and_schema_file_pairs = [
('build-artifacts.json', 'build-artifacts-schema-v0.9.0.json'),
('build-output.json', 'build-output-schema-v0.9.3.json'),
]
build_output_file = join(svmbuild_dir(), 'build-output.json')
helloworld(['--output-path', svmbuild_dir()] + svm_experimental_options([f'-H:BuildOutputJSONFile={build_output_file}', '-H:+GenerateBuildArtifactsFile']))
try:
for json_file, schema_file in json_and_schema_file_pairs:
with open(join(svmbuild_dir(), json_file)) as f:
json_contents = json.load(f)
with open(join(suite.dir, '..', 'docs', 'reference-manual', 'native-image', 'assets', schema_file)) as f:
schema_contents = json.load(f)
json_validate(json_contents, schema_contents)
except IOError as e:
mx.abort(f'Unable to load JSON build info: {e}')
except ValidationError as e:
mx.abort(f'Unable to validate JSON build info against the schema: {e}')
except SchemaError as e:
mx.abort(f'JSON schema not valid: {e}')
with Task('java agent tests', tasks, tags=[GraalTags.java_agent]) as t:
if t:
java_agent_test(args.extra_image_builder_arguments)
def native_unittests_task(extra_build_args=None):
if mx.is_windows():
# GR-24075
mx_unittest.add_global_ignore_glob('com.oracle.svm.test.ProcessPropertiesTest')
# add resources that are not in jar but in the separate directory
cp_entry_name = join(svmbuild_dir(), 'cpEntryDir')
resources_from_dir = join(cp_entry_name, 'resourcesFromDir')
simple_dir = join(cp_entry_name, 'simpleDir')
os.makedirs(cp_entry_name)
os.makedirs(resources_from_dir)
os.makedirs(simple_dir)
for i in range(4):
with open(join(cp_entry_name, "resourcesFromDir", f'cond-resource{i}.txt'), 'w') as out:
out.write(f"Conditional file{i}" + '\n')
with open(join(cp_entry_name, "simpleDir", f'simple-resource{i}.txt'), 'w') as out:
out.write(f"Simple file{i}" + '\n')
additional_build_args = svm_experimental_options([
'-H:AdditionalSecurityProviders=com.oracle.svm.test.services.SecurityServiceTest$NoOpProvider',
'-H:AdditionalSecurityServiceTypes=com.oracle.svm.test.services.SecurityServiceTest$JCACompliantNoOpService',
'-cp', cp_entry_name
])
if extra_build_args is not None:
additional_build_args += extra_build_args
if get_jdk().javaCompliance == '17':
if mx.is_windows():
mx_unittest.add_global_ignore_glob('com.oracle.svm.test.SecurityServiceTest')
native_unittest(['--build-args', _native_unittest_features] + additional_build_args)
def conditional_config_task(native_image):
agent_path = build_native_image_agent(native_image)
conditional_config_filter_path = join(svmbuild_dir(), 'conditional-config-filter.json')
with open(conditional_config_filter_path, 'w') as conditional_config_filter:
conditional_config_filter.write(
'''
{
"rules": [
{"includeClasses": "com.oracle.svm.configure.test.conditionalconfig.**"}
]
}
'''
)
run_agent_conditional_config_test(agent_path, conditional_config_filter_path)
run_nic_conditional_config_test(agent_path, conditional_config_filter_path)
def run_nic_conditional_config_test(agent_path, conditional_config_filter_path):
test_cases = [
"createConfigPartOne",
"createConfigPartTwo",
"createConfigPartThree",
]
config_directories = []
nic_test_dir = join(svmbuild_dir(), 'nic-cond-config-test')
if exists(nic_test_dir):
mx.rmtree(nic_test_dir)
for test_case in test_cases:
config_dir = join(nic_test_dir, test_case)
config_directories.append(config_dir)
agent_opts = ['config-output-dir=' + config_dir,
'experimental-conditional-config-part']
jvm_unittest(['-agentpath:' + agent_path + '=' + ','.join(agent_opts),
'-Dcom.oracle.svm.configure.test.conditionalconfig.PartialConfigurationGenerator.enabled=true',
'com.oracle.svm.configure.test.conditionalconfig.PartialConfigurationGenerator#' + test_case])
config_output_dir = join(nic_test_dir, 'config-output')
nic_exe = mx.cmd_suffix(join(mx.JDKConfig(home=mx_sdk_vm_impl.graalvm_output()).home, 'bin', 'native-image-configure'))
nic_command = [nic_exe, 'create-conditional'] \
+ ['--user-code-filter=' + conditional_config_filter_path] \
+ ['--input-dir=' + config_dir for config_dir in config_directories] \
+ ['--output-dir=' + config_output_dir]
mx.run(nic_command)
jvm_unittest(
['-Dcom.oracle.svm.configure.test.conditionalconfig.ConfigurationVerifier.configpath=' + config_output_dir,
"-Dcom.oracle.svm.configure.test.conditionalconfig.ConfigurationVerifier.enabled=true",
'com.oracle.svm.configure.test.conditionalconfig.ConfigurationVerifier'])
def run_agent_conditional_config_test(agent_path, conditional_config_filter_path):
config_dir = join(svmbuild_dir(), 'cond-config-test-config')
if exists(config_dir):
mx.rmtree(config_dir)
agent_opts = ['config-output-dir=' + config_dir,
'experimental-conditional-config-filter-file=' + conditional_config_filter_path]
# This run generates the configuration from different test cases
jvm_unittest(['-agentpath:' + agent_path + '=' + ','.join(agent_opts),
'-Dcom.oracle.svm.configure.test.conditionalconfig.ConfigurationGenerator.enabled=true',
'com.oracle.svm.configure.test.conditionalconfig.ConfigurationGenerator'])
# This run verifies that the generated configuration matches the expected one
jvm_unittest(['-Dcom.oracle.svm.configure.test.conditionalconfig.ConfigurationVerifier.configpath=' + config_dir,
"-Dcom.oracle.svm.configure.test.conditionalconfig.ConfigurationVerifier.enabled=true",
'com.oracle.svm.configure.test.conditionalconfig.ConfigurationVerifier'])
def javac_image_command(javac_path):
return [join(javac_path, 'javac'), '-proc:none'] + (
# We need to set java.home as com.sun.tools.javac.file.Locations.<clinit> can't handle `null`.
# However, the actual value isn't important because we won't use system classes from JDK jimage,
# but from JDK jmods that we will pass as app modules.
['-Djava.home=', '--system', 'none', '-p', join(mx_compiler.jdk.home, 'jmods')]
)
# replace with itertools.batched once python 3.12 is supported.
def batched(iterable, n):
if n < 1:
raise ValueError('n must be at least one')
it = iter(iterable)
while batch := tuple(islice(it, n)):
yield batch
def _native_junit(native_image, unittest_args, build_args=None, run_args=None, blacklist=None, whitelist=None, preserve_image=False, test_classes_per_run=None):
build_args = build_args or []
javaProperties = {}
for dist in suite.dists:
if isinstance(dist, mx.ClasspathDependency):
for cpEntry in mx.classpath_entries(dist):
if hasattr(cpEntry, "getJavaProperties"):
for key, value in cpEntry.getJavaProperties().items():
javaProperties[key] = value
for key, value in javaProperties.items():
build_args.append("-D" + key + "=" + value)
build_args.append('--add-exports=java.base/jdk.internal.misc=ALL-UNNAMED')
run_args = run_args or ['--verbose']
junit_native_dir = join(svmbuild_dir(), platform_name(), 'junit')
mx_util.ensure_dir_exists(junit_native_dir)
junit_test_dir = junit_native_dir if preserve_image else tempfile.mkdtemp(dir=junit_native_dir)
try:
unittest_deps = []
def dummy_harness(test_deps, vm_launcher, vm_args):
unittest_deps.extend(test_deps)
unittest_file = join(junit_test_dir, 'svmjunit.tests')
_run_tests(unittest_args, dummy_harness, _VMLauncher('dummy_launcher', None, mx_compiler.jdk), ['@Test', '@Parameters'], unittest_file, blacklist, whitelist, None, None)
if not exists(unittest_file):
mx.abort('No matching unit tests found. Skip image build and execution.')
with open(unittest_file, 'r') as f:
test_classes = [line.rstrip() for line in f]
mx.log('Building junit image for matching: ' + ' '.join(test_classes))
extra_image_args = mx.get_runtime_jvm_args(unittest_deps, jdk=mx_compiler.jdk, exclude_names=mx_sdk_vm_impl.NativePropertiesBuildTask.implicit_excludes)
macro_junit = '--macro:junit'
unittest_image = native_image(['-ea', '-esa'] + build_args + extra_image_args + [macro_junit + '=' + unittest_file] + svm_experimental_options(['-H:Path=' + junit_test_dir]))
image_pattern_replacement = unittest_image + ".exe" if mx.is_windows() else unittest_image
run_args = [arg.replace('${unittest.image}', image_pattern_replacement) for arg in run_args]
mx.log('Running: ' + ' '.join(map(shlex.quote, [unittest_image] + run_args)))
if not test_classes_per_run:
# Run all tests in one go. The default behavior.
test_classes_per_run = sys.maxsize
failures = []
for classes in batched(test_classes, test_classes_per_run):
ret = mx.run([unittest_image] + run_args + [arg for c in classes for arg in ['--run-explicit', c]], nonZeroIsFatal=False)
if ret != 0:
failures.append((ret, classes))
if len(failures) != 0:
fail_descs = (f"> Test run of the following classes failed with exit code {ret}: {', '.join(classes)}" for ret, classes in failures)
mx.log('Some test runs failed:\n' + '\n'.join(fail_descs))
mx.abort(1)
finally:
if not preserve_image:
mx.rmtree(junit_test_dir)
_mask_str = '$mask$'
def _mask(arg, arg_list):
if arg in (arg_list + ['-h', '--help', '--']):
return arg
else:
return arg.replace('-', _mask_str)
def unmask(args):
return [arg.replace(_mask_str, '-') for arg in args]
def _native_unittest(native_image, cmdline_args):
parser = ArgumentParser(prog='mx native-unittest', description='Run unittests as native image.')
all_args = ['--build-args', '--run-args', '--blacklist', '--whitelist', '-p', '--preserve-image', '--test-classes-per-run']
cmdline_args = [_mask(arg, all_args) for arg in cmdline_args]
parser.add_argument(all_args[0], metavar='ARG', nargs='*', default=[])
parser.add_argument(all_args[1], metavar='ARG', nargs='*', default=[])
parser.add_argument('--blacklist', help='run all testcases not specified in <file>', metavar='<file>')
parser.add_argument('--whitelist', help='run testcases specified in <file> only', metavar='<file>')
parser.add_argument('-p', '--preserve-image', help='do not delete the generated native image', action='store_true')
parser.add_argument('--test-classes-per-run', help='run N test classes per image run, instead of all tests at once', nargs=1, type=int)
parser.add_argument('unittest_args', metavar='TEST_ARG', nargs='*')
pargs = parser.parse_args(cmdline_args)
blacklist = unmask([pargs.blacklist])[0] if pargs.blacklist else None
whitelist = unmask([pargs.whitelist])[0] if pargs.whitelist else None
test_classes_per_run = pargs.test_classes_per_run[0] if pargs.test_classes_per_run else None
if whitelist:
try:
with open(whitelist) as fp:
whitelist = [re.compile(fnmatch.translate(l.rstrip())) for l in fp.readlines() if not l.startswith('#')]
except IOError:
mx.log('warning: could not read whitelist: ' + whitelist)
if blacklist:
try:
with open(blacklist) as fp:
blacklist = [re.compile(fnmatch.translate(l.rstrip())) for l in fp.readlines() if not l.startswith('#')]
except IOError:
mx.log('warning: could not read blacklist: ' + blacklist)
unittest_args = unmask(pargs.unittest_args) if unmask(pargs.unittest_args) else ['com.oracle.svm.test', 'com.oracle.svm.configure.test']
_native_junit(native_image, unittest_args, unmask(pargs.build_args), unmask(pargs.run_args), blacklist, whitelist, pargs.preserve_image, test_classes_per_run)
def jvm_unittest(args):
return mx_unittest.unittest(['--suite', 'substratevm'] + args)
def js_image_test(jslib, bench_location, name, warmup_iterations, iterations, timeout=None, bin_args=None):
bin_args = bin_args if bin_args is not None else []
jsruncmd = [get_js_launcher(jslib)] + bin_args + [join(bench_location, 'harness.js'), '--', join(bench_location, name + '.js'),
'--', '--warmup-time=' + str(15_000),
'--warmup-iterations=' + str(warmup_iterations),
'--iterations=' + str(iterations)]
mx.log(' '.join(jsruncmd))
passing = []
stdoutdata = []
def stdout_collector(x):
stdoutdata.append(x)
mx.log(x.rstrip())
stderrdata = []
def stderr_collector(x):
stderrdata.append(x)
mx.warn(x.rstrip())
returncode = mx.run(jsruncmd, cwd=bench_location, out=stdout_collector, err=stderr_collector, nonZeroIsFatal=False, timeout=timeout)
if returncode == mx.ERROR_TIMEOUT:
print('INFO: TIMEOUT (> %d): %s' % (timeout, name))
elif returncode >= 0:
matches = 0
for line in stdoutdata:
if re.match(r'^\S+: *\d+(\.\d+)?\s*$', line):
matches += 1
if matches > 0:
passing = stdoutdata
if not passing:
mx.abort('JS benchmark ' + name + ' failed')
def build_js_lib(native_image):
return mx.add_lib_suffix(native_image(['--macro:jsvm-library']))
def get_js_launcher(jslib):
return os.path.join(os.path.dirname(jslib), "..", "bin", "js")
def test_js(js, benchmarks, bin_args=None):
bench_location = join(suite.dir, '..', '..', 'js-benchmarks')
for benchmark_name, warmup_iterations, iterations, timeout in benchmarks:
js_image_test(js, bench_location, benchmark_name, warmup_iterations, iterations, timeout, bin_args=bin_args)
def test_run(cmds, expected_stdout, timeout=10, env=None):
stdoutdata = []
def stdout_collector(x):
stdoutdata.append(x)
mx.log(x.rstrip())
stderrdata = []
def stderr_collector(x):
stderrdata.append(x)
mx.warn(x.rstrip())
returncode = mx.run(cmds, out=stdout_collector, err=stderr_collector, nonZeroIsFatal=False, timeout=timeout, env=env)
if ''.join(stdoutdata) != expected_stdout:
mx.abort('Error: stdout does not match expected_stdout')
return (returncode, stdoutdata, stderrdata)
mx_gate.add_gate_runner(suite, svm_gate_body)
mx_gate.add_gate_argument('--extra-image-builder-arguments', action=mx_compiler.ShellEscapedStringAction, help='adds image builder arguments to gate tasks where applicable', default=[])
def _cinterfacetutorial(native_image, args=None):
"""Build and run the tutorial for the C interface"""
args = [] if args is None else args
tutorial_proj = mx.dependency('com.oracle.svm.tutorial')
c_source_dir = join(tutorial_proj.dir, 'native')
build_dir = join(svmbuild_dir(), tutorial_proj.name, 'build')
# clean / create output directory
if exists(build_dir):
mx.rmtree(build_dir)
mx_util.ensure_dir_exists(build_dir)
# Build the shared library from Java code
native_image(['--shared', '-o', join(build_dir, 'libcinterfacetutorial'), '-Dcom.oracle.svm.tutorial.headerfile=' + join(c_source_dir, 'mydata.h'),
'-H:CLibraryPath=' + tutorial_proj.dir, '-cp', tutorial_proj.output_dir()] + args)
# Build the C executable
if mx.get_os() != 'windows':
mx.run(['cc', '-g', join(c_source_dir, 'cinterfacetutorial.c'),
'-I.', '-L.', '-lcinterfacetutorial',
'-ldl', '-Wl,-rpath,' + build_dir,
'-o', 'cinterfacetutorial'],
cwd=build_dir)
else:
mx.run(['cl', '-MD', join(c_source_dir, 'cinterfacetutorial.c'),
'-I.', 'libcinterfacetutorial.lib'],
cwd=build_dir)
# Start the C executable
mx.run([join(build_dir, 'cinterfacetutorial')])
_helloworld_variants = {
'traditional': '''
public class HelloWorld {
public static void main(String[] args) {
System.out.println(System.getenv("%s"));
}
}
''',
'noArgs': '''
// requires JDK 21 and --enable-preview
public class HelloWorld {
static void main() {
System.out.println(System.getenv("%s"));
}
}
''',
'instance': '''
// requires JDK 21 and --enable-preview
class HelloWorld {
void main(String[] args) {
System.out.println(System.getenv("%s"));
}
}
''',
'instanceNoArgs': '''
// requires JDK 21 and --enable-preview
class HelloWorld {
void main() {
System.out.println(System.getenv("%s"));
}
}
''',
'unnamedClass': '''
// requires JDK 21 and javac --enable-preview --source 21 and native-image --enable-preview
void main() {
System.out.println(System.getenv("%s"));
}
''',
}
def _helloworld(native_image, javac_command, path, build_only, args, variant=list(_helloworld_variants.keys())[0]):
mx_util.ensure_dir_exists(path)
hello_file = os.path.join(path, 'HelloWorld.java')
envkey = 'HELLO_WORLD_MESSAGE'
output = 'Hello from native-image!'
with open(hello_file, 'w') as fp:
fp.write(_helloworld_variants[variant] % envkey)
fp.flush()
mx.run(javac_command + [hello_file])
javaProperties = {}
for dist in suite.dists:
if isinstance(dist, mx.ClasspathDependency):
for cpEntry in mx.classpath_entries(dist):
if hasattr(cpEntry, "getJavaProperties"):
for key, value in cpEntry.getJavaProperties().items():
javaProperties[key] = value
for key, value in javaProperties.items():
args.append("-D" + key + "=" + value)
binary_path = join(path, "helloworld")
native_image(["--native-image-info", "-o", binary_path,] +
svm_experimental_options(['-H:+VerifyNamingConventions']) +
['-cp', path, 'HelloWorld'] + args)
if not build_only:
expected_output = [(output + os.linesep).encode()]
actual_output = []
if '--shared' in args:
# If helloword got built into a shared library we use python to load the shared library
# and call its `run_main`. We are capturing the stdout during the call into an unnamed
# pipe so that we can use it in the actual vs. expected check below.
try:
import ctypes
so_name = mx.add_lib_suffix('helloworld')
lib = ctypes.CDLL(join(path, so_name))
stdout = os.dup(1) # save original stdout
pout, pin = os.pipe()
os.dup2(pin, 1) # connect stdout to pipe
os.environ[envkey] = output
argc = 1
argv = (ctypes.c_char_p * argc)(b'dummy')
lib.run_main(argc, argv) # call run_main of shared lib
call_stdout = os.read(pout, 120) # get pipe contents
actual_output.append(call_stdout)
os.dup2(stdout, 1) # restore original stdout
mx.log('Stdout from calling run_main in shared object {}:'.format(so_name))
mx.log(call_stdout)
finally:
del os.environ[envkey]
os.close(pin)
os.close(pout)
else:
env = os.environ.copy()
env[envkey] = output
def _collector(x):
actual_output.append(x.encode())
mx.log(x)
mx.run([binary_path], out=_collector, env=env)
if actual_output != expected_output:
raise Exception('Unexpected output: ' + str(actual_output) + " != " + str(expected_output))
def _debuginfotest(native_image, path, build_only, with_isolates_only, args):
mx.log(f"path={path}")
sourcepath = mx.project('com.oracle.svm.test').source_dirs()[0]
mx.log(f"sourcepath={sourcepath}")
sourcecache = join(path, 'sources')
mx.log(f"sourcecache={sourcecache}")
# the header file for foreign types resides at the root of the
# com.oracle.svm.test source tree
cincludepath = sourcepath
javaProperties = {}
for dist in suite.dists:
if isinstance(dist, mx.ClasspathDependency):
for cpEntry in mx.classpath_entries(dist):
if hasattr(cpEntry, "getJavaProperties"):
for key, value in cpEntry.getJavaProperties().items():
javaProperties[key] = value
for key, value in javaProperties.items():
args.append("-D" + key + "=" + value)
# set property controlling inclusion of foreign struct header
args.append("-DbuildDebugInfoTestExample=true")
native_image_args = [
'--native-compiler-options=-I' + cincludepath,
'-H:CLibraryPath=' + sourcepath,
'--native-image-info',
'-cp', classpath('com.oracle.svm.test'),
'-Djdk.graal.LogFile=graal.log',
'-g',
] + svm_experimental_options([
'-H:+VerifyNamingConventions',
'-H:+SourceLevelDebug',
'-H:DebugInfoSourceSearchPath=' + sourcepath,
]) + args
def build_debug_test(variant_name, image_name, extra_args):
per_build_path = join(path, variant_name)
mx_util.ensure_dir_exists(per_build_path)
build_args = native_image_args + extra_args + [
'-o', join(per_build_path, image_name)
]
mx.log(f'native_image {build_args}')
return native_image(build_args)
# build with and without Isolates and check both work
if '--libc=musl' in args:
os.environ.update({'debuginfotest_musl': 'yes'})
testhello_py = join(suite.dir, 'mx.substratevm', 'testhello.py')