1// Copyright (C) 2019 The Android Open Source Project
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 apex
16
17import (
18	"fmt"
19	"io"
20	"path/filepath"
21	"strings"
22
23	"android/soong/android"
24	"android/soong/cc"
25	"android/soong/java"
26	"android/soong/rust"
27)
28
29func (a *apexBundle) AndroidMk() android.AndroidMkData {
30	if a.properties.HideFromMake {
31		return android.AndroidMkData{
32			Disabled: true,
33		}
34	}
35	return a.androidMkForType()
36}
37
38// nameInMake converts apexFileClass into the corresponding class name in Make.
39func (class apexFileClass) nameInMake() string {
40	switch class {
41	case etc:
42		return "ETC"
43	case nativeSharedLib:
44		return "SHARED_LIBRARIES"
45	case nativeExecutable, shBinary:
46		return "EXECUTABLES"
47	case javaSharedLib:
48		return "JAVA_LIBRARIES"
49	case nativeTest:
50		return "NATIVE_TESTS"
51	case app, appSet:
52		// b/142537672 Why isn't this APP? We want to have full control over
53		// the paths and file names of the apk file under the flattend APEX.
54		// If this is set to APP, then the paths and file names are modified
55		// by the Make build system. For example, it is installed to
56		// /system/apex/<apexname>/app/<Appname>/<apexname>.<Appname>/ instead of
57		// /system/apex/<apexname>/app/<Appname> because the build system automatically
58		// appends module name (which is <apexname>.<Appname> to the path.
59		return "ETC"
60	default:
61		panic(fmt.Errorf("unknown class %d", class))
62	}
63}
64
65// Return the full module name for a dependency module, which appends the apex module name unless re-using a system lib.
66func (a *apexBundle) fullModuleName(apexBundleName string, linkToSystemLib bool, fi *apexFile) string {
67	if linkToSystemLib {
68		return fi.androidMkModuleName
69	}
70	return fi.androidMkModuleName + "." + apexBundleName
71}
72
73// androidMkForFiles generates Make definitions for the contents of an
74// apexBundle (apexBundle#filesInfo).  The filesInfo structure can either be
75// populated by Soong for unconverted APEXes, or Bazel in mixed mode. Use
76// apexFile#isBazelPrebuilt to differentiate.
77func (a *apexBundle) androidMkForFiles(w io.Writer, apexBundleName, moduleDir string,
78	apexAndroidMkData android.AndroidMkData) []string {
79
80	// apexBundleName comes from the 'name' property or soong module.
81	// apexName comes from 'name' property of apex_manifest.
82	// An apex is installed to /system/apex/<apexBundleName> and is activated at /apex/<apexName>
83	// In many cases, the two names are the same, but could be different in general.
84	// However, symbol files for apex files are installed under /apex/<apexBundleName> to avoid
85	// conflicts between two apexes with the same apexName.
86
87	moduleNames := []string{}
88
89	for _, fi := range a.filesInfo {
90		linkToSystemLib := a.linkToSystemLib && fi.transitiveDep && fi.availableToPlatform()
91		moduleName := a.fullModuleName(apexBundleName, linkToSystemLib, &fi)
92
93		// This name will be added to LOCAL_REQUIRED_MODULES of the APEX. We need to be
94		// arch-specific otherwise we will end up installing both ABIs even when only
95		// either of the ABI is requested.
96		aName := moduleName
97		switch fi.multilib {
98		case "lib32":
99			aName = aName + ":32"
100		case "lib64":
101			aName = aName + ":64"
102		}
103		if !android.InList(aName, moduleNames) {
104			moduleNames = append(moduleNames, aName)
105		}
106
107		if linkToSystemLib {
108			// No need to copy the file since it's linked to the system file
109			continue
110		}
111
112		fmt.Fprintln(w, "\ninclude $(CLEAR_VARS)  # apex.apexBundle.files")
113		if fi.moduleDir != "" {
114			fmt.Fprintln(w, "LOCAL_PATH :=", fi.moduleDir)
115		} else {
116			fmt.Fprintln(w, "LOCAL_PATH :=", moduleDir)
117		}
118		fmt.Fprintln(w, "LOCAL_MODULE :=", moduleName)
119
120		if fi.module != nil && fi.module.Owner() != "" {
121			fmt.Fprintln(w, "LOCAL_MODULE_OWNER :=", fi.module.Owner())
122		}
123		// /apex/<apexBundleName>/{lib|framework|...}
124		pathForSymbol := filepath.Join("$(PRODUCT_OUT)", "apex", apexBundleName, fi.installDir)
125		modulePath := pathForSymbol
126		fmt.Fprintln(w, "LOCAL_MODULE_PATH :=", modulePath)
127		// AconfigUpdateAndroidMkData may have added elements to Extra.  Process them here.
128		for _, extra := range apexAndroidMkData.Extra {
129			extra(w, fi.builtFile)
130		}
131
132		// For non-flattend APEXes, the merged notice file is attached to the APEX itself.
133		// We don't need to have notice file for the individual modules in it. Otherwise,
134		// we will have duplicated notice entries.
135		fmt.Fprintln(w, "LOCAL_NO_NOTICE_FILE := true")
136		fmt.Fprintln(w, "LOCAL_SOONG_INSTALLED_MODULE :=", filepath.Join(modulePath, fi.stem()))
137		fmt.Fprintln(w, "LOCAL_SOONG_INSTALL_PAIRS :=", fi.builtFile.String()+":"+filepath.Join(modulePath, fi.stem()))
138		fmt.Fprintln(w, "LOCAL_PREBUILT_MODULE_FILE :=", fi.builtFile.String())
139		fmt.Fprintln(w, "LOCAL_MODULE_CLASS :=", fi.class.nameInMake())
140		if fi.module != nil {
141			// This apexFile's module comes from Soong
142			if fi.module.Target().Arch.ArchType != android.Common {
143				archStr := fi.module.Target().Arch.ArchType.String()
144				fmt.Fprintln(w, "LOCAL_MODULE_TARGET_ARCH :=", archStr)
145			}
146		}
147		if fi.jacocoReportClassesFile != nil {
148			fmt.Fprintln(w, "LOCAL_SOONG_JACOCO_REPORT_CLASSES_JAR :=", fi.jacocoReportClassesFile.String())
149		}
150		switch fi.class {
151		case javaSharedLib:
152			// soong_java_prebuilt.mk sets LOCAL_MODULE_SUFFIX := .jar  Therefore
153			// we need to remove the suffix from LOCAL_MODULE_STEM, otherwise
154			// we will have foo.jar.jar
155			fmt.Fprintln(w, "LOCAL_MODULE_STEM :=", strings.TrimSuffix(fi.stem(), ".jar"))
156			if javaModule, ok := fi.module.(java.ApexDependency); ok {
157				fmt.Fprintln(w, "LOCAL_SOONG_CLASSES_JAR :=", javaModule.ImplementationAndResourcesJars()[0].String())
158				fmt.Fprintln(w, "LOCAL_SOONG_HEADER_JAR :=", javaModule.HeaderJars()[0].String())
159			} else {
160				fmt.Fprintln(w, "LOCAL_SOONG_CLASSES_JAR :=", fi.builtFile.String())
161				fmt.Fprintln(w, "LOCAL_SOONG_HEADER_JAR :=", fi.builtFile.String())
162			}
163			fmt.Fprintln(w, "LOCAL_SOONG_DEX_JAR :=", fi.builtFile.String())
164			fmt.Fprintln(w, "LOCAL_DEX_PREOPT := false")
165			fmt.Fprintln(w, "include $(BUILD_SYSTEM)/soong_java_prebuilt.mk")
166		case app:
167			fmt.Fprintln(w, "LOCAL_CERTIFICATE :=", fi.certificate.AndroidMkString())
168			// soong_app_prebuilt.mk sets LOCAL_MODULE_SUFFIX := .apk  Therefore
169			// we need to remove the suffix from LOCAL_MODULE_STEM, otherwise
170			// we will have foo.apk.apk
171			fmt.Fprintln(w, "LOCAL_MODULE_STEM :=", strings.TrimSuffix(fi.stem(), ".apk"))
172			if app, ok := fi.module.(*java.AndroidApp); ok {
173				android.AndroidMkEmitAssignList(w, "LOCAL_PREBUILT_COVERAGE_ARCHIVE", app.JniCoverageOutputs().Strings())
174				if jniLibSymbols := app.JNISymbolsInstalls(modulePath); len(jniLibSymbols) > 0 {
175					fmt.Fprintln(w, "LOCAL_SOONG_JNI_LIBS_SYMBOLS :=", jniLibSymbols.String())
176				}
177			}
178			fmt.Fprintln(w, "include $(BUILD_SYSTEM)/soong_app_prebuilt.mk")
179		case appSet:
180			as, ok := fi.module.(*java.AndroidAppSet)
181			if !ok {
182				panic(fmt.Sprintf("Expected %s to be AndroidAppSet", fi.module))
183			}
184			fmt.Fprintln(w, "LOCAL_APK_SET_INSTALL_FILE :=", as.PackedAdditionalOutputs().String())
185			fmt.Fprintln(w, "LOCAL_APKCERTS_FILE :=", as.APKCertsFile().String())
186			fmt.Fprintln(w, "include $(BUILD_SYSTEM)/soong_android_app_set.mk")
187		case nativeSharedLib, nativeExecutable, nativeTest:
188			fmt.Fprintln(w, "LOCAL_MODULE_STEM :=", fi.stem())
189			if ccMod, ok := fi.module.(*cc.Module); ok {
190				if ccMod.UnstrippedOutputFile() != nil {
191					fmt.Fprintln(w, "LOCAL_SOONG_UNSTRIPPED_BINARY :=", ccMod.UnstrippedOutputFile().String())
192				}
193				ccMod.AndroidMkWriteAdditionalDependenciesForSourceAbiDiff(w)
194				if ccMod.CoverageOutputFile().Valid() {
195					fmt.Fprintln(w, "LOCAL_PREBUILT_COVERAGE_ARCHIVE :=", ccMod.CoverageOutputFile().String())
196				}
197			} else if rustMod, ok := fi.module.(*rust.Module); ok {
198				if rustMod.UnstrippedOutputFile() != nil {
199					fmt.Fprintln(w, "LOCAL_SOONG_UNSTRIPPED_BINARY :=", rustMod.UnstrippedOutputFile().String())
200				}
201			}
202			fmt.Fprintln(w, "include $(BUILD_SYSTEM)/soong_cc_rust_prebuilt.mk")
203		default:
204			fmt.Fprintln(w, "LOCAL_MODULE_STEM :=", fi.stem())
205			fmt.Fprintln(w, "include $(BUILD_PREBUILT)")
206		}
207
208		// m <module_name> will build <module_name>.<apex_name> as well.
209		if fi.androidMkModuleName != moduleName {
210			fmt.Fprintf(w, ".PHONY: %s\n", fi.androidMkModuleName)
211			fmt.Fprintf(w, "%s: %s\n", fi.androidMkModuleName, moduleName)
212		}
213	}
214	return moduleNames
215}
216
217func (a *apexBundle) writeRequiredModules(w io.Writer, moduleNames []string) {
218	var required []string
219	var targetRequired []string
220	var hostRequired []string
221	required = append(required, a.RequiredModuleNames()...)
222	targetRequired = append(targetRequired, a.TargetRequiredModuleNames()...)
223	hostRequired = append(hostRequired, a.HostRequiredModuleNames()...)
224	for _, fi := range a.filesInfo {
225		required = append(required, fi.requiredModuleNames...)
226		targetRequired = append(targetRequired, fi.targetRequiredModuleNames...)
227		hostRequired = append(hostRequired, fi.hostRequiredModuleNames...)
228	}
229	android.AndroidMkEmitAssignList(w, "LOCAL_REQUIRED_MODULES", moduleNames, a.makeModulesToInstall, required)
230	android.AndroidMkEmitAssignList(w, "LOCAL_TARGET_REQUIRED_MODULES", targetRequired)
231	android.AndroidMkEmitAssignList(w, "LOCAL_HOST_REQUIRED_MODULES", hostRequired)
232}
233
234func (a *apexBundle) androidMkForType() android.AndroidMkData {
235	return android.AndroidMkData{
236		// While we do not provide a value for `Extra`, AconfigUpdateAndroidMkData may add some, which we must honor.
237		Custom: func(w io.Writer, name, prefix, moduleDir string, data android.AndroidMkData) {
238			moduleNames := []string{}
239			if a.installable() {
240				moduleNames = a.androidMkForFiles(w, name, moduleDir, data)
241			}
242
243			fmt.Fprintln(w, "\ninclude $(CLEAR_VARS)  # apex.apexBundle")
244			fmt.Fprintln(w, "LOCAL_PATH :=", moduleDir)
245			fmt.Fprintln(w, "LOCAL_MODULE :=", name)
246			fmt.Fprintln(w, "LOCAL_MODULE_CLASS := ETC") // do we need a new class?
247			fmt.Fprintln(w, "LOCAL_PREBUILT_MODULE_FILE :=", a.outputFile.String())
248			fmt.Fprintln(w, "LOCAL_MODULE_PATH :=", a.installDir.String())
249			stemSuffix := imageApexSuffix
250			if a.isCompressed {
251				stemSuffix = imageCapexSuffix
252			}
253			fmt.Fprintln(w, "LOCAL_MODULE_STEM :=", name+stemSuffix)
254			fmt.Fprintln(w, "LOCAL_UNINSTALLABLE_MODULE :=", !a.installable())
255			if a.installable() {
256				fmt.Fprintln(w, "LOCAL_SOONG_INSTALLED_MODULE :=", a.installedFile.String())
257				fmt.Fprintln(w, "LOCAL_SOONG_INSTALL_PAIRS :=", a.outputFile.String()+":"+a.installedFile.String())
258				fmt.Fprintln(w, "LOCAL_SOONG_INSTALL_SYMLINKS := ", strings.Join(a.compatSymlinks.Strings(), " "))
259			}
260			fmt.Fprintln(w, "LOCAL_APEX_KEY_PATH := ", a.apexKeysPath.String())
261
262			// Because apex writes .mk with Custom(), we need to write manually some common properties
263			// which are available via data.Entries
264			commonProperties := []string{
265				"LOCAL_FULL_INIT_RC", "LOCAL_FULL_VINTF_FRAGMENTS",
266				"LOCAL_PROPRIETARY_MODULE", "LOCAL_VENDOR_MODULE", "LOCAL_ODM_MODULE", "LOCAL_PRODUCT_MODULE", "LOCAL_SYSTEM_EXT_MODULE",
267				"LOCAL_MODULE_OWNER",
268			}
269			for _, name := range commonProperties {
270				if value, ok := data.Entries.EntryMap[name]; ok {
271					android.AndroidMkEmitAssignList(w, name, value)
272				}
273			}
274
275			android.AndroidMkEmitAssignList(w, "LOCAL_OVERRIDES_MODULES", a.overridableProperties.Overrides)
276			a.writeRequiredModules(w, moduleNames)
277			// AconfigUpdateAndroidMkData may have added elements to Extra.  Process them here.
278			for _, extra := range data.Extra {
279				extra(w, a.outputFile)
280			}
281
282			fmt.Fprintln(w, "include $(BUILD_PREBUILT)")
283			fmt.Fprintln(w, "ALL_MODULES.$(my_register_name).BUNDLE :=", a.bundleModuleFile.String())
284			android.AndroidMkEmitAssignList(w, "ALL_MODULES.$(my_register_name).LINT_REPORTS", a.lintReports.Strings())
285
286			if a.installedFilesFile != nil {
287				goal := "checkbuild"
288				distFile := name + "-installed-files.txt"
289				fmt.Fprintln(w, ".PHONY:", goal)
290				fmt.Fprintf(w, "$(call dist-for-goals,%s,%s:%s)\n",
291					goal, a.installedFilesFile.String(), distFile)
292				fmt.Fprintf(w, "$(call declare-0p-target,%s)\n", a.installedFilesFile.String())
293			}
294			for _, dist := range data.Entries.GetDistForGoals(a) {
295				fmt.Fprintf(w, dist)
296			}
297
298			distCoverageFiles(w, "ndk_apis_usedby_apex", a.nativeApisUsedByModuleFile.String())
299			distCoverageFiles(w, "ndk_apis_backedby_apex", a.nativeApisBackedByModuleFile.String())
300			distCoverageFiles(w, "java_apis_used_by_apex", a.javaApisUsedByModuleFile.String())
301		}}
302}
303
304func distCoverageFiles(w io.Writer, dir string, distfile string) {
305	if distfile != "" {
306		goal := "apps_only"
307		fmt.Fprintf(w, "ifneq (,$(filter $(my_register_name),$(TARGET_BUILD_APPS)))\n"+
308			" $(call dist-for-goals,%s,%s:%s/$(notdir %s))\n"+
309			"endif\n", goal, distfile, dir, distfile)
310	}
311}
312