blob: 0a366e14c08cac4cffb1635737efc19b2ed7532c [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"
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 {
159 Config() Config
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700160}
161
Colin Crossaa255532020-07-03 13:18:24 -0700162type AndroidMkExtraEntriesContext interface {
Colin Cross3c0a83d2023-12-12 14:13:26 -0800163 Provider(provider blueprint.AnyProviderKey) (any, bool)
Colin Crossaa255532020-07-03 13:18:24 -0700164}
165
166type androidMkExtraEntriesContext struct {
167 ctx fillInEntriesContext
168 mod blueprint.Module
169}
170
Colin Cross3c0a83d2023-12-12 14:13:26 -0800171func (a *androidMkExtraEntriesContext) Provider(provider blueprint.AnyProviderKey) (any, bool) {
172 return a.ctx.moduleProvider(a.mod, provider)
Colin Crossaa255532020-07-03 13:18:24 -0700173}
174
175type AndroidMkExtraEntriesFunc func(ctx AndroidMkExtraEntriesContext, entries *AndroidMkEntries)
Jaewoong Jung02b11a62020-12-07 10:23:54 -0800176type AndroidMkExtraFootersFunc func(w io.Writer, name, prefix, moduleDir string)
Jaewoong Junge0dc8df2019-08-27 17:33:16 -0700177
Jaewoong Jung7ef4a902020-11-16 12:50:29 -0800178// Utility funcs to manipulate Android.mk variable entries.
179
180// SetString sets a Make variable with the given name to the given value.
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700181func (a *AndroidMkEntries) SetString(name, value string) {
182 if _, ok := a.EntryMap[name]; !ok {
183 a.entryOrder = append(a.entryOrder, name)
184 }
185 a.EntryMap[name] = []string{value}
186}
187
Jaewoong Jung7ef4a902020-11-16 12:50:29 -0800188// SetPath sets a Make variable with the given name to the given path string.
Jaewoong Jung9a1e8bd2019-09-04 20:17:54 -0700189func (a *AndroidMkEntries) SetPath(name string, path Path) {
190 if _, ok := a.EntryMap[name]; !ok {
191 a.entryOrder = append(a.entryOrder, name)
192 }
193 a.EntryMap[name] = []string{path.String()}
194}
195
Jaewoong Jung7ef4a902020-11-16 12:50:29 -0800196// SetOptionalPath sets a Make variable with the given name to the given path string if it is valid.
197// It is a no-op if the given path is invalid.
Colin Crossc0efd1d2020-07-03 11:56:24 -0700198func (a *AndroidMkEntries) SetOptionalPath(name string, path OptionalPath) {
199 if path.Valid() {
200 a.SetPath(name, path.Path())
201 }
202}
203
Jaewoong Jung7ef4a902020-11-16 12:50:29 -0800204// AddPath appends the given path string to a Make variable with the given name.
Colin Crossc0efd1d2020-07-03 11:56:24 -0700205func (a *AndroidMkEntries) AddPath(name string, path Path) {
206 if _, ok := a.EntryMap[name]; !ok {
207 a.entryOrder = append(a.entryOrder, name)
208 }
209 a.EntryMap[name] = append(a.EntryMap[name], path.String())
210}
211
Jaewoong Jung7ef4a902020-11-16 12:50:29 -0800212// AddOptionalPath appends the given path string to a Make variable with the given name if it is
213// valid. It is a no-op if the given path is invalid.
Colin Crossc0efd1d2020-07-03 11:56:24 -0700214func (a *AndroidMkEntries) AddOptionalPath(name string, path OptionalPath) {
215 if path.Valid() {
216 a.AddPath(name, path.Path())
217 }
218}
219
Jaewoong Jung7ef4a902020-11-16 12:50:29 -0800220// SetPaths sets a Make variable with the given name to a slice of the given path strings.
Colin Cross08dca382020-07-21 20:31:17 -0700221func (a *AndroidMkEntries) SetPaths(name string, paths Paths) {
222 if _, ok := a.EntryMap[name]; !ok {
223 a.entryOrder = append(a.entryOrder, name)
224 }
225 a.EntryMap[name] = paths.Strings()
226}
227
Jaewoong Jung7ef4a902020-11-16 12:50:29 -0800228// SetOptionalPaths sets a Make variable with the given name to a slice of the given path strings
229// only if there are a non-zero amount of paths.
Colin Cross08dca382020-07-21 20:31:17 -0700230func (a *AndroidMkEntries) SetOptionalPaths(name string, paths Paths) {
231 if len(paths) > 0 {
232 a.SetPaths(name, paths)
233 }
234}
235
Jaewoong Jung7ef4a902020-11-16 12:50:29 -0800236// AddPaths appends the given path strings to a Make variable with the given name.
Colin Cross08dca382020-07-21 20:31:17 -0700237func (a *AndroidMkEntries) AddPaths(name string, paths Paths) {
238 if _, ok := a.EntryMap[name]; !ok {
239 a.entryOrder = append(a.entryOrder, name)
240 }
241 a.EntryMap[name] = append(a.EntryMap[name], paths.Strings()...)
242}
243
Jaewoong Jung7ef4a902020-11-16 12:50:29 -0800244// SetBoolIfTrue sets a Make variable with the given name to true if the given flag is true.
245// It is a no-op if the given flag is false.
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700246func (a *AndroidMkEntries) SetBoolIfTrue(name string, flag bool) {
247 if flag {
248 if _, ok := a.EntryMap[name]; !ok {
249 a.entryOrder = append(a.entryOrder, name)
250 }
251 a.EntryMap[name] = []string{"true"}
252 }
253}
254
Jaewoong Jung7ef4a902020-11-16 12:50:29 -0800255// SetBool sets a Make variable with the given name to if the given bool flag value.
Jaewoong Jung9a1e8bd2019-09-04 20:17:54 -0700256func (a *AndroidMkEntries) SetBool(name string, flag bool) {
257 if _, ok := a.EntryMap[name]; !ok {
258 a.entryOrder = append(a.entryOrder, name)
259 }
260 if flag {
261 a.EntryMap[name] = []string{"true"}
262 } else {
263 a.EntryMap[name] = []string{"false"}
264 }
265}
266
Jaewoong Jung7ef4a902020-11-16 12:50:29 -0800267// AddStrings appends the given strings to a Make variable with the given name.
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700268func (a *AndroidMkEntries) AddStrings(name string, value ...string) {
269 if len(value) == 0 {
270 return
271 }
272 if _, ok := a.EntryMap[name]; !ok {
273 a.entryOrder = append(a.entryOrder, name)
274 }
275 a.EntryMap[name] = append(a.EntryMap[name], value...)
276}
277
Liz Kammer57f5b332020-11-24 12:42:58 -0800278// AddCompatibilityTestSuites adds the supplied test suites to the EntryMap, with special handling
Tongbo Liuc5f7b962024-01-04 09:03:35 +0000279// for partial MTS and MCTS test suites.
Liz Kammer57f5b332020-11-24 12:42:58 -0800280func (a *AndroidMkEntries) AddCompatibilityTestSuites(suites ...string) {
Tongbo Liuc5f7b962024-01-04 09:03:35 +0000281 // M(C)TS supports a full test suite and partial per-module MTS test suites, with naming mts-${MODULE}.
282 // To reduce repetition, if we find a partial M(C)TS test suite without an full M(C)TS test suite,
Liz Kammer57f5b332020-11-24 12:42:58 -0800283 // we add the full test suite to our list.
284 if PrefixInList(suites, "mts-") && !InList("mts", suites) {
285 suites = append(suites, "mts")
286 }
Tongbo Liuc5f7b962024-01-04 09:03:35 +0000287 if PrefixInList(suites, "mcts-") && !InList("mcts", suites) {
288 suites = append(suites, "mcts")
289 }
Liz Kammer57f5b332020-11-24 12:42:58 -0800290 a.AddStrings("LOCAL_COMPATIBILITY_SUITE", suites...)
291}
292
Paul Duffin8b0349c2020-11-26 14:33:21 +0000293// The contributions to the dist.
294type distContributions struct {
Bob Badour51804382022-04-13 11:27:19 -0700295 // Path to license metadata file.
296 licenseMetadataFile Path
Paul Duffin8b0349c2020-11-26 14:33:21 +0000297 // List of goals and the dist copy instructions.
298 copiesForGoals []*copiesForGoals
299}
300
301// getCopiesForGoals returns a copiesForGoals into which copy instructions that
302// must be processed when building one or more of those goals can be added.
303func (d *distContributions) getCopiesForGoals(goals string) *copiesForGoals {
304 copiesForGoals := &copiesForGoals{goals: goals}
305 d.copiesForGoals = append(d.copiesForGoals, copiesForGoals)
306 return copiesForGoals
307}
308
309// Associates a list of dist copy instructions with a set of goals for which they
310// should be run.
311type copiesForGoals struct {
312 // goals are a space separated list of build targets that will trigger the
313 // copy instructions.
314 goals string
315
316 // A list of instructions to copy a module's output files to somewhere in the
317 // dist directory.
318 copies []distCopy
319}
320
321// Adds a copy instruction.
322func (d *copiesForGoals) addCopyInstruction(from Path, dest string) {
323 d.copies = append(d.copies, distCopy{from, dest})
324}
325
326// Instruction on a path that must be copied into the dist.
327type distCopy struct {
328 // The path to copy from.
329 from Path
330
331 // The destination within the dist directory to copy to.
332 dest string
333}
334
335// Compute the contributions that the module makes to the dist.
336func (a *AndroidMkEntries) getDistContributions(mod blueprint.Module) *distContributions {
Jingwen Chen40fd90a2020-06-15 05:24:19 +0000337 amod := mod.(Module).base()
338 name := amod.BaseModuleName()
339
Paul Duffin74f05592020-11-25 16:37:46 +0000340 // Collate the set of associated tag/paths available for copying to the dist.
341 // Start with an empty (nil) set.
Jingwen Chen7b27ca72020-07-24 09:13:49 +0000342 var availableTaggedDists TaggedDistFiles
Jingwen Chen40fd90a2020-06-15 05:24:19 +0000343
Paul Duffin74f05592020-11-25 16:37:46 +0000344 // Then merge in any that are provided explicitly by the module.
Jingwen Chen84811862020-07-21 11:32:19 +0000345 if a.DistFiles != nil {
Paul Duffin74f05592020-11-25 16:37:46 +0000346 // Merge the DistFiles into the set.
347 availableTaggedDists = availableTaggedDists.merge(a.DistFiles)
348 }
349
350 // If no paths have been provided for the DefaultDistTag and the output file is
351 // valid then add that as the default dist path.
352 if _, ok := availableTaggedDists[DefaultDistTag]; !ok && a.OutputFile.Valid() {
353 availableTaggedDists = availableTaggedDists.addPathsForTag(DefaultDistTag, a.OutputFile.Path())
354 }
355
Paul Duffinaf970a22020-11-23 23:32:56 +0000356 // If the distFiles created by GenerateTaggedDistFiles contains paths for the
357 // DefaultDistTag then that takes priority so delete any existing paths.
358 if _, ok := amod.distFiles[DefaultDistTag]; ok {
359 delete(availableTaggedDists, DefaultDistTag)
360 }
361
362 // Finally, merge the distFiles created by GenerateTaggedDistFiles.
363 availableTaggedDists = availableTaggedDists.merge(amod.distFiles)
364
Paul Duffin74f05592020-11-25 16:37:46 +0000365 if len(availableTaggedDists) == 0 {
Jingwen Chen7b27ca72020-07-24 09:13:49 +0000366 // Nothing dist-able for this module.
367 return nil
Jingwen Chen40fd90a2020-06-15 05:24:19 +0000368 }
369
Paul Duffin8b0349c2020-11-26 14:33:21 +0000370 // Collate the contributions this module makes to the dist.
371 distContributions := &distContributions{}
372
Bob Badour4660a982022-09-12 16:06:03 -0700373 if !exemptFromRequiredApplicableLicensesProperty(mod.(Module)) {
374 distContributions.licenseMetadataFile = amod.licenseMetadataFile
375 }
Bob Badour51804382022-04-13 11:27:19 -0700376
Jingwen Chen40fd90a2020-06-15 05:24:19 +0000377 // Iterate over this module's dist structs, merged from the dist and dists properties.
378 for _, dist := range amod.Dists() {
379 // Get the list of goals this dist should be enabled for. e.g. sdk, droidcore
380 goals := strings.Join(dist.Targets, " ")
381
382 // Get the tag representing the output files to be dist'd. e.g. ".jar", ".proguard_map"
383 var tag string
384 if dist.Tag == nil {
385 // If the dist struct does not specify a tag, use the default output files tag.
Paul Duffin74f05592020-11-25 16:37:46 +0000386 tag = DefaultDistTag
Jingwen Chen40fd90a2020-06-15 05:24:19 +0000387 } else {
388 tag = *dist.Tag
389 }
390
391 // Get the paths of the output files to be dist'd, represented by the tag.
392 // Can be an empty list.
393 tagPaths := availableTaggedDists[tag]
394 if len(tagPaths) == 0 {
395 // Nothing to dist for this tag, continue to the next dist.
396 continue
397 }
398
399 if len(tagPaths) > 1 && (dist.Dest != nil || dist.Suffix != nil) {
Paul Duffin74f05592020-11-25 16:37:46 +0000400 errorMessage := "%s: Cannot apply dest/suffix for more than one dist " +
401 "file for %q goals tag %q in module %s. The list of dist files, " +
Jingwen Chen40fd90a2020-06-15 05:24:19 +0000402 "which should have a single element, is:\n%s"
Paul Duffin74f05592020-11-25 16:37:46 +0000403 panic(fmt.Errorf(errorMessage, mod, goals, tag, name, tagPaths))
Jingwen Chen40fd90a2020-06-15 05:24:19 +0000404 }
405
Paul Duffin8b0349c2020-11-26 14:33:21 +0000406 copiesForGoals := distContributions.getCopiesForGoals(goals)
Jingwen Chen40fd90a2020-06-15 05:24:19 +0000407
Paul Duffin8b0349c2020-11-26 14:33:21 +0000408 // Iterate over each path adding a copy instruction to copiesForGoals
Jingwen Chen40fd90a2020-06-15 05:24:19 +0000409 for _, path := range tagPaths {
410 // It's possible that the Path is nil from errant modules. Be defensive here.
411 if path == nil {
412 tagName := "default" // for error message readability
413 if dist.Tag != nil {
414 tagName = *dist.Tag
415 }
416 panic(fmt.Errorf("Dist file should not be nil for the %s tag in %s", tagName, name))
417 }
418
419 dest := filepath.Base(path.String())
420
421 if dist.Dest != nil {
422 var err error
423 if dest, err = validateSafePath(*dist.Dest); err != nil {
424 // This was checked in ModuleBase.GenerateBuildActions
425 panic(err)
426 }
427 }
428
Trevor Radcliffe90727f42022-03-21 19:34:02 +0000429 ext := filepath.Ext(dest)
430 suffix := ""
Jingwen Chen40fd90a2020-06-15 05:24:19 +0000431 if dist.Suffix != nil {
Trevor Radcliffe90727f42022-03-21 19:34:02 +0000432 suffix = *dist.Suffix
433 }
434
435 productString := ""
436 if dist.Append_artifact_with_product != nil && *dist.Append_artifact_with_product {
437 productString = fmt.Sprintf("_%s", a.entryContext.Config().DeviceProduct())
438 }
439
440 if suffix != "" || productString != "" {
441 dest = strings.TrimSuffix(dest, ext) + suffix + productString + ext
Jingwen Chen40fd90a2020-06-15 05:24:19 +0000442 }
443
444 if dist.Dir != nil {
445 var err error
446 if dest, err = validateSafePath(*dist.Dir, dest); err != nil {
447 // This was checked in ModuleBase.GenerateBuildActions
448 panic(err)
449 }
450 }
451
Paul Duffin8b0349c2020-11-26 14:33:21 +0000452 copiesForGoals.addCopyInstruction(path, dest)
453 }
454 }
455
456 return distContributions
457}
458
459// generateDistContributionsForMake generates make rules that will generate the
460// dist according to the instructions in the supplied distContribution.
461func generateDistContributionsForMake(distContributions *distContributions) []string {
462 var ret []string
463 for _, d := range distContributions.copiesForGoals {
464 ret = append(ret, fmt.Sprintf(".PHONY: %s\n", d.goals))
465 // Create dist-for-goals calls for each of the copy instructions.
466 for _, c := range d.copies {
Bob Badour4660a982022-09-12 16:06:03 -0700467 if distContributions.licenseMetadataFile != nil {
468 ret = append(
469 ret,
470 fmt.Sprintf("$(if $(strip $(ALL_TARGETS.%s.META_LIC)),,$(eval ALL_TARGETS.%s.META_LIC := %s))\n",
471 c.from.String(), c.from.String(), distContributions.licenseMetadataFile.String()))
472 }
Bob Badour51804382022-04-13 11:27:19 -0700473 ret = append(
474 ret,
Paul Duffin8b0349c2020-11-26 14:33:21 +0000475 fmt.Sprintf("$(call dist-for-goals,%s,%s:%s)\n", d.goals, c.from.String(), c.dest))
Jingwen Chen40fd90a2020-06-15 05:24:19 +0000476 }
477 }
478
479 return ret
480}
481
Paul Duffin8b0349c2020-11-26 14:33:21 +0000482// Compute the list of Make strings to declare phony goals and dist-for-goals
483// calls from the module's dist and dists properties.
484func (a *AndroidMkEntries) GetDistForGoals(mod blueprint.Module) []string {
485 distContributions := a.getDistContributions(mod)
486 if distContributions == nil {
487 return nil
488 }
489
490 return generateDistContributionsForMake(distContributions)
491}
492
Jaewoong Jung7ef4a902020-11-16 12:50:29 -0800493// fillInEntries goes through the common variable processing and calls the extra data funcs to
494// generate and fill in AndroidMkEntries's in-struct data, ready to be flushed to a file.
Colin Crossaa255532020-07-03 13:18:24 -0700495type fillInEntriesContext interface {
496 ModuleDir(module blueprint.Module) string
Cole Faust39aabe92023-02-23 16:57:43 -0800497 ModuleSubDir(module blueprint.Module) string
Colin Crossaa255532020-07-03 13:18:24 -0700498 Config() Config
Colin Cross3c0a83d2023-12-12 14:13:26 -0800499 moduleProvider(module blueprint.Module, provider blueprint.AnyProviderKey) (any, bool)
Sasha Smundak5c4729d2022-12-01 10:49:23 -0800500 ModuleType(module blueprint.Module) string
Colin Crossaa255532020-07-03 13:18:24 -0700501}
502
503func (a *AndroidMkEntries) fillInEntries(ctx fillInEntriesContext, mod blueprint.Module) {
Trevor Radcliffe90727f42022-03-21 19:34:02 +0000504 a.entryContext = ctx
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700505 a.EntryMap = make(map[string][]string)
Colin Crossf1f763a2021-10-21 16:14:19 -0700506 amod := mod.(Module)
507 base := amod.base()
508 name := base.BaseModuleName()
Colin Cross0477b422020-10-13 18:43:54 -0700509 if a.OverrideName != "" {
510 name = a.OverrideName
511 }
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700512
513 if a.Include == "" {
514 a.Include = "$(BUILD_PREBUILT)"
515 }
Colin Crossf1f763a2021-10-21 16:14:19 -0700516 a.Required = append(a.Required, amod.RequiredModuleNames()...)
517 a.Host_required = append(a.Host_required, amod.HostRequiredModuleNames()...)
518 a.Target_required = append(a.Target_required, amod.TargetRequiredModuleNames()...)
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700519
Jingwen Chen40fd90a2020-06-15 05:24:19 +0000520 for _, distString := range a.GetDistForGoals(mod) {
521 fmt.Fprintf(&a.header, distString)
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700522 }
523
Cole Faust39aabe92023-02-23 16:57:43 -0800524 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 -0700525
526 // Collect make variable assignment entries.
Colin Crossaa255532020-07-03 13:18:24 -0700527 a.SetString("LOCAL_PATH", ctx.ModuleDir(mod))
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700528 a.SetString("LOCAL_MODULE", name+a.SubName)
529 a.SetString("LOCAL_MODULE_CLASS", a.Class)
530 a.SetString("LOCAL_PREBUILT_MODULE_FILE", a.OutputFile.String())
531 a.AddStrings("LOCAL_REQUIRED_MODULES", a.Required...)
532 a.AddStrings("LOCAL_HOST_REQUIRED_MODULES", a.Host_required...)
533 a.AddStrings("LOCAL_TARGET_REQUIRED_MODULES", a.Target_required...)
Wei Li598f92d2023-01-04 17:12:24 -0800534 a.AddStrings("LOCAL_SOONG_MODULE_TYPE", ctx.ModuleType(amod))
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700535
Colin Cross6301c3c2021-09-28 17:40:21 -0700536 // If the install rule was generated by Soong tell Make about it.
Colin Crossc68db4b2021-11-11 18:59:15 -0800537 if len(base.katiInstalls) > 0 {
Colin Cross6301c3c2021-09-28 17:40:21 -0700538 // Assume the primary install file is last since it probably needs to depend on any other
539 // installed files. If that is not the case we can add a method to specify the primary
540 // installed file.
541 a.SetPath("LOCAL_SOONG_INSTALLED_MODULE", base.katiInstalls[len(base.katiInstalls)-1].to)
542 a.SetString("LOCAL_SOONG_INSTALL_PAIRS", base.katiInstalls.BuiltInstalled())
543 a.SetPaths("LOCAL_SOONG_INSTALL_SYMLINKS", base.katiSymlinks.InstallPaths().Paths())
544 }
545
Colin Cross5c1d5fb2023-11-15 12:39:40 -0800546 if len(base.testData) > 0 {
547 a.AddStrings("LOCAL_TEST_DATA", androidMkDataPaths(base.testData)...)
548 }
549
Jiyong Park89e850a2020-04-07 16:37:39 +0900550 if am, ok := mod.(ApexModule); ok {
551 a.SetBoolIfTrue("LOCAL_NOT_AVAILABLE_FOR_PLATFORM", am.NotAvailableForPlatform())
552 }
553
Colin Crossf1f763a2021-10-21 16:14:19 -0700554 archStr := base.Arch().ArchType.String()
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700555 host := false
Colin Crossf1f763a2021-10-21 16:14:19 -0700556 switch base.Os().Class {
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700557 case Host:
Colin Crossf1f763a2021-10-21 16:14:19 -0700558 if base.Target().HostCross {
Jiyong Park1613e552020-09-14 19:43:17 +0900559 // Make cannot identify LOCAL_MODULE_HOST_CROSS_ARCH:= common.
Colin Crossf1f763a2021-10-21 16:14:19 -0700560 if base.Arch().ArchType != Common {
Jiyong Park1613e552020-09-14 19:43:17 +0900561 a.SetString("LOCAL_MODULE_HOST_CROSS_ARCH", archStr)
562 }
563 } else {
564 // Make cannot identify LOCAL_MODULE_HOST_ARCH:= common.
Colin Crossf1f763a2021-10-21 16:14:19 -0700565 if base.Arch().ArchType != Common {
Jiyong Park1613e552020-09-14 19:43:17 +0900566 a.SetString("LOCAL_MODULE_HOST_ARCH", archStr)
567 }
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700568 }
569 host = true
570 case Device:
571 // Make cannot identify LOCAL_MODULE_TARGET_ARCH:= common.
Colin Crossf1f763a2021-10-21 16:14:19 -0700572 if base.Arch().ArchType != Common {
573 if base.Target().NativeBridge {
574 hostArchStr := base.Target().NativeBridgeHostArchName
dimitry1f33e402019-03-26 12:39:31 +0100575 if hostArchStr != "" {
576 a.SetString("LOCAL_MODULE_TARGET_ARCH", hostArchStr)
577 }
578 } else {
579 a.SetString("LOCAL_MODULE_TARGET_ARCH", archStr)
580 }
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700581 }
582
Kelvin Zhang46977252022-04-13 16:41:34 -0700583 if !base.InVendorRamdisk() {
Colin Crossf1f763a2021-10-21 16:14:19 -0700584 a.AddPaths("LOCAL_FULL_INIT_RC", base.initRcPaths)
Yifan Hong919dae12020-12-02 18:55:06 -0800585 }
Colin Crossf1f763a2021-10-21 16:14:19 -0700586 if len(base.vintfFragmentsPaths) > 0 {
587 a.AddPaths("LOCAL_FULL_VINTF_FRAGMENTS", base.vintfFragmentsPaths)
Liz Kammer7b3dc8a2021-04-16 16:41:59 -0400588 }
Colin Crossf1f763a2021-10-21 16:14:19 -0700589 a.SetBoolIfTrue("LOCAL_PROPRIETARY_MODULE", Bool(base.commonProperties.Proprietary))
590 if Bool(base.commonProperties.Vendor) || Bool(base.commonProperties.Soc_specific) {
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700591 a.SetString("LOCAL_VENDOR_MODULE", "true")
592 }
Colin Crossf1f763a2021-10-21 16:14:19 -0700593 a.SetBoolIfTrue("LOCAL_ODM_MODULE", Bool(base.commonProperties.Device_specific))
594 a.SetBoolIfTrue("LOCAL_PRODUCT_MODULE", Bool(base.commonProperties.Product_specific))
595 a.SetBoolIfTrue("LOCAL_SYSTEM_EXT_MODULE", Bool(base.commonProperties.System_ext_specific))
596 if base.commonProperties.Owner != nil {
597 a.SetString("LOCAL_MODULE_OWNER", *base.commonProperties.Owner)
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700598 }
599 }
600
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700601 if host {
Colin Crossf1f763a2021-10-21 16:14:19 -0700602 makeOs := base.Os().String()
603 if base.Os() == Linux || base.Os() == LinuxBionic || base.Os() == LinuxMusl {
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700604 makeOs = "linux"
605 }
606 a.SetString("LOCAL_MODULE_HOST_OS", makeOs)
607 a.SetString("LOCAL_IS_HOST_MODULE", "true")
608 }
609
610 prefix := ""
Colin Crossf1f763a2021-10-21 16:14:19 -0700611 if base.ArchSpecific() {
612 switch base.Os().Class {
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700613 case Host:
Colin Crossf1f763a2021-10-21 16:14:19 -0700614 if base.Target().HostCross {
Jiyong Park1613e552020-09-14 19:43:17 +0900615 prefix = "HOST_CROSS_"
616 } else {
617 prefix = "HOST_"
618 }
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700619 case Device:
620 prefix = "TARGET_"
621
622 }
623
Colin Crossf1f763a2021-10-21 16:14:19 -0700624 if base.Arch().ArchType != ctx.Config().Targets[base.Os()][0].Arch.ArchType {
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700625 prefix = "2ND_" + prefix
626 }
627 }
Colin Crossaa255532020-07-03 13:18:24 -0700628
Colin Cross313aa542023-12-13 13:47:44 -0800629 if licenseMetadata, ok := SingletonModuleProvider(ctx, mod, LicenseMetadataProvider); ok {
Colin Cross4acaea92021-12-10 23:05:02 +0000630 a.SetPath("LOCAL_SOONG_LICENSE_METADATA", licenseMetadata.LicenseMetadataPath)
631 }
632
Colin Crossd6fd0132023-11-06 13:54:06 -0800633 if _, ok := SingletonModuleProvider(ctx, mod, ModuleInfoJSONProvider); ok {
634 a.SetBool("LOCAL_SOONG_MODULE_INFO_JSON", true)
635 }
636
Colin Crossaa255532020-07-03 13:18:24 -0700637 extraCtx := &androidMkExtraEntriesContext{
638 ctx: ctx,
639 mod: mod,
640 }
641
Jaewoong Junge0dc8df2019-08-27 17:33:16 -0700642 for _, extra := range a.ExtraEntries {
Colin Crossaa255532020-07-03 13:18:24 -0700643 extra(extraCtx, a)
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700644 }
645
646 // Write to footer.
647 fmt.Fprintln(&a.footer, "include "+a.Include)
Colin Crossaa255532020-07-03 13:18:24 -0700648 blueprintDir := ctx.ModuleDir(mod)
Jaewoong Jungb0c127c2019-08-29 14:56:03 -0700649 for _, footerFunc := range a.ExtraFooters {
Jaewoong Jung02b11a62020-12-07 10:23:54 -0800650 footerFunc(&a.footer, name, prefix, blueprintDir)
Jaewoong Jungb0c127c2019-08-29 14:56:03 -0700651 }
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700652}
653
Colin Crossd6fd0132023-11-06 13:54:06 -0800654func (a *AndroidMkEntries) disabled() bool {
655 return a.Disabled || !a.OutputFile.Valid()
656}
657
Jaewoong Jung7ef4a902020-11-16 12:50:29 -0800658// write flushes the AndroidMkEntries's in-struct data populated by AndroidMkEntries into the
659// given Writer object.
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700660func (a *AndroidMkEntries) write(w io.Writer) {
Colin Crossd6fd0132023-11-06 13:54:06 -0800661 if a.disabled() {
Jaewoong Jungb0c127c2019-08-29 14:56:03 -0700662 return
663 }
664
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700665 w.Write(a.header.Bytes())
666 for _, name := range a.entryOrder {
Sasha Smundakdcb61292022-12-08 10:41:33 -0800667 AndroidMkEmitAssignList(w, name, a.EntryMap[name])
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700668 }
669 w.Write(a.footer.Bytes())
670}
671
Jaewoong Jungb0c127c2019-08-29 14:56:03 -0700672func (a *AndroidMkEntries) FooterLinesForTests() []string {
673 return strings.Split(string(a.footer.Bytes()), "\n")
674}
675
Jaewoong Jung7ef4a902020-11-16 12:50:29 -0800676// AndroidMkSingleton is a singleton to collect Android.mk data from all modules and dump them into
677// the final Android-<product_name>.mk file output.
Colin Cross0875c522017-11-28 17:34:01 -0800678func AndroidMkSingleton() Singleton {
Dan Willemsen218f6562015-07-08 18:13:11 -0700679 return &androidMkSingleton{}
680}
681
682type androidMkSingleton struct{}
683
Colin Cross0875c522017-11-28 17:34:01 -0800684func (c *androidMkSingleton) GenerateBuildActions(ctx SingletonContext) {
Jaewoong Jung7ef4a902020-11-16 12:50:29 -0800685 // Skip if Soong wasn't invoked from Make.
Jingwen Chencda22c92020-11-23 00:22:30 -0500686 if !ctx.Config().KatiEnabled() {
Dan Willemsen5ba07e82015-12-11 13:51:06 -0800687 return
688 }
689
Colin Cross2465c3d2018-09-28 10:19:18 -0700690 var androidMkModulesList []blueprint.Module
Colin Cross4f6e4e62016-01-11 12:55:55 -0800691
Colin Cross2465c3d2018-09-28 10:19:18 -0700692 ctx.VisitAllModulesBlueprint(func(module blueprint.Module) {
Colin Cross0875c522017-11-28 17:34:01 -0800693 androidMkModulesList = append(androidMkModulesList, module)
Colin Cross4f6e4e62016-01-11 12:55:55 -0800694 })
Dan Willemsen218f6562015-07-08 18:13:11 -0700695
Jaewoong Jung7ef4a902020-11-16 12:50:29 -0800696 // Sort the module list by the module names to eliminate random churns, which may erroneously
697 // invoke additional build processes.
Colin Cross1ad81422019-01-14 12:47:35 -0800698 sort.SliceStable(androidMkModulesList, func(i, j int) bool {
699 return ctx.ModuleName(androidMkModulesList[i]) < ctx.ModuleName(androidMkModulesList[j])
700 })
Colin Crossd779da42015-12-17 18:00:23 -0800701
Dan Willemsen45133ac2018-03-09 21:22:06 -0800702 transMk := PathForOutput(ctx, "Android"+String(ctx.Config().productVariables.Make_suffix)+".mk")
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700703 if ctx.Failed() {
704 return
705 }
Dan Willemsen218f6562015-07-08 18:13:11 -0700706
Colin Crossd6fd0132023-11-06 13:54:06 -0800707 moduleInfoJSON := PathForOutput(ctx, "module-info"+String(ctx.Config().productVariables.Make_suffix)+".json")
708
709 err := translateAndroidMk(ctx, absolutePath(transMk.String()), moduleInfoJSON, androidMkModulesList)
Dan Willemsen218f6562015-07-08 18:13:11 -0700710 if err != nil {
711 ctx.Errorf(err.Error())
712 }
713
Colin Cross0875c522017-11-28 17:34:01 -0800714 ctx.Build(pctx, BuildParams{
715 Rule: blueprint.Phony,
716 Output: transMk,
Dan Willemsen218f6562015-07-08 18:13:11 -0700717 })
718}
719
Colin Crossd6fd0132023-11-06 13:54:06 -0800720func translateAndroidMk(ctx SingletonContext, absMkFile string, moduleInfoJSONPath WritablePath, mods []blueprint.Module) error {
Dan Willemsen218f6562015-07-08 18:13:11 -0700721 buf := &bytes.Buffer{}
722
Colin Crossd6fd0132023-11-06 13:54:06 -0800723 var moduleInfoJSONs []*ModuleInfoJSON
724
Dan Willemsen97750522016-02-09 17:43:51 -0800725 fmt.Fprintln(buf, "LOCAL_MODULE_MAKEFILE := $(lastword $(MAKEFILE_LIST))")
Dan Willemsen218f6562015-07-08 18:13:11 -0700726
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800727 typeStats := make(map[string]int)
Dan Willemsen218f6562015-07-08 18:13:11 -0700728 for _, mod := range mods {
Colin Crossd6fd0132023-11-06 13:54:06 -0800729 err := translateAndroidMkModule(ctx, buf, &moduleInfoJSONs, mod)
Dan Willemsen218f6562015-07-08 18:13:11 -0700730 if err != nil {
Colin Cross836e3872021-11-09 12:30:59 -0800731 os.Remove(absMkFile)
Dan Willemsen218f6562015-07-08 18:13:11 -0700732 return err
733 }
Dan Willemsen70e17fa2016-07-25 16:00:20 -0700734
Colin Cross2465c3d2018-09-28 10:19:18 -0700735 if amod, ok := mod.(Module); ok && ctx.PrimaryModule(amod) == amod {
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800736 typeStats[ctx.ModuleType(amod)] += 1
Dan Willemsen70e17fa2016-07-25 16:00:20 -0700737 }
738 }
739
740 keys := []string{}
741 fmt.Fprintln(buf, "\nSTATS.SOONG_MODULE_TYPE :=")
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800742 for k := range typeStats {
Dan Willemsen70e17fa2016-07-25 16:00:20 -0700743 keys = append(keys, k)
744 }
745 sort.Strings(keys)
746 for _, mod_type := range keys {
747 fmt.Fprintln(buf, "STATS.SOONG_MODULE_TYPE +=", mod_type)
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800748 fmt.Fprintf(buf, "STATS.SOONG_MODULE_TYPE.%s := %d\n", mod_type, typeStats[mod_type])
Dan Willemsen218f6562015-07-08 18:13:11 -0700749 }
750
Colin Crossd6fd0132023-11-06 13:54:06 -0800751 err := pathtools.WriteFileIfChanged(absMkFile, buf.Bytes(), 0666)
752 if err != nil {
753 return err
754 }
755
756 return writeModuleInfoJSON(ctx, moduleInfoJSONs, moduleInfoJSONPath)
Dan Willemsen218f6562015-07-08 18:13:11 -0700757}
758
Colin Crossd6fd0132023-11-06 13:54:06 -0800759func writeModuleInfoJSON(ctx SingletonContext, moduleInfoJSONs []*ModuleInfoJSON, moduleInfoJSONPath WritablePath) error {
760 moduleInfoJSONBuf := &strings.Builder{}
761 moduleInfoJSONBuf.WriteString("[")
762 for i, moduleInfoJSON := range moduleInfoJSONs {
763 if i != 0 {
764 moduleInfoJSONBuf.WriteString(",\n")
765 }
766 moduleInfoJSONBuf.WriteString("{")
767 moduleInfoJSONBuf.WriteString(strconv.Quote(moduleInfoJSON.core.RegisterName))
768 moduleInfoJSONBuf.WriteString(":")
769 err := encodeModuleInfoJSON(moduleInfoJSONBuf, moduleInfoJSON)
770 moduleInfoJSONBuf.WriteString("}")
771 if err != nil {
772 return err
773 }
774 }
775 moduleInfoJSONBuf.WriteString("]")
776 WriteFileRule(ctx, moduleInfoJSONPath, moduleInfoJSONBuf.String())
777 return nil
778}
779
780func translateAndroidMkModule(ctx SingletonContext, w io.Writer, moduleInfoJSONs *[]*ModuleInfoJSON, mod blueprint.Module) error {
Colin Cross953d3a22018-09-05 16:23:54 -0700781 defer func() {
782 if r := recover(); r != nil {
783 panic(fmt.Errorf("%s in translateAndroidMkModule for module %s variant %s",
784 r, ctx.ModuleName(mod), ctx.ModuleSubDir(mod)))
785 }
786 }()
787
Bob Badourb4999222021-01-07 03:34:31 +0000788 // Additional cases here require review for correct license propagation to make.
Colin Crossd6fd0132023-11-06 13:54:06 -0800789 var err error
Colin Cross2465c3d2018-09-28 10:19:18 -0700790 switch x := mod.(type) {
791 case AndroidMkDataProvider:
Colin Crossd6fd0132023-11-06 13:54:06 -0800792 err = translateAndroidModule(ctx, w, moduleInfoJSONs, mod, x)
Colin Cross2465c3d2018-09-28 10:19:18 -0700793 case bootstrap.GoBinaryTool:
Colin Crossd6fd0132023-11-06 13:54:06 -0800794 err = translateGoBinaryModule(ctx, w, mod, x)
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700795 case AndroidMkEntriesProvider:
Colin Crossd6fd0132023-11-06 13:54:06 -0800796 err = translateAndroidMkEntriesModule(ctx, w, moduleInfoJSONs, mod, x)
Colin Cross2465c3d2018-09-28 10:19:18 -0700797 default:
Bob Badourb4999222021-01-07 03:34:31 +0000798 // Not exported to make so no make variables to set.
Dan Willemsen218f6562015-07-08 18:13:11 -0700799 }
Colin Crossd6fd0132023-11-06 13:54:06 -0800800
801 if err != nil {
802 return err
803 }
804
805 return err
Colin Cross2465c3d2018-09-28 10:19:18 -0700806}
807
Jaewoong Jung7ef4a902020-11-16 12:50:29 -0800808// A simple, special Android.mk entry output func to make it possible to build blueprint tools using
809// m by making them phony targets.
Colin Cross2465c3d2018-09-28 10:19:18 -0700810func translateGoBinaryModule(ctx SingletonContext, w io.Writer, mod blueprint.Module,
811 goBinary bootstrap.GoBinaryTool) error {
812
813 name := ctx.ModuleName(mod)
814 fmt.Fprintln(w, ".PHONY:", name)
815 fmt.Fprintln(w, name+":", goBinary.InstallPath())
816 fmt.Fprintln(w, "")
Bob Badourb4999222021-01-07 03:34:31 +0000817 // Assuming no rules in make include go binaries in distributables.
818 // If the assumption is wrong, make will fail to build without the necessary .meta_lic and .meta_module files.
819 // In that case, add the targets and rules here to build a .meta_lic file for `name` and a .meta_module for
820 // `goBinary.InstallPath()` pointing to the `name`.meta_lic file.
Colin Cross2465c3d2018-09-28 10:19:18 -0700821
822 return nil
823}
824
Colin Crossaa255532020-07-03 13:18:24 -0700825func (data *AndroidMkData) fillInData(ctx fillInEntriesContext, mod blueprint.Module) {
Jooyung Han12df5fb2019-07-11 16:18:47 +0900826 // Get the preamble content through AndroidMkEntries logic.
Jooyung Han2ed99d02020-06-24 23:26:26 +0900827 data.Entries = AndroidMkEntries{
Jooyung Han12df5fb2019-07-11 16:18:47 +0900828 Class: data.Class,
829 SubName: data.SubName,
Jingwen Chen40fd90a2020-06-15 05:24:19 +0000830 DistFiles: data.DistFiles,
Jooyung Han12df5fb2019-07-11 16:18:47 +0900831 OutputFile: data.OutputFile,
832 Disabled: data.Disabled,
833 Include: data.Include,
834 Required: data.Required,
835 Host_required: data.Host_required,
836 Target_required: data.Target_required,
837 }
Colin Crossaa255532020-07-03 13:18:24 -0700838 data.Entries.fillInEntries(ctx, mod)
Jooyung Han12df5fb2019-07-11 16:18:47 +0900839
840 // copy entries back to data since it is used in Custom
Jooyung Han2ed99d02020-06-24 23:26:26 +0900841 data.Required = data.Entries.Required
842 data.Host_required = data.Entries.Host_required
843 data.Target_required = data.Entries.Target_required
Jooyung Han12df5fb2019-07-11 16:18:47 +0900844}
845
Jaewoong Jung7ef4a902020-11-16 12:50:29 -0800846// A support func for the deprecated AndroidMkDataProvider interface. Use AndroidMkEntryProvider
847// instead.
Colin Crossd6fd0132023-11-06 13:54:06 -0800848func translateAndroidModule(ctx SingletonContext, w io.Writer, moduleInfoJSONs *[]*ModuleInfoJSON,
849 mod blueprint.Module, provider AndroidMkDataProvider) error {
Dan Willemsen218f6562015-07-08 18:13:11 -0700850
Colin Cross635c3b02016-05-18 15:37:25 -0700851 amod := mod.(Module).base()
Cole Fausta963b942024-04-11 17:43:00 -0700852 if shouldSkipAndroidMkProcessing(ctx, amod) {
Jeff Gaston088e29e2017-11-29 16:47:17 -0800853 return nil
854 }
855
Colin Cross91825d22017-08-10 16:59:47 -0700856 data := provider.AndroidMk()
Colin Cross53499412017-09-07 13:20:25 -0700857 if data.Include == "" {
858 data.Include = "$(BUILD_PREBUILT)"
859 }
860
Colin Crossaa255532020-07-03 13:18:24 -0700861 data.fillInData(ctx, mod)
LaMont Jonesb5099382024-01-10 23:42:36 +0000862 aconfigUpdateAndroidMkData(ctx, mod.(Module), &data)
Dan Willemsen01a405a2016-06-13 17:19:03 -0700863
Colin Cross0f86d182017-08-10 17:07:28 -0700864 prefix := ""
865 if amod.ArchSpecific() {
866 switch amod.Os().Class {
867 case Host:
Jiyong Park1613e552020-09-14 19:43:17 +0900868 if amod.Target().HostCross {
869 prefix = "HOST_CROSS_"
870 } else {
871 prefix = "HOST_"
872 }
Colin Cross0f86d182017-08-10 17:07:28 -0700873 case Device:
874 prefix = "TARGET_"
Colin Crossa2344662016-03-24 13:14:12 -0700875
Dan Willemsen218f6562015-07-08 18:13:11 -0700876 }
877
Dan Willemsen0ef639b2018-10-10 17:02:29 -0700878 if amod.Arch().ArchType != ctx.Config().Targets[amod.Os()][0].Arch.ArchType {
Colin Cross0f86d182017-08-10 17:07:28 -0700879 prefix = "2ND_" + prefix
880 }
Dan Willemsen218f6562015-07-08 18:13:11 -0700881 }
882
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700883 name := provider.BaseModuleName()
Colin Cross0f86d182017-08-10 17:07:28 -0700884 blueprintDir := filepath.Dir(ctx.BlueprintFile(mod))
885
886 if data.Custom != nil {
Bob Badourb4999222021-01-07 03:34:31 +0000887 // List of module types allowed to use .Custom(...)
888 // Additions to the list require careful review for proper license handling.
Colin Crossaa255532020-07-03 13:18:24 -0700889 switch reflect.TypeOf(mod).String() { // ctx.ModuleType(mod) doesn't work: aidl_interface creates phony without type
Bob Badourb4999222021-01-07 03:34:31 +0000890 case "*aidl.aidlApi": // writes non-custom before adding .phony
891 case "*aidl.aidlMapping": // writes non-custom before adding .phony
892 case "*android.customModule": // appears in tests only
Dan Willemsen9fe14102021-07-13 21:52:04 -0700893 case "*android_sdk.sdkRepoHost": // doesn't go through base_rules
Bob Badourb4999222021-01-07 03:34:31 +0000894 case "*apex.apexBundle": // license properties written
895 case "*bpf.bpf": // license properties written (both for module and objs)
896 case "*genrule.Module": // writes non-custom before adding .phony
897 case "*java.SystemModules": // doesn't go through base_rules
898 case "*java.systemModulesImport": // doesn't go through base_rules
899 case "*phony.phony": // license properties written
Nelson Lif3c70682023-12-20 02:37:52 +0000900 case "*phony.PhonyRule": // writes phony deps and acts like `.PHONY`
Bob Badourb4999222021-01-07 03:34:31 +0000901 case "*selinux.selinuxContextsModule": // license properties written
902 case "*sysprop.syspropLibrary": // license properties written
903 default:
Bob Badour65ee90a2021-09-02 15:33:10 -0700904 if !ctx.Config().IsEnvFalse("ANDROID_REQUIRE_LICENSES") {
Bob Badourb4999222021-01-07 03:34:31 +0000905 return fmt.Errorf("custom make rules not allowed for %q (%q) module %q", ctx.ModuleType(mod), reflect.TypeOf(mod), ctx.ModuleName(mod))
906 }
907 }
Colin Cross0f86d182017-08-10 17:07:28 -0700908 data.Custom(w, name, prefix, blueprintDir, data)
909 } else {
910 WriteAndroidMkData(w, data)
911 }
912
Colin Crossd6fd0132023-11-06 13:54:06 -0800913 if !data.Entries.disabled() {
914 if moduleInfoJSON, ok := SingletonModuleProvider(ctx, mod, ModuleInfoJSONProvider); ok {
915 *moduleInfoJSONs = append(*moduleInfoJSONs, moduleInfoJSON)
916 }
917 }
918
Colin Cross0f86d182017-08-10 17:07:28 -0700919 return nil
920}
921
Jaewoong Jung7ef4a902020-11-16 12:50:29 -0800922// A support func for the deprecated AndroidMkDataProvider interface. Use AndroidMkEntryProvider
923// instead.
Colin Cross0f86d182017-08-10 17:07:28 -0700924func WriteAndroidMkData(w io.Writer, data AndroidMkData) {
Colin Crossd6fd0132023-11-06 13:54:06 -0800925 if data.Entries.disabled() {
Colin Cross0f86d182017-08-10 17:07:28 -0700926 return
927 }
928
Jooyung Han2ed99d02020-06-24 23:26:26 +0900929 // write preamble via Entries
930 data.Entries.footer = bytes.Buffer{}
931 data.Entries.write(w)
Colin Cross0f86d182017-08-10 17:07:28 -0700932
Colin Crossca860ac2016-01-04 14:34:37 -0800933 for _, extra := range data.Extra {
Colin Cross27a4b052017-08-10 16:32:23 -0700934 extra(w, data.OutputFile.Path())
Dan Willemsen97750522016-02-09 17:43:51 -0800935 }
936
Colin Cross53499412017-09-07 13:20:25 -0700937 fmt.Fprintln(w, "include "+data.Include)
Dan Willemsen218f6562015-07-08 18:13:11 -0700938}
Sasha Smundakb6d23052019-04-01 18:37:36 -0700939
Colin Crossd6fd0132023-11-06 13:54:06 -0800940func translateAndroidMkEntriesModule(ctx SingletonContext, w io.Writer, moduleInfoJSONs *[]*ModuleInfoJSON,
941 mod blueprint.Module, provider AndroidMkEntriesProvider) error {
Cole Fausta963b942024-04-11 17:43:00 -0700942 if shouldSkipAndroidMkProcessing(ctx, mod.(Module).base()) {
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700943 return nil
Sasha Smundakb6d23052019-04-01 18:37:36 -0700944 }
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700945
Colin Crossd6fd0132023-11-06 13:54:06 -0800946 entriesList := provider.AndroidMkEntries()
LaMont Jonesb5099382024-01-10 23:42:36 +0000947 aconfigUpdateAndroidMkEntries(ctx, mod.(Module), &entriesList)
Colin Crossd6fd0132023-11-06 13:54:06 -0800948
Bob Badourb4999222021-01-07 03:34:31 +0000949 // Any new or special cases here need review to verify correct propagation of license information.
Colin Crossd6fd0132023-11-06 13:54:06 -0800950 for _, entries := range entriesList {
Colin Crossaa255532020-07-03 13:18:24 -0700951 entries.fillInEntries(ctx, mod)
Jiyong Park0b0e1b92019-12-03 13:24:29 +0900952 entries.write(w)
953 }
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700954
Colin Crossd6fd0132023-11-06 13:54:06 -0800955 if len(entriesList) > 0 && !entriesList[0].disabled() {
956 if moduleInfoJSON, ok := SingletonModuleProvider(ctx, mod, ModuleInfoJSONProvider); ok {
957 *moduleInfoJSONs = append(*moduleInfoJSONs, moduleInfoJSON)
958 }
959 }
960
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700961 return nil
962}
963
Cole Fausta963b942024-04-11 17:43:00 -0700964func ShouldSkipAndroidMkProcessing(ctx ConfigAndErrorContext, module Module) bool {
965 return shouldSkipAndroidMkProcessing(ctx, module.base())
Chih-Hung Hsieh80783772021-10-11 16:46:56 -0700966}
967
Cole Fausta963b942024-04-11 17:43:00 -0700968func shouldSkipAndroidMkProcessing(ctx ConfigAndErrorContext, module *ModuleBase) bool {
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700969 if !module.commonProperties.NamespaceExportedToMake {
970 // TODO(jeffrygaston) do we want to validate that there are no modules being
971 // exported to Kati that depend on this module?
972 return true
Sasha Smundakb6d23052019-04-01 18:37:36 -0700973 }
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700974
Dan Willemsendef7b5d2021-10-17 00:22:33 -0700975 // On Mac, only expose host darwin modules to Make, as that's all we claim to support.
976 // In reality, some of them depend on device-built (Java) modules, so we can't disable all
977 // device modules in Soong, but we can hide them from Make (and thus the build user interface)
978 if runtime.GOOS == "darwin" && module.Os() != Darwin {
979 return true
980 }
981
Dan Willemsen8528f4e2021-10-19 00:22:06 -0700982 // Only expose the primary Darwin target, as Make does not understand Darwin+Arm64
983 if module.Os() == Darwin && module.Target().HostCross {
984 return true
985 }
986
Cole Fausta963b942024-04-11 17:43:00 -0700987 return !module.Enabled(ctx) ||
Colin Crossa9c8c9f2020-12-16 10:20:23 -0800988 module.commonProperties.HideFromMake ||
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700989 // Make does not understand LinuxBionic
Colin Cross9a027be2022-06-24 18:45:58 -0700990 module.Os() == LinuxBionic ||
991 // Make does not understand LinuxMusl, except when we are building with USE_HOST_MUSL=true
992 // and all host binaries are LinuxMusl
993 (module.Os() == LinuxMusl && module.Target().HostCross)
Sasha Smundakb6d23052019-04-01 18:37:36 -0700994}
Dan Shi31949122020-09-21 12:11:02 -0700995
Jaewoong Jung7ef4a902020-11-16 12:50:29 -0800996// A utility func to format LOCAL_TEST_DATA outputs. See the comments on DataPath to understand how
997// to use this func.
Colin Cross5c1d5fb2023-11-15 12:39:40 -0800998func androidMkDataPaths(data []DataPath) []string {
Dan Shi31949122020-09-21 12:11:02 -0700999 var testFiles []string
1000 for _, d := range data {
1001 rel := d.SrcPath.Rel()
Colin Cross5c1d5fb2023-11-15 12:39:40 -08001002 if d.WithoutRel {
1003 rel = d.SrcPath.Base()
1004 }
Dan Shi31949122020-09-21 12:11:02 -07001005 path := d.SrcPath.String()
Jaewoong Jung7ef4a902020-11-16 12:50:29 -08001006 // LOCAL_TEST_DATA requires the rel portion of the path to be removed from the path.
Dan Shi31949122020-09-21 12:11:02 -07001007 if !strings.HasSuffix(path, rel) {
1008 panic(fmt.Errorf("path %q does not end with %q", path, rel))
1009 }
1010 path = strings.TrimSuffix(path, rel)
1011 testFileString := path + ":" + rel
1012 if len(d.RelativeInstallPath) > 0 {
1013 testFileString += ":" + d.RelativeInstallPath
1014 }
1015 testFiles = append(testFiles, testFileString)
1016 }
1017 return testFiles
1018}
Sasha Smundakdcb61292022-12-08 10:41:33 -08001019
1020// AndroidMkEmitAssignList emits the line
1021//
1022// VAR := ITEM ...
1023//
1024// Items are the elements to the given set of lists
1025// If all the passed lists are empty, no line will be emitted
1026func AndroidMkEmitAssignList(w io.Writer, varName string, lists ...[]string) {
1027 doPrint := false
1028 for _, l := range lists {
1029 if doPrint = len(l) > 0; doPrint {
1030 break
1031 }
1032 }
1033 if !doPrint {
1034 return
1035 }
1036 fmt.Fprint(w, varName, " :=")
1037 for _, l := range lists {
1038 for _, item := range l {
1039 fmt.Fprint(w, " ", item)
1040 }
1041 }
1042 fmt.Fprintln(w)
1043}