blob: 5fb0cd167b5f2135ea81990753d1203927f9230e [file] [log] [blame]
Dan Willemsen218f6562015-07-08 18:13:11 -07001// Copyright 2015 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
Jaewoong Jung7ef4a902020-11-16 12:50:29 -080015// This file offers AndroidMkEntriesProvider, which individual modules implement to output
16// Android.mk entries that contain information about the modules built through Soong. Kati reads
17// and combines them with the legacy Make-based module definitions to produce the complete view of
18// the source tree, which makes this a critical point of Make-Soong interoperability.
19//
20// Naturally, Soong-only builds do not rely on this mechanism.
21
Colin Cross635c3b02016-05-18 15:37:25 -070022package android
Dan Willemsen218f6562015-07-08 18:13:11 -070023
24import (
25 "bytes"
Dan Willemsen97750522016-02-09 17:43:51 -080026 "fmt"
Dan Willemsen218f6562015-07-08 18:13:11 -070027 "io"
Dan Willemsen218f6562015-07-08 18:13:11 -070028 "os"
29 "path/filepath"
Bob Badourb4999222021-01-07 03:34:31 +000030 "reflect"
Dan Willemsendef7b5d2021-10-17 00:22:33 -070031 "runtime"
Dan Willemsen218f6562015-07-08 18:13:11 -070032 "sort"
Colin Crossd6fd0132023-11-06 13:54:06 -080033 "strconv"
Dan Willemsen0fda89f2016-06-01 15:25:32 -070034 "strings"
Dan Willemsen218f6562015-07-08 18:13:11 -070035
Dan Willemsen218f6562015-07-08 18:13:11 -070036 "github.com/google/blueprint"
Colin Cross2465c3d2018-09-28 10:19:18 -070037 "github.com/google/blueprint/bootstrap"
Colin Cross836e3872021-11-09 12:30:59 -080038 "github.com/google/blueprint/pathtools"
Jiyong Park3f627e62024-05-01 16:14:38 +090039 "github.com/google/blueprint/proptools"
Dan Willemsen218f6562015-07-08 18:13:11 -070040)
41
42func init() {
Paul Duffin8c3fec42020-03-04 20:15:08 +000043 RegisterAndroidMkBuildComponents(InitRegistrationContext)
44}
45
46func RegisterAndroidMkBuildComponents(ctx RegistrationContext) {
LaMont Jones0c10e4d2023-05-16 00:58:37 +000047 ctx.RegisterParallelSingletonType("androidmk", AndroidMkSingleton)
Dan Willemsen218f6562015-07-08 18:13:11 -070048}
49
Paul Duffin6c9da042021-03-07 15:44:41 +000050// Enable androidmk support.
51// * Register the singleton
52// * Configure that we are inside make
53var PrepareForTestWithAndroidMk = GroupFixturePreparers(
54 FixtureRegisterWithContext(RegisterAndroidMkBuildComponents),
55 FixtureModifyConfig(SetKatiEnabledForTests),
56)
57
Jaewoong Jung7ef4a902020-11-16 12:50:29 -080058// Deprecated: Use AndroidMkEntriesProvider instead, especially if you're not going to use the
59// Custom function. It's easier to use and test.
Dan Willemsen218f6562015-07-08 18:13:11 -070060type AndroidMkDataProvider interface {
Colin Crossa18e9cf2017-08-10 17:00:19 -070061 AndroidMk() AndroidMkData
Colin Crossce75d2c2016-10-06 16:12:58 -070062 BaseModuleName() string
Dan Willemsen218f6562015-07-08 18:13:11 -070063}
64
65type AndroidMkData struct {
Sasha Smundakb6d23052019-04-01 18:37:36 -070066 Class string
67 SubName string
Jingwen Chen40fd90a2020-06-15 05:24:19 +000068 DistFiles TaggedDistFiles
Sasha Smundakb6d23052019-04-01 18:37:36 -070069 OutputFile OptionalPath
70 Disabled bool
71 Include string
72 Required []string
73 Host_required []string
74 Target_required []string
Dan Willemsen218f6562015-07-08 18:13:11 -070075
Colin Cross0f86d182017-08-10 17:07:28 -070076 Custom func(w io.Writer, name, prefix, moduleDir string, data AndroidMkData)
Dan Willemsen218f6562015-07-08 18:13:11 -070077
Colin Cross27a4b052017-08-10 16:32:23 -070078 Extra []AndroidMkExtraFunc
Colin Cross0f86d182017-08-10 17:07:28 -070079
Jooyung Han2ed99d02020-06-24 23:26:26 +090080 Entries AndroidMkEntries
Dan Willemsen218f6562015-07-08 18:13:11 -070081}
82
Colin Cross27a4b052017-08-10 16:32:23 -070083type AndroidMkExtraFunc func(w io.Writer, outputFile Path)
84
Jaewoong Jung7ef4a902020-11-16 12:50:29 -080085// Interface for modules to declare their Android.mk outputs. Note that every module needs to
86// implement this in order to be included in the final Android-<product_name>.mk output, even if
87// they only need to output the common set of entries without any customizations.
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -070088type AndroidMkEntriesProvider interface {
Jaewoong Jung7ef4a902020-11-16 12:50:29 -080089 // Returns AndroidMkEntries objects that contain all basic info plus extra customization data
90 // if needed. This is the core func to implement.
91 // Note that one can return multiple objects. For example, java_library may return an additional
92 // AndroidMkEntries object for its hostdex sub-module.
Jiyong Park0b0e1b92019-12-03 13:24:29 +090093 AndroidMkEntries() []AndroidMkEntries
Jaewoong Jung7ef4a902020-11-16 12:50:29 -080094 // Modules don't need to implement this as it's already implemented by ModuleBase.
95 // AndroidMkEntries uses BaseModuleName() instead of ModuleName() because certain modules
96 // e.g. Prebuilts, override the Name() func and return modified names.
97 // If a different name is preferred, use SubName or OverrideName in AndroidMkEntries.
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -070098 BaseModuleName() string
99}
100
Jaewoong Jung7ef4a902020-11-16 12:50:29 -0800101// The core data struct that modules use to provide their Android.mk data.
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700102type AndroidMkEntries struct {
Jaewoong Jung7ef4a902020-11-16 12:50:29 -0800103 // Android.mk class string, e.g EXECUTABLES, JAVA_LIBRARIES, ETC
104 Class string
105 // Optional suffix to append to the module name. Useful when a module wants to return multiple
106 // AndroidMkEntries objects. For example, when a java_library returns an additional entry for
107 // its hostdex sub-module, this SubName field is set to "-hostdex" so that it can have a
108 // different name than the parent's.
109 SubName string
110 // If set, this value overrides the base module name. SubName is still appended.
111 OverrideName string
112 // Dist files to output
113 DistFiles TaggedDistFiles
114 // The output file for Kati to process and/or install. If absent, the module is skipped.
115 OutputFile OptionalPath
116 // If true, the module is skipped and does not appear on the final Android-<product name>.mk
117 // file. Useful when a module needs to be skipped conditionally.
118 Disabled bool
Ivan Lozanod06cc742021-11-12 13:27:58 -0500119 // The postprocessing mk file to include, e.g. $(BUILD_SYSTEM)/soong_cc_rust_prebuilt.mk
Jaewoong Jung7ef4a902020-11-16 12:50:29 -0800120 // If not set, $(BUILD_SYSTEM)/prebuilt.mk is used.
121 Include string
122 // Required modules that need to be built and included in the final build output when building
123 // this module.
124 Required []string
125 // Required host modules that need to be built and included in the final build output when
126 // building this module.
127 Host_required []string
128 // Required device modules that need to be built and included in the final build output when
129 // building this module.
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700130 Target_required []string
131
132 header bytes.Buffer
133 footer bytes.Buffer
134
Jaewoong Jung7ef4a902020-11-16 12:50:29 -0800135 // Funcs to append additional Android.mk entries or modify the common ones. Multiple funcs are
136 // accepted so that common logic can be factored out as a shared func.
Jaewoong Junge0dc8df2019-08-27 17:33:16 -0700137 ExtraEntries []AndroidMkExtraEntriesFunc
Jaewoong Jung7ef4a902020-11-16 12:50:29 -0800138 // Funcs to add extra lines to the module's Android.mk output. Unlike AndroidMkExtraEntriesFunc,
139 // which simply sets Make variable values, this can be used for anything since it can write any
140 // Make statements directly to the final Android-*.mk file.
141 // Primarily used to call macros or declare/update Make targets.
Jaewoong Jungb0c127c2019-08-29 14:56:03 -0700142 ExtraFooters []AndroidMkExtraFootersFunc
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700143
Jaewoong Jung7ef4a902020-11-16 12:50:29 -0800144 // A map that holds the up-to-date Make variable values. Can be accessed from tests.
145 EntryMap map[string][]string
146 // A list of EntryMap keys in insertion order. This serves a few purposes:
147 // 1. Prevents churns. Golang map doesn't provide consistent iteration order, so without this,
148 // the outputted Android-*.mk file may change even though there have been no content changes.
149 // 2. Allows modules to refer to other variables, like LOCAL_BAR_VAR := $(LOCAL_FOO_VAR),
150 // without worrying about the variables being mixed up in the actual mk file.
151 // 3. Makes troubleshooting and spotting errors easier.
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700152 entryOrder []string
Trevor Radcliffe90727f42022-03-21 19:34:02 +0000153
154 // Provides data typically stored by Context objects that are commonly needed by
155 //AndroidMkEntries objects.
156 entryContext AndroidMkEntriesContext
157}
158
159type AndroidMkEntriesContext interface {
Yu Liuec810542024-08-26 18:09:15 +0000160 OtherModuleProviderContext
Trevor Radcliffe90727f42022-03-21 19:34:02 +0000161 Config() Config
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700162}
163
Colin Crossaa255532020-07-03 13:18:24 -0700164type AndroidMkExtraEntriesContext interface {
Colin Cross3c0a83d2023-12-12 14:13:26 -0800165 Provider(provider blueprint.AnyProviderKey) (any, bool)
Colin Crossaa255532020-07-03 13:18:24 -0700166}
167
168type androidMkExtraEntriesContext struct {
169 ctx fillInEntriesContext
170 mod blueprint.Module
171}
172
Colin Cross3c0a83d2023-12-12 14:13:26 -0800173func (a *androidMkExtraEntriesContext) Provider(provider blueprint.AnyProviderKey) (any, bool) {
Yu Liu663e4502024-08-12 18:23:59 +0000174 return a.ctx.otherModuleProvider(a.mod, provider)
Colin Crossaa255532020-07-03 13:18:24 -0700175}
176
177type AndroidMkExtraEntriesFunc func(ctx AndroidMkExtraEntriesContext, entries *AndroidMkEntries)
Jaewoong Jung02b11a62020-12-07 10:23:54 -0800178type AndroidMkExtraFootersFunc func(w io.Writer, name, prefix, moduleDir string)
Jaewoong Junge0dc8df2019-08-27 17:33:16 -0700179
Jaewoong Jung7ef4a902020-11-16 12:50:29 -0800180// Utility funcs to manipulate Android.mk variable entries.
181
182// SetString sets a Make variable with the given name to the given value.
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700183func (a *AndroidMkEntries) SetString(name, value string) {
184 if _, ok := a.EntryMap[name]; !ok {
185 a.entryOrder = append(a.entryOrder, name)
186 }
187 a.EntryMap[name] = []string{value}
188}
189
Jaewoong Jung7ef4a902020-11-16 12:50:29 -0800190// SetPath sets a Make variable with the given name to the given path string.
Jaewoong Jung9a1e8bd2019-09-04 20:17:54 -0700191func (a *AndroidMkEntries) SetPath(name string, path Path) {
192 if _, ok := a.EntryMap[name]; !ok {
193 a.entryOrder = append(a.entryOrder, name)
194 }
195 a.EntryMap[name] = []string{path.String()}
196}
197
Jaewoong Jung7ef4a902020-11-16 12:50:29 -0800198// SetOptionalPath sets a Make variable with the given name to the given path string if it is valid.
199// It is a no-op if the given path is invalid.
Colin Crossc0efd1d2020-07-03 11:56:24 -0700200func (a *AndroidMkEntries) SetOptionalPath(name string, path OptionalPath) {
201 if path.Valid() {
202 a.SetPath(name, path.Path())
203 }
204}
205
Jaewoong Jung7ef4a902020-11-16 12:50:29 -0800206// AddPath appends the given path string to a Make variable with the given name.
Colin Crossc0efd1d2020-07-03 11:56:24 -0700207func (a *AndroidMkEntries) AddPath(name string, path Path) {
208 if _, ok := a.EntryMap[name]; !ok {
209 a.entryOrder = append(a.entryOrder, name)
210 }
211 a.EntryMap[name] = append(a.EntryMap[name], path.String())
212}
213
Jaewoong Jung7ef4a902020-11-16 12:50:29 -0800214// AddOptionalPath appends the given path string to a Make variable with the given name if it is
215// valid. It is a no-op if the given path is invalid.
Colin Crossc0efd1d2020-07-03 11:56:24 -0700216func (a *AndroidMkEntries) AddOptionalPath(name string, path OptionalPath) {
217 if path.Valid() {
218 a.AddPath(name, path.Path())
219 }
220}
221
Jaewoong Jung7ef4a902020-11-16 12:50:29 -0800222// SetPaths sets a Make variable with the given name to a slice of the given path strings.
Colin Cross08dca382020-07-21 20:31:17 -0700223func (a *AndroidMkEntries) SetPaths(name string, paths Paths) {
224 if _, ok := a.EntryMap[name]; !ok {
225 a.entryOrder = append(a.entryOrder, name)
226 }
227 a.EntryMap[name] = paths.Strings()
228}
229
Jaewoong Jung7ef4a902020-11-16 12:50:29 -0800230// SetOptionalPaths sets a Make variable with the given name to a slice of the given path strings
231// only if there are a non-zero amount of paths.
Colin Cross08dca382020-07-21 20:31:17 -0700232func (a *AndroidMkEntries) SetOptionalPaths(name string, paths Paths) {
233 if len(paths) > 0 {
234 a.SetPaths(name, paths)
235 }
236}
237
Jaewoong Jung7ef4a902020-11-16 12:50:29 -0800238// AddPaths appends the given path strings to a Make variable with the given name.
Colin Cross08dca382020-07-21 20:31:17 -0700239func (a *AndroidMkEntries) AddPaths(name string, paths Paths) {
240 if _, ok := a.EntryMap[name]; !ok {
241 a.entryOrder = append(a.entryOrder, name)
242 }
243 a.EntryMap[name] = append(a.EntryMap[name], paths.Strings()...)
244}
245
Jaewoong Jung7ef4a902020-11-16 12:50:29 -0800246// SetBoolIfTrue sets a Make variable with the given name to true if the given flag is true.
247// It is a no-op if the given flag is false.
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700248func (a *AndroidMkEntries) SetBoolIfTrue(name string, flag bool) {
249 if flag {
250 if _, ok := a.EntryMap[name]; !ok {
251 a.entryOrder = append(a.entryOrder, name)
252 }
253 a.EntryMap[name] = []string{"true"}
254 }
255}
256
Jaewoong Jung7ef4a902020-11-16 12:50:29 -0800257// SetBool sets a Make variable with the given name to if the given bool flag value.
Jaewoong Jung9a1e8bd2019-09-04 20:17:54 -0700258func (a *AndroidMkEntries) SetBool(name string, flag bool) {
259 if _, ok := a.EntryMap[name]; !ok {
260 a.entryOrder = append(a.entryOrder, name)
261 }
262 if flag {
263 a.EntryMap[name] = []string{"true"}
264 } else {
265 a.EntryMap[name] = []string{"false"}
266 }
267}
268
Jaewoong Jung7ef4a902020-11-16 12:50:29 -0800269// AddStrings appends the given strings to a Make variable with the given name.
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700270func (a *AndroidMkEntries) AddStrings(name string, value ...string) {
271 if len(value) == 0 {
272 return
273 }
274 if _, ok := a.EntryMap[name]; !ok {
275 a.entryOrder = append(a.entryOrder, name)
276 }
277 a.EntryMap[name] = append(a.EntryMap[name], value...)
278}
279
Liz Kammer57f5b332020-11-24 12:42:58 -0800280// AddCompatibilityTestSuites adds the supplied test suites to the EntryMap, with special handling
Tongbo Liuc5f7b962024-01-04 09:03:35 +0000281// for partial MTS and MCTS test suites.
Liz Kammer57f5b332020-11-24 12:42:58 -0800282func (a *AndroidMkEntries) AddCompatibilityTestSuites(suites ...string) {
Tongbo Liuc5f7b962024-01-04 09:03:35 +0000283 // M(C)TS supports a full test suite and partial per-module MTS test suites, with naming mts-${MODULE}.
284 // To reduce repetition, if we find a partial M(C)TS test suite without an full M(C)TS test suite,
Liz Kammer57f5b332020-11-24 12:42:58 -0800285 // we add the full test suite to our list.
286 if PrefixInList(suites, "mts-") && !InList("mts", suites) {
287 suites = append(suites, "mts")
288 }
Tongbo Liuc5f7b962024-01-04 09:03:35 +0000289 if PrefixInList(suites, "mcts-") && !InList("mcts", suites) {
290 suites = append(suites, "mcts")
291 }
Liz Kammer57f5b332020-11-24 12:42:58 -0800292 a.AddStrings("LOCAL_COMPATIBILITY_SUITE", suites...)
293}
294
Paul Duffin8b0349c2020-11-26 14:33:21 +0000295// The contributions to the dist.
296type distContributions struct {
Bob Badour51804382022-04-13 11:27:19 -0700297 // Path to license metadata file.
298 licenseMetadataFile Path
Paul Duffin8b0349c2020-11-26 14:33:21 +0000299 // List of goals and the dist copy instructions.
300 copiesForGoals []*copiesForGoals
301}
302
303// getCopiesForGoals returns a copiesForGoals into which copy instructions that
304// must be processed when building one or more of those goals can be added.
305func (d *distContributions) getCopiesForGoals(goals string) *copiesForGoals {
306 copiesForGoals := &copiesForGoals{goals: goals}
307 d.copiesForGoals = append(d.copiesForGoals, copiesForGoals)
308 return copiesForGoals
309}
310
311// Associates a list of dist copy instructions with a set of goals for which they
312// should be run.
313type copiesForGoals struct {
314 // goals are a space separated list of build targets that will trigger the
315 // copy instructions.
316 goals string
317
318 // A list of instructions to copy a module's output files to somewhere in the
319 // dist directory.
320 copies []distCopy
321}
322
323// Adds a copy instruction.
324func (d *copiesForGoals) addCopyInstruction(from Path, dest string) {
325 d.copies = append(d.copies, distCopy{from, dest})
326}
327
328// Instruction on a path that must be copied into the dist.
329type distCopy struct {
330 // The path to copy from.
331 from Path
332
333 // The destination within the dist directory to copy to.
334 dest string
335}
336
337// Compute the contributions that the module makes to the dist.
338func (a *AndroidMkEntries) getDistContributions(mod blueprint.Module) *distContributions {
Jingwen Chen40fd90a2020-06-15 05:24:19 +0000339 amod := mod.(Module).base()
340 name := amod.BaseModuleName()
341
Paul Duffin74f05592020-11-25 16:37:46 +0000342 // Collate the set of associated tag/paths available for copying to the dist.
343 // Start with an empty (nil) set.
Jingwen Chen7b27ca72020-07-24 09:13:49 +0000344 var availableTaggedDists TaggedDistFiles
Jingwen Chen40fd90a2020-06-15 05:24:19 +0000345
Paul Duffin74f05592020-11-25 16:37:46 +0000346 // Then merge in any that are provided explicitly by the module.
Jingwen Chen84811862020-07-21 11:32:19 +0000347 if a.DistFiles != nil {
Paul Duffin74f05592020-11-25 16:37:46 +0000348 // Merge the DistFiles into the set.
349 availableTaggedDists = availableTaggedDists.merge(a.DistFiles)
350 }
351
352 // If no paths have been provided for the DefaultDistTag and the output file is
353 // valid then add that as the default dist path.
354 if _, ok := availableTaggedDists[DefaultDistTag]; !ok && a.OutputFile.Valid() {
355 availableTaggedDists = availableTaggedDists.addPathsForTag(DefaultDistTag, a.OutputFile.Path())
356 }
357
Yu Liuec810542024-08-26 18:09:15 +0000358 info := OtherModuleProviderOrDefault(a.entryContext, mod, InstallFilesProvider)
Paul Duffinaf970a22020-11-23 23:32:56 +0000359 // If the distFiles created by GenerateTaggedDistFiles contains paths for the
360 // DefaultDistTag then that takes priority so delete any existing paths.
Yu Liuec810542024-08-26 18:09:15 +0000361 if _, ok := info.DistFiles[DefaultDistTag]; ok {
Paul Duffinaf970a22020-11-23 23:32:56 +0000362 delete(availableTaggedDists, DefaultDistTag)
363 }
364
365 // Finally, merge the distFiles created by GenerateTaggedDistFiles.
Yu Liuec810542024-08-26 18:09:15 +0000366 availableTaggedDists = availableTaggedDists.merge(info.DistFiles)
Paul Duffinaf970a22020-11-23 23:32:56 +0000367
Paul Duffin74f05592020-11-25 16:37:46 +0000368 if len(availableTaggedDists) == 0 {
Jingwen Chen7b27ca72020-07-24 09:13:49 +0000369 // Nothing dist-able for this module.
370 return nil
Jingwen Chen40fd90a2020-06-15 05:24:19 +0000371 }
372
Paul Duffin8b0349c2020-11-26 14:33:21 +0000373 // Collate the contributions this module makes to the dist.
374 distContributions := &distContributions{}
375
Bob Badour4660a982022-09-12 16:06:03 -0700376 if !exemptFromRequiredApplicableLicensesProperty(mod.(Module)) {
Yu Liuec810542024-08-26 18:09:15 +0000377 distContributions.licenseMetadataFile = info.LicenseMetadataFile
Bob Badour4660a982022-09-12 16:06:03 -0700378 }
Bob Badour51804382022-04-13 11:27:19 -0700379
Jingwen Chen40fd90a2020-06-15 05:24:19 +0000380 // Iterate over this module's dist structs, merged from the dist and dists properties.
381 for _, dist := range amod.Dists() {
382 // Get the list of goals this dist should be enabled for. e.g. sdk, droidcore
383 goals := strings.Join(dist.Targets, " ")
384
385 // Get the tag representing the output files to be dist'd. e.g. ".jar", ".proguard_map"
386 var tag string
387 if dist.Tag == nil {
388 // If the dist struct does not specify a tag, use the default output files tag.
Paul Duffin74f05592020-11-25 16:37:46 +0000389 tag = DefaultDistTag
Jingwen Chen40fd90a2020-06-15 05:24:19 +0000390 } else {
391 tag = *dist.Tag
392 }
393
394 // Get the paths of the output files to be dist'd, represented by the tag.
395 // Can be an empty list.
396 tagPaths := availableTaggedDists[tag]
397 if len(tagPaths) == 0 {
398 // Nothing to dist for this tag, continue to the next dist.
399 continue
400 }
401
402 if len(tagPaths) > 1 && (dist.Dest != nil || dist.Suffix != nil) {
Paul Duffin74f05592020-11-25 16:37:46 +0000403 errorMessage := "%s: Cannot apply dest/suffix for more than one dist " +
404 "file for %q goals tag %q in module %s. The list of dist files, " +
Jingwen Chen40fd90a2020-06-15 05:24:19 +0000405 "which should have a single element, is:\n%s"
Paul Duffin74f05592020-11-25 16:37:46 +0000406 panic(fmt.Errorf(errorMessage, mod, goals, tag, name, tagPaths))
Jingwen Chen40fd90a2020-06-15 05:24:19 +0000407 }
408
Paul Duffin8b0349c2020-11-26 14:33:21 +0000409 copiesForGoals := distContributions.getCopiesForGoals(goals)
Jingwen Chen40fd90a2020-06-15 05:24:19 +0000410
Paul Duffin8b0349c2020-11-26 14:33:21 +0000411 // Iterate over each path adding a copy instruction to copiesForGoals
Jingwen Chen40fd90a2020-06-15 05:24:19 +0000412 for _, path := range tagPaths {
413 // It's possible that the Path is nil from errant modules. Be defensive here.
414 if path == nil {
415 tagName := "default" // for error message readability
416 if dist.Tag != nil {
417 tagName = *dist.Tag
418 }
419 panic(fmt.Errorf("Dist file should not be nil for the %s tag in %s", tagName, name))
420 }
421
422 dest := filepath.Base(path.String())
423
424 if dist.Dest != nil {
425 var err error
426 if dest, err = validateSafePath(*dist.Dest); err != nil {
427 // This was checked in ModuleBase.GenerateBuildActions
428 panic(err)
429 }
430 }
431
Trevor Radcliffe90727f42022-03-21 19:34:02 +0000432 ext := filepath.Ext(dest)
433 suffix := ""
Jingwen Chen40fd90a2020-06-15 05:24:19 +0000434 if dist.Suffix != nil {
Trevor Radcliffe90727f42022-03-21 19:34:02 +0000435 suffix = *dist.Suffix
436 }
437
438 productString := ""
439 if dist.Append_artifact_with_product != nil && *dist.Append_artifact_with_product {
440 productString = fmt.Sprintf("_%s", a.entryContext.Config().DeviceProduct())
441 }
442
443 if suffix != "" || productString != "" {
444 dest = strings.TrimSuffix(dest, ext) + suffix + productString + ext
Jingwen Chen40fd90a2020-06-15 05:24:19 +0000445 }
446
447 if dist.Dir != nil {
448 var err error
449 if dest, err = validateSafePath(*dist.Dir, dest); err != nil {
450 // This was checked in ModuleBase.GenerateBuildActions
451 panic(err)
452 }
453 }
454
Paul Duffin8b0349c2020-11-26 14:33:21 +0000455 copiesForGoals.addCopyInstruction(path, dest)
456 }
457 }
458
459 return distContributions
460}
461
462// generateDistContributionsForMake generates make rules that will generate the
463// dist according to the instructions in the supplied distContribution.
464func generateDistContributionsForMake(distContributions *distContributions) []string {
465 var ret []string
466 for _, d := range distContributions.copiesForGoals {
467 ret = append(ret, fmt.Sprintf(".PHONY: %s\n", d.goals))
468 // Create dist-for-goals calls for each of the copy instructions.
469 for _, c := range d.copies {
Bob Badour4660a982022-09-12 16:06:03 -0700470 if distContributions.licenseMetadataFile != nil {
471 ret = append(
472 ret,
473 fmt.Sprintf("$(if $(strip $(ALL_TARGETS.%s.META_LIC)),,$(eval ALL_TARGETS.%s.META_LIC := %s))\n",
474 c.from.String(), c.from.String(), distContributions.licenseMetadataFile.String()))
475 }
Bob Badour51804382022-04-13 11:27:19 -0700476 ret = append(
477 ret,
Paul Duffin8b0349c2020-11-26 14:33:21 +0000478 fmt.Sprintf("$(call dist-for-goals,%s,%s:%s)\n", d.goals, c.from.String(), c.dest))
Jingwen Chen40fd90a2020-06-15 05:24:19 +0000479 }
480 }
481
482 return ret
483}
484
Paul Duffin8b0349c2020-11-26 14:33:21 +0000485// Compute the list of Make strings to declare phony goals and dist-for-goals
486// calls from the module's dist and dists properties.
487func (a *AndroidMkEntries) GetDistForGoals(mod blueprint.Module) []string {
488 distContributions := a.getDistContributions(mod)
489 if distContributions == nil {
490 return nil
491 }
492
493 return generateDistContributionsForMake(distContributions)
494}
495
Jaewoong Jung7ef4a902020-11-16 12:50:29 -0800496// fillInEntries goes through the common variable processing and calls the extra data funcs to
497// generate and fill in AndroidMkEntries's in-struct data, ready to be flushed to a file.
Colin Crossaa255532020-07-03 13:18:24 -0700498type fillInEntriesContext interface {
499 ModuleDir(module blueprint.Module) string
Cole Faust39aabe92023-02-23 16:57:43 -0800500 ModuleSubDir(module blueprint.Module) string
Colin Crossaa255532020-07-03 13:18:24 -0700501 Config() Config
Yu Liu663e4502024-08-12 18:23:59 +0000502 otherModuleProvider(module blueprint.Module, provider blueprint.AnyProviderKey) (any, bool)
Sasha Smundak5c4729d2022-12-01 10:49:23 -0800503 ModuleType(module blueprint.Module) string
Cole Faust43ddd082024-06-17 12:32:40 -0700504 OtherModulePropertyErrorf(module Module, property string, fmt string, args ...interface{})
Cole Faust4e2bf9f2024-09-11 13:26:20 -0700505 HasMutatorFinished(mutatorName string) bool
Colin Crossaa255532020-07-03 13:18:24 -0700506}
507
508func (a *AndroidMkEntries) fillInEntries(ctx fillInEntriesContext, mod blueprint.Module) {
Trevor Radcliffe90727f42022-03-21 19:34:02 +0000509 a.entryContext = ctx
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700510 a.EntryMap = make(map[string][]string)
Colin Crossf1f763a2021-10-21 16:14:19 -0700511 amod := mod.(Module)
512 base := amod.base()
513 name := base.BaseModuleName()
Colin Cross0477b422020-10-13 18:43:54 -0700514 if a.OverrideName != "" {
515 name = a.OverrideName
516 }
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700517
518 if a.Include == "" {
519 a.Include = "$(BUILD_PREBUILT)"
520 }
Cole Faust43ddd082024-06-17 12:32:40 -0700521 a.Required = append(a.Required, amod.RequiredModuleNames(ctx)...)
Kiyoung Kim04b64fc2024-08-19 11:25:30 +0900522 a.Required = append(a.Required, amod.VintfFragmentModuleNames(ctx)...)
Colin Crossf1f763a2021-10-21 16:14:19 -0700523 a.Host_required = append(a.Host_required, amod.HostRequiredModuleNames()...)
524 a.Target_required = append(a.Target_required, amod.TargetRequiredModuleNames()...)
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700525
Jingwen Chen40fd90a2020-06-15 05:24:19 +0000526 for _, distString := range a.GetDistForGoals(mod) {
527 fmt.Fprintf(&a.header, distString)
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700528 }
529
Cole Faust39aabe92023-02-23 16:57:43 -0800530 fmt.Fprintf(&a.header, "\ninclude $(CLEAR_VARS) # type: %s, name: %s, variant: %s\n", ctx.ModuleType(mod), base.BaseModuleName(), ctx.ModuleSubDir(mod))
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700531
532 // Collect make variable assignment entries.
Colin Crossaa255532020-07-03 13:18:24 -0700533 a.SetString("LOCAL_PATH", ctx.ModuleDir(mod))
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700534 a.SetString("LOCAL_MODULE", name+a.SubName)
535 a.SetString("LOCAL_MODULE_CLASS", a.Class)
536 a.SetString("LOCAL_PREBUILT_MODULE_FILE", a.OutputFile.String())
537 a.AddStrings("LOCAL_REQUIRED_MODULES", a.Required...)
538 a.AddStrings("LOCAL_HOST_REQUIRED_MODULES", a.Host_required...)
539 a.AddStrings("LOCAL_TARGET_REQUIRED_MODULES", a.Target_required...)
Wei Li598f92d2023-01-04 17:12:24 -0800540 a.AddStrings("LOCAL_SOONG_MODULE_TYPE", ctx.ModuleType(amod))
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700541
Colin Cross6301c3c2021-09-28 17:40:21 -0700542 // If the install rule was generated by Soong tell Make about it.
Yu Liud46e5ae2024-08-15 18:46:17 +0000543 info := OtherModuleProviderOrDefault(ctx, mod, InstallFilesProvider)
544 if len(info.KatiInstalls) > 0 {
Colin Cross6301c3c2021-09-28 17:40:21 -0700545 // Assume the primary install file is last since it probably needs to depend on any other
546 // installed files. If that is not the case we can add a method to specify the primary
547 // installed file.
Yu Liud46e5ae2024-08-15 18:46:17 +0000548 a.SetPath("LOCAL_SOONG_INSTALLED_MODULE", info.KatiInstalls[len(info.KatiInstalls)-1].to)
549 a.SetString("LOCAL_SOONG_INSTALL_PAIRS", info.KatiInstalls.BuiltInstalled())
550 a.SetPaths("LOCAL_SOONG_INSTALL_SYMLINKS", info.KatiSymlinks.InstallPaths().Paths())
Jiyong Park3f627e62024-05-01 16:14:38 +0900551 } else {
552 // Soong may not have generated the install rule also when `no_full_install: true`.
553 // Mark this module as uninstallable in order to prevent Make from creating an
554 // install rule there.
555 a.SetBoolIfTrue("LOCAL_UNINSTALLABLE_MODULE", proptools.Bool(base.commonProperties.No_full_install))
Colin Cross6301c3c2021-09-28 17:40:21 -0700556 }
557
Colin Crossa6182ab2024-08-21 10:47:44 -0700558 if info.UncheckedModule {
559 a.SetBool("LOCAL_DONT_CHECK_MODULE", true)
560 } else if info.CheckbuildTarget != nil {
561 a.SetPath("LOCAL_CHECKED_MODULE", info.CheckbuildTarget)
562 } else {
563 a.SetOptionalPath("LOCAL_CHECKED_MODULE", a.OutputFile)
564 }
565
Yu Liud46e5ae2024-08-15 18:46:17 +0000566 if len(info.TestData) > 0 {
567 a.AddStrings("LOCAL_TEST_DATA", androidMkDataPaths(info.TestData)...)
Colin Cross5c1d5fb2023-11-15 12:39:40 -0800568 }
569
Jiyong Park89e850a2020-04-07 16:37:39 +0900570 if am, ok := mod.(ApexModule); ok {
571 a.SetBoolIfTrue("LOCAL_NOT_AVAILABLE_FOR_PLATFORM", am.NotAvailableForPlatform())
572 }
573
Colin Crossf1f763a2021-10-21 16:14:19 -0700574 archStr := base.Arch().ArchType.String()
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700575 host := false
Colin Crossf1f763a2021-10-21 16:14:19 -0700576 switch base.Os().Class {
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700577 case Host:
Colin Crossf1f763a2021-10-21 16:14:19 -0700578 if base.Target().HostCross {
Jiyong Park1613e552020-09-14 19:43:17 +0900579 // Make cannot identify LOCAL_MODULE_HOST_CROSS_ARCH:= common.
Colin Crossf1f763a2021-10-21 16:14:19 -0700580 if base.Arch().ArchType != Common {
Jiyong Park1613e552020-09-14 19:43:17 +0900581 a.SetString("LOCAL_MODULE_HOST_CROSS_ARCH", archStr)
582 }
583 } else {
584 // Make cannot identify LOCAL_MODULE_HOST_ARCH:= common.
Colin Crossf1f763a2021-10-21 16:14:19 -0700585 if base.Arch().ArchType != Common {
Jiyong Park1613e552020-09-14 19:43:17 +0900586 a.SetString("LOCAL_MODULE_HOST_ARCH", archStr)
587 }
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700588 }
589 host = true
590 case Device:
591 // Make cannot identify LOCAL_MODULE_TARGET_ARCH:= common.
Colin Crossf1f763a2021-10-21 16:14:19 -0700592 if base.Arch().ArchType != Common {
593 if base.Target().NativeBridge {
594 hostArchStr := base.Target().NativeBridgeHostArchName
dimitry1f33e402019-03-26 12:39:31 +0100595 if hostArchStr != "" {
596 a.SetString("LOCAL_MODULE_TARGET_ARCH", hostArchStr)
597 }
598 } else {
599 a.SetString("LOCAL_MODULE_TARGET_ARCH", archStr)
600 }
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700601 }
602
Kelvin Zhang46977252022-04-13 16:41:34 -0700603 if !base.InVendorRamdisk() {
Yu Liu82a6d142024-08-27 19:02:29 +0000604 a.AddPaths("LOCAL_FULL_INIT_RC", info.InitRcPaths)
Yifan Hong919dae12020-12-02 18:55:06 -0800605 }
Yu Liu82a6d142024-08-27 19:02:29 +0000606 if len(info.VintfFragmentsPaths) > 0 {
607 a.AddPaths("LOCAL_FULL_VINTF_FRAGMENTS", info.VintfFragmentsPaths)
Liz Kammer7b3dc8a2021-04-16 16:41:59 -0400608 }
Colin Crossf1f763a2021-10-21 16:14:19 -0700609 a.SetBoolIfTrue("LOCAL_PROPRIETARY_MODULE", Bool(base.commonProperties.Proprietary))
610 if Bool(base.commonProperties.Vendor) || Bool(base.commonProperties.Soc_specific) {
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700611 a.SetString("LOCAL_VENDOR_MODULE", "true")
612 }
Colin Crossf1f763a2021-10-21 16:14:19 -0700613 a.SetBoolIfTrue("LOCAL_ODM_MODULE", Bool(base.commonProperties.Device_specific))
614 a.SetBoolIfTrue("LOCAL_PRODUCT_MODULE", Bool(base.commonProperties.Product_specific))
615 a.SetBoolIfTrue("LOCAL_SYSTEM_EXT_MODULE", Bool(base.commonProperties.System_ext_specific))
616 if base.commonProperties.Owner != nil {
617 a.SetString("LOCAL_MODULE_OWNER", *base.commonProperties.Owner)
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700618 }
619 }
620
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700621 if host {
Colin Crossf1f763a2021-10-21 16:14:19 -0700622 makeOs := base.Os().String()
623 if base.Os() == Linux || base.Os() == LinuxBionic || base.Os() == LinuxMusl {
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700624 makeOs = "linux"
625 }
626 a.SetString("LOCAL_MODULE_HOST_OS", makeOs)
627 a.SetString("LOCAL_IS_HOST_MODULE", "true")
628 }
629
630 prefix := ""
Colin Crossf1f763a2021-10-21 16:14:19 -0700631 if base.ArchSpecific() {
632 switch base.Os().Class {
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700633 case Host:
Colin Crossf1f763a2021-10-21 16:14:19 -0700634 if base.Target().HostCross {
Jiyong Park1613e552020-09-14 19:43:17 +0900635 prefix = "HOST_CROSS_"
636 } else {
637 prefix = "HOST_"
638 }
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700639 case Device:
640 prefix = "TARGET_"
641
642 }
643
Colin Crossf1f763a2021-10-21 16:14:19 -0700644 if base.Arch().ArchType != ctx.Config().Targets[base.Os()][0].Arch.ArchType {
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700645 prefix = "2ND_" + prefix
646 }
647 }
Colin Crossaa255532020-07-03 13:18:24 -0700648
Yu Liu663e4502024-08-12 18:23:59 +0000649 if licenseMetadata, ok := OtherModuleProvider(ctx, mod, LicenseMetadataProvider); ok {
Colin Cross4acaea92021-12-10 23:05:02 +0000650 a.SetPath("LOCAL_SOONG_LICENSE_METADATA", licenseMetadata.LicenseMetadataPath)
651 }
652
Yu Liu663e4502024-08-12 18:23:59 +0000653 if _, ok := OtherModuleProvider(ctx, mod, ModuleInfoJSONProvider); ok {
Colin Crossd6fd0132023-11-06 13:54:06 -0800654 a.SetBool("LOCAL_SOONG_MODULE_INFO_JSON", true)
655 }
656
Colin Crossaa255532020-07-03 13:18:24 -0700657 extraCtx := &androidMkExtraEntriesContext{
658 ctx: ctx,
659 mod: mod,
660 }
661
Jaewoong Junge0dc8df2019-08-27 17:33:16 -0700662 for _, extra := range a.ExtraEntries {
Colin Crossaa255532020-07-03 13:18:24 -0700663 extra(extraCtx, a)
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700664 }
665
666 // Write to footer.
667 fmt.Fprintln(&a.footer, "include "+a.Include)
Colin Crossaa255532020-07-03 13:18:24 -0700668 blueprintDir := ctx.ModuleDir(mod)
Jaewoong Jungb0c127c2019-08-29 14:56:03 -0700669 for _, footerFunc := range a.ExtraFooters {
Jaewoong Jung02b11a62020-12-07 10:23:54 -0800670 footerFunc(&a.footer, name, prefix, blueprintDir)
Jaewoong Jungb0c127c2019-08-29 14:56:03 -0700671 }
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700672}
673
Colin Crossd6fd0132023-11-06 13:54:06 -0800674func (a *AndroidMkEntries) disabled() bool {
675 return a.Disabled || !a.OutputFile.Valid()
676}
677
Jaewoong Jung7ef4a902020-11-16 12:50:29 -0800678// write flushes the AndroidMkEntries's in-struct data populated by AndroidMkEntries into the
679// given Writer object.
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700680func (a *AndroidMkEntries) write(w io.Writer) {
Colin Crossd6fd0132023-11-06 13:54:06 -0800681 if a.disabled() {
Jaewoong Jungb0c127c2019-08-29 14:56:03 -0700682 return
683 }
684
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700685 w.Write(a.header.Bytes())
686 for _, name := range a.entryOrder {
Sasha Smundakdcb61292022-12-08 10:41:33 -0800687 AndroidMkEmitAssignList(w, name, a.EntryMap[name])
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700688 }
689 w.Write(a.footer.Bytes())
690}
691
Jaewoong Jungb0c127c2019-08-29 14:56:03 -0700692func (a *AndroidMkEntries) FooterLinesForTests() []string {
693 return strings.Split(string(a.footer.Bytes()), "\n")
694}
695
Jaewoong Jung7ef4a902020-11-16 12:50:29 -0800696// AndroidMkSingleton is a singleton to collect Android.mk data from all modules and dump them into
697// the final Android-<product_name>.mk file output.
Colin Cross0875c522017-11-28 17:34:01 -0800698func AndroidMkSingleton() Singleton {
Dan Willemsen218f6562015-07-08 18:13:11 -0700699 return &androidMkSingleton{}
700}
701
702type androidMkSingleton struct{}
703
Colin Cross0875c522017-11-28 17:34:01 -0800704func (c *androidMkSingleton) GenerateBuildActions(ctx SingletonContext) {
Jaewoong Jung7ef4a902020-11-16 12:50:29 -0800705 // Skip if Soong wasn't invoked from Make.
Jingwen Chencda22c92020-11-23 00:22:30 -0500706 if !ctx.Config().KatiEnabled() {
Dan Willemsen5ba07e82015-12-11 13:51:06 -0800707 return
708 }
709
Colin Cross2465c3d2018-09-28 10:19:18 -0700710 var androidMkModulesList []blueprint.Module
Colin Cross4f6e4e62016-01-11 12:55:55 -0800711
Colin Cross2465c3d2018-09-28 10:19:18 -0700712 ctx.VisitAllModulesBlueprint(func(module blueprint.Module) {
Colin Cross0875c522017-11-28 17:34:01 -0800713 androidMkModulesList = append(androidMkModulesList, module)
Colin Cross4f6e4e62016-01-11 12:55:55 -0800714 })
Dan Willemsen218f6562015-07-08 18:13:11 -0700715
Jaewoong Jung7ef4a902020-11-16 12:50:29 -0800716 // Sort the module list by the module names to eliminate random churns, which may erroneously
717 // invoke additional build processes.
Colin Cross1ad81422019-01-14 12:47:35 -0800718 sort.SliceStable(androidMkModulesList, func(i, j int) bool {
719 return ctx.ModuleName(androidMkModulesList[i]) < ctx.ModuleName(androidMkModulesList[j])
720 })
Colin Crossd779da42015-12-17 18:00:23 -0800721
Dan Willemsen45133ac2018-03-09 21:22:06 -0800722 transMk := PathForOutput(ctx, "Android"+String(ctx.Config().productVariables.Make_suffix)+".mk")
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700723 if ctx.Failed() {
724 return
725 }
Dan Willemsen218f6562015-07-08 18:13:11 -0700726
Colin Crossd6fd0132023-11-06 13:54:06 -0800727 moduleInfoJSON := PathForOutput(ctx, "module-info"+String(ctx.Config().productVariables.Make_suffix)+".json")
728
729 err := translateAndroidMk(ctx, absolutePath(transMk.String()), moduleInfoJSON, androidMkModulesList)
Dan Willemsen218f6562015-07-08 18:13:11 -0700730 if err != nil {
731 ctx.Errorf(err.Error())
732 }
733
Colin Cross0875c522017-11-28 17:34:01 -0800734 ctx.Build(pctx, BuildParams{
735 Rule: blueprint.Phony,
736 Output: transMk,
Dan Willemsen218f6562015-07-08 18:13:11 -0700737 })
738}
739
Colin Crossd6fd0132023-11-06 13:54:06 -0800740func translateAndroidMk(ctx SingletonContext, absMkFile string, moduleInfoJSONPath WritablePath, mods []blueprint.Module) error {
Dan Willemsen218f6562015-07-08 18:13:11 -0700741 buf := &bytes.Buffer{}
742
Colin Crossd6fd0132023-11-06 13:54:06 -0800743 var moduleInfoJSONs []*ModuleInfoJSON
744
Dan Willemsen97750522016-02-09 17:43:51 -0800745 fmt.Fprintln(buf, "LOCAL_MODULE_MAKEFILE := $(lastword $(MAKEFILE_LIST))")
Dan Willemsen218f6562015-07-08 18:13:11 -0700746
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800747 typeStats := make(map[string]int)
Dan Willemsen218f6562015-07-08 18:13:11 -0700748 for _, mod := range mods {
Colin Crossd6fd0132023-11-06 13:54:06 -0800749 err := translateAndroidMkModule(ctx, buf, &moduleInfoJSONs, mod)
Dan Willemsen218f6562015-07-08 18:13:11 -0700750 if err != nil {
Colin Cross836e3872021-11-09 12:30:59 -0800751 os.Remove(absMkFile)
Dan Willemsen218f6562015-07-08 18:13:11 -0700752 return err
753 }
Dan Willemsen70e17fa2016-07-25 16:00:20 -0700754
Colin Cross2465c3d2018-09-28 10:19:18 -0700755 if amod, ok := mod.(Module); ok && ctx.PrimaryModule(amod) == amod {
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800756 typeStats[ctx.ModuleType(amod)] += 1
Dan Willemsen70e17fa2016-07-25 16:00:20 -0700757 }
758 }
759
760 keys := []string{}
761 fmt.Fprintln(buf, "\nSTATS.SOONG_MODULE_TYPE :=")
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800762 for k := range typeStats {
Dan Willemsen70e17fa2016-07-25 16:00:20 -0700763 keys = append(keys, k)
764 }
765 sort.Strings(keys)
766 for _, mod_type := range keys {
767 fmt.Fprintln(buf, "STATS.SOONG_MODULE_TYPE +=", mod_type)
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800768 fmt.Fprintf(buf, "STATS.SOONG_MODULE_TYPE.%s := %d\n", mod_type, typeStats[mod_type])
Dan Willemsen218f6562015-07-08 18:13:11 -0700769 }
770
Colin Crossd6fd0132023-11-06 13:54:06 -0800771 err := pathtools.WriteFileIfChanged(absMkFile, buf.Bytes(), 0666)
772 if err != nil {
773 return err
774 }
775
776 return writeModuleInfoJSON(ctx, moduleInfoJSONs, moduleInfoJSONPath)
Dan Willemsen218f6562015-07-08 18:13:11 -0700777}
778
Colin Crossd6fd0132023-11-06 13:54:06 -0800779func writeModuleInfoJSON(ctx SingletonContext, moduleInfoJSONs []*ModuleInfoJSON, moduleInfoJSONPath WritablePath) error {
780 moduleInfoJSONBuf := &strings.Builder{}
781 moduleInfoJSONBuf.WriteString("[")
782 for i, moduleInfoJSON := range moduleInfoJSONs {
783 if i != 0 {
784 moduleInfoJSONBuf.WriteString(",\n")
785 }
786 moduleInfoJSONBuf.WriteString("{")
787 moduleInfoJSONBuf.WriteString(strconv.Quote(moduleInfoJSON.core.RegisterName))
788 moduleInfoJSONBuf.WriteString(":")
789 err := encodeModuleInfoJSON(moduleInfoJSONBuf, moduleInfoJSON)
790 moduleInfoJSONBuf.WriteString("}")
791 if err != nil {
792 return err
793 }
794 }
795 moduleInfoJSONBuf.WriteString("]")
796 WriteFileRule(ctx, moduleInfoJSONPath, moduleInfoJSONBuf.String())
797 return nil
798}
799
800func translateAndroidMkModule(ctx SingletonContext, w io.Writer, moduleInfoJSONs *[]*ModuleInfoJSON, mod blueprint.Module) error {
Colin Cross953d3a22018-09-05 16:23:54 -0700801 defer func() {
802 if r := recover(); r != nil {
803 panic(fmt.Errorf("%s in translateAndroidMkModule for module %s variant %s",
804 r, ctx.ModuleName(mod), ctx.ModuleSubDir(mod)))
805 }
806 }()
807
Bob Badourb4999222021-01-07 03:34:31 +0000808 // Additional cases here require review for correct license propagation to make.
Colin Crossd6fd0132023-11-06 13:54:06 -0800809 var err error
mrziwang18420972024-09-03 15:12:51 -0700810
811 if info, ok := ctx.otherModuleProvider(mod, AndroidMkInfoProvider); ok {
812 androidMkEntriesInfos := info.(*AndroidMkProviderInfo)
813 err = translateAndroidMkEntriesInfoModule(ctx, w, moduleInfoJSONs, mod, androidMkEntriesInfos)
814 } else {
815 switch x := mod.(type) {
816 case AndroidMkDataProvider:
817 err = translateAndroidModule(ctx, w, moduleInfoJSONs, mod, x)
818 case bootstrap.GoBinaryTool:
819 err = translateGoBinaryModule(ctx, w, mod, x)
820 case AndroidMkEntriesProvider:
821 err = translateAndroidMkEntriesModule(ctx, w, moduleInfoJSONs, mod, x)
822 default:
823 // Not exported to make so no make variables to set.
824 }
Dan Willemsen218f6562015-07-08 18:13:11 -0700825 }
Colin Crossd6fd0132023-11-06 13:54:06 -0800826
827 if err != nil {
828 return err
829 }
830
831 return err
Colin Cross2465c3d2018-09-28 10:19:18 -0700832}
833
Jaewoong Jung7ef4a902020-11-16 12:50:29 -0800834// A simple, special Android.mk entry output func to make it possible to build blueprint tools using
835// m by making them phony targets.
Colin Cross2465c3d2018-09-28 10:19:18 -0700836func translateGoBinaryModule(ctx SingletonContext, w io.Writer, mod blueprint.Module,
837 goBinary bootstrap.GoBinaryTool) error {
838
839 name := ctx.ModuleName(mod)
840 fmt.Fprintln(w, ".PHONY:", name)
841 fmt.Fprintln(w, name+":", goBinary.InstallPath())
842 fmt.Fprintln(w, "")
Bob Badourb4999222021-01-07 03:34:31 +0000843 // Assuming no rules in make include go binaries in distributables.
844 // If the assumption is wrong, make will fail to build without the necessary .meta_lic and .meta_module files.
845 // In that case, add the targets and rules here to build a .meta_lic file for `name` and a .meta_module for
846 // `goBinary.InstallPath()` pointing to the `name`.meta_lic file.
Colin Cross2465c3d2018-09-28 10:19:18 -0700847
848 return nil
849}
850
Colin Crossaa255532020-07-03 13:18:24 -0700851func (data *AndroidMkData) fillInData(ctx fillInEntriesContext, mod blueprint.Module) {
Jooyung Han12df5fb2019-07-11 16:18:47 +0900852 // Get the preamble content through AndroidMkEntries logic.
Jooyung Han2ed99d02020-06-24 23:26:26 +0900853 data.Entries = AndroidMkEntries{
Jooyung Han12df5fb2019-07-11 16:18:47 +0900854 Class: data.Class,
855 SubName: data.SubName,
Jingwen Chen40fd90a2020-06-15 05:24:19 +0000856 DistFiles: data.DistFiles,
Jooyung Han12df5fb2019-07-11 16:18:47 +0900857 OutputFile: data.OutputFile,
858 Disabled: data.Disabled,
859 Include: data.Include,
860 Required: data.Required,
861 Host_required: data.Host_required,
862 Target_required: data.Target_required,
863 }
Colin Crossaa255532020-07-03 13:18:24 -0700864 data.Entries.fillInEntries(ctx, mod)
Jooyung Han12df5fb2019-07-11 16:18:47 +0900865
866 // copy entries back to data since it is used in Custom
Jooyung Han2ed99d02020-06-24 23:26:26 +0900867 data.Required = data.Entries.Required
868 data.Host_required = data.Entries.Host_required
869 data.Target_required = data.Entries.Target_required
Jooyung Han12df5fb2019-07-11 16:18:47 +0900870}
871
Jaewoong Jung7ef4a902020-11-16 12:50:29 -0800872// A support func for the deprecated AndroidMkDataProvider interface. Use AndroidMkEntryProvider
873// instead.
Colin Crossd6fd0132023-11-06 13:54:06 -0800874func translateAndroidModule(ctx SingletonContext, w io.Writer, moduleInfoJSONs *[]*ModuleInfoJSON,
875 mod blueprint.Module, provider AndroidMkDataProvider) error {
Dan Willemsen218f6562015-07-08 18:13:11 -0700876
Colin Cross635c3b02016-05-18 15:37:25 -0700877 amod := mod.(Module).base()
Cole Fausta963b942024-04-11 17:43:00 -0700878 if shouldSkipAndroidMkProcessing(ctx, amod) {
Jeff Gaston088e29e2017-11-29 16:47:17 -0800879 return nil
880 }
881
Colin Cross91825d22017-08-10 16:59:47 -0700882 data := provider.AndroidMk()
Yu Liuddc28332024-08-09 22:48:30 +0000883
Colin Cross53499412017-09-07 13:20:25 -0700884 if data.Include == "" {
885 data.Include = "$(BUILD_PREBUILT)"
886 }
887
Colin Crossaa255532020-07-03 13:18:24 -0700888 data.fillInData(ctx, mod)
LaMont Jonesb5099382024-01-10 23:42:36 +0000889 aconfigUpdateAndroidMkData(ctx, mod.(Module), &data)
Dan Willemsen01a405a2016-06-13 17:19:03 -0700890
Colin Cross0f86d182017-08-10 17:07:28 -0700891 prefix := ""
892 if amod.ArchSpecific() {
893 switch amod.Os().Class {
894 case Host:
Jiyong Park1613e552020-09-14 19:43:17 +0900895 if amod.Target().HostCross {
896 prefix = "HOST_CROSS_"
897 } else {
898 prefix = "HOST_"
899 }
Colin Cross0f86d182017-08-10 17:07:28 -0700900 case Device:
901 prefix = "TARGET_"
Colin Crossa2344662016-03-24 13:14:12 -0700902
Dan Willemsen218f6562015-07-08 18:13:11 -0700903 }
904
Dan Willemsen0ef639b2018-10-10 17:02:29 -0700905 if amod.Arch().ArchType != ctx.Config().Targets[amod.Os()][0].Arch.ArchType {
Colin Cross0f86d182017-08-10 17:07:28 -0700906 prefix = "2ND_" + prefix
907 }
Dan Willemsen218f6562015-07-08 18:13:11 -0700908 }
909
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700910 name := provider.BaseModuleName()
Colin Cross0f86d182017-08-10 17:07:28 -0700911 blueprintDir := filepath.Dir(ctx.BlueprintFile(mod))
912
913 if data.Custom != nil {
Bob Badourb4999222021-01-07 03:34:31 +0000914 // List of module types allowed to use .Custom(...)
915 // Additions to the list require careful review for proper license handling.
Colin Crossaa255532020-07-03 13:18:24 -0700916 switch reflect.TypeOf(mod).String() { // ctx.ModuleType(mod) doesn't work: aidl_interface creates phony without type
Bob Badourb4999222021-01-07 03:34:31 +0000917 case "*aidl.aidlApi": // writes non-custom before adding .phony
918 case "*aidl.aidlMapping": // writes non-custom before adding .phony
919 case "*android.customModule": // appears in tests only
Dan Willemsen9fe14102021-07-13 21:52:04 -0700920 case "*android_sdk.sdkRepoHost": // doesn't go through base_rules
Bob Badourb4999222021-01-07 03:34:31 +0000921 case "*apex.apexBundle": // license properties written
922 case "*bpf.bpf": // license properties written (both for module and objs)
Neill Kapron41efab72024-07-31 22:17:36 +0000923 case "*libbpf_prog.libbpfProg": // license properties written (both for module and objs)
Bob Badourb4999222021-01-07 03:34:31 +0000924 case "*genrule.Module": // writes non-custom before adding .phony
925 case "*java.SystemModules": // doesn't go through base_rules
926 case "*java.systemModulesImport": // doesn't go through base_rules
927 case "*phony.phony": // license properties written
Nelson Lif3c70682023-12-20 02:37:52 +0000928 case "*phony.PhonyRule": // writes phony deps and acts like `.PHONY`
Bob Badourb4999222021-01-07 03:34:31 +0000929 case "*selinux.selinuxContextsModule": // license properties written
930 case "*sysprop.syspropLibrary": // license properties written
Bill Yang3b3aac02024-09-05 09:22:09 +0000931 case "*vintf.vintfCompatibilityMatrixRule": // use case like phony
Bob Badourb4999222021-01-07 03:34:31 +0000932 default:
Bob Badour65ee90a2021-09-02 15:33:10 -0700933 if !ctx.Config().IsEnvFalse("ANDROID_REQUIRE_LICENSES") {
Bob Badourb4999222021-01-07 03:34:31 +0000934 return fmt.Errorf("custom make rules not allowed for %q (%q) module %q", ctx.ModuleType(mod), reflect.TypeOf(mod), ctx.ModuleName(mod))
935 }
936 }
Colin Cross0f86d182017-08-10 17:07:28 -0700937 data.Custom(w, name, prefix, blueprintDir, data)
938 } else {
939 WriteAndroidMkData(w, data)
940 }
941
Colin Crossd6fd0132023-11-06 13:54:06 -0800942 if !data.Entries.disabled() {
Yu Liu663e4502024-08-12 18:23:59 +0000943 if moduleInfoJSON, ok := OtherModuleProvider(ctx, mod, ModuleInfoJSONProvider); ok {
Colin Crossd6fd0132023-11-06 13:54:06 -0800944 *moduleInfoJSONs = append(*moduleInfoJSONs, moduleInfoJSON)
945 }
946 }
947
Colin Cross0f86d182017-08-10 17:07:28 -0700948 return nil
949}
950
Jaewoong Jung7ef4a902020-11-16 12:50:29 -0800951// A support func for the deprecated AndroidMkDataProvider interface. Use AndroidMkEntryProvider
952// instead.
Colin Cross0f86d182017-08-10 17:07:28 -0700953func WriteAndroidMkData(w io.Writer, data AndroidMkData) {
Colin Crossd6fd0132023-11-06 13:54:06 -0800954 if data.Entries.disabled() {
Colin Cross0f86d182017-08-10 17:07:28 -0700955 return
956 }
957
Jooyung Han2ed99d02020-06-24 23:26:26 +0900958 // write preamble via Entries
959 data.Entries.footer = bytes.Buffer{}
960 data.Entries.write(w)
Colin Cross0f86d182017-08-10 17:07:28 -0700961
Colin Crossca860ac2016-01-04 14:34:37 -0800962 for _, extra := range data.Extra {
Colin Cross27a4b052017-08-10 16:32:23 -0700963 extra(w, data.OutputFile.Path())
Dan Willemsen97750522016-02-09 17:43:51 -0800964 }
965
Colin Cross53499412017-09-07 13:20:25 -0700966 fmt.Fprintln(w, "include "+data.Include)
Dan Willemsen218f6562015-07-08 18:13:11 -0700967}
Sasha Smundakb6d23052019-04-01 18:37:36 -0700968
Colin Crossd6fd0132023-11-06 13:54:06 -0800969func translateAndroidMkEntriesModule(ctx SingletonContext, w io.Writer, moduleInfoJSONs *[]*ModuleInfoJSON,
970 mod blueprint.Module, provider AndroidMkEntriesProvider) error {
Cole Fausta963b942024-04-11 17:43:00 -0700971 if shouldSkipAndroidMkProcessing(ctx, mod.(Module).base()) {
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700972 return nil
Sasha Smundakb6d23052019-04-01 18:37:36 -0700973 }
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700974
Colin Crossd6fd0132023-11-06 13:54:06 -0800975 entriesList := provider.AndroidMkEntries()
LaMont Jonesb5099382024-01-10 23:42:36 +0000976 aconfigUpdateAndroidMkEntries(ctx, mod.(Module), &entriesList)
Colin Crossd6fd0132023-11-06 13:54:06 -0800977
Bob Badourb4999222021-01-07 03:34:31 +0000978 // Any new or special cases here need review to verify correct propagation of license information.
Colin Crossd6fd0132023-11-06 13:54:06 -0800979 for _, entries := range entriesList {
Colin Crossaa255532020-07-03 13:18:24 -0700980 entries.fillInEntries(ctx, mod)
Jiyong Park0b0e1b92019-12-03 13:24:29 +0900981 entries.write(w)
982 }
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700983
Colin Crossd6fd0132023-11-06 13:54:06 -0800984 if len(entriesList) > 0 && !entriesList[0].disabled() {
Yu Liu663e4502024-08-12 18:23:59 +0000985 if moduleInfoJSON, ok := OtherModuleProvider(ctx, mod, ModuleInfoJSONProvider); ok {
Colin Crossd6fd0132023-11-06 13:54:06 -0800986 *moduleInfoJSONs = append(*moduleInfoJSONs, moduleInfoJSON)
987 }
988 }
989
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700990 return nil
991}
992
Cole Fauste8a87832024-09-11 11:35:46 -0700993func ShouldSkipAndroidMkProcessing(ctx ConfigurableEvaluatorContext, module Module) bool {
Cole Fausta963b942024-04-11 17:43:00 -0700994 return shouldSkipAndroidMkProcessing(ctx, module.base())
Chih-Hung Hsieh80783772021-10-11 16:46:56 -0700995}
996
Cole Fauste8a87832024-09-11 11:35:46 -0700997func shouldSkipAndroidMkProcessing(ctx ConfigurableEvaluatorContext, module *ModuleBase) bool {
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700998 if !module.commonProperties.NamespaceExportedToMake {
999 // TODO(jeffrygaston) do we want to validate that there are no modules being
1000 // exported to Kati that depend on this module?
1001 return true
Sasha Smundakb6d23052019-04-01 18:37:36 -07001002 }
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -07001003
Dan Willemsendef7b5d2021-10-17 00:22:33 -07001004 // On Mac, only expose host darwin modules to Make, as that's all we claim to support.
1005 // In reality, some of them depend on device-built (Java) modules, so we can't disable all
1006 // device modules in Soong, but we can hide them from Make (and thus the build user interface)
1007 if runtime.GOOS == "darwin" && module.Os() != Darwin {
1008 return true
1009 }
1010
Dan Willemsen8528f4e2021-10-19 00:22:06 -07001011 // Only expose the primary Darwin target, as Make does not understand Darwin+Arm64
1012 if module.Os() == Darwin && module.Target().HostCross {
1013 return true
1014 }
1015
Cole Fausta963b942024-04-11 17:43:00 -07001016 return !module.Enabled(ctx) ||
Colin Crossa9c8c9f2020-12-16 10:20:23 -08001017 module.commonProperties.HideFromMake ||
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -07001018 // Make does not understand LinuxBionic
Colin Cross9a027be2022-06-24 18:45:58 -07001019 module.Os() == LinuxBionic ||
1020 // Make does not understand LinuxMusl, except when we are building with USE_HOST_MUSL=true
1021 // and all host binaries are LinuxMusl
1022 (module.Os() == LinuxMusl && module.Target().HostCross)
Sasha Smundakb6d23052019-04-01 18:37:36 -07001023}
Dan Shi31949122020-09-21 12:11:02 -07001024
Jaewoong Jung7ef4a902020-11-16 12:50:29 -08001025// A utility func to format LOCAL_TEST_DATA outputs. See the comments on DataPath to understand how
1026// to use this func.
Colin Cross5c1d5fb2023-11-15 12:39:40 -08001027func androidMkDataPaths(data []DataPath) []string {
Dan Shi31949122020-09-21 12:11:02 -07001028 var testFiles []string
1029 for _, d := range data {
1030 rel := d.SrcPath.Rel()
Colin Cross5c1d5fb2023-11-15 12:39:40 -08001031 if d.WithoutRel {
1032 rel = d.SrcPath.Base()
1033 }
Dan Shi31949122020-09-21 12:11:02 -07001034 path := d.SrcPath.String()
Jaewoong Jung7ef4a902020-11-16 12:50:29 -08001035 // LOCAL_TEST_DATA requires the rel portion of the path to be removed from the path.
Dan Shi31949122020-09-21 12:11:02 -07001036 if !strings.HasSuffix(path, rel) {
1037 panic(fmt.Errorf("path %q does not end with %q", path, rel))
1038 }
1039 path = strings.TrimSuffix(path, rel)
1040 testFileString := path + ":" + rel
1041 if len(d.RelativeInstallPath) > 0 {
1042 testFileString += ":" + d.RelativeInstallPath
1043 }
1044 testFiles = append(testFiles, testFileString)
1045 }
1046 return testFiles
1047}
Sasha Smundakdcb61292022-12-08 10:41:33 -08001048
1049// AndroidMkEmitAssignList emits the line
1050//
1051// VAR := ITEM ...
1052//
1053// Items are the elements to the given set of lists
1054// If all the passed lists are empty, no line will be emitted
1055func AndroidMkEmitAssignList(w io.Writer, varName string, lists ...[]string) {
1056 doPrint := false
1057 for _, l := range lists {
1058 if doPrint = len(l) > 0; doPrint {
1059 break
1060 }
1061 }
1062 if !doPrint {
1063 return
1064 }
1065 fmt.Fprint(w, varName, " :=")
1066 for _, l := range lists {
1067 for _, item := range l {
1068 fmt.Fprint(w, " ", item)
1069 }
1070 }
1071 fmt.Fprintln(w)
1072}
mrziwang18420972024-09-03 15:12:51 -07001073
1074type AndroidMkProviderInfo struct {
1075 PrimaryInfo AndroidMkInfo
1076 ExtraInfo []AndroidMkInfo
1077}
1078
1079type AndroidMkInfo struct {
1080 // Android.mk class string, e.g. EXECUTABLES, JAVA_LIBRARIES, ETC
1081 Class string
1082 // Optional suffix to append to the module name. Useful when a module wants to return multiple
1083 // AndroidMkEntries objects. For example, when a java_library returns an additional entry for
1084 // its hostdex sub-module, this SubName field is set to "-hostdex" so that it can have a
1085 // different name than the parent's.
1086 SubName string
1087 // If set, this value overrides the base module name. SubName is still appended.
1088 OverrideName string
1089 // Dist files to output
1090 DistFiles TaggedDistFiles
1091 // The output file for Kati to process and/or install. If absent, the module is skipped.
1092 OutputFile OptionalPath
1093 // If true, the module is skipped and does not appear on the final Android-<product name>.mk
1094 // file. Useful when a module needs to be skipped conditionally.
1095 Disabled bool
1096 // The postprocessing mk file to include, e.g. $(BUILD_SYSTEM)/soong_cc_rust_prebuilt.mk
1097 // If not set, $(BUILD_SYSTEM)/prebuilt.mk is used.
1098 Include string
1099 // Required modules that need to be built and included in the final build output when building
1100 // this module.
1101 Required []string
1102 // Required host modules that need to be built and included in the final build output when
1103 // building this module.
1104 Host_required []string
1105 // Required device modules that need to be built and included in the final build output when
1106 // building this module.
1107 Target_required []string
1108
1109 HeaderStrings []string
1110 FooterStrings []string
1111
1112 // A map that holds the up-to-date Make variable values. Can be accessed from tests.
1113 EntryMap map[string][]string
1114 // A list of EntryMap keys in insertion order. This serves a few purposes:
1115 // 1. Prevents churns. Golang map doesn't provide consistent iteration order, so without this,
1116 // the outputted Android-*.mk file may change even though there have been no content changes.
1117 // 2. Allows modules to refer to other variables, like LOCAL_BAR_VAR := $(LOCAL_FOO_VAR),
1118 // without worrying about the variables being mixed up in the actual mk file.
1119 // 3. Makes troubleshooting and spotting errors easier.
1120 EntryOrder []string
1121}
1122
1123// TODO: rename it to AndroidMkEntriesProvider after AndroidMkEntriesProvider interface is gone.
1124var AndroidMkInfoProvider = blueprint.NewProvider[*AndroidMkProviderInfo]()
1125
1126func translateAndroidMkEntriesInfoModule(ctx SingletonContext, w io.Writer, moduleInfoJSONs *[]*ModuleInfoJSON,
1127 mod blueprint.Module, providerInfo *AndroidMkProviderInfo) error {
1128 if shouldSkipAndroidMkProcessing(ctx, mod.(Module).base()) {
1129 return nil
1130 }
1131
1132 // Deep copy the provider info since we need to modify the info later
1133 info := deepCopyAndroidMkProviderInfo(providerInfo)
1134
1135 aconfigUpdateAndroidMkInfos(ctx, mod.(Module), &info)
1136
1137 // Any new or special cases here need review to verify correct propagation of license information.
1138 info.PrimaryInfo.fillInEntries(ctx, mod)
1139 info.PrimaryInfo.write(w)
1140 if len(info.ExtraInfo) > 0 {
1141 for _, ei := range info.ExtraInfo {
1142 ei.fillInEntries(ctx, mod)
1143 ei.write(w)
1144 }
1145 }
1146
1147 if !info.PrimaryInfo.disabled() {
1148 if moduleInfoJSON, ok := OtherModuleProvider(ctx, mod, ModuleInfoJSONProvider); ok {
1149 *moduleInfoJSONs = append(*moduleInfoJSONs, moduleInfoJSON)
1150 }
1151 }
1152
1153 return nil
1154}
1155
1156// Utility funcs to manipulate Android.mk variable entries.
1157
1158// SetString sets a Make variable with the given name to the given value.
1159func (a *AndroidMkInfo) SetString(name, value string) {
1160 if _, ok := a.EntryMap[name]; !ok {
1161 a.EntryOrder = append(a.EntryOrder, name)
1162 }
1163 a.EntryMap[name] = []string{value}
1164}
1165
1166// SetPath sets a Make variable with the given name to the given path string.
1167func (a *AndroidMkInfo) SetPath(name string, path Path) {
1168 if _, ok := a.EntryMap[name]; !ok {
1169 a.EntryOrder = append(a.EntryOrder, name)
1170 }
1171 a.EntryMap[name] = []string{path.String()}
1172}
1173
1174// SetOptionalPath sets a Make variable with the given name to the given path string if it is valid.
1175// It is a no-op if the given path is invalid.
1176func (a *AndroidMkInfo) SetOptionalPath(name string, path OptionalPath) {
1177 if path.Valid() {
1178 a.SetPath(name, path.Path())
1179 }
1180}
1181
1182// AddPath appends the given path string to a Make variable with the given name.
1183func (a *AndroidMkInfo) AddPath(name string, path Path) {
1184 if _, ok := a.EntryMap[name]; !ok {
1185 a.EntryOrder = append(a.EntryOrder, name)
1186 }
1187 a.EntryMap[name] = append(a.EntryMap[name], path.String())
1188}
1189
1190// AddOptionalPath appends the given path string to a Make variable with the given name if it is
1191// valid. It is a no-op if the given path is invalid.
1192func (a *AndroidMkInfo) AddOptionalPath(name string, path OptionalPath) {
1193 if path.Valid() {
1194 a.AddPath(name, path.Path())
1195 }
1196}
1197
1198// SetPaths sets a Make variable with the given name to a slice of the given path strings.
1199func (a *AndroidMkInfo) SetPaths(name string, paths Paths) {
1200 if _, ok := a.EntryMap[name]; !ok {
1201 a.EntryOrder = append(a.EntryOrder, name)
1202 }
1203 a.EntryMap[name] = paths.Strings()
1204}
1205
1206// SetOptionalPaths sets a Make variable with the given name to a slice of the given path strings
1207// only if there are a non-zero amount of paths.
1208func (a *AndroidMkInfo) SetOptionalPaths(name string, paths Paths) {
1209 if len(paths) > 0 {
1210 a.SetPaths(name, paths)
1211 }
1212}
1213
1214// AddPaths appends the given path strings to a Make variable with the given name.
1215func (a *AndroidMkInfo) AddPaths(name string, paths Paths) {
1216 if _, ok := a.EntryMap[name]; !ok {
1217 a.EntryOrder = append(a.EntryOrder, name)
1218 }
1219 a.EntryMap[name] = append(a.EntryMap[name], paths.Strings()...)
1220}
1221
1222// SetBoolIfTrue sets a Make variable with the given name to true if the given flag is true.
1223// It is a no-op if the given flag is false.
1224func (a *AndroidMkInfo) SetBoolIfTrue(name string, flag bool) {
1225 if flag {
1226 if _, ok := a.EntryMap[name]; !ok {
1227 a.EntryOrder = append(a.EntryOrder, name)
1228 }
1229 a.EntryMap[name] = []string{"true"}
1230 }
1231}
1232
1233// SetBool sets a Make variable with the given name to if the given bool flag value.
1234func (a *AndroidMkInfo) SetBool(name string, flag bool) {
1235 if _, ok := a.EntryMap[name]; !ok {
1236 a.EntryOrder = append(a.EntryOrder, name)
1237 }
1238 if flag {
1239 a.EntryMap[name] = []string{"true"}
1240 } else {
1241 a.EntryMap[name] = []string{"false"}
1242 }
1243}
1244
1245// AddStrings appends the given strings to a Make variable with the given name.
1246func (a *AndroidMkInfo) AddStrings(name string, value ...string) {
1247 if len(value) == 0 {
1248 return
1249 }
1250 if _, ok := a.EntryMap[name]; !ok {
1251 a.EntryOrder = append(a.EntryOrder, name)
1252 }
1253 a.EntryMap[name] = append(a.EntryMap[name], value...)
1254}
1255
1256// AddCompatibilityTestSuites adds the supplied test suites to the EntryMap, with special handling
1257// for partial MTS and MCTS test suites.
1258func (a *AndroidMkInfo) AddCompatibilityTestSuites(suites ...string) {
1259 // M(C)TS supports a full test suite and partial per-module MTS test suites, with naming mts-${MODULE}.
1260 // To reduce repetition, if we find a partial M(C)TS test suite without an full M(C)TS test suite,
1261 // we add the full test suite to our list.
1262 if PrefixInList(suites, "mts-") && !InList("mts", suites) {
1263 suites = append(suites, "mts")
1264 }
1265 if PrefixInList(suites, "mcts-") && !InList("mcts", suites) {
1266 suites = append(suites, "mcts")
1267 }
1268 a.AddStrings("LOCAL_COMPATIBILITY_SUITE", suites...)
1269}
1270
1271func (a *AndroidMkInfo) fillInEntries(ctx fillInEntriesContext, mod blueprint.Module) {
1272 helperInfo := AndroidMkInfo{
1273 EntryMap: make(map[string][]string),
1274 }
1275
1276 amod := mod.(Module)
1277 base := amod.base()
1278 name := base.BaseModuleName()
1279 if a.OverrideName != "" {
1280 name = a.OverrideName
1281 }
1282
1283 if a.Include == "" {
1284 a.Include = "$(BUILD_PREBUILT)"
1285 }
1286 a.Required = append(a.Required, amod.RequiredModuleNames(ctx)...)
1287 a.Required = append(a.Required, amod.VintfFragmentModuleNames(ctx)...)
1288 a.Host_required = append(a.Host_required, amod.HostRequiredModuleNames()...)
1289 a.Target_required = append(a.Target_required, amod.TargetRequiredModuleNames()...)
1290
1291 for _, distString := range a.GetDistForGoals(ctx, mod) {
1292 a.HeaderStrings = append(a.HeaderStrings, distString)
1293 }
1294
1295 a.HeaderStrings = append(a.HeaderStrings, fmt.Sprintf("\ninclude $(CLEAR_VARS) # type: %s, name: %s, variant: %s\n", ctx.ModuleType(mod), base.BaseModuleName(), ctx.ModuleSubDir(mod)))
1296
1297 // Collect make variable assignment entries.
1298 helperInfo.SetString("LOCAL_PATH", ctx.ModuleDir(mod))
1299 helperInfo.SetString("LOCAL_MODULE", name+a.SubName)
1300 helperInfo.SetString("LOCAL_MODULE_CLASS", a.Class)
1301 helperInfo.SetString("LOCAL_PREBUILT_MODULE_FILE", a.OutputFile.String())
1302 helperInfo.AddStrings("LOCAL_REQUIRED_MODULES", a.Required...)
1303 helperInfo.AddStrings("LOCAL_HOST_REQUIRED_MODULES", a.Host_required...)
1304 helperInfo.AddStrings("LOCAL_TARGET_REQUIRED_MODULES", a.Target_required...)
1305 helperInfo.AddStrings("LOCAL_SOONG_MODULE_TYPE", ctx.ModuleType(amod))
1306
1307 // If the install rule was generated by Soong tell Make about it.
1308 info := OtherModuleProviderOrDefault(ctx, mod, InstallFilesProvider)
1309 if len(info.KatiInstalls) > 0 {
1310 // Assume the primary install file is last since it probably needs to depend on any other
1311 // installed files. If that is not the case we can add a method to specify the primary
1312 // installed file.
1313 helperInfo.SetPath("LOCAL_SOONG_INSTALLED_MODULE", info.KatiInstalls[len(info.KatiInstalls)-1].to)
1314 helperInfo.SetString("LOCAL_SOONG_INSTALL_PAIRS", info.KatiInstalls.BuiltInstalled())
1315 helperInfo.SetPaths("LOCAL_SOONG_INSTALL_SYMLINKS", info.KatiSymlinks.InstallPaths().Paths())
1316 } else {
1317 // Soong may not have generated the install rule also when `no_full_install: true`.
1318 // Mark this module as uninstallable in order to prevent Make from creating an
1319 // install rule there.
1320 helperInfo.SetBoolIfTrue("LOCAL_UNINSTALLABLE_MODULE", proptools.Bool(base.commonProperties.No_full_install))
1321 }
1322
1323 if len(info.TestData) > 0 {
1324 helperInfo.AddStrings("LOCAL_TEST_DATA", androidMkDataPaths(info.TestData)...)
1325 }
1326
1327 if am, ok := mod.(ApexModule); ok {
1328 helperInfo.SetBoolIfTrue("LOCAL_NOT_AVAILABLE_FOR_PLATFORM", am.NotAvailableForPlatform())
1329 }
1330
1331 archStr := base.Arch().ArchType.String()
1332 host := false
1333 switch base.Os().Class {
1334 case Host:
1335 if base.Target().HostCross {
1336 // Make cannot identify LOCAL_MODULE_HOST_CROSS_ARCH:= common.
1337 if base.Arch().ArchType != Common {
1338 helperInfo.SetString("LOCAL_MODULE_HOST_CROSS_ARCH", archStr)
1339 }
1340 } else {
1341 // Make cannot identify LOCAL_MODULE_HOST_ARCH:= common.
1342 if base.Arch().ArchType != Common {
1343 helperInfo.SetString("LOCAL_MODULE_HOST_ARCH", archStr)
1344 }
1345 }
1346 host = true
1347 case Device:
1348 // Make cannot identify LOCAL_MODULE_TARGET_ARCH:= common.
1349 if base.Arch().ArchType != Common {
1350 if base.Target().NativeBridge {
1351 hostArchStr := base.Target().NativeBridgeHostArchName
1352 if hostArchStr != "" {
1353 helperInfo.SetString("LOCAL_MODULE_TARGET_ARCH", hostArchStr)
1354 }
1355 } else {
1356 helperInfo.SetString("LOCAL_MODULE_TARGET_ARCH", archStr)
1357 }
1358 }
1359
1360 if !base.InVendorRamdisk() {
1361 helperInfo.AddPaths("LOCAL_FULL_INIT_RC", info.InitRcPaths)
1362 }
1363 if len(info.VintfFragmentsPaths) > 0 {
1364 helperInfo.AddPaths("LOCAL_FULL_VINTF_FRAGMENTS", info.VintfFragmentsPaths)
1365 }
1366 helperInfo.SetBoolIfTrue("LOCAL_PROPRIETARY_MODULE", Bool(base.commonProperties.Proprietary))
1367 if Bool(base.commonProperties.Vendor) || Bool(base.commonProperties.Soc_specific) {
1368 helperInfo.SetString("LOCAL_VENDOR_MODULE", "true")
1369 }
1370 helperInfo.SetBoolIfTrue("LOCAL_ODM_MODULE", Bool(base.commonProperties.Device_specific))
1371 helperInfo.SetBoolIfTrue("LOCAL_PRODUCT_MODULE", Bool(base.commonProperties.Product_specific))
1372 helperInfo.SetBoolIfTrue("LOCAL_SYSTEM_EXT_MODULE", Bool(base.commonProperties.System_ext_specific))
1373 if base.commonProperties.Owner != nil {
1374 helperInfo.SetString("LOCAL_MODULE_OWNER", *base.commonProperties.Owner)
1375 }
1376 }
1377
1378 if host {
1379 makeOs := base.Os().String()
1380 if base.Os() == Linux || base.Os() == LinuxBionic || base.Os() == LinuxMusl {
1381 makeOs = "linux"
1382 }
1383 helperInfo.SetString("LOCAL_MODULE_HOST_OS", makeOs)
1384 helperInfo.SetString("LOCAL_IS_HOST_MODULE", "true")
1385 }
1386
1387 prefix := ""
1388 if base.ArchSpecific() {
1389 switch base.Os().Class {
1390 case Host:
1391 if base.Target().HostCross {
1392 prefix = "HOST_CROSS_"
1393 } else {
1394 prefix = "HOST_"
1395 }
1396 case Device:
1397 prefix = "TARGET_"
1398
1399 }
1400
1401 if base.Arch().ArchType != ctx.Config().Targets[base.Os()][0].Arch.ArchType {
1402 prefix = "2ND_" + prefix
1403 }
1404 }
1405
1406 if licenseMetadata, ok := OtherModuleProvider(ctx, mod, LicenseMetadataProvider); ok {
1407 helperInfo.SetPath("LOCAL_SOONG_LICENSE_METADATA", licenseMetadata.LicenseMetadataPath)
1408 }
1409
1410 if _, ok := OtherModuleProvider(ctx, mod, ModuleInfoJSONProvider); ok {
1411 helperInfo.SetBool("LOCAL_SOONG_MODULE_INFO_JSON", true)
1412 }
1413
1414 a.mergeEntries(&helperInfo)
1415
1416 // Write to footer.
1417 a.FooterStrings = append([]string{"include " + a.Include}, a.FooterStrings...)
1418}
1419
1420// This method merges the entries to helperInfo, then replaces a's EntryMap and
1421// EntryOrder with helperInfo's
1422func (a *AndroidMkInfo) mergeEntries(helperInfo *AndroidMkInfo) {
1423 for _, extraEntry := range a.EntryOrder {
1424 if v, ok := helperInfo.EntryMap[extraEntry]; ok {
1425 v = append(v, a.EntryMap[extraEntry]...)
1426 } else {
1427 helperInfo.EntryMap[extraEntry] = a.EntryMap[extraEntry]
1428 helperInfo.EntryOrder = append(helperInfo.EntryOrder, extraEntry)
1429 }
1430 }
1431 a.EntryOrder = helperInfo.EntryOrder
1432 a.EntryMap = helperInfo.EntryMap
1433}
1434
1435func (a *AndroidMkInfo) disabled() bool {
1436 return a.Disabled || !a.OutputFile.Valid()
1437}
1438
1439// write flushes the AndroidMkEntries's in-struct data populated by AndroidMkEntries into the
1440// given Writer object.
1441func (a *AndroidMkInfo) write(w io.Writer) {
1442 if a.disabled() {
1443 return
1444 }
1445
1446 combinedHeaderString := strings.Join(a.HeaderStrings, "\n")
1447 combinedFooterString := strings.Join(a.FooterStrings, "\n")
1448 w.Write([]byte(combinedHeaderString))
1449 for _, name := range a.EntryOrder {
1450 AndroidMkEmitAssignList(w, name, a.EntryMap[name])
1451 }
1452 w.Write([]byte(combinedFooterString))
1453}
1454
1455// Compute the list of Make strings to declare phony goals and dist-for-goals
1456// calls from the module's dist and dists properties.
1457func (a *AndroidMkInfo) GetDistForGoals(ctx fillInEntriesContext, mod blueprint.Module) []string {
1458 distContributions := a.getDistContributions(ctx, mod)
1459 if distContributions == nil {
1460 return nil
1461 }
1462
1463 return generateDistContributionsForMake(distContributions)
1464}
1465
1466// Compute the contributions that the module makes to the dist.
1467func (a *AndroidMkInfo) getDistContributions(ctx fillInEntriesContext, mod blueprint.Module) *distContributions {
1468 amod := mod.(Module).base()
1469 name := amod.BaseModuleName()
1470
1471 // Collate the set of associated tag/paths available for copying to the dist.
1472 // Start with an empty (nil) set.
1473 var availableTaggedDists TaggedDistFiles
1474
1475 // Then merge in any that are provided explicitly by the module.
1476 if a.DistFiles != nil {
1477 // Merge the DistFiles into the set.
1478 availableTaggedDists = availableTaggedDists.merge(a.DistFiles)
1479 }
1480
1481 // If no paths have been provided for the DefaultDistTag and the output file is
1482 // valid then add that as the default dist path.
1483 if _, ok := availableTaggedDists[DefaultDistTag]; !ok && a.OutputFile.Valid() {
1484 availableTaggedDists = availableTaggedDists.addPathsForTag(DefaultDistTag, a.OutputFile.Path())
1485 }
1486
1487 info := OtherModuleProviderOrDefault(ctx, mod, InstallFilesProvider)
1488 // If the distFiles created by GenerateTaggedDistFiles contains paths for the
1489 // DefaultDistTag then that takes priority so delete any existing paths.
1490 if _, ok := info.DistFiles[DefaultDistTag]; ok {
1491 delete(availableTaggedDists, DefaultDistTag)
1492 }
1493
1494 // Finally, merge the distFiles created by GenerateTaggedDistFiles.
1495 availableTaggedDists = availableTaggedDists.merge(info.DistFiles)
1496
1497 if len(availableTaggedDists) == 0 {
1498 // Nothing dist-able for this module.
1499 return nil
1500 }
1501
1502 // Collate the contributions this module makes to the dist.
1503 distContributions := &distContributions{}
1504
1505 if !exemptFromRequiredApplicableLicensesProperty(mod.(Module)) {
1506 distContributions.licenseMetadataFile = info.LicenseMetadataFile
1507 }
1508
1509 // Iterate over this module's dist structs, merged from the dist and dists properties.
1510 for _, dist := range amod.Dists() {
1511 // Get the list of goals this dist should be enabled for. e.g. sdk, droidcore
1512 goals := strings.Join(dist.Targets, " ")
1513
1514 // Get the tag representing the output files to be dist'd. e.g. ".jar", ".proguard_map"
1515 var tag string
1516 if dist.Tag == nil {
1517 // If the dist struct does not specify a tag, use the default output files tag.
1518 tag = DefaultDistTag
1519 } else {
1520 tag = *dist.Tag
1521 }
1522
1523 // Get the paths of the output files to be dist'd, represented by the tag.
1524 // Can be an empty list.
1525 tagPaths := availableTaggedDists[tag]
1526 if len(tagPaths) == 0 {
1527 // Nothing to dist for this tag, continue to the next dist.
1528 continue
1529 }
1530
1531 if len(tagPaths) > 1 && (dist.Dest != nil || dist.Suffix != nil) {
1532 errorMessage := "%s: Cannot apply dest/suffix for more than one dist " +
1533 "file for %q goals tag %q in module %s. The list of dist files, " +
1534 "which should have a single element, is:\n%s"
1535 panic(fmt.Errorf(errorMessage, mod, goals, tag, name, tagPaths))
1536 }
1537
1538 copiesForGoals := distContributions.getCopiesForGoals(goals)
1539
1540 // Iterate over each path adding a copy instruction to copiesForGoals
1541 for _, path := range tagPaths {
1542 // It's possible that the Path is nil from errant modules. Be defensive here.
1543 if path == nil {
1544 tagName := "default" // for error message readability
1545 if dist.Tag != nil {
1546 tagName = *dist.Tag
1547 }
1548 panic(fmt.Errorf("Dist file should not be nil for the %s tag in %s", tagName, name))
1549 }
1550
1551 dest := filepath.Base(path.String())
1552
1553 if dist.Dest != nil {
1554 var err error
1555 if dest, err = validateSafePath(*dist.Dest); err != nil {
1556 // This was checked in ModuleBase.GenerateBuildActions
1557 panic(err)
1558 }
1559 }
1560
1561 ext := filepath.Ext(dest)
1562 suffix := ""
1563 if dist.Suffix != nil {
1564 suffix = *dist.Suffix
1565 }
1566
1567 productString := ""
1568 if dist.Append_artifact_with_product != nil && *dist.Append_artifact_with_product {
1569 productString = fmt.Sprintf("_%s", ctx.Config().DeviceProduct())
1570 }
1571
1572 if suffix != "" || productString != "" {
1573 dest = strings.TrimSuffix(dest, ext) + suffix + productString + ext
1574 }
1575
1576 if dist.Dir != nil {
1577 var err error
1578 if dest, err = validateSafePath(*dist.Dir, dest); err != nil {
1579 // This was checked in ModuleBase.GenerateBuildActions
1580 panic(err)
1581 }
1582 }
1583
1584 copiesForGoals.addCopyInstruction(path, dest)
1585 }
1586 }
1587
1588 return distContributions
1589}
1590
1591func deepCopyAndroidMkProviderInfo(providerInfo *AndroidMkProviderInfo) AndroidMkProviderInfo {
1592 info := AndroidMkProviderInfo{
1593 PrimaryInfo: deepCopyAndroidMkInfo(&providerInfo.PrimaryInfo),
1594 }
1595 if len(providerInfo.ExtraInfo) > 0 {
1596 for _, i := range providerInfo.ExtraInfo {
1597 info.ExtraInfo = append(info.ExtraInfo, deepCopyAndroidMkInfo(&i))
1598 }
1599 }
1600 return info
1601}
1602
1603func deepCopyAndroidMkInfo(mkinfo *AndroidMkInfo) AndroidMkInfo {
1604 info := AndroidMkInfo{
1605 Class: mkinfo.Class,
1606 SubName: mkinfo.SubName,
1607 OverrideName: mkinfo.OverrideName,
1608 // There is no modification on DistFiles or OutputFile, so no need to
1609 // make their deep copy.
1610 DistFiles: mkinfo.DistFiles,
1611 OutputFile: mkinfo.OutputFile,
1612 Disabled: mkinfo.Disabled,
1613 Include: mkinfo.Include,
1614 Required: deepCopyStringSlice(mkinfo.Required),
1615 Host_required: deepCopyStringSlice(mkinfo.Host_required),
1616 Target_required: deepCopyStringSlice(mkinfo.Target_required),
1617 HeaderStrings: deepCopyStringSlice(mkinfo.HeaderStrings),
1618 FooterStrings: deepCopyStringSlice(mkinfo.FooterStrings),
1619 EntryOrder: deepCopyStringSlice(mkinfo.EntryOrder),
1620 }
1621 info.EntryMap = make(map[string][]string)
1622 for k, v := range mkinfo.EntryMap {
1623 info.EntryMap[k] = deepCopyStringSlice(v)
1624 }
1625
1626 return info
1627}
1628
1629func deepCopyStringSlice(original []string) []string {
1630 result := make([]string, len(original))
1631 copy(result, original)
1632 return result
1633}