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