blob: 081bca92eefa91e2b3d2c48c53faab90ca3553a8 [file] [log] [blame]
Dan Willemsen218f6562015-07-08 18:13:11 -07001// Copyright 2015 Google Inc. All rights reserved.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
Jaewoong Jung7ef4a902020-11-16 12:50:29 -080015// This file offers AndroidMkEntriesProvider, which individual modules implement to output
16// Android.mk entries that contain information about the modules built through Soong. Kati reads
17// and combines them with the legacy Make-based module definitions to produce the complete view of
18// the source tree, which makes this a critical point of Make-Soong interoperability.
19//
20// Naturally, Soong-only builds do not rely on this mechanism.
21
Colin Cross635c3b02016-05-18 15:37:25 -070022package android
Dan Willemsen218f6562015-07-08 18:13:11 -070023
24import (
25 "bytes"
Dan Willemsen97750522016-02-09 17:43:51 -080026 "fmt"
Dan Willemsen218f6562015-07-08 18:13:11 -070027 "io"
Dan Willemsen218f6562015-07-08 18:13:11 -070028 "os"
29 "path/filepath"
Bob Badourb4999222021-01-07 03:34:31 +000030 "reflect"
Dan Willemsendef7b5d2021-10-17 00:22:33 -070031 "runtime"
Dan Willemsen218f6562015-07-08 18:13:11 -070032 "sort"
Colin Crossd6fd0132023-11-06 13:54:06 -080033 "strconv"
Dan Willemsen0fda89f2016-06-01 15:25:32 -070034 "strings"
Dan Willemsen218f6562015-07-08 18:13:11 -070035
Dan Willemsen218f6562015-07-08 18:13:11 -070036 "github.com/google/blueprint"
Colin Cross2465c3d2018-09-28 10:19:18 -070037 "github.com/google/blueprint/bootstrap"
Colin Cross836e3872021-11-09 12:30:59 -080038 "github.com/google/blueprint/pathtools"
Jiyong Park3f627e62024-05-01 16:14:38 +090039 "github.com/google/blueprint/proptools"
Dan Willemsen218f6562015-07-08 18:13:11 -070040)
41
42func init() {
Paul Duffin8c3fec42020-03-04 20:15:08 +000043 RegisterAndroidMkBuildComponents(InitRegistrationContext)
44}
45
46func RegisterAndroidMkBuildComponents(ctx RegistrationContext) {
LaMont Jones0c10e4d2023-05-16 00:58:37 +000047 ctx.RegisterParallelSingletonType("androidmk", AndroidMkSingleton)
Dan Willemsen218f6562015-07-08 18:13:11 -070048}
49
Paul Duffin6c9da042021-03-07 15:44:41 +000050// Enable androidmk support.
51// * Register the singleton
52// * Configure that we are inside make
53var PrepareForTestWithAndroidMk = GroupFixturePreparers(
54 FixtureRegisterWithContext(RegisterAndroidMkBuildComponents),
55 FixtureModifyConfig(SetKatiEnabledForTests),
56)
57
Jaewoong Jung7ef4a902020-11-16 12:50:29 -080058// Deprecated: Use AndroidMkEntriesProvider instead, especially if you're not going to use the
59// Custom function. It's easier to use and test.
Dan Willemsen218f6562015-07-08 18:13:11 -070060type AndroidMkDataProvider interface {
Colin Crossa18e9cf2017-08-10 17:00:19 -070061 AndroidMk() AndroidMkData
Colin Crossce75d2c2016-10-06 16:12:58 -070062 BaseModuleName() string
Dan Willemsen218f6562015-07-08 18:13:11 -070063}
64
65type AndroidMkData struct {
Sasha Smundakb6d23052019-04-01 18:37:36 -070066 Class string
67 SubName string
Jingwen Chen40fd90a2020-06-15 05:24:19 +000068 DistFiles TaggedDistFiles
Sasha Smundakb6d23052019-04-01 18:37:36 -070069 OutputFile OptionalPath
70 Disabled bool
71 Include string
72 Required []string
73 Host_required []string
74 Target_required []string
Dan Willemsen218f6562015-07-08 18:13:11 -070075
Colin Cross0f86d182017-08-10 17:07:28 -070076 Custom func(w io.Writer, name, prefix, moduleDir string, data AndroidMkData)
Dan Willemsen218f6562015-07-08 18:13:11 -070077
Colin Cross27a4b052017-08-10 16:32:23 -070078 Extra []AndroidMkExtraFunc
Colin Cross0f86d182017-08-10 17:07:28 -070079
Jooyung Han2ed99d02020-06-24 23:26:26 +090080 Entries AndroidMkEntries
Dan Willemsen218f6562015-07-08 18:13:11 -070081}
82
Colin Cross27a4b052017-08-10 16:32:23 -070083type AndroidMkExtraFunc func(w io.Writer, outputFile Path)
84
Jaewoong Jung7ef4a902020-11-16 12:50:29 -080085// Interface for modules to declare their Android.mk outputs. Note that every module needs to
86// implement this in order to be included in the final Android-<product_name>.mk output, even if
87// they only need to output the common set of entries without any customizations.
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -070088type AndroidMkEntriesProvider interface {
Jaewoong Jung7ef4a902020-11-16 12:50:29 -080089 // Returns AndroidMkEntries objects that contain all basic info plus extra customization data
90 // if needed. This is the core func to implement.
91 // Note that one can return multiple objects. For example, java_library may return an additional
92 // AndroidMkEntries object for its hostdex sub-module.
Jiyong Park0b0e1b92019-12-03 13:24:29 +090093 AndroidMkEntries() []AndroidMkEntries
Jaewoong Jung7ef4a902020-11-16 12:50:29 -080094 // Modules don't need to implement this as it's already implemented by ModuleBase.
95 // AndroidMkEntries uses BaseModuleName() instead of ModuleName() because certain modules
96 // e.g. Prebuilts, override the Name() func and return modified names.
97 // If a different name is preferred, use SubName or OverrideName in AndroidMkEntries.
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -070098 BaseModuleName() string
99}
100
Jaewoong Jung7ef4a902020-11-16 12:50:29 -0800101// The core data struct that modules use to provide their Android.mk data.
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700102type AndroidMkEntries struct {
Jaewoong Jung7ef4a902020-11-16 12:50:29 -0800103 // Android.mk class string, e.g EXECUTABLES, JAVA_LIBRARIES, ETC
104 Class string
105 // Optional suffix to append to the module name. Useful when a module wants to return multiple
106 // AndroidMkEntries objects. For example, when a java_library returns an additional entry for
107 // its hostdex sub-module, this SubName field is set to "-hostdex" so that it can have a
108 // different name than the parent's.
109 SubName string
110 // If set, this value overrides the base module name. SubName is still appended.
111 OverrideName string
112 // Dist files to output
113 DistFiles TaggedDistFiles
114 // The output file for Kati to process and/or install. If absent, the module is skipped.
115 OutputFile OptionalPath
116 // If true, the module is skipped and does not appear on the final Android-<product name>.mk
117 // file. Useful when a module needs to be skipped conditionally.
118 Disabled bool
Ivan Lozanod06cc742021-11-12 13:27:58 -0500119 // The postprocessing mk file to include, e.g. $(BUILD_SYSTEM)/soong_cc_rust_prebuilt.mk
Jaewoong Jung7ef4a902020-11-16 12:50:29 -0800120 // If not set, $(BUILD_SYSTEM)/prebuilt.mk is used.
121 Include string
122 // Required modules that need to be built and included in the final build output when building
123 // this module.
124 Required []string
125 // Required host modules that need to be built and included in the final build output when
126 // building this module.
127 Host_required []string
128 // Required device modules that need to be built and included in the final build output when
129 // building this module.
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700130 Target_required []string
131
132 header bytes.Buffer
133 footer bytes.Buffer
134
Jaewoong Jung7ef4a902020-11-16 12:50:29 -0800135 // Funcs to append additional Android.mk entries or modify the common ones. Multiple funcs are
136 // accepted so that common logic can be factored out as a shared func.
Jaewoong Junge0dc8df2019-08-27 17:33:16 -0700137 ExtraEntries []AndroidMkExtraEntriesFunc
Jaewoong Jung7ef4a902020-11-16 12:50:29 -0800138 // Funcs to add extra lines to the module's Android.mk output. Unlike AndroidMkExtraEntriesFunc,
139 // which simply sets Make variable values, this can be used for anything since it can write any
140 // Make statements directly to the final Android-*.mk file.
141 // Primarily used to call macros or declare/update Make targets.
Jaewoong Jungb0c127c2019-08-29 14:56:03 -0700142 ExtraFooters []AndroidMkExtraFootersFunc
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700143
Jaewoong Jung7ef4a902020-11-16 12:50:29 -0800144 // A map that holds the up-to-date Make variable values. Can be accessed from tests.
145 EntryMap map[string][]string
146 // A list of EntryMap keys in insertion order. This serves a few purposes:
147 // 1. Prevents churns. Golang map doesn't provide consistent iteration order, so without this,
148 // the outputted Android-*.mk file may change even though there have been no content changes.
149 // 2. Allows modules to refer to other variables, like LOCAL_BAR_VAR := $(LOCAL_FOO_VAR),
150 // without worrying about the variables being mixed up in the actual mk file.
151 // 3. Makes troubleshooting and spotting errors easier.
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700152 entryOrder []string
Trevor Radcliffe90727f42022-03-21 19:34:02 +0000153
154 // Provides data typically stored by Context objects that are commonly needed by
155 //AndroidMkEntries objects.
156 entryContext AndroidMkEntriesContext
157}
158
159type AndroidMkEntriesContext interface {
160 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
Paul Duffinaf970a22020-11-23 23:32:56 +0000357 // If the distFiles created by GenerateTaggedDistFiles contains paths for the
358 // DefaultDistTag then that takes priority so delete any existing paths.
359 if _, ok := amod.distFiles[DefaultDistTag]; ok {
360 delete(availableTaggedDists, DefaultDistTag)
361 }
362
363 // Finally, merge the distFiles created by GenerateTaggedDistFiles.
364 availableTaggedDists = availableTaggedDists.merge(amod.distFiles)
365
Paul Duffin74f05592020-11-25 16:37:46 +0000366 if len(availableTaggedDists) == 0 {
Jingwen Chen7b27ca72020-07-24 09:13:49 +0000367 // Nothing dist-able for this module.
368 return nil
Jingwen Chen40fd90a2020-06-15 05:24:19 +0000369 }
370
Paul Duffin8b0349c2020-11-26 14:33:21 +0000371 // Collate the contributions this module makes to the dist.
372 distContributions := &distContributions{}
373
Bob Badour4660a982022-09-12 16:06:03 -0700374 if !exemptFromRequiredApplicableLicensesProperty(mod.(Module)) {
375 distContributions.licenseMetadataFile = amod.licenseMetadataFile
376 }
Bob Badour51804382022-04-13 11:27:19 -0700377
Jingwen Chen40fd90a2020-06-15 05:24:19 +0000378 // Iterate over this module's dist structs, merged from the dist and dists properties.
379 for _, dist := range amod.Dists() {
380 // Get the list of goals this dist should be enabled for. e.g. sdk, droidcore
381 goals := strings.Join(dist.Targets, " ")
382
383 // Get the tag representing the output files to be dist'd. e.g. ".jar", ".proguard_map"
384 var tag string
385 if dist.Tag == nil {
386 // If the dist struct does not specify a tag, use the default output files tag.
Paul Duffin74f05592020-11-25 16:37:46 +0000387 tag = DefaultDistTag
Jingwen Chen40fd90a2020-06-15 05:24:19 +0000388 } else {
389 tag = *dist.Tag
390 }
391
392 // Get the paths of the output files to be dist'd, represented by the tag.
393 // Can be an empty list.
394 tagPaths := availableTaggedDists[tag]
395 if len(tagPaths) == 0 {
396 // Nothing to dist for this tag, continue to the next dist.
397 continue
398 }
399
400 if len(tagPaths) > 1 && (dist.Dest != nil || dist.Suffix != nil) {
Paul Duffin74f05592020-11-25 16:37:46 +0000401 errorMessage := "%s: Cannot apply dest/suffix for more than one dist " +
402 "file for %q goals tag %q in module %s. The list of dist files, " +
Jingwen Chen40fd90a2020-06-15 05:24:19 +0000403 "which should have a single element, is:\n%s"
Paul Duffin74f05592020-11-25 16:37:46 +0000404 panic(fmt.Errorf(errorMessage, mod, goals, tag, name, tagPaths))
Jingwen Chen40fd90a2020-06-15 05:24:19 +0000405 }
406
Paul Duffin8b0349c2020-11-26 14:33:21 +0000407 copiesForGoals := distContributions.getCopiesForGoals(goals)
Jingwen Chen40fd90a2020-06-15 05:24:19 +0000408
Paul Duffin8b0349c2020-11-26 14:33:21 +0000409 // Iterate over each path adding a copy instruction to copiesForGoals
Jingwen Chen40fd90a2020-06-15 05:24:19 +0000410 for _, path := range tagPaths {
411 // It's possible that the Path is nil from errant modules. Be defensive here.
412 if path == nil {
413 tagName := "default" // for error message readability
414 if dist.Tag != nil {
415 tagName = *dist.Tag
416 }
417 panic(fmt.Errorf("Dist file should not be nil for the %s tag in %s", tagName, name))
418 }
419
420 dest := filepath.Base(path.String())
421
422 if dist.Dest != nil {
423 var err error
424 if dest, err = validateSafePath(*dist.Dest); err != nil {
425 // This was checked in ModuleBase.GenerateBuildActions
426 panic(err)
427 }
428 }
429
Trevor Radcliffe90727f42022-03-21 19:34:02 +0000430 ext := filepath.Ext(dest)
431 suffix := ""
Jingwen Chen40fd90a2020-06-15 05:24:19 +0000432 if dist.Suffix != nil {
Trevor Radcliffe90727f42022-03-21 19:34:02 +0000433 suffix = *dist.Suffix
434 }
435
436 productString := ""
437 if dist.Append_artifact_with_product != nil && *dist.Append_artifact_with_product {
438 productString = fmt.Sprintf("_%s", a.entryContext.Config().DeviceProduct())
439 }
440
441 if suffix != "" || productString != "" {
442 dest = strings.TrimSuffix(dest, ext) + suffix + productString + ext
Jingwen Chen40fd90a2020-06-15 05:24:19 +0000443 }
444
445 if dist.Dir != nil {
446 var err error
447 if dest, err = validateSafePath(*dist.Dir, dest); err != nil {
448 // This was checked in ModuleBase.GenerateBuildActions
449 panic(err)
450 }
451 }
452
Paul Duffin8b0349c2020-11-26 14:33:21 +0000453 copiesForGoals.addCopyInstruction(path, dest)
454 }
455 }
456
457 return distContributions
458}
459
460// generateDistContributionsForMake generates make rules that will generate the
461// dist according to the instructions in the supplied distContribution.
462func generateDistContributionsForMake(distContributions *distContributions) []string {
463 var ret []string
464 for _, d := range distContributions.copiesForGoals {
465 ret = append(ret, fmt.Sprintf(".PHONY: %s\n", d.goals))
466 // Create dist-for-goals calls for each of the copy instructions.
467 for _, c := range d.copies {
Bob Badour4660a982022-09-12 16:06:03 -0700468 if distContributions.licenseMetadataFile != nil {
469 ret = append(
470 ret,
471 fmt.Sprintf("$(if $(strip $(ALL_TARGETS.%s.META_LIC)),,$(eval ALL_TARGETS.%s.META_LIC := %s))\n",
472 c.from.String(), c.from.String(), distContributions.licenseMetadataFile.String()))
473 }
Bob Badour51804382022-04-13 11:27:19 -0700474 ret = append(
475 ret,
Paul Duffin8b0349c2020-11-26 14:33:21 +0000476 fmt.Sprintf("$(call dist-for-goals,%s,%s:%s)\n", d.goals, c.from.String(), c.dest))
Jingwen Chen40fd90a2020-06-15 05:24:19 +0000477 }
478 }
479
480 return ret
481}
482
Paul Duffin8b0349c2020-11-26 14:33:21 +0000483// Compute the list of Make strings to declare phony goals and dist-for-goals
484// calls from the module's dist and dists properties.
485func (a *AndroidMkEntries) GetDistForGoals(mod blueprint.Module) []string {
486 distContributions := a.getDistContributions(mod)
487 if distContributions == nil {
488 return nil
489 }
490
491 return generateDistContributionsForMake(distContributions)
492}
493
Jaewoong Jung7ef4a902020-11-16 12:50:29 -0800494// fillInEntries goes through the common variable processing and calls the extra data funcs to
495// generate and fill in AndroidMkEntries's in-struct data, ready to be flushed to a file.
Colin Crossaa255532020-07-03 13:18:24 -0700496type fillInEntriesContext interface {
497 ModuleDir(module blueprint.Module) string
Cole Faust39aabe92023-02-23 16:57:43 -0800498 ModuleSubDir(module blueprint.Module) string
Colin Crossaa255532020-07-03 13:18:24 -0700499 Config() Config
Yu Liu663e4502024-08-12 18:23:59 +0000500 otherModuleProvider(module blueprint.Module, provider blueprint.AnyProviderKey) (any, bool)
Sasha Smundak5c4729d2022-12-01 10:49:23 -0800501 ModuleType(module blueprint.Module) string
Cole Faust43ddd082024-06-17 12:32:40 -0700502 OtherModulePropertyErrorf(module Module, property string, fmt string, args ...interface{})
Colin Crossaa255532020-07-03 13:18:24 -0700503}
504
505func (a *AndroidMkEntries) fillInEntries(ctx fillInEntriesContext, mod blueprint.Module) {
Trevor Radcliffe90727f42022-03-21 19:34:02 +0000506 a.entryContext = ctx
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700507 a.EntryMap = make(map[string][]string)
Colin Crossf1f763a2021-10-21 16:14:19 -0700508 amod := mod.(Module)
509 base := amod.base()
510 name := base.BaseModuleName()
Colin Cross0477b422020-10-13 18:43:54 -0700511 if a.OverrideName != "" {
512 name = a.OverrideName
513 }
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700514
515 if a.Include == "" {
516 a.Include = "$(BUILD_PREBUILT)"
517 }
Cole Faust43ddd082024-06-17 12:32:40 -0700518 a.Required = append(a.Required, amod.RequiredModuleNames(ctx)...)
Colin Crossf1f763a2021-10-21 16:14:19 -0700519 a.Host_required = append(a.Host_required, amod.HostRequiredModuleNames()...)
520 a.Target_required = append(a.Target_required, amod.TargetRequiredModuleNames()...)
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700521
Jingwen Chen40fd90a2020-06-15 05:24:19 +0000522 for _, distString := range a.GetDistForGoals(mod) {
523 fmt.Fprintf(&a.header, distString)
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700524 }
525
Cole Faust39aabe92023-02-23 16:57:43 -0800526 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 -0700527
528 // Collect make variable assignment entries.
Colin Crossaa255532020-07-03 13:18:24 -0700529 a.SetString("LOCAL_PATH", ctx.ModuleDir(mod))
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700530 a.SetString("LOCAL_MODULE", name+a.SubName)
531 a.SetString("LOCAL_MODULE_CLASS", a.Class)
532 a.SetString("LOCAL_PREBUILT_MODULE_FILE", a.OutputFile.String())
533 a.AddStrings("LOCAL_REQUIRED_MODULES", a.Required...)
534 a.AddStrings("LOCAL_HOST_REQUIRED_MODULES", a.Host_required...)
535 a.AddStrings("LOCAL_TARGET_REQUIRED_MODULES", a.Target_required...)
Wei Li598f92d2023-01-04 17:12:24 -0800536 a.AddStrings("LOCAL_SOONG_MODULE_TYPE", ctx.ModuleType(amod))
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700537
Colin Cross6301c3c2021-09-28 17:40:21 -0700538 // If the install rule was generated by Soong tell Make about it.
Yu Liud46e5ae2024-08-15 18:46:17 +0000539 info := OtherModuleProviderOrDefault(ctx, mod, InstallFilesProvider)
540 if len(info.KatiInstalls) > 0 {
Colin Cross6301c3c2021-09-28 17:40:21 -0700541 // Assume the primary install file is last since it probably needs to depend on any other
542 // installed files. If that is not the case we can add a method to specify the primary
543 // installed file.
Yu Liud46e5ae2024-08-15 18:46:17 +0000544 a.SetPath("LOCAL_SOONG_INSTALLED_MODULE", info.KatiInstalls[len(info.KatiInstalls)-1].to)
545 a.SetString("LOCAL_SOONG_INSTALL_PAIRS", info.KatiInstalls.BuiltInstalled())
546 a.SetPaths("LOCAL_SOONG_INSTALL_SYMLINKS", info.KatiSymlinks.InstallPaths().Paths())
Jiyong Park3f627e62024-05-01 16:14:38 +0900547 } else {
548 // Soong may not have generated the install rule also when `no_full_install: true`.
549 // Mark this module as uninstallable in order to prevent Make from creating an
550 // install rule there.
551 a.SetBoolIfTrue("LOCAL_UNINSTALLABLE_MODULE", proptools.Bool(base.commonProperties.No_full_install))
Colin Cross6301c3c2021-09-28 17:40:21 -0700552 }
553
Yu Liud46e5ae2024-08-15 18:46:17 +0000554 if len(info.TestData) > 0 {
555 a.AddStrings("LOCAL_TEST_DATA", androidMkDataPaths(info.TestData)...)
Colin Cross5c1d5fb2023-11-15 12:39:40 -0800556 }
557
Jiyong Park89e850a2020-04-07 16:37:39 +0900558 if am, ok := mod.(ApexModule); ok {
559 a.SetBoolIfTrue("LOCAL_NOT_AVAILABLE_FOR_PLATFORM", am.NotAvailableForPlatform())
560 }
561
Colin Crossf1f763a2021-10-21 16:14:19 -0700562 archStr := base.Arch().ArchType.String()
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700563 host := false
Colin Crossf1f763a2021-10-21 16:14:19 -0700564 switch base.Os().Class {
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700565 case Host:
Colin Crossf1f763a2021-10-21 16:14:19 -0700566 if base.Target().HostCross {
Jiyong Park1613e552020-09-14 19:43:17 +0900567 // Make cannot identify LOCAL_MODULE_HOST_CROSS_ARCH:= common.
Colin Crossf1f763a2021-10-21 16:14:19 -0700568 if base.Arch().ArchType != Common {
Jiyong Park1613e552020-09-14 19:43:17 +0900569 a.SetString("LOCAL_MODULE_HOST_CROSS_ARCH", archStr)
570 }
571 } else {
572 // Make cannot identify LOCAL_MODULE_HOST_ARCH:= common.
Colin Crossf1f763a2021-10-21 16:14:19 -0700573 if base.Arch().ArchType != Common {
Jiyong Park1613e552020-09-14 19:43:17 +0900574 a.SetString("LOCAL_MODULE_HOST_ARCH", archStr)
575 }
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700576 }
577 host = true
578 case Device:
579 // Make cannot identify LOCAL_MODULE_TARGET_ARCH:= common.
Colin Crossf1f763a2021-10-21 16:14:19 -0700580 if base.Arch().ArchType != Common {
581 if base.Target().NativeBridge {
582 hostArchStr := base.Target().NativeBridgeHostArchName
dimitry1f33e402019-03-26 12:39:31 +0100583 if hostArchStr != "" {
584 a.SetString("LOCAL_MODULE_TARGET_ARCH", hostArchStr)
585 }
586 } else {
587 a.SetString("LOCAL_MODULE_TARGET_ARCH", archStr)
588 }
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700589 }
590
Kelvin Zhang46977252022-04-13 16:41:34 -0700591 if !base.InVendorRamdisk() {
Colin Crossf1f763a2021-10-21 16:14:19 -0700592 a.AddPaths("LOCAL_FULL_INIT_RC", base.initRcPaths)
Yifan Hong919dae12020-12-02 18:55:06 -0800593 }
Colin Crossf1f763a2021-10-21 16:14:19 -0700594 if len(base.vintfFragmentsPaths) > 0 {
595 a.AddPaths("LOCAL_FULL_VINTF_FRAGMENTS", base.vintfFragmentsPaths)
Liz Kammer7b3dc8a2021-04-16 16:41:59 -0400596 }
Colin Crossf1f763a2021-10-21 16:14:19 -0700597 a.SetBoolIfTrue("LOCAL_PROPRIETARY_MODULE", Bool(base.commonProperties.Proprietary))
598 if Bool(base.commonProperties.Vendor) || Bool(base.commonProperties.Soc_specific) {
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700599 a.SetString("LOCAL_VENDOR_MODULE", "true")
600 }
Colin Crossf1f763a2021-10-21 16:14:19 -0700601 a.SetBoolIfTrue("LOCAL_ODM_MODULE", Bool(base.commonProperties.Device_specific))
602 a.SetBoolIfTrue("LOCAL_PRODUCT_MODULE", Bool(base.commonProperties.Product_specific))
603 a.SetBoolIfTrue("LOCAL_SYSTEM_EXT_MODULE", Bool(base.commonProperties.System_ext_specific))
604 if base.commonProperties.Owner != nil {
605 a.SetString("LOCAL_MODULE_OWNER", *base.commonProperties.Owner)
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700606 }
607 }
608
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700609 if host {
Colin Crossf1f763a2021-10-21 16:14:19 -0700610 makeOs := base.Os().String()
611 if base.Os() == Linux || base.Os() == LinuxBionic || base.Os() == LinuxMusl {
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700612 makeOs = "linux"
613 }
614 a.SetString("LOCAL_MODULE_HOST_OS", makeOs)
615 a.SetString("LOCAL_IS_HOST_MODULE", "true")
616 }
617
618 prefix := ""
Colin Crossf1f763a2021-10-21 16:14:19 -0700619 if base.ArchSpecific() {
620 switch base.Os().Class {
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700621 case Host:
Colin Crossf1f763a2021-10-21 16:14:19 -0700622 if base.Target().HostCross {
Jiyong Park1613e552020-09-14 19:43:17 +0900623 prefix = "HOST_CROSS_"
624 } else {
625 prefix = "HOST_"
626 }
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700627 case Device:
628 prefix = "TARGET_"
629
630 }
631
Colin Crossf1f763a2021-10-21 16:14:19 -0700632 if base.Arch().ArchType != ctx.Config().Targets[base.Os()][0].Arch.ArchType {
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700633 prefix = "2ND_" + prefix
634 }
635 }
Colin Crossaa255532020-07-03 13:18:24 -0700636
Yu Liu663e4502024-08-12 18:23:59 +0000637 if licenseMetadata, ok := OtherModuleProvider(ctx, mod, LicenseMetadataProvider); ok {
Colin Cross4acaea92021-12-10 23:05:02 +0000638 a.SetPath("LOCAL_SOONG_LICENSE_METADATA", licenseMetadata.LicenseMetadataPath)
639 }
640
Yu Liu663e4502024-08-12 18:23:59 +0000641 if _, ok := OtherModuleProvider(ctx, mod, ModuleInfoJSONProvider); ok {
Colin Crossd6fd0132023-11-06 13:54:06 -0800642 a.SetBool("LOCAL_SOONG_MODULE_INFO_JSON", true)
643 }
644
Colin Crossaa255532020-07-03 13:18:24 -0700645 extraCtx := &androidMkExtraEntriesContext{
646 ctx: ctx,
647 mod: mod,
648 }
649
Jaewoong Junge0dc8df2019-08-27 17:33:16 -0700650 for _, extra := range a.ExtraEntries {
Colin Crossaa255532020-07-03 13:18:24 -0700651 extra(extraCtx, a)
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700652 }
653
654 // Write to footer.
655 fmt.Fprintln(&a.footer, "include "+a.Include)
Colin Crossaa255532020-07-03 13:18:24 -0700656 blueprintDir := ctx.ModuleDir(mod)
Jaewoong Jungb0c127c2019-08-29 14:56:03 -0700657 for _, footerFunc := range a.ExtraFooters {
Jaewoong Jung02b11a62020-12-07 10:23:54 -0800658 footerFunc(&a.footer, name, prefix, blueprintDir)
Jaewoong Jungb0c127c2019-08-29 14:56:03 -0700659 }
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700660}
661
Colin Crossd6fd0132023-11-06 13:54:06 -0800662func (a *AndroidMkEntries) disabled() bool {
663 return a.Disabled || !a.OutputFile.Valid()
664}
665
Jaewoong Jung7ef4a902020-11-16 12:50:29 -0800666// write flushes the AndroidMkEntries's in-struct data populated by AndroidMkEntries into the
667// given Writer object.
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700668func (a *AndroidMkEntries) write(w io.Writer) {
Colin Crossd6fd0132023-11-06 13:54:06 -0800669 if a.disabled() {
Jaewoong Jungb0c127c2019-08-29 14:56:03 -0700670 return
671 }
672
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700673 w.Write(a.header.Bytes())
674 for _, name := range a.entryOrder {
Sasha Smundakdcb61292022-12-08 10:41:33 -0800675 AndroidMkEmitAssignList(w, name, a.EntryMap[name])
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700676 }
677 w.Write(a.footer.Bytes())
678}
679
Jaewoong Jungb0c127c2019-08-29 14:56:03 -0700680func (a *AndroidMkEntries) FooterLinesForTests() []string {
681 return strings.Split(string(a.footer.Bytes()), "\n")
682}
683
Jaewoong Jung7ef4a902020-11-16 12:50:29 -0800684// AndroidMkSingleton is a singleton to collect Android.mk data from all modules and dump them into
685// the final Android-<product_name>.mk file output.
Colin Cross0875c522017-11-28 17:34:01 -0800686func AndroidMkSingleton() Singleton {
Dan Willemsen218f6562015-07-08 18:13:11 -0700687 return &androidMkSingleton{}
688}
689
690type androidMkSingleton struct{}
691
Colin Cross0875c522017-11-28 17:34:01 -0800692func (c *androidMkSingleton) GenerateBuildActions(ctx SingletonContext) {
Jaewoong Jung7ef4a902020-11-16 12:50:29 -0800693 // Skip if Soong wasn't invoked from Make.
Jingwen Chencda22c92020-11-23 00:22:30 -0500694 if !ctx.Config().KatiEnabled() {
Dan Willemsen5ba07e82015-12-11 13:51:06 -0800695 return
696 }
697
Colin Cross2465c3d2018-09-28 10:19:18 -0700698 var androidMkModulesList []blueprint.Module
Colin Cross4f6e4e62016-01-11 12:55:55 -0800699
Colin Cross2465c3d2018-09-28 10:19:18 -0700700 ctx.VisitAllModulesBlueprint(func(module blueprint.Module) {
Colin Cross0875c522017-11-28 17:34:01 -0800701 androidMkModulesList = append(androidMkModulesList, module)
Colin Cross4f6e4e62016-01-11 12:55:55 -0800702 })
Dan Willemsen218f6562015-07-08 18:13:11 -0700703
Jaewoong Jung7ef4a902020-11-16 12:50:29 -0800704 // Sort the module list by the module names to eliminate random churns, which may erroneously
705 // invoke additional build processes.
Colin Cross1ad81422019-01-14 12:47:35 -0800706 sort.SliceStable(androidMkModulesList, func(i, j int) bool {
707 return ctx.ModuleName(androidMkModulesList[i]) < ctx.ModuleName(androidMkModulesList[j])
708 })
Colin Crossd779da42015-12-17 18:00:23 -0800709
Dan Willemsen45133ac2018-03-09 21:22:06 -0800710 transMk := PathForOutput(ctx, "Android"+String(ctx.Config().productVariables.Make_suffix)+".mk")
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700711 if ctx.Failed() {
712 return
713 }
Dan Willemsen218f6562015-07-08 18:13:11 -0700714
Colin Crossd6fd0132023-11-06 13:54:06 -0800715 moduleInfoJSON := PathForOutput(ctx, "module-info"+String(ctx.Config().productVariables.Make_suffix)+".json")
716
717 err := translateAndroidMk(ctx, absolutePath(transMk.String()), moduleInfoJSON, androidMkModulesList)
Dan Willemsen218f6562015-07-08 18:13:11 -0700718 if err != nil {
719 ctx.Errorf(err.Error())
720 }
721
Colin Cross0875c522017-11-28 17:34:01 -0800722 ctx.Build(pctx, BuildParams{
723 Rule: blueprint.Phony,
724 Output: transMk,
Dan Willemsen218f6562015-07-08 18:13:11 -0700725 })
726}
727
Colin Crossd6fd0132023-11-06 13:54:06 -0800728func translateAndroidMk(ctx SingletonContext, absMkFile string, moduleInfoJSONPath WritablePath, mods []blueprint.Module) error {
Dan Willemsen218f6562015-07-08 18:13:11 -0700729 buf := &bytes.Buffer{}
730
Colin Crossd6fd0132023-11-06 13:54:06 -0800731 var moduleInfoJSONs []*ModuleInfoJSON
732
Dan Willemsen97750522016-02-09 17:43:51 -0800733 fmt.Fprintln(buf, "LOCAL_MODULE_MAKEFILE := $(lastword $(MAKEFILE_LIST))")
Dan Willemsen218f6562015-07-08 18:13:11 -0700734
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800735 typeStats := make(map[string]int)
Dan Willemsen218f6562015-07-08 18:13:11 -0700736 for _, mod := range mods {
Colin Crossd6fd0132023-11-06 13:54:06 -0800737 err := translateAndroidMkModule(ctx, buf, &moduleInfoJSONs, mod)
Dan Willemsen218f6562015-07-08 18:13:11 -0700738 if err != nil {
Colin Cross836e3872021-11-09 12:30:59 -0800739 os.Remove(absMkFile)
Dan Willemsen218f6562015-07-08 18:13:11 -0700740 return err
741 }
Dan Willemsen70e17fa2016-07-25 16:00:20 -0700742
Colin Cross2465c3d2018-09-28 10:19:18 -0700743 if amod, ok := mod.(Module); ok && ctx.PrimaryModule(amod) == amod {
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800744 typeStats[ctx.ModuleType(amod)] += 1
Dan Willemsen70e17fa2016-07-25 16:00:20 -0700745 }
746 }
747
748 keys := []string{}
749 fmt.Fprintln(buf, "\nSTATS.SOONG_MODULE_TYPE :=")
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800750 for k := range typeStats {
Dan Willemsen70e17fa2016-07-25 16:00:20 -0700751 keys = append(keys, k)
752 }
753 sort.Strings(keys)
754 for _, mod_type := range keys {
755 fmt.Fprintln(buf, "STATS.SOONG_MODULE_TYPE +=", mod_type)
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800756 fmt.Fprintf(buf, "STATS.SOONG_MODULE_TYPE.%s := %d\n", mod_type, typeStats[mod_type])
Dan Willemsen218f6562015-07-08 18:13:11 -0700757 }
758
Colin Crossd6fd0132023-11-06 13:54:06 -0800759 err := pathtools.WriteFileIfChanged(absMkFile, buf.Bytes(), 0666)
760 if err != nil {
761 return err
762 }
763
764 return writeModuleInfoJSON(ctx, moduleInfoJSONs, moduleInfoJSONPath)
Dan Willemsen218f6562015-07-08 18:13:11 -0700765}
766
Colin Crossd6fd0132023-11-06 13:54:06 -0800767func writeModuleInfoJSON(ctx SingletonContext, moduleInfoJSONs []*ModuleInfoJSON, moduleInfoJSONPath WritablePath) error {
768 moduleInfoJSONBuf := &strings.Builder{}
769 moduleInfoJSONBuf.WriteString("[")
770 for i, moduleInfoJSON := range moduleInfoJSONs {
771 if i != 0 {
772 moduleInfoJSONBuf.WriteString(",\n")
773 }
774 moduleInfoJSONBuf.WriteString("{")
775 moduleInfoJSONBuf.WriteString(strconv.Quote(moduleInfoJSON.core.RegisterName))
776 moduleInfoJSONBuf.WriteString(":")
777 err := encodeModuleInfoJSON(moduleInfoJSONBuf, moduleInfoJSON)
778 moduleInfoJSONBuf.WriteString("}")
779 if err != nil {
780 return err
781 }
782 }
783 moduleInfoJSONBuf.WriteString("]")
784 WriteFileRule(ctx, moduleInfoJSONPath, moduleInfoJSONBuf.String())
785 return nil
786}
787
788func translateAndroidMkModule(ctx SingletonContext, w io.Writer, moduleInfoJSONs *[]*ModuleInfoJSON, mod blueprint.Module) error {
Colin Cross953d3a22018-09-05 16:23:54 -0700789 defer func() {
790 if r := recover(); r != nil {
791 panic(fmt.Errorf("%s in translateAndroidMkModule for module %s variant %s",
792 r, ctx.ModuleName(mod), ctx.ModuleSubDir(mod)))
793 }
794 }()
795
Bob Badourb4999222021-01-07 03:34:31 +0000796 // Additional cases here require review for correct license propagation to make.
Colin Crossd6fd0132023-11-06 13:54:06 -0800797 var err error
Colin Cross2465c3d2018-09-28 10:19:18 -0700798 switch x := mod.(type) {
799 case AndroidMkDataProvider:
Colin Crossd6fd0132023-11-06 13:54:06 -0800800 err = translateAndroidModule(ctx, w, moduleInfoJSONs, mod, x)
Colin Cross2465c3d2018-09-28 10:19:18 -0700801 case bootstrap.GoBinaryTool:
Colin Crossd6fd0132023-11-06 13:54:06 -0800802 err = translateGoBinaryModule(ctx, w, mod, x)
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700803 case AndroidMkEntriesProvider:
Colin Crossd6fd0132023-11-06 13:54:06 -0800804 err = translateAndroidMkEntriesModule(ctx, w, moduleInfoJSONs, mod, x)
Colin Cross2465c3d2018-09-28 10:19:18 -0700805 default:
Bob Badourb4999222021-01-07 03:34:31 +0000806 // Not exported to make so no make variables to set.
Dan Willemsen218f6562015-07-08 18:13:11 -0700807 }
Colin Crossd6fd0132023-11-06 13:54:06 -0800808
809 if err != nil {
810 return err
811 }
812
813 return err
Colin Cross2465c3d2018-09-28 10:19:18 -0700814}
815
Jaewoong Jung7ef4a902020-11-16 12:50:29 -0800816// A simple, special Android.mk entry output func to make it possible to build blueprint tools using
817// m by making them phony targets.
Colin Cross2465c3d2018-09-28 10:19:18 -0700818func translateGoBinaryModule(ctx SingletonContext, w io.Writer, mod blueprint.Module,
819 goBinary bootstrap.GoBinaryTool) error {
820
821 name := ctx.ModuleName(mod)
822 fmt.Fprintln(w, ".PHONY:", name)
823 fmt.Fprintln(w, name+":", goBinary.InstallPath())
824 fmt.Fprintln(w, "")
Bob Badourb4999222021-01-07 03:34:31 +0000825 // Assuming no rules in make include go binaries in distributables.
826 // If the assumption is wrong, make will fail to build without the necessary .meta_lic and .meta_module files.
827 // In that case, add the targets and rules here to build a .meta_lic file for `name` and a .meta_module for
828 // `goBinary.InstallPath()` pointing to the `name`.meta_lic file.
Colin Cross2465c3d2018-09-28 10:19:18 -0700829
830 return nil
831}
832
Colin Crossaa255532020-07-03 13:18:24 -0700833func (data *AndroidMkData) fillInData(ctx fillInEntriesContext, mod blueprint.Module) {
Jooyung Han12df5fb2019-07-11 16:18:47 +0900834 // Get the preamble content through AndroidMkEntries logic.
Jooyung Han2ed99d02020-06-24 23:26:26 +0900835 data.Entries = AndroidMkEntries{
Jooyung Han12df5fb2019-07-11 16:18:47 +0900836 Class: data.Class,
837 SubName: data.SubName,
Jingwen Chen40fd90a2020-06-15 05:24:19 +0000838 DistFiles: data.DistFiles,
Jooyung Han12df5fb2019-07-11 16:18:47 +0900839 OutputFile: data.OutputFile,
840 Disabled: data.Disabled,
841 Include: data.Include,
842 Required: data.Required,
843 Host_required: data.Host_required,
844 Target_required: data.Target_required,
845 }
Colin Crossaa255532020-07-03 13:18:24 -0700846 data.Entries.fillInEntries(ctx, mod)
Jooyung Han12df5fb2019-07-11 16:18:47 +0900847
848 // copy entries back to data since it is used in Custom
Jooyung Han2ed99d02020-06-24 23:26:26 +0900849 data.Required = data.Entries.Required
850 data.Host_required = data.Entries.Host_required
851 data.Target_required = data.Entries.Target_required
Jooyung Han12df5fb2019-07-11 16:18:47 +0900852}
853
Jaewoong Jung7ef4a902020-11-16 12:50:29 -0800854// A support func for the deprecated AndroidMkDataProvider interface. Use AndroidMkEntryProvider
855// instead.
Colin Crossd6fd0132023-11-06 13:54:06 -0800856func translateAndroidModule(ctx SingletonContext, w io.Writer, moduleInfoJSONs *[]*ModuleInfoJSON,
857 mod blueprint.Module, provider AndroidMkDataProvider) error {
Dan Willemsen218f6562015-07-08 18:13:11 -0700858
Colin Cross635c3b02016-05-18 15:37:25 -0700859 amod := mod.(Module).base()
Cole Fausta963b942024-04-11 17:43:00 -0700860 if shouldSkipAndroidMkProcessing(ctx, amod) {
Jeff Gaston088e29e2017-11-29 16:47:17 -0800861 return nil
862 }
863
Colin Cross91825d22017-08-10 16:59:47 -0700864 data := provider.AndroidMk()
Yu Liuddc28332024-08-09 22:48:30 +0000865
Colin Cross53499412017-09-07 13:20:25 -0700866 if data.Include == "" {
867 data.Include = "$(BUILD_PREBUILT)"
868 }
869
Colin Crossaa255532020-07-03 13:18:24 -0700870 data.fillInData(ctx, mod)
LaMont Jonesb5099382024-01-10 23:42:36 +0000871 aconfigUpdateAndroidMkData(ctx, mod.(Module), &data)
Dan Willemsen01a405a2016-06-13 17:19:03 -0700872
Colin Cross0f86d182017-08-10 17:07:28 -0700873 prefix := ""
874 if amod.ArchSpecific() {
875 switch amod.Os().Class {
876 case Host:
Jiyong Park1613e552020-09-14 19:43:17 +0900877 if amod.Target().HostCross {
878 prefix = "HOST_CROSS_"
879 } else {
880 prefix = "HOST_"
881 }
Colin Cross0f86d182017-08-10 17:07:28 -0700882 case Device:
883 prefix = "TARGET_"
Colin Crossa2344662016-03-24 13:14:12 -0700884
Dan Willemsen218f6562015-07-08 18:13:11 -0700885 }
886
Dan Willemsen0ef639b2018-10-10 17:02:29 -0700887 if amod.Arch().ArchType != ctx.Config().Targets[amod.Os()][0].Arch.ArchType {
Colin Cross0f86d182017-08-10 17:07:28 -0700888 prefix = "2ND_" + prefix
889 }
Dan Willemsen218f6562015-07-08 18:13:11 -0700890 }
891
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700892 name := provider.BaseModuleName()
Colin Cross0f86d182017-08-10 17:07:28 -0700893 blueprintDir := filepath.Dir(ctx.BlueprintFile(mod))
894
895 if data.Custom != nil {
Bob Badourb4999222021-01-07 03:34:31 +0000896 // List of module types allowed to use .Custom(...)
897 // Additions to the list require careful review for proper license handling.
Colin Crossaa255532020-07-03 13:18:24 -0700898 switch reflect.TypeOf(mod).String() { // ctx.ModuleType(mod) doesn't work: aidl_interface creates phony without type
Bob Badourb4999222021-01-07 03:34:31 +0000899 case "*aidl.aidlApi": // writes non-custom before adding .phony
900 case "*aidl.aidlMapping": // writes non-custom before adding .phony
901 case "*android.customModule": // appears in tests only
Dan Willemsen9fe14102021-07-13 21:52:04 -0700902 case "*android_sdk.sdkRepoHost": // doesn't go through base_rules
Bob Badourb4999222021-01-07 03:34:31 +0000903 case "*apex.apexBundle": // license properties written
904 case "*bpf.bpf": // license properties written (both for module and objs)
905 case "*genrule.Module": // writes non-custom before adding .phony
906 case "*java.SystemModules": // doesn't go through base_rules
907 case "*java.systemModulesImport": // doesn't go through base_rules
908 case "*phony.phony": // license properties written
Nelson Lif3c70682023-12-20 02:37:52 +0000909 case "*phony.PhonyRule": // writes phony deps and acts like `.PHONY`
Bob Badourb4999222021-01-07 03:34:31 +0000910 case "*selinux.selinuxContextsModule": // license properties written
911 case "*sysprop.syspropLibrary": // license properties written
yangbill66e555c2024-07-29 03:37:12 +0000912 case "*vintf.vintfCompatibilityMatrixRule": // use case like phony
Bob Badourb4999222021-01-07 03:34:31 +0000913 default:
Bob Badour65ee90a2021-09-02 15:33:10 -0700914 if !ctx.Config().IsEnvFalse("ANDROID_REQUIRE_LICENSES") {
Bob Badourb4999222021-01-07 03:34:31 +0000915 return fmt.Errorf("custom make rules not allowed for %q (%q) module %q", ctx.ModuleType(mod), reflect.TypeOf(mod), ctx.ModuleName(mod))
916 }
917 }
Colin Cross0f86d182017-08-10 17:07:28 -0700918 data.Custom(w, name, prefix, blueprintDir, data)
919 } else {
920 WriteAndroidMkData(w, data)
921 }
922
Colin Crossd6fd0132023-11-06 13:54:06 -0800923 if !data.Entries.disabled() {
Yu Liu663e4502024-08-12 18:23:59 +0000924 if moduleInfoJSON, ok := OtherModuleProvider(ctx, mod, ModuleInfoJSONProvider); ok {
Colin Crossd6fd0132023-11-06 13:54:06 -0800925 *moduleInfoJSONs = append(*moduleInfoJSONs, moduleInfoJSON)
926 }
927 }
928
Colin Cross0f86d182017-08-10 17:07:28 -0700929 return nil
930}
931
Jaewoong Jung7ef4a902020-11-16 12:50:29 -0800932// A support func for the deprecated AndroidMkDataProvider interface. Use AndroidMkEntryProvider
933// instead.
Colin Cross0f86d182017-08-10 17:07:28 -0700934func WriteAndroidMkData(w io.Writer, data AndroidMkData) {
Colin Crossd6fd0132023-11-06 13:54:06 -0800935 if data.Entries.disabled() {
Colin Cross0f86d182017-08-10 17:07:28 -0700936 return
937 }
938
Jooyung Han2ed99d02020-06-24 23:26:26 +0900939 // write preamble via Entries
940 data.Entries.footer = bytes.Buffer{}
941 data.Entries.write(w)
Colin Cross0f86d182017-08-10 17:07:28 -0700942
Colin Crossca860ac2016-01-04 14:34:37 -0800943 for _, extra := range data.Extra {
Colin Cross27a4b052017-08-10 16:32:23 -0700944 extra(w, data.OutputFile.Path())
Dan Willemsen97750522016-02-09 17:43:51 -0800945 }
946
Colin Cross53499412017-09-07 13:20:25 -0700947 fmt.Fprintln(w, "include "+data.Include)
Dan Willemsen218f6562015-07-08 18:13:11 -0700948}
Sasha Smundakb6d23052019-04-01 18:37:36 -0700949
Colin Crossd6fd0132023-11-06 13:54:06 -0800950func translateAndroidMkEntriesModule(ctx SingletonContext, w io.Writer, moduleInfoJSONs *[]*ModuleInfoJSON,
951 mod blueprint.Module, provider AndroidMkEntriesProvider) error {
Cole Fausta963b942024-04-11 17:43:00 -0700952 if shouldSkipAndroidMkProcessing(ctx, mod.(Module).base()) {
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700953 return nil
Sasha Smundakb6d23052019-04-01 18:37:36 -0700954 }
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700955
Colin Crossd6fd0132023-11-06 13:54:06 -0800956 entriesList := provider.AndroidMkEntries()
LaMont Jonesb5099382024-01-10 23:42:36 +0000957 aconfigUpdateAndroidMkEntries(ctx, mod.(Module), &entriesList)
Colin Crossd6fd0132023-11-06 13:54:06 -0800958
Bob Badourb4999222021-01-07 03:34:31 +0000959 // Any new or special cases here need review to verify correct propagation of license information.
Colin Crossd6fd0132023-11-06 13:54:06 -0800960 for _, entries := range entriesList {
Colin Crossaa255532020-07-03 13:18:24 -0700961 entries.fillInEntries(ctx, mod)
Jiyong Park0b0e1b92019-12-03 13:24:29 +0900962 entries.write(w)
963 }
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700964
Colin Crossd6fd0132023-11-06 13:54:06 -0800965 if len(entriesList) > 0 && !entriesList[0].disabled() {
Yu Liu663e4502024-08-12 18:23:59 +0000966 if moduleInfoJSON, ok := OtherModuleProvider(ctx, mod, ModuleInfoJSONProvider); ok {
Colin Crossd6fd0132023-11-06 13:54:06 -0800967 *moduleInfoJSONs = append(*moduleInfoJSONs, moduleInfoJSON)
968 }
969 }
970
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700971 return nil
972}
973
Cole Fausta963b942024-04-11 17:43:00 -0700974func ShouldSkipAndroidMkProcessing(ctx ConfigAndErrorContext, module Module) bool {
975 return shouldSkipAndroidMkProcessing(ctx, module.base())
Chih-Hung Hsieh80783772021-10-11 16:46:56 -0700976}
977
Cole Fausta963b942024-04-11 17:43:00 -0700978func shouldSkipAndroidMkProcessing(ctx ConfigAndErrorContext, module *ModuleBase) bool {
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700979 if !module.commonProperties.NamespaceExportedToMake {
980 // TODO(jeffrygaston) do we want to validate that there are no modules being
981 // exported to Kati that depend on this module?
982 return true
Sasha Smundakb6d23052019-04-01 18:37:36 -0700983 }
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700984
Dan Willemsendef7b5d2021-10-17 00:22:33 -0700985 // On Mac, only expose host darwin modules to Make, as that's all we claim to support.
986 // In reality, some of them depend on device-built (Java) modules, so we can't disable all
987 // device modules in Soong, but we can hide them from Make (and thus the build user interface)
988 if runtime.GOOS == "darwin" && module.Os() != Darwin {
989 return true
990 }
991
Dan Willemsen8528f4e2021-10-19 00:22:06 -0700992 // Only expose the primary Darwin target, as Make does not understand Darwin+Arm64
993 if module.Os() == Darwin && module.Target().HostCross {
994 return true
995 }
996
Cole Fausta963b942024-04-11 17:43:00 -0700997 return !module.Enabled(ctx) ||
Colin Crossa9c8c9f2020-12-16 10:20:23 -0800998 module.commonProperties.HideFromMake ||
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700999 // Make does not understand LinuxBionic
Colin Cross9a027be2022-06-24 18:45:58 -07001000 module.Os() == LinuxBionic ||
1001 // Make does not understand LinuxMusl, except when we are building with USE_HOST_MUSL=true
1002 // and all host binaries are LinuxMusl
1003 (module.Os() == LinuxMusl && module.Target().HostCross)
Sasha Smundakb6d23052019-04-01 18:37:36 -07001004}
Dan Shi31949122020-09-21 12:11:02 -07001005
Jaewoong Jung7ef4a902020-11-16 12:50:29 -08001006// A utility func to format LOCAL_TEST_DATA outputs. See the comments on DataPath to understand how
1007// to use this func.
Colin Cross5c1d5fb2023-11-15 12:39:40 -08001008func androidMkDataPaths(data []DataPath) []string {
Dan Shi31949122020-09-21 12:11:02 -07001009 var testFiles []string
1010 for _, d := range data {
1011 rel := d.SrcPath.Rel()
Colin Cross5c1d5fb2023-11-15 12:39:40 -08001012 if d.WithoutRel {
1013 rel = d.SrcPath.Base()
1014 }
Dan Shi31949122020-09-21 12:11:02 -07001015 path := d.SrcPath.String()
Jaewoong Jung7ef4a902020-11-16 12:50:29 -08001016 // LOCAL_TEST_DATA requires the rel portion of the path to be removed from the path.
Dan Shi31949122020-09-21 12:11:02 -07001017 if !strings.HasSuffix(path, rel) {
1018 panic(fmt.Errorf("path %q does not end with %q", path, rel))
1019 }
1020 path = strings.TrimSuffix(path, rel)
1021 testFileString := path + ":" + rel
1022 if len(d.RelativeInstallPath) > 0 {
1023 testFileString += ":" + d.RelativeInstallPath
1024 }
1025 testFiles = append(testFiles, testFileString)
1026 }
1027 return testFiles
1028}
Sasha Smundakdcb61292022-12-08 10:41:33 -08001029
1030// AndroidMkEmitAssignList emits the line
1031//
1032// VAR := ITEM ...
1033//
1034// Items are the elements to the given set of lists
1035// If all the passed lists are empty, no line will be emitted
1036func AndroidMkEmitAssignList(w io.Writer, varName string, lists ...[]string) {
1037 doPrint := false
1038 for _, l := range lists {
1039 if doPrint = len(l) > 0; doPrint {
1040 break
1041 }
1042 }
1043 if !doPrint {
1044 return
1045 }
1046 fmt.Fprint(w, varName, " :=")
1047 for _, l := range lists {
1048 for _, item := range l {
1049 fmt.Fprint(w, " ", item)
1050 }
1051 }
1052 fmt.Fprintln(w)
1053}