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			TransitiveSdkMembers: 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			`${config.JmodCmd} create --module-version ${config.JlinkVersion} --target-platform android ` +
60			`  --class-path ${workDir}/module.jar ${workDir}/jmod/java.base.jmod && ` +
61			`${config.JlinkCmd} --module-path ${workDir}/jmod --add-modules java.base --output ${outDir} ` +
62			// Note: The system-modules jlink plugin is disabled because (a) it is not
63			// useful on Android, and (b) it causes errors with later versions of jlink
64			// when the jdk.internal.module is absent from java.base (as it is here).
65			`  --disable-plugin system-modules && ` +
66			`cp ${config.JrtFsJar} ${outDir}/lib/`,
67		CommandDeps: []string{
68			"${moduleInfoJavaPath}",
69			"${config.JavacCmd}",
70			"${config.SoongZipCmd}",
71			"${config.MergeZipsCmd}",
72			"${config.JmodCmd}",
73			"${config.JlinkCmd}",
74			"${config.JrtFsJar}",
75		},
76	},
77		"classpath", "outDir", "workDir")
78
79	// Dependency tag that causes the added dependencies to be added as java_header_libs
80	// to the sdk/module_exports/snapshot.
81	systemModulesLibsTag = android.DependencyTagForSdkMemberType(javaHeaderLibsSdkMemberType)
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	return module
118}
119
120type SystemModulesProvider interface {
121	HeaderJars() android.Paths
122	OutputDirAndDeps() (android.Path, android.Paths)
123}
124
125var _ SystemModulesProvider = (*SystemModules)(nil)
126
127var _ SystemModulesProvider = (*systemModulesImport)(nil)
128
129type SystemModules struct {
130	android.ModuleBase
131	android.DefaultableModuleBase
132	android.SdkBase
133
134	properties SystemModulesProperties
135
136	// The aggregated header jars from all jars specified in the libs property.
137	// Used when system module is added as a dependency to bootclasspath.
138	headerJars android.Paths
139	outputDir  android.Path
140	outputDeps android.Paths
141}
142
143type SystemModulesProperties struct {
144	// List of java library modules that should be included in the system modules
145	Libs []string
146}
147
148func (system *SystemModules) HeaderJars() android.Paths {
149	return system.headerJars
150}
151
152func (system *SystemModules) OutputDirAndDeps() (android.Path, android.Paths) {
153	if system.outputDir == nil || len(system.outputDeps) == 0 {
154		panic("Missing directory for system module dependency")
155	}
156	return system.outputDir, system.outputDeps
157}
158
159func (system *SystemModules) GenerateAndroidBuildActions(ctx android.ModuleContext) {
160	var jars android.Paths
161
162	ctx.VisitDirectDepsWithTag(systemModulesLibsTag, func(module android.Module) {
163		dep, _ := module.(Dependency)
164		jars = append(jars, dep.HeaderJars()...)
165	})
166
167	system.headerJars = jars
168
169	system.outputDir, system.outputDeps = TransformJarsToSystemModules(ctx, jars)
170}
171
172func (system *SystemModules) DepsMutator(ctx android.BottomUpMutatorContext) {
173	ctx.AddVariationDependencies(nil, systemModulesLibsTag, system.properties.Libs...)
174}
175
176func (system *SystemModules) AndroidMk() android.AndroidMkData {
177	return android.AndroidMkData{
178		Custom: func(w io.Writer, name, prefix, moduleDir string, data android.AndroidMkData) {
179			fmt.Fprintln(w)
180
181			makevar := "SOONG_SYSTEM_MODULES_" + name
182			fmt.Fprintln(w, makevar, ":=$=", system.outputDir.String())
183			fmt.Fprintln(w)
184
185			makevar = "SOONG_SYSTEM_MODULES_LIBS_" + name
186			fmt.Fprintln(w, makevar, ":=$=", strings.Join(system.properties.Libs, " "))
187			fmt.Fprintln(w)
188
189			makevar = "SOONG_SYSTEM_MODULES_DEPS_" + name
190			fmt.Fprintln(w, makevar, ":=$=", strings.Join(system.outputDeps.Strings(), " "))
191			fmt.Fprintln(w)
192
193			fmt.Fprintln(w, name+":", "$("+makevar+")")
194			fmt.Fprintln(w, ".PHONY:", name)
195		},
196	}
197}
198
199// A prebuilt version of java_system_modules. It does not import the
200// generated system module, it generates the system module from imported
201// java libraries in the same way that java_system_modules does. It just
202// acts as a prebuilt, i.e. can have the same base name as another module
203// type and the one to use is selected at runtime.
204func systemModulesImportFactory() android.Module {
205	module := &systemModulesImport{}
206	module.AddProperties(&module.properties)
207	android.InitPrebuiltModule(module, &module.properties.Libs)
208	android.InitAndroidArchModule(module, android.HostAndDeviceSupported, android.MultilibCommon)
209	android.InitDefaultableModule(module)
210	android.InitSdkAwareModule(module)
211	return module
212}
213
214type systemModulesImport struct {
215	SystemModules
216	prebuilt android.Prebuilt
217}
218
219func (system *systemModulesImport) Name() string {
220	return system.prebuilt.Name(system.ModuleBase.Name())
221}
222
223func (system *systemModulesImport) Prebuilt() *android.Prebuilt {
224	return &system.prebuilt
225}
226
227type systemModulesSdkMemberType struct {
228	android.SdkMemberTypeBase
229}
230
231func (mt *systemModulesSdkMemberType) AddDependencies(mctx android.BottomUpMutatorContext, dependencyTag blueprint.DependencyTag, names []string) {
232	mctx.AddVariationDependencies(nil, dependencyTag, names...)
233}
234
235func (mt *systemModulesSdkMemberType) IsInstance(module android.Module) bool {
236	if _, ok := module.(*SystemModules); ok {
237		// A prebuilt system module cannot be added as a member of an sdk because the source and
238		// snapshot instances would conflict.
239		_, ok := module.(*systemModulesImport)
240		return !ok
241	}
242	return false
243}
244
245func (mt *systemModulesSdkMemberType) AddPrebuiltModule(ctx android.SdkMemberContext, member android.SdkMember) android.BpModule {
246	return ctx.SnapshotBuilder().AddPrebuiltModule(member, "java_system_modules_import")
247}
248
249type systemModulesInfoProperties struct {
250	android.SdkMemberPropertiesBase
251
252	Libs []string
253}
254
255func (mt *systemModulesSdkMemberType) CreateVariantPropertiesStruct() android.SdkMemberProperties {
256	return &systemModulesInfoProperties{}
257}
258
259func (p *systemModulesInfoProperties) PopulateFromVariant(ctx android.SdkMemberContext, variant android.Module) {
260	systemModule := variant.(*SystemModules)
261	p.Libs = systemModule.properties.Libs
262}
263
264func (p *systemModulesInfoProperties) AddToPropertySet(ctx android.SdkMemberContext, propertySet android.BpPropertySet) {
265	if len(p.Libs) > 0 {
266		// Add the references to the libraries that form the system module.
267		propertySet.AddPropertyWithTag("libs", p.Libs, ctx.SnapshotBuilder().SdkMemberReferencePropertyTag(true))
268	}
269}
270