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