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
27	"github.com/google/blueprint/proptools"
28)
29
30func (a *apexBundle) AndroidMk() android.AndroidMkData {
31	if a.properties.HideFromMake {
32		return android.AndroidMkData{
33			Disabled: true,
34		}
35	}
36	return a.androidMkForType()
37}
38
39func (a *apexBundle) androidMkForFiles(w io.Writer, apexBundleName, apexName, moduleDir string) []string {
40	// apexBundleName comes from the 'name' property; apexName comes from 'apex_name' property.
41	// An apex is installed to /system/apex/<apexBundleName> and is activated at /apex/<apexName>
42	// In many cases, the two names are the same, but could be different in general.
43
44	moduleNames := []string{}
45	apexType := a.properties.ApexType
46	// To avoid creating duplicate build rules, run this function only when primaryApexType is true
47	// to install symbol files in $(PRODUCT_OUT}/apex.
48	// And if apexType is flattened, run this function to install files in $(PRODUCT_OUT}/system/apex.
49	if !a.primaryApexType && apexType != flattenedApex {
50		return moduleNames
51	}
52
53	// b/162366062. Prevent GKI APEXes to emit make rules to avoid conflicts.
54	if strings.HasPrefix(apexName, "com.android.gki.") && apexType != flattenedApex {
55		return moduleNames
56	}
57
58	// b/140136207. When there are overriding APEXes for a VNDK APEX, the symbols file for the overridden
59	// APEX and the overriding APEX will have the same installation paths at /apex/com.android.vndk.v<ver>
60	// as their apexName will be the same. To avoid the path conflicts, skip installing the symbol files
61	// for the overriding VNDK APEXes.
62	symbolFilesNotNeeded := a.vndkApex && len(a.overridableProperties.Overrides) > 0
63	if symbolFilesNotNeeded && apexType != flattenedApex {
64		return moduleNames
65	}
66
67	var postInstallCommands []string
68	for _, fi := range a.filesInfo {
69		if a.linkToSystemLib && fi.transitiveDep && fi.AvailableToPlatform() {
70			// TODO(jiyong): pathOnDevice should come from fi.module, not being calculated here
71			linkTarget := filepath.Join("/system", fi.Path())
72			linkPath := filepath.Join(a.installDir.ToMakePath().String(), apexBundleName, fi.Path())
73			mkdirCmd := "mkdir -p " + filepath.Dir(linkPath)
74			linkCmd := "ln -sfn " + linkTarget + " " + linkPath
75			postInstallCommands = append(postInstallCommands, mkdirCmd, linkCmd)
76		}
77	}
78
79	seenDataOutPaths := make(map[string]bool)
80
81	for _, fi := range a.filesInfo {
82		if ccMod, ok := fi.module.(*cc.Module); ok && ccMod.Properties.HideFromMake {
83			continue
84		}
85
86		linkToSystemLib := a.linkToSystemLib && fi.transitiveDep && fi.AvailableToPlatform()
87
88		var moduleName string
89		if linkToSystemLib {
90			moduleName = fi.androidMkModuleName
91		} else {
92			moduleName = fi.androidMkModuleName + "." + apexBundleName + a.suffix
93		}
94
95		if !android.InList(moduleName, moduleNames) {
96			moduleNames = append(moduleNames, moduleName)
97		}
98
99		if linkToSystemLib {
100			// No need to copy the file since it's linked to the system file
101			continue
102		}
103
104		fmt.Fprintln(w, "\ninclude $(CLEAR_VARS)")
105		if fi.moduleDir != "" {
106			fmt.Fprintln(w, "LOCAL_PATH :=", fi.moduleDir)
107		} else {
108			fmt.Fprintln(w, "LOCAL_PATH :=", moduleDir)
109		}
110		fmt.Fprintln(w, "LOCAL_MODULE :=", moduleName)
111		// /apex/<apex_name>/{lib|framework|...}
112		pathWhenActivated := filepath.Join("$(PRODUCT_OUT)", "apex", apexName, fi.installDir)
113		var modulePath string
114		if apexType == flattenedApex {
115			// /system/apex/<name>/{lib|framework|...}
116			modulePath = filepath.Join(a.installDir.ToMakePath().String(), apexBundleName, fi.installDir)
117			fmt.Fprintln(w, "LOCAL_MODULE_PATH :=", modulePath)
118			if a.primaryApexType && !symbolFilesNotNeeded {
119				fmt.Fprintln(w, "LOCAL_SOONG_SYMBOL_PATH :=", pathWhenActivated)
120			}
121			if len(fi.symlinks) > 0 {
122				fmt.Fprintln(w, "LOCAL_MODULE_SYMLINKS :=", strings.Join(fi.symlinks, " "))
123			}
124			newDataPaths := []android.DataPath{}
125			for _, path := range fi.dataPaths {
126				dataOutPath := modulePath + ":" + path.SrcPath.Rel()
127				if ok := seenDataOutPaths[dataOutPath]; !ok {
128					newDataPaths = append(newDataPaths, path)
129					seenDataOutPaths[dataOutPath] = true
130				}
131			}
132			if len(newDataPaths) > 0 {
133				fmt.Fprintln(w, "LOCAL_TEST_DATA :=", strings.Join(cc.AndroidMkDataPaths(newDataPaths), " "))
134			}
135
136			if fi.module != nil && len(fi.module.NoticeFiles()) > 0 {
137				fmt.Fprintln(w, "LOCAL_NOTICE_FILE :=", strings.Join(fi.module.NoticeFiles().Strings(), " "))
138			}
139		} else {
140			modulePath = pathWhenActivated
141			fmt.Fprintln(w, "LOCAL_MODULE_PATH :=", pathWhenActivated)
142
143			// For non-flattend APEXes, the merged notice file is attached to the APEX itself.
144			// We don't need to have notice file for the individual modules in it. Otherwise,
145			// we will have duplicated notice entries.
146			fmt.Fprintln(w, "LOCAL_NO_NOTICE_FILE := true")
147		}
148		fmt.Fprintln(w, "LOCAL_PREBUILT_MODULE_FILE :=", fi.builtFile.String())
149		fmt.Fprintln(w, "LOCAL_MODULE_CLASS :=", fi.class.NameInMake())
150		if fi.module != nil {
151			archStr := fi.module.Target().Arch.ArchType.String()
152			host := false
153			switch fi.module.Target().Os.Class {
154			case android.Host:
155				if fi.module.Target().Arch.ArchType != android.Common {
156					fmt.Fprintln(w, "LOCAL_MODULE_HOST_ARCH :=", archStr)
157				}
158				host = true
159			case android.HostCross:
160				if fi.module.Target().Arch.ArchType != android.Common {
161					fmt.Fprintln(w, "LOCAL_MODULE_HOST_CROSS_ARCH :=", archStr)
162				}
163				host = true
164			case android.Device:
165				if fi.module.Target().Arch.ArchType != android.Common {
166					fmt.Fprintln(w, "LOCAL_MODULE_TARGET_ARCH :=", archStr)
167				}
168			}
169			if host {
170				makeOs := fi.module.Target().Os.String()
171				if fi.module.Target().Os == android.Linux || fi.module.Target().Os == android.LinuxBionic {
172					makeOs = "linux"
173				}
174				fmt.Fprintln(w, "LOCAL_MODULE_HOST_OS :=", makeOs)
175				fmt.Fprintln(w, "LOCAL_IS_HOST_MODULE := true")
176			}
177		}
178		if fi.jacocoReportClassesFile != nil {
179			fmt.Fprintln(w, "LOCAL_SOONG_JACOCO_REPORT_CLASSES_JAR :=", fi.jacocoReportClassesFile.String())
180		}
181		switch fi.class {
182		case javaSharedLib:
183			// soong_java_prebuilt.mk sets LOCAL_MODULE_SUFFIX := .jar  Therefore
184			// we need to remove the suffix from LOCAL_MODULE_STEM, otherwise
185			// we will have foo.jar.jar
186			fmt.Fprintln(w, "LOCAL_MODULE_STEM :=", strings.TrimSuffix(fi.Stem(), ".jar"))
187			if javaModule, ok := fi.module.(java.ApexDependency); ok {
188				fmt.Fprintln(w, "LOCAL_SOONG_CLASSES_JAR :=", javaModule.ImplementationAndResourcesJars()[0].String())
189				fmt.Fprintln(w, "LOCAL_SOONG_HEADER_JAR :=", javaModule.HeaderJars()[0].String())
190			} else {
191				fmt.Fprintln(w, "LOCAL_SOONG_CLASSES_JAR :=", fi.builtFile.String())
192				fmt.Fprintln(w, "LOCAL_SOONG_HEADER_JAR :=", fi.builtFile.String())
193			}
194			fmt.Fprintln(w, "LOCAL_SOONG_DEX_JAR :=", fi.builtFile.String())
195			fmt.Fprintln(w, "LOCAL_DEX_PREOPT := false")
196			fmt.Fprintln(w, "include $(BUILD_SYSTEM)/soong_java_prebuilt.mk")
197		case app:
198			fmt.Fprintln(w, "LOCAL_CERTIFICATE :=", fi.certificate.AndroidMkString())
199			// soong_app_prebuilt.mk sets LOCAL_MODULE_SUFFIX := .apk  Therefore
200			// we need to remove the suffix from LOCAL_MODULE_STEM, otherwise
201			// we will have foo.apk.apk
202			fmt.Fprintln(w, "LOCAL_MODULE_STEM :=", strings.TrimSuffix(fi.Stem(), ".apk"))
203			if app, ok := fi.module.(*java.AndroidApp); ok {
204				if jniCoverageOutputs := app.JniCoverageOutputs(); len(jniCoverageOutputs) > 0 {
205					fmt.Fprintln(w, "LOCAL_PREBUILT_COVERAGE_ARCHIVE :=", strings.Join(jniCoverageOutputs.Strings(), " "))
206				}
207				if jniLibSymbols := app.JNISymbolsInstalls(modulePath); len(jniLibSymbols) > 0 {
208					fmt.Fprintln(w, "LOCAL_SOONG_JNI_LIBS_SYMBOLS :=", jniLibSymbols.String())
209				}
210			}
211			fmt.Fprintln(w, "include $(BUILD_SYSTEM)/soong_app_prebuilt.mk")
212		case appSet:
213			as, ok := fi.module.(*java.AndroidAppSet)
214			if !ok {
215				panic(fmt.Sprintf("Expected %s to be AndroidAppSet", fi.module))
216			}
217			fmt.Fprintln(w, "LOCAL_APK_SET_INSTALL_FILE :=", as.InstallFile())
218			fmt.Fprintln(w, "LOCAL_APKCERTS_FILE :=", as.APKCertsFile().String())
219			fmt.Fprintln(w, "include $(BUILD_SYSTEM)/soong_android_app_set.mk")
220		case nativeSharedLib, nativeExecutable, nativeTest:
221			fmt.Fprintln(w, "LOCAL_MODULE_STEM :=", fi.Stem())
222			if ccMod, ok := fi.module.(*cc.Module); ok {
223				if ccMod.UnstrippedOutputFile() != nil {
224					fmt.Fprintln(w, "LOCAL_SOONG_UNSTRIPPED_BINARY :=", ccMod.UnstrippedOutputFile().String())
225				}
226				ccMod.AndroidMkWriteAdditionalDependenciesForSourceAbiDiff(w)
227				if ccMod.CoverageOutputFile().Valid() {
228					fmt.Fprintln(w, "LOCAL_PREBUILT_COVERAGE_ARCHIVE :=", ccMod.CoverageOutputFile().String())
229				}
230			}
231			fmt.Fprintln(w, "include $(BUILD_SYSTEM)/soong_cc_prebuilt.mk")
232		default:
233			fmt.Fprintln(w, "LOCAL_MODULE_STEM :=", fi.Stem())
234			if fi.builtFile == a.manifestPbOut && apexType == flattenedApex {
235				if a.primaryApexType {
236					// Make apex_manifest.pb module for this APEX to override all other
237					// modules in the APEXes being overridden by this APEX
238					var patterns []string
239					for _, o := range a.overridableProperties.Overrides {
240						patterns = append(patterns, "%."+o+a.suffix)
241					}
242					if len(patterns) > 0 {
243						fmt.Fprintln(w, "LOCAL_OVERRIDES_MODULES :=", strings.Join(patterns, " "))
244					}
245					if len(a.compatSymlinks) > 0 {
246						// For flattened apexes, compat symlinks are attached to apex_manifest.json which is guaranteed for every apex
247						postInstallCommands = append(postInstallCommands, a.compatSymlinks...)
248					}
249				}
250				if len(postInstallCommands) > 0 {
251					fmt.Fprintln(w, "LOCAL_POST_INSTALL_CMD :=", strings.Join(postInstallCommands, " && "))
252				}
253			}
254			fmt.Fprintln(w, "include $(BUILD_PREBUILT)")
255		}
256
257		// m <module_name> will build <module_name>.<apex_name> as well.
258		if fi.androidMkModuleName != moduleName && a.primaryApexType {
259			fmt.Fprintf(w, ".PHONY: %s\n", fi.androidMkModuleName)
260			fmt.Fprintf(w, "%s: %s\n", fi.androidMkModuleName, moduleName)
261		}
262	}
263	return moduleNames
264}
265
266func (a *apexBundle) writeRequiredModules(w io.Writer) {
267	var required []string
268	var targetRequired []string
269	var hostRequired []string
270	for _, fi := range a.filesInfo {
271		required = append(required, fi.requiredModuleNames...)
272		targetRequired = append(targetRequired, fi.targetRequiredModuleNames...)
273		hostRequired = append(hostRequired, fi.hostRequiredModuleNames...)
274	}
275
276	if len(required) > 0 {
277		fmt.Fprintln(w, "LOCAL_REQUIRED_MODULES +=", strings.Join(required, " "))
278	}
279	if len(targetRequired) > 0 {
280		fmt.Fprintln(w, "LOCAL_TARGET_REQUIRED_MODULES +=", strings.Join(targetRequired, " "))
281	}
282	if len(hostRequired) > 0 {
283		fmt.Fprintln(w, "LOCAL_HOST_REQUIRED_MODULES +=", strings.Join(hostRequired, " "))
284	}
285}
286
287func (a *apexBundle) androidMkForType() android.AndroidMkData {
288	return android.AndroidMkData{
289		Custom: func(w io.Writer, name, prefix, moduleDir string, data android.AndroidMkData) {
290			moduleNames := []string{}
291			apexType := a.properties.ApexType
292			if a.installable() {
293				apexName := proptools.StringDefault(a.properties.Apex_name, name)
294				moduleNames = a.androidMkForFiles(w, name, apexName, moduleDir)
295			}
296
297			if apexType == flattenedApex {
298				// Only image APEXes can be flattened.
299				fmt.Fprintln(w, "\ninclude $(CLEAR_VARS)")
300				fmt.Fprintln(w, "LOCAL_PATH :=", moduleDir)
301				fmt.Fprintln(w, "LOCAL_MODULE :=", name+a.suffix)
302				if len(moduleNames) > 0 {
303					fmt.Fprintln(w, "LOCAL_REQUIRED_MODULES :=", strings.Join(moduleNames, " "))
304				}
305				a.writeRequiredModules(w)
306				fmt.Fprintln(w, "include $(BUILD_PHONY_PACKAGE)")
307
308			} else {
309				fmt.Fprintln(w, "\ninclude $(CLEAR_VARS)")
310				fmt.Fprintln(w, "LOCAL_PATH :=", moduleDir)
311				fmt.Fprintln(w, "LOCAL_MODULE :=", name+a.suffix)
312				fmt.Fprintln(w, "LOCAL_MODULE_CLASS := ETC") // do we need a new class?
313				fmt.Fprintln(w, "LOCAL_PREBUILT_MODULE_FILE :=", a.outputFile.String())
314				fmt.Fprintln(w, "LOCAL_MODULE_PATH :=", a.installDir.ToMakePath().String())
315				fmt.Fprintln(w, "LOCAL_MODULE_STEM :=", name+apexType.suffix())
316				fmt.Fprintln(w, "LOCAL_UNINSTALLABLE_MODULE :=", !a.installable())
317
318				// Because apex writes .mk with Custom(), we need to write manually some common properties
319				// which are available via data.Entries
320				commonProperties := []string{
321					"LOCAL_INIT_RC", "LOCAL_VINTF_FRAGMENTS",
322					"LOCAL_PROPRIETARY_MODULE", "LOCAL_VENDOR_MODULE", "LOCAL_ODM_MODULE", "LOCAL_PRODUCT_MODULE", "LOCAL_SYSTEM_EXT_MODULE",
323					"LOCAL_MODULE_OWNER",
324				}
325				for _, name := range commonProperties {
326					if value, ok := data.Entries.EntryMap[name]; ok {
327						fmt.Fprintln(w, name+" := "+strings.Join(value, " "))
328					}
329				}
330
331				if len(a.overridableProperties.Overrides) > 0 {
332					fmt.Fprintln(w, "LOCAL_OVERRIDES_MODULES :=", strings.Join(a.overridableProperties.Overrides, " "))
333				}
334				if len(moduleNames) > 0 {
335					fmt.Fprintln(w, "LOCAL_REQUIRED_MODULES +=", strings.Join(moduleNames, " "))
336				}
337				if len(a.requiredDeps) > 0 {
338					fmt.Fprintln(w, "LOCAL_REQUIRED_MODULES +=", strings.Join(a.requiredDeps, " "))
339				}
340				a.writeRequiredModules(w)
341				var postInstallCommands []string
342				if a.prebuiltFileToDelete != "" {
343					postInstallCommands = append(postInstallCommands, "rm -rf "+
344						filepath.Join(a.installDir.ToMakePath().String(), a.prebuiltFileToDelete))
345				}
346				// For unflattened apexes, compat symlinks are attached to apex package itself as LOCAL_POST_INSTALL_CMD
347				postInstallCommands = append(postInstallCommands, a.compatSymlinks...)
348				if len(postInstallCommands) > 0 {
349					fmt.Fprintln(w, "LOCAL_POST_INSTALL_CMD :=", strings.Join(postInstallCommands, " && "))
350				}
351
352				if a.mergedNotices.Merged.Valid() {
353					fmt.Fprintln(w, "LOCAL_NOTICE_FILE :=", a.mergedNotices.Merged.Path().String())
354				}
355
356				fmt.Fprintln(w, "include $(BUILD_PREBUILT)")
357
358				if apexType == imageApex {
359					fmt.Fprintln(w, "ALL_MODULES.$(my_register_name).BUNDLE :=", a.bundleModuleFile.String())
360				}
361				if len(a.lintReports) > 0 {
362					fmt.Fprintln(w, "ALL_MODULES.$(my_register_name).LINT_REPORTS :=",
363						strings.Join(a.lintReports.Strings(), " "))
364				}
365
366				if a.installedFilesFile != nil {
367					goal := "checkbuild"
368					distFile := name + "-installed-files.txt"
369					fmt.Fprintln(w, ".PHONY:", goal)
370					fmt.Fprintf(w, "$(call dist-for-goals,%s,%s:%s)\n",
371						goal, a.installedFilesFile.String(), distFile)
372				}
373			}
374		}}
375}
376