blob: 02bcb65fc9c2c97b2b03a8541bb042b11df3de93 [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 {
Yu Liuec810542024-08-26 18:09:15 +0000160 OtherModuleProviderContext
Trevor Radcliffe90727f42022-03-21 19:34:02 +0000161 Config() Config
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700162}
163
Colin Crossaa255532020-07-03 13:18:24 -0700164type AndroidMkExtraEntriesContext interface {
Colin Cross3c0a83d2023-12-12 14:13:26 -0800165 Provider(provider blueprint.AnyProviderKey) (any, bool)
Colin Crossaa255532020-07-03 13:18:24 -0700166}
167
168type androidMkExtraEntriesContext struct {
169 ctx fillInEntriesContext
170 mod blueprint.Module
171}
172
Colin Cross3c0a83d2023-12-12 14:13:26 -0800173func (a *androidMkExtraEntriesContext) Provider(provider blueprint.AnyProviderKey) (any, bool) {
Yu Liu663e4502024-08-12 18:23:59 +0000174 return a.ctx.otherModuleProvider(a.mod, provider)
Colin Crossaa255532020-07-03 13:18:24 -0700175}
176
177type AndroidMkExtraEntriesFunc func(ctx AndroidMkExtraEntriesContext, entries *AndroidMkEntries)
Jaewoong Jung02b11a62020-12-07 10:23:54 -0800178type AndroidMkExtraFootersFunc func(w io.Writer, name, prefix, moduleDir string)
Jaewoong Junge0dc8df2019-08-27 17:33:16 -0700179
Jaewoong Jung7ef4a902020-11-16 12:50:29 -0800180// Utility funcs to manipulate Android.mk variable entries.
181
182// SetString sets a Make variable with the given name to the given value.
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700183func (a *AndroidMkEntries) SetString(name, value string) {
184 if _, ok := a.EntryMap[name]; !ok {
185 a.entryOrder = append(a.entryOrder, name)
186 }
187 a.EntryMap[name] = []string{value}
188}
189
Jaewoong Jung7ef4a902020-11-16 12:50:29 -0800190// SetPath sets a Make variable with the given name to the given path string.
Jaewoong Jung9a1e8bd2019-09-04 20:17:54 -0700191func (a *AndroidMkEntries) SetPath(name string, path Path) {
192 if _, ok := a.EntryMap[name]; !ok {
193 a.entryOrder = append(a.entryOrder, name)
194 }
195 a.EntryMap[name] = []string{path.String()}
196}
197
Jaewoong Jung7ef4a902020-11-16 12:50:29 -0800198// SetOptionalPath sets a Make variable with the given name to the given path string if it is valid.
199// It is a no-op if the given path is invalid.
Colin Crossc0efd1d2020-07-03 11:56:24 -0700200func (a *AndroidMkEntries) SetOptionalPath(name string, path OptionalPath) {
201 if path.Valid() {
202 a.SetPath(name, path.Path())
203 }
204}
205
Jaewoong Jung7ef4a902020-11-16 12:50:29 -0800206// AddPath appends the given path string to a Make variable with the given name.
Colin Crossc0efd1d2020-07-03 11:56:24 -0700207func (a *AndroidMkEntries) AddPath(name string, path Path) {
208 if _, ok := a.EntryMap[name]; !ok {
209 a.entryOrder = append(a.entryOrder, name)
210 }
211 a.EntryMap[name] = append(a.EntryMap[name], path.String())
212}
213
Jaewoong Jung7ef4a902020-11-16 12:50:29 -0800214// AddOptionalPath appends the given path string to a Make variable with the given name if it is
215// valid. It is a no-op if the given path is invalid.
Colin Crossc0efd1d2020-07-03 11:56:24 -0700216func (a *AndroidMkEntries) AddOptionalPath(name string, path OptionalPath) {
217 if path.Valid() {
218 a.AddPath(name, path.Path())
219 }
220}
221
Jaewoong Jung7ef4a902020-11-16 12:50:29 -0800222// SetPaths sets a Make variable with the given name to a slice of the given path strings.
Colin Cross08dca382020-07-21 20:31:17 -0700223func (a *AndroidMkEntries) SetPaths(name string, paths Paths) {
224 if _, ok := a.EntryMap[name]; !ok {
225 a.entryOrder = append(a.entryOrder, name)
226 }
227 a.EntryMap[name] = paths.Strings()
228}
229
Jaewoong Jung7ef4a902020-11-16 12:50:29 -0800230// SetOptionalPaths sets a Make variable with the given name to a slice of the given path strings
231// only if there are a non-zero amount of paths.
Colin Cross08dca382020-07-21 20:31:17 -0700232func (a *AndroidMkEntries) SetOptionalPaths(name string, paths Paths) {
233 if len(paths) > 0 {
234 a.SetPaths(name, paths)
235 }
236}
237
Jaewoong Jung7ef4a902020-11-16 12:50:29 -0800238// AddPaths appends the given path strings to a Make variable with the given name.
Colin Cross08dca382020-07-21 20:31:17 -0700239func (a *AndroidMkEntries) AddPaths(name string, paths Paths) {
240 if _, ok := a.EntryMap[name]; !ok {
241 a.entryOrder = append(a.entryOrder, name)
242 }
243 a.EntryMap[name] = append(a.EntryMap[name], paths.Strings()...)
244}
245
Jaewoong Jung7ef4a902020-11-16 12:50:29 -0800246// SetBoolIfTrue sets a Make variable with the given name to true if the given flag is true.
247// It is a no-op if the given flag is false.
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700248func (a *AndroidMkEntries) SetBoolIfTrue(name string, flag bool) {
249 if flag {
250 if _, ok := a.EntryMap[name]; !ok {
251 a.entryOrder = append(a.entryOrder, name)
252 }
253 a.EntryMap[name] = []string{"true"}
254 }
255}
256
Jaewoong Jung7ef4a902020-11-16 12:50:29 -0800257// SetBool sets a Make variable with the given name to if the given bool flag value.
Jaewoong Jung9a1e8bd2019-09-04 20:17:54 -0700258func (a *AndroidMkEntries) SetBool(name string, flag bool) {
259 if _, ok := a.EntryMap[name]; !ok {
260 a.entryOrder = append(a.entryOrder, name)
261 }
262 if flag {
263 a.EntryMap[name] = []string{"true"}
264 } else {
265 a.EntryMap[name] = []string{"false"}
266 }
267}
268
Jaewoong Jung7ef4a902020-11-16 12:50:29 -0800269// AddStrings appends the given strings to a Make variable with the given name.
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700270func (a *AndroidMkEntries) AddStrings(name string, value ...string) {
271 if len(value) == 0 {
272 return
273 }
274 if _, ok := a.EntryMap[name]; !ok {
275 a.entryOrder = append(a.entryOrder, name)
276 }
277 a.EntryMap[name] = append(a.EntryMap[name], value...)
278}
279
Liz Kammer57f5b332020-11-24 12:42:58 -0800280// AddCompatibilityTestSuites adds the supplied test suites to the EntryMap, with special handling
Tongbo Liuc5f7b962024-01-04 09:03:35 +0000281// for partial MTS and MCTS test suites.
Liz Kammer57f5b332020-11-24 12:42:58 -0800282func (a *AndroidMkEntries) AddCompatibilityTestSuites(suites ...string) {
Tongbo Liuc5f7b962024-01-04 09:03:35 +0000283 // M(C)TS supports a full test suite and partial per-module MTS test suites, with naming mts-${MODULE}.
284 // 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 -0800285 // we add the full test suite to our list.
286 if PrefixInList(suites, "mts-") && !InList("mts", suites) {
287 suites = append(suites, "mts")
288 }
Tongbo Liuc5f7b962024-01-04 09:03:35 +0000289 if PrefixInList(suites, "mcts-") && !InList("mcts", suites) {
290 suites = append(suites, "mcts")
291 }
Liz Kammer57f5b332020-11-24 12:42:58 -0800292 a.AddStrings("LOCAL_COMPATIBILITY_SUITE", suites...)
293}
294
Paul Duffin8b0349c2020-11-26 14:33:21 +0000295// The contributions to the dist.
296type distContributions struct {
Bob Badour51804382022-04-13 11:27:19 -0700297 // Path to license metadata file.
298 licenseMetadataFile Path
Paul Duffin8b0349c2020-11-26 14:33:21 +0000299 // List of goals and the dist copy instructions.
300 copiesForGoals []*copiesForGoals
301}
302
303// getCopiesForGoals returns a copiesForGoals into which copy instructions that
304// must be processed when building one or more of those goals can be added.
305func (d *distContributions) getCopiesForGoals(goals string) *copiesForGoals {
306 copiesForGoals := &copiesForGoals{goals: goals}
307 d.copiesForGoals = append(d.copiesForGoals, copiesForGoals)
308 return copiesForGoals
309}
310
311// Associates a list of dist copy instructions with a set of goals for which they
312// should be run.
313type copiesForGoals struct {
314 // goals are a space separated list of build targets that will trigger the
315 // copy instructions.
316 goals string
317
318 // A list of instructions to copy a module's output files to somewhere in the
319 // dist directory.
320 copies []distCopy
321}
322
323// Adds a copy instruction.
324func (d *copiesForGoals) addCopyInstruction(from Path, dest string) {
325 d.copies = append(d.copies, distCopy{from, dest})
326}
327
328// Instruction on a path that must be copied into the dist.
329type distCopy struct {
330 // The path to copy from.
331 from Path
332
333 // The destination within the dist directory to copy to.
334 dest string
335}
336
337// Compute the contributions that the module makes to the dist.
338func (a *AndroidMkEntries) getDistContributions(mod blueprint.Module) *distContributions {
Jingwen Chen40fd90a2020-06-15 05:24:19 +0000339 amod := mod.(Module).base()
340 name := amod.BaseModuleName()
341
Paul Duffin74f05592020-11-25 16:37:46 +0000342 // Collate the set of associated tag/paths available for copying to the dist.
343 // Start with an empty (nil) set.
Jingwen Chen7b27ca72020-07-24 09:13:49 +0000344 var availableTaggedDists TaggedDistFiles
Jingwen Chen40fd90a2020-06-15 05:24:19 +0000345
Paul Duffin74f05592020-11-25 16:37:46 +0000346 // Then merge in any that are provided explicitly by the module.
Jingwen Chen84811862020-07-21 11:32:19 +0000347 if a.DistFiles != nil {
Paul Duffin74f05592020-11-25 16:37:46 +0000348 // Merge the DistFiles into the set.
349 availableTaggedDists = availableTaggedDists.merge(a.DistFiles)
350 }
351
352 // If no paths have been provided for the DefaultDistTag and the output file is
353 // valid then add that as the default dist path.
354 if _, ok := availableTaggedDists[DefaultDistTag]; !ok && a.OutputFile.Valid() {
355 availableTaggedDists = availableTaggedDists.addPathsForTag(DefaultDistTag, a.OutputFile.Path())
356 }
357
Yu Liuec810542024-08-26 18:09:15 +0000358 info := OtherModuleProviderOrDefault(a.entryContext, mod, InstallFilesProvider)
Paul Duffinaf970a22020-11-23 23:32:56 +0000359 // If the distFiles created by GenerateTaggedDistFiles contains paths for the
360 // DefaultDistTag then that takes priority so delete any existing paths.
Yu Liuec810542024-08-26 18:09:15 +0000361 if _, ok := info.DistFiles[DefaultDistTag]; ok {
Paul Duffinaf970a22020-11-23 23:32:56 +0000362 delete(availableTaggedDists, DefaultDistTag)
363 }
364
365 // Finally, merge the distFiles created by GenerateTaggedDistFiles.
Yu Liuec810542024-08-26 18:09:15 +0000366 availableTaggedDists = availableTaggedDists.merge(info.DistFiles)
Paul Duffinaf970a22020-11-23 23:32:56 +0000367
Paul Duffin74f05592020-11-25 16:37:46 +0000368 if len(availableTaggedDists) == 0 {
Jingwen Chen7b27ca72020-07-24 09:13:49 +0000369 // Nothing dist-able for this module.
370 return nil
Jingwen Chen40fd90a2020-06-15 05:24:19 +0000371 }
372
Paul Duffin8b0349c2020-11-26 14:33:21 +0000373 // Collate the contributions this module makes to the dist.
374 distContributions := &distContributions{}
375
Bob Badour4660a982022-09-12 16:06:03 -0700376 if !exemptFromRequiredApplicableLicensesProperty(mod.(Module)) {
Yu Liuec810542024-08-26 18:09:15 +0000377 distContributions.licenseMetadataFile = info.LicenseMetadataFile
Bob Badour4660a982022-09-12 16:06:03 -0700378 }
Bob Badour51804382022-04-13 11:27:19 -0700379
Jingwen Chen40fd90a2020-06-15 05:24:19 +0000380 // Iterate over this module's dist structs, merged from the dist and dists properties.
381 for _, dist := range amod.Dists() {
382 // Get the list of goals this dist should be enabled for. e.g. sdk, droidcore
383 goals := strings.Join(dist.Targets, " ")
384
385 // Get the tag representing the output files to be dist'd. e.g. ".jar", ".proguard_map"
386 var tag string
387 if dist.Tag == nil {
388 // If the dist struct does not specify a tag, use the default output files tag.
Paul Duffin74f05592020-11-25 16:37:46 +0000389 tag = DefaultDistTag
Jingwen Chen40fd90a2020-06-15 05:24:19 +0000390 } else {
391 tag = *dist.Tag
392 }
393
394 // Get the paths of the output files to be dist'd, represented by the tag.
395 // Can be an empty list.
396 tagPaths := availableTaggedDists[tag]
397 if len(tagPaths) == 0 {
398 // Nothing to dist for this tag, continue to the next dist.
399 continue
400 }
401
402 if len(tagPaths) > 1 && (dist.Dest != nil || dist.Suffix != nil) {
Paul Duffin74f05592020-11-25 16:37:46 +0000403 errorMessage := "%s: Cannot apply dest/suffix for more than one dist " +
404 "file for %q goals tag %q in module %s. The list of dist files, " +
Jingwen Chen40fd90a2020-06-15 05:24:19 +0000405 "which should have a single element, is:\n%s"
Paul Duffin74f05592020-11-25 16:37:46 +0000406 panic(fmt.Errorf(errorMessage, mod, goals, tag, name, tagPaths))
Jingwen Chen40fd90a2020-06-15 05:24:19 +0000407 }
408
Paul Duffin8b0349c2020-11-26 14:33:21 +0000409 copiesForGoals := distContributions.getCopiesForGoals(goals)
Jingwen Chen40fd90a2020-06-15 05:24:19 +0000410
Paul Duffin8b0349c2020-11-26 14:33:21 +0000411 // Iterate over each path adding a copy instruction to copiesForGoals
Jingwen Chen40fd90a2020-06-15 05:24:19 +0000412 for _, path := range tagPaths {
413 // It's possible that the Path is nil from errant modules. Be defensive here.
414 if path == nil {
415 tagName := "default" // for error message readability
416 if dist.Tag != nil {
417 tagName = *dist.Tag
418 }
419 panic(fmt.Errorf("Dist file should not be nil for the %s tag in %s", tagName, name))
420 }
421
422 dest := filepath.Base(path.String())
423
424 if dist.Dest != nil {
425 var err error
426 if dest, err = validateSafePath(*dist.Dest); err != nil {
427 // This was checked in ModuleBase.GenerateBuildActions
428 panic(err)
429 }
430 }
431
Trevor Radcliffe90727f42022-03-21 19:34:02 +0000432 ext := filepath.Ext(dest)
433 suffix := ""
Jingwen Chen40fd90a2020-06-15 05:24:19 +0000434 if dist.Suffix != nil {
Trevor Radcliffe90727f42022-03-21 19:34:02 +0000435 suffix = *dist.Suffix
436 }
437
438 productString := ""
439 if dist.Append_artifact_with_product != nil && *dist.Append_artifact_with_product {
440 productString = fmt.Sprintf("_%s", a.entryContext.Config().DeviceProduct())
441 }
442
443 if suffix != "" || productString != "" {
444 dest = strings.TrimSuffix(dest, ext) + suffix + productString + ext
Jingwen Chen40fd90a2020-06-15 05:24:19 +0000445 }
446
447 if dist.Dir != nil {
448 var err error
449 if dest, err = validateSafePath(*dist.Dir, dest); err != nil {
450 // This was checked in ModuleBase.GenerateBuildActions
451 panic(err)
452 }
453 }
454
Paul Duffin8b0349c2020-11-26 14:33:21 +0000455 copiesForGoals.addCopyInstruction(path, dest)
456 }
457 }
458
459 return distContributions
460}
461
462// generateDistContributionsForMake generates make rules that will generate the
463// dist according to the instructions in the supplied distContribution.
464func generateDistContributionsForMake(distContributions *distContributions) []string {
465 var ret []string
466 for _, d := range distContributions.copiesForGoals {
467 ret = append(ret, fmt.Sprintf(".PHONY: %s\n", d.goals))
468 // Create dist-for-goals calls for each of the copy instructions.
469 for _, c := range d.copies {
Bob Badour4660a982022-09-12 16:06:03 -0700470 if distContributions.licenseMetadataFile != nil {
471 ret = append(
472 ret,
473 fmt.Sprintf("$(if $(strip $(ALL_TARGETS.%s.META_LIC)),,$(eval ALL_TARGETS.%s.META_LIC := %s))\n",
474 c.from.String(), c.from.String(), distContributions.licenseMetadataFile.String()))
475 }
Bob Badour51804382022-04-13 11:27:19 -0700476 ret = append(
477 ret,
Paul Duffin8b0349c2020-11-26 14:33:21 +0000478 fmt.Sprintf("$(call dist-for-goals,%s,%s:%s)\n", d.goals, c.from.String(), c.dest))
Jingwen Chen40fd90a2020-06-15 05:24:19 +0000479 }
480 }
481
482 return ret
483}
484
Paul Duffin8b0349c2020-11-26 14:33:21 +0000485// Compute the list of Make strings to declare phony goals and dist-for-goals
486// calls from the module's dist and dists properties.
487func (a *AndroidMkEntries) GetDistForGoals(mod blueprint.Module) []string {
488 distContributions := a.getDistContributions(mod)
489 if distContributions == nil {
490 return nil
491 }
492
493 return generateDistContributionsForMake(distContributions)
494}
495
Jaewoong Jung7ef4a902020-11-16 12:50:29 -0800496// fillInEntries goes through the common variable processing and calls the extra data funcs to
497// generate and fill in AndroidMkEntries's in-struct data, ready to be flushed to a file.
Colin Crossaa255532020-07-03 13:18:24 -0700498type fillInEntriesContext interface {
499 ModuleDir(module blueprint.Module) string
Cole Faust39aabe92023-02-23 16:57:43 -0800500 ModuleSubDir(module blueprint.Module) string
Colin Crossaa255532020-07-03 13:18:24 -0700501 Config() Config
Yu Liu663e4502024-08-12 18:23:59 +0000502 otherModuleProvider(module blueprint.Module, provider blueprint.AnyProviderKey) (any, bool)
Sasha Smundak5c4729d2022-12-01 10:49:23 -0800503 ModuleType(module blueprint.Module) string
Cole Faust43ddd082024-06-17 12:32:40 -0700504 OtherModulePropertyErrorf(module Module, property string, fmt string, args ...interface{})
Colin Crossaa255532020-07-03 13:18:24 -0700505}
506
507func (a *AndroidMkEntries) fillInEntries(ctx fillInEntriesContext, mod blueprint.Module) {
Trevor Radcliffe90727f42022-03-21 19:34:02 +0000508 a.entryContext = ctx
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700509 a.EntryMap = make(map[string][]string)
Colin Crossf1f763a2021-10-21 16:14:19 -0700510 amod := mod.(Module)
511 base := amod.base()
512 name := base.BaseModuleName()
Colin Cross0477b422020-10-13 18:43:54 -0700513 if a.OverrideName != "" {
514 name = a.OverrideName
515 }
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700516
517 if a.Include == "" {
518 a.Include = "$(BUILD_PREBUILT)"
519 }
Cole Faust43ddd082024-06-17 12:32:40 -0700520 a.Required = append(a.Required, amod.RequiredModuleNames(ctx)...)
Kiyoung Kim04b64fc2024-08-19 11:25:30 +0900521 a.Required = append(a.Required, amod.VintfFragmentModuleNames(ctx)...)
Colin Crossf1f763a2021-10-21 16:14:19 -0700522 a.Host_required = append(a.Host_required, amod.HostRequiredModuleNames()...)
523 a.Target_required = append(a.Target_required, amod.TargetRequiredModuleNames()...)
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700524
Jingwen Chen40fd90a2020-06-15 05:24:19 +0000525 for _, distString := range a.GetDistForGoals(mod) {
526 fmt.Fprintf(&a.header, distString)
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700527 }
528
Cole Faust39aabe92023-02-23 16:57:43 -0800529 fmt.Fprintf(&a.header, "\ninclude $(CLEAR_VARS) # type: %s, name: %s, variant: %s\n", ctx.ModuleType(mod), base.BaseModuleName(), ctx.ModuleSubDir(mod))
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700530
531 // Collect make variable assignment entries.
Colin Crossaa255532020-07-03 13:18:24 -0700532 a.SetString("LOCAL_PATH", ctx.ModuleDir(mod))
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700533 a.SetString("LOCAL_MODULE", name+a.SubName)
534 a.SetString("LOCAL_MODULE_CLASS", a.Class)
535 a.SetString("LOCAL_PREBUILT_MODULE_FILE", a.OutputFile.String())
536 a.AddStrings("LOCAL_REQUIRED_MODULES", a.Required...)
537 a.AddStrings("LOCAL_HOST_REQUIRED_MODULES", a.Host_required...)
538 a.AddStrings("LOCAL_TARGET_REQUIRED_MODULES", a.Target_required...)
Wei Li598f92d2023-01-04 17:12:24 -0800539 a.AddStrings("LOCAL_SOONG_MODULE_TYPE", ctx.ModuleType(amod))
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700540
Colin Cross6301c3c2021-09-28 17:40:21 -0700541 // If the install rule was generated by Soong tell Make about it.
Yu Liud46e5ae2024-08-15 18:46:17 +0000542 info := OtherModuleProviderOrDefault(ctx, mod, InstallFilesProvider)
543 if len(info.KatiInstalls) > 0 {
Colin Cross6301c3c2021-09-28 17:40:21 -0700544 // Assume the primary install file is last since it probably needs to depend on any other
545 // installed files. If that is not the case we can add a method to specify the primary
546 // installed file.
Yu Liud46e5ae2024-08-15 18:46:17 +0000547 a.SetPath("LOCAL_SOONG_INSTALLED_MODULE", info.KatiInstalls[len(info.KatiInstalls)-1].to)
548 a.SetString("LOCAL_SOONG_INSTALL_PAIRS", info.KatiInstalls.BuiltInstalled())
549 a.SetPaths("LOCAL_SOONG_INSTALL_SYMLINKS", info.KatiSymlinks.InstallPaths().Paths())
Jiyong Park3f627e62024-05-01 16:14:38 +0900550 } else {
551 // Soong may not have generated the install rule also when `no_full_install: true`.
552 // Mark this module as uninstallable in order to prevent Make from creating an
553 // install rule there.
554 a.SetBoolIfTrue("LOCAL_UNINSTALLABLE_MODULE", proptools.Bool(base.commonProperties.No_full_install))
Colin Cross6301c3c2021-09-28 17:40:21 -0700555 }
556
Yu Liud46e5ae2024-08-15 18:46:17 +0000557 if len(info.TestData) > 0 {
558 a.AddStrings("LOCAL_TEST_DATA", androidMkDataPaths(info.TestData)...)
Colin Cross5c1d5fb2023-11-15 12:39:40 -0800559 }
560
Jiyong Park89e850a2020-04-07 16:37:39 +0900561 if am, ok := mod.(ApexModule); ok {
562 a.SetBoolIfTrue("LOCAL_NOT_AVAILABLE_FOR_PLATFORM", am.NotAvailableForPlatform())
563 }
564
Colin Crossf1f763a2021-10-21 16:14:19 -0700565 archStr := base.Arch().ArchType.String()
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700566 host := false
Colin Crossf1f763a2021-10-21 16:14:19 -0700567 switch base.Os().Class {
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700568 case Host:
Colin Crossf1f763a2021-10-21 16:14:19 -0700569 if base.Target().HostCross {
Jiyong Park1613e552020-09-14 19:43:17 +0900570 // Make cannot identify LOCAL_MODULE_HOST_CROSS_ARCH:= common.
Colin Crossf1f763a2021-10-21 16:14:19 -0700571 if base.Arch().ArchType != Common {
Jiyong Park1613e552020-09-14 19:43:17 +0900572 a.SetString("LOCAL_MODULE_HOST_CROSS_ARCH", archStr)
573 }
574 } else {
575 // Make cannot identify LOCAL_MODULE_HOST_ARCH:= common.
Colin Crossf1f763a2021-10-21 16:14:19 -0700576 if base.Arch().ArchType != Common {
Jiyong Park1613e552020-09-14 19:43:17 +0900577 a.SetString("LOCAL_MODULE_HOST_ARCH", archStr)
578 }
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700579 }
580 host = true
581 case Device:
582 // Make cannot identify LOCAL_MODULE_TARGET_ARCH:= common.
Colin Crossf1f763a2021-10-21 16:14:19 -0700583 if base.Arch().ArchType != Common {
584 if base.Target().NativeBridge {
585 hostArchStr := base.Target().NativeBridgeHostArchName
dimitry1f33e402019-03-26 12:39:31 +0100586 if hostArchStr != "" {
587 a.SetString("LOCAL_MODULE_TARGET_ARCH", hostArchStr)
588 }
589 } else {
590 a.SetString("LOCAL_MODULE_TARGET_ARCH", archStr)
591 }
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700592 }
593
Kelvin Zhang46977252022-04-13 16:41:34 -0700594 if !base.InVendorRamdisk() {
Colin Crossf1f763a2021-10-21 16:14:19 -0700595 a.AddPaths("LOCAL_FULL_INIT_RC", base.initRcPaths)
Yifan Hong919dae12020-12-02 18:55:06 -0800596 }
Colin Crossf1f763a2021-10-21 16:14:19 -0700597 if len(base.vintfFragmentsPaths) > 0 {
598 a.AddPaths("LOCAL_FULL_VINTF_FRAGMENTS", base.vintfFragmentsPaths)
Liz Kammer7b3dc8a2021-04-16 16:41:59 -0400599 }
Colin Crossf1f763a2021-10-21 16:14:19 -0700600 a.SetBoolIfTrue("LOCAL_PROPRIETARY_MODULE", Bool(base.commonProperties.Proprietary))
601 if Bool(base.commonProperties.Vendor) || Bool(base.commonProperties.Soc_specific) {
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700602 a.SetString("LOCAL_VENDOR_MODULE", "true")
603 }
Colin Crossf1f763a2021-10-21 16:14:19 -0700604 a.SetBoolIfTrue("LOCAL_ODM_MODULE", Bool(base.commonProperties.Device_specific))
605 a.SetBoolIfTrue("LOCAL_PRODUCT_MODULE", Bool(base.commonProperties.Product_specific))
606 a.SetBoolIfTrue("LOCAL_SYSTEM_EXT_MODULE", Bool(base.commonProperties.System_ext_specific))
607 if base.commonProperties.Owner != nil {
608 a.SetString("LOCAL_MODULE_OWNER", *base.commonProperties.Owner)
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700609 }
610 }
611
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700612 if host {
Colin Crossf1f763a2021-10-21 16:14:19 -0700613 makeOs := base.Os().String()
614 if base.Os() == Linux || base.Os() == LinuxBionic || base.Os() == LinuxMusl {
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700615 makeOs = "linux"
616 }
617 a.SetString("LOCAL_MODULE_HOST_OS", makeOs)
618 a.SetString("LOCAL_IS_HOST_MODULE", "true")
619 }
620
621 prefix := ""
Colin Crossf1f763a2021-10-21 16:14:19 -0700622 if base.ArchSpecific() {
623 switch base.Os().Class {
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700624 case Host:
Colin Crossf1f763a2021-10-21 16:14:19 -0700625 if base.Target().HostCross {
Jiyong Park1613e552020-09-14 19:43:17 +0900626 prefix = "HOST_CROSS_"
627 } else {
628 prefix = "HOST_"
629 }
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700630 case Device:
631 prefix = "TARGET_"
632
633 }
634
Colin Crossf1f763a2021-10-21 16:14:19 -0700635 if base.Arch().ArchType != ctx.Config().Targets[base.Os()][0].Arch.ArchType {
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700636 prefix = "2ND_" + prefix
637 }
638 }
Colin Crossaa255532020-07-03 13:18:24 -0700639
Yu Liu663e4502024-08-12 18:23:59 +0000640 if licenseMetadata, ok := OtherModuleProvider(ctx, mod, LicenseMetadataProvider); ok {
Colin Cross4acaea92021-12-10 23:05:02 +0000641 a.SetPath("LOCAL_SOONG_LICENSE_METADATA", licenseMetadata.LicenseMetadataPath)
642 }
643
Yu Liu663e4502024-08-12 18:23:59 +0000644 if _, ok := OtherModuleProvider(ctx, mod, ModuleInfoJSONProvider); ok {
Colin Crossd6fd0132023-11-06 13:54:06 -0800645 a.SetBool("LOCAL_SOONG_MODULE_INFO_JSON", true)
646 }
647
Colin Crossaa255532020-07-03 13:18:24 -0700648 extraCtx := &androidMkExtraEntriesContext{
649 ctx: ctx,
650 mod: mod,
651 }
652
Jaewoong Junge0dc8df2019-08-27 17:33:16 -0700653 for _, extra := range a.ExtraEntries {
Colin Crossaa255532020-07-03 13:18:24 -0700654 extra(extraCtx, a)
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700655 }
656
657 // Write to footer.
658 fmt.Fprintln(&a.footer, "include "+a.Include)
Colin Crossaa255532020-07-03 13:18:24 -0700659 blueprintDir := ctx.ModuleDir(mod)
Jaewoong Jungb0c127c2019-08-29 14:56:03 -0700660 for _, footerFunc := range a.ExtraFooters {
Jaewoong Jung02b11a62020-12-07 10:23:54 -0800661 footerFunc(&a.footer, name, prefix, blueprintDir)
Jaewoong Jungb0c127c2019-08-29 14:56:03 -0700662 }
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700663}
664
Colin Crossd6fd0132023-11-06 13:54:06 -0800665func (a *AndroidMkEntries) disabled() bool {
666 return a.Disabled || !a.OutputFile.Valid()
667}
668
Jaewoong Jung7ef4a902020-11-16 12:50:29 -0800669// write flushes the AndroidMkEntries's in-struct data populated by AndroidMkEntries into the
670// given Writer object.
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700671func (a *AndroidMkEntries) write(w io.Writer) {
Colin Crossd6fd0132023-11-06 13:54:06 -0800672 if a.disabled() {
Jaewoong Jungb0c127c2019-08-29 14:56:03 -0700673 return
674 }
675
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700676 w.Write(a.header.Bytes())
677 for _, name := range a.entryOrder {
Sasha Smundakdcb61292022-12-08 10:41:33 -0800678 AndroidMkEmitAssignList(w, name, a.EntryMap[name])
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700679 }
680 w.Write(a.footer.Bytes())
681}
682
Jaewoong Jungb0c127c2019-08-29 14:56:03 -0700683func (a *AndroidMkEntries) FooterLinesForTests() []string {
684 return strings.Split(string(a.footer.Bytes()), "\n")
685}
686
Jaewoong Jung7ef4a902020-11-16 12:50:29 -0800687// AndroidMkSingleton is a singleton to collect Android.mk data from all modules and dump them into
688// the final Android-<product_name>.mk file output.
Colin Cross0875c522017-11-28 17:34:01 -0800689func AndroidMkSingleton() Singleton {
Dan Willemsen218f6562015-07-08 18:13:11 -0700690 return &androidMkSingleton{}
691}
692
693type androidMkSingleton struct{}
694
Colin Cross0875c522017-11-28 17:34:01 -0800695func (c *androidMkSingleton) GenerateBuildActions(ctx SingletonContext) {
Jaewoong Jung7ef4a902020-11-16 12:50:29 -0800696 // Skip if Soong wasn't invoked from Make.
Jingwen Chencda22c92020-11-23 00:22:30 -0500697 if !ctx.Config().KatiEnabled() {
Dan Willemsen5ba07e82015-12-11 13:51:06 -0800698 return
699 }
700
Colin Cross2465c3d2018-09-28 10:19:18 -0700701 var androidMkModulesList []blueprint.Module
Colin Cross4f6e4e62016-01-11 12:55:55 -0800702
Colin Cross2465c3d2018-09-28 10:19:18 -0700703 ctx.VisitAllModulesBlueprint(func(module blueprint.Module) {
Colin Cross0875c522017-11-28 17:34:01 -0800704 androidMkModulesList = append(androidMkModulesList, module)
Colin Cross4f6e4e62016-01-11 12:55:55 -0800705 })
Dan Willemsen218f6562015-07-08 18:13:11 -0700706
Jaewoong Jung7ef4a902020-11-16 12:50:29 -0800707 // Sort the module list by the module names to eliminate random churns, which may erroneously
708 // invoke additional build processes.
Colin Cross1ad81422019-01-14 12:47:35 -0800709 sort.SliceStable(androidMkModulesList, func(i, j int) bool {
710 return ctx.ModuleName(androidMkModulesList[i]) < ctx.ModuleName(androidMkModulesList[j])
711 })
Colin Crossd779da42015-12-17 18:00:23 -0800712
Dan Willemsen45133ac2018-03-09 21:22:06 -0800713 transMk := PathForOutput(ctx, "Android"+String(ctx.Config().productVariables.Make_suffix)+".mk")
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700714 if ctx.Failed() {
715 return
716 }
Dan Willemsen218f6562015-07-08 18:13:11 -0700717
Colin Crossd6fd0132023-11-06 13:54:06 -0800718 moduleInfoJSON := PathForOutput(ctx, "module-info"+String(ctx.Config().productVariables.Make_suffix)+".json")
719
720 err := translateAndroidMk(ctx, absolutePath(transMk.String()), moduleInfoJSON, androidMkModulesList)
Dan Willemsen218f6562015-07-08 18:13:11 -0700721 if err != nil {
722 ctx.Errorf(err.Error())
723 }
724
Colin Cross0875c522017-11-28 17:34:01 -0800725 ctx.Build(pctx, BuildParams{
726 Rule: blueprint.Phony,
727 Output: transMk,
Dan Willemsen218f6562015-07-08 18:13:11 -0700728 })
729}
730
Colin Crossd6fd0132023-11-06 13:54:06 -0800731func translateAndroidMk(ctx SingletonContext, absMkFile string, moduleInfoJSONPath WritablePath, mods []blueprint.Module) error {
Dan Willemsen218f6562015-07-08 18:13:11 -0700732 buf := &bytes.Buffer{}
733
Colin Crossd6fd0132023-11-06 13:54:06 -0800734 var moduleInfoJSONs []*ModuleInfoJSON
735
Dan Willemsen97750522016-02-09 17:43:51 -0800736 fmt.Fprintln(buf, "LOCAL_MODULE_MAKEFILE := $(lastword $(MAKEFILE_LIST))")
Dan Willemsen218f6562015-07-08 18:13:11 -0700737
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800738 typeStats := make(map[string]int)
Dan Willemsen218f6562015-07-08 18:13:11 -0700739 for _, mod := range mods {
Colin Crossd6fd0132023-11-06 13:54:06 -0800740 err := translateAndroidMkModule(ctx, buf, &moduleInfoJSONs, mod)
Dan Willemsen218f6562015-07-08 18:13:11 -0700741 if err != nil {
Colin Cross836e3872021-11-09 12:30:59 -0800742 os.Remove(absMkFile)
Dan Willemsen218f6562015-07-08 18:13:11 -0700743 return err
744 }
Dan Willemsen70e17fa2016-07-25 16:00:20 -0700745
Colin Cross2465c3d2018-09-28 10:19:18 -0700746 if amod, ok := mod.(Module); ok && ctx.PrimaryModule(amod) == amod {
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800747 typeStats[ctx.ModuleType(amod)] += 1
Dan Willemsen70e17fa2016-07-25 16:00:20 -0700748 }
749 }
750
751 keys := []string{}
752 fmt.Fprintln(buf, "\nSTATS.SOONG_MODULE_TYPE :=")
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800753 for k := range typeStats {
Dan Willemsen70e17fa2016-07-25 16:00:20 -0700754 keys = append(keys, k)
755 }
756 sort.Strings(keys)
757 for _, mod_type := range keys {
758 fmt.Fprintln(buf, "STATS.SOONG_MODULE_TYPE +=", mod_type)
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800759 fmt.Fprintf(buf, "STATS.SOONG_MODULE_TYPE.%s := %d\n", mod_type, typeStats[mod_type])
Dan Willemsen218f6562015-07-08 18:13:11 -0700760 }
761
Colin Crossd6fd0132023-11-06 13:54:06 -0800762 err := pathtools.WriteFileIfChanged(absMkFile, buf.Bytes(), 0666)
763 if err != nil {
764 return err
765 }
766
767 return writeModuleInfoJSON(ctx, moduleInfoJSONs, moduleInfoJSONPath)
Dan Willemsen218f6562015-07-08 18:13:11 -0700768}
769
Colin Crossd6fd0132023-11-06 13:54:06 -0800770func writeModuleInfoJSON(ctx SingletonContext, moduleInfoJSONs []*ModuleInfoJSON, moduleInfoJSONPath WritablePath) error {
771 moduleInfoJSONBuf := &strings.Builder{}
772 moduleInfoJSONBuf.WriteString("[")
773 for i, moduleInfoJSON := range moduleInfoJSONs {
774 if i != 0 {
775 moduleInfoJSONBuf.WriteString(",\n")
776 }
777 moduleInfoJSONBuf.WriteString("{")
778 moduleInfoJSONBuf.WriteString(strconv.Quote(moduleInfoJSON.core.RegisterName))
779 moduleInfoJSONBuf.WriteString(":")
780 err := encodeModuleInfoJSON(moduleInfoJSONBuf, moduleInfoJSON)
781 moduleInfoJSONBuf.WriteString("}")
782 if err != nil {
783 return err
784 }
785 }
786 moduleInfoJSONBuf.WriteString("]")
787 WriteFileRule(ctx, moduleInfoJSONPath, moduleInfoJSONBuf.String())
788 return nil
789}
790
791func translateAndroidMkModule(ctx SingletonContext, w io.Writer, moduleInfoJSONs *[]*ModuleInfoJSON, mod blueprint.Module) error {
Colin Cross953d3a22018-09-05 16:23:54 -0700792 defer func() {
793 if r := recover(); r != nil {
794 panic(fmt.Errorf("%s in translateAndroidMkModule for module %s variant %s",
795 r, ctx.ModuleName(mod), ctx.ModuleSubDir(mod)))
796 }
797 }()
798
Bob Badourb4999222021-01-07 03:34:31 +0000799 // Additional cases here require review for correct license propagation to make.
Colin Crossd6fd0132023-11-06 13:54:06 -0800800 var err error
Colin Cross2465c3d2018-09-28 10:19:18 -0700801 switch x := mod.(type) {
802 case AndroidMkDataProvider:
Colin Crossd6fd0132023-11-06 13:54:06 -0800803 err = translateAndroidModule(ctx, w, moduleInfoJSONs, mod, x)
Colin Cross2465c3d2018-09-28 10:19:18 -0700804 case bootstrap.GoBinaryTool:
Colin Crossd6fd0132023-11-06 13:54:06 -0800805 err = translateGoBinaryModule(ctx, w, mod, x)
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700806 case AndroidMkEntriesProvider:
Colin Crossd6fd0132023-11-06 13:54:06 -0800807 err = translateAndroidMkEntriesModule(ctx, w, moduleInfoJSONs, mod, x)
Colin Cross2465c3d2018-09-28 10:19:18 -0700808 default:
Bob Badourb4999222021-01-07 03:34:31 +0000809 // Not exported to make so no make variables to set.
Dan Willemsen218f6562015-07-08 18:13:11 -0700810 }
Colin Crossd6fd0132023-11-06 13:54:06 -0800811
812 if err != nil {
813 return err
814 }
815
816 return err
Colin Cross2465c3d2018-09-28 10:19:18 -0700817}
818
Jaewoong Jung7ef4a902020-11-16 12:50:29 -0800819// A simple, special Android.mk entry output func to make it possible to build blueprint tools using
820// m by making them phony targets.
Colin Cross2465c3d2018-09-28 10:19:18 -0700821func translateGoBinaryModule(ctx SingletonContext, w io.Writer, mod blueprint.Module,
822 goBinary bootstrap.GoBinaryTool) error {
823
824 name := ctx.ModuleName(mod)
825 fmt.Fprintln(w, ".PHONY:", name)
826 fmt.Fprintln(w, name+":", goBinary.InstallPath())
827 fmt.Fprintln(w, "")
Bob Badourb4999222021-01-07 03:34:31 +0000828 // Assuming no rules in make include go binaries in distributables.
829 // If the assumption is wrong, make will fail to build without the necessary .meta_lic and .meta_module files.
830 // In that case, add the targets and rules here to build a .meta_lic file for `name` and a .meta_module for
831 // `goBinary.InstallPath()` pointing to the `name`.meta_lic file.
Colin Cross2465c3d2018-09-28 10:19:18 -0700832
833 return nil
834}
835
Colin Crossaa255532020-07-03 13:18:24 -0700836func (data *AndroidMkData) fillInData(ctx fillInEntriesContext, mod blueprint.Module) {
Jooyung Han12df5fb2019-07-11 16:18:47 +0900837 // Get the preamble content through AndroidMkEntries logic.
Jooyung Han2ed99d02020-06-24 23:26:26 +0900838 data.Entries = AndroidMkEntries{
Jooyung Han12df5fb2019-07-11 16:18:47 +0900839 Class: data.Class,
840 SubName: data.SubName,
Jingwen Chen40fd90a2020-06-15 05:24:19 +0000841 DistFiles: data.DistFiles,
Jooyung Han12df5fb2019-07-11 16:18:47 +0900842 OutputFile: data.OutputFile,
843 Disabled: data.Disabled,
844 Include: data.Include,
845 Required: data.Required,
846 Host_required: data.Host_required,
847 Target_required: data.Target_required,
848 }
Colin Crossaa255532020-07-03 13:18:24 -0700849 data.Entries.fillInEntries(ctx, mod)
Jooyung Han12df5fb2019-07-11 16:18:47 +0900850
851 // copy entries back to data since it is used in Custom
Jooyung Han2ed99d02020-06-24 23:26:26 +0900852 data.Required = data.Entries.Required
853 data.Host_required = data.Entries.Host_required
854 data.Target_required = data.Entries.Target_required
Jooyung Han12df5fb2019-07-11 16:18:47 +0900855}
856
Jaewoong Jung7ef4a902020-11-16 12:50:29 -0800857// A support func for the deprecated AndroidMkDataProvider interface. Use AndroidMkEntryProvider
858// instead.
Colin Crossd6fd0132023-11-06 13:54:06 -0800859func translateAndroidModule(ctx SingletonContext, w io.Writer, moduleInfoJSONs *[]*ModuleInfoJSON,
860 mod blueprint.Module, provider AndroidMkDataProvider) error {
Dan Willemsen218f6562015-07-08 18:13:11 -0700861
Colin Cross635c3b02016-05-18 15:37:25 -0700862 amod := mod.(Module).base()
Cole Fausta963b942024-04-11 17:43:00 -0700863 if shouldSkipAndroidMkProcessing(ctx, amod) {
Jeff Gaston088e29e2017-11-29 16:47:17 -0800864 return nil
865 }
866
Colin Cross91825d22017-08-10 16:59:47 -0700867 data := provider.AndroidMk()
Yu Liuddc28332024-08-09 22:48:30 +0000868
Colin Cross53499412017-09-07 13:20:25 -0700869 if data.Include == "" {
870 data.Include = "$(BUILD_PREBUILT)"
871 }
872
Colin Crossaa255532020-07-03 13:18:24 -0700873 data.fillInData(ctx, mod)
LaMont Jonesb5099382024-01-10 23:42:36 +0000874 aconfigUpdateAndroidMkData(ctx, mod.(Module), &data)
Dan Willemsen01a405a2016-06-13 17:19:03 -0700875
Colin Cross0f86d182017-08-10 17:07:28 -0700876 prefix := ""
877 if amod.ArchSpecific() {
878 switch amod.Os().Class {
879 case Host:
Jiyong Park1613e552020-09-14 19:43:17 +0900880 if amod.Target().HostCross {
881 prefix = "HOST_CROSS_"
882 } else {
883 prefix = "HOST_"
884 }
Colin Cross0f86d182017-08-10 17:07:28 -0700885 case Device:
886 prefix = "TARGET_"
Colin Crossa2344662016-03-24 13:14:12 -0700887
Dan Willemsen218f6562015-07-08 18:13:11 -0700888 }
889
Dan Willemsen0ef639b2018-10-10 17:02:29 -0700890 if amod.Arch().ArchType != ctx.Config().Targets[amod.Os()][0].Arch.ArchType {
Colin Cross0f86d182017-08-10 17:07:28 -0700891 prefix = "2ND_" + prefix
892 }
Dan Willemsen218f6562015-07-08 18:13:11 -0700893 }
894
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700895 name := provider.BaseModuleName()
Colin Cross0f86d182017-08-10 17:07:28 -0700896 blueprintDir := filepath.Dir(ctx.BlueprintFile(mod))
897
898 if data.Custom != nil {
Bob Badourb4999222021-01-07 03:34:31 +0000899 // List of module types allowed to use .Custom(...)
900 // Additions to the list require careful review for proper license handling.
Colin Crossaa255532020-07-03 13:18:24 -0700901 switch reflect.TypeOf(mod).String() { // ctx.ModuleType(mod) doesn't work: aidl_interface creates phony without type
Bob Badourb4999222021-01-07 03:34:31 +0000902 case "*aidl.aidlApi": // writes non-custom before adding .phony
903 case "*aidl.aidlMapping": // writes non-custom before adding .phony
904 case "*android.customModule": // appears in tests only
Dan Willemsen9fe14102021-07-13 21:52:04 -0700905 case "*android_sdk.sdkRepoHost": // doesn't go through base_rules
Bob Badourb4999222021-01-07 03:34:31 +0000906 case "*apex.apexBundle": // license properties written
907 case "*bpf.bpf": // license properties written (both for module and objs)
908 case "*genrule.Module": // writes non-custom before adding .phony
909 case "*java.SystemModules": // doesn't go through base_rules
910 case "*java.systemModulesImport": // doesn't go through base_rules
911 case "*phony.phony": // license properties written
Nelson Lif3c70682023-12-20 02:37:52 +0000912 case "*phony.PhonyRule": // writes phony deps and acts like `.PHONY`
Bob Badourb4999222021-01-07 03:34:31 +0000913 case "*selinux.selinuxContextsModule": // license properties written
914 case "*sysprop.syspropLibrary": // license properties written
yangbill66e555c2024-07-29 03:37:12 +0000915 case "*vintf.vintfCompatibilityMatrixRule": // use case like phony
Bob Badourb4999222021-01-07 03:34:31 +0000916 default:
Bob Badour65ee90a2021-09-02 15:33:10 -0700917 if !ctx.Config().IsEnvFalse("ANDROID_REQUIRE_LICENSES") {
Bob Badourb4999222021-01-07 03:34:31 +0000918 return fmt.Errorf("custom make rules not allowed for %q (%q) module %q", ctx.ModuleType(mod), reflect.TypeOf(mod), ctx.ModuleName(mod))
919 }
920 }
Colin Cross0f86d182017-08-10 17:07:28 -0700921 data.Custom(w, name, prefix, blueprintDir, data)
922 } else {
923 WriteAndroidMkData(w, data)
924 }
925
Colin Crossd6fd0132023-11-06 13:54:06 -0800926 if !data.Entries.disabled() {
Yu Liu663e4502024-08-12 18:23:59 +0000927 if moduleInfoJSON, ok := OtherModuleProvider(ctx, mod, ModuleInfoJSONProvider); ok {
Colin Crossd6fd0132023-11-06 13:54:06 -0800928 *moduleInfoJSONs = append(*moduleInfoJSONs, moduleInfoJSON)
929 }
930 }
931
Colin Cross0f86d182017-08-10 17:07:28 -0700932 return nil
933}
934
Jaewoong Jung7ef4a902020-11-16 12:50:29 -0800935// A support func for the deprecated AndroidMkDataProvider interface. Use AndroidMkEntryProvider
936// instead.
Colin Cross0f86d182017-08-10 17:07:28 -0700937func WriteAndroidMkData(w io.Writer, data AndroidMkData) {
Colin Crossd6fd0132023-11-06 13:54:06 -0800938 if data.Entries.disabled() {
Colin Cross0f86d182017-08-10 17:07:28 -0700939 return
940 }
941
Jooyung Han2ed99d02020-06-24 23:26:26 +0900942 // write preamble via Entries
943 data.Entries.footer = bytes.Buffer{}
944 data.Entries.write(w)
Colin Cross0f86d182017-08-10 17:07:28 -0700945
Colin Crossca860ac2016-01-04 14:34:37 -0800946 for _, extra := range data.Extra {
Colin Cross27a4b052017-08-10 16:32:23 -0700947 extra(w, data.OutputFile.Path())
Dan Willemsen97750522016-02-09 17:43:51 -0800948 }
949
Colin Cross53499412017-09-07 13:20:25 -0700950 fmt.Fprintln(w, "include "+data.Include)
Dan Willemsen218f6562015-07-08 18:13:11 -0700951}
Sasha Smundakb6d23052019-04-01 18:37:36 -0700952
Colin Crossd6fd0132023-11-06 13:54:06 -0800953func translateAndroidMkEntriesModule(ctx SingletonContext, w io.Writer, moduleInfoJSONs *[]*ModuleInfoJSON,
954 mod blueprint.Module, provider AndroidMkEntriesProvider) error {
Cole Fausta963b942024-04-11 17:43:00 -0700955 if shouldSkipAndroidMkProcessing(ctx, mod.(Module).base()) {
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700956 return nil
Sasha Smundakb6d23052019-04-01 18:37:36 -0700957 }
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700958
Colin Crossd6fd0132023-11-06 13:54:06 -0800959 entriesList := provider.AndroidMkEntries()
LaMont Jonesb5099382024-01-10 23:42:36 +0000960 aconfigUpdateAndroidMkEntries(ctx, mod.(Module), &entriesList)
Colin Crossd6fd0132023-11-06 13:54:06 -0800961
Bob Badourb4999222021-01-07 03:34:31 +0000962 // Any new or special cases here need review to verify correct propagation of license information.
Colin Crossd6fd0132023-11-06 13:54:06 -0800963 for _, entries := range entriesList {
Colin Crossaa255532020-07-03 13:18:24 -0700964 entries.fillInEntries(ctx, mod)
Jiyong Park0b0e1b92019-12-03 13:24:29 +0900965 entries.write(w)
966 }
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700967
Colin Crossd6fd0132023-11-06 13:54:06 -0800968 if len(entriesList) > 0 && !entriesList[0].disabled() {
Yu Liu663e4502024-08-12 18:23:59 +0000969 if moduleInfoJSON, ok := OtherModuleProvider(ctx, mod, ModuleInfoJSONProvider); ok {
Colin Crossd6fd0132023-11-06 13:54:06 -0800970 *moduleInfoJSONs = append(*moduleInfoJSONs, moduleInfoJSON)
971 }
972 }
973
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700974 return nil
975}
976
Cole Fausta963b942024-04-11 17:43:00 -0700977func ShouldSkipAndroidMkProcessing(ctx ConfigAndErrorContext, module Module) bool {
978 return shouldSkipAndroidMkProcessing(ctx, module.base())
Chih-Hung Hsieh80783772021-10-11 16:46:56 -0700979}
980
Cole Fausta963b942024-04-11 17:43:00 -0700981func shouldSkipAndroidMkProcessing(ctx ConfigAndErrorContext, module *ModuleBase) bool {
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700982 if !module.commonProperties.NamespaceExportedToMake {
983 // TODO(jeffrygaston) do we want to validate that there are no modules being
984 // exported to Kati that depend on this module?
985 return true
Sasha Smundakb6d23052019-04-01 18:37:36 -0700986 }
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700987
Dan Willemsendef7b5d2021-10-17 00:22:33 -0700988 // On Mac, only expose host darwin modules to Make, as that's all we claim to support.
989 // In reality, some of them depend on device-built (Java) modules, so we can't disable all
990 // device modules in Soong, but we can hide them from Make (and thus the build user interface)
991 if runtime.GOOS == "darwin" && module.Os() != Darwin {
992 return true
993 }
994
Dan Willemsen8528f4e2021-10-19 00:22:06 -0700995 // Only expose the primary Darwin target, as Make does not understand Darwin+Arm64
996 if module.Os() == Darwin && module.Target().HostCross {
997 return true
998 }
999
Cole Fausta963b942024-04-11 17:43:00 -07001000 return !module.Enabled(ctx) ||
Colin Crossa9c8c9f2020-12-16 10:20:23 -08001001 module.commonProperties.HideFromMake ||
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -07001002 // Make does not understand LinuxBionic
Colin Cross9a027be2022-06-24 18:45:58 -07001003 module.Os() == LinuxBionic ||
1004 // Make does not understand LinuxMusl, except when we are building with USE_HOST_MUSL=true
1005 // and all host binaries are LinuxMusl
1006 (module.Os() == LinuxMusl && module.Target().HostCross)
Sasha Smundakb6d23052019-04-01 18:37:36 -07001007}
Dan Shi31949122020-09-21 12:11:02 -07001008
Jaewoong Jung7ef4a902020-11-16 12:50:29 -08001009// A utility func to format LOCAL_TEST_DATA outputs. See the comments on DataPath to understand how
1010// to use this func.
Colin Cross5c1d5fb2023-11-15 12:39:40 -08001011func androidMkDataPaths(data []DataPath) []string {
Dan Shi31949122020-09-21 12:11:02 -07001012 var testFiles []string
1013 for _, d := range data {
1014 rel := d.SrcPath.Rel()
Colin Cross5c1d5fb2023-11-15 12:39:40 -08001015 if d.WithoutRel {
1016 rel = d.SrcPath.Base()
1017 }
Dan Shi31949122020-09-21 12:11:02 -07001018 path := d.SrcPath.String()
Jaewoong Jung7ef4a902020-11-16 12:50:29 -08001019 // LOCAL_TEST_DATA requires the rel portion of the path to be removed from the path.
Dan Shi31949122020-09-21 12:11:02 -07001020 if !strings.HasSuffix(path, rel) {
1021 panic(fmt.Errorf("path %q does not end with %q", path, rel))
1022 }
1023 path = strings.TrimSuffix(path, rel)
1024 testFileString := path + ":" + rel
1025 if len(d.RelativeInstallPath) > 0 {
1026 testFileString += ":" + d.RelativeInstallPath
1027 }
1028 testFiles = append(testFiles, testFileString)
1029 }
1030 return testFiles
1031}
Sasha Smundakdcb61292022-12-08 10:41:33 -08001032
1033// AndroidMkEmitAssignList emits the line
1034//
1035// VAR := ITEM ...
1036//
1037// Items are the elements to the given set of lists
1038// If all the passed lists are empty, no line will be emitted
1039func AndroidMkEmitAssignList(w io.Writer, varName string, lists ...[]string) {
1040 doPrint := false
1041 for _, l := range lists {
1042 if doPrint = len(l) > 0; doPrint {
1043 break
1044 }
1045 }
1046 if !doPrint {
1047 return
1048 }
1049 fmt.Fprint(w, varName, " :=")
1050 for _, l := range lists {
1051 for _, item := range l {
1052 fmt.Fprint(w, " ", item)
1053 }
1054 }
1055 fmt.Fprintln(w)
1056}