blob: 6f094e557991d4c0c649469afac1ead333aee559 [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
Jingwen Chen40fd90a2020-06-15 05:24:19 +000067 DistFiles TaggedDistFiles
Sasha Smundakb6d23052019-04-01 18:37:36 -070068 OutputFile OptionalPath
69 Disabled bool
70 Include string
71 Required []string
72 Host_required []string
73 Target_required []string
Dan Willemsen218f6562015-07-08 18:13:11 -070074
Colin Cross0f86d182017-08-10 17:07:28 -070075 Custom func(w io.Writer, name, prefix, moduleDir string, data AndroidMkData)
Dan Willemsen218f6562015-07-08 18:13:11 -070076
Colin Cross27a4b052017-08-10 16:32:23 -070077 Extra []AndroidMkExtraFunc
Colin Cross0f86d182017-08-10 17:07:28 -070078
Jooyung Han2ed99d02020-06-24 23:26:26 +090079 Entries AndroidMkEntries
Dan Willemsen218f6562015-07-08 18:13:11 -070080}
81
Colin Cross27a4b052017-08-10 16:32:23 -070082type AndroidMkExtraFunc func(w io.Writer, outputFile Path)
83
Jaewoong Jung7ef4a902020-11-16 12:50:29 -080084// Interface for modules to declare their Android.mk outputs. Note that every module needs to
85// implement this in order to be included in the final Android-<product_name>.mk output, even if
86// they only need to output the common set of entries without any customizations.
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -070087type AndroidMkEntriesProvider interface {
Jaewoong Jung7ef4a902020-11-16 12:50:29 -080088 // Returns AndroidMkEntries objects that contain all basic info plus extra customization data
89 // if needed. This is the core func to implement.
90 // Note that one can return multiple objects. For example, java_library may return an additional
91 // AndroidMkEntries object for its hostdex sub-module.
Jiyong Park0b0e1b92019-12-03 13:24:29 +090092 AndroidMkEntries() []AndroidMkEntries
Jaewoong Jung7ef4a902020-11-16 12:50:29 -080093 // Modules don't need to implement this as it's already implemented by ModuleBase.
94 // AndroidMkEntries uses BaseModuleName() instead of ModuleName() because certain modules
95 // e.g. Prebuilts, override the Name() func and return modified names.
96 // If a different name is preferred, use SubName or OverrideName in AndroidMkEntries.
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -070097 BaseModuleName() string
98}
99
Jaewoong Jung7ef4a902020-11-16 12:50:29 -0800100// The core data struct that modules use to provide their Android.mk data.
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700101type AndroidMkEntries struct {
Jaewoong Jung7ef4a902020-11-16 12:50:29 -0800102 // Android.mk class string, e.g EXECUTABLES, JAVA_LIBRARIES, ETC
103 Class string
104 // Optional suffix to append to the module name. Useful when a module wants to return multiple
105 // AndroidMkEntries objects. For example, when a java_library returns an additional entry for
106 // its hostdex sub-module, this SubName field is set to "-hostdex" so that it can have a
107 // different name than the parent's.
108 SubName string
109 // If set, this value overrides the base module name. SubName is still appended.
110 OverrideName string
111 // Dist files to output
112 DistFiles TaggedDistFiles
113 // The output file for Kati to process and/or install. If absent, the module is skipped.
114 OutputFile OptionalPath
115 // If true, the module is skipped and does not appear on the final Android-<product name>.mk
116 // file. Useful when a module needs to be skipped conditionally.
117 Disabled bool
Ivan Lozanod06cc742021-11-12 13:27:58 -0500118 // The postprocessing mk file to include, e.g. $(BUILD_SYSTEM)/soong_cc_rust_prebuilt.mk
Jaewoong Jung7ef4a902020-11-16 12:50:29 -0800119 // If not set, $(BUILD_SYSTEM)/prebuilt.mk is used.
120 Include string
121 // Required modules that need to be built and included in the final build output when building
122 // this module.
123 Required []string
124 // Required host modules that need to be built and included in the final build output when
125 // building this module.
126 Host_required []string
127 // Required device modules that need to be built and included in the final build output when
128 // building this module.
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700129 Target_required []string
130
131 header bytes.Buffer
132 footer bytes.Buffer
133
Jaewoong Jung7ef4a902020-11-16 12:50:29 -0800134 // Funcs to append additional Android.mk entries or modify the common ones. Multiple funcs are
135 // accepted so that common logic can be factored out as a shared func.
Jaewoong Junge0dc8df2019-08-27 17:33:16 -0700136 ExtraEntries []AndroidMkExtraEntriesFunc
Jaewoong Jung7ef4a902020-11-16 12:50:29 -0800137 // Funcs to add extra lines to the module's Android.mk output. Unlike AndroidMkExtraEntriesFunc,
138 // which simply sets Make variable values, this can be used for anything since it can write any
139 // Make statements directly to the final Android-*.mk file.
140 // Primarily used to call macros or declare/update Make targets.
Jaewoong Jungb0c127c2019-08-29 14:56:03 -0700141 ExtraFooters []AndroidMkExtraFootersFunc
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700142
Jaewoong Jung7ef4a902020-11-16 12:50:29 -0800143 // A map that holds the up-to-date Make variable values. Can be accessed from tests.
144 EntryMap map[string][]string
145 // A list of EntryMap keys in insertion order. This serves a few purposes:
146 // 1. Prevents churns. Golang map doesn't provide consistent iteration order, so without this,
147 // the outputted Android-*.mk file may change even though there have been no content changes.
148 // 2. Allows modules to refer to other variables, like LOCAL_BAR_VAR := $(LOCAL_FOO_VAR),
149 // without worrying about the variables being mixed up in the actual mk file.
150 // 3. Makes troubleshooting and spotting errors easier.
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700151 entryOrder []string
Trevor Radcliffe90727f42022-03-21 19:34:02 +0000152
153 // Provides data typically stored by Context objects that are commonly needed by
154 //AndroidMkEntries objects.
155 entryContext AndroidMkEntriesContext
156}
157
158type AndroidMkEntriesContext interface {
Yu Liuec810542024-08-26 18:09:15 +0000159 OtherModuleProviderContext
Trevor Radcliffe90727f42022-03-21 19:34:02 +0000160 Config() Config
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700161}
162
Colin Crossaa255532020-07-03 13:18:24 -0700163type AndroidMkExtraEntriesContext interface {
Colin Cross3c0a83d2023-12-12 14:13:26 -0800164 Provider(provider blueprint.AnyProviderKey) (any, bool)
Colin Crossaa255532020-07-03 13:18:24 -0700165}
166
167type androidMkExtraEntriesContext struct {
168 ctx fillInEntriesContext
169 mod blueprint.Module
170}
171
Colin Cross3c0a83d2023-12-12 14:13:26 -0800172func (a *androidMkExtraEntriesContext) Provider(provider blueprint.AnyProviderKey) (any, bool) {
Yu Liu663e4502024-08-12 18:23:59 +0000173 return a.ctx.otherModuleProvider(a.mod, provider)
Colin Crossaa255532020-07-03 13:18:24 -0700174}
175
176type AndroidMkExtraEntriesFunc func(ctx AndroidMkExtraEntriesContext, entries *AndroidMkEntries)
Jaewoong Jung02b11a62020-12-07 10:23:54 -0800177type AndroidMkExtraFootersFunc func(w io.Writer, name, prefix, moduleDir string)
Jaewoong Junge0dc8df2019-08-27 17:33:16 -0700178
Jaewoong Jung7ef4a902020-11-16 12:50:29 -0800179// Utility funcs to manipulate Android.mk variable entries.
180
181// SetString sets a Make variable with the given name to the given value.
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700182func (a *AndroidMkEntries) SetString(name, value string) {
183 if _, ok := a.EntryMap[name]; !ok {
184 a.entryOrder = append(a.entryOrder, name)
185 }
186 a.EntryMap[name] = []string{value}
187}
188
Jaewoong Jung7ef4a902020-11-16 12:50:29 -0800189// SetPath sets a Make variable with the given name to the given path string.
Jaewoong Jung9a1e8bd2019-09-04 20:17:54 -0700190func (a *AndroidMkEntries) SetPath(name string, path Path) {
191 if _, ok := a.EntryMap[name]; !ok {
192 a.entryOrder = append(a.entryOrder, name)
193 }
194 a.EntryMap[name] = []string{path.String()}
195}
196
Jaewoong Jung7ef4a902020-11-16 12:50:29 -0800197// SetOptionalPath sets a Make variable with the given name to the given path string if it is valid.
198// It is a no-op if the given path is invalid.
Colin Crossc0efd1d2020-07-03 11:56:24 -0700199func (a *AndroidMkEntries) SetOptionalPath(name string, path OptionalPath) {
200 if path.Valid() {
201 a.SetPath(name, path.Path())
202 }
203}
204
Jaewoong Jung7ef4a902020-11-16 12:50:29 -0800205// AddPath appends the given path string to a Make variable with the given name.
Colin Crossc0efd1d2020-07-03 11:56:24 -0700206func (a *AndroidMkEntries) AddPath(name string, path Path) {
207 if _, ok := a.EntryMap[name]; !ok {
208 a.entryOrder = append(a.entryOrder, name)
209 }
210 a.EntryMap[name] = append(a.EntryMap[name], path.String())
211}
212
Jaewoong Jung7ef4a902020-11-16 12:50:29 -0800213// AddOptionalPath appends the given path string to a Make variable with the given name if it is
214// valid. It is a no-op if the given path is invalid.
Colin Crossc0efd1d2020-07-03 11:56:24 -0700215func (a *AndroidMkEntries) AddOptionalPath(name string, path OptionalPath) {
216 if path.Valid() {
217 a.AddPath(name, path.Path())
218 }
219}
220
Jaewoong Jung7ef4a902020-11-16 12:50:29 -0800221// SetPaths sets a Make variable with the given name to a slice of the given path strings.
Colin Cross08dca382020-07-21 20:31:17 -0700222func (a *AndroidMkEntries) SetPaths(name string, paths Paths) {
223 if _, ok := a.EntryMap[name]; !ok {
224 a.entryOrder = append(a.entryOrder, name)
225 }
226 a.EntryMap[name] = paths.Strings()
227}
228
Jaewoong Jung7ef4a902020-11-16 12:50:29 -0800229// SetOptionalPaths sets a Make variable with the given name to a slice of the given path strings
230// only if there are a non-zero amount of paths.
Colin Cross08dca382020-07-21 20:31:17 -0700231func (a *AndroidMkEntries) SetOptionalPaths(name string, paths Paths) {
232 if len(paths) > 0 {
233 a.SetPaths(name, paths)
234 }
235}
236
Jaewoong Jung7ef4a902020-11-16 12:50:29 -0800237// AddPaths appends the given path strings to a Make variable with the given name.
Colin Cross08dca382020-07-21 20:31:17 -0700238func (a *AndroidMkEntries) AddPaths(name string, paths Paths) {
239 if _, ok := a.EntryMap[name]; !ok {
240 a.entryOrder = append(a.entryOrder, name)
241 }
242 a.EntryMap[name] = append(a.EntryMap[name], paths.Strings()...)
243}
244
Jaewoong Jung7ef4a902020-11-16 12:50:29 -0800245// SetBoolIfTrue sets a Make variable with the given name to true if the given flag is true.
246// It is a no-op if the given flag is false.
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700247func (a *AndroidMkEntries) SetBoolIfTrue(name string, flag bool) {
248 if flag {
249 if _, ok := a.EntryMap[name]; !ok {
250 a.entryOrder = append(a.entryOrder, name)
251 }
252 a.EntryMap[name] = []string{"true"}
253 }
254}
255
Jaewoong Jung7ef4a902020-11-16 12:50:29 -0800256// SetBool sets a Make variable with the given name to if the given bool flag value.
Jaewoong Jung9a1e8bd2019-09-04 20:17:54 -0700257func (a *AndroidMkEntries) SetBool(name string, flag bool) {
258 if _, ok := a.EntryMap[name]; !ok {
259 a.entryOrder = append(a.entryOrder, name)
260 }
261 if flag {
262 a.EntryMap[name] = []string{"true"}
263 } else {
264 a.EntryMap[name] = []string{"false"}
265 }
266}
267
Jaewoong Jung7ef4a902020-11-16 12:50:29 -0800268// AddStrings appends the given strings to a Make variable with the given name.
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700269func (a *AndroidMkEntries) AddStrings(name string, value ...string) {
270 if len(value) == 0 {
271 return
272 }
273 if _, ok := a.EntryMap[name]; !ok {
274 a.entryOrder = append(a.entryOrder, name)
275 }
276 a.EntryMap[name] = append(a.EntryMap[name], value...)
277}
278
Liz Kammer57f5b332020-11-24 12:42:58 -0800279// AddCompatibilityTestSuites adds the supplied test suites to the EntryMap, with special handling
Tongbo Liuc5f7b962024-01-04 09:03:35 +0000280// for partial MTS and MCTS test suites.
Liz Kammer57f5b332020-11-24 12:42:58 -0800281func (a *AndroidMkEntries) AddCompatibilityTestSuites(suites ...string) {
Tongbo Liuc5f7b962024-01-04 09:03:35 +0000282 // M(C)TS supports a full test suite and partial per-module MTS test suites, with naming mts-${MODULE}.
283 // 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 -0800284 // we add the full test suite to our list.
285 if PrefixInList(suites, "mts-") && !InList("mts", suites) {
286 suites = append(suites, "mts")
287 }
Tongbo Liuc5f7b962024-01-04 09:03:35 +0000288 if PrefixInList(suites, "mcts-") && !InList("mcts", suites) {
289 suites = append(suites, "mcts")
290 }
Liz Kammer57f5b332020-11-24 12:42:58 -0800291 a.AddStrings("LOCAL_COMPATIBILITY_SUITE", suites...)
292}
293
Paul Duffin8b0349c2020-11-26 14:33:21 +0000294// The contributions to the dist.
295type distContributions struct {
Bob Badour51804382022-04-13 11:27:19 -0700296 // Path to license metadata file.
297 licenseMetadataFile Path
Paul Duffin8b0349c2020-11-26 14:33:21 +0000298 // List of goals and the dist copy instructions.
299 copiesForGoals []*copiesForGoals
300}
301
302// getCopiesForGoals returns a copiesForGoals into which copy instructions that
303// must be processed when building one or more of those goals can be added.
304func (d *distContributions) getCopiesForGoals(goals string) *copiesForGoals {
305 copiesForGoals := &copiesForGoals{goals: goals}
306 d.copiesForGoals = append(d.copiesForGoals, copiesForGoals)
307 return copiesForGoals
308}
309
310// Associates a list of dist copy instructions with a set of goals for which they
311// should be run.
312type copiesForGoals struct {
313 // goals are a space separated list of build targets that will trigger the
314 // copy instructions.
315 goals string
316
317 // A list of instructions to copy a module's output files to somewhere in the
318 // dist directory.
319 copies []distCopy
320}
321
322// Adds a copy instruction.
323func (d *copiesForGoals) addCopyInstruction(from Path, dest string) {
324 d.copies = append(d.copies, distCopy{from, dest})
325}
326
327// Instruction on a path that must be copied into the dist.
328type distCopy struct {
329 // The path to copy from.
330 from Path
331
332 // The destination within the dist directory to copy to.
333 dest string
334}
335
336// Compute the contributions that the module makes to the dist.
337func (a *AndroidMkEntries) getDistContributions(mod blueprint.Module) *distContributions {
Jingwen Chen40fd90a2020-06-15 05:24:19 +0000338 amod := mod.(Module).base()
339 name := amod.BaseModuleName()
340
Paul Duffin74f05592020-11-25 16:37:46 +0000341 // Collate the set of associated tag/paths available for copying to the dist.
342 // Start with an empty (nil) set.
Jingwen Chen7b27ca72020-07-24 09:13:49 +0000343 var availableTaggedDists TaggedDistFiles
Jingwen Chen40fd90a2020-06-15 05:24:19 +0000344
Paul Duffin74f05592020-11-25 16:37:46 +0000345 // Then merge in any that are provided explicitly by the module.
Jingwen Chen84811862020-07-21 11:32:19 +0000346 if a.DistFiles != nil {
Paul Duffin74f05592020-11-25 16:37:46 +0000347 // Merge the DistFiles into the set.
348 availableTaggedDists = availableTaggedDists.merge(a.DistFiles)
349 }
350
351 // If no paths have been provided for the DefaultDistTag and the output file is
352 // valid then add that as the default dist path.
353 if _, ok := availableTaggedDists[DefaultDistTag]; !ok && a.OutputFile.Valid() {
354 availableTaggedDists = availableTaggedDists.addPathsForTag(DefaultDistTag, a.OutputFile.Path())
355 }
356
Yu Liuec810542024-08-26 18:09:15 +0000357 info := OtherModuleProviderOrDefault(a.entryContext, mod, InstallFilesProvider)
Paul Duffinaf970a22020-11-23 23:32:56 +0000358 // If the distFiles created by GenerateTaggedDistFiles contains paths for the
359 // DefaultDistTag then that takes priority so delete any existing paths.
Yu Liuec810542024-08-26 18:09:15 +0000360 if _, ok := info.DistFiles[DefaultDistTag]; ok {
Paul Duffinaf970a22020-11-23 23:32:56 +0000361 delete(availableTaggedDists, DefaultDistTag)
362 }
363
364 // Finally, merge the distFiles created by GenerateTaggedDistFiles.
Yu Liuec810542024-08-26 18:09:15 +0000365 availableTaggedDists = availableTaggedDists.merge(info.DistFiles)
Paul Duffinaf970a22020-11-23 23:32:56 +0000366
Paul Duffin74f05592020-11-25 16:37:46 +0000367 if len(availableTaggedDists) == 0 {
Jingwen Chen7b27ca72020-07-24 09:13:49 +0000368 // Nothing dist-able for this module.
369 return nil
Jingwen Chen40fd90a2020-06-15 05:24:19 +0000370 }
371
Paul Duffin8b0349c2020-11-26 14:33:21 +0000372 // Collate the contributions this module makes to the dist.
373 distContributions := &distContributions{}
374
Bob Badour4660a982022-09-12 16:06:03 -0700375 if !exemptFromRequiredApplicableLicensesProperty(mod.(Module)) {
Yu Liuec810542024-08-26 18:09:15 +0000376 distContributions.licenseMetadataFile = info.LicenseMetadataFile
Bob Badour4660a982022-09-12 16:06:03 -0700377 }
Bob Badour51804382022-04-13 11:27:19 -0700378
Jingwen Chen40fd90a2020-06-15 05:24:19 +0000379 // Iterate over this module's dist structs, merged from the dist and dists properties.
380 for _, dist := range amod.Dists() {
381 // Get the list of goals this dist should be enabled for. e.g. sdk, droidcore
382 goals := strings.Join(dist.Targets, " ")
383
384 // Get the tag representing the output files to be dist'd. e.g. ".jar", ".proguard_map"
385 var tag string
386 if dist.Tag == nil {
387 // If the dist struct does not specify a tag, use the default output files tag.
Paul Duffin74f05592020-11-25 16:37:46 +0000388 tag = DefaultDistTag
Jingwen Chen40fd90a2020-06-15 05:24:19 +0000389 } else {
390 tag = *dist.Tag
391 }
392
393 // Get the paths of the output files to be dist'd, represented by the tag.
394 // Can be an empty list.
395 tagPaths := availableTaggedDists[tag]
396 if len(tagPaths) == 0 {
397 // Nothing to dist for this tag, continue to the next dist.
398 continue
399 }
400
401 if len(tagPaths) > 1 && (dist.Dest != nil || dist.Suffix != nil) {
Paul Duffin74f05592020-11-25 16:37:46 +0000402 errorMessage := "%s: Cannot apply dest/suffix for more than one dist " +
403 "file for %q goals tag %q in module %s. The list of dist files, " +
Jingwen Chen40fd90a2020-06-15 05:24:19 +0000404 "which should have a single element, is:\n%s"
Paul Duffin74f05592020-11-25 16:37:46 +0000405 panic(fmt.Errorf(errorMessage, mod, goals, tag, name, tagPaths))
Jingwen Chen40fd90a2020-06-15 05:24:19 +0000406 }
407
Paul Duffin8b0349c2020-11-26 14:33:21 +0000408 copiesForGoals := distContributions.getCopiesForGoals(goals)
Jingwen Chen40fd90a2020-06-15 05:24:19 +0000409
Paul Duffin8b0349c2020-11-26 14:33:21 +0000410 // Iterate over each path adding a copy instruction to copiesForGoals
Jingwen Chen40fd90a2020-06-15 05:24:19 +0000411 for _, path := range tagPaths {
412 // It's possible that the Path is nil from errant modules. Be defensive here.
413 if path == nil {
414 tagName := "default" // for error message readability
415 if dist.Tag != nil {
416 tagName = *dist.Tag
417 }
418 panic(fmt.Errorf("Dist file should not be nil for the %s tag in %s", tagName, name))
419 }
420
421 dest := filepath.Base(path.String())
422
423 if dist.Dest != nil {
424 var err error
425 if dest, err = validateSafePath(*dist.Dest); err != nil {
426 // This was checked in ModuleBase.GenerateBuildActions
427 panic(err)
428 }
429 }
430
Trevor Radcliffe90727f42022-03-21 19:34:02 +0000431 ext := filepath.Ext(dest)
432 suffix := ""
Jingwen Chen40fd90a2020-06-15 05:24:19 +0000433 if dist.Suffix != nil {
Trevor Radcliffe90727f42022-03-21 19:34:02 +0000434 suffix = *dist.Suffix
435 }
436
437 productString := ""
438 if dist.Append_artifact_with_product != nil && *dist.Append_artifact_with_product {
439 productString = fmt.Sprintf("_%s", a.entryContext.Config().DeviceProduct())
440 }
441
442 if suffix != "" || productString != "" {
443 dest = strings.TrimSuffix(dest, ext) + suffix + productString + ext
Jingwen Chen40fd90a2020-06-15 05:24:19 +0000444 }
445
446 if dist.Dir != nil {
447 var err error
448 if dest, err = validateSafePath(*dist.Dir, dest); err != nil {
449 // This was checked in ModuleBase.GenerateBuildActions
450 panic(err)
451 }
452 }
453
Paul Duffin8b0349c2020-11-26 14:33:21 +0000454 copiesForGoals.addCopyInstruction(path, dest)
455 }
456 }
457
458 return distContributions
459}
460
461// generateDistContributionsForMake generates make rules that will generate the
462// dist according to the instructions in the supplied distContribution.
463func generateDistContributionsForMake(distContributions *distContributions) []string {
464 var ret []string
465 for _, d := range distContributions.copiesForGoals {
Yu Liue70976d2024-10-15 20:45:35 +0000466 ret = append(ret, fmt.Sprintf(".PHONY: %s", d.goals))
Paul Duffin8b0349c2020-11-26 14:33:21 +0000467 // Create dist-for-goals calls for each of the copy instructions.
468 for _, c := range d.copies {
Bob Badour4660a982022-09-12 16:06:03 -0700469 if distContributions.licenseMetadataFile != nil {
470 ret = append(
471 ret,
Yu Liue70976d2024-10-15 20:45:35 +0000472 fmt.Sprintf("$(if $(strip $(ALL_TARGETS.%s.META_LIC)),,$(eval ALL_TARGETS.%s.META_LIC := %s))",
Bob Badour4660a982022-09-12 16:06:03 -0700473 c.from.String(), c.from.String(), distContributions.licenseMetadataFile.String()))
474 }
Bob Badour51804382022-04-13 11:27:19 -0700475 ret = append(
476 ret,
Yu Liue70976d2024-10-15 20:45:35 +0000477 fmt.Sprintf("$(call dist-for-goals,%s,%s:%s)", d.goals, c.from.String(), c.dest))
Jingwen Chen40fd90a2020-06-15 05:24:19 +0000478 }
479 }
480
481 return ret
482}
483
Paul Duffin8b0349c2020-11-26 14:33:21 +0000484// Compute the list of Make strings to declare phony goals and dist-for-goals
485// calls from the module's dist and dists properties.
486func (a *AndroidMkEntries) GetDistForGoals(mod blueprint.Module) []string {
487 distContributions := a.getDistContributions(mod)
488 if distContributions == nil {
489 return nil
490 }
491
492 return generateDistContributionsForMake(distContributions)
493}
494
Jaewoong Jung7ef4a902020-11-16 12:50:29 -0800495// fillInEntries goes through the common variable processing and calls the extra data funcs to
496// generate and fill in AndroidMkEntries's in-struct data, ready to be flushed to a file.
Colin Crossaa255532020-07-03 13:18:24 -0700497type fillInEntriesContext interface {
498 ModuleDir(module blueprint.Module) string
Cole Faust39aabe92023-02-23 16:57:43 -0800499 ModuleSubDir(module blueprint.Module) string
Colin Crossaa255532020-07-03 13:18:24 -0700500 Config() Config
Yu Liu663e4502024-08-12 18:23:59 +0000501 otherModuleProvider(module blueprint.Module, provider blueprint.AnyProviderKey) (any, bool)
Sasha Smundak5c4729d2022-12-01 10:49:23 -0800502 ModuleType(module blueprint.Module) string
Cole Faust43ddd082024-06-17 12:32:40 -0700503 OtherModulePropertyErrorf(module Module, property string, fmt string, args ...interface{})
Cole Faust4e2bf9f2024-09-11 13:26:20 -0700504 HasMutatorFinished(mutatorName string) bool
Colin Crossaa255532020-07-03 13:18:24 -0700505}
506
507func (a *AndroidMkEntries) fillInEntries(ctx fillInEntriesContext, mod blueprint.Module) {
Trevor Radcliffe90727f42022-03-21 19:34:02 +0000508 a.entryContext = ctx
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700509 a.EntryMap = make(map[string][]string)
Colin Crossf1f763a2021-10-21 16:14:19 -0700510 amod := mod.(Module)
511 base := amod.base()
512 name := base.BaseModuleName()
Colin Cross0477b422020-10-13 18:43:54 -0700513 if a.OverrideName != "" {
514 name = a.OverrideName
515 }
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700516
517 if a.Include == "" {
518 a.Include = "$(BUILD_PREBUILT)"
519 }
Cole Faust43ddd082024-06-17 12:32:40 -0700520 a.Required = append(a.Required, amod.RequiredModuleNames(ctx)...)
Kiyoung Kim04b64fc2024-08-19 11:25:30 +0900521 a.Required = append(a.Required, amod.VintfFragmentModuleNames(ctx)...)
Colin Crossf1f763a2021-10-21 16:14:19 -0700522 a.Host_required = append(a.Host_required, amod.HostRequiredModuleNames()...)
523 a.Target_required = append(a.Target_required, amod.TargetRequiredModuleNames()...)
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700524
Jingwen Chen40fd90a2020-06-15 05:24:19 +0000525 for _, distString := range a.GetDistForGoals(mod) {
Yu Liue70976d2024-10-15 20:45:35 +0000526 fmt.Fprintln(&a.header, distString)
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700527 }
528
Cole Faust39aabe92023-02-23 16:57:43 -0800529 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 -0700530
531 // Collect make variable assignment entries.
Colin Crossaa255532020-07-03 13:18:24 -0700532 a.SetString("LOCAL_PATH", ctx.ModuleDir(mod))
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700533 a.SetString("LOCAL_MODULE", name+a.SubName)
534 a.SetString("LOCAL_MODULE_CLASS", a.Class)
535 a.SetString("LOCAL_PREBUILT_MODULE_FILE", a.OutputFile.String())
536 a.AddStrings("LOCAL_REQUIRED_MODULES", a.Required...)
537 a.AddStrings("LOCAL_HOST_REQUIRED_MODULES", a.Host_required...)
538 a.AddStrings("LOCAL_TARGET_REQUIRED_MODULES", a.Target_required...)
Wei Li598f92d2023-01-04 17:12:24 -0800539 a.AddStrings("LOCAL_SOONG_MODULE_TYPE", ctx.ModuleType(amod))
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700540
Colin Cross6301c3c2021-09-28 17:40:21 -0700541 // If the install rule was generated by Soong tell Make about it.
Yu Liud46e5ae2024-08-15 18:46:17 +0000542 info := OtherModuleProviderOrDefault(ctx, mod, InstallFilesProvider)
543 if len(info.KatiInstalls) > 0 {
Colin Cross6301c3c2021-09-28 17:40:21 -0700544 // Assume the primary install file is last since it probably needs to depend on any other
545 // installed files. If that is not the case we can add a method to specify the primary
546 // installed file.
Yu Liud46e5ae2024-08-15 18:46:17 +0000547 a.SetPath("LOCAL_SOONG_INSTALLED_MODULE", info.KatiInstalls[len(info.KatiInstalls)-1].to)
548 a.SetString("LOCAL_SOONG_INSTALL_PAIRS", info.KatiInstalls.BuiltInstalled())
549 a.SetPaths("LOCAL_SOONG_INSTALL_SYMLINKS", info.KatiSymlinks.InstallPaths().Paths())
Jiyong Park3f627e62024-05-01 16:14:38 +0900550 } else {
551 // Soong may not have generated the install rule also when `no_full_install: true`.
552 // Mark this module as uninstallable in order to prevent Make from creating an
553 // install rule there.
554 a.SetBoolIfTrue("LOCAL_UNINSTALLABLE_MODULE", proptools.Bool(base.commonProperties.No_full_install))
Colin Cross6301c3c2021-09-28 17:40:21 -0700555 }
556
Colin Crossa6182ab2024-08-21 10:47:44 -0700557 if info.UncheckedModule {
558 a.SetBool("LOCAL_DONT_CHECK_MODULE", true)
559 } else if info.CheckbuildTarget != nil {
560 a.SetPath("LOCAL_CHECKED_MODULE", info.CheckbuildTarget)
561 } else {
562 a.SetOptionalPath("LOCAL_CHECKED_MODULE", a.OutputFile)
563 }
564
Yu Liud46e5ae2024-08-15 18:46:17 +0000565 if len(info.TestData) > 0 {
566 a.AddStrings("LOCAL_TEST_DATA", androidMkDataPaths(info.TestData)...)
Colin Cross5c1d5fb2023-11-15 12:39:40 -0800567 }
568
Jiyong Park89e850a2020-04-07 16:37:39 +0900569 if am, ok := mod.(ApexModule); ok {
570 a.SetBoolIfTrue("LOCAL_NOT_AVAILABLE_FOR_PLATFORM", am.NotAvailableForPlatform())
571 }
572
Colin Crossf1f763a2021-10-21 16:14:19 -0700573 archStr := base.Arch().ArchType.String()
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700574 host := false
Colin Crossf1f763a2021-10-21 16:14:19 -0700575 switch base.Os().Class {
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700576 case Host:
Colin Crossf1f763a2021-10-21 16:14:19 -0700577 if base.Target().HostCross {
Jiyong Park1613e552020-09-14 19:43:17 +0900578 // Make cannot identify LOCAL_MODULE_HOST_CROSS_ARCH:= common.
Colin Crossf1f763a2021-10-21 16:14:19 -0700579 if base.Arch().ArchType != Common {
Jiyong Park1613e552020-09-14 19:43:17 +0900580 a.SetString("LOCAL_MODULE_HOST_CROSS_ARCH", archStr)
581 }
582 } else {
583 // Make cannot identify LOCAL_MODULE_HOST_ARCH:= common.
Colin Crossf1f763a2021-10-21 16:14:19 -0700584 if base.Arch().ArchType != Common {
Jiyong Park1613e552020-09-14 19:43:17 +0900585 a.SetString("LOCAL_MODULE_HOST_ARCH", archStr)
586 }
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700587 }
588 host = true
589 case Device:
590 // Make cannot identify LOCAL_MODULE_TARGET_ARCH:= common.
Colin Crossf1f763a2021-10-21 16:14:19 -0700591 if base.Arch().ArchType != Common {
592 if base.Target().NativeBridge {
593 hostArchStr := base.Target().NativeBridgeHostArchName
dimitry1f33e402019-03-26 12:39:31 +0100594 if hostArchStr != "" {
595 a.SetString("LOCAL_MODULE_TARGET_ARCH", hostArchStr)
596 }
597 } else {
598 a.SetString("LOCAL_MODULE_TARGET_ARCH", archStr)
599 }
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700600 }
601
Kelvin Zhang46977252022-04-13 16:41:34 -0700602 if !base.InVendorRamdisk() {
Yu Liu82a6d142024-08-27 19:02:29 +0000603 a.AddPaths("LOCAL_FULL_INIT_RC", info.InitRcPaths)
Yifan Hong919dae12020-12-02 18:55:06 -0800604 }
Yu Liu82a6d142024-08-27 19:02:29 +0000605 if len(info.VintfFragmentsPaths) > 0 {
606 a.AddPaths("LOCAL_FULL_VINTF_FRAGMENTS", info.VintfFragmentsPaths)
Liz Kammer7b3dc8a2021-04-16 16:41:59 -0400607 }
Colin Crossf1f763a2021-10-21 16:14:19 -0700608 a.SetBoolIfTrue("LOCAL_PROPRIETARY_MODULE", Bool(base.commonProperties.Proprietary))
609 if Bool(base.commonProperties.Vendor) || Bool(base.commonProperties.Soc_specific) {
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700610 a.SetString("LOCAL_VENDOR_MODULE", "true")
611 }
Colin Crossf1f763a2021-10-21 16:14:19 -0700612 a.SetBoolIfTrue("LOCAL_ODM_MODULE", Bool(base.commonProperties.Device_specific))
613 a.SetBoolIfTrue("LOCAL_PRODUCT_MODULE", Bool(base.commonProperties.Product_specific))
614 a.SetBoolIfTrue("LOCAL_SYSTEM_EXT_MODULE", Bool(base.commonProperties.System_ext_specific))
615 if base.commonProperties.Owner != nil {
616 a.SetString("LOCAL_MODULE_OWNER", *base.commonProperties.Owner)
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700617 }
618 }
619
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700620 if host {
Colin Crossf1f763a2021-10-21 16:14:19 -0700621 makeOs := base.Os().String()
622 if base.Os() == Linux || base.Os() == LinuxBionic || base.Os() == LinuxMusl {
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700623 makeOs = "linux"
624 }
625 a.SetString("LOCAL_MODULE_HOST_OS", makeOs)
626 a.SetString("LOCAL_IS_HOST_MODULE", "true")
627 }
628
629 prefix := ""
Colin Crossf1f763a2021-10-21 16:14:19 -0700630 if base.ArchSpecific() {
631 switch base.Os().Class {
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700632 case Host:
Colin Crossf1f763a2021-10-21 16:14:19 -0700633 if base.Target().HostCross {
Jiyong Park1613e552020-09-14 19:43:17 +0900634 prefix = "HOST_CROSS_"
635 } else {
636 prefix = "HOST_"
637 }
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700638 case Device:
639 prefix = "TARGET_"
640
641 }
642
Colin Crossf1f763a2021-10-21 16:14:19 -0700643 if base.Arch().ArchType != ctx.Config().Targets[base.Os()][0].Arch.ArchType {
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700644 prefix = "2ND_" + prefix
645 }
646 }
Colin Crossaa255532020-07-03 13:18:24 -0700647
Yu Liu663e4502024-08-12 18:23:59 +0000648 if licenseMetadata, ok := OtherModuleProvider(ctx, mod, LicenseMetadataProvider); ok {
Colin Cross4acaea92021-12-10 23:05:02 +0000649 a.SetPath("LOCAL_SOONG_LICENSE_METADATA", licenseMetadata.LicenseMetadataPath)
650 }
651
Yu Liu663e4502024-08-12 18:23:59 +0000652 if _, ok := OtherModuleProvider(ctx, mod, ModuleInfoJSONProvider); ok {
Colin Crossd6fd0132023-11-06 13:54:06 -0800653 a.SetBool("LOCAL_SOONG_MODULE_INFO_JSON", true)
654 }
655
Colin Crossaa255532020-07-03 13:18:24 -0700656 extraCtx := &androidMkExtraEntriesContext{
657 ctx: ctx,
658 mod: mod,
659 }
660
Jaewoong Junge0dc8df2019-08-27 17:33:16 -0700661 for _, extra := range a.ExtraEntries {
Colin Crossaa255532020-07-03 13:18:24 -0700662 extra(extraCtx, a)
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700663 }
664
665 // Write to footer.
666 fmt.Fprintln(&a.footer, "include "+a.Include)
Colin Crossaa255532020-07-03 13:18:24 -0700667 blueprintDir := ctx.ModuleDir(mod)
Jaewoong Jungb0c127c2019-08-29 14:56:03 -0700668 for _, footerFunc := range a.ExtraFooters {
Jaewoong Jung02b11a62020-12-07 10:23:54 -0800669 footerFunc(&a.footer, name, prefix, blueprintDir)
Jaewoong Jungb0c127c2019-08-29 14:56:03 -0700670 }
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700671}
672
Colin Crossd6fd0132023-11-06 13:54:06 -0800673func (a *AndroidMkEntries) disabled() bool {
674 return a.Disabled || !a.OutputFile.Valid()
675}
676
Jaewoong Jung7ef4a902020-11-16 12:50:29 -0800677// write flushes the AndroidMkEntries's in-struct data populated by AndroidMkEntries into the
678// given Writer object.
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700679func (a *AndroidMkEntries) write(w io.Writer) {
Colin Crossd6fd0132023-11-06 13:54:06 -0800680 if a.disabled() {
Jaewoong Jungb0c127c2019-08-29 14:56:03 -0700681 return
682 }
683
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700684 w.Write(a.header.Bytes())
685 for _, name := range a.entryOrder {
Sasha Smundakdcb61292022-12-08 10:41:33 -0800686 AndroidMkEmitAssignList(w, name, a.EntryMap[name])
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700687 }
688 w.Write(a.footer.Bytes())
689}
690
Jaewoong Jungb0c127c2019-08-29 14:56:03 -0700691func (a *AndroidMkEntries) FooterLinesForTests() []string {
692 return strings.Split(string(a.footer.Bytes()), "\n")
693}
694
Jaewoong Jung7ef4a902020-11-16 12:50:29 -0800695// AndroidMkSingleton is a singleton to collect Android.mk data from all modules and dump them into
696// the final Android-<product_name>.mk file output.
Colin Cross0875c522017-11-28 17:34:01 -0800697func AndroidMkSingleton() Singleton {
Dan Willemsen218f6562015-07-08 18:13:11 -0700698 return &androidMkSingleton{}
699}
700
701type androidMkSingleton struct{}
702
Colin Cross0875c522017-11-28 17:34:01 -0800703func (c *androidMkSingleton) GenerateBuildActions(ctx SingletonContext) {
Colin Cross2465c3d2018-09-28 10:19:18 -0700704 var androidMkModulesList []blueprint.Module
Colin Cross4f6e4e62016-01-11 12:55:55 -0800705
Colin Cross2465c3d2018-09-28 10:19:18 -0700706 ctx.VisitAllModulesBlueprint(func(module blueprint.Module) {
Colin Cross0875c522017-11-28 17:34:01 -0800707 androidMkModulesList = append(androidMkModulesList, module)
Colin Cross4f6e4e62016-01-11 12:55:55 -0800708 })
Dan Willemsen218f6562015-07-08 18:13:11 -0700709
Jaewoong Jung7ef4a902020-11-16 12:50:29 -0800710 // Sort the module list by the module names to eliminate random churns, which may erroneously
711 // invoke additional build processes.
Colin Cross1ad81422019-01-14 12:47:35 -0800712 sort.SliceStable(androidMkModulesList, func(i, j int) bool {
713 return ctx.ModuleName(androidMkModulesList[i]) < ctx.ModuleName(androidMkModulesList[j])
714 })
Colin Crossd779da42015-12-17 18:00:23 -0800715
Cole Faustc5bfbdd2025-01-08 13:05:40 -0800716 // If running in soong-only mode, do a different, more limited version of this singleton
717 if !ctx.Config().KatiEnabled() {
718 c.soongOnlyBuildActions(ctx, androidMkModulesList)
719 return
720 }
721
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
Cole Faustc5bfbdd2025-01-08 13:05:40 -0800740// In soong-only mode, we don't do most of the androidmk stuff. But disted files are still largely
741// defined through the androidmk mechanisms, so this function is an alternate implementation of
742// the androidmk singleton that just focuses on getting the dist contributions
743func (c *androidMkSingleton) soongOnlyBuildActions(ctx SingletonContext, mods []blueprint.Module) {
Cole Faustf9a096c2025-01-21 16:55:43 -0800744 allDistContributions, moduleInfoJSONs := getSoongOnlyDataFromMods(ctx, mods)
Cole Faustc5bfbdd2025-01-08 13:05:40 -0800745
Cole Faustf9a096c2025-01-21 16:55:43 -0800746 // Build module-info.json. Only in builds with HasDeviceProduct(), as we need a named
747 // device to have a TARGET_OUT folder.
748 if ctx.Config().HasDeviceProduct() {
Cole Faust601da062025-01-22 13:15:10 -0800749 preMergePath := PathForOutput(ctx, "module_info_pre_merging.json")
Cole Faustf9a096c2025-01-21 16:55:43 -0800750 moduleInfoJSONPath := pathForInstall(ctx, Android, X86_64, "", "module-info.json")
Cole Faust601da062025-01-22 13:15:10 -0800751 if err := writeModuleInfoJSON(ctx, moduleInfoJSONs, preMergePath); err != nil {
Cole Faustf9a096c2025-01-21 16:55:43 -0800752 ctx.Errorf("%s", err)
753 }
Cole Faust601da062025-01-22 13:15:10 -0800754 builder := NewRuleBuilder(pctx, ctx)
755 builder.Command().
756 BuiltTool("merge_module_info_json").
757 FlagWithOutput("-o ", moduleInfoJSONPath).
758 Input(preMergePath)
759 builder.Build("merge_module_info_json", "merge module info json")
Cole Faustf9a096c2025-01-21 16:55:43 -0800760 ctx.Phony("module-info", moduleInfoJSONPath)
761 ctx.Phony("droidcore-unbundled", moduleInfoJSONPath)
762 allDistContributions = append(allDistContributions, distContributions{
763 copiesForGoals: []*copiesForGoals{{
764 goals: "general-tests droidcore-unbundled",
765 copies: []distCopy{{
766 from: moduleInfoJSONPath,
767 dest: "module-info.json",
768 }},
769 }},
770 })
771 }
772
773 // Build dist.mk for the packaging step to read and generate dist targets
Cole Faustc5bfbdd2025-01-08 13:05:40 -0800774 distMkFile := absolutePath(filepath.Join(ctx.Config().katiPackageMkDir(), "dist.mk"))
775
776 var goalOutputPairs []string
Cole Faust82611a12025-01-09 11:20:41 -0800777 var srcDstPairs []string
Cole Faustc5bfbdd2025-01-08 13:05:40 -0800778 for _, contributions := range allDistContributions {
779 for _, copiesForGoal := range contributions.copiesForGoals {
780 goals := strings.Fields(copiesForGoal.goals)
781 for _, copy := range copiesForGoal.copies {
782 for _, goal := range goals {
Cole Faust82611a12025-01-09 11:20:41 -0800783 goalOutputPairs = append(goalOutputPairs, fmt.Sprintf(" %s:%s", goal, copy.dest))
Cole Faustc5bfbdd2025-01-08 13:05:40 -0800784 }
Cole Faust82611a12025-01-09 11:20:41 -0800785 srcDstPairs = append(srcDstPairs, fmt.Sprintf(" %s:%s", copy.from.String(), copy.dest))
Cole Faustc5bfbdd2025-01-08 13:05:40 -0800786 }
787 }
788 }
Cole Faust82611a12025-01-09 11:20:41 -0800789 // There are duplicates in the lists that we need to remove
790 goalOutputPairs = SortedUniqueStrings(goalOutputPairs)
791 srcDstPairs = SortedUniqueStrings(srcDstPairs)
792 var buf strings.Builder
793 buf.WriteString("DIST_SRC_DST_PAIRS :=")
794 for _, srcDstPair := range srcDstPairs {
795 buf.WriteString(srcDstPair)
796 }
797 buf.WriteString("\nDIST_GOAL_OUTPUT_PAIRS :=")
798 for _, goalOutputPair := range goalOutputPairs {
799 buf.WriteString(goalOutputPair)
800 }
801 buf.WriteString("\n")
Cole Faustc5bfbdd2025-01-08 13:05:40 -0800802
803 writeValueIfChanged(ctx, distMkFile, buf.String())
804}
805
806func writeValueIfChanged(ctx SingletonContext, path string, value string) {
807 if err := os.MkdirAll(filepath.Dir(path), 0777); err != nil {
808 ctx.Errorf("%s\n", err)
809 return
810 }
811 previousValue := ""
812 rawPreviousValue, err := os.ReadFile(path)
813 if err == nil {
814 previousValue = string(rawPreviousValue)
815 }
816
817 if previousValue != value {
818 if err = os.WriteFile(path, []byte(value), 0666); err != nil {
819 ctx.Errorf("Failed to write: %v", err)
820 }
821 }
822}
823
Cole Faustf9a096c2025-01-21 16:55:43 -0800824// getSoongOnlyDataFromMods gathers data from the given modules needed in soong-only builds.
825// Currently, this is the dist contributions, and the module-info.json contents.
826func getSoongOnlyDataFromMods(ctx fillInEntriesContext, mods []blueprint.Module) ([]distContributions, []*ModuleInfoJSON) {
Cole Faustc5bfbdd2025-01-08 13:05:40 -0800827 var allDistContributions []distContributions
Cole Faustf9a096c2025-01-21 16:55:43 -0800828 var moduleInfoJSONs []*ModuleInfoJSON
Cole Faustc5bfbdd2025-01-08 13:05:40 -0800829 for _, mod := range mods {
830 if amod, ok := mod.(Module); ok && shouldSkipAndroidMkProcessing(ctx, amod.base()) {
831 continue
832 }
833 if info, ok := OtherModuleProvider(ctx, mod, AndroidMkInfoProvider); ok {
Cole Faust556f1f42025-01-09 10:49:42 -0800834 // Deep copy the provider info since we need to modify the info later
835 info := deepCopyAndroidMkProviderInfo(info)
836 info.PrimaryInfo.fillInEntries(ctx, mod)
837 if info.PrimaryInfo.disabled() {
838 continue
839 }
Cole Faustf9a096c2025-01-21 16:55:43 -0800840 if moduleInfoJSON, ok := OtherModuleProvider(ctx, mod, ModuleInfoJSONProvider); ok {
841 moduleInfoJSONs = append(moduleInfoJSONs, moduleInfoJSON)
842 }
Cole Faustc5bfbdd2025-01-08 13:05:40 -0800843 if contribution := info.PrimaryInfo.getDistContributions(ctx, mod); contribution != nil {
844 allDistContributions = append(allDistContributions, *contribution)
845 }
846 for _, ei := range info.ExtraInfo {
Cole Faust556f1f42025-01-09 10:49:42 -0800847 ei.fillInEntries(ctx, mod)
848 if ei.disabled() {
849 continue
850 }
Cole Faustc5bfbdd2025-01-08 13:05:40 -0800851 if contribution := ei.getDistContributions(ctx, mod); contribution != nil {
852 allDistContributions = append(allDistContributions, *contribution)
853 }
854 }
855 } else {
856 switch x := mod.(type) {
857 case AndroidMkDataProvider:
858 data := x.AndroidMk()
859
860 if data.Include == "" {
861 data.Include = "$(BUILD_PREBUILT)"
862 }
863
864 data.fillInData(ctx, mod)
Cole Faust556f1f42025-01-09 10:49:42 -0800865 if data.Entries.disabled() {
866 continue
867 }
Cole Faustf9a096c2025-01-21 16:55:43 -0800868 if moduleInfoJSON, ok := OtherModuleProvider(ctx, mod, ModuleInfoJSONProvider); ok {
869 moduleInfoJSONs = append(moduleInfoJSONs, moduleInfoJSON)
870 }
Cole Faustc5bfbdd2025-01-08 13:05:40 -0800871 if contribution := data.Entries.getDistContributions(mod); contribution != nil {
872 allDistContributions = append(allDistContributions, *contribution)
873 }
874 case AndroidMkEntriesProvider:
875 entriesList := x.AndroidMkEntries()
876 for _, entries := range entriesList {
877 entries.fillInEntries(ctx, mod)
Cole Faust556f1f42025-01-09 10:49:42 -0800878 if entries.disabled() {
879 continue
880 }
Cole Faustf9a096c2025-01-21 16:55:43 -0800881 if moduleInfoJSON, ok := OtherModuleProvider(ctx, mod, ModuleInfoJSONProvider); ok {
882 moduleInfoJSONs = append(moduleInfoJSONs, moduleInfoJSON)
883 }
Cole Faustc5bfbdd2025-01-08 13:05:40 -0800884 if contribution := entries.getDistContributions(mod); contribution != nil {
885 allDistContributions = append(allDistContributions, *contribution)
886 }
887 }
888 default:
889 // Not exported to make so no make variables to set.
890 }
891 }
892 }
Cole Faustf9a096c2025-01-21 16:55:43 -0800893 return allDistContributions, moduleInfoJSONs
Cole Faustc5bfbdd2025-01-08 13:05:40 -0800894}
895
Colin Crossd6fd0132023-11-06 13:54:06 -0800896func translateAndroidMk(ctx SingletonContext, absMkFile string, moduleInfoJSONPath WritablePath, mods []blueprint.Module) error {
Dan Willemsen218f6562015-07-08 18:13:11 -0700897 buf := &bytes.Buffer{}
898
Colin Crossd6fd0132023-11-06 13:54:06 -0800899 var moduleInfoJSONs []*ModuleInfoJSON
900
Dan Willemsen97750522016-02-09 17:43:51 -0800901 fmt.Fprintln(buf, "LOCAL_MODULE_MAKEFILE := $(lastword $(MAKEFILE_LIST))")
Dan Willemsen218f6562015-07-08 18:13:11 -0700902
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800903 typeStats := make(map[string]int)
Dan Willemsen218f6562015-07-08 18:13:11 -0700904 for _, mod := range mods {
Colin Crossd6fd0132023-11-06 13:54:06 -0800905 err := translateAndroidMkModule(ctx, buf, &moduleInfoJSONs, mod)
Dan Willemsen218f6562015-07-08 18:13:11 -0700906 if err != nil {
Colin Cross836e3872021-11-09 12:30:59 -0800907 os.Remove(absMkFile)
Dan Willemsen218f6562015-07-08 18:13:11 -0700908 return err
909 }
Dan Willemsen70e17fa2016-07-25 16:00:20 -0700910
Colin Cross2465c3d2018-09-28 10:19:18 -0700911 if amod, ok := mod.(Module); ok && ctx.PrimaryModule(amod) == amod {
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800912 typeStats[ctx.ModuleType(amod)] += 1
Dan Willemsen70e17fa2016-07-25 16:00:20 -0700913 }
914 }
915
916 keys := []string{}
917 fmt.Fprintln(buf, "\nSTATS.SOONG_MODULE_TYPE :=")
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800918 for k := range typeStats {
Dan Willemsen70e17fa2016-07-25 16:00:20 -0700919 keys = append(keys, k)
920 }
921 sort.Strings(keys)
922 for _, mod_type := range keys {
923 fmt.Fprintln(buf, "STATS.SOONG_MODULE_TYPE +=", mod_type)
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800924 fmt.Fprintf(buf, "STATS.SOONG_MODULE_TYPE.%s := %d\n", mod_type, typeStats[mod_type])
Dan Willemsen218f6562015-07-08 18:13:11 -0700925 }
926
Colin Crossd6fd0132023-11-06 13:54:06 -0800927 err := pathtools.WriteFileIfChanged(absMkFile, buf.Bytes(), 0666)
928 if err != nil {
929 return err
930 }
931
932 return writeModuleInfoJSON(ctx, moduleInfoJSONs, moduleInfoJSONPath)
Dan Willemsen218f6562015-07-08 18:13:11 -0700933}
934
Colin Crossd6fd0132023-11-06 13:54:06 -0800935func writeModuleInfoJSON(ctx SingletonContext, moduleInfoJSONs []*ModuleInfoJSON, moduleInfoJSONPath WritablePath) error {
936 moduleInfoJSONBuf := &strings.Builder{}
937 moduleInfoJSONBuf.WriteString("[")
938 for i, moduleInfoJSON := range moduleInfoJSONs {
939 if i != 0 {
940 moduleInfoJSONBuf.WriteString(",\n")
941 }
942 moduleInfoJSONBuf.WriteString("{")
943 moduleInfoJSONBuf.WriteString(strconv.Quote(moduleInfoJSON.core.RegisterName))
944 moduleInfoJSONBuf.WriteString(":")
945 err := encodeModuleInfoJSON(moduleInfoJSONBuf, moduleInfoJSON)
946 moduleInfoJSONBuf.WriteString("}")
947 if err != nil {
948 return err
949 }
950 }
951 moduleInfoJSONBuf.WriteString("]")
952 WriteFileRule(ctx, moduleInfoJSONPath, moduleInfoJSONBuf.String())
953 return nil
954}
955
956func translateAndroidMkModule(ctx SingletonContext, w io.Writer, moduleInfoJSONs *[]*ModuleInfoJSON, mod blueprint.Module) error {
Colin Cross953d3a22018-09-05 16:23:54 -0700957 defer func() {
958 if r := recover(); r != nil {
959 panic(fmt.Errorf("%s in translateAndroidMkModule for module %s variant %s",
960 r, ctx.ModuleName(mod), ctx.ModuleSubDir(mod)))
961 }
962 }()
963
Bob Badourb4999222021-01-07 03:34:31 +0000964 // Additional cases here require review for correct license propagation to make.
Colin Crossd6fd0132023-11-06 13:54:06 -0800965 var err error
mrziwang18420972024-09-03 15:12:51 -0700966
Yu Liue70976d2024-10-15 20:45:35 +0000967 if info, ok := OtherModuleProvider(ctx, mod, AndroidMkInfoProvider); ok {
968 err = translateAndroidMkEntriesInfoModule(ctx, w, moduleInfoJSONs, mod, info)
mrziwang18420972024-09-03 15:12:51 -0700969 } else {
970 switch x := mod.(type) {
971 case AndroidMkDataProvider:
972 err = translateAndroidModule(ctx, w, moduleInfoJSONs, mod, x)
mrziwang18420972024-09-03 15:12:51 -0700973 case AndroidMkEntriesProvider:
974 err = translateAndroidMkEntriesModule(ctx, w, moduleInfoJSONs, mod, x)
975 default:
976 // Not exported to make so no make variables to set.
977 }
Dan Willemsen218f6562015-07-08 18:13:11 -0700978 }
Colin Crossd6fd0132023-11-06 13:54:06 -0800979
980 if err != nil {
981 return err
982 }
983
984 return err
Colin Cross2465c3d2018-09-28 10:19:18 -0700985}
986
Colin Crossaa255532020-07-03 13:18:24 -0700987func (data *AndroidMkData) fillInData(ctx fillInEntriesContext, mod blueprint.Module) {
Jooyung Han12df5fb2019-07-11 16:18:47 +0900988 // Get the preamble content through AndroidMkEntries logic.
Jooyung Han2ed99d02020-06-24 23:26:26 +0900989 data.Entries = AndroidMkEntries{
Jooyung Han12df5fb2019-07-11 16:18:47 +0900990 Class: data.Class,
991 SubName: data.SubName,
Jingwen Chen40fd90a2020-06-15 05:24:19 +0000992 DistFiles: data.DistFiles,
Jooyung Han12df5fb2019-07-11 16:18:47 +0900993 OutputFile: data.OutputFile,
994 Disabled: data.Disabled,
995 Include: data.Include,
996 Required: data.Required,
997 Host_required: data.Host_required,
998 Target_required: data.Target_required,
999 }
Colin Crossaa255532020-07-03 13:18:24 -07001000 data.Entries.fillInEntries(ctx, mod)
Jooyung Han12df5fb2019-07-11 16:18:47 +09001001
1002 // copy entries back to data since it is used in Custom
Jooyung Han2ed99d02020-06-24 23:26:26 +09001003 data.Required = data.Entries.Required
1004 data.Host_required = data.Entries.Host_required
1005 data.Target_required = data.Entries.Target_required
Jooyung Han12df5fb2019-07-11 16:18:47 +09001006}
1007
Jaewoong Jung7ef4a902020-11-16 12:50:29 -08001008// A support func for the deprecated AndroidMkDataProvider interface. Use AndroidMkEntryProvider
1009// instead.
Colin Crossd6fd0132023-11-06 13:54:06 -08001010func translateAndroidModule(ctx SingletonContext, w io.Writer, moduleInfoJSONs *[]*ModuleInfoJSON,
1011 mod blueprint.Module, provider AndroidMkDataProvider) error {
Dan Willemsen218f6562015-07-08 18:13:11 -07001012
Colin Cross635c3b02016-05-18 15:37:25 -07001013 amod := mod.(Module).base()
Cole Fausta963b942024-04-11 17:43:00 -07001014 if shouldSkipAndroidMkProcessing(ctx, amod) {
Jeff Gaston088e29e2017-11-29 16:47:17 -08001015 return nil
1016 }
1017
Colin Cross91825d22017-08-10 16:59:47 -07001018 data := provider.AndroidMk()
Yu Liuddc28332024-08-09 22:48:30 +00001019
Colin Cross53499412017-09-07 13:20:25 -07001020 if data.Include == "" {
1021 data.Include = "$(BUILD_PREBUILT)"
1022 }
1023
Colin Crossaa255532020-07-03 13:18:24 -07001024 data.fillInData(ctx, mod)
LaMont Jonesb5099382024-01-10 23:42:36 +00001025 aconfigUpdateAndroidMkData(ctx, mod.(Module), &data)
Dan Willemsen01a405a2016-06-13 17:19:03 -07001026
Colin Cross0f86d182017-08-10 17:07:28 -07001027 prefix := ""
1028 if amod.ArchSpecific() {
1029 switch amod.Os().Class {
1030 case Host:
Jiyong Park1613e552020-09-14 19:43:17 +09001031 if amod.Target().HostCross {
1032 prefix = "HOST_CROSS_"
1033 } else {
1034 prefix = "HOST_"
1035 }
Colin Cross0f86d182017-08-10 17:07:28 -07001036 case Device:
1037 prefix = "TARGET_"
Colin Crossa2344662016-03-24 13:14:12 -07001038
Dan Willemsen218f6562015-07-08 18:13:11 -07001039 }
1040
Dan Willemsen0ef639b2018-10-10 17:02:29 -07001041 if amod.Arch().ArchType != ctx.Config().Targets[amod.Os()][0].Arch.ArchType {
Colin Cross0f86d182017-08-10 17:07:28 -07001042 prefix = "2ND_" + prefix
1043 }
Dan Willemsen218f6562015-07-08 18:13:11 -07001044 }
1045
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -07001046 name := provider.BaseModuleName()
Colin Cross0f86d182017-08-10 17:07:28 -07001047 blueprintDir := filepath.Dir(ctx.BlueprintFile(mod))
1048
1049 if data.Custom != nil {
Bob Badourb4999222021-01-07 03:34:31 +00001050 // List of module types allowed to use .Custom(...)
1051 // Additions to the list require careful review for proper license handling.
Colin Crossaa255532020-07-03 13:18:24 -07001052 switch reflect.TypeOf(mod).String() { // ctx.ModuleType(mod) doesn't work: aidl_interface creates phony without type
Bob Badourb4999222021-01-07 03:34:31 +00001053 case "*aidl.aidlApi": // writes non-custom before adding .phony
1054 case "*aidl.aidlMapping": // writes non-custom before adding .phony
1055 case "*android.customModule": // appears in tests only
Dan Willemsen9fe14102021-07-13 21:52:04 -07001056 case "*android_sdk.sdkRepoHost": // doesn't go through base_rules
Bob Badourb4999222021-01-07 03:34:31 +00001057 case "*apex.apexBundle": // license properties written
1058 case "*bpf.bpf": // license properties written (both for module and objs)
Neill Kapron41efab72024-07-31 22:17:36 +00001059 case "*libbpf_prog.libbpfProg": // license properties written (both for module and objs)
Bob Badourb4999222021-01-07 03:34:31 +00001060 case "*genrule.Module": // writes non-custom before adding .phony
1061 case "*java.SystemModules": // doesn't go through base_rules
1062 case "*java.systemModulesImport": // doesn't go through base_rules
1063 case "*phony.phony": // license properties written
Nelson Lif3c70682023-12-20 02:37:52 +00001064 case "*phony.PhonyRule": // writes phony deps and acts like `.PHONY`
Bob Badourb4999222021-01-07 03:34:31 +00001065 case "*selinux.selinuxContextsModule": // license properties written
1066 case "*sysprop.syspropLibrary": // license properties written
Bill Yang3b3aac02024-09-05 09:22:09 +00001067 case "*vintf.vintfCompatibilityMatrixRule": // use case like phony
Bob Badourb4999222021-01-07 03:34:31 +00001068 default:
Bob Badour65ee90a2021-09-02 15:33:10 -07001069 if !ctx.Config().IsEnvFalse("ANDROID_REQUIRE_LICENSES") {
Bob Badourb4999222021-01-07 03:34:31 +00001070 return fmt.Errorf("custom make rules not allowed for %q (%q) module %q", ctx.ModuleType(mod), reflect.TypeOf(mod), ctx.ModuleName(mod))
1071 }
1072 }
Colin Cross0f86d182017-08-10 17:07:28 -07001073 data.Custom(w, name, prefix, blueprintDir, data)
1074 } else {
1075 WriteAndroidMkData(w, data)
1076 }
1077
Colin Crossd6fd0132023-11-06 13:54:06 -08001078 if !data.Entries.disabled() {
Yu Liu663e4502024-08-12 18:23:59 +00001079 if moduleInfoJSON, ok := OtherModuleProvider(ctx, mod, ModuleInfoJSONProvider); ok {
Colin Crossd6fd0132023-11-06 13:54:06 -08001080 *moduleInfoJSONs = append(*moduleInfoJSONs, moduleInfoJSON)
1081 }
1082 }
1083
Colin Cross0f86d182017-08-10 17:07:28 -07001084 return nil
1085}
1086
Jaewoong Jung7ef4a902020-11-16 12:50:29 -08001087// A support func for the deprecated AndroidMkDataProvider interface. Use AndroidMkEntryProvider
1088// instead.
Colin Cross0f86d182017-08-10 17:07:28 -07001089func WriteAndroidMkData(w io.Writer, data AndroidMkData) {
Colin Crossd6fd0132023-11-06 13:54:06 -08001090 if data.Entries.disabled() {
Colin Cross0f86d182017-08-10 17:07:28 -07001091 return
1092 }
1093
Jooyung Han2ed99d02020-06-24 23:26:26 +09001094 // write preamble via Entries
1095 data.Entries.footer = bytes.Buffer{}
1096 data.Entries.write(w)
Colin Cross0f86d182017-08-10 17:07:28 -07001097
Colin Crossca860ac2016-01-04 14:34:37 -08001098 for _, extra := range data.Extra {
Colin Cross27a4b052017-08-10 16:32:23 -07001099 extra(w, data.OutputFile.Path())
Dan Willemsen97750522016-02-09 17:43:51 -08001100 }
1101
Colin Cross53499412017-09-07 13:20:25 -07001102 fmt.Fprintln(w, "include "+data.Include)
Dan Willemsen218f6562015-07-08 18:13:11 -07001103}
Sasha Smundakb6d23052019-04-01 18:37:36 -07001104
Colin Crossd6fd0132023-11-06 13:54:06 -08001105func translateAndroidMkEntriesModule(ctx SingletonContext, w io.Writer, moduleInfoJSONs *[]*ModuleInfoJSON,
1106 mod blueprint.Module, provider AndroidMkEntriesProvider) error {
Cole Fausta963b942024-04-11 17:43:00 -07001107 if shouldSkipAndroidMkProcessing(ctx, mod.(Module).base()) {
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -07001108 return nil
Sasha Smundakb6d23052019-04-01 18:37:36 -07001109 }
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -07001110
Colin Crossd6fd0132023-11-06 13:54:06 -08001111 entriesList := provider.AndroidMkEntries()
LaMont Jonesb5099382024-01-10 23:42:36 +00001112 aconfigUpdateAndroidMkEntries(ctx, mod.(Module), &entriesList)
Colin Crossd6fd0132023-11-06 13:54:06 -08001113
Bob Badourb4999222021-01-07 03:34:31 +00001114 // Any new or special cases here need review to verify correct propagation of license information.
Colin Crossd6fd0132023-11-06 13:54:06 -08001115 for _, entries := range entriesList {
Colin Crossaa255532020-07-03 13:18:24 -07001116 entries.fillInEntries(ctx, mod)
Jiyong Park0b0e1b92019-12-03 13:24:29 +09001117 entries.write(w)
1118 }
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -07001119
Colin Crossd6fd0132023-11-06 13:54:06 -08001120 if len(entriesList) > 0 && !entriesList[0].disabled() {
Yu Liu663e4502024-08-12 18:23:59 +00001121 if moduleInfoJSON, ok := OtherModuleProvider(ctx, mod, ModuleInfoJSONProvider); ok {
Colin Crossd6fd0132023-11-06 13:54:06 -08001122 *moduleInfoJSONs = append(*moduleInfoJSONs, moduleInfoJSON)
1123 }
1124 }
1125
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -07001126 return nil
1127}
1128
Cole Fauste8a87832024-09-11 11:35:46 -07001129func ShouldSkipAndroidMkProcessing(ctx ConfigurableEvaluatorContext, module Module) bool {
Cole Fausta963b942024-04-11 17:43:00 -07001130 return shouldSkipAndroidMkProcessing(ctx, module.base())
Chih-Hung Hsieh80783772021-10-11 16:46:56 -07001131}
1132
Cole Fauste8a87832024-09-11 11:35:46 -07001133func shouldSkipAndroidMkProcessing(ctx ConfigurableEvaluatorContext, module *ModuleBase) bool {
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -07001134 if !module.commonProperties.NamespaceExportedToMake {
1135 // TODO(jeffrygaston) do we want to validate that there are no modules being
1136 // exported to Kati that depend on this module?
1137 return true
Sasha Smundakb6d23052019-04-01 18:37:36 -07001138 }
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -07001139
Dan Willemsendef7b5d2021-10-17 00:22:33 -07001140 // On Mac, only expose host darwin modules to Make, as that's all we claim to support.
1141 // In reality, some of them depend on device-built (Java) modules, so we can't disable all
1142 // device modules in Soong, but we can hide them from Make (and thus the build user interface)
1143 if runtime.GOOS == "darwin" && module.Os() != Darwin {
1144 return true
1145 }
1146
Dan Willemsen8528f4e2021-10-19 00:22:06 -07001147 // Only expose the primary Darwin target, as Make does not understand Darwin+Arm64
1148 if module.Os() == Darwin && module.Target().HostCross {
1149 return true
1150 }
1151
Cole Fausta963b942024-04-11 17:43:00 -07001152 return !module.Enabled(ctx) ||
Colin Crossa9c8c9f2020-12-16 10:20:23 -08001153 module.commonProperties.HideFromMake ||
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -07001154 // Make does not understand LinuxBionic
Colin Cross9a027be2022-06-24 18:45:58 -07001155 module.Os() == LinuxBionic ||
1156 // Make does not understand LinuxMusl, except when we are building with USE_HOST_MUSL=true
1157 // and all host binaries are LinuxMusl
1158 (module.Os() == LinuxMusl && module.Target().HostCross)
Sasha Smundakb6d23052019-04-01 18:37:36 -07001159}
Dan Shi31949122020-09-21 12:11:02 -07001160
Jaewoong Jung7ef4a902020-11-16 12:50:29 -08001161// A utility func to format LOCAL_TEST_DATA outputs. See the comments on DataPath to understand how
1162// to use this func.
Colin Cross5c1d5fb2023-11-15 12:39:40 -08001163func androidMkDataPaths(data []DataPath) []string {
Dan Shi31949122020-09-21 12:11:02 -07001164 var testFiles []string
1165 for _, d := range data {
1166 rel := d.SrcPath.Rel()
Colin Cross5c1d5fb2023-11-15 12:39:40 -08001167 if d.WithoutRel {
1168 rel = d.SrcPath.Base()
1169 }
Dan Shi31949122020-09-21 12:11:02 -07001170 path := d.SrcPath.String()
Jaewoong Jung7ef4a902020-11-16 12:50:29 -08001171 // LOCAL_TEST_DATA requires the rel portion of the path to be removed from the path.
Dan Shi31949122020-09-21 12:11:02 -07001172 if !strings.HasSuffix(path, rel) {
1173 panic(fmt.Errorf("path %q does not end with %q", path, rel))
1174 }
1175 path = strings.TrimSuffix(path, rel)
1176 testFileString := path + ":" + rel
1177 if len(d.RelativeInstallPath) > 0 {
1178 testFileString += ":" + d.RelativeInstallPath
1179 }
1180 testFiles = append(testFiles, testFileString)
1181 }
1182 return testFiles
1183}
Sasha Smundakdcb61292022-12-08 10:41:33 -08001184
1185// AndroidMkEmitAssignList emits the line
1186//
1187// VAR := ITEM ...
1188//
1189// Items are the elements to the given set of lists
1190// If all the passed lists are empty, no line will be emitted
1191func AndroidMkEmitAssignList(w io.Writer, varName string, lists ...[]string) {
1192 doPrint := false
1193 for _, l := range lists {
1194 if doPrint = len(l) > 0; doPrint {
1195 break
1196 }
1197 }
1198 if !doPrint {
1199 return
1200 }
1201 fmt.Fprint(w, varName, " :=")
1202 for _, l := range lists {
1203 for _, item := range l {
1204 fmt.Fprint(w, " ", item)
1205 }
1206 }
1207 fmt.Fprintln(w)
1208}
mrziwang18420972024-09-03 15:12:51 -07001209
1210type AndroidMkProviderInfo struct {
1211 PrimaryInfo AndroidMkInfo
1212 ExtraInfo []AndroidMkInfo
1213}
1214
1215type AndroidMkInfo struct {
1216 // Android.mk class string, e.g. EXECUTABLES, JAVA_LIBRARIES, ETC
1217 Class string
1218 // Optional suffix to append to the module name. Useful when a module wants to return multiple
1219 // AndroidMkEntries objects. For example, when a java_library returns an additional entry for
1220 // its hostdex sub-module, this SubName field is set to "-hostdex" so that it can have a
1221 // different name than the parent's.
1222 SubName string
1223 // If set, this value overrides the base module name. SubName is still appended.
1224 OverrideName string
1225 // Dist files to output
1226 DistFiles TaggedDistFiles
1227 // The output file for Kati to process and/or install. If absent, the module is skipped.
1228 OutputFile OptionalPath
1229 // If true, the module is skipped and does not appear on the final Android-<product name>.mk
1230 // file. Useful when a module needs to be skipped conditionally.
1231 Disabled bool
1232 // The postprocessing mk file to include, e.g. $(BUILD_SYSTEM)/soong_cc_rust_prebuilt.mk
1233 // If not set, $(BUILD_SYSTEM)/prebuilt.mk is used.
1234 Include string
1235 // Required modules that need to be built and included in the final build output when building
1236 // this module.
1237 Required []string
1238 // Required host modules that need to be built and included in the final build output when
1239 // building this module.
1240 Host_required []string
1241 // Required device modules that need to be built and included in the final build output when
1242 // building this module.
1243 Target_required []string
1244
1245 HeaderStrings []string
1246 FooterStrings []string
1247
1248 // A map that holds the up-to-date Make variable values. Can be accessed from tests.
1249 EntryMap map[string][]string
1250 // A list of EntryMap keys in insertion order. This serves a few purposes:
1251 // 1. Prevents churns. Golang map doesn't provide consistent iteration order, so without this,
1252 // the outputted Android-*.mk file may change even though there have been no content changes.
1253 // 2. Allows modules to refer to other variables, like LOCAL_BAR_VAR := $(LOCAL_FOO_VAR),
1254 // without worrying about the variables being mixed up in the actual mk file.
1255 // 3. Makes troubleshooting and spotting errors easier.
1256 EntryOrder []string
1257}
1258
Yu Liue70976d2024-10-15 20:45:35 +00001259type AndroidMkProviderInfoProducer interface {
1260 PrepareAndroidMKProviderInfo(config Config) *AndroidMkProviderInfo
1261}
1262
mrziwang18420972024-09-03 15:12:51 -07001263// TODO: rename it to AndroidMkEntriesProvider after AndroidMkEntriesProvider interface is gone.
1264var AndroidMkInfoProvider = blueprint.NewProvider[*AndroidMkProviderInfo]()
1265
1266func translateAndroidMkEntriesInfoModule(ctx SingletonContext, w io.Writer, moduleInfoJSONs *[]*ModuleInfoJSON,
1267 mod blueprint.Module, providerInfo *AndroidMkProviderInfo) error {
1268 if shouldSkipAndroidMkProcessing(ctx, mod.(Module).base()) {
1269 return nil
1270 }
1271
1272 // Deep copy the provider info since we need to modify the info later
1273 info := deepCopyAndroidMkProviderInfo(providerInfo)
1274
1275 aconfigUpdateAndroidMkInfos(ctx, mod.(Module), &info)
1276
1277 // Any new or special cases here need review to verify correct propagation of license information.
1278 info.PrimaryInfo.fillInEntries(ctx, mod)
1279 info.PrimaryInfo.write(w)
1280 if len(info.ExtraInfo) > 0 {
1281 for _, ei := range info.ExtraInfo {
1282 ei.fillInEntries(ctx, mod)
1283 ei.write(w)
1284 }
1285 }
1286
1287 if !info.PrimaryInfo.disabled() {
1288 if moduleInfoJSON, ok := OtherModuleProvider(ctx, mod, ModuleInfoJSONProvider); ok {
1289 *moduleInfoJSONs = append(*moduleInfoJSONs, moduleInfoJSON)
1290 }
1291 }
1292
1293 return nil
1294}
1295
1296// Utility funcs to manipulate Android.mk variable entries.
1297
1298// SetString sets a Make variable with the given name to the given value.
1299func (a *AndroidMkInfo) SetString(name, value string) {
1300 if _, ok := a.EntryMap[name]; !ok {
1301 a.EntryOrder = append(a.EntryOrder, name)
1302 }
1303 a.EntryMap[name] = []string{value}
1304}
1305
1306// SetPath sets a Make variable with the given name to the given path string.
1307func (a *AndroidMkInfo) SetPath(name string, path Path) {
1308 if _, ok := a.EntryMap[name]; !ok {
1309 a.EntryOrder = append(a.EntryOrder, name)
1310 }
1311 a.EntryMap[name] = []string{path.String()}
1312}
1313
1314// SetOptionalPath sets a Make variable with the given name to the given path string if it is valid.
1315// It is a no-op if the given path is invalid.
1316func (a *AndroidMkInfo) SetOptionalPath(name string, path OptionalPath) {
1317 if path.Valid() {
1318 a.SetPath(name, path.Path())
1319 }
1320}
1321
1322// AddPath appends the given path string to a Make variable with the given name.
1323func (a *AndroidMkInfo) AddPath(name string, path Path) {
1324 if _, ok := a.EntryMap[name]; !ok {
1325 a.EntryOrder = append(a.EntryOrder, name)
1326 }
1327 a.EntryMap[name] = append(a.EntryMap[name], path.String())
1328}
1329
1330// AddOptionalPath appends the given path string to a Make variable with the given name if it is
1331// valid. It is a no-op if the given path is invalid.
1332func (a *AndroidMkInfo) AddOptionalPath(name string, path OptionalPath) {
1333 if path.Valid() {
1334 a.AddPath(name, path.Path())
1335 }
1336}
1337
1338// SetPaths sets a Make variable with the given name to a slice of the given path strings.
1339func (a *AndroidMkInfo) SetPaths(name string, paths Paths) {
1340 if _, ok := a.EntryMap[name]; !ok {
1341 a.EntryOrder = append(a.EntryOrder, name)
1342 }
1343 a.EntryMap[name] = paths.Strings()
1344}
1345
1346// SetOptionalPaths sets a Make variable with the given name to a slice of the given path strings
1347// only if there are a non-zero amount of paths.
1348func (a *AndroidMkInfo) SetOptionalPaths(name string, paths Paths) {
1349 if len(paths) > 0 {
1350 a.SetPaths(name, paths)
1351 }
1352}
1353
1354// AddPaths appends the given path strings to a Make variable with the given name.
1355func (a *AndroidMkInfo) AddPaths(name string, paths Paths) {
1356 if _, ok := a.EntryMap[name]; !ok {
1357 a.EntryOrder = append(a.EntryOrder, name)
1358 }
1359 a.EntryMap[name] = append(a.EntryMap[name], paths.Strings()...)
1360}
1361
1362// SetBoolIfTrue sets a Make variable with the given name to true if the given flag is true.
1363// It is a no-op if the given flag is false.
1364func (a *AndroidMkInfo) SetBoolIfTrue(name string, flag bool) {
1365 if flag {
1366 if _, ok := a.EntryMap[name]; !ok {
1367 a.EntryOrder = append(a.EntryOrder, name)
1368 }
1369 a.EntryMap[name] = []string{"true"}
1370 }
1371}
1372
1373// SetBool sets a Make variable with the given name to if the given bool flag value.
1374func (a *AndroidMkInfo) SetBool(name string, flag bool) {
1375 if _, ok := a.EntryMap[name]; !ok {
1376 a.EntryOrder = append(a.EntryOrder, name)
1377 }
1378 if flag {
1379 a.EntryMap[name] = []string{"true"}
1380 } else {
1381 a.EntryMap[name] = []string{"false"}
1382 }
1383}
1384
1385// AddStrings appends the given strings to a Make variable with the given name.
1386func (a *AndroidMkInfo) AddStrings(name string, value ...string) {
1387 if len(value) == 0 {
1388 return
1389 }
1390 if _, ok := a.EntryMap[name]; !ok {
1391 a.EntryOrder = append(a.EntryOrder, name)
1392 }
1393 a.EntryMap[name] = append(a.EntryMap[name], value...)
1394}
1395
1396// AddCompatibilityTestSuites adds the supplied test suites to the EntryMap, with special handling
1397// for partial MTS and MCTS test suites.
1398func (a *AndroidMkInfo) AddCompatibilityTestSuites(suites ...string) {
1399 // M(C)TS supports a full test suite and partial per-module MTS test suites, with naming mts-${MODULE}.
1400 // To reduce repetition, if we find a partial M(C)TS test suite without an full M(C)TS test suite,
1401 // we add the full test suite to our list.
1402 if PrefixInList(suites, "mts-") && !InList("mts", suites) {
1403 suites = append(suites, "mts")
1404 }
1405 if PrefixInList(suites, "mcts-") && !InList("mcts", suites) {
1406 suites = append(suites, "mcts")
1407 }
1408 a.AddStrings("LOCAL_COMPATIBILITY_SUITE", suites...)
1409}
1410
1411func (a *AndroidMkInfo) fillInEntries(ctx fillInEntriesContext, mod blueprint.Module) {
1412 helperInfo := AndroidMkInfo{
1413 EntryMap: make(map[string][]string),
1414 }
1415
1416 amod := mod.(Module)
1417 base := amod.base()
1418 name := base.BaseModuleName()
1419 if a.OverrideName != "" {
1420 name = a.OverrideName
1421 }
1422
1423 if a.Include == "" {
1424 a.Include = "$(BUILD_PREBUILT)"
1425 }
1426 a.Required = append(a.Required, amod.RequiredModuleNames(ctx)...)
1427 a.Required = append(a.Required, amod.VintfFragmentModuleNames(ctx)...)
1428 a.Host_required = append(a.Host_required, amod.HostRequiredModuleNames()...)
1429 a.Target_required = append(a.Target_required, amod.TargetRequiredModuleNames()...)
1430
1431 for _, distString := range a.GetDistForGoals(ctx, mod) {
1432 a.HeaderStrings = append(a.HeaderStrings, distString)
1433 }
1434
Yu Liue70976d2024-10-15 20:45:35 +00001435 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 -07001436
1437 // Collect make variable assignment entries.
1438 helperInfo.SetString("LOCAL_PATH", ctx.ModuleDir(mod))
1439 helperInfo.SetString("LOCAL_MODULE", name+a.SubName)
1440 helperInfo.SetString("LOCAL_MODULE_CLASS", a.Class)
1441 helperInfo.SetString("LOCAL_PREBUILT_MODULE_FILE", a.OutputFile.String())
1442 helperInfo.AddStrings("LOCAL_REQUIRED_MODULES", a.Required...)
1443 helperInfo.AddStrings("LOCAL_HOST_REQUIRED_MODULES", a.Host_required...)
1444 helperInfo.AddStrings("LOCAL_TARGET_REQUIRED_MODULES", a.Target_required...)
1445 helperInfo.AddStrings("LOCAL_SOONG_MODULE_TYPE", ctx.ModuleType(amod))
1446
1447 // If the install rule was generated by Soong tell Make about it.
1448 info := OtherModuleProviderOrDefault(ctx, mod, InstallFilesProvider)
1449 if len(info.KatiInstalls) > 0 {
1450 // Assume the primary install file is last since it probably needs to depend on any other
1451 // installed files. If that is not the case we can add a method to specify the primary
1452 // installed file.
1453 helperInfo.SetPath("LOCAL_SOONG_INSTALLED_MODULE", info.KatiInstalls[len(info.KatiInstalls)-1].to)
1454 helperInfo.SetString("LOCAL_SOONG_INSTALL_PAIRS", info.KatiInstalls.BuiltInstalled())
1455 helperInfo.SetPaths("LOCAL_SOONG_INSTALL_SYMLINKS", info.KatiSymlinks.InstallPaths().Paths())
1456 } else {
1457 // Soong may not have generated the install rule also when `no_full_install: true`.
1458 // Mark this module as uninstallable in order to prevent Make from creating an
1459 // install rule there.
1460 helperInfo.SetBoolIfTrue("LOCAL_UNINSTALLABLE_MODULE", proptools.Bool(base.commonProperties.No_full_install))
1461 }
1462
Yu Liue70976d2024-10-15 20:45:35 +00001463 if info.UncheckedModule {
1464 helperInfo.SetBool("LOCAL_DONT_CHECK_MODULE", true)
1465 } else if info.CheckbuildTarget != nil {
1466 helperInfo.SetPath("LOCAL_CHECKED_MODULE", info.CheckbuildTarget)
1467 } else {
1468 helperInfo.SetOptionalPath("LOCAL_CHECKED_MODULE", a.OutputFile)
1469 }
1470
mrziwang18420972024-09-03 15:12:51 -07001471 if len(info.TestData) > 0 {
1472 helperInfo.AddStrings("LOCAL_TEST_DATA", androidMkDataPaths(info.TestData)...)
1473 }
1474
1475 if am, ok := mod.(ApexModule); ok {
1476 helperInfo.SetBoolIfTrue("LOCAL_NOT_AVAILABLE_FOR_PLATFORM", am.NotAvailableForPlatform())
1477 }
1478
1479 archStr := base.Arch().ArchType.String()
1480 host := false
1481 switch base.Os().Class {
1482 case Host:
1483 if base.Target().HostCross {
1484 // Make cannot identify LOCAL_MODULE_HOST_CROSS_ARCH:= common.
1485 if base.Arch().ArchType != Common {
1486 helperInfo.SetString("LOCAL_MODULE_HOST_CROSS_ARCH", archStr)
1487 }
1488 } else {
1489 // Make cannot identify LOCAL_MODULE_HOST_ARCH:= common.
1490 if base.Arch().ArchType != Common {
1491 helperInfo.SetString("LOCAL_MODULE_HOST_ARCH", archStr)
1492 }
1493 }
1494 host = true
1495 case Device:
1496 // Make cannot identify LOCAL_MODULE_TARGET_ARCH:= common.
1497 if base.Arch().ArchType != Common {
1498 if base.Target().NativeBridge {
1499 hostArchStr := base.Target().NativeBridgeHostArchName
1500 if hostArchStr != "" {
1501 helperInfo.SetString("LOCAL_MODULE_TARGET_ARCH", hostArchStr)
1502 }
1503 } else {
1504 helperInfo.SetString("LOCAL_MODULE_TARGET_ARCH", archStr)
1505 }
1506 }
1507
1508 if !base.InVendorRamdisk() {
1509 helperInfo.AddPaths("LOCAL_FULL_INIT_RC", info.InitRcPaths)
1510 }
1511 if len(info.VintfFragmentsPaths) > 0 {
1512 helperInfo.AddPaths("LOCAL_FULL_VINTF_FRAGMENTS", info.VintfFragmentsPaths)
1513 }
1514 helperInfo.SetBoolIfTrue("LOCAL_PROPRIETARY_MODULE", Bool(base.commonProperties.Proprietary))
1515 if Bool(base.commonProperties.Vendor) || Bool(base.commonProperties.Soc_specific) {
1516 helperInfo.SetString("LOCAL_VENDOR_MODULE", "true")
1517 }
1518 helperInfo.SetBoolIfTrue("LOCAL_ODM_MODULE", Bool(base.commonProperties.Device_specific))
1519 helperInfo.SetBoolIfTrue("LOCAL_PRODUCT_MODULE", Bool(base.commonProperties.Product_specific))
1520 helperInfo.SetBoolIfTrue("LOCAL_SYSTEM_EXT_MODULE", Bool(base.commonProperties.System_ext_specific))
1521 if base.commonProperties.Owner != nil {
1522 helperInfo.SetString("LOCAL_MODULE_OWNER", *base.commonProperties.Owner)
1523 }
1524 }
1525
1526 if host {
1527 makeOs := base.Os().String()
1528 if base.Os() == Linux || base.Os() == LinuxBionic || base.Os() == LinuxMusl {
1529 makeOs = "linux"
1530 }
1531 helperInfo.SetString("LOCAL_MODULE_HOST_OS", makeOs)
1532 helperInfo.SetString("LOCAL_IS_HOST_MODULE", "true")
1533 }
1534
mrziwang18420972024-09-03 15:12:51 -07001535 if licenseMetadata, ok := OtherModuleProvider(ctx, mod, LicenseMetadataProvider); ok {
1536 helperInfo.SetPath("LOCAL_SOONG_LICENSE_METADATA", licenseMetadata.LicenseMetadataPath)
1537 }
1538
1539 if _, ok := OtherModuleProvider(ctx, mod, ModuleInfoJSONProvider); ok {
1540 helperInfo.SetBool("LOCAL_SOONG_MODULE_INFO_JSON", true)
1541 }
1542
1543 a.mergeEntries(&helperInfo)
1544
1545 // Write to footer.
1546 a.FooterStrings = append([]string{"include " + a.Include}, a.FooterStrings...)
1547}
1548
1549// This method merges the entries to helperInfo, then replaces a's EntryMap and
1550// EntryOrder with helperInfo's
1551func (a *AndroidMkInfo) mergeEntries(helperInfo *AndroidMkInfo) {
1552 for _, extraEntry := range a.EntryOrder {
1553 if v, ok := helperInfo.EntryMap[extraEntry]; ok {
1554 v = append(v, a.EntryMap[extraEntry]...)
1555 } else {
1556 helperInfo.EntryMap[extraEntry] = a.EntryMap[extraEntry]
1557 helperInfo.EntryOrder = append(helperInfo.EntryOrder, extraEntry)
1558 }
1559 }
1560 a.EntryOrder = helperInfo.EntryOrder
1561 a.EntryMap = helperInfo.EntryMap
1562}
1563
1564func (a *AndroidMkInfo) disabled() bool {
1565 return a.Disabled || !a.OutputFile.Valid()
1566}
1567
1568// write flushes the AndroidMkEntries's in-struct data populated by AndroidMkEntries into the
1569// given Writer object.
1570func (a *AndroidMkInfo) write(w io.Writer) {
1571 if a.disabled() {
1572 return
1573 }
1574
Yu Liue70976d2024-10-15 20:45:35 +00001575 combinedHeaderString := strings.Join(a.HeaderStrings, "\n") + "\n"
1576 combinedFooterString := strings.Join(a.FooterStrings, "\n") + "\n"
mrziwang18420972024-09-03 15:12:51 -07001577 w.Write([]byte(combinedHeaderString))
1578 for _, name := range a.EntryOrder {
1579 AndroidMkEmitAssignList(w, name, a.EntryMap[name])
1580 }
1581 w.Write([]byte(combinedFooterString))
1582}
1583
1584// Compute the list of Make strings to declare phony goals and dist-for-goals
1585// calls from the module's dist and dists properties.
1586func (a *AndroidMkInfo) GetDistForGoals(ctx fillInEntriesContext, mod blueprint.Module) []string {
1587 distContributions := a.getDistContributions(ctx, mod)
1588 if distContributions == nil {
1589 return nil
1590 }
1591
1592 return generateDistContributionsForMake(distContributions)
1593}
1594
1595// Compute the contributions that the module makes to the dist.
1596func (a *AndroidMkInfo) getDistContributions(ctx fillInEntriesContext, mod blueprint.Module) *distContributions {
1597 amod := mod.(Module).base()
1598 name := amod.BaseModuleName()
1599
1600 // Collate the set of associated tag/paths available for copying to the dist.
1601 // Start with an empty (nil) set.
1602 var availableTaggedDists TaggedDistFiles
1603
1604 // Then merge in any that are provided explicitly by the module.
1605 if a.DistFiles != nil {
1606 // Merge the DistFiles into the set.
1607 availableTaggedDists = availableTaggedDists.merge(a.DistFiles)
1608 }
1609
1610 // If no paths have been provided for the DefaultDistTag and the output file is
1611 // valid then add that as the default dist path.
1612 if _, ok := availableTaggedDists[DefaultDistTag]; !ok && a.OutputFile.Valid() {
1613 availableTaggedDists = availableTaggedDists.addPathsForTag(DefaultDistTag, a.OutputFile.Path())
1614 }
1615
1616 info := OtherModuleProviderOrDefault(ctx, mod, InstallFilesProvider)
1617 // If the distFiles created by GenerateTaggedDistFiles contains paths for the
1618 // DefaultDistTag then that takes priority so delete any existing paths.
1619 if _, ok := info.DistFiles[DefaultDistTag]; ok {
1620 delete(availableTaggedDists, DefaultDistTag)
1621 }
1622
1623 // Finally, merge the distFiles created by GenerateTaggedDistFiles.
1624 availableTaggedDists = availableTaggedDists.merge(info.DistFiles)
1625
1626 if len(availableTaggedDists) == 0 {
1627 // Nothing dist-able for this module.
1628 return nil
1629 }
1630
1631 // Collate the contributions this module makes to the dist.
1632 distContributions := &distContributions{}
1633
1634 if !exemptFromRequiredApplicableLicensesProperty(mod.(Module)) {
1635 distContributions.licenseMetadataFile = info.LicenseMetadataFile
1636 }
1637
1638 // Iterate over this module's dist structs, merged from the dist and dists properties.
1639 for _, dist := range amod.Dists() {
1640 // Get the list of goals this dist should be enabled for. e.g. sdk, droidcore
1641 goals := strings.Join(dist.Targets, " ")
1642
1643 // Get the tag representing the output files to be dist'd. e.g. ".jar", ".proguard_map"
1644 var tag string
1645 if dist.Tag == nil {
1646 // If the dist struct does not specify a tag, use the default output files tag.
1647 tag = DefaultDistTag
1648 } else {
1649 tag = *dist.Tag
1650 }
1651
1652 // Get the paths of the output files to be dist'd, represented by the tag.
1653 // Can be an empty list.
1654 tagPaths := availableTaggedDists[tag]
1655 if len(tagPaths) == 0 {
1656 // Nothing to dist for this tag, continue to the next dist.
1657 continue
1658 }
1659
1660 if len(tagPaths) > 1 && (dist.Dest != nil || dist.Suffix != nil) {
1661 errorMessage := "%s: Cannot apply dest/suffix for more than one dist " +
1662 "file for %q goals tag %q in module %s. The list of dist files, " +
1663 "which should have a single element, is:\n%s"
1664 panic(fmt.Errorf(errorMessage, mod, goals, tag, name, tagPaths))
1665 }
1666
1667 copiesForGoals := distContributions.getCopiesForGoals(goals)
1668
1669 // Iterate over each path adding a copy instruction to copiesForGoals
1670 for _, path := range tagPaths {
1671 // It's possible that the Path is nil from errant modules. Be defensive here.
1672 if path == nil {
1673 tagName := "default" // for error message readability
1674 if dist.Tag != nil {
1675 tagName = *dist.Tag
1676 }
1677 panic(fmt.Errorf("Dist file should not be nil for the %s tag in %s", tagName, name))
1678 }
1679
1680 dest := filepath.Base(path.String())
1681
1682 if dist.Dest != nil {
1683 var err error
1684 if dest, err = validateSafePath(*dist.Dest); err != nil {
1685 // This was checked in ModuleBase.GenerateBuildActions
1686 panic(err)
1687 }
1688 }
1689
1690 ext := filepath.Ext(dest)
1691 suffix := ""
1692 if dist.Suffix != nil {
1693 suffix = *dist.Suffix
1694 }
1695
1696 productString := ""
1697 if dist.Append_artifact_with_product != nil && *dist.Append_artifact_with_product {
1698 productString = fmt.Sprintf("_%s", ctx.Config().DeviceProduct())
1699 }
1700
1701 if suffix != "" || productString != "" {
1702 dest = strings.TrimSuffix(dest, ext) + suffix + productString + ext
1703 }
1704
1705 if dist.Dir != nil {
1706 var err error
1707 if dest, err = validateSafePath(*dist.Dir, dest); err != nil {
1708 // This was checked in ModuleBase.GenerateBuildActions
1709 panic(err)
1710 }
1711 }
1712
1713 copiesForGoals.addCopyInstruction(path, dest)
1714 }
1715 }
1716
1717 return distContributions
1718}
1719
1720func deepCopyAndroidMkProviderInfo(providerInfo *AndroidMkProviderInfo) AndroidMkProviderInfo {
1721 info := AndroidMkProviderInfo{
1722 PrimaryInfo: deepCopyAndroidMkInfo(&providerInfo.PrimaryInfo),
1723 }
1724 if len(providerInfo.ExtraInfo) > 0 {
1725 for _, i := range providerInfo.ExtraInfo {
1726 info.ExtraInfo = append(info.ExtraInfo, deepCopyAndroidMkInfo(&i))
1727 }
1728 }
1729 return info
1730}
1731
1732func deepCopyAndroidMkInfo(mkinfo *AndroidMkInfo) AndroidMkInfo {
1733 info := AndroidMkInfo{
1734 Class: mkinfo.Class,
1735 SubName: mkinfo.SubName,
1736 OverrideName: mkinfo.OverrideName,
1737 // There is no modification on DistFiles or OutputFile, so no need to
1738 // make their deep copy.
1739 DistFiles: mkinfo.DistFiles,
1740 OutputFile: mkinfo.OutputFile,
1741 Disabled: mkinfo.Disabled,
1742 Include: mkinfo.Include,
1743 Required: deepCopyStringSlice(mkinfo.Required),
1744 Host_required: deepCopyStringSlice(mkinfo.Host_required),
1745 Target_required: deepCopyStringSlice(mkinfo.Target_required),
1746 HeaderStrings: deepCopyStringSlice(mkinfo.HeaderStrings),
1747 FooterStrings: deepCopyStringSlice(mkinfo.FooterStrings),
1748 EntryOrder: deepCopyStringSlice(mkinfo.EntryOrder),
1749 }
1750 info.EntryMap = make(map[string][]string)
1751 for k, v := range mkinfo.EntryMap {
1752 info.EntryMap[k] = deepCopyStringSlice(v)
1753 }
1754
1755 return info
1756}
1757
1758func deepCopyStringSlice(original []string) []string {
1759 result := make([]string, len(original))
1760 copy(result, original)
1761 return result
1762}