blob: 62ab5966d91f8beb6e847ea8a3a1da80db7d6c4b [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 Cross836e3872021-11-09 12:30:59 -080037 "github.com/google/blueprint/pathtools"
Jiyong Park3f627e62024-05-01 16:14:38 +090038 "github.com/google/blueprint/proptools"
Dan Willemsen218f6562015-07-08 18:13:11 -070039)
40
41func init() {
Paul Duffin8c3fec42020-03-04 20:15:08 +000042 RegisterAndroidMkBuildComponents(InitRegistrationContext)
43}
44
45func RegisterAndroidMkBuildComponents(ctx RegistrationContext) {
LaMont Jones0c10e4d2023-05-16 00:58:37 +000046 ctx.RegisterParallelSingletonType("androidmk", AndroidMkSingleton)
Dan Willemsen218f6562015-07-08 18:13:11 -070047}
48
Paul Duffin6c9da042021-03-07 15:44:41 +000049// Enable androidmk support.
50// * Register the singleton
51// * Configure that we are inside make
52var PrepareForTestWithAndroidMk = GroupFixturePreparers(
53 FixtureRegisterWithContext(RegisterAndroidMkBuildComponents),
54 FixtureModifyConfig(SetKatiEnabledForTests),
55)
56
Jaewoong Jung7ef4a902020-11-16 12:50:29 -080057// Deprecated: Use AndroidMkEntriesProvider instead, especially if you're not going to use the
58// Custom function. It's easier to use and test.
Dan Willemsen218f6562015-07-08 18:13:11 -070059type AndroidMkDataProvider interface {
Colin Crossa18e9cf2017-08-10 17:00:19 -070060 AndroidMk() AndroidMkData
Colin Crossce75d2c2016-10-06 16:12:58 -070061 BaseModuleName() string
Dan Willemsen218f6562015-07-08 18:13:11 -070062}
63
64type AndroidMkData struct {
Sasha Smundakb6d23052019-04-01 18:37:36 -070065 Class string
66 SubName string
Sasha Smundakb6d23052019-04-01 18:37:36 -070067 OutputFile OptionalPath
68 Disabled bool
69 Include string
70 Required []string
71 Host_required []string
72 Target_required []string
Dan Willemsen218f6562015-07-08 18:13:11 -070073
Colin Cross0f86d182017-08-10 17:07:28 -070074 Custom func(w io.Writer, name, prefix, moduleDir string, data AndroidMkData)
Dan Willemsen218f6562015-07-08 18:13:11 -070075
Colin Cross27a4b052017-08-10 16:32:23 -070076 Extra []AndroidMkExtraFunc
Colin Cross0f86d182017-08-10 17:07:28 -070077
Jooyung Han2ed99d02020-06-24 23:26:26 +090078 Entries AndroidMkEntries
Dan Willemsen218f6562015-07-08 18:13:11 -070079}
80
Colin Cross27a4b052017-08-10 16:32:23 -070081type AndroidMkExtraFunc func(w io.Writer, outputFile Path)
82
Jaewoong Jung7ef4a902020-11-16 12:50:29 -080083// Interface for modules to declare their Android.mk outputs. Note that every module needs to
84// implement this in order to be included in the final Android-<product_name>.mk output, even if
85// they only need to output the common set of entries without any customizations.
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -070086type AndroidMkEntriesProvider interface {
Jaewoong Jung7ef4a902020-11-16 12:50:29 -080087 // Returns AndroidMkEntries objects that contain all basic info plus extra customization data
88 // if needed. This is the core func to implement.
89 // Note that one can return multiple objects. For example, java_library may return an additional
90 // AndroidMkEntries object for its hostdex sub-module.
Jiyong Park0b0e1b92019-12-03 13:24:29 +090091 AndroidMkEntries() []AndroidMkEntries
Jaewoong Jung7ef4a902020-11-16 12:50:29 -080092 // Modules don't need to implement this as it's already implemented by ModuleBase.
93 // AndroidMkEntries uses BaseModuleName() instead of ModuleName() because certain modules
94 // e.g. Prebuilts, override the Name() func and return modified names.
95 // If a different name is preferred, use SubName or OverrideName in AndroidMkEntries.
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -070096 BaseModuleName() string
97}
98
Jaewoong Jung7ef4a902020-11-16 12:50:29 -080099// The core data struct that modules use to provide their Android.mk data.
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700100type AndroidMkEntries struct {
Jaewoong Jung7ef4a902020-11-16 12:50:29 -0800101 // Android.mk class string, e.g EXECUTABLES, JAVA_LIBRARIES, ETC
102 Class string
103 // Optional suffix to append to the module name. Useful when a module wants to return multiple
104 // AndroidMkEntries objects. For example, when a java_library returns an additional entry for
105 // its hostdex sub-module, this SubName field is set to "-hostdex" so that it can have a
106 // different name than the parent's.
107 SubName string
108 // If set, this value overrides the base module name. SubName is still appended.
109 OverrideName string
110 // Dist files to output
111 DistFiles TaggedDistFiles
112 // The output file for Kati to process and/or install. If absent, the module is skipped.
113 OutputFile OptionalPath
114 // If true, the module is skipped and does not appear on the final Android-<product name>.mk
115 // file. Useful when a module needs to be skipped conditionally.
116 Disabled bool
Ivan Lozanod06cc742021-11-12 13:27:58 -0500117 // The postprocessing mk file to include, e.g. $(BUILD_SYSTEM)/soong_cc_rust_prebuilt.mk
Jaewoong Jung7ef4a902020-11-16 12:50:29 -0800118 // If not set, $(BUILD_SYSTEM)/prebuilt.mk is used.
119 Include string
120 // Required modules that need to be built and included in the final build output when building
121 // this module.
122 Required []string
123 // Required host modules that need to be built and included in the final build output when
124 // building this module.
125 Host_required []string
126 // Required device modules that need to be built and included in the final build output when
127 // building this module.
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700128 Target_required []string
129
130 header bytes.Buffer
131 footer bytes.Buffer
132
Jaewoong Jung7ef4a902020-11-16 12:50:29 -0800133 // Funcs to append additional Android.mk entries or modify the common ones. Multiple funcs are
134 // accepted so that common logic can be factored out as a shared func.
Jaewoong Junge0dc8df2019-08-27 17:33:16 -0700135 ExtraEntries []AndroidMkExtraEntriesFunc
Jaewoong Jung7ef4a902020-11-16 12:50:29 -0800136 // Funcs to add extra lines to the module's Android.mk output. Unlike AndroidMkExtraEntriesFunc,
137 // which simply sets Make variable values, this can be used for anything since it can write any
138 // Make statements directly to the final Android-*.mk file.
139 // Primarily used to call macros or declare/update Make targets.
Jaewoong Jungb0c127c2019-08-29 14:56:03 -0700140 ExtraFooters []AndroidMkExtraFootersFunc
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700141
Jaewoong Jung7ef4a902020-11-16 12:50:29 -0800142 // A map that holds the up-to-date Make variable values. Can be accessed from tests.
143 EntryMap map[string][]string
144 // A list of EntryMap keys in insertion order. This serves a few purposes:
145 // 1. Prevents churns. Golang map doesn't provide consistent iteration order, so without this,
146 // the outputted Android-*.mk file may change even though there have been no content changes.
147 // 2. Allows modules to refer to other variables, like LOCAL_BAR_VAR := $(LOCAL_FOO_VAR),
148 // without worrying about the variables being mixed up in the actual mk file.
149 // 3. Makes troubleshooting and spotting errors easier.
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700150 entryOrder []string
Trevor Radcliffe90727f42022-03-21 19:34:02 +0000151
152 // Provides data typically stored by Context objects that are commonly needed by
153 //AndroidMkEntries objects.
154 entryContext AndroidMkEntriesContext
155}
156
157type AndroidMkEntriesContext interface {
Yu Liuec810542024-08-26 18:09:15 +0000158 OtherModuleProviderContext
Trevor Radcliffe90727f42022-03-21 19:34:02 +0000159 Config() Config
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700160}
161
Colin Crossaa255532020-07-03 13:18:24 -0700162type AndroidMkExtraEntriesContext interface {
Colin Cross3c0a83d2023-12-12 14:13:26 -0800163 Provider(provider blueprint.AnyProviderKey) (any, bool)
Colin Crossaa255532020-07-03 13:18:24 -0700164}
165
166type androidMkExtraEntriesContext struct {
167 ctx fillInEntriesContext
168 mod blueprint.Module
169}
170
Colin Cross3c0a83d2023-12-12 14:13:26 -0800171func (a *androidMkExtraEntriesContext) Provider(provider blueprint.AnyProviderKey) (any, bool) {
Yu Liu663e4502024-08-12 18:23:59 +0000172 return a.ctx.otherModuleProvider(a.mod, provider)
Colin Crossaa255532020-07-03 13:18:24 -0700173}
174
175type AndroidMkExtraEntriesFunc func(ctx AndroidMkExtraEntriesContext, entries *AndroidMkEntries)
Jaewoong Jung02b11a62020-12-07 10:23:54 -0800176type AndroidMkExtraFootersFunc func(w io.Writer, name, prefix, moduleDir string)
Jaewoong Junge0dc8df2019-08-27 17:33:16 -0700177
Jaewoong Jung7ef4a902020-11-16 12:50:29 -0800178// Utility funcs to manipulate Android.mk variable entries.
179
180// SetString sets a Make variable with the given name to the given value.
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700181func (a *AndroidMkEntries) SetString(name, value string) {
182 if _, ok := a.EntryMap[name]; !ok {
183 a.entryOrder = append(a.entryOrder, name)
184 }
185 a.EntryMap[name] = []string{value}
186}
187
Jaewoong Jung7ef4a902020-11-16 12:50:29 -0800188// SetPath sets a Make variable with the given name to the given path string.
Jaewoong Jung9a1e8bd2019-09-04 20:17:54 -0700189func (a *AndroidMkEntries) SetPath(name string, path Path) {
190 if _, ok := a.EntryMap[name]; !ok {
191 a.entryOrder = append(a.entryOrder, name)
192 }
193 a.EntryMap[name] = []string{path.String()}
194}
195
Jaewoong Jung7ef4a902020-11-16 12:50:29 -0800196// SetOptionalPath sets a Make variable with the given name to the given path string if it is valid.
197// It is a no-op if the given path is invalid.
Colin Crossc0efd1d2020-07-03 11:56:24 -0700198func (a *AndroidMkEntries) SetOptionalPath(name string, path OptionalPath) {
199 if path.Valid() {
200 a.SetPath(name, path.Path())
201 }
202}
203
Jaewoong Jung7ef4a902020-11-16 12:50:29 -0800204// AddPath appends the given path string to a Make variable with the given name.
Colin Crossc0efd1d2020-07-03 11:56:24 -0700205func (a *AndroidMkEntries) AddPath(name string, path Path) {
206 if _, ok := a.EntryMap[name]; !ok {
207 a.entryOrder = append(a.entryOrder, name)
208 }
209 a.EntryMap[name] = append(a.EntryMap[name], path.String())
210}
211
Jaewoong Jung7ef4a902020-11-16 12:50:29 -0800212// AddOptionalPath appends the given path string to a Make variable with the given name if it is
213// valid. It is a no-op if the given path is invalid.
Colin Crossc0efd1d2020-07-03 11:56:24 -0700214func (a *AndroidMkEntries) AddOptionalPath(name string, path OptionalPath) {
215 if path.Valid() {
216 a.AddPath(name, path.Path())
217 }
218}
219
Jaewoong Jung7ef4a902020-11-16 12:50:29 -0800220// SetPaths sets a Make variable with the given name to a slice of the given path strings.
Colin Cross08dca382020-07-21 20:31:17 -0700221func (a *AndroidMkEntries) SetPaths(name string, paths Paths) {
222 if _, ok := a.EntryMap[name]; !ok {
223 a.entryOrder = append(a.entryOrder, name)
224 }
225 a.EntryMap[name] = paths.Strings()
226}
227
Jaewoong Jung7ef4a902020-11-16 12:50:29 -0800228// SetOptionalPaths sets a Make variable with the given name to a slice of the given path strings
229// only if there are a non-zero amount of paths.
Colin Cross08dca382020-07-21 20:31:17 -0700230func (a *AndroidMkEntries) SetOptionalPaths(name string, paths Paths) {
231 if len(paths) > 0 {
232 a.SetPaths(name, paths)
233 }
234}
235
Jaewoong Jung7ef4a902020-11-16 12:50:29 -0800236// AddPaths appends the given path strings to a Make variable with the given name.
Colin Cross08dca382020-07-21 20:31:17 -0700237func (a *AndroidMkEntries) AddPaths(name string, paths Paths) {
238 if _, ok := a.EntryMap[name]; !ok {
239 a.entryOrder = append(a.entryOrder, name)
240 }
241 a.EntryMap[name] = append(a.EntryMap[name], paths.Strings()...)
242}
243
Jaewoong Jung7ef4a902020-11-16 12:50:29 -0800244// SetBoolIfTrue sets a Make variable with the given name to true if the given flag is true.
245// It is a no-op if the given flag is false.
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700246func (a *AndroidMkEntries) SetBoolIfTrue(name string, flag bool) {
247 if flag {
248 if _, ok := a.EntryMap[name]; !ok {
249 a.entryOrder = append(a.entryOrder, name)
250 }
251 a.EntryMap[name] = []string{"true"}
252 }
253}
254
Jaewoong Jung7ef4a902020-11-16 12:50:29 -0800255// SetBool sets a Make variable with the given name to if the given bool flag value.
Jaewoong Jung9a1e8bd2019-09-04 20:17:54 -0700256func (a *AndroidMkEntries) SetBool(name string, flag bool) {
257 if _, ok := a.EntryMap[name]; !ok {
258 a.entryOrder = append(a.entryOrder, name)
259 }
260 if flag {
261 a.EntryMap[name] = []string{"true"}
262 } else {
263 a.EntryMap[name] = []string{"false"}
264 }
265}
266
Jaewoong Jung7ef4a902020-11-16 12:50:29 -0800267// AddStrings appends the given strings to a Make variable with the given name.
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700268func (a *AndroidMkEntries) AddStrings(name string, value ...string) {
269 if len(value) == 0 {
270 return
271 }
272 if _, ok := a.EntryMap[name]; !ok {
273 a.entryOrder = append(a.entryOrder, name)
274 }
275 a.EntryMap[name] = append(a.EntryMap[name], value...)
276}
277
Liz Kammer57f5b332020-11-24 12:42:58 -0800278// AddCompatibilityTestSuites adds the supplied test suites to the EntryMap, with special handling
Tongbo Liuc5f7b962024-01-04 09:03:35 +0000279// for partial MTS and MCTS test suites.
Liz Kammer57f5b332020-11-24 12:42:58 -0800280func (a *AndroidMkEntries) AddCompatibilityTestSuites(suites ...string) {
Tongbo Liuc5f7b962024-01-04 09:03:35 +0000281 // M(C)TS supports a full test suite and partial per-module MTS test suites, with naming mts-${MODULE}.
282 // 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 -0800283 // we add the full test suite to our list.
284 if PrefixInList(suites, "mts-") && !InList("mts", suites) {
285 suites = append(suites, "mts")
286 }
Tongbo Liuc5f7b962024-01-04 09:03:35 +0000287 if PrefixInList(suites, "mcts-") && !InList("mcts", suites) {
288 suites = append(suites, "mcts")
289 }
Liz Kammer57f5b332020-11-24 12:42:58 -0800290 a.AddStrings("LOCAL_COMPATIBILITY_SUITE", suites...)
291}
292
Paul Duffin8b0349c2020-11-26 14:33:21 +0000293// The contributions to the dist.
294type distContributions struct {
Bob Badour51804382022-04-13 11:27:19 -0700295 // Path to license metadata file.
296 licenseMetadataFile Path
Paul Duffin8b0349c2020-11-26 14:33:21 +0000297 // List of goals and the dist copy instructions.
298 copiesForGoals []*copiesForGoals
299}
300
301// getCopiesForGoals returns a copiesForGoals into which copy instructions that
302// must be processed when building one or more of those goals can be added.
303func (d *distContributions) getCopiesForGoals(goals string) *copiesForGoals {
304 copiesForGoals := &copiesForGoals{goals: goals}
305 d.copiesForGoals = append(d.copiesForGoals, copiesForGoals)
306 return copiesForGoals
307}
308
309// Associates a list of dist copy instructions with a set of goals for which they
310// should be run.
311type copiesForGoals struct {
312 // goals are a space separated list of build targets that will trigger the
313 // copy instructions.
314 goals string
315
316 // A list of instructions to copy a module's output files to somewhere in the
317 // dist directory.
318 copies []distCopy
319}
320
321// Adds a copy instruction.
322func (d *copiesForGoals) addCopyInstruction(from Path, dest string) {
323 d.copies = append(d.copies, distCopy{from, dest})
324}
325
326// Instruction on a path that must be copied into the dist.
327type distCopy struct {
328 // The path to copy from.
329 from Path
330
331 // The destination within the dist directory to copy to.
332 dest string
333}
334
Jihoon Kang593171e2025-02-05 01:54:45 +0000335func (d *distCopy) String() string {
336 if len(d.dest) == 0 {
337 return d.from.String()
338 }
339 return fmt.Sprintf("%s:%s", d.from.String(), d.dest)
340}
341
342type distCopies []distCopy
343
344func (d *distCopies) Strings() (ret []string) {
345 if d == nil {
346 return
347 }
348 for _, dist := range *d {
349 ret = append(ret, dist.String())
350 }
351 return
352}
353
Paul Duffin8b0349c2020-11-26 14:33:21 +0000354// Compute the contributions that the module makes to the dist.
355func (a *AndroidMkEntries) getDistContributions(mod blueprint.Module) *distContributions {
Jingwen Chen40fd90a2020-06-15 05:24:19 +0000356 amod := mod.(Module).base()
357 name := amod.BaseModuleName()
358
Paul Duffin74f05592020-11-25 16:37:46 +0000359 // Collate the set of associated tag/paths available for copying to the dist.
360 // Start with an empty (nil) set.
Jingwen Chen7b27ca72020-07-24 09:13:49 +0000361 var availableTaggedDists TaggedDistFiles
Jingwen Chen40fd90a2020-06-15 05:24:19 +0000362
Paul Duffin74f05592020-11-25 16:37:46 +0000363 // Then merge in any that are provided explicitly by the module.
Jingwen Chen84811862020-07-21 11:32:19 +0000364 if a.DistFiles != nil {
Paul Duffin74f05592020-11-25 16:37:46 +0000365 // Merge the DistFiles into the set.
366 availableTaggedDists = availableTaggedDists.merge(a.DistFiles)
367 }
368
369 // If no paths have been provided for the DefaultDistTag and the output file is
370 // valid then add that as the default dist path.
371 if _, ok := availableTaggedDists[DefaultDistTag]; !ok && a.OutputFile.Valid() {
372 availableTaggedDists = availableTaggedDists.addPathsForTag(DefaultDistTag, a.OutputFile.Path())
373 }
374
Yu Liuec810542024-08-26 18:09:15 +0000375 info := OtherModuleProviderOrDefault(a.entryContext, mod, InstallFilesProvider)
Paul Duffinaf970a22020-11-23 23:32:56 +0000376 // If the distFiles created by GenerateTaggedDistFiles contains paths for the
377 // DefaultDistTag then that takes priority so delete any existing paths.
Yu Liuec810542024-08-26 18:09:15 +0000378 if _, ok := info.DistFiles[DefaultDistTag]; ok {
Paul Duffinaf970a22020-11-23 23:32:56 +0000379 delete(availableTaggedDists, DefaultDistTag)
380 }
381
382 // Finally, merge the distFiles created by GenerateTaggedDistFiles.
Yu Liuec810542024-08-26 18:09:15 +0000383 availableTaggedDists = availableTaggedDists.merge(info.DistFiles)
Paul Duffinaf970a22020-11-23 23:32:56 +0000384
Paul Duffin74f05592020-11-25 16:37:46 +0000385 if len(availableTaggedDists) == 0 {
Jingwen Chen7b27ca72020-07-24 09:13:49 +0000386 // Nothing dist-able for this module.
387 return nil
Jingwen Chen40fd90a2020-06-15 05:24:19 +0000388 }
389
Paul Duffin8b0349c2020-11-26 14:33:21 +0000390 // Collate the contributions this module makes to the dist.
391 distContributions := &distContributions{}
392
Bob Badour4660a982022-09-12 16:06:03 -0700393 if !exemptFromRequiredApplicableLicensesProperty(mod.(Module)) {
Yu Liuec810542024-08-26 18:09:15 +0000394 distContributions.licenseMetadataFile = info.LicenseMetadataFile
Bob Badour4660a982022-09-12 16:06:03 -0700395 }
Bob Badour51804382022-04-13 11:27:19 -0700396
Jingwen Chen40fd90a2020-06-15 05:24:19 +0000397 // Iterate over this module's dist structs, merged from the dist and dists properties.
398 for _, dist := range amod.Dists() {
399 // Get the list of goals this dist should be enabled for. e.g. sdk, droidcore
400 goals := strings.Join(dist.Targets, " ")
401
402 // Get the tag representing the output files to be dist'd. e.g. ".jar", ".proguard_map"
403 var tag string
404 if dist.Tag == nil {
405 // If the dist struct does not specify a tag, use the default output files tag.
Paul Duffin74f05592020-11-25 16:37:46 +0000406 tag = DefaultDistTag
Jingwen Chen40fd90a2020-06-15 05:24:19 +0000407 } else {
408 tag = *dist.Tag
409 }
410
411 // Get the paths of the output files to be dist'd, represented by the tag.
412 // Can be an empty list.
413 tagPaths := availableTaggedDists[tag]
414 if len(tagPaths) == 0 {
415 // Nothing to dist for this tag, continue to the next dist.
416 continue
417 }
418
419 if len(tagPaths) > 1 && (dist.Dest != nil || dist.Suffix != nil) {
Paul Duffin74f05592020-11-25 16:37:46 +0000420 errorMessage := "%s: Cannot apply dest/suffix for more than one dist " +
421 "file for %q goals tag %q in module %s. The list of dist files, " +
Jingwen Chen40fd90a2020-06-15 05:24:19 +0000422 "which should have a single element, is:\n%s"
Paul Duffin74f05592020-11-25 16:37:46 +0000423 panic(fmt.Errorf(errorMessage, mod, goals, tag, name, tagPaths))
Jingwen Chen40fd90a2020-06-15 05:24:19 +0000424 }
425
Paul Duffin8b0349c2020-11-26 14:33:21 +0000426 copiesForGoals := distContributions.getCopiesForGoals(goals)
Jingwen Chen40fd90a2020-06-15 05:24:19 +0000427
Paul Duffin8b0349c2020-11-26 14:33:21 +0000428 // Iterate over each path adding a copy instruction to copiesForGoals
Jingwen Chen40fd90a2020-06-15 05:24:19 +0000429 for _, path := range tagPaths {
430 // It's possible that the Path is nil from errant modules. Be defensive here.
431 if path == nil {
432 tagName := "default" // for error message readability
433 if dist.Tag != nil {
434 tagName = *dist.Tag
435 }
436 panic(fmt.Errorf("Dist file should not be nil for the %s tag in %s", tagName, name))
437 }
438
439 dest := filepath.Base(path.String())
440
441 if dist.Dest != nil {
442 var err error
443 if dest, err = validateSafePath(*dist.Dest); err != nil {
444 // This was checked in ModuleBase.GenerateBuildActions
445 panic(err)
446 }
447 }
448
Trevor Radcliffe90727f42022-03-21 19:34:02 +0000449 ext := filepath.Ext(dest)
450 suffix := ""
Jingwen Chen40fd90a2020-06-15 05:24:19 +0000451 if dist.Suffix != nil {
Trevor Radcliffe90727f42022-03-21 19:34:02 +0000452 suffix = *dist.Suffix
453 }
454
455 productString := ""
456 if dist.Append_artifact_with_product != nil && *dist.Append_artifact_with_product {
457 productString = fmt.Sprintf("_%s", a.entryContext.Config().DeviceProduct())
458 }
459
460 if suffix != "" || productString != "" {
461 dest = strings.TrimSuffix(dest, ext) + suffix + productString + ext
Jingwen Chen40fd90a2020-06-15 05:24:19 +0000462 }
463
464 if dist.Dir != nil {
465 var err error
466 if dest, err = validateSafePath(*dist.Dir, dest); err != nil {
467 // This was checked in ModuleBase.GenerateBuildActions
468 panic(err)
469 }
470 }
471
Paul Duffin8b0349c2020-11-26 14:33:21 +0000472 copiesForGoals.addCopyInstruction(path, dest)
473 }
474 }
475
476 return distContributions
477}
478
479// generateDistContributionsForMake generates make rules that will generate the
480// dist according to the instructions in the supplied distContribution.
481func generateDistContributionsForMake(distContributions *distContributions) []string {
482 var ret []string
483 for _, d := range distContributions.copiesForGoals {
Yu Liue70976d2024-10-15 20:45:35 +0000484 ret = append(ret, fmt.Sprintf(".PHONY: %s", d.goals))
Paul Duffin8b0349c2020-11-26 14:33:21 +0000485 // Create dist-for-goals calls for each of the copy instructions.
486 for _, c := range d.copies {
Bob Badour4660a982022-09-12 16:06:03 -0700487 if distContributions.licenseMetadataFile != nil {
488 ret = append(
489 ret,
Yu Liue70976d2024-10-15 20:45:35 +0000490 fmt.Sprintf("$(if $(strip $(ALL_TARGETS.%s.META_LIC)),,$(eval ALL_TARGETS.%s.META_LIC := %s))",
Bob Badour4660a982022-09-12 16:06:03 -0700491 c.from.String(), c.from.String(), distContributions.licenseMetadataFile.String()))
492 }
Bob Badour51804382022-04-13 11:27:19 -0700493 ret = append(
494 ret,
Yu Liue70976d2024-10-15 20:45:35 +0000495 fmt.Sprintf("$(call dist-for-goals,%s,%s:%s)", d.goals, c.from.String(), c.dest))
Jingwen Chen40fd90a2020-06-15 05:24:19 +0000496 }
497 }
498
499 return ret
500}
501
Paul Duffin8b0349c2020-11-26 14:33:21 +0000502// Compute the list of Make strings to declare phony goals and dist-for-goals
503// calls from the module's dist and dists properties.
504func (a *AndroidMkEntries) GetDistForGoals(mod blueprint.Module) []string {
505 distContributions := a.getDistContributions(mod)
506 if distContributions == nil {
507 return nil
508 }
509
510 return generateDistContributionsForMake(distContributions)
511}
512
Jaewoong Jung7ef4a902020-11-16 12:50:29 -0800513// fillInEntries goes through the common variable processing and calls the extra data funcs to
514// generate and fill in AndroidMkEntries's in-struct data, ready to be flushed to a file.
Colin Crossaa255532020-07-03 13:18:24 -0700515type fillInEntriesContext interface {
516 ModuleDir(module blueprint.Module) string
Cole Faust39aabe92023-02-23 16:57:43 -0800517 ModuleSubDir(module blueprint.Module) string
Colin Crossaa255532020-07-03 13:18:24 -0700518 Config() Config
Yu Liu663e4502024-08-12 18:23:59 +0000519 otherModuleProvider(module blueprint.Module, provider blueprint.AnyProviderKey) (any, bool)
Sasha Smundak5c4729d2022-12-01 10:49:23 -0800520 ModuleType(module blueprint.Module) string
Cole Faust43ddd082024-06-17 12:32:40 -0700521 OtherModulePropertyErrorf(module Module, property string, fmt string, args ...interface{})
Cole Faust4e2bf9f2024-09-11 13:26:20 -0700522 HasMutatorFinished(mutatorName string) bool
Colin Crossaa255532020-07-03 13:18:24 -0700523}
524
525func (a *AndroidMkEntries) fillInEntries(ctx fillInEntriesContext, mod blueprint.Module) {
Trevor Radcliffe90727f42022-03-21 19:34:02 +0000526 a.entryContext = ctx
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700527 a.EntryMap = make(map[string][]string)
Colin Crossf1f763a2021-10-21 16:14:19 -0700528 amod := mod.(Module)
529 base := amod.base()
530 name := base.BaseModuleName()
Colin Cross0477b422020-10-13 18:43:54 -0700531 if a.OverrideName != "" {
532 name = a.OverrideName
533 }
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700534
535 if a.Include == "" {
536 a.Include = "$(BUILD_PREBUILT)"
537 }
Cole Faust43ddd082024-06-17 12:32:40 -0700538 a.Required = append(a.Required, amod.RequiredModuleNames(ctx)...)
Kiyoung Kim04b64fc2024-08-19 11:25:30 +0900539 a.Required = append(a.Required, amod.VintfFragmentModuleNames(ctx)...)
Colin Crossf1f763a2021-10-21 16:14:19 -0700540 a.Host_required = append(a.Host_required, amod.HostRequiredModuleNames()...)
541 a.Target_required = append(a.Target_required, amod.TargetRequiredModuleNames()...)
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700542
Jingwen Chen40fd90a2020-06-15 05:24:19 +0000543 for _, distString := range a.GetDistForGoals(mod) {
Yu Liue70976d2024-10-15 20:45:35 +0000544 fmt.Fprintln(&a.header, distString)
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700545 }
546
Cole Faust39aabe92023-02-23 16:57:43 -0800547 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 -0700548
549 // Collect make variable assignment entries.
Colin Crossaa255532020-07-03 13:18:24 -0700550 a.SetString("LOCAL_PATH", ctx.ModuleDir(mod))
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700551 a.SetString("LOCAL_MODULE", name+a.SubName)
552 a.SetString("LOCAL_MODULE_CLASS", a.Class)
553 a.SetString("LOCAL_PREBUILT_MODULE_FILE", a.OutputFile.String())
554 a.AddStrings("LOCAL_REQUIRED_MODULES", a.Required...)
555 a.AddStrings("LOCAL_HOST_REQUIRED_MODULES", a.Host_required...)
556 a.AddStrings("LOCAL_TARGET_REQUIRED_MODULES", a.Target_required...)
Wei Li598f92d2023-01-04 17:12:24 -0800557 a.AddStrings("LOCAL_SOONG_MODULE_TYPE", ctx.ModuleType(amod))
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700558
Colin Cross6301c3c2021-09-28 17:40:21 -0700559 // If the install rule was generated by Soong tell Make about it.
Yu Liud46e5ae2024-08-15 18:46:17 +0000560 info := OtherModuleProviderOrDefault(ctx, mod, InstallFilesProvider)
561 if len(info.KatiInstalls) > 0 {
Colin Cross6301c3c2021-09-28 17:40:21 -0700562 // Assume the primary install file is last since it probably needs to depend on any other
563 // installed files. If that is not the case we can add a method to specify the primary
564 // installed file.
Yu Liud46e5ae2024-08-15 18:46:17 +0000565 a.SetPath("LOCAL_SOONG_INSTALLED_MODULE", info.KatiInstalls[len(info.KatiInstalls)-1].to)
566 a.SetString("LOCAL_SOONG_INSTALL_PAIRS", info.KatiInstalls.BuiltInstalled())
567 a.SetPaths("LOCAL_SOONG_INSTALL_SYMLINKS", info.KatiSymlinks.InstallPaths().Paths())
Jiyong Park3f627e62024-05-01 16:14:38 +0900568 } else {
569 // Soong may not have generated the install rule also when `no_full_install: true`.
570 // Mark this module as uninstallable in order to prevent Make from creating an
571 // install rule there.
572 a.SetBoolIfTrue("LOCAL_UNINSTALLABLE_MODULE", proptools.Bool(base.commonProperties.No_full_install))
Colin Cross6301c3c2021-09-28 17:40:21 -0700573 }
574
Colin Crossa6182ab2024-08-21 10:47:44 -0700575 if info.UncheckedModule {
576 a.SetBool("LOCAL_DONT_CHECK_MODULE", true)
577 } else if info.CheckbuildTarget != nil {
578 a.SetPath("LOCAL_CHECKED_MODULE", info.CheckbuildTarget)
579 } else {
580 a.SetOptionalPath("LOCAL_CHECKED_MODULE", a.OutputFile)
581 }
582
Yu Liud46e5ae2024-08-15 18:46:17 +0000583 if len(info.TestData) > 0 {
584 a.AddStrings("LOCAL_TEST_DATA", androidMkDataPaths(info.TestData)...)
Colin Cross5c1d5fb2023-11-15 12:39:40 -0800585 }
586
Jiyong Park89e850a2020-04-07 16:37:39 +0900587 if am, ok := mod.(ApexModule); ok {
588 a.SetBoolIfTrue("LOCAL_NOT_AVAILABLE_FOR_PLATFORM", am.NotAvailableForPlatform())
589 }
590
Colin Crossf1f763a2021-10-21 16:14:19 -0700591 archStr := base.Arch().ArchType.String()
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700592 host := false
Colin Crossf1f763a2021-10-21 16:14:19 -0700593 switch base.Os().Class {
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700594 case Host:
Colin Crossf1f763a2021-10-21 16:14:19 -0700595 if base.Target().HostCross {
Jiyong Park1613e552020-09-14 19:43:17 +0900596 // Make cannot identify LOCAL_MODULE_HOST_CROSS_ARCH:= common.
Colin Crossf1f763a2021-10-21 16:14:19 -0700597 if base.Arch().ArchType != Common {
Jiyong Park1613e552020-09-14 19:43:17 +0900598 a.SetString("LOCAL_MODULE_HOST_CROSS_ARCH", archStr)
599 }
600 } else {
601 // Make cannot identify LOCAL_MODULE_HOST_ARCH:= common.
Colin Crossf1f763a2021-10-21 16:14:19 -0700602 if base.Arch().ArchType != Common {
Jiyong Park1613e552020-09-14 19:43:17 +0900603 a.SetString("LOCAL_MODULE_HOST_ARCH", archStr)
604 }
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700605 }
606 host = true
607 case Device:
608 // Make cannot identify LOCAL_MODULE_TARGET_ARCH:= common.
Colin Crossf1f763a2021-10-21 16:14:19 -0700609 if base.Arch().ArchType != Common {
610 if base.Target().NativeBridge {
611 hostArchStr := base.Target().NativeBridgeHostArchName
dimitry1f33e402019-03-26 12:39:31 +0100612 if hostArchStr != "" {
613 a.SetString("LOCAL_MODULE_TARGET_ARCH", hostArchStr)
614 }
615 } else {
616 a.SetString("LOCAL_MODULE_TARGET_ARCH", archStr)
617 }
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700618 }
619
Kelvin Zhang46977252022-04-13 16:41:34 -0700620 if !base.InVendorRamdisk() {
Yu Liu82a6d142024-08-27 19:02:29 +0000621 a.AddPaths("LOCAL_FULL_INIT_RC", info.InitRcPaths)
Yifan Hong919dae12020-12-02 18:55:06 -0800622 }
Yu Liu82a6d142024-08-27 19:02:29 +0000623 if len(info.VintfFragmentsPaths) > 0 {
624 a.AddPaths("LOCAL_FULL_VINTF_FRAGMENTS", info.VintfFragmentsPaths)
Liz Kammer7b3dc8a2021-04-16 16:41:59 -0400625 }
Colin Crossf1f763a2021-10-21 16:14:19 -0700626 a.SetBoolIfTrue("LOCAL_PROPRIETARY_MODULE", Bool(base.commonProperties.Proprietary))
627 if Bool(base.commonProperties.Vendor) || Bool(base.commonProperties.Soc_specific) {
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700628 a.SetString("LOCAL_VENDOR_MODULE", "true")
629 }
Colin Crossf1f763a2021-10-21 16:14:19 -0700630 a.SetBoolIfTrue("LOCAL_ODM_MODULE", Bool(base.commonProperties.Device_specific))
631 a.SetBoolIfTrue("LOCAL_PRODUCT_MODULE", Bool(base.commonProperties.Product_specific))
632 a.SetBoolIfTrue("LOCAL_SYSTEM_EXT_MODULE", Bool(base.commonProperties.System_ext_specific))
633 if base.commonProperties.Owner != nil {
634 a.SetString("LOCAL_MODULE_OWNER", *base.commonProperties.Owner)
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700635 }
636 }
637
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700638 if host {
Colin Crossf1f763a2021-10-21 16:14:19 -0700639 makeOs := base.Os().String()
640 if base.Os() == Linux || base.Os() == LinuxBionic || base.Os() == LinuxMusl {
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700641 makeOs = "linux"
642 }
643 a.SetString("LOCAL_MODULE_HOST_OS", makeOs)
644 a.SetString("LOCAL_IS_HOST_MODULE", "true")
645 }
646
647 prefix := ""
Colin Crossf1f763a2021-10-21 16:14:19 -0700648 if base.ArchSpecific() {
649 switch base.Os().Class {
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700650 case Host:
Colin Crossf1f763a2021-10-21 16:14:19 -0700651 if base.Target().HostCross {
Jiyong Park1613e552020-09-14 19:43:17 +0900652 prefix = "HOST_CROSS_"
653 } else {
654 prefix = "HOST_"
655 }
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700656 case Device:
657 prefix = "TARGET_"
658
659 }
660
Colin Crossf1f763a2021-10-21 16:14:19 -0700661 if base.Arch().ArchType != ctx.Config().Targets[base.Os()][0].Arch.ArchType {
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700662 prefix = "2ND_" + prefix
663 }
664 }
Colin Crossaa255532020-07-03 13:18:24 -0700665
Yu Liu663e4502024-08-12 18:23:59 +0000666 if licenseMetadata, ok := OtherModuleProvider(ctx, mod, LicenseMetadataProvider); ok {
Colin Cross4acaea92021-12-10 23:05:02 +0000667 a.SetPath("LOCAL_SOONG_LICENSE_METADATA", licenseMetadata.LicenseMetadataPath)
668 }
669
Yu Liu663e4502024-08-12 18:23:59 +0000670 if _, ok := OtherModuleProvider(ctx, mod, ModuleInfoJSONProvider); ok {
Colin Crossd6fd0132023-11-06 13:54:06 -0800671 a.SetBool("LOCAL_SOONG_MODULE_INFO_JSON", true)
672 }
673
Colin Crossaa255532020-07-03 13:18:24 -0700674 extraCtx := &androidMkExtraEntriesContext{
675 ctx: ctx,
676 mod: mod,
677 }
678
Jaewoong Junge0dc8df2019-08-27 17:33:16 -0700679 for _, extra := range a.ExtraEntries {
Colin Crossaa255532020-07-03 13:18:24 -0700680 extra(extraCtx, a)
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700681 }
682
683 // Write to footer.
684 fmt.Fprintln(&a.footer, "include "+a.Include)
Colin Crossaa255532020-07-03 13:18:24 -0700685 blueprintDir := ctx.ModuleDir(mod)
Jaewoong Jungb0c127c2019-08-29 14:56:03 -0700686 for _, footerFunc := range a.ExtraFooters {
Jaewoong Jung02b11a62020-12-07 10:23:54 -0800687 footerFunc(&a.footer, name, prefix, blueprintDir)
Jaewoong Jungb0c127c2019-08-29 14:56:03 -0700688 }
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700689}
690
Colin Crossd6fd0132023-11-06 13:54:06 -0800691func (a *AndroidMkEntries) disabled() bool {
692 return a.Disabled || !a.OutputFile.Valid()
693}
694
Jaewoong Jung7ef4a902020-11-16 12:50:29 -0800695// write flushes the AndroidMkEntries's in-struct data populated by AndroidMkEntries into the
696// given Writer object.
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700697func (a *AndroidMkEntries) write(w io.Writer) {
Colin Crossd6fd0132023-11-06 13:54:06 -0800698 if a.disabled() {
Jaewoong Jungb0c127c2019-08-29 14:56:03 -0700699 return
700 }
701
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700702 w.Write(a.header.Bytes())
703 for _, name := range a.entryOrder {
Sasha Smundakdcb61292022-12-08 10:41:33 -0800704 AndroidMkEmitAssignList(w, name, a.EntryMap[name])
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700705 }
706 w.Write(a.footer.Bytes())
707}
708
Jaewoong Jungb0c127c2019-08-29 14:56:03 -0700709func (a *AndroidMkEntries) FooterLinesForTests() []string {
710 return strings.Split(string(a.footer.Bytes()), "\n")
711}
712
Jaewoong Jung7ef4a902020-11-16 12:50:29 -0800713// AndroidMkSingleton is a singleton to collect Android.mk data from all modules and dump them into
714// the final Android-<product_name>.mk file output.
Colin Cross0875c522017-11-28 17:34:01 -0800715func AndroidMkSingleton() Singleton {
Dan Willemsen218f6562015-07-08 18:13:11 -0700716 return &androidMkSingleton{}
717}
718
719type androidMkSingleton struct{}
720
Jihoon Kang4be8eb32025-02-10 23:02:42 +0000721func allModulesSorted(ctx SingletonContext) []blueprint.Module {
722 var allModules []blueprint.Module
Colin Cross4f6e4e62016-01-11 12:55:55 -0800723
Colin Cross2465c3d2018-09-28 10:19:18 -0700724 ctx.VisitAllModulesBlueprint(func(module blueprint.Module) {
Jihoon Kang4be8eb32025-02-10 23:02:42 +0000725 allModules = append(allModules, module)
Colin Cross4f6e4e62016-01-11 12:55:55 -0800726 })
Dan Willemsen218f6562015-07-08 18:13:11 -0700727
Jaewoong Jung7ef4a902020-11-16 12:50:29 -0800728 // Sort the module list by the module names to eliminate random churns, which may erroneously
729 // invoke additional build processes.
Jihoon Kang4be8eb32025-02-10 23:02:42 +0000730 sort.SliceStable(allModules, func(i, j int) bool {
731 return ctx.ModuleName(allModules[i]) < ctx.ModuleName(allModules[j])
Colin Cross1ad81422019-01-14 12:47:35 -0800732 })
Colin Crossd779da42015-12-17 18:00:23 -0800733
Jihoon Kang4be8eb32025-02-10 23:02:42 +0000734 return allModules
735}
736
737func (c *androidMkSingleton) GenerateBuildActions(ctx SingletonContext) {
738 // If running in soong-only mode, more limited version of this singleton is run as
739 // soong only androidmk singleton
Cole Faustc5bfbdd2025-01-08 13:05:40 -0800740 if !ctx.Config().KatiEnabled() {
Cole Faustc5bfbdd2025-01-08 13:05:40 -0800741 return
742 }
743
Dan Willemsen45133ac2018-03-09 21:22:06 -0800744 transMk := PathForOutput(ctx, "Android"+String(ctx.Config().productVariables.Make_suffix)+".mk")
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700745 if ctx.Failed() {
746 return
747 }
Dan Willemsen218f6562015-07-08 18:13:11 -0700748
Colin Crossd6fd0132023-11-06 13:54:06 -0800749 moduleInfoJSON := PathForOutput(ctx, "module-info"+String(ctx.Config().productVariables.Make_suffix)+".json")
750
Jihoon Kang4be8eb32025-02-10 23:02:42 +0000751 err := translateAndroidMk(ctx, absolutePath(transMk.String()), moduleInfoJSON, allModulesSorted(ctx))
Dan Willemsen218f6562015-07-08 18:13:11 -0700752 if err != nil {
753 ctx.Errorf(err.Error())
754 }
755
Colin Cross0875c522017-11-28 17:34:01 -0800756 ctx.Build(pctx, BuildParams{
757 Rule: blueprint.Phony,
758 Output: transMk,
Dan Willemsen218f6562015-07-08 18:13:11 -0700759 })
760}
761
Jihoon Kang4be8eb32025-02-10 23:02:42 +0000762type soongOnlyAndroidMkSingleton struct {
763 Singleton
764}
765
766func soongOnlyAndroidMkSingletonFactory() Singleton {
767 return &soongOnlyAndroidMkSingleton{}
768}
769
770func (so *soongOnlyAndroidMkSingleton) GenerateBuildActions(ctx SingletonContext) {
771 if !ctx.Config().KatiEnabled() {
772 so.soongOnlyBuildActions(ctx, allModulesSorted(ctx))
773 }
774}
775
Cole Faustc5bfbdd2025-01-08 13:05:40 -0800776// In soong-only mode, we don't do most of the androidmk stuff. But disted files are still largely
777// defined through the androidmk mechanisms, so this function is an alternate implementation of
778// the androidmk singleton that just focuses on getting the dist contributions
Jihoon Kang4be8eb32025-02-10 23:02:42 +0000779func (so *soongOnlyAndroidMkSingleton) soongOnlyBuildActions(ctx SingletonContext, mods []blueprint.Module) {
Cole Faustf9a096c2025-01-21 16:55:43 -0800780 allDistContributions, moduleInfoJSONs := getSoongOnlyDataFromMods(ctx, mods)
Cole Faustc5bfbdd2025-01-08 13:05:40 -0800781
Cole Faustf2aab5e2025-02-11 13:32:51 -0800782 singletonDists := getSingletonDists(ctx.Config())
783 singletonDists.lock.Lock()
784 if contribution := distsToDistContributions(singletonDists.dists); contribution != nil {
785 allDistContributions = append(allDistContributions, *contribution)
786 }
787 singletonDists.lock.Unlock()
788
Cole Faustf9a096c2025-01-21 16:55:43 -0800789 // Build module-info.json. Only in builds with HasDeviceProduct(), as we need a named
790 // device to have a TARGET_OUT folder.
791 if ctx.Config().HasDeviceProduct() {
Cole Faust601da062025-01-22 13:15:10 -0800792 preMergePath := PathForOutput(ctx, "module_info_pre_merging.json")
Cole Faustf9a096c2025-01-21 16:55:43 -0800793 moduleInfoJSONPath := pathForInstall(ctx, Android, X86_64, "", "module-info.json")
Cole Faust601da062025-01-22 13:15:10 -0800794 if err := writeModuleInfoJSON(ctx, moduleInfoJSONs, preMergePath); err != nil {
Cole Faustf9a096c2025-01-21 16:55:43 -0800795 ctx.Errorf("%s", err)
796 }
Cole Faust601da062025-01-22 13:15:10 -0800797 builder := NewRuleBuilder(pctx, ctx)
798 builder.Command().
799 BuiltTool("merge_module_info_json").
800 FlagWithOutput("-o ", moduleInfoJSONPath).
801 Input(preMergePath)
802 builder.Build("merge_module_info_json", "merge module info json")
Cole Faustf9a096c2025-01-21 16:55:43 -0800803 ctx.Phony("module-info", moduleInfoJSONPath)
804 ctx.Phony("droidcore-unbundled", moduleInfoJSONPath)
805 allDistContributions = append(allDistContributions, distContributions{
806 copiesForGoals: []*copiesForGoals{{
807 goals: "general-tests droidcore-unbundled",
808 copies: []distCopy{{
809 from: moduleInfoJSONPath,
810 dest: "module-info.json",
811 }},
812 }},
813 })
814 }
815
816 // Build dist.mk for the packaging step to read and generate dist targets
Cole Faustc5bfbdd2025-01-08 13:05:40 -0800817 distMkFile := absolutePath(filepath.Join(ctx.Config().katiPackageMkDir(), "dist.mk"))
818
819 var goalOutputPairs []string
Cole Faust82611a12025-01-09 11:20:41 -0800820 var srcDstPairs []string
Cole Faustc5bfbdd2025-01-08 13:05:40 -0800821 for _, contributions := range allDistContributions {
822 for _, copiesForGoal := range contributions.copiesForGoals {
823 goals := strings.Fields(copiesForGoal.goals)
824 for _, copy := range copiesForGoal.copies {
825 for _, goal := range goals {
Cole Faust82611a12025-01-09 11:20:41 -0800826 goalOutputPairs = append(goalOutputPairs, fmt.Sprintf(" %s:%s", goal, copy.dest))
Cole Faustc5bfbdd2025-01-08 13:05:40 -0800827 }
Cole Faust82611a12025-01-09 11:20:41 -0800828 srcDstPairs = append(srcDstPairs, fmt.Sprintf(" %s:%s", copy.from.String(), copy.dest))
Cole Faustc5bfbdd2025-01-08 13:05:40 -0800829 }
830 }
831 }
Cole Faust82611a12025-01-09 11:20:41 -0800832 // There are duplicates in the lists that we need to remove
833 goalOutputPairs = SortedUniqueStrings(goalOutputPairs)
834 srcDstPairs = SortedUniqueStrings(srcDstPairs)
835 var buf strings.Builder
836 buf.WriteString("DIST_SRC_DST_PAIRS :=")
837 for _, srcDstPair := range srcDstPairs {
838 buf.WriteString(srcDstPair)
839 }
840 buf.WriteString("\nDIST_GOAL_OUTPUT_PAIRS :=")
841 for _, goalOutputPair := range goalOutputPairs {
842 buf.WriteString(goalOutputPair)
843 }
844 buf.WriteString("\n")
Cole Faustc5bfbdd2025-01-08 13:05:40 -0800845
846 writeValueIfChanged(ctx, distMkFile, buf.String())
847}
848
849func writeValueIfChanged(ctx SingletonContext, path string, value string) {
850 if err := os.MkdirAll(filepath.Dir(path), 0777); err != nil {
851 ctx.Errorf("%s\n", err)
852 return
853 }
854 previousValue := ""
855 rawPreviousValue, err := os.ReadFile(path)
856 if err == nil {
857 previousValue = string(rawPreviousValue)
858 }
859
860 if previousValue != value {
861 if err = os.WriteFile(path, []byte(value), 0666); err != nil {
862 ctx.Errorf("Failed to write: %v", err)
863 }
864 }
865}
866
Cole Faustd62a4892025-02-07 16:55:11 -0800867func distsToDistContributions(dists []dist) *distContributions {
868 if len(dists) == 0 {
Jihoon Kang593171e2025-02-05 01:54:45 +0000869 return nil
870 }
871
872 copyGoals := []*copiesForGoals{}
Cole Faustd62a4892025-02-07 16:55:11 -0800873 for _, dist := range dists {
Jihoon Kang593171e2025-02-05 01:54:45 +0000874 for _, goal := range dist.goals {
Cole Faustd62a4892025-02-07 16:55:11 -0800875 copyGoals = append(copyGoals, &copiesForGoals{
876 goals: goal,
877 copies: dist.paths,
878 })
Jihoon Kang593171e2025-02-05 01:54:45 +0000879 }
880 }
881
Cole Faustd62a4892025-02-07 16:55:11 -0800882 return &distContributions{
883 copiesForGoals: copyGoals,
884 }
Jihoon Kang593171e2025-02-05 01:54:45 +0000885}
886
Cole Faustf9a096c2025-01-21 16:55:43 -0800887// getSoongOnlyDataFromMods gathers data from the given modules needed in soong-only builds.
888// Currently, this is the dist contributions, and the module-info.json contents.
889func getSoongOnlyDataFromMods(ctx fillInEntriesContext, mods []blueprint.Module) ([]distContributions, []*ModuleInfoJSON) {
Cole Faustc5bfbdd2025-01-08 13:05:40 -0800890 var allDistContributions []distContributions
Cole Faustf9a096c2025-01-21 16:55:43 -0800891 var moduleInfoJSONs []*ModuleInfoJSON
Cole Faustc5bfbdd2025-01-08 13:05:40 -0800892 for _, mod := range mods {
Cole Faustd62a4892025-02-07 16:55:11 -0800893 if distInfo, ok := OtherModuleProvider(ctx, mod, DistProvider); ok {
894 if contribution := distsToDistContributions(distInfo.Dists); contribution != nil {
895 allDistContributions = append(allDistContributions, *contribution)
896 }
897 }
898
Cole Faustc5bfbdd2025-01-08 13:05:40 -0800899 if amod, ok := mod.(Module); ok && shouldSkipAndroidMkProcessing(ctx, amod.base()) {
900 continue
901 }
902 if info, ok := OtherModuleProvider(ctx, mod, AndroidMkInfoProvider); ok {
Cole Faust556f1f42025-01-09 10:49:42 -0800903 // Deep copy the provider info since we need to modify the info later
904 info := deepCopyAndroidMkProviderInfo(info)
905 info.PrimaryInfo.fillInEntries(ctx, mod)
906 if info.PrimaryInfo.disabled() {
907 continue
908 }
Cole Faustf9a096c2025-01-21 16:55:43 -0800909 if moduleInfoJSON, ok := OtherModuleProvider(ctx, mod, ModuleInfoJSONProvider); ok {
Jihoon Kangd4063812025-01-24 00:25:30 +0000910 moduleInfoJSONs = append(moduleInfoJSONs, moduleInfoJSON...)
Cole Faustf9a096c2025-01-21 16:55:43 -0800911 }
Cole Faustc5bfbdd2025-01-08 13:05:40 -0800912 if contribution := info.PrimaryInfo.getDistContributions(ctx, mod); contribution != nil {
913 allDistContributions = append(allDistContributions, *contribution)
914 }
915 for _, ei := range info.ExtraInfo {
Cole Faust556f1f42025-01-09 10:49:42 -0800916 ei.fillInEntries(ctx, mod)
917 if ei.disabled() {
918 continue
919 }
Cole Faustc5bfbdd2025-01-08 13:05:40 -0800920 if contribution := ei.getDistContributions(ctx, mod); contribution != nil {
921 allDistContributions = append(allDistContributions, *contribution)
922 }
923 }
924 } else {
Jihoon Kange6daf662025-02-06 01:38:16 +0000925 if x, ok := mod.(AndroidMkDataProvider); ok {
Cole Faustc5bfbdd2025-01-08 13:05:40 -0800926 data := x.AndroidMk()
927
928 if data.Include == "" {
929 data.Include = "$(BUILD_PREBUILT)"
930 }
931
932 data.fillInData(ctx, mod)
Cole Faust556f1f42025-01-09 10:49:42 -0800933 if data.Entries.disabled() {
934 continue
935 }
Cole Faustf9a096c2025-01-21 16:55:43 -0800936 if moduleInfoJSON, ok := OtherModuleProvider(ctx, mod, ModuleInfoJSONProvider); ok {
Jihoon Kangd4063812025-01-24 00:25:30 +0000937 moduleInfoJSONs = append(moduleInfoJSONs, moduleInfoJSON...)
Cole Faustf9a096c2025-01-21 16:55:43 -0800938 }
Cole Faustc5bfbdd2025-01-08 13:05:40 -0800939 if contribution := data.Entries.getDistContributions(mod); contribution != nil {
940 allDistContributions = append(allDistContributions, *contribution)
941 }
Jihoon Kange6daf662025-02-06 01:38:16 +0000942 }
943 if x, ok := mod.(AndroidMkEntriesProvider); ok {
Cole Faustc5bfbdd2025-01-08 13:05:40 -0800944 entriesList := x.AndroidMkEntries()
945 for _, entries := range entriesList {
946 entries.fillInEntries(ctx, mod)
Cole Faust556f1f42025-01-09 10:49:42 -0800947 if entries.disabled() {
948 continue
949 }
Cole Faustf9a096c2025-01-21 16:55:43 -0800950 if moduleInfoJSON, ok := OtherModuleProvider(ctx, mod, ModuleInfoJSONProvider); ok {
Jihoon Kangd4063812025-01-24 00:25:30 +0000951 moduleInfoJSONs = append(moduleInfoJSONs, moduleInfoJSON...)
Cole Faustf9a096c2025-01-21 16:55:43 -0800952 }
Cole Faustc5bfbdd2025-01-08 13:05:40 -0800953 if contribution := entries.getDistContributions(mod); contribution != nil {
954 allDistContributions = append(allDistContributions, *contribution)
955 }
956 }
Jihoon Kange6daf662025-02-06 01:38:16 +0000957 }
Cole Faustc5bfbdd2025-01-08 13:05:40 -0800958 }
959 }
Cole Faustf9a096c2025-01-21 16:55:43 -0800960 return allDistContributions, moduleInfoJSONs
Cole Faustc5bfbdd2025-01-08 13:05:40 -0800961}
962
Colin Crossd6fd0132023-11-06 13:54:06 -0800963func translateAndroidMk(ctx SingletonContext, absMkFile string, moduleInfoJSONPath WritablePath, mods []blueprint.Module) error {
Dan Willemsen218f6562015-07-08 18:13:11 -0700964 buf := &bytes.Buffer{}
965
Colin Crossd6fd0132023-11-06 13:54:06 -0800966 var moduleInfoJSONs []*ModuleInfoJSON
967
Dan Willemsen97750522016-02-09 17:43:51 -0800968 fmt.Fprintln(buf, "LOCAL_MODULE_MAKEFILE := $(lastword $(MAKEFILE_LIST))")
Dan Willemsen218f6562015-07-08 18:13:11 -0700969
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800970 typeStats := make(map[string]int)
Dan Willemsen218f6562015-07-08 18:13:11 -0700971 for _, mod := range mods {
Colin Crossd6fd0132023-11-06 13:54:06 -0800972 err := translateAndroidMkModule(ctx, buf, &moduleInfoJSONs, mod)
Dan Willemsen218f6562015-07-08 18:13:11 -0700973 if err != nil {
Colin Cross836e3872021-11-09 12:30:59 -0800974 os.Remove(absMkFile)
Dan Willemsen218f6562015-07-08 18:13:11 -0700975 return err
976 }
Dan Willemsen70e17fa2016-07-25 16:00:20 -0700977
Colin Cross2465c3d2018-09-28 10:19:18 -0700978 if amod, ok := mod.(Module); ok && ctx.PrimaryModule(amod) == amod {
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800979 typeStats[ctx.ModuleType(amod)] += 1
Dan Willemsen70e17fa2016-07-25 16:00:20 -0700980 }
981 }
982
983 keys := []string{}
984 fmt.Fprintln(buf, "\nSTATS.SOONG_MODULE_TYPE :=")
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800985 for k := range typeStats {
Dan Willemsen70e17fa2016-07-25 16:00:20 -0700986 keys = append(keys, k)
987 }
988 sort.Strings(keys)
989 for _, mod_type := range keys {
990 fmt.Fprintln(buf, "STATS.SOONG_MODULE_TYPE +=", mod_type)
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800991 fmt.Fprintf(buf, "STATS.SOONG_MODULE_TYPE.%s := %d\n", mod_type, typeStats[mod_type])
Dan Willemsen218f6562015-07-08 18:13:11 -0700992 }
993
Colin Crossd6fd0132023-11-06 13:54:06 -0800994 err := pathtools.WriteFileIfChanged(absMkFile, buf.Bytes(), 0666)
995 if err != nil {
996 return err
997 }
998
999 return writeModuleInfoJSON(ctx, moduleInfoJSONs, moduleInfoJSONPath)
Dan Willemsen218f6562015-07-08 18:13:11 -07001000}
1001
Colin Crossd6fd0132023-11-06 13:54:06 -08001002func writeModuleInfoJSON(ctx SingletonContext, moduleInfoJSONs []*ModuleInfoJSON, moduleInfoJSONPath WritablePath) error {
1003 moduleInfoJSONBuf := &strings.Builder{}
1004 moduleInfoJSONBuf.WriteString("[")
1005 for i, moduleInfoJSON := range moduleInfoJSONs {
1006 if i != 0 {
1007 moduleInfoJSONBuf.WriteString(",\n")
1008 }
1009 moduleInfoJSONBuf.WriteString("{")
1010 moduleInfoJSONBuf.WriteString(strconv.Quote(moduleInfoJSON.core.RegisterName))
1011 moduleInfoJSONBuf.WriteString(":")
1012 err := encodeModuleInfoJSON(moduleInfoJSONBuf, moduleInfoJSON)
1013 moduleInfoJSONBuf.WriteString("}")
1014 if err != nil {
1015 return err
1016 }
1017 }
1018 moduleInfoJSONBuf.WriteString("]")
1019 WriteFileRule(ctx, moduleInfoJSONPath, moduleInfoJSONBuf.String())
1020 return nil
1021}
1022
1023func translateAndroidMkModule(ctx SingletonContext, w io.Writer, moduleInfoJSONs *[]*ModuleInfoJSON, mod blueprint.Module) error {
Colin Cross953d3a22018-09-05 16:23:54 -07001024 defer func() {
1025 if r := recover(); r != nil {
1026 panic(fmt.Errorf("%s in translateAndroidMkModule for module %s variant %s",
1027 r, ctx.ModuleName(mod), ctx.ModuleSubDir(mod)))
1028 }
1029 }()
1030
Bob Badourb4999222021-01-07 03:34:31 +00001031 // Additional cases here require review for correct license propagation to make.
Colin Crossd6fd0132023-11-06 13:54:06 -08001032 var err error
mrziwang18420972024-09-03 15:12:51 -07001033
Yu Liue70976d2024-10-15 20:45:35 +00001034 if info, ok := OtherModuleProvider(ctx, mod, AndroidMkInfoProvider); ok {
1035 err = translateAndroidMkEntriesInfoModule(ctx, w, moduleInfoJSONs, mod, info)
mrziwang18420972024-09-03 15:12:51 -07001036 } else {
1037 switch x := mod.(type) {
1038 case AndroidMkDataProvider:
1039 err = translateAndroidModule(ctx, w, moduleInfoJSONs, mod, x)
mrziwang18420972024-09-03 15:12:51 -07001040 case AndroidMkEntriesProvider:
1041 err = translateAndroidMkEntriesModule(ctx, w, moduleInfoJSONs, mod, x)
1042 default:
1043 // Not exported to make so no make variables to set.
1044 }
Dan Willemsen218f6562015-07-08 18:13:11 -07001045 }
Colin Crossd6fd0132023-11-06 13:54:06 -08001046
1047 if err != nil {
1048 return err
1049 }
1050
1051 return err
Colin Cross2465c3d2018-09-28 10:19:18 -07001052}
1053
Colin Crossaa255532020-07-03 13:18:24 -07001054func (data *AndroidMkData) fillInData(ctx fillInEntriesContext, mod blueprint.Module) {
Jooyung Han12df5fb2019-07-11 16:18:47 +09001055 // Get the preamble content through AndroidMkEntries logic.
Jooyung Han2ed99d02020-06-24 23:26:26 +09001056 data.Entries = AndroidMkEntries{
Jooyung Han12df5fb2019-07-11 16:18:47 +09001057 Class: data.Class,
1058 SubName: data.SubName,
Jooyung Han12df5fb2019-07-11 16:18:47 +09001059 OutputFile: data.OutputFile,
1060 Disabled: data.Disabled,
1061 Include: data.Include,
1062 Required: data.Required,
1063 Host_required: data.Host_required,
1064 Target_required: data.Target_required,
1065 }
Colin Crossaa255532020-07-03 13:18:24 -07001066 data.Entries.fillInEntries(ctx, mod)
Jooyung Han12df5fb2019-07-11 16:18:47 +09001067
1068 // copy entries back to data since it is used in Custom
Jooyung Han2ed99d02020-06-24 23:26:26 +09001069 data.Required = data.Entries.Required
1070 data.Host_required = data.Entries.Host_required
1071 data.Target_required = data.Entries.Target_required
Jooyung Han12df5fb2019-07-11 16:18:47 +09001072}
1073
Jaewoong Jung7ef4a902020-11-16 12:50:29 -08001074// A support func for the deprecated AndroidMkDataProvider interface. Use AndroidMkEntryProvider
1075// instead.
Colin Crossd6fd0132023-11-06 13:54:06 -08001076func translateAndroidModule(ctx SingletonContext, w io.Writer, moduleInfoJSONs *[]*ModuleInfoJSON,
1077 mod blueprint.Module, provider AndroidMkDataProvider) error {
Dan Willemsen218f6562015-07-08 18:13:11 -07001078
Colin Cross635c3b02016-05-18 15:37:25 -07001079 amod := mod.(Module).base()
Cole Fausta963b942024-04-11 17:43:00 -07001080 if shouldSkipAndroidMkProcessing(ctx, amod) {
Jeff Gaston088e29e2017-11-29 16:47:17 -08001081 return nil
1082 }
1083
Colin Cross91825d22017-08-10 16:59:47 -07001084 data := provider.AndroidMk()
Yu Liuddc28332024-08-09 22:48:30 +00001085
Colin Cross53499412017-09-07 13:20:25 -07001086 if data.Include == "" {
1087 data.Include = "$(BUILD_PREBUILT)"
1088 }
1089
Colin Crossaa255532020-07-03 13:18:24 -07001090 data.fillInData(ctx, mod)
LaMont Jonesb5099382024-01-10 23:42:36 +00001091 aconfigUpdateAndroidMkData(ctx, mod.(Module), &data)
Dan Willemsen01a405a2016-06-13 17:19:03 -07001092
Colin Cross0f86d182017-08-10 17:07:28 -07001093 prefix := ""
1094 if amod.ArchSpecific() {
1095 switch amod.Os().Class {
1096 case Host:
Jiyong Park1613e552020-09-14 19:43:17 +09001097 if amod.Target().HostCross {
1098 prefix = "HOST_CROSS_"
1099 } else {
1100 prefix = "HOST_"
1101 }
Colin Cross0f86d182017-08-10 17:07:28 -07001102 case Device:
1103 prefix = "TARGET_"
Colin Crossa2344662016-03-24 13:14:12 -07001104
Dan Willemsen218f6562015-07-08 18:13:11 -07001105 }
1106
Dan Willemsen0ef639b2018-10-10 17:02:29 -07001107 if amod.Arch().ArchType != ctx.Config().Targets[amod.Os()][0].Arch.ArchType {
Colin Cross0f86d182017-08-10 17:07:28 -07001108 prefix = "2ND_" + prefix
1109 }
Dan Willemsen218f6562015-07-08 18:13:11 -07001110 }
1111
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -07001112 name := provider.BaseModuleName()
Colin Cross0f86d182017-08-10 17:07:28 -07001113 blueprintDir := filepath.Dir(ctx.BlueprintFile(mod))
1114
1115 if data.Custom != nil {
Bob Badourb4999222021-01-07 03:34:31 +00001116 // List of module types allowed to use .Custom(...)
1117 // Additions to the list require careful review for proper license handling.
Colin Crossaa255532020-07-03 13:18:24 -07001118 switch reflect.TypeOf(mod).String() { // ctx.ModuleType(mod) doesn't work: aidl_interface creates phony without type
Bob Badourb4999222021-01-07 03:34:31 +00001119 case "*aidl.aidlApi": // writes non-custom before adding .phony
1120 case "*aidl.aidlMapping": // writes non-custom before adding .phony
1121 case "*android.customModule": // appears in tests only
Dan Willemsen9fe14102021-07-13 21:52:04 -07001122 case "*android_sdk.sdkRepoHost": // doesn't go through base_rules
Bob Badourb4999222021-01-07 03:34:31 +00001123 case "*apex.apexBundle": // license properties written
1124 case "*bpf.bpf": // license properties written (both for module and objs)
Neill Kapron41efab72024-07-31 22:17:36 +00001125 case "*libbpf_prog.libbpfProg": // license properties written (both for module and objs)
Bob Badourb4999222021-01-07 03:34:31 +00001126 case "*genrule.Module": // writes non-custom before adding .phony
1127 case "*java.SystemModules": // doesn't go through base_rules
1128 case "*java.systemModulesImport": // doesn't go through base_rules
1129 case "*phony.phony": // license properties written
Nelson Lif3c70682023-12-20 02:37:52 +00001130 case "*phony.PhonyRule": // writes phony deps and acts like `.PHONY`
Bob Badourb4999222021-01-07 03:34:31 +00001131 case "*selinux.selinuxContextsModule": // license properties written
1132 case "*sysprop.syspropLibrary": // license properties written
Bill Yang3b3aac02024-09-05 09:22:09 +00001133 case "*vintf.vintfCompatibilityMatrixRule": // use case like phony
Bob Badourb4999222021-01-07 03:34:31 +00001134 default:
Bob Badour65ee90a2021-09-02 15:33:10 -07001135 if !ctx.Config().IsEnvFalse("ANDROID_REQUIRE_LICENSES") {
Bob Badourb4999222021-01-07 03:34:31 +00001136 return fmt.Errorf("custom make rules not allowed for %q (%q) module %q", ctx.ModuleType(mod), reflect.TypeOf(mod), ctx.ModuleName(mod))
1137 }
1138 }
Colin Cross0f86d182017-08-10 17:07:28 -07001139 data.Custom(w, name, prefix, blueprintDir, data)
1140 } else {
1141 WriteAndroidMkData(w, data)
1142 }
1143
Colin Crossd6fd0132023-11-06 13:54:06 -08001144 if !data.Entries.disabled() {
Yu Liu663e4502024-08-12 18:23:59 +00001145 if moduleInfoJSON, ok := OtherModuleProvider(ctx, mod, ModuleInfoJSONProvider); ok {
Jihoon Kangd4063812025-01-24 00:25:30 +00001146 *moduleInfoJSONs = append(*moduleInfoJSONs, moduleInfoJSON...)
Colin Crossd6fd0132023-11-06 13:54:06 -08001147 }
1148 }
1149
Colin Cross0f86d182017-08-10 17:07:28 -07001150 return nil
1151}
1152
Jaewoong Jung7ef4a902020-11-16 12:50:29 -08001153// A support func for the deprecated AndroidMkDataProvider interface. Use AndroidMkEntryProvider
1154// instead.
Colin Cross0f86d182017-08-10 17:07:28 -07001155func WriteAndroidMkData(w io.Writer, data AndroidMkData) {
Colin Crossd6fd0132023-11-06 13:54:06 -08001156 if data.Entries.disabled() {
Colin Cross0f86d182017-08-10 17:07:28 -07001157 return
1158 }
1159
Jooyung Han2ed99d02020-06-24 23:26:26 +09001160 // write preamble via Entries
1161 data.Entries.footer = bytes.Buffer{}
1162 data.Entries.write(w)
Colin Cross0f86d182017-08-10 17:07:28 -07001163
Colin Crossca860ac2016-01-04 14:34:37 -08001164 for _, extra := range data.Extra {
Colin Cross27a4b052017-08-10 16:32:23 -07001165 extra(w, data.OutputFile.Path())
Dan Willemsen97750522016-02-09 17:43:51 -08001166 }
1167
Colin Cross53499412017-09-07 13:20:25 -07001168 fmt.Fprintln(w, "include "+data.Include)
Dan Willemsen218f6562015-07-08 18:13:11 -07001169}
Sasha Smundakb6d23052019-04-01 18:37:36 -07001170
Colin Crossd6fd0132023-11-06 13:54:06 -08001171func translateAndroidMkEntriesModule(ctx SingletonContext, w io.Writer, moduleInfoJSONs *[]*ModuleInfoJSON,
1172 mod blueprint.Module, provider AndroidMkEntriesProvider) error {
Cole Fausta963b942024-04-11 17:43:00 -07001173 if shouldSkipAndroidMkProcessing(ctx, mod.(Module).base()) {
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -07001174 return nil
Sasha Smundakb6d23052019-04-01 18:37:36 -07001175 }
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -07001176
Colin Crossd6fd0132023-11-06 13:54:06 -08001177 entriesList := provider.AndroidMkEntries()
LaMont Jonesb5099382024-01-10 23:42:36 +00001178 aconfigUpdateAndroidMkEntries(ctx, mod.(Module), &entriesList)
Colin Crossd6fd0132023-11-06 13:54:06 -08001179
Jihoon Kangd4063812025-01-24 00:25:30 +00001180 moduleInfoJSON, providesModuleInfoJSON := OtherModuleProvider(ctx, mod, ModuleInfoJSONProvider)
1181
Bob Badourb4999222021-01-07 03:34:31 +00001182 // Any new or special cases here need review to verify correct propagation of license information.
Colin Crossd6fd0132023-11-06 13:54:06 -08001183 for _, entries := range entriesList {
Colin Crossaa255532020-07-03 13:18:24 -07001184 entries.fillInEntries(ctx, mod)
Jiyong Park0b0e1b92019-12-03 13:24:29 +09001185 entries.write(w)
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -07001186
Jihoon Kangd4063812025-01-24 00:25:30 +00001187 if providesModuleInfoJSON && !entries.disabled() {
1188 // append only the name matching moduleInfoJSON entry
1189 for _, m := range moduleInfoJSON {
1190 if m.RegisterNameOverride == entries.OverrideName && m.SubName == entries.SubName {
1191 *moduleInfoJSONs = append(*moduleInfoJSONs, m)
1192 }
1193 }
Colin Crossd6fd0132023-11-06 13:54:06 -08001194 }
1195 }
1196
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -07001197 return nil
1198}
1199
Cole Fauste8a87832024-09-11 11:35:46 -07001200func ShouldSkipAndroidMkProcessing(ctx ConfigurableEvaluatorContext, module Module) bool {
Cole Fausta963b942024-04-11 17:43:00 -07001201 return shouldSkipAndroidMkProcessing(ctx, module.base())
Chih-Hung Hsieh80783772021-10-11 16:46:56 -07001202}
1203
Cole Fauste8a87832024-09-11 11:35:46 -07001204func shouldSkipAndroidMkProcessing(ctx ConfigurableEvaluatorContext, module *ModuleBase) bool {
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -07001205 if !module.commonProperties.NamespaceExportedToMake {
1206 // TODO(jeffrygaston) do we want to validate that there are no modules being
1207 // exported to Kati that depend on this module?
1208 return true
Sasha Smundakb6d23052019-04-01 18:37:36 -07001209 }
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -07001210
Dan Willemsendef7b5d2021-10-17 00:22:33 -07001211 // On Mac, only expose host darwin modules to Make, as that's all we claim to support.
1212 // In reality, some of them depend on device-built (Java) modules, so we can't disable all
1213 // device modules in Soong, but we can hide them from Make (and thus the build user interface)
1214 if runtime.GOOS == "darwin" && module.Os() != Darwin {
1215 return true
1216 }
1217
Dan Willemsen8528f4e2021-10-19 00:22:06 -07001218 // Only expose the primary Darwin target, as Make does not understand Darwin+Arm64
1219 if module.Os() == Darwin && module.Target().HostCross {
1220 return true
1221 }
1222
Cole Fausta963b942024-04-11 17:43:00 -07001223 return !module.Enabled(ctx) ||
Colin Crossa9c8c9f2020-12-16 10:20:23 -08001224 module.commonProperties.HideFromMake ||
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -07001225 // Make does not understand LinuxBionic
Colin Cross9a027be2022-06-24 18:45:58 -07001226 module.Os() == LinuxBionic ||
1227 // Make does not understand LinuxMusl, except when we are building with USE_HOST_MUSL=true
1228 // and all host binaries are LinuxMusl
1229 (module.Os() == LinuxMusl && module.Target().HostCross)
Sasha Smundakb6d23052019-04-01 18:37:36 -07001230}
Dan Shi31949122020-09-21 12:11:02 -07001231
Jaewoong Jung7ef4a902020-11-16 12:50:29 -08001232// A utility func to format LOCAL_TEST_DATA outputs. See the comments on DataPath to understand how
1233// to use this func.
Colin Cross5c1d5fb2023-11-15 12:39:40 -08001234func androidMkDataPaths(data []DataPath) []string {
Dan Shi31949122020-09-21 12:11:02 -07001235 var testFiles []string
1236 for _, d := range data {
1237 rel := d.SrcPath.Rel()
Colin Cross5c1d5fb2023-11-15 12:39:40 -08001238 if d.WithoutRel {
1239 rel = d.SrcPath.Base()
1240 }
Dan Shi31949122020-09-21 12:11:02 -07001241 path := d.SrcPath.String()
Jaewoong Jung7ef4a902020-11-16 12:50:29 -08001242 // LOCAL_TEST_DATA requires the rel portion of the path to be removed from the path.
Dan Shi31949122020-09-21 12:11:02 -07001243 if !strings.HasSuffix(path, rel) {
1244 panic(fmt.Errorf("path %q does not end with %q", path, rel))
1245 }
1246 path = strings.TrimSuffix(path, rel)
1247 testFileString := path + ":" + rel
1248 if len(d.RelativeInstallPath) > 0 {
1249 testFileString += ":" + d.RelativeInstallPath
1250 }
1251 testFiles = append(testFiles, testFileString)
1252 }
1253 return testFiles
1254}
Sasha Smundakdcb61292022-12-08 10:41:33 -08001255
1256// AndroidMkEmitAssignList emits the line
1257//
1258// VAR := ITEM ...
1259//
1260// Items are the elements to the given set of lists
1261// If all the passed lists are empty, no line will be emitted
1262func AndroidMkEmitAssignList(w io.Writer, varName string, lists ...[]string) {
1263 doPrint := false
1264 for _, l := range lists {
1265 if doPrint = len(l) > 0; doPrint {
1266 break
1267 }
1268 }
1269 if !doPrint {
1270 return
1271 }
1272 fmt.Fprint(w, varName, " :=")
1273 for _, l := range lists {
1274 for _, item := range l {
1275 fmt.Fprint(w, " ", item)
1276 }
1277 }
1278 fmt.Fprintln(w)
1279}
mrziwang18420972024-09-03 15:12:51 -07001280
1281type AndroidMkProviderInfo struct {
1282 PrimaryInfo AndroidMkInfo
1283 ExtraInfo []AndroidMkInfo
1284}
1285
1286type AndroidMkInfo struct {
1287 // Android.mk class string, e.g. EXECUTABLES, JAVA_LIBRARIES, ETC
1288 Class string
1289 // Optional suffix to append to the module name. Useful when a module wants to return multiple
1290 // AndroidMkEntries objects. For example, when a java_library returns an additional entry for
1291 // its hostdex sub-module, this SubName field is set to "-hostdex" so that it can have a
1292 // different name than the parent's.
1293 SubName string
1294 // If set, this value overrides the base module name. SubName is still appended.
1295 OverrideName string
1296 // Dist files to output
1297 DistFiles TaggedDistFiles
1298 // The output file for Kati to process and/or install. If absent, the module is skipped.
1299 OutputFile OptionalPath
1300 // If true, the module is skipped and does not appear on the final Android-<product name>.mk
1301 // file. Useful when a module needs to be skipped conditionally.
1302 Disabled bool
1303 // The postprocessing mk file to include, e.g. $(BUILD_SYSTEM)/soong_cc_rust_prebuilt.mk
1304 // If not set, $(BUILD_SYSTEM)/prebuilt.mk is used.
1305 Include string
1306 // Required modules that need to be built and included in the final build output when building
1307 // this module.
1308 Required []string
1309 // Required host modules that need to be built and included in the final build output when
1310 // building this module.
1311 Host_required []string
1312 // Required device modules that need to be built and included in the final build output when
1313 // building this module.
1314 Target_required []string
1315
1316 HeaderStrings []string
1317 FooterStrings []string
1318
1319 // A map that holds the up-to-date Make variable values. Can be accessed from tests.
1320 EntryMap map[string][]string
1321 // A list of EntryMap keys in insertion order. This serves a few purposes:
1322 // 1. Prevents churns. Golang map doesn't provide consistent iteration order, so without this,
1323 // the outputted Android-*.mk file may change even though there have been no content changes.
1324 // 2. Allows modules to refer to other variables, like LOCAL_BAR_VAR := $(LOCAL_FOO_VAR),
1325 // without worrying about the variables being mixed up in the actual mk file.
1326 // 3. Makes troubleshooting and spotting errors easier.
1327 EntryOrder []string
1328}
1329
Yu Liue70976d2024-10-15 20:45:35 +00001330type AndroidMkProviderInfoProducer interface {
1331 PrepareAndroidMKProviderInfo(config Config) *AndroidMkProviderInfo
1332}
1333
mrziwang18420972024-09-03 15:12:51 -07001334// TODO: rename it to AndroidMkEntriesProvider after AndroidMkEntriesProvider interface is gone.
1335var AndroidMkInfoProvider = blueprint.NewProvider[*AndroidMkProviderInfo]()
1336
1337func translateAndroidMkEntriesInfoModule(ctx SingletonContext, w io.Writer, moduleInfoJSONs *[]*ModuleInfoJSON,
1338 mod blueprint.Module, providerInfo *AndroidMkProviderInfo) error {
1339 if shouldSkipAndroidMkProcessing(ctx, mod.(Module).base()) {
1340 return nil
1341 }
1342
1343 // Deep copy the provider info since we need to modify the info later
1344 info := deepCopyAndroidMkProviderInfo(providerInfo)
1345
1346 aconfigUpdateAndroidMkInfos(ctx, mod.(Module), &info)
1347
1348 // Any new or special cases here need review to verify correct propagation of license information.
1349 info.PrimaryInfo.fillInEntries(ctx, mod)
1350 info.PrimaryInfo.write(w)
1351 if len(info.ExtraInfo) > 0 {
1352 for _, ei := range info.ExtraInfo {
1353 ei.fillInEntries(ctx, mod)
1354 ei.write(w)
1355 }
1356 }
1357
1358 if !info.PrimaryInfo.disabled() {
1359 if moduleInfoJSON, ok := OtherModuleProvider(ctx, mod, ModuleInfoJSONProvider); ok {
Jihoon Kangd4063812025-01-24 00:25:30 +00001360 *moduleInfoJSONs = append(*moduleInfoJSONs, moduleInfoJSON...)
mrziwang18420972024-09-03 15:12:51 -07001361 }
1362 }
1363
1364 return nil
1365}
1366
1367// Utility funcs to manipulate Android.mk variable entries.
1368
1369// SetString sets a Make variable with the given name to the given value.
1370func (a *AndroidMkInfo) SetString(name, value string) {
1371 if _, ok := a.EntryMap[name]; !ok {
1372 a.EntryOrder = append(a.EntryOrder, name)
1373 }
1374 a.EntryMap[name] = []string{value}
1375}
1376
1377// SetPath sets a Make variable with the given name to the given path string.
1378func (a *AndroidMkInfo) SetPath(name string, path Path) {
1379 if _, ok := a.EntryMap[name]; !ok {
1380 a.EntryOrder = append(a.EntryOrder, name)
1381 }
1382 a.EntryMap[name] = []string{path.String()}
1383}
1384
1385// SetOptionalPath sets a Make variable with the given name to the given path string if it is valid.
1386// It is a no-op if the given path is invalid.
1387func (a *AndroidMkInfo) SetOptionalPath(name string, path OptionalPath) {
1388 if path.Valid() {
1389 a.SetPath(name, path.Path())
1390 }
1391}
1392
1393// AddPath appends the given path string to a Make variable with the given name.
1394func (a *AndroidMkInfo) AddPath(name string, path Path) {
1395 if _, ok := a.EntryMap[name]; !ok {
1396 a.EntryOrder = append(a.EntryOrder, name)
1397 }
1398 a.EntryMap[name] = append(a.EntryMap[name], path.String())
1399}
1400
1401// AddOptionalPath appends the given path string to a Make variable with the given name if it is
1402// valid. It is a no-op if the given path is invalid.
1403func (a *AndroidMkInfo) AddOptionalPath(name string, path OptionalPath) {
1404 if path.Valid() {
1405 a.AddPath(name, path.Path())
1406 }
1407}
1408
1409// SetPaths sets a Make variable with the given name to a slice of the given path strings.
1410func (a *AndroidMkInfo) SetPaths(name string, paths Paths) {
1411 if _, ok := a.EntryMap[name]; !ok {
1412 a.EntryOrder = append(a.EntryOrder, name)
1413 }
1414 a.EntryMap[name] = paths.Strings()
1415}
1416
1417// SetOptionalPaths sets a Make variable with the given name to a slice of the given path strings
1418// only if there are a non-zero amount of paths.
1419func (a *AndroidMkInfo) SetOptionalPaths(name string, paths Paths) {
1420 if len(paths) > 0 {
1421 a.SetPaths(name, paths)
1422 }
1423}
1424
1425// AddPaths appends the given path strings to a Make variable with the given name.
1426func (a *AndroidMkInfo) AddPaths(name string, paths Paths) {
1427 if _, ok := a.EntryMap[name]; !ok {
1428 a.EntryOrder = append(a.EntryOrder, name)
1429 }
1430 a.EntryMap[name] = append(a.EntryMap[name], paths.Strings()...)
1431}
1432
1433// SetBoolIfTrue sets a Make variable with the given name to true if the given flag is true.
1434// It is a no-op if the given flag is false.
1435func (a *AndroidMkInfo) SetBoolIfTrue(name string, flag bool) {
1436 if flag {
1437 if _, ok := a.EntryMap[name]; !ok {
1438 a.EntryOrder = append(a.EntryOrder, name)
1439 }
1440 a.EntryMap[name] = []string{"true"}
1441 }
1442}
1443
1444// SetBool sets a Make variable with the given name to if the given bool flag value.
1445func (a *AndroidMkInfo) SetBool(name string, flag bool) {
1446 if _, ok := a.EntryMap[name]; !ok {
1447 a.EntryOrder = append(a.EntryOrder, name)
1448 }
1449 if flag {
1450 a.EntryMap[name] = []string{"true"}
1451 } else {
1452 a.EntryMap[name] = []string{"false"}
1453 }
1454}
1455
1456// AddStrings appends the given strings to a Make variable with the given name.
1457func (a *AndroidMkInfo) AddStrings(name string, value ...string) {
1458 if len(value) == 0 {
1459 return
1460 }
1461 if _, ok := a.EntryMap[name]; !ok {
1462 a.EntryOrder = append(a.EntryOrder, name)
1463 }
1464 a.EntryMap[name] = append(a.EntryMap[name], value...)
1465}
1466
1467// AddCompatibilityTestSuites adds the supplied test suites to the EntryMap, with special handling
1468// for partial MTS and MCTS test suites.
1469func (a *AndroidMkInfo) AddCompatibilityTestSuites(suites ...string) {
1470 // M(C)TS supports a full test suite and partial per-module MTS test suites, with naming mts-${MODULE}.
1471 // To reduce repetition, if we find a partial M(C)TS test suite without an full M(C)TS test suite,
1472 // we add the full test suite to our list.
1473 if PrefixInList(suites, "mts-") && !InList("mts", suites) {
1474 suites = append(suites, "mts")
1475 }
1476 if PrefixInList(suites, "mcts-") && !InList("mcts", suites) {
1477 suites = append(suites, "mcts")
1478 }
1479 a.AddStrings("LOCAL_COMPATIBILITY_SUITE", suites...)
1480}
1481
1482func (a *AndroidMkInfo) fillInEntries(ctx fillInEntriesContext, mod blueprint.Module) {
1483 helperInfo := AndroidMkInfo{
1484 EntryMap: make(map[string][]string),
1485 }
1486
1487 amod := mod.(Module)
1488 base := amod.base()
1489 name := base.BaseModuleName()
1490 if a.OverrideName != "" {
1491 name = a.OverrideName
1492 }
1493
1494 if a.Include == "" {
1495 a.Include = "$(BUILD_PREBUILT)"
1496 }
1497 a.Required = append(a.Required, amod.RequiredModuleNames(ctx)...)
1498 a.Required = append(a.Required, amod.VintfFragmentModuleNames(ctx)...)
1499 a.Host_required = append(a.Host_required, amod.HostRequiredModuleNames()...)
1500 a.Target_required = append(a.Target_required, amod.TargetRequiredModuleNames()...)
1501
1502 for _, distString := range a.GetDistForGoals(ctx, mod) {
1503 a.HeaderStrings = append(a.HeaderStrings, distString)
1504 }
1505
Yu Liue70976d2024-10-15 20:45:35 +00001506 a.HeaderStrings = append(a.HeaderStrings, fmt.Sprintf("\ninclude $(CLEAR_VARS) # type: %s, name: %s, variant: %s", ctx.ModuleType(mod), base.BaseModuleName(), ctx.ModuleSubDir(mod)))
mrziwang18420972024-09-03 15:12:51 -07001507
1508 // Collect make variable assignment entries.
1509 helperInfo.SetString("LOCAL_PATH", ctx.ModuleDir(mod))
1510 helperInfo.SetString("LOCAL_MODULE", name+a.SubName)
1511 helperInfo.SetString("LOCAL_MODULE_CLASS", a.Class)
1512 helperInfo.SetString("LOCAL_PREBUILT_MODULE_FILE", a.OutputFile.String())
1513 helperInfo.AddStrings("LOCAL_REQUIRED_MODULES", a.Required...)
1514 helperInfo.AddStrings("LOCAL_HOST_REQUIRED_MODULES", a.Host_required...)
1515 helperInfo.AddStrings("LOCAL_TARGET_REQUIRED_MODULES", a.Target_required...)
1516 helperInfo.AddStrings("LOCAL_SOONG_MODULE_TYPE", ctx.ModuleType(amod))
1517
1518 // If the install rule was generated by Soong tell Make about it.
1519 info := OtherModuleProviderOrDefault(ctx, mod, InstallFilesProvider)
1520 if len(info.KatiInstalls) > 0 {
1521 // Assume the primary install file is last since it probably needs to depend on any other
1522 // installed files. If that is not the case we can add a method to specify the primary
1523 // installed file.
1524 helperInfo.SetPath("LOCAL_SOONG_INSTALLED_MODULE", info.KatiInstalls[len(info.KatiInstalls)-1].to)
1525 helperInfo.SetString("LOCAL_SOONG_INSTALL_PAIRS", info.KatiInstalls.BuiltInstalled())
1526 helperInfo.SetPaths("LOCAL_SOONG_INSTALL_SYMLINKS", info.KatiSymlinks.InstallPaths().Paths())
1527 } else {
1528 // Soong may not have generated the install rule also when `no_full_install: true`.
1529 // Mark this module as uninstallable in order to prevent Make from creating an
1530 // install rule there.
1531 helperInfo.SetBoolIfTrue("LOCAL_UNINSTALLABLE_MODULE", proptools.Bool(base.commonProperties.No_full_install))
1532 }
1533
Yu Liue70976d2024-10-15 20:45:35 +00001534 if info.UncheckedModule {
1535 helperInfo.SetBool("LOCAL_DONT_CHECK_MODULE", true)
1536 } else if info.CheckbuildTarget != nil {
1537 helperInfo.SetPath("LOCAL_CHECKED_MODULE", info.CheckbuildTarget)
1538 } else {
1539 helperInfo.SetOptionalPath("LOCAL_CHECKED_MODULE", a.OutputFile)
1540 }
1541
mrziwang18420972024-09-03 15:12:51 -07001542 if len(info.TestData) > 0 {
1543 helperInfo.AddStrings("LOCAL_TEST_DATA", androidMkDataPaths(info.TestData)...)
1544 }
1545
1546 if am, ok := mod.(ApexModule); ok {
1547 helperInfo.SetBoolIfTrue("LOCAL_NOT_AVAILABLE_FOR_PLATFORM", am.NotAvailableForPlatform())
1548 }
1549
1550 archStr := base.Arch().ArchType.String()
1551 host := false
1552 switch base.Os().Class {
1553 case Host:
1554 if base.Target().HostCross {
1555 // Make cannot identify LOCAL_MODULE_HOST_CROSS_ARCH:= common.
1556 if base.Arch().ArchType != Common {
1557 helperInfo.SetString("LOCAL_MODULE_HOST_CROSS_ARCH", archStr)
1558 }
1559 } else {
1560 // Make cannot identify LOCAL_MODULE_HOST_ARCH:= common.
1561 if base.Arch().ArchType != Common {
1562 helperInfo.SetString("LOCAL_MODULE_HOST_ARCH", archStr)
1563 }
1564 }
1565 host = true
1566 case Device:
1567 // Make cannot identify LOCAL_MODULE_TARGET_ARCH:= common.
1568 if base.Arch().ArchType != Common {
1569 if base.Target().NativeBridge {
1570 hostArchStr := base.Target().NativeBridgeHostArchName
1571 if hostArchStr != "" {
1572 helperInfo.SetString("LOCAL_MODULE_TARGET_ARCH", hostArchStr)
1573 }
1574 } else {
1575 helperInfo.SetString("LOCAL_MODULE_TARGET_ARCH", archStr)
1576 }
1577 }
1578
1579 if !base.InVendorRamdisk() {
1580 helperInfo.AddPaths("LOCAL_FULL_INIT_RC", info.InitRcPaths)
1581 }
1582 if len(info.VintfFragmentsPaths) > 0 {
1583 helperInfo.AddPaths("LOCAL_FULL_VINTF_FRAGMENTS", info.VintfFragmentsPaths)
1584 }
1585 helperInfo.SetBoolIfTrue("LOCAL_PROPRIETARY_MODULE", Bool(base.commonProperties.Proprietary))
1586 if Bool(base.commonProperties.Vendor) || Bool(base.commonProperties.Soc_specific) {
1587 helperInfo.SetString("LOCAL_VENDOR_MODULE", "true")
1588 }
1589 helperInfo.SetBoolIfTrue("LOCAL_ODM_MODULE", Bool(base.commonProperties.Device_specific))
1590 helperInfo.SetBoolIfTrue("LOCAL_PRODUCT_MODULE", Bool(base.commonProperties.Product_specific))
1591 helperInfo.SetBoolIfTrue("LOCAL_SYSTEM_EXT_MODULE", Bool(base.commonProperties.System_ext_specific))
1592 if base.commonProperties.Owner != nil {
1593 helperInfo.SetString("LOCAL_MODULE_OWNER", *base.commonProperties.Owner)
1594 }
1595 }
1596
1597 if host {
1598 makeOs := base.Os().String()
1599 if base.Os() == Linux || base.Os() == LinuxBionic || base.Os() == LinuxMusl {
1600 makeOs = "linux"
1601 }
1602 helperInfo.SetString("LOCAL_MODULE_HOST_OS", makeOs)
1603 helperInfo.SetString("LOCAL_IS_HOST_MODULE", "true")
1604 }
1605
mrziwang18420972024-09-03 15:12:51 -07001606 if licenseMetadata, ok := OtherModuleProvider(ctx, mod, LicenseMetadataProvider); ok {
1607 helperInfo.SetPath("LOCAL_SOONG_LICENSE_METADATA", licenseMetadata.LicenseMetadataPath)
1608 }
1609
1610 if _, ok := OtherModuleProvider(ctx, mod, ModuleInfoJSONProvider); ok {
1611 helperInfo.SetBool("LOCAL_SOONG_MODULE_INFO_JSON", true)
1612 }
1613
1614 a.mergeEntries(&helperInfo)
1615
1616 // Write to footer.
1617 a.FooterStrings = append([]string{"include " + a.Include}, a.FooterStrings...)
1618}
1619
1620// This method merges the entries to helperInfo, then replaces a's EntryMap and
1621// EntryOrder with helperInfo's
1622func (a *AndroidMkInfo) mergeEntries(helperInfo *AndroidMkInfo) {
1623 for _, extraEntry := range a.EntryOrder {
1624 if v, ok := helperInfo.EntryMap[extraEntry]; ok {
1625 v = append(v, a.EntryMap[extraEntry]...)
1626 } else {
1627 helperInfo.EntryMap[extraEntry] = a.EntryMap[extraEntry]
1628 helperInfo.EntryOrder = append(helperInfo.EntryOrder, extraEntry)
1629 }
1630 }
1631 a.EntryOrder = helperInfo.EntryOrder
1632 a.EntryMap = helperInfo.EntryMap
1633}
1634
1635func (a *AndroidMkInfo) disabled() bool {
1636 return a.Disabled || !a.OutputFile.Valid()
1637}
1638
1639// write flushes the AndroidMkEntries's in-struct data populated by AndroidMkEntries into the
1640// given Writer object.
1641func (a *AndroidMkInfo) write(w io.Writer) {
1642 if a.disabled() {
1643 return
1644 }
1645
Yu Liue70976d2024-10-15 20:45:35 +00001646 combinedHeaderString := strings.Join(a.HeaderStrings, "\n") + "\n"
1647 combinedFooterString := strings.Join(a.FooterStrings, "\n") + "\n"
mrziwang18420972024-09-03 15:12:51 -07001648 w.Write([]byte(combinedHeaderString))
1649 for _, name := range a.EntryOrder {
1650 AndroidMkEmitAssignList(w, name, a.EntryMap[name])
1651 }
1652 w.Write([]byte(combinedFooterString))
1653}
1654
1655// Compute the list of Make strings to declare phony goals and dist-for-goals
1656// calls from the module's dist and dists properties.
1657func (a *AndroidMkInfo) GetDistForGoals(ctx fillInEntriesContext, mod blueprint.Module) []string {
1658 distContributions := a.getDistContributions(ctx, mod)
1659 if distContributions == nil {
1660 return nil
1661 }
1662
1663 return generateDistContributionsForMake(distContributions)
1664}
1665
1666// Compute the contributions that the module makes to the dist.
1667func (a *AndroidMkInfo) getDistContributions(ctx fillInEntriesContext, mod blueprint.Module) *distContributions {
1668 amod := mod.(Module).base()
1669 name := amod.BaseModuleName()
1670
1671 // Collate the set of associated tag/paths available for copying to the dist.
1672 // Start with an empty (nil) set.
1673 var availableTaggedDists TaggedDistFiles
1674
1675 // Then merge in any that are provided explicitly by the module.
1676 if a.DistFiles != nil {
1677 // Merge the DistFiles into the set.
1678 availableTaggedDists = availableTaggedDists.merge(a.DistFiles)
1679 }
1680
1681 // If no paths have been provided for the DefaultDistTag and the output file is
1682 // valid then add that as the default dist path.
1683 if _, ok := availableTaggedDists[DefaultDistTag]; !ok && a.OutputFile.Valid() {
1684 availableTaggedDists = availableTaggedDists.addPathsForTag(DefaultDistTag, a.OutputFile.Path())
1685 }
1686
1687 info := OtherModuleProviderOrDefault(ctx, mod, InstallFilesProvider)
1688 // If the distFiles created by GenerateTaggedDistFiles contains paths for the
1689 // DefaultDistTag then that takes priority so delete any existing paths.
1690 if _, ok := info.DistFiles[DefaultDistTag]; ok {
1691 delete(availableTaggedDists, DefaultDistTag)
1692 }
1693
1694 // Finally, merge the distFiles created by GenerateTaggedDistFiles.
1695 availableTaggedDists = availableTaggedDists.merge(info.DistFiles)
1696
1697 if len(availableTaggedDists) == 0 {
1698 // Nothing dist-able for this module.
1699 return nil
1700 }
1701
1702 // Collate the contributions this module makes to the dist.
1703 distContributions := &distContributions{}
1704
1705 if !exemptFromRequiredApplicableLicensesProperty(mod.(Module)) {
1706 distContributions.licenseMetadataFile = info.LicenseMetadataFile
1707 }
1708
1709 // Iterate over this module's dist structs, merged from the dist and dists properties.
1710 for _, dist := range amod.Dists() {
1711 // Get the list of goals this dist should be enabled for. e.g. sdk, droidcore
1712 goals := strings.Join(dist.Targets, " ")
1713
1714 // Get the tag representing the output files to be dist'd. e.g. ".jar", ".proguard_map"
1715 var tag string
1716 if dist.Tag == nil {
1717 // If the dist struct does not specify a tag, use the default output files tag.
1718 tag = DefaultDistTag
1719 } else {
1720 tag = *dist.Tag
1721 }
1722
1723 // Get the paths of the output files to be dist'd, represented by the tag.
1724 // Can be an empty list.
1725 tagPaths := availableTaggedDists[tag]
1726 if len(tagPaths) == 0 {
1727 // Nothing to dist for this tag, continue to the next dist.
1728 continue
1729 }
1730
1731 if len(tagPaths) > 1 && (dist.Dest != nil || dist.Suffix != nil) {
1732 errorMessage := "%s: Cannot apply dest/suffix for more than one dist " +
1733 "file for %q goals tag %q in module %s. The list of dist files, " +
1734 "which should have a single element, is:\n%s"
1735 panic(fmt.Errorf(errorMessage, mod, goals, tag, name, tagPaths))
1736 }
1737
1738 copiesForGoals := distContributions.getCopiesForGoals(goals)
1739
1740 // Iterate over each path adding a copy instruction to copiesForGoals
1741 for _, path := range tagPaths {
1742 // It's possible that the Path is nil from errant modules. Be defensive here.
1743 if path == nil {
1744 tagName := "default" // for error message readability
1745 if dist.Tag != nil {
1746 tagName = *dist.Tag
1747 }
1748 panic(fmt.Errorf("Dist file should not be nil for the %s tag in %s", tagName, name))
1749 }
1750
1751 dest := filepath.Base(path.String())
1752
1753 if dist.Dest != nil {
1754 var err error
1755 if dest, err = validateSafePath(*dist.Dest); err != nil {
1756 // This was checked in ModuleBase.GenerateBuildActions
1757 panic(err)
1758 }
1759 }
1760
1761 ext := filepath.Ext(dest)
1762 suffix := ""
1763 if dist.Suffix != nil {
1764 suffix = *dist.Suffix
1765 }
1766
1767 productString := ""
1768 if dist.Append_artifact_with_product != nil && *dist.Append_artifact_with_product {
1769 productString = fmt.Sprintf("_%s", ctx.Config().DeviceProduct())
1770 }
1771
1772 if suffix != "" || productString != "" {
1773 dest = strings.TrimSuffix(dest, ext) + suffix + productString + ext
1774 }
1775
1776 if dist.Dir != nil {
1777 var err error
1778 if dest, err = validateSafePath(*dist.Dir, dest); err != nil {
1779 // This was checked in ModuleBase.GenerateBuildActions
1780 panic(err)
1781 }
1782 }
1783
1784 copiesForGoals.addCopyInstruction(path, dest)
1785 }
1786 }
1787
1788 return distContributions
1789}
1790
1791func deepCopyAndroidMkProviderInfo(providerInfo *AndroidMkProviderInfo) AndroidMkProviderInfo {
1792 info := AndroidMkProviderInfo{
1793 PrimaryInfo: deepCopyAndroidMkInfo(&providerInfo.PrimaryInfo),
1794 }
1795 if len(providerInfo.ExtraInfo) > 0 {
1796 for _, i := range providerInfo.ExtraInfo {
1797 info.ExtraInfo = append(info.ExtraInfo, deepCopyAndroidMkInfo(&i))
1798 }
1799 }
1800 return info
1801}
1802
1803func deepCopyAndroidMkInfo(mkinfo *AndroidMkInfo) AndroidMkInfo {
1804 info := AndroidMkInfo{
1805 Class: mkinfo.Class,
1806 SubName: mkinfo.SubName,
1807 OverrideName: mkinfo.OverrideName,
1808 // There is no modification on DistFiles or OutputFile, so no need to
1809 // make their deep copy.
1810 DistFiles: mkinfo.DistFiles,
1811 OutputFile: mkinfo.OutputFile,
1812 Disabled: mkinfo.Disabled,
1813 Include: mkinfo.Include,
1814 Required: deepCopyStringSlice(mkinfo.Required),
1815 Host_required: deepCopyStringSlice(mkinfo.Host_required),
1816 Target_required: deepCopyStringSlice(mkinfo.Target_required),
1817 HeaderStrings: deepCopyStringSlice(mkinfo.HeaderStrings),
1818 FooterStrings: deepCopyStringSlice(mkinfo.FooterStrings),
1819 EntryOrder: deepCopyStringSlice(mkinfo.EntryOrder),
1820 }
1821 info.EntryMap = make(map[string][]string)
1822 for k, v := range mkinfo.EntryMap {
1823 info.EntryMap[k] = deepCopyStringSlice(v)
1824 }
1825
1826 return info
1827}
1828
1829func deepCopyStringSlice(original []string) []string {
1830 result := make([]string, len(original))
1831 copy(result, original)
1832 return result
1833}