blob: db838f0d3367609fb4339d3ca6645537abc194fc [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
Jihoon Kang593171e2025-02-05 01:54:45 +0000336func (d *distCopy) String() string {
337 if len(d.dest) == 0 {
338 return d.from.String()
339 }
340 return fmt.Sprintf("%s:%s", d.from.String(), d.dest)
341}
342
343type distCopies []distCopy
344
345func (d *distCopies) Strings() (ret []string) {
346 if d == nil {
347 return
348 }
349 for _, dist := range *d {
350 ret = append(ret, dist.String())
351 }
352 return
353}
354
Paul Duffin8b0349c2020-11-26 14:33:21 +0000355// Compute the contributions that the module makes to the dist.
356func (a *AndroidMkEntries) getDistContributions(mod blueprint.Module) *distContributions {
Jingwen Chen40fd90a2020-06-15 05:24:19 +0000357 amod := mod.(Module).base()
358 name := amod.BaseModuleName()
359
Paul Duffin74f05592020-11-25 16:37:46 +0000360 // Collate the set of associated tag/paths available for copying to the dist.
361 // Start with an empty (nil) set.
Jingwen Chen7b27ca72020-07-24 09:13:49 +0000362 var availableTaggedDists TaggedDistFiles
Jingwen Chen40fd90a2020-06-15 05:24:19 +0000363
Paul Duffin74f05592020-11-25 16:37:46 +0000364 // Then merge in any that are provided explicitly by the module.
Jingwen Chen84811862020-07-21 11:32:19 +0000365 if a.DistFiles != nil {
Paul Duffin74f05592020-11-25 16:37:46 +0000366 // Merge the DistFiles into the set.
367 availableTaggedDists = availableTaggedDists.merge(a.DistFiles)
368 }
369
370 // If no paths have been provided for the DefaultDistTag and the output file is
371 // valid then add that as the default dist path.
372 if _, ok := availableTaggedDists[DefaultDistTag]; !ok && a.OutputFile.Valid() {
373 availableTaggedDists = availableTaggedDists.addPathsForTag(DefaultDistTag, a.OutputFile.Path())
374 }
375
Yu Liuec810542024-08-26 18:09:15 +0000376 info := OtherModuleProviderOrDefault(a.entryContext, mod, InstallFilesProvider)
Paul Duffinaf970a22020-11-23 23:32:56 +0000377 // If the distFiles created by GenerateTaggedDistFiles contains paths for the
378 // DefaultDistTag then that takes priority so delete any existing paths.
Yu Liuec810542024-08-26 18:09:15 +0000379 if _, ok := info.DistFiles[DefaultDistTag]; ok {
Paul Duffinaf970a22020-11-23 23:32:56 +0000380 delete(availableTaggedDists, DefaultDistTag)
381 }
382
383 // Finally, merge the distFiles created by GenerateTaggedDistFiles.
Yu Liuec810542024-08-26 18:09:15 +0000384 availableTaggedDists = availableTaggedDists.merge(info.DistFiles)
Paul Duffinaf970a22020-11-23 23:32:56 +0000385
Paul Duffin74f05592020-11-25 16:37:46 +0000386 if len(availableTaggedDists) == 0 {
Jingwen Chen7b27ca72020-07-24 09:13:49 +0000387 // Nothing dist-able for this module.
388 return nil
Jingwen Chen40fd90a2020-06-15 05:24:19 +0000389 }
390
Paul Duffin8b0349c2020-11-26 14:33:21 +0000391 // Collate the contributions this module makes to the dist.
392 distContributions := &distContributions{}
393
Bob Badour4660a982022-09-12 16:06:03 -0700394 if !exemptFromRequiredApplicableLicensesProperty(mod.(Module)) {
Yu Liuec810542024-08-26 18:09:15 +0000395 distContributions.licenseMetadataFile = info.LicenseMetadataFile
Bob Badour4660a982022-09-12 16:06:03 -0700396 }
Bob Badour51804382022-04-13 11:27:19 -0700397
Jingwen Chen40fd90a2020-06-15 05:24:19 +0000398 // Iterate over this module's dist structs, merged from the dist and dists properties.
399 for _, dist := range amod.Dists() {
400 // Get the list of goals this dist should be enabled for. e.g. sdk, droidcore
401 goals := strings.Join(dist.Targets, " ")
402
403 // Get the tag representing the output files to be dist'd. e.g. ".jar", ".proguard_map"
404 var tag string
405 if dist.Tag == nil {
406 // If the dist struct does not specify a tag, use the default output files tag.
Paul Duffin74f05592020-11-25 16:37:46 +0000407 tag = DefaultDistTag
Jingwen Chen40fd90a2020-06-15 05:24:19 +0000408 } else {
409 tag = *dist.Tag
410 }
411
412 // Get the paths of the output files to be dist'd, represented by the tag.
413 // Can be an empty list.
414 tagPaths := availableTaggedDists[tag]
415 if len(tagPaths) == 0 {
416 // Nothing to dist for this tag, continue to the next dist.
417 continue
418 }
419
420 if len(tagPaths) > 1 && (dist.Dest != nil || dist.Suffix != nil) {
Paul Duffin74f05592020-11-25 16:37:46 +0000421 errorMessage := "%s: Cannot apply dest/suffix for more than one dist " +
422 "file for %q goals tag %q in module %s. The list of dist files, " +
Jingwen Chen40fd90a2020-06-15 05:24:19 +0000423 "which should have a single element, is:\n%s"
Paul Duffin74f05592020-11-25 16:37:46 +0000424 panic(fmt.Errorf(errorMessage, mod, goals, tag, name, tagPaths))
Jingwen Chen40fd90a2020-06-15 05:24:19 +0000425 }
426
Paul Duffin8b0349c2020-11-26 14:33:21 +0000427 copiesForGoals := distContributions.getCopiesForGoals(goals)
Jingwen Chen40fd90a2020-06-15 05:24:19 +0000428
Paul Duffin8b0349c2020-11-26 14:33:21 +0000429 // Iterate over each path adding a copy instruction to copiesForGoals
Jingwen Chen40fd90a2020-06-15 05:24:19 +0000430 for _, path := range tagPaths {
431 // It's possible that the Path is nil from errant modules. Be defensive here.
432 if path == nil {
433 tagName := "default" // for error message readability
434 if dist.Tag != nil {
435 tagName = *dist.Tag
436 }
437 panic(fmt.Errorf("Dist file should not be nil for the %s tag in %s", tagName, name))
438 }
439
440 dest := filepath.Base(path.String())
441
442 if dist.Dest != nil {
443 var err error
444 if dest, err = validateSafePath(*dist.Dest); err != nil {
445 // This was checked in ModuleBase.GenerateBuildActions
446 panic(err)
447 }
448 }
449
Trevor Radcliffe90727f42022-03-21 19:34:02 +0000450 ext := filepath.Ext(dest)
451 suffix := ""
Jingwen Chen40fd90a2020-06-15 05:24:19 +0000452 if dist.Suffix != nil {
Trevor Radcliffe90727f42022-03-21 19:34:02 +0000453 suffix = *dist.Suffix
454 }
455
456 productString := ""
457 if dist.Append_artifact_with_product != nil && *dist.Append_artifact_with_product {
458 productString = fmt.Sprintf("_%s", a.entryContext.Config().DeviceProduct())
459 }
460
461 if suffix != "" || productString != "" {
462 dest = strings.TrimSuffix(dest, ext) + suffix + productString + ext
Jingwen Chen40fd90a2020-06-15 05:24:19 +0000463 }
464
465 if dist.Dir != nil {
466 var err error
467 if dest, err = validateSafePath(*dist.Dir, dest); err != nil {
468 // This was checked in ModuleBase.GenerateBuildActions
469 panic(err)
470 }
471 }
472
Paul Duffin8b0349c2020-11-26 14:33:21 +0000473 copiesForGoals.addCopyInstruction(path, dest)
474 }
475 }
476
477 return distContributions
478}
479
480// generateDistContributionsForMake generates make rules that will generate the
481// dist according to the instructions in the supplied distContribution.
482func generateDistContributionsForMake(distContributions *distContributions) []string {
483 var ret []string
484 for _, d := range distContributions.copiesForGoals {
Yu Liue70976d2024-10-15 20:45:35 +0000485 ret = append(ret, fmt.Sprintf(".PHONY: %s", d.goals))
Paul Duffin8b0349c2020-11-26 14:33:21 +0000486 // Create dist-for-goals calls for each of the copy instructions.
487 for _, c := range d.copies {
Bob Badour4660a982022-09-12 16:06:03 -0700488 if distContributions.licenseMetadataFile != nil {
489 ret = append(
490 ret,
Yu Liue70976d2024-10-15 20:45:35 +0000491 fmt.Sprintf("$(if $(strip $(ALL_TARGETS.%s.META_LIC)),,$(eval ALL_TARGETS.%s.META_LIC := %s))",
Bob Badour4660a982022-09-12 16:06:03 -0700492 c.from.String(), c.from.String(), distContributions.licenseMetadataFile.String()))
493 }
Bob Badour51804382022-04-13 11:27:19 -0700494 ret = append(
495 ret,
Yu Liue70976d2024-10-15 20:45:35 +0000496 fmt.Sprintf("$(call dist-for-goals,%s,%s:%s)", d.goals, c.from.String(), c.dest))
Jingwen Chen40fd90a2020-06-15 05:24:19 +0000497 }
498 }
499
500 return ret
501}
502
Paul Duffin8b0349c2020-11-26 14:33:21 +0000503// Compute the list of Make strings to declare phony goals and dist-for-goals
504// calls from the module's dist and dists properties.
505func (a *AndroidMkEntries) GetDistForGoals(mod blueprint.Module) []string {
506 distContributions := a.getDistContributions(mod)
507 if distContributions == nil {
508 return nil
509 }
510
511 return generateDistContributionsForMake(distContributions)
512}
513
Jaewoong Jung7ef4a902020-11-16 12:50:29 -0800514// fillInEntries goes through the common variable processing and calls the extra data funcs to
515// generate and fill in AndroidMkEntries's in-struct data, ready to be flushed to a file.
Colin Crossaa255532020-07-03 13:18:24 -0700516type fillInEntriesContext interface {
517 ModuleDir(module blueprint.Module) string
Cole Faust39aabe92023-02-23 16:57:43 -0800518 ModuleSubDir(module blueprint.Module) string
Colin Crossaa255532020-07-03 13:18:24 -0700519 Config() Config
Yu Liu663e4502024-08-12 18:23:59 +0000520 otherModuleProvider(module blueprint.Module, provider blueprint.AnyProviderKey) (any, bool)
Sasha Smundak5c4729d2022-12-01 10:49:23 -0800521 ModuleType(module blueprint.Module) string
Cole Faust43ddd082024-06-17 12:32:40 -0700522 OtherModulePropertyErrorf(module Module, property string, fmt string, args ...interface{})
Cole Faust4e2bf9f2024-09-11 13:26:20 -0700523 HasMutatorFinished(mutatorName string) bool
Colin Crossaa255532020-07-03 13:18:24 -0700524}
525
526func (a *AndroidMkEntries) fillInEntries(ctx fillInEntriesContext, mod blueprint.Module) {
Trevor Radcliffe90727f42022-03-21 19:34:02 +0000527 a.entryContext = ctx
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700528 a.EntryMap = make(map[string][]string)
Colin Crossf1f763a2021-10-21 16:14:19 -0700529 amod := mod.(Module)
530 base := amod.base()
531 name := base.BaseModuleName()
Colin Cross0477b422020-10-13 18:43:54 -0700532 if a.OverrideName != "" {
533 name = a.OverrideName
534 }
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700535
536 if a.Include == "" {
537 a.Include = "$(BUILD_PREBUILT)"
538 }
Cole Faust43ddd082024-06-17 12:32:40 -0700539 a.Required = append(a.Required, amod.RequiredModuleNames(ctx)...)
Kiyoung Kim04b64fc2024-08-19 11:25:30 +0900540 a.Required = append(a.Required, amod.VintfFragmentModuleNames(ctx)...)
Colin Crossf1f763a2021-10-21 16:14:19 -0700541 a.Host_required = append(a.Host_required, amod.HostRequiredModuleNames()...)
542 a.Target_required = append(a.Target_required, amod.TargetRequiredModuleNames()...)
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700543
Jingwen Chen40fd90a2020-06-15 05:24:19 +0000544 for _, distString := range a.GetDistForGoals(mod) {
Yu Liue70976d2024-10-15 20:45:35 +0000545 fmt.Fprintln(&a.header, distString)
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700546 }
547
Cole Faust39aabe92023-02-23 16:57:43 -0800548 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 -0700549
550 // Collect make variable assignment entries.
Colin Crossaa255532020-07-03 13:18:24 -0700551 a.SetString("LOCAL_PATH", ctx.ModuleDir(mod))
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700552 a.SetString("LOCAL_MODULE", name+a.SubName)
553 a.SetString("LOCAL_MODULE_CLASS", a.Class)
554 a.SetString("LOCAL_PREBUILT_MODULE_FILE", a.OutputFile.String())
555 a.AddStrings("LOCAL_REQUIRED_MODULES", a.Required...)
556 a.AddStrings("LOCAL_HOST_REQUIRED_MODULES", a.Host_required...)
557 a.AddStrings("LOCAL_TARGET_REQUIRED_MODULES", a.Target_required...)
Wei Li598f92d2023-01-04 17:12:24 -0800558 a.AddStrings("LOCAL_SOONG_MODULE_TYPE", ctx.ModuleType(amod))
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700559
Colin Cross6301c3c2021-09-28 17:40:21 -0700560 // If the install rule was generated by Soong tell Make about it.
Yu Liud46e5ae2024-08-15 18:46:17 +0000561 info := OtherModuleProviderOrDefault(ctx, mod, InstallFilesProvider)
562 if len(info.KatiInstalls) > 0 {
Colin Cross6301c3c2021-09-28 17:40:21 -0700563 // Assume the primary install file is last since it probably needs to depend on any other
564 // installed files. If that is not the case we can add a method to specify the primary
565 // installed file.
Yu Liud46e5ae2024-08-15 18:46:17 +0000566 a.SetPath("LOCAL_SOONG_INSTALLED_MODULE", info.KatiInstalls[len(info.KatiInstalls)-1].to)
567 a.SetString("LOCAL_SOONG_INSTALL_PAIRS", info.KatiInstalls.BuiltInstalled())
568 a.SetPaths("LOCAL_SOONG_INSTALL_SYMLINKS", info.KatiSymlinks.InstallPaths().Paths())
Jiyong Park3f627e62024-05-01 16:14:38 +0900569 } else {
570 // Soong may not have generated the install rule also when `no_full_install: true`.
571 // Mark this module as uninstallable in order to prevent Make from creating an
572 // install rule there.
573 a.SetBoolIfTrue("LOCAL_UNINSTALLABLE_MODULE", proptools.Bool(base.commonProperties.No_full_install))
Colin Cross6301c3c2021-09-28 17:40:21 -0700574 }
575
Colin Crossa6182ab2024-08-21 10:47:44 -0700576 if info.UncheckedModule {
577 a.SetBool("LOCAL_DONT_CHECK_MODULE", true)
578 } else if info.CheckbuildTarget != nil {
579 a.SetPath("LOCAL_CHECKED_MODULE", info.CheckbuildTarget)
580 } else {
581 a.SetOptionalPath("LOCAL_CHECKED_MODULE", a.OutputFile)
582 }
583
Yu Liud46e5ae2024-08-15 18:46:17 +0000584 if len(info.TestData) > 0 {
585 a.AddStrings("LOCAL_TEST_DATA", androidMkDataPaths(info.TestData)...)
Colin Cross5c1d5fb2023-11-15 12:39:40 -0800586 }
587
Jiyong Park89e850a2020-04-07 16:37:39 +0900588 if am, ok := mod.(ApexModule); ok {
589 a.SetBoolIfTrue("LOCAL_NOT_AVAILABLE_FOR_PLATFORM", am.NotAvailableForPlatform())
590 }
591
Colin Crossf1f763a2021-10-21 16:14:19 -0700592 archStr := base.Arch().ArchType.String()
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700593 host := false
Colin Crossf1f763a2021-10-21 16:14:19 -0700594 switch base.Os().Class {
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700595 case Host:
Colin Crossf1f763a2021-10-21 16:14:19 -0700596 if base.Target().HostCross {
Jiyong Park1613e552020-09-14 19:43:17 +0900597 // Make cannot identify LOCAL_MODULE_HOST_CROSS_ARCH:= common.
Colin Crossf1f763a2021-10-21 16:14:19 -0700598 if base.Arch().ArchType != Common {
Jiyong Park1613e552020-09-14 19:43:17 +0900599 a.SetString("LOCAL_MODULE_HOST_CROSS_ARCH", archStr)
600 }
601 } else {
602 // Make cannot identify LOCAL_MODULE_HOST_ARCH:= common.
Colin Crossf1f763a2021-10-21 16:14:19 -0700603 if base.Arch().ArchType != Common {
Jiyong Park1613e552020-09-14 19:43:17 +0900604 a.SetString("LOCAL_MODULE_HOST_ARCH", archStr)
605 }
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700606 }
607 host = true
608 case Device:
609 // Make cannot identify LOCAL_MODULE_TARGET_ARCH:= common.
Colin Crossf1f763a2021-10-21 16:14:19 -0700610 if base.Arch().ArchType != Common {
611 if base.Target().NativeBridge {
612 hostArchStr := base.Target().NativeBridgeHostArchName
dimitry1f33e402019-03-26 12:39:31 +0100613 if hostArchStr != "" {
614 a.SetString("LOCAL_MODULE_TARGET_ARCH", hostArchStr)
615 }
616 } else {
617 a.SetString("LOCAL_MODULE_TARGET_ARCH", archStr)
618 }
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700619 }
620
Kelvin Zhang46977252022-04-13 16:41:34 -0700621 if !base.InVendorRamdisk() {
Yu Liu82a6d142024-08-27 19:02:29 +0000622 a.AddPaths("LOCAL_FULL_INIT_RC", info.InitRcPaths)
Yifan Hong919dae12020-12-02 18:55:06 -0800623 }
Yu Liu82a6d142024-08-27 19:02:29 +0000624 if len(info.VintfFragmentsPaths) > 0 {
625 a.AddPaths("LOCAL_FULL_VINTF_FRAGMENTS", info.VintfFragmentsPaths)
Liz Kammer7b3dc8a2021-04-16 16:41:59 -0400626 }
Colin Crossf1f763a2021-10-21 16:14:19 -0700627 a.SetBoolIfTrue("LOCAL_PROPRIETARY_MODULE", Bool(base.commonProperties.Proprietary))
628 if Bool(base.commonProperties.Vendor) || Bool(base.commonProperties.Soc_specific) {
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700629 a.SetString("LOCAL_VENDOR_MODULE", "true")
630 }
Colin Crossf1f763a2021-10-21 16:14:19 -0700631 a.SetBoolIfTrue("LOCAL_ODM_MODULE", Bool(base.commonProperties.Device_specific))
632 a.SetBoolIfTrue("LOCAL_PRODUCT_MODULE", Bool(base.commonProperties.Product_specific))
633 a.SetBoolIfTrue("LOCAL_SYSTEM_EXT_MODULE", Bool(base.commonProperties.System_ext_specific))
634 if base.commonProperties.Owner != nil {
635 a.SetString("LOCAL_MODULE_OWNER", *base.commonProperties.Owner)
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700636 }
637 }
638
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700639 if host {
Colin Crossf1f763a2021-10-21 16:14:19 -0700640 makeOs := base.Os().String()
641 if base.Os() == Linux || base.Os() == LinuxBionic || base.Os() == LinuxMusl {
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700642 makeOs = "linux"
643 }
644 a.SetString("LOCAL_MODULE_HOST_OS", makeOs)
645 a.SetString("LOCAL_IS_HOST_MODULE", "true")
646 }
647
648 prefix := ""
Colin Crossf1f763a2021-10-21 16:14:19 -0700649 if base.ArchSpecific() {
650 switch base.Os().Class {
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700651 case Host:
Colin Crossf1f763a2021-10-21 16:14:19 -0700652 if base.Target().HostCross {
Jiyong Park1613e552020-09-14 19:43:17 +0900653 prefix = "HOST_CROSS_"
654 } else {
655 prefix = "HOST_"
656 }
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700657 case Device:
658 prefix = "TARGET_"
659
660 }
661
Colin Crossf1f763a2021-10-21 16:14:19 -0700662 if base.Arch().ArchType != ctx.Config().Targets[base.Os()][0].Arch.ArchType {
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700663 prefix = "2ND_" + prefix
664 }
665 }
Colin Crossaa255532020-07-03 13:18:24 -0700666
Yu Liu663e4502024-08-12 18:23:59 +0000667 if licenseMetadata, ok := OtherModuleProvider(ctx, mod, LicenseMetadataProvider); ok {
Colin Cross4acaea92021-12-10 23:05:02 +0000668 a.SetPath("LOCAL_SOONG_LICENSE_METADATA", licenseMetadata.LicenseMetadataPath)
669 }
670
Yu Liu663e4502024-08-12 18:23:59 +0000671 if _, ok := OtherModuleProvider(ctx, mod, ModuleInfoJSONProvider); ok {
Colin Crossd6fd0132023-11-06 13:54:06 -0800672 a.SetBool("LOCAL_SOONG_MODULE_INFO_JSON", true)
673 }
674
Colin Crossaa255532020-07-03 13:18:24 -0700675 extraCtx := &androidMkExtraEntriesContext{
676 ctx: ctx,
677 mod: mod,
678 }
679
Jaewoong Junge0dc8df2019-08-27 17:33:16 -0700680 for _, extra := range a.ExtraEntries {
Colin Crossaa255532020-07-03 13:18:24 -0700681 extra(extraCtx, a)
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700682 }
683
684 // Write to footer.
685 fmt.Fprintln(&a.footer, "include "+a.Include)
Colin Crossaa255532020-07-03 13:18:24 -0700686 blueprintDir := ctx.ModuleDir(mod)
Jaewoong Jungb0c127c2019-08-29 14:56:03 -0700687 for _, footerFunc := range a.ExtraFooters {
Jaewoong Jung02b11a62020-12-07 10:23:54 -0800688 footerFunc(&a.footer, name, prefix, blueprintDir)
Jaewoong Jungb0c127c2019-08-29 14:56:03 -0700689 }
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700690}
691
Colin Crossd6fd0132023-11-06 13:54:06 -0800692func (a *AndroidMkEntries) disabled() bool {
693 return a.Disabled || !a.OutputFile.Valid()
694}
695
Jaewoong Jung7ef4a902020-11-16 12:50:29 -0800696// write flushes the AndroidMkEntries's in-struct data populated by AndroidMkEntries into the
697// given Writer object.
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700698func (a *AndroidMkEntries) write(w io.Writer) {
Colin Crossd6fd0132023-11-06 13:54:06 -0800699 if a.disabled() {
Jaewoong Jungb0c127c2019-08-29 14:56:03 -0700700 return
701 }
702
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700703 w.Write(a.header.Bytes())
704 for _, name := range a.entryOrder {
Sasha Smundakdcb61292022-12-08 10:41:33 -0800705 AndroidMkEmitAssignList(w, name, a.EntryMap[name])
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700706 }
707 w.Write(a.footer.Bytes())
708}
709
Jaewoong Jungb0c127c2019-08-29 14:56:03 -0700710func (a *AndroidMkEntries) FooterLinesForTests() []string {
711 return strings.Split(string(a.footer.Bytes()), "\n")
712}
713
Jaewoong Jung7ef4a902020-11-16 12:50:29 -0800714// AndroidMkSingleton is a singleton to collect Android.mk data from all modules and dump them into
715// the final Android-<product_name>.mk file output.
Colin Cross0875c522017-11-28 17:34:01 -0800716func AndroidMkSingleton() Singleton {
Dan Willemsen218f6562015-07-08 18:13:11 -0700717 return &androidMkSingleton{}
718}
719
720type androidMkSingleton struct{}
721
Jihoon Kang4be8eb32025-02-10 23:02:42 +0000722func allModulesSorted(ctx SingletonContext) []blueprint.Module {
723 var allModules []blueprint.Module
Colin Cross4f6e4e62016-01-11 12:55:55 -0800724
Colin Cross2465c3d2018-09-28 10:19:18 -0700725 ctx.VisitAllModulesBlueprint(func(module blueprint.Module) {
Jihoon Kang4be8eb32025-02-10 23:02:42 +0000726 allModules = append(allModules, module)
Colin Cross4f6e4e62016-01-11 12:55:55 -0800727 })
Dan Willemsen218f6562015-07-08 18:13:11 -0700728
Jaewoong Jung7ef4a902020-11-16 12:50:29 -0800729 // Sort the module list by the module names to eliminate random churns, which may erroneously
730 // invoke additional build processes.
Jihoon Kang4be8eb32025-02-10 23:02:42 +0000731 sort.SliceStable(allModules, func(i, j int) bool {
732 return ctx.ModuleName(allModules[i]) < ctx.ModuleName(allModules[j])
Colin Cross1ad81422019-01-14 12:47:35 -0800733 })
Colin Crossd779da42015-12-17 18:00:23 -0800734
Jihoon Kang4be8eb32025-02-10 23:02:42 +0000735 return allModules
736}
737
738func (c *androidMkSingleton) GenerateBuildActions(ctx SingletonContext) {
739 // If running in soong-only mode, more limited version of this singleton is run as
740 // soong only androidmk singleton
Cole Faustc5bfbdd2025-01-08 13:05:40 -0800741 if !ctx.Config().KatiEnabled() {
Cole Faustc5bfbdd2025-01-08 13:05:40 -0800742 return
743 }
744
Dan Willemsen45133ac2018-03-09 21:22:06 -0800745 transMk := PathForOutput(ctx, "Android"+String(ctx.Config().productVariables.Make_suffix)+".mk")
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700746 if ctx.Failed() {
747 return
748 }
Dan Willemsen218f6562015-07-08 18:13:11 -0700749
Colin Crossd6fd0132023-11-06 13:54:06 -0800750 moduleInfoJSON := PathForOutput(ctx, "module-info"+String(ctx.Config().productVariables.Make_suffix)+".json")
751
Jihoon Kang4be8eb32025-02-10 23:02:42 +0000752 err := translateAndroidMk(ctx, absolutePath(transMk.String()), moduleInfoJSON, allModulesSorted(ctx))
Dan Willemsen218f6562015-07-08 18:13:11 -0700753 if err != nil {
754 ctx.Errorf(err.Error())
755 }
756
Colin Cross0875c522017-11-28 17:34:01 -0800757 ctx.Build(pctx, BuildParams{
758 Rule: blueprint.Phony,
759 Output: transMk,
Dan Willemsen218f6562015-07-08 18:13:11 -0700760 })
761}
762
Jihoon Kang4be8eb32025-02-10 23:02:42 +0000763type soongOnlyAndroidMkSingleton struct {
764 Singleton
765}
766
767func soongOnlyAndroidMkSingletonFactory() Singleton {
768 return &soongOnlyAndroidMkSingleton{}
769}
770
771func (so *soongOnlyAndroidMkSingleton) GenerateBuildActions(ctx SingletonContext) {
772 if !ctx.Config().KatiEnabled() {
773 so.soongOnlyBuildActions(ctx, allModulesSorted(ctx))
774 }
775}
776
Cole Faustc5bfbdd2025-01-08 13:05:40 -0800777// In soong-only mode, we don't do most of the androidmk stuff. But disted files are still largely
778// defined through the androidmk mechanisms, so this function is an alternate implementation of
779// the androidmk singleton that just focuses on getting the dist contributions
Jihoon Kang4be8eb32025-02-10 23:02:42 +0000780func (so *soongOnlyAndroidMkSingleton) soongOnlyBuildActions(ctx SingletonContext, mods []blueprint.Module) {
Cole Faustf9a096c2025-01-21 16:55:43 -0800781 allDistContributions, moduleInfoJSONs := getSoongOnlyDataFromMods(ctx, mods)
Cole Faustc5bfbdd2025-01-08 13:05:40 -0800782
Jihoon Kang1c6fcf52025-02-06 23:52:27 +0000783 for _, provider := range makeVarsInitProviders {
784 mctx := &makeVarsContext{
785 SingletonContext: ctx,
786 pctx: provider.pctx,
787 }
788 provider.call(mctx)
Cole Faustd62a4892025-02-07 16:55:11 -0800789 if contribution := distsToDistContributions(mctx.dists); contribution != nil {
Jihoon Kang1c6fcf52025-02-06 23:52:27 +0000790 allDistContributions = append(allDistContributions, *contribution)
791 }
792 }
793
Cole Faustf2aab5e2025-02-11 13:32:51 -0800794 singletonDists := getSingletonDists(ctx.Config())
795 singletonDists.lock.Lock()
796 if contribution := distsToDistContributions(singletonDists.dists); contribution != nil {
797 allDistContributions = append(allDistContributions, *contribution)
798 }
799 singletonDists.lock.Unlock()
800
Cole Faustf9a096c2025-01-21 16:55:43 -0800801 // Build module-info.json. Only in builds with HasDeviceProduct(), as we need a named
802 // device to have a TARGET_OUT folder.
803 if ctx.Config().HasDeviceProduct() {
Cole Faust601da062025-01-22 13:15:10 -0800804 preMergePath := PathForOutput(ctx, "module_info_pre_merging.json")
Cole Faustf9a096c2025-01-21 16:55:43 -0800805 moduleInfoJSONPath := pathForInstall(ctx, Android, X86_64, "", "module-info.json")
Cole Faust601da062025-01-22 13:15:10 -0800806 if err := writeModuleInfoJSON(ctx, moduleInfoJSONs, preMergePath); err != nil {
Cole Faustf9a096c2025-01-21 16:55:43 -0800807 ctx.Errorf("%s", err)
808 }
Cole Faust601da062025-01-22 13:15:10 -0800809 builder := NewRuleBuilder(pctx, ctx)
810 builder.Command().
811 BuiltTool("merge_module_info_json").
812 FlagWithOutput("-o ", moduleInfoJSONPath).
813 Input(preMergePath)
814 builder.Build("merge_module_info_json", "merge module info json")
Cole Faustf9a096c2025-01-21 16:55:43 -0800815 ctx.Phony("module-info", moduleInfoJSONPath)
816 ctx.Phony("droidcore-unbundled", moduleInfoJSONPath)
817 allDistContributions = append(allDistContributions, distContributions{
818 copiesForGoals: []*copiesForGoals{{
819 goals: "general-tests droidcore-unbundled",
820 copies: []distCopy{{
821 from: moduleInfoJSONPath,
822 dest: "module-info.json",
823 }},
824 }},
825 })
826 }
827
828 // Build dist.mk for the packaging step to read and generate dist targets
Cole Faustc5bfbdd2025-01-08 13:05:40 -0800829 distMkFile := absolutePath(filepath.Join(ctx.Config().katiPackageMkDir(), "dist.mk"))
830
831 var goalOutputPairs []string
Cole Faust82611a12025-01-09 11:20:41 -0800832 var srcDstPairs []string
Cole Faustc5bfbdd2025-01-08 13:05:40 -0800833 for _, contributions := range allDistContributions {
834 for _, copiesForGoal := range contributions.copiesForGoals {
835 goals := strings.Fields(copiesForGoal.goals)
836 for _, copy := range copiesForGoal.copies {
837 for _, goal := range goals {
Cole Faust82611a12025-01-09 11:20:41 -0800838 goalOutputPairs = append(goalOutputPairs, fmt.Sprintf(" %s:%s", goal, copy.dest))
Cole Faustc5bfbdd2025-01-08 13:05:40 -0800839 }
Cole Faust82611a12025-01-09 11:20:41 -0800840 srcDstPairs = append(srcDstPairs, fmt.Sprintf(" %s:%s", copy.from.String(), copy.dest))
Cole Faustc5bfbdd2025-01-08 13:05:40 -0800841 }
842 }
843 }
Cole Faust82611a12025-01-09 11:20:41 -0800844 // There are duplicates in the lists that we need to remove
845 goalOutputPairs = SortedUniqueStrings(goalOutputPairs)
846 srcDstPairs = SortedUniqueStrings(srcDstPairs)
847 var buf strings.Builder
848 buf.WriteString("DIST_SRC_DST_PAIRS :=")
849 for _, srcDstPair := range srcDstPairs {
850 buf.WriteString(srcDstPair)
851 }
852 buf.WriteString("\nDIST_GOAL_OUTPUT_PAIRS :=")
853 for _, goalOutputPair := range goalOutputPairs {
854 buf.WriteString(goalOutputPair)
855 }
856 buf.WriteString("\n")
Cole Faustc5bfbdd2025-01-08 13:05:40 -0800857
858 writeValueIfChanged(ctx, distMkFile, buf.String())
859}
860
861func writeValueIfChanged(ctx SingletonContext, path string, value string) {
862 if err := os.MkdirAll(filepath.Dir(path), 0777); err != nil {
863 ctx.Errorf("%s\n", err)
864 return
865 }
866 previousValue := ""
867 rawPreviousValue, err := os.ReadFile(path)
868 if err == nil {
869 previousValue = string(rawPreviousValue)
870 }
871
872 if previousValue != value {
873 if err = os.WriteFile(path, []byte(value), 0666); err != nil {
874 ctx.Errorf("Failed to write: %v", err)
875 }
876 }
877}
878
Cole Faustd62a4892025-02-07 16:55:11 -0800879func distsToDistContributions(dists []dist) *distContributions {
880 if len(dists) == 0 {
Jihoon Kang593171e2025-02-05 01:54:45 +0000881 return nil
882 }
883
884 copyGoals := []*copiesForGoals{}
Cole Faustd62a4892025-02-07 16:55:11 -0800885 for _, dist := range dists {
Jihoon Kang593171e2025-02-05 01:54:45 +0000886 for _, goal := range dist.goals {
Cole Faustd62a4892025-02-07 16:55:11 -0800887 copyGoals = append(copyGoals, &copiesForGoals{
888 goals: goal,
889 copies: dist.paths,
890 })
Jihoon Kang593171e2025-02-05 01:54:45 +0000891 }
892 }
893
Cole Faustd62a4892025-02-07 16:55:11 -0800894 return &distContributions{
895 copiesForGoals: copyGoals,
896 }
Jihoon Kang593171e2025-02-05 01:54:45 +0000897}
898
Cole Faustf9a096c2025-01-21 16:55:43 -0800899// getSoongOnlyDataFromMods gathers data from the given modules needed in soong-only builds.
900// Currently, this is the dist contributions, and the module-info.json contents.
901func getSoongOnlyDataFromMods(ctx fillInEntriesContext, mods []blueprint.Module) ([]distContributions, []*ModuleInfoJSON) {
Cole Faustc5bfbdd2025-01-08 13:05:40 -0800902 var allDistContributions []distContributions
Cole Faustf9a096c2025-01-21 16:55:43 -0800903 var moduleInfoJSONs []*ModuleInfoJSON
Cole Faustc5bfbdd2025-01-08 13:05:40 -0800904 for _, mod := range mods {
Cole Faustd62a4892025-02-07 16:55:11 -0800905 if distInfo, ok := OtherModuleProvider(ctx, mod, DistProvider); ok {
906 if contribution := distsToDistContributions(distInfo.Dists); contribution != nil {
907 allDistContributions = append(allDistContributions, *contribution)
908 }
909 }
910
Cole Faustc5bfbdd2025-01-08 13:05:40 -0800911 if amod, ok := mod.(Module); ok && shouldSkipAndroidMkProcessing(ctx, amod.base()) {
912 continue
913 }
914 if info, ok := OtherModuleProvider(ctx, mod, AndroidMkInfoProvider); ok {
Cole Faust556f1f42025-01-09 10:49:42 -0800915 // Deep copy the provider info since we need to modify the info later
916 info := deepCopyAndroidMkProviderInfo(info)
917 info.PrimaryInfo.fillInEntries(ctx, mod)
918 if info.PrimaryInfo.disabled() {
919 continue
920 }
Cole Faustf9a096c2025-01-21 16:55:43 -0800921 if moduleInfoJSON, ok := OtherModuleProvider(ctx, mod, ModuleInfoJSONProvider); ok {
Jihoon Kangd4063812025-01-24 00:25:30 +0000922 moduleInfoJSONs = append(moduleInfoJSONs, moduleInfoJSON...)
Cole Faustf9a096c2025-01-21 16:55:43 -0800923 }
Cole Faustc5bfbdd2025-01-08 13:05:40 -0800924 if contribution := info.PrimaryInfo.getDistContributions(ctx, mod); contribution != nil {
925 allDistContributions = append(allDistContributions, *contribution)
926 }
927 for _, ei := range info.ExtraInfo {
Cole Faust556f1f42025-01-09 10:49:42 -0800928 ei.fillInEntries(ctx, mod)
929 if ei.disabled() {
930 continue
931 }
Cole Faustc5bfbdd2025-01-08 13:05:40 -0800932 if contribution := ei.getDistContributions(ctx, mod); contribution != nil {
933 allDistContributions = append(allDistContributions, *contribution)
934 }
935 }
936 } else {
Jihoon Kange6daf662025-02-06 01:38:16 +0000937 if x, ok := mod.(AndroidMkDataProvider); ok {
Cole Faustc5bfbdd2025-01-08 13:05:40 -0800938 data := x.AndroidMk()
939
940 if data.Include == "" {
941 data.Include = "$(BUILD_PREBUILT)"
942 }
943
944 data.fillInData(ctx, mod)
Cole Faust556f1f42025-01-09 10:49:42 -0800945 if data.Entries.disabled() {
946 continue
947 }
Cole Faustf9a096c2025-01-21 16:55:43 -0800948 if moduleInfoJSON, ok := OtherModuleProvider(ctx, mod, ModuleInfoJSONProvider); ok {
Jihoon Kangd4063812025-01-24 00:25:30 +0000949 moduleInfoJSONs = append(moduleInfoJSONs, moduleInfoJSON...)
Cole Faustf9a096c2025-01-21 16:55:43 -0800950 }
Cole Faustc5bfbdd2025-01-08 13:05:40 -0800951 if contribution := data.Entries.getDistContributions(mod); contribution != nil {
952 allDistContributions = append(allDistContributions, *contribution)
953 }
Jihoon Kange6daf662025-02-06 01:38:16 +0000954 }
955 if x, ok := mod.(AndroidMkEntriesProvider); ok {
Cole Faustc5bfbdd2025-01-08 13:05:40 -0800956 entriesList := x.AndroidMkEntries()
957 for _, entries := range entriesList {
958 entries.fillInEntries(ctx, mod)
Cole Faust556f1f42025-01-09 10:49:42 -0800959 if entries.disabled() {
960 continue
961 }
Cole Faustf9a096c2025-01-21 16:55:43 -0800962 if moduleInfoJSON, ok := OtherModuleProvider(ctx, mod, ModuleInfoJSONProvider); ok {
Jihoon Kangd4063812025-01-24 00:25:30 +0000963 moduleInfoJSONs = append(moduleInfoJSONs, moduleInfoJSON...)
Cole Faustf9a096c2025-01-21 16:55:43 -0800964 }
Cole Faustc5bfbdd2025-01-08 13:05:40 -0800965 if contribution := entries.getDistContributions(mod); contribution != nil {
966 allDistContributions = append(allDistContributions, *contribution)
967 }
968 }
Jihoon Kange6daf662025-02-06 01:38:16 +0000969 }
970 if x, ok := mod.(ModuleMakeVarsProvider); ok {
971 mctx := &makeVarsContext{
972 SingletonContext: ctx.(SingletonContext),
973 config: ctx.Config(),
974 pctx: pctx,
975 }
Jihoon Kang593171e2025-02-05 01:54:45 +0000976 if !x.Enabled(ctx) {
977 continue
978 }
979 x.MakeVars(mctx)
Cole Faustd62a4892025-02-07 16:55:11 -0800980 if contribution := distsToDistContributions(mctx.dists); contribution != nil {
Jihoon Kang593171e2025-02-05 01:54:45 +0000981 allDistContributions = append(allDistContributions, *contribution)
982 }
Jihoon Kange6daf662025-02-06 01:38:16 +0000983 }
984 if x, ok := mod.(SingletonMakeVarsProvider); ok {
985 mctx := &makeVarsContext{
986 SingletonContext: ctx.(SingletonContext),
987 config: ctx.Config(),
988 pctx: pctx,
989 }
Jihoon Kang593171e2025-02-05 01:54:45 +0000990 x.MakeVars(mctx)
Cole Faustd62a4892025-02-07 16:55:11 -0800991 if contribution := distsToDistContributions(mctx.dists); contribution != nil {
Jihoon Kang593171e2025-02-05 01:54:45 +0000992 allDistContributions = append(allDistContributions, *contribution)
993 }
Cole Faustc5bfbdd2025-01-08 13:05:40 -0800994 }
995 }
996 }
Cole Faustf9a096c2025-01-21 16:55:43 -0800997 return allDistContributions, moduleInfoJSONs
Cole Faustc5bfbdd2025-01-08 13:05:40 -0800998}
999
Colin Crossd6fd0132023-11-06 13:54:06 -08001000func translateAndroidMk(ctx SingletonContext, absMkFile string, moduleInfoJSONPath WritablePath, mods []blueprint.Module) error {
Dan Willemsen218f6562015-07-08 18:13:11 -07001001 buf := &bytes.Buffer{}
1002
Colin Crossd6fd0132023-11-06 13:54:06 -08001003 var moduleInfoJSONs []*ModuleInfoJSON
1004
Dan Willemsen97750522016-02-09 17:43:51 -08001005 fmt.Fprintln(buf, "LOCAL_MODULE_MAKEFILE := $(lastword $(MAKEFILE_LIST))")
Dan Willemsen218f6562015-07-08 18:13:11 -07001006
Jaewoong Jung18aefc12020-12-21 09:11:10 -08001007 typeStats := make(map[string]int)
Dan Willemsen218f6562015-07-08 18:13:11 -07001008 for _, mod := range mods {
Colin Crossd6fd0132023-11-06 13:54:06 -08001009 err := translateAndroidMkModule(ctx, buf, &moduleInfoJSONs, mod)
Dan Willemsen218f6562015-07-08 18:13:11 -07001010 if err != nil {
Colin Cross836e3872021-11-09 12:30:59 -08001011 os.Remove(absMkFile)
Dan Willemsen218f6562015-07-08 18:13:11 -07001012 return err
1013 }
Dan Willemsen70e17fa2016-07-25 16:00:20 -07001014
Colin Cross2465c3d2018-09-28 10:19:18 -07001015 if amod, ok := mod.(Module); ok && ctx.PrimaryModule(amod) == amod {
Jaewoong Jung18aefc12020-12-21 09:11:10 -08001016 typeStats[ctx.ModuleType(amod)] += 1
Dan Willemsen70e17fa2016-07-25 16:00:20 -07001017 }
1018 }
1019
1020 keys := []string{}
1021 fmt.Fprintln(buf, "\nSTATS.SOONG_MODULE_TYPE :=")
Jaewoong Jung18aefc12020-12-21 09:11:10 -08001022 for k := range typeStats {
Dan Willemsen70e17fa2016-07-25 16:00:20 -07001023 keys = append(keys, k)
1024 }
1025 sort.Strings(keys)
1026 for _, mod_type := range keys {
1027 fmt.Fprintln(buf, "STATS.SOONG_MODULE_TYPE +=", mod_type)
Jaewoong Jung18aefc12020-12-21 09:11:10 -08001028 fmt.Fprintf(buf, "STATS.SOONG_MODULE_TYPE.%s := %d\n", mod_type, typeStats[mod_type])
Dan Willemsen218f6562015-07-08 18:13:11 -07001029 }
1030
Colin Crossd6fd0132023-11-06 13:54:06 -08001031 err := pathtools.WriteFileIfChanged(absMkFile, buf.Bytes(), 0666)
1032 if err != nil {
1033 return err
1034 }
1035
1036 return writeModuleInfoJSON(ctx, moduleInfoJSONs, moduleInfoJSONPath)
Dan Willemsen218f6562015-07-08 18:13:11 -07001037}
1038
Colin Crossd6fd0132023-11-06 13:54:06 -08001039func writeModuleInfoJSON(ctx SingletonContext, moduleInfoJSONs []*ModuleInfoJSON, moduleInfoJSONPath WritablePath) error {
1040 moduleInfoJSONBuf := &strings.Builder{}
1041 moduleInfoJSONBuf.WriteString("[")
1042 for i, moduleInfoJSON := range moduleInfoJSONs {
1043 if i != 0 {
1044 moduleInfoJSONBuf.WriteString(",\n")
1045 }
1046 moduleInfoJSONBuf.WriteString("{")
1047 moduleInfoJSONBuf.WriteString(strconv.Quote(moduleInfoJSON.core.RegisterName))
1048 moduleInfoJSONBuf.WriteString(":")
1049 err := encodeModuleInfoJSON(moduleInfoJSONBuf, moduleInfoJSON)
1050 moduleInfoJSONBuf.WriteString("}")
1051 if err != nil {
1052 return err
1053 }
1054 }
1055 moduleInfoJSONBuf.WriteString("]")
1056 WriteFileRule(ctx, moduleInfoJSONPath, moduleInfoJSONBuf.String())
1057 return nil
1058}
1059
1060func translateAndroidMkModule(ctx SingletonContext, w io.Writer, moduleInfoJSONs *[]*ModuleInfoJSON, mod blueprint.Module) error {
Colin Cross953d3a22018-09-05 16:23:54 -07001061 defer func() {
1062 if r := recover(); r != nil {
1063 panic(fmt.Errorf("%s in translateAndroidMkModule for module %s variant %s",
1064 r, ctx.ModuleName(mod), ctx.ModuleSubDir(mod)))
1065 }
1066 }()
1067
Bob Badourb4999222021-01-07 03:34:31 +00001068 // Additional cases here require review for correct license propagation to make.
Colin Crossd6fd0132023-11-06 13:54:06 -08001069 var err error
mrziwang18420972024-09-03 15:12:51 -07001070
Yu Liue70976d2024-10-15 20:45:35 +00001071 if info, ok := OtherModuleProvider(ctx, mod, AndroidMkInfoProvider); ok {
1072 err = translateAndroidMkEntriesInfoModule(ctx, w, moduleInfoJSONs, mod, info)
mrziwang18420972024-09-03 15:12:51 -07001073 } else {
1074 switch x := mod.(type) {
1075 case AndroidMkDataProvider:
1076 err = translateAndroidModule(ctx, w, moduleInfoJSONs, mod, x)
mrziwang18420972024-09-03 15:12:51 -07001077 case AndroidMkEntriesProvider:
1078 err = translateAndroidMkEntriesModule(ctx, w, moduleInfoJSONs, mod, x)
1079 default:
1080 // Not exported to make so no make variables to set.
1081 }
Dan Willemsen218f6562015-07-08 18:13:11 -07001082 }
Colin Crossd6fd0132023-11-06 13:54:06 -08001083
1084 if err != nil {
1085 return err
1086 }
1087
1088 return err
Colin Cross2465c3d2018-09-28 10:19:18 -07001089}
1090
Colin Crossaa255532020-07-03 13:18:24 -07001091func (data *AndroidMkData) fillInData(ctx fillInEntriesContext, mod blueprint.Module) {
Jooyung Han12df5fb2019-07-11 16:18:47 +09001092 // Get the preamble content through AndroidMkEntries logic.
Jooyung Han2ed99d02020-06-24 23:26:26 +09001093 data.Entries = AndroidMkEntries{
Jooyung Han12df5fb2019-07-11 16:18:47 +09001094 Class: data.Class,
1095 SubName: data.SubName,
Jingwen Chen40fd90a2020-06-15 05:24:19 +00001096 DistFiles: data.DistFiles,
Jooyung Han12df5fb2019-07-11 16:18:47 +09001097 OutputFile: data.OutputFile,
1098 Disabled: data.Disabled,
1099 Include: data.Include,
1100 Required: data.Required,
1101 Host_required: data.Host_required,
1102 Target_required: data.Target_required,
1103 }
Colin Crossaa255532020-07-03 13:18:24 -07001104 data.Entries.fillInEntries(ctx, mod)
Jooyung Han12df5fb2019-07-11 16:18:47 +09001105
1106 // copy entries back to data since it is used in Custom
Jooyung Han2ed99d02020-06-24 23:26:26 +09001107 data.Required = data.Entries.Required
1108 data.Host_required = data.Entries.Host_required
1109 data.Target_required = data.Entries.Target_required
Jooyung Han12df5fb2019-07-11 16:18:47 +09001110}
1111
Jaewoong Jung7ef4a902020-11-16 12:50:29 -08001112// A support func for the deprecated AndroidMkDataProvider interface. Use AndroidMkEntryProvider
1113// instead.
Colin Crossd6fd0132023-11-06 13:54:06 -08001114func translateAndroidModule(ctx SingletonContext, w io.Writer, moduleInfoJSONs *[]*ModuleInfoJSON,
1115 mod blueprint.Module, provider AndroidMkDataProvider) error {
Dan Willemsen218f6562015-07-08 18:13:11 -07001116
Colin Cross635c3b02016-05-18 15:37:25 -07001117 amod := mod.(Module).base()
Cole Fausta963b942024-04-11 17:43:00 -07001118 if shouldSkipAndroidMkProcessing(ctx, amod) {
Jeff Gaston088e29e2017-11-29 16:47:17 -08001119 return nil
1120 }
1121
Colin Cross91825d22017-08-10 16:59:47 -07001122 data := provider.AndroidMk()
Yu Liuddc28332024-08-09 22:48:30 +00001123
Colin Cross53499412017-09-07 13:20:25 -07001124 if data.Include == "" {
1125 data.Include = "$(BUILD_PREBUILT)"
1126 }
1127
Colin Crossaa255532020-07-03 13:18:24 -07001128 data.fillInData(ctx, mod)
LaMont Jonesb5099382024-01-10 23:42:36 +00001129 aconfigUpdateAndroidMkData(ctx, mod.(Module), &data)
Dan Willemsen01a405a2016-06-13 17:19:03 -07001130
Colin Cross0f86d182017-08-10 17:07:28 -07001131 prefix := ""
1132 if amod.ArchSpecific() {
1133 switch amod.Os().Class {
1134 case Host:
Jiyong Park1613e552020-09-14 19:43:17 +09001135 if amod.Target().HostCross {
1136 prefix = "HOST_CROSS_"
1137 } else {
1138 prefix = "HOST_"
1139 }
Colin Cross0f86d182017-08-10 17:07:28 -07001140 case Device:
1141 prefix = "TARGET_"
Colin Crossa2344662016-03-24 13:14:12 -07001142
Dan Willemsen218f6562015-07-08 18:13:11 -07001143 }
1144
Dan Willemsen0ef639b2018-10-10 17:02:29 -07001145 if amod.Arch().ArchType != ctx.Config().Targets[amod.Os()][0].Arch.ArchType {
Colin Cross0f86d182017-08-10 17:07:28 -07001146 prefix = "2ND_" + prefix
1147 }
Dan Willemsen218f6562015-07-08 18:13:11 -07001148 }
1149
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -07001150 name := provider.BaseModuleName()
Colin Cross0f86d182017-08-10 17:07:28 -07001151 blueprintDir := filepath.Dir(ctx.BlueprintFile(mod))
1152
1153 if data.Custom != nil {
Bob Badourb4999222021-01-07 03:34:31 +00001154 // List of module types allowed to use .Custom(...)
1155 // Additions to the list require careful review for proper license handling.
Colin Crossaa255532020-07-03 13:18:24 -07001156 switch reflect.TypeOf(mod).String() { // ctx.ModuleType(mod) doesn't work: aidl_interface creates phony without type
Bob Badourb4999222021-01-07 03:34:31 +00001157 case "*aidl.aidlApi": // writes non-custom before adding .phony
1158 case "*aidl.aidlMapping": // writes non-custom before adding .phony
1159 case "*android.customModule": // appears in tests only
Dan Willemsen9fe14102021-07-13 21:52:04 -07001160 case "*android_sdk.sdkRepoHost": // doesn't go through base_rules
Bob Badourb4999222021-01-07 03:34:31 +00001161 case "*apex.apexBundle": // license properties written
1162 case "*bpf.bpf": // license properties written (both for module and objs)
Neill Kapron41efab72024-07-31 22:17:36 +00001163 case "*libbpf_prog.libbpfProg": // license properties written (both for module and objs)
Bob Badourb4999222021-01-07 03:34:31 +00001164 case "*genrule.Module": // writes non-custom before adding .phony
1165 case "*java.SystemModules": // doesn't go through base_rules
1166 case "*java.systemModulesImport": // doesn't go through base_rules
1167 case "*phony.phony": // license properties written
Nelson Lif3c70682023-12-20 02:37:52 +00001168 case "*phony.PhonyRule": // writes phony deps and acts like `.PHONY`
Bob Badourb4999222021-01-07 03:34:31 +00001169 case "*selinux.selinuxContextsModule": // license properties written
1170 case "*sysprop.syspropLibrary": // license properties written
Bill Yang3b3aac02024-09-05 09:22:09 +00001171 case "*vintf.vintfCompatibilityMatrixRule": // use case like phony
Bob Badourb4999222021-01-07 03:34:31 +00001172 default:
Bob Badour65ee90a2021-09-02 15:33:10 -07001173 if !ctx.Config().IsEnvFalse("ANDROID_REQUIRE_LICENSES") {
Bob Badourb4999222021-01-07 03:34:31 +00001174 return fmt.Errorf("custom make rules not allowed for %q (%q) module %q", ctx.ModuleType(mod), reflect.TypeOf(mod), ctx.ModuleName(mod))
1175 }
1176 }
Colin Cross0f86d182017-08-10 17:07:28 -07001177 data.Custom(w, name, prefix, blueprintDir, data)
1178 } else {
1179 WriteAndroidMkData(w, data)
1180 }
1181
Colin Crossd6fd0132023-11-06 13:54:06 -08001182 if !data.Entries.disabled() {
Yu Liu663e4502024-08-12 18:23:59 +00001183 if moduleInfoJSON, ok := OtherModuleProvider(ctx, mod, ModuleInfoJSONProvider); ok {
Jihoon Kangd4063812025-01-24 00:25:30 +00001184 *moduleInfoJSONs = append(*moduleInfoJSONs, moduleInfoJSON...)
Colin Crossd6fd0132023-11-06 13:54:06 -08001185 }
1186 }
1187
Colin Cross0f86d182017-08-10 17:07:28 -07001188 return nil
1189}
1190
Jaewoong Jung7ef4a902020-11-16 12:50:29 -08001191// A support func for the deprecated AndroidMkDataProvider interface. Use AndroidMkEntryProvider
1192// instead.
Colin Cross0f86d182017-08-10 17:07:28 -07001193func WriteAndroidMkData(w io.Writer, data AndroidMkData) {
Colin Crossd6fd0132023-11-06 13:54:06 -08001194 if data.Entries.disabled() {
Colin Cross0f86d182017-08-10 17:07:28 -07001195 return
1196 }
1197
Jooyung Han2ed99d02020-06-24 23:26:26 +09001198 // write preamble via Entries
1199 data.Entries.footer = bytes.Buffer{}
1200 data.Entries.write(w)
Colin Cross0f86d182017-08-10 17:07:28 -07001201
Colin Crossca860ac2016-01-04 14:34:37 -08001202 for _, extra := range data.Extra {
Colin Cross27a4b052017-08-10 16:32:23 -07001203 extra(w, data.OutputFile.Path())
Dan Willemsen97750522016-02-09 17:43:51 -08001204 }
1205
Colin Cross53499412017-09-07 13:20:25 -07001206 fmt.Fprintln(w, "include "+data.Include)
Dan Willemsen218f6562015-07-08 18:13:11 -07001207}
Sasha Smundakb6d23052019-04-01 18:37:36 -07001208
Colin Crossd6fd0132023-11-06 13:54:06 -08001209func translateAndroidMkEntriesModule(ctx SingletonContext, w io.Writer, moduleInfoJSONs *[]*ModuleInfoJSON,
1210 mod blueprint.Module, provider AndroidMkEntriesProvider) error {
Cole Fausta963b942024-04-11 17:43:00 -07001211 if shouldSkipAndroidMkProcessing(ctx, mod.(Module).base()) {
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -07001212 return nil
Sasha Smundakb6d23052019-04-01 18:37:36 -07001213 }
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -07001214
Colin Crossd6fd0132023-11-06 13:54:06 -08001215 entriesList := provider.AndroidMkEntries()
LaMont Jonesb5099382024-01-10 23:42:36 +00001216 aconfigUpdateAndroidMkEntries(ctx, mod.(Module), &entriesList)
Colin Crossd6fd0132023-11-06 13:54:06 -08001217
Jihoon Kangd4063812025-01-24 00:25:30 +00001218 moduleInfoJSON, providesModuleInfoJSON := OtherModuleProvider(ctx, mod, ModuleInfoJSONProvider)
1219
Bob Badourb4999222021-01-07 03:34:31 +00001220 // Any new or special cases here need review to verify correct propagation of license information.
Colin Crossd6fd0132023-11-06 13:54:06 -08001221 for _, entries := range entriesList {
Colin Crossaa255532020-07-03 13:18:24 -07001222 entries.fillInEntries(ctx, mod)
Jiyong Park0b0e1b92019-12-03 13:24:29 +09001223 entries.write(w)
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -07001224
Jihoon Kangd4063812025-01-24 00:25:30 +00001225 if providesModuleInfoJSON && !entries.disabled() {
1226 // append only the name matching moduleInfoJSON entry
1227 for _, m := range moduleInfoJSON {
1228 if m.RegisterNameOverride == entries.OverrideName && m.SubName == entries.SubName {
1229 *moduleInfoJSONs = append(*moduleInfoJSONs, m)
1230 }
1231 }
Colin Crossd6fd0132023-11-06 13:54:06 -08001232 }
1233 }
1234
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -07001235 return nil
1236}
1237
Cole Fauste8a87832024-09-11 11:35:46 -07001238func ShouldSkipAndroidMkProcessing(ctx ConfigurableEvaluatorContext, module Module) bool {
Cole Fausta963b942024-04-11 17:43:00 -07001239 return shouldSkipAndroidMkProcessing(ctx, module.base())
Chih-Hung Hsieh80783772021-10-11 16:46:56 -07001240}
1241
Cole Fauste8a87832024-09-11 11:35:46 -07001242func shouldSkipAndroidMkProcessing(ctx ConfigurableEvaluatorContext, module *ModuleBase) bool {
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -07001243 if !module.commonProperties.NamespaceExportedToMake {
1244 // TODO(jeffrygaston) do we want to validate that there are no modules being
1245 // exported to Kati that depend on this module?
1246 return true
Sasha Smundakb6d23052019-04-01 18:37:36 -07001247 }
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -07001248
Dan Willemsendef7b5d2021-10-17 00:22:33 -07001249 // On Mac, only expose host darwin modules to Make, as that's all we claim to support.
1250 // In reality, some of them depend on device-built (Java) modules, so we can't disable all
1251 // device modules in Soong, but we can hide them from Make (and thus the build user interface)
1252 if runtime.GOOS == "darwin" && module.Os() != Darwin {
1253 return true
1254 }
1255
Dan Willemsen8528f4e2021-10-19 00:22:06 -07001256 // Only expose the primary Darwin target, as Make does not understand Darwin+Arm64
1257 if module.Os() == Darwin && module.Target().HostCross {
1258 return true
1259 }
1260
Cole Fausta963b942024-04-11 17:43:00 -07001261 return !module.Enabled(ctx) ||
Colin Crossa9c8c9f2020-12-16 10:20:23 -08001262 module.commonProperties.HideFromMake ||
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -07001263 // Make does not understand LinuxBionic
Colin Cross9a027be2022-06-24 18:45:58 -07001264 module.Os() == LinuxBionic ||
1265 // Make does not understand LinuxMusl, except when we are building with USE_HOST_MUSL=true
1266 // and all host binaries are LinuxMusl
1267 (module.Os() == LinuxMusl && module.Target().HostCross)
Sasha Smundakb6d23052019-04-01 18:37:36 -07001268}
Dan Shi31949122020-09-21 12:11:02 -07001269
Jaewoong Jung7ef4a902020-11-16 12:50:29 -08001270// A utility func to format LOCAL_TEST_DATA outputs. See the comments on DataPath to understand how
1271// to use this func.
Colin Cross5c1d5fb2023-11-15 12:39:40 -08001272func androidMkDataPaths(data []DataPath) []string {
Dan Shi31949122020-09-21 12:11:02 -07001273 var testFiles []string
1274 for _, d := range data {
1275 rel := d.SrcPath.Rel()
Colin Cross5c1d5fb2023-11-15 12:39:40 -08001276 if d.WithoutRel {
1277 rel = d.SrcPath.Base()
1278 }
Dan Shi31949122020-09-21 12:11:02 -07001279 path := d.SrcPath.String()
Jaewoong Jung7ef4a902020-11-16 12:50:29 -08001280 // LOCAL_TEST_DATA requires the rel portion of the path to be removed from the path.
Dan Shi31949122020-09-21 12:11:02 -07001281 if !strings.HasSuffix(path, rel) {
1282 panic(fmt.Errorf("path %q does not end with %q", path, rel))
1283 }
1284 path = strings.TrimSuffix(path, rel)
1285 testFileString := path + ":" + rel
1286 if len(d.RelativeInstallPath) > 0 {
1287 testFileString += ":" + d.RelativeInstallPath
1288 }
1289 testFiles = append(testFiles, testFileString)
1290 }
1291 return testFiles
1292}
Sasha Smundakdcb61292022-12-08 10:41:33 -08001293
1294// AndroidMkEmitAssignList emits the line
1295//
1296// VAR := ITEM ...
1297//
1298// Items are the elements to the given set of lists
1299// If all the passed lists are empty, no line will be emitted
1300func AndroidMkEmitAssignList(w io.Writer, varName string, lists ...[]string) {
1301 doPrint := false
1302 for _, l := range lists {
1303 if doPrint = len(l) > 0; doPrint {
1304 break
1305 }
1306 }
1307 if !doPrint {
1308 return
1309 }
1310 fmt.Fprint(w, varName, " :=")
1311 for _, l := range lists {
1312 for _, item := range l {
1313 fmt.Fprint(w, " ", item)
1314 }
1315 }
1316 fmt.Fprintln(w)
1317}
mrziwang18420972024-09-03 15:12:51 -07001318
1319type AndroidMkProviderInfo struct {
1320 PrimaryInfo AndroidMkInfo
1321 ExtraInfo []AndroidMkInfo
1322}
1323
1324type AndroidMkInfo struct {
1325 // Android.mk class string, e.g. EXECUTABLES, JAVA_LIBRARIES, ETC
1326 Class string
1327 // Optional suffix to append to the module name. Useful when a module wants to return multiple
1328 // AndroidMkEntries objects. For example, when a java_library returns an additional entry for
1329 // its hostdex sub-module, this SubName field is set to "-hostdex" so that it can have a
1330 // different name than the parent's.
1331 SubName string
1332 // If set, this value overrides the base module name. SubName is still appended.
1333 OverrideName string
1334 // Dist files to output
1335 DistFiles TaggedDistFiles
1336 // The output file for Kati to process and/or install. If absent, the module is skipped.
1337 OutputFile OptionalPath
1338 // If true, the module is skipped and does not appear on the final Android-<product name>.mk
1339 // file. Useful when a module needs to be skipped conditionally.
1340 Disabled bool
1341 // The postprocessing mk file to include, e.g. $(BUILD_SYSTEM)/soong_cc_rust_prebuilt.mk
1342 // If not set, $(BUILD_SYSTEM)/prebuilt.mk is used.
1343 Include string
1344 // Required modules that need to be built and included in the final build output when building
1345 // this module.
1346 Required []string
1347 // Required host modules that need to be built and included in the final build output when
1348 // building this module.
1349 Host_required []string
1350 // Required device modules that need to be built and included in the final build output when
1351 // building this module.
1352 Target_required []string
1353
1354 HeaderStrings []string
1355 FooterStrings []string
1356
1357 // A map that holds the up-to-date Make variable values. Can be accessed from tests.
1358 EntryMap map[string][]string
1359 // A list of EntryMap keys in insertion order. This serves a few purposes:
1360 // 1. Prevents churns. Golang map doesn't provide consistent iteration order, so without this,
1361 // the outputted Android-*.mk file may change even though there have been no content changes.
1362 // 2. Allows modules to refer to other variables, like LOCAL_BAR_VAR := $(LOCAL_FOO_VAR),
1363 // without worrying about the variables being mixed up in the actual mk file.
1364 // 3. Makes troubleshooting and spotting errors easier.
1365 EntryOrder []string
1366}
1367
Yu Liue70976d2024-10-15 20:45:35 +00001368type AndroidMkProviderInfoProducer interface {
1369 PrepareAndroidMKProviderInfo(config Config) *AndroidMkProviderInfo
1370}
1371
mrziwang18420972024-09-03 15:12:51 -07001372// TODO: rename it to AndroidMkEntriesProvider after AndroidMkEntriesProvider interface is gone.
1373var AndroidMkInfoProvider = blueprint.NewProvider[*AndroidMkProviderInfo]()
1374
1375func translateAndroidMkEntriesInfoModule(ctx SingletonContext, w io.Writer, moduleInfoJSONs *[]*ModuleInfoJSON,
1376 mod blueprint.Module, providerInfo *AndroidMkProviderInfo) error {
1377 if shouldSkipAndroidMkProcessing(ctx, mod.(Module).base()) {
1378 return nil
1379 }
1380
1381 // Deep copy the provider info since we need to modify the info later
1382 info := deepCopyAndroidMkProviderInfo(providerInfo)
1383
1384 aconfigUpdateAndroidMkInfos(ctx, mod.(Module), &info)
1385
1386 // Any new or special cases here need review to verify correct propagation of license information.
1387 info.PrimaryInfo.fillInEntries(ctx, mod)
1388 info.PrimaryInfo.write(w)
1389 if len(info.ExtraInfo) > 0 {
1390 for _, ei := range info.ExtraInfo {
1391 ei.fillInEntries(ctx, mod)
1392 ei.write(w)
1393 }
1394 }
1395
1396 if !info.PrimaryInfo.disabled() {
1397 if moduleInfoJSON, ok := OtherModuleProvider(ctx, mod, ModuleInfoJSONProvider); ok {
Jihoon Kangd4063812025-01-24 00:25:30 +00001398 *moduleInfoJSONs = append(*moduleInfoJSONs, moduleInfoJSON...)
mrziwang18420972024-09-03 15:12:51 -07001399 }
1400 }
1401
1402 return nil
1403}
1404
1405// Utility funcs to manipulate Android.mk variable entries.
1406
1407// SetString sets a Make variable with the given name to the given value.
1408func (a *AndroidMkInfo) SetString(name, value string) {
1409 if _, ok := a.EntryMap[name]; !ok {
1410 a.EntryOrder = append(a.EntryOrder, name)
1411 }
1412 a.EntryMap[name] = []string{value}
1413}
1414
1415// SetPath sets a Make variable with the given name to the given path string.
1416func (a *AndroidMkInfo) SetPath(name string, path Path) {
1417 if _, ok := a.EntryMap[name]; !ok {
1418 a.EntryOrder = append(a.EntryOrder, name)
1419 }
1420 a.EntryMap[name] = []string{path.String()}
1421}
1422
1423// SetOptionalPath sets a Make variable with the given name to the given path string if it is valid.
1424// It is a no-op if the given path is invalid.
1425func (a *AndroidMkInfo) SetOptionalPath(name string, path OptionalPath) {
1426 if path.Valid() {
1427 a.SetPath(name, path.Path())
1428 }
1429}
1430
1431// AddPath appends the given path string to a Make variable with the given name.
1432func (a *AndroidMkInfo) AddPath(name string, path Path) {
1433 if _, ok := a.EntryMap[name]; !ok {
1434 a.EntryOrder = append(a.EntryOrder, name)
1435 }
1436 a.EntryMap[name] = append(a.EntryMap[name], path.String())
1437}
1438
1439// AddOptionalPath appends the given path string to a Make variable with the given name if it is
1440// valid. It is a no-op if the given path is invalid.
1441func (a *AndroidMkInfo) AddOptionalPath(name string, path OptionalPath) {
1442 if path.Valid() {
1443 a.AddPath(name, path.Path())
1444 }
1445}
1446
1447// SetPaths sets a Make variable with the given name to a slice of the given path strings.
1448func (a *AndroidMkInfo) SetPaths(name string, paths Paths) {
1449 if _, ok := a.EntryMap[name]; !ok {
1450 a.EntryOrder = append(a.EntryOrder, name)
1451 }
1452 a.EntryMap[name] = paths.Strings()
1453}
1454
1455// SetOptionalPaths sets a Make variable with the given name to a slice of the given path strings
1456// only if there are a non-zero amount of paths.
1457func (a *AndroidMkInfo) SetOptionalPaths(name string, paths Paths) {
1458 if len(paths) > 0 {
1459 a.SetPaths(name, paths)
1460 }
1461}
1462
1463// AddPaths appends the given path strings to a Make variable with the given name.
1464func (a *AndroidMkInfo) AddPaths(name string, paths Paths) {
1465 if _, ok := a.EntryMap[name]; !ok {
1466 a.EntryOrder = append(a.EntryOrder, name)
1467 }
1468 a.EntryMap[name] = append(a.EntryMap[name], paths.Strings()...)
1469}
1470
1471// SetBoolIfTrue sets a Make variable with the given name to true if the given flag is true.
1472// It is a no-op if the given flag is false.
1473func (a *AndroidMkInfo) SetBoolIfTrue(name string, flag bool) {
1474 if flag {
1475 if _, ok := a.EntryMap[name]; !ok {
1476 a.EntryOrder = append(a.EntryOrder, name)
1477 }
1478 a.EntryMap[name] = []string{"true"}
1479 }
1480}
1481
1482// SetBool sets a Make variable with the given name to if the given bool flag value.
1483func (a *AndroidMkInfo) SetBool(name string, flag bool) {
1484 if _, ok := a.EntryMap[name]; !ok {
1485 a.EntryOrder = append(a.EntryOrder, name)
1486 }
1487 if flag {
1488 a.EntryMap[name] = []string{"true"}
1489 } else {
1490 a.EntryMap[name] = []string{"false"}
1491 }
1492}
1493
1494// AddStrings appends the given strings to a Make variable with the given name.
1495func (a *AndroidMkInfo) AddStrings(name string, value ...string) {
1496 if len(value) == 0 {
1497 return
1498 }
1499 if _, ok := a.EntryMap[name]; !ok {
1500 a.EntryOrder = append(a.EntryOrder, name)
1501 }
1502 a.EntryMap[name] = append(a.EntryMap[name], value...)
1503}
1504
1505// AddCompatibilityTestSuites adds the supplied test suites to the EntryMap, with special handling
1506// for partial MTS and MCTS test suites.
1507func (a *AndroidMkInfo) AddCompatibilityTestSuites(suites ...string) {
1508 // M(C)TS supports a full test suite and partial per-module MTS test suites, with naming mts-${MODULE}.
1509 // To reduce repetition, if we find a partial M(C)TS test suite without an full M(C)TS test suite,
1510 // we add the full test suite to our list.
1511 if PrefixInList(suites, "mts-") && !InList("mts", suites) {
1512 suites = append(suites, "mts")
1513 }
1514 if PrefixInList(suites, "mcts-") && !InList("mcts", suites) {
1515 suites = append(suites, "mcts")
1516 }
1517 a.AddStrings("LOCAL_COMPATIBILITY_SUITE", suites...)
1518}
1519
1520func (a *AndroidMkInfo) fillInEntries(ctx fillInEntriesContext, mod blueprint.Module) {
1521 helperInfo := AndroidMkInfo{
1522 EntryMap: make(map[string][]string),
1523 }
1524
1525 amod := mod.(Module)
1526 base := amod.base()
1527 name := base.BaseModuleName()
1528 if a.OverrideName != "" {
1529 name = a.OverrideName
1530 }
1531
1532 if a.Include == "" {
1533 a.Include = "$(BUILD_PREBUILT)"
1534 }
1535 a.Required = append(a.Required, amod.RequiredModuleNames(ctx)...)
1536 a.Required = append(a.Required, amod.VintfFragmentModuleNames(ctx)...)
1537 a.Host_required = append(a.Host_required, amod.HostRequiredModuleNames()...)
1538 a.Target_required = append(a.Target_required, amod.TargetRequiredModuleNames()...)
1539
1540 for _, distString := range a.GetDistForGoals(ctx, mod) {
1541 a.HeaderStrings = append(a.HeaderStrings, distString)
1542 }
1543
Yu Liue70976d2024-10-15 20:45:35 +00001544 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 -07001545
1546 // Collect make variable assignment entries.
1547 helperInfo.SetString("LOCAL_PATH", ctx.ModuleDir(mod))
1548 helperInfo.SetString("LOCAL_MODULE", name+a.SubName)
1549 helperInfo.SetString("LOCAL_MODULE_CLASS", a.Class)
1550 helperInfo.SetString("LOCAL_PREBUILT_MODULE_FILE", a.OutputFile.String())
1551 helperInfo.AddStrings("LOCAL_REQUIRED_MODULES", a.Required...)
1552 helperInfo.AddStrings("LOCAL_HOST_REQUIRED_MODULES", a.Host_required...)
1553 helperInfo.AddStrings("LOCAL_TARGET_REQUIRED_MODULES", a.Target_required...)
1554 helperInfo.AddStrings("LOCAL_SOONG_MODULE_TYPE", ctx.ModuleType(amod))
1555
1556 // If the install rule was generated by Soong tell Make about it.
1557 info := OtherModuleProviderOrDefault(ctx, mod, InstallFilesProvider)
1558 if len(info.KatiInstalls) > 0 {
1559 // Assume the primary install file is last since it probably needs to depend on any other
1560 // installed files. If that is not the case we can add a method to specify the primary
1561 // installed file.
1562 helperInfo.SetPath("LOCAL_SOONG_INSTALLED_MODULE", info.KatiInstalls[len(info.KatiInstalls)-1].to)
1563 helperInfo.SetString("LOCAL_SOONG_INSTALL_PAIRS", info.KatiInstalls.BuiltInstalled())
1564 helperInfo.SetPaths("LOCAL_SOONG_INSTALL_SYMLINKS", info.KatiSymlinks.InstallPaths().Paths())
1565 } else {
1566 // Soong may not have generated the install rule also when `no_full_install: true`.
1567 // Mark this module as uninstallable in order to prevent Make from creating an
1568 // install rule there.
1569 helperInfo.SetBoolIfTrue("LOCAL_UNINSTALLABLE_MODULE", proptools.Bool(base.commonProperties.No_full_install))
1570 }
1571
Yu Liue70976d2024-10-15 20:45:35 +00001572 if info.UncheckedModule {
1573 helperInfo.SetBool("LOCAL_DONT_CHECK_MODULE", true)
1574 } else if info.CheckbuildTarget != nil {
1575 helperInfo.SetPath("LOCAL_CHECKED_MODULE", info.CheckbuildTarget)
1576 } else {
1577 helperInfo.SetOptionalPath("LOCAL_CHECKED_MODULE", a.OutputFile)
1578 }
1579
mrziwang18420972024-09-03 15:12:51 -07001580 if len(info.TestData) > 0 {
1581 helperInfo.AddStrings("LOCAL_TEST_DATA", androidMkDataPaths(info.TestData)...)
1582 }
1583
1584 if am, ok := mod.(ApexModule); ok {
1585 helperInfo.SetBoolIfTrue("LOCAL_NOT_AVAILABLE_FOR_PLATFORM", am.NotAvailableForPlatform())
1586 }
1587
1588 archStr := base.Arch().ArchType.String()
1589 host := false
1590 switch base.Os().Class {
1591 case Host:
1592 if base.Target().HostCross {
1593 // Make cannot identify LOCAL_MODULE_HOST_CROSS_ARCH:= common.
1594 if base.Arch().ArchType != Common {
1595 helperInfo.SetString("LOCAL_MODULE_HOST_CROSS_ARCH", archStr)
1596 }
1597 } else {
1598 // Make cannot identify LOCAL_MODULE_HOST_ARCH:= common.
1599 if base.Arch().ArchType != Common {
1600 helperInfo.SetString("LOCAL_MODULE_HOST_ARCH", archStr)
1601 }
1602 }
1603 host = true
1604 case Device:
1605 // Make cannot identify LOCAL_MODULE_TARGET_ARCH:= common.
1606 if base.Arch().ArchType != Common {
1607 if base.Target().NativeBridge {
1608 hostArchStr := base.Target().NativeBridgeHostArchName
1609 if hostArchStr != "" {
1610 helperInfo.SetString("LOCAL_MODULE_TARGET_ARCH", hostArchStr)
1611 }
1612 } else {
1613 helperInfo.SetString("LOCAL_MODULE_TARGET_ARCH", archStr)
1614 }
1615 }
1616
1617 if !base.InVendorRamdisk() {
1618 helperInfo.AddPaths("LOCAL_FULL_INIT_RC", info.InitRcPaths)
1619 }
1620 if len(info.VintfFragmentsPaths) > 0 {
1621 helperInfo.AddPaths("LOCAL_FULL_VINTF_FRAGMENTS", info.VintfFragmentsPaths)
1622 }
1623 helperInfo.SetBoolIfTrue("LOCAL_PROPRIETARY_MODULE", Bool(base.commonProperties.Proprietary))
1624 if Bool(base.commonProperties.Vendor) || Bool(base.commonProperties.Soc_specific) {
1625 helperInfo.SetString("LOCAL_VENDOR_MODULE", "true")
1626 }
1627 helperInfo.SetBoolIfTrue("LOCAL_ODM_MODULE", Bool(base.commonProperties.Device_specific))
1628 helperInfo.SetBoolIfTrue("LOCAL_PRODUCT_MODULE", Bool(base.commonProperties.Product_specific))
1629 helperInfo.SetBoolIfTrue("LOCAL_SYSTEM_EXT_MODULE", Bool(base.commonProperties.System_ext_specific))
1630 if base.commonProperties.Owner != nil {
1631 helperInfo.SetString("LOCAL_MODULE_OWNER", *base.commonProperties.Owner)
1632 }
1633 }
1634
1635 if host {
1636 makeOs := base.Os().String()
1637 if base.Os() == Linux || base.Os() == LinuxBionic || base.Os() == LinuxMusl {
1638 makeOs = "linux"
1639 }
1640 helperInfo.SetString("LOCAL_MODULE_HOST_OS", makeOs)
1641 helperInfo.SetString("LOCAL_IS_HOST_MODULE", "true")
1642 }
1643
mrziwang18420972024-09-03 15:12:51 -07001644 if licenseMetadata, ok := OtherModuleProvider(ctx, mod, LicenseMetadataProvider); ok {
1645 helperInfo.SetPath("LOCAL_SOONG_LICENSE_METADATA", licenseMetadata.LicenseMetadataPath)
1646 }
1647
1648 if _, ok := OtherModuleProvider(ctx, mod, ModuleInfoJSONProvider); ok {
1649 helperInfo.SetBool("LOCAL_SOONG_MODULE_INFO_JSON", true)
1650 }
1651
1652 a.mergeEntries(&helperInfo)
1653
1654 // Write to footer.
1655 a.FooterStrings = append([]string{"include " + a.Include}, a.FooterStrings...)
1656}
1657
1658// This method merges the entries to helperInfo, then replaces a's EntryMap and
1659// EntryOrder with helperInfo's
1660func (a *AndroidMkInfo) mergeEntries(helperInfo *AndroidMkInfo) {
1661 for _, extraEntry := range a.EntryOrder {
1662 if v, ok := helperInfo.EntryMap[extraEntry]; ok {
1663 v = append(v, a.EntryMap[extraEntry]...)
1664 } else {
1665 helperInfo.EntryMap[extraEntry] = a.EntryMap[extraEntry]
1666 helperInfo.EntryOrder = append(helperInfo.EntryOrder, extraEntry)
1667 }
1668 }
1669 a.EntryOrder = helperInfo.EntryOrder
1670 a.EntryMap = helperInfo.EntryMap
1671}
1672
1673func (a *AndroidMkInfo) disabled() bool {
1674 return a.Disabled || !a.OutputFile.Valid()
1675}
1676
1677// write flushes the AndroidMkEntries's in-struct data populated by AndroidMkEntries into the
1678// given Writer object.
1679func (a *AndroidMkInfo) write(w io.Writer) {
1680 if a.disabled() {
1681 return
1682 }
1683
Yu Liue70976d2024-10-15 20:45:35 +00001684 combinedHeaderString := strings.Join(a.HeaderStrings, "\n") + "\n"
1685 combinedFooterString := strings.Join(a.FooterStrings, "\n") + "\n"
mrziwang18420972024-09-03 15:12:51 -07001686 w.Write([]byte(combinedHeaderString))
1687 for _, name := range a.EntryOrder {
1688 AndroidMkEmitAssignList(w, name, a.EntryMap[name])
1689 }
1690 w.Write([]byte(combinedFooterString))
1691}
1692
1693// Compute the list of Make strings to declare phony goals and dist-for-goals
1694// calls from the module's dist and dists properties.
1695func (a *AndroidMkInfo) GetDistForGoals(ctx fillInEntriesContext, mod blueprint.Module) []string {
1696 distContributions := a.getDistContributions(ctx, mod)
1697 if distContributions == nil {
1698 return nil
1699 }
1700
1701 return generateDistContributionsForMake(distContributions)
1702}
1703
1704// Compute the contributions that the module makes to the dist.
1705func (a *AndroidMkInfo) getDistContributions(ctx fillInEntriesContext, mod blueprint.Module) *distContributions {
1706 amod := mod.(Module).base()
1707 name := amod.BaseModuleName()
1708
1709 // Collate the set of associated tag/paths available for copying to the dist.
1710 // Start with an empty (nil) set.
1711 var availableTaggedDists TaggedDistFiles
1712
1713 // Then merge in any that are provided explicitly by the module.
1714 if a.DistFiles != nil {
1715 // Merge the DistFiles into the set.
1716 availableTaggedDists = availableTaggedDists.merge(a.DistFiles)
1717 }
1718
1719 // If no paths have been provided for the DefaultDistTag and the output file is
1720 // valid then add that as the default dist path.
1721 if _, ok := availableTaggedDists[DefaultDistTag]; !ok && a.OutputFile.Valid() {
1722 availableTaggedDists = availableTaggedDists.addPathsForTag(DefaultDistTag, a.OutputFile.Path())
1723 }
1724
1725 info := OtherModuleProviderOrDefault(ctx, mod, InstallFilesProvider)
1726 // If the distFiles created by GenerateTaggedDistFiles contains paths for the
1727 // DefaultDistTag then that takes priority so delete any existing paths.
1728 if _, ok := info.DistFiles[DefaultDistTag]; ok {
1729 delete(availableTaggedDists, DefaultDistTag)
1730 }
1731
1732 // Finally, merge the distFiles created by GenerateTaggedDistFiles.
1733 availableTaggedDists = availableTaggedDists.merge(info.DistFiles)
1734
1735 if len(availableTaggedDists) == 0 {
1736 // Nothing dist-able for this module.
1737 return nil
1738 }
1739
1740 // Collate the contributions this module makes to the dist.
1741 distContributions := &distContributions{}
1742
1743 if !exemptFromRequiredApplicableLicensesProperty(mod.(Module)) {
1744 distContributions.licenseMetadataFile = info.LicenseMetadataFile
1745 }
1746
1747 // Iterate over this module's dist structs, merged from the dist and dists properties.
1748 for _, dist := range amod.Dists() {
1749 // Get the list of goals this dist should be enabled for. e.g. sdk, droidcore
1750 goals := strings.Join(dist.Targets, " ")
1751
1752 // Get the tag representing the output files to be dist'd. e.g. ".jar", ".proguard_map"
1753 var tag string
1754 if dist.Tag == nil {
1755 // If the dist struct does not specify a tag, use the default output files tag.
1756 tag = DefaultDistTag
1757 } else {
1758 tag = *dist.Tag
1759 }
1760
1761 // Get the paths of the output files to be dist'd, represented by the tag.
1762 // Can be an empty list.
1763 tagPaths := availableTaggedDists[tag]
1764 if len(tagPaths) == 0 {
1765 // Nothing to dist for this tag, continue to the next dist.
1766 continue
1767 }
1768
1769 if len(tagPaths) > 1 && (dist.Dest != nil || dist.Suffix != nil) {
1770 errorMessage := "%s: Cannot apply dest/suffix for more than one dist " +
1771 "file for %q goals tag %q in module %s. The list of dist files, " +
1772 "which should have a single element, is:\n%s"
1773 panic(fmt.Errorf(errorMessage, mod, goals, tag, name, tagPaths))
1774 }
1775
1776 copiesForGoals := distContributions.getCopiesForGoals(goals)
1777
1778 // Iterate over each path adding a copy instruction to copiesForGoals
1779 for _, path := range tagPaths {
1780 // It's possible that the Path is nil from errant modules. Be defensive here.
1781 if path == nil {
1782 tagName := "default" // for error message readability
1783 if dist.Tag != nil {
1784 tagName = *dist.Tag
1785 }
1786 panic(fmt.Errorf("Dist file should not be nil for the %s tag in %s", tagName, name))
1787 }
1788
1789 dest := filepath.Base(path.String())
1790
1791 if dist.Dest != nil {
1792 var err error
1793 if dest, err = validateSafePath(*dist.Dest); err != nil {
1794 // This was checked in ModuleBase.GenerateBuildActions
1795 panic(err)
1796 }
1797 }
1798
1799 ext := filepath.Ext(dest)
1800 suffix := ""
1801 if dist.Suffix != nil {
1802 suffix = *dist.Suffix
1803 }
1804
1805 productString := ""
1806 if dist.Append_artifact_with_product != nil && *dist.Append_artifact_with_product {
1807 productString = fmt.Sprintf("_%s", ctx.Config().DeviceProduct())
1808 }
1809
1810 if suffix != "" || productString != "" {
1811 dest = strings.TrimSuffix(dest, ext) + suffix + productString + ext
1812 }
1813
1814 if dist.Dir != nil {
1815 var err error
1816 if dest, err = validateSafePath(*dist.Dir, dest); err != nil {
1817 // This was checked in ModuleBase.GenerateBuildActions
1818 panic(err)
1819 }
1820 }
1821
1822 copiesForGoals.addCopyInstruction(path, dest)
1823 }
1824 }
1825
1826 return distContributions
1827}
1828
1829func deepCopyAndroidMkProviderInfo(providerInfo *AndroidMkProviderInfo) AndroidMkProviderInfo {
1830 info := AndroidMkProviderInfo{
1831 PrimaryInfo: deepCopyAndroidMkInfo(&providerInfo.PrimaryInfo),
1832 }
1833 if len(providerInfo.ExtraInfo) > 0 {
1834 for _, i := range providerInfo.ExtraInfo {
1835 info.ExtraInfo = append(info.ExtraInfo, deepCopyAndroidMkInfo(&i))
1836 }
1837 }
1838 return info
1839}
1840
1841func deepCopyAndroidMkInfo(mkinfo *AndroidMkInfo) AndroidMkInfo {
1842 info := AndroidMkInfo{
1843 Class: mkinfo.Class,
1844 SubName: mkinfo.SubName,
1845 OverrideName: mkinfo.OverrideName,
1846 // There is no modification on DistFiles or OutputFile, so no need to
1847 // make their deep copy.
1848 DistFiles: mkinfo.DistFiles,
1849 OutputFile: mkinfo.OutputFile,
1850 Disabled: mkinfo.Disabled,
1851 Include: mkinfo.Include,
1852 Required: deepCopyStringSlice(mkinfo.Required),
1853 Host_required: deepCopyStringSlice(mkinfo.Host_required),
1854 Target_required: deepCopyStringSlice(mkinfo.Target_required),
1855 HeaderStrings: deepCopyStringSlice(mkinfo.HeaderStrings),
1856 FooterStrings: deepCopyStringSlice(mkinfo.FooterStrings),
1857 EntryOrder: deepCopyStringSlice(mkinfo.EntryOrder),
1858 }
1859 info.EntryMap = make(map[string][]string)
1860 for k, v := range mkinfo.EntryMap {
1861 info.EntryMap[k] = deepCopyStringSlice(v)
1862 }
1863
1864 return info
1865}
1866
1867func deepCopyStringSlice(original []string) []string {
1868 result := make([]string, len(original))
1869 copy(result, original)
1870 return result
1871}