1// Copyright 2019 Google Inc. All rights reserved.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15package java
16
17import (
18	"bytes"
19	"encoding/base64"
20	"encoding/binary"
21	"path/filepath"
22	"strings"
23
24	"android/soong/android"
25
26	"github.com/google/blueprint"
27)
28
29var kotlinc = pctx.AndroidRemoteStaticRule("kotlinc", android.RemoteRuleSupports{Goma: true},
30	blueprint.RuleParams{
31		Command: `rm -rf "$classesDir" "$srcJarDir" "$kotlinBuildFile" "$emptyDir" && ` +
32			`mkdir -p "$classesDir" "$srcJarDir" "$emptyDir" && ` +
33			`${config.ZipSyncCmd} -d $srcJarDir -l $srcJarDir/list -f "*.java" $srcJars && ` +
34			`${config.GenKotlinBuildFileCmd} --classpath "$classpath" --name "$name"` +
35			` --out_dir "$classesDir" --srcs "$out.rsp" --srcs "$srcJarDir/list"` +
36			` $commonSrcFilesArg --out "$kotlinBuildFile" && ` +
37			`${config.KotlincCmd} ${config.KotlincSuppressJDK9Warnings} ${config.JavacHeapFlags} ` +
38			`$kotlincFlags -jvm-target $kotlinJvmTarget -Xbuild-file=$kotlinBuildFile ` +
39			`-kotlin-home $emptyDir && ` +
40			`${config.SoongZipCmd} -jar -o $out -C $classesDir -D $classesDir && ` +
41			`rm -rf "$srcJarDir"`,
42		CommandDeps: []string{
43			"${config.KotlincCmd}",
44			"${config.KotlinCompilerJar}",
45			"${config.KotlinPreloaderJar}",
46			"${config.KotlinReflectJar}",
47			"${config.KotlinScriptRuntimeJar}",
48			"${config.KotlinStdlibJar}",
49			"${config.KotlinTrove4jJar}",
50			"${config.KotlinAnnotationJar}",
51			"${config.GenKotlinBuildFileCmd}",
52			"${config.SoongZipCmd}",
53			"${config.ZipSyncCmd}",
54		},
55		Rspfile:        "$out.rsp",
56		RspfileContent: `$in`,
57	},
58	"kotlincFlags", "classpath", "srcJars", "commonSrcFilesArg", "srcJarDir", "classesDir",
59	"kotlinJvmTarget", "kotlinBuildFile", "emptyDir", "name")
60
61func kotlinCommonSrcsList(ctx android.ModuleContext, commonSrcFiles android.Paths) android.OptionalPath {
62	if len(commonSrcFiles) > 0 {
63		// The list of common_srcs may be too long to put on the command line, but
64		// we can't use the rsp file because it is already being used for srcs.
65		// Insert a second rule to write out the list of resources to a file.
66		commonSrcsList := android.PathForModuleOut(ctx, "kotlinc_common_srcs.list")
67		rule := android.NewRuleBuilder(pctx, ctx)
68		rule.Command().Text("cp").
69			FlagWithRspFileInputList("", commonSrcsList.ReplaceExtension(ctx, "rsp"), commonSrcFiles).
70			Output(commonSrcsList)
71		rule.Build("kotlin_common_srcs_list", "kotlin common_srcs list")
72		return android.OptionalPathForPath(commonSrcsList)
73	}
74	return android.OptionalPath{}
75}
76
77// kotlinCompile takes .java and .kt sources and srcJars, and compiles the .kt sources into a classes jar in outputFile.
78func kotlinCompile(ctx android.ModuleContext, outputFile android.WritablePath,
79	srcFiles, commonSrcFiles, srcJars android.Paths,
80	flags javaBuilderFlags) {
81
82	var deps android.Paths
83	deps = append(deps, flags.kotlincClasspath...)
84	deps = append(deps, srcJars...)
85	deps = append(deps, commonSrcFiles...)
86
87	kotlinName := filepath.Join(ctx.ModuleDir(), ctx.ModuleSubDir(), ctx.ModuleName())
88	kotlinName = strings.ReplaceAll(kotlinName, "/", "__")
89
90	commonSrcsList := kotlinCommonSrcsList(ctx, commonSrcFiles)
91	commonSrcFilesArg := ""
92	if commonSrcsList.Valid() {
93		deps = append(deps, commonSrcsList.Path())
94		commonSrcFilesArg = "--common_srcs " + commonSrcsList.String()
95	}
96
97	ctx.Build(pctx, android.BuildParams{
98		Rule:        kotlinc,
99		Description: "kotlinc",
100		Output:      outputFile,
101		Inputs:      srcFiles,
102		Implicits:   deps,
103		Args: map[string]string{
104			"classpath":         flags.kotlincClasspath.FormJavaClassPath(""),
105			"kotlincFlags":      flags.kotlincFlags,
106			"commonSrcFilesArg": commonSrcFilesArg,
107			"srcJars":           strings.Join(srcJars.Strings(), " "),
108			"classesDir":        android.PathForModuleOut(ctx, "kotlinc", "classes").String(),
109			"srcJarDir":         android.PathForModuleOut(ctx, "kotlinc", "srcJars").String(),
110			"kotlinBuildFile":   android.PathForModuleOut(ctx, "kotlinc-build.xml").String(),
111			"emptyDir":          android.PathForModuleOut(ctx, "kotlinc", "empty").String(),
112			// http://b/69160377 kotlinc only supports -jvm-target 1.6 and 1.8
113			"kotlinJvmTarget": "1.8",
114			"name":            kotlinName,
115		},
116	})
117}
118
119var kapt = pctx.AndroidRemoteStaticRule("kapt", android.RemoteRuleSupports{Goma: true},
120	blueprint.RuleParams{
121		Command: `rm -rf "$srcJarDir" "$kotlinBuildFile" "$kaptDir" && ` +
122			`mkdir -p "$srcJarDir" "$kaptDir/sources" "$kaptDir/classes" && ` +
123			`${config.ZipSyncCmd} -d $srcJarDir -l $srcJarDir/list -f "*.java" $srcJars && ` +
124			`${config.GenKotlinBuildFileCmd} --classpath "$classpath" --name "$name"` +
125			` --srcs "$out.rsp" --srcs "$srcJarDir/list"` +
126			` $commonSrcFilesArg --out "$kotlinBuildFile" && ` +
127			`${config.KotlincCmd} ${config.KaptSuppressJDK9Warnings} ${config.KotlincSuppressJDK9Warnings} ` +
128			`${config.JavacHeapFlags} $kotlincFlags -Xplugin=${config.KotlinKaptJar} ` +
129			`-P plugin:org.jetbrains.kotlin.kapt3:sources=$kaptDir/sources ` +
130			`-P plugin:org.jetbrains.kotlin.kapt3:classes=$kaptDir/classes ` +
131			`-P plugin:org.jetbrains.kotlin.kapt3:stubs=$kaptDir/stubs ` +
132			`-P plugin:org.jetbrains.kotlin.kapt3:correctErrorTypes=true ` +
133			`-P plugin:org.jetbrains.kotlin.kapt3:aptMode=stubsAndApt ` +
134			`-P plugin:org.jetbrains.kotlin.kapt3:javacArguments=$encodedJavacFlags ` +
135			`$kaptProcessorPath ` +
136			`$kaptProcessor ` +
137			`-Xbuild-file=$kotlinBuildFile && ` +
138			`${config.SoongZipCmd} -jar -o $out -C $kaptDir/sources -D $kaptDir/sources && ` +
139			`${config.SoongZipCmd} -jar -o $classesJarOut -C $kaptDir/classes -D $kaptDir/classes && ` +
140			`rm -rf "$srcJarDir"`,
141		CommandDeps: []string{
142			"${config.KotlincCmd}",
143			"${config.KotlinCompilerJar}",
144			"${config.KotlinKaptJar}",
145			"${config.GenKotlinBuildFileCmd}",
146			"${config.SoongZipCmd}",
147			"${config.ZipSyncCmd}",
148		},
149		Rspfile:        "$out.rsp",
150		RspfileContent: `$in`,
151	},
152	"kotlincFlags", "encodedJavacFlags", "kaptProcessorPath", "kaptProcessor",
153	"classpath", "srcJars", "commonSrcFilesArg", "srcJarDir", "kaptDir", "kotlinJvmTarget",
154	"kotlinBuildFile", "name", "classesJarOut")
155
156// kotlinKapt performs Kotlin-compatible annotation processing.  It takes .kt and .java sources and srcjars, and runs
157// annotation processors over all of them, producing a srcjar of generated code in outputFile.  The srcjar should be
158// added as an additional input to kotlinc and javac rules, and the javac rule should have annotation processing
159// disabled.
160func kotlinKapt(ctx android.ModuleContext, srcJarOutputFile, resJarOutputFile android.WritablePath,
161	srcFiles, commonSrcFiles, srcJars android.Paths,
162	flags javaBuilderFlags) {
163
164	srcFiles = append(android.Paths(nil), srcFiles...)
165
166	var deps android.Paths
167	deps = append(deps, flags.kotlincClasspath...)
168	deps = append(deps, srcJars...)
169	deps = append(deps, flags.processorPath...)
170	deps = append(deps, commonSrcFiles...)
171
172	commonSrcsList := kotlinCommonSrcsList(ctx, commonSrcFiles)
173	commonSrcFilesArg := ""
174	if commonSrcsList.Valid() {
175		deps = append(deps, commonSrcsList.Path())
176		commonSrcFilesArg = "--common_srcs " + commonSrcsList.String()
177	}
178
179	kaptProcessorPath := flags.processorPath.FormRepeatedClassPath("-P plugin:org.jetbrains.kotlin.kapt3:apclasspath=")
180
181	kaptProcessor := ""
182	for i, p := range flags.processors {
183		if i > 0 {
184			kaptProcessor += " "
185		}
186		kaptProcessor += "-P plugin:org.jetbrains.kotlin.kapt3:processors=" + p
187	}
188
189	encodedJavacFlags := kaptEncodeFlags([][2]string{
190		{"-source", flags.javaVersion.String()},
191		{"-target", flags.javaVersion.String()},
192	})
193
194	kotlinName := filepath.Join(ctx.ModuleDir(), ctx.ModuleSubDir(), ctx.ModuleName())
195	kotlinName = strings.ReplaceAll(kotlinName, "/", "__")
196
197	ctx.Build(pctx, android.BuildParams{
198		Rule:           kapt,
199		Description:    "kapt",
200		Output:         srcJarOutputFile,
201		ImplicitOutput: resJarOutputFile,
202		Inputs:         srcFiles,
203		Implicits:      deps,
204		Args: map[string]string{
205			"classpath":         flags.kotlincClasspath.FormJavaClassPath(""),
206			"kotlincFlags":      flags.kotlincFlags,
207			"commonSrcFilesArg": commonSrcFilesArg,
208			"srcJars":           strings.Join(srcJars.Strings(), " "),
209			"srcJarDir":         android.PathForModuleOut(ctx, "kapt", "srcJars").String(),
210			"kotlinBuildFile":   android.PathForModuleOut(ctx, "kapt", "build.xml").String(),
211			"kaptProcessorPath": strings.Join(kaptProcessorPath, " "),
212			"kaptProcessor":     kaptProcessor,
213			"kaptDir":           android.PathForModuleOut(ctx, "kapt/gen").String(),
214			"encodedJavacFlags": encodedJavacFlags,
215			"name":              kotlinName,
216			"classesJarOut":     resJarOutputFile.String(),
217		},
218	})
219}
220
221// kapt converts a list of key, value pairs into a base64 encoded Java serialization, which is what kapt expects.
222func kaptEncodeFlags(options [][2]string) string {
223	buf := &bytes.Buffer{}
224
225	binary.Write(buf, binary.BigEndian, uint32(len(options)))
226	for _, option := range options {
227		binary.Write(buf, binary.BigEndian, uint16(len(option[0])))
228		buf.WriteString(option[0])
229		binary.Write(buf, binary.BigEndian, uint16(len(option[1])))
230		buf.WriteString(option[1])
231	}
232
233	header := &bytes.Buffer{}
234	header.Write([]byte{0xac, 0xed, 0x00, 0x05}) // java serialization header
235
236	if buf.Len() < 256 {
237		header.WriteByte(0x77) // blockdata
238		header.WriteByte(byte(buf.Len()))
239	} else {
240		header.WriteByte(0x7a) // blockdatalong
241		binary.Write(header, binary.BigEndian, uint32(buf.Len()))
242	}
243
244	return base64.StdEncoding.EncodeToString(append(header.Bytes(), buf.Bytes()...))
245}
246