1// Copyright 2017 Google Inc. All rights reserved.
2// Licensed under the Apache License, Version 2.0 (the "License");
3// you may not use this file except in compliance with the License.
4// You may obtain a copy of the License at
5//
6//     http://www.apache.org/licenses/LICENSE-2.0
7//
8// Unless required by applicable law or agreed to in writing, software
9// distributed under the License is distributed on an "AS IS" BASIS,
10// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11// See the License for the specific language governing permissions and
12// limitations under the License.
13
14package java
15
16import (
17	"fmt"
18	"io"
19	"strings"
20
21	"github.com/google/blueprint"
22
23	"android/soong/android"
24)
25
26// OpenJDK 9 introduces the concept of "system modules", which replace the bootclasspath.  This
27// file will produce the rules necessary to convert each unique set of bootclasspath jars into
28// system modules in a runtime image using the jmod and jlink tools.
29
30func init() {
31	RegisterSystemModulesBuildComponents(android.InitRegistrationContext)
32
33	pctx.SourcePathVariable("moduleInfoJavaPath", "build/soong/scripts/jars-to-module-info-java.sh")
34
35	// Register sdk member types.
36	android.RegisterSdkMemberType(&systemModulesSdkMemberType{
37		android.SdkMemberTypeBase{
38			PropertyName: "java_system_modules",
39			SupportsSdk:  true,
40		},
41	})
42}
43
44func RegisterSystemModulesBuildComponents(ctx android.RegistrationContext) {
45	ctx.RegisterModuleType("java_system_modules", SystemModulesFactory)
46	ctx.RegisterModuleType("java_system_modules_import", systemModulesImportFactory)
47}
48
49var (
50	jarsTosystemModules = pctx.AndroidStaticRule("jarsTosystemModules", blueprint.RuleParams{
51		Command: `rm -rf ${outDir} ${workDir} && mkdir -p ${workDir}/jmod && ` +
52			`${moduleInfoJavaPath} java.base $in > ${workDir}/module-info.java && ` +
53			`${config.JavacCmd} --system=none --patch-module=java.base=${classpath} ${workDir}/module-info.java && ` +
54			`${config.SoongZipCmd} -jar -o ${workDir}/classes.jar -C ${workDir} -f ${workDir}/module-info.class && ` +
55			`${config.MergeZipsCmd} -j ${workDir}/module.jar ${workDir}/classes.jar $in && ` +
56			// Note: The version of the java.base module created must match the version
57			// of the jlink tool which consumes it.
58			`${config.JmodCmd} create --module-version ${config.JlinkVersion} --target-platform android ` +
59			`  --class-path ${workDir}/module.jar ${workDir}/jmod/java.base.jmod && ` +
60			`${config.JlinkCmd} --module-path ${workDir}/jmod --add-modules java.base --output ${outDir} ` +
61			// Note: The system-modules jlink plugin is disabled because (a) it is not
62			// useful on Android, and (b) it causes errors with later versions of jlink
63			// when the jdk.internal.module is absent from java.base (as it is here).
64			`  --disable-plugin system-modules && ` +
65			`cp ${config.JrtFsJar} ${outDir}/lib/`,
66		CommandDeps: []string{
67			"${moduleInfoJavaPath}",
68			"${config.JavacCmd}",
69			"${config.SoongZipCmd}",
70			"${config.MergeZipsCmd}",
71			"${config.JmodCmd}",
72			"${config.JlinkCmd}",
73			"${config.JrtFsJar}",
74		},
75	},
76		"classpath", "outDir", "workDir")
77
78	// Dependency tag that causes the added dependencies to be added as java_header_libs
79	// to the sdk/module_exports/snapshot. Dependencies that are added automatically via this tag are
80	// not automatically exported.
81	systemModulesLibsTag = android.DependencyTagForSdkMemberType(javaHeaderLibsSdkMemberType, false)
82)
83
84func TransformJarsToSystemModules(ctx android.ModuleContext, jars android.Paths) (android.Path, android.Paths) {
85	outDir := android.PathForModuleOut(ctx, "system")
86	workDir := android.PathForModuleOut(ctx, "modules")
87	outputFile := android.PathForModuleOut(ctx, "system/lib/modules")
88	outputs := android.WritablePaths{
89		outputFile,
90		android.PathForModuleOut(ctx, "system/lib/jrt-fs.jar"),
91		android.PathForModuleOut(ctx, "system/release"),
92	}
93
94	ctx.Build(pctx, android.BuildParams{
95		Rule:        jarsTosystemModules,
96		Description: "system modules",
97		Outputs:     outputs,
98		Inputs:      jars,
99		Args: map[string]string{
100			"classpath": strings.Join(jars.Strings(), ":"),
101			"workDir":   workDir.String(),
102			"outDir":    outDir.String(),
103		},
104	})
105
106	return outDir, outputs.Paths()
107}
108
109// java_system_modules creates a system module from a set of java libraries that can
110// be referenced from the system_modules property. It must contain at a minimum the
111// java.base module which must include classes from java.lang amongst other java packages.
112func SystemModulesFactory() android.Module {
113	module := &SystemModules{}
114	module.AddProperties(&module.properties)
115	android.InitAndroidArchModule(module, android.HostAndDeviceSupported, android.MultilibCommon)
116	android.InitDefaultableModule(module)
117	android.InitSdkAwareModule(module)
118	return module
119}
120
121type SystemModulesProvider interface {
122	HeaderJars() android.Paths
123	OutputDirAndDeps() (android.Path, android.Paths)
124}
125
126var _ SystemModulesProvider = (*SystemModules)(nil)
127
128var _ SystemModulesProvider = (*systemModulesImport)(nil)
129
130type SystemModules struct {
131	android.ModuleBase
132	android.DefaultableModuleBase
133	android.SdkBase
134
135	properties SystemModulesProperties
136
137	// The aggregated header jars from all jars specified in the libs property.
138	// Used when system module is added as a dependency to bootclasspath.
139	headerJars android.Paths
140	outputDir  android.Path
141	outputDeps android.Paths
142}
143
144type SystemModulesProperties struct {
145	// List of java library modules that should be included in the system modules
146	Libs []string
147}
148
149func (system *SystemModules) HeaderJars() android.Paths {
150	return system.headerJars
151}
152
153func (system *SystemModules) OutputDirAndDeps() (android.Path, android.Paths) {
154	if system.outputDir == nil || len(system.outputDeps) == 0 {
155		panic("Missing directory for system module dependency")
156	}
157	return system.outputDir, system.outputDeps
158}
159
160func (system *SystemModules) GenerateAndroidBuildActions(ctx android.ModuleContext) {
161	var jars android.Paths
162
163	ctx.VisitDirectDepsWithTag(systemModulesLibsTag, func(module android.Module) {
164		dep, _ := ctx.OtherModuleProvider(module, JavaInfoProvider).(JavaInfo)
165		jars = append(jars, dep.HeaderJars...)
166	})
167
168	system.headerJars = jars
169
170	system.outputDir, system.outputDeps = TransformJarsToSystemModules(ctx, jars)
171}
172
173// ComponentDepsMutator is called before prebuilt modules without a corresponding source module are
174// renamed so unless the supplied libs specifically includes the prebuilt_ prefix this is guaranteed
175// to only add dependencies on source modules.
176//
177// The systemModuleLibsTag will prevent the prebuilt mutators from replacing this dependency so it
178// will never be changed to depend on a prebuilt either.
179func (system *SystemModules) ComponentDepsMutator(ctx android.BottomUpMutatorContext) {
180	ctx.AddVariationDependencies(nil, systemModulesLibsTag, system.properties.Libs...)
181}
182
183func (system *SystemModules) AndroidMk() android.AndroidMkData {
184	return android.AndroidMkData{
185		Custom: func(w io.Writer, name, prefix, moduleDir string, data android.AndroidMkData) {
186			fmt.Fprintln(w)
187
188			makevar := "SOONG_SYSTEM_MODULES_" + name
189			fmt.Fprintln(w, makevar, ":=$=", system.outputDir.String())
190			fmt.Fprintln(w)
191
192			makevar = "SOONG_SYSTEM_MODULES_LIBS_" + name
193			fmt.Fprintln(w, makevar, ":=$=", strings.Join(system.properties.Libs, " "))
194			fmt.Fprintln(w)
195
196			makevar = "SOONG_SYSTEM_MODULES_DEPS_" + name
197			fmt.Fprintln(w, makevar, ":=$=", strings.Join(system.outputDeps.Strings(), " "))
198			fmt.Fprintln(w)
199
200			fmt.Fprintln(w, name+":", "$("+makevar+")")
201			fmt.Fprintln(w, ".PHONY:", name)
202			// TODO(b/151177513): Licenses: Doesn't go through base_rules. May have to generate meta_lic and meta_module here.
203		},
204	}
205}
206
207// A prebuilt version of java_system_modules. It does not import the
208// generated system module, it generates the system module from imported
209// java libraries in the same way that java_system_modules does. It just
210// acts as a prebuilt, i.e. can have the same base name as another module
211// type and the one to use is selected at runtime.
212func systemModulesImportFactory() android.Module {
213	module := &systemModulesImport{}
214	module.AddProperties(&module.properties)
215	android.InitPrebuiltModule(module, &module.properties.Libs)
216	android.InitAndroidArchModule(module, android.HostAndDeviceSupported, android.MultilibCommon)
217	android.InitDefaultableModule(module)
218	android.InitSdkAwareModule(module)
219	return module
220}
221
222type systemModulesImport struct {
223	SystemModules
224	prebuilt android.Prebuilt
225}
226
227func (system *systemModulesImport) Name() string {
228	return system.prebuilt.Name(system.ModuleBase.Name())
229}
230
231func (system *systemModulesImport) Prebuilt() *android.Prebuilt {
232	return &system.prebuilt
233}
234
235// ComponentDepsMutator is called before prebuilt modules without a corresponding source module are
236// renamed so as this adds a prebuilt_ prefix this is guaranteed to only add dependencies on source
237// modules.
238func (system *systemModulesImport) ComponentDepsMutator(ctx android.BottomUpMutatorContext) {
239	for _, lib := range system.properties.Libs {
240		ctx.AddVariationDependencies(nil, systemModulesLibsTag, android.PrebuiltNameFromSource(lib))
241	}
242}
243
244type systemModulesSdkMemberType struct {
245	android.SdkMemberTypeBase
246}
247
248func (mt *systemModulesSdkMemberType) AddDependencies(mctx android.BottomUpMutatorContext, dependencyTag blueprint.DependencyTag, names []string) {
249	mctx.AddVariationDependencies(nil, dependencyTag, names...)
250}
251
252func (mt *systemModulesSdkMemberType) IsInstance(module android.Module) bool {
253	if _, ok := module.(*SystemModules); ok {
254		// A prebuilt system module cannot be added as a member of an sdk because the source and
255		// snapshot instances would conflict.
256		_, ok := module.(*systemModulesImport)
257		return !ok
258	}
259	return false
260}
261
262func (mt *systemModulesSdkMemberType) AddPrebuiltModule(ctx android.SdkMemberContext, member android.SdkMember) android.BpModule {
263	return ctx.SnapshotBuilder().AddPrebuiltModule(member, "java_system_modules_import")
264}
265
266type systemModulesInfoProperties struct {
267	android.SdkMemberPropertiesBase
268
269	Libs []string
270}
271
272func (mt *systemModulesSdkMemberType) CreateVariantPropertiesStruct() android.SdkMemberProperties {
273	return &systemModulesInfoProperties{}
274}
275
276func (p *systemModulesInfoProperties) PopulateFromVariant(ctx android.SdkMemberContext, variant android.Module) {
277	systemModule := variant.(*SystemModules)
278	p.Libs = systemModule.properties.Libs
279}
280
281func (p *systemModulesInfoProperties) AddToPropertySet(ctx android.SdkMemberContext, propertySet android.BpPropertySet) {
282	if len(p.Libs) > 0 {
283		// Add the references to the libraries that form the system module.
284		propertySet.AddPropertyWithTag("libs", p.Libs, ctx.SnapshotBuilder().SdkMemberReferencePropertyTag(true))
285	}
286}
287