blob: 08589905518e94be6630753ff14a57ebb3bd2cdd [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
Colin Crossa6182ab2024-08-21 10:47:44 -0700557 if info.UncheckedModule {
558 a.SetBool("LOCAL_DONT_CHECK_MODULE", true)
559 } else if info.CheckbuildTarget != nil {
560 a.SetPath("LOCAL_CHECKED_MODULE", info.CheckbuildTarget)
561 } else {
562 a.SetOptionalPath("LOCAL_CHECKED_MODULE", a.OutputFile)
563 }
564
Yu Liud46e5ae2024-08-15 18:46:17 +0000565 if len(info.TestData) > 0 {
566 a.AddStrings("LOCAL_TEST_DATA", androidMkDataPaths(info.TestData)...)
Colin Cross5c1d5fb2023-11-15 12:39:40 -0800567 }
568
Jiyong Park89e850a2020-04-07 16:37:39 +0900569 if am, ok := mod.(ApexModule); ok {
570 a.SetBoolIfTrue("LOCAL_NOT_AVAILABLE_FOR_PLATFORM", am.NotAvailableForPlatform())
571 }
572
Colin Crossf1f763a2021-10-21 16:14:19 -0700573 archStr := base.Arch().ArchType.String()
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700574 host := false
Colin Crossf1f763a2021-10-21 16:14:19 -0700575 switch base.Os().Class {
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700576 case Host:
Colin Crossf1f763a2021-10-21 16:14:19 -0700577 if base.Target().HostCross {
Jiyong Park1613e552020-09-14 19:43:17 +0900578 // Make cannot identify LOCAL_MODULE_HOST_CROSS_ARCH:= common.
Colin Crossf1f763a2021-10-21 16:14:19 -0700579 if base.Arch().ArchType != Common {
Jiyong Park1613e552020-09-14 19:43:17 +0900580 a.SetString("LOCAL_MODULE_HOST_CROSS_ARCH", archStr)
581 }
582 } else {
583 // Make cannot identify LOCAL_MODULE_HOST_ARCH:= common.
Colin Crossf1f763a2021-10-21 16:14:19 -0700584 if base.Arch().ArchType != Common {
Jiyong Park1613e552020-09-14 19:43:17 +0900585 a.SetString("LOCAL_MODULE_HOST_ARCH", archStr)
586 }
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700587 }
588 host = true
589 case Device:
590 // Make cannot identify LOCAL_MODULE_TARGET_ARCH:= common.
Colin Crossf1f763a2021-10-21 16:14:19 -0700591 if base.Arch().ArchType != Common {
592 if base.Target().NativeBridge {
593 hostArchStr := base.Target().NativeBridgeHostArchName
dimitry1f33e402019-03-26 12:39:31 +0100594 if hostArchStr != "" {
595 a.SetString("LOCAL_MODULE_TARGET_ARCH", hostArchStr)
596 }
597 } else {
598 a.SetString("LOCAL_MODULE_TARGET_ARCH", archStr)
599 }
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700600 }
601
Kelvin Zhang46977252022-04-13 16:41:34 -0700602 if !base.InVendorRamdisk() {
Yu Liu82a6d142024-08-27 19:02:29 +0000603 a.AddPaths("LOCAL_FULL_INIT_RC", info.InitRcPaths)
Yifan Hong919dae12020-12-02 18:55:06 -0800604 }
Yu Liu82a6d142024-08-27 19:02:29 +0000605 if len(info.VintfFragmentsPaths) > 0 {
606 a.AddPaths("LOCAL_FULL_VINTF_FRAGMENTS", info.VintfFragmentsPaths)
Liz Kammer7b3dc8a2021-04-16 16:41:59 -0400607 }
Colin Crossf1f763a2021-10-21 16:14:19 -0700608 a.SetBoolIfTrue("LOCAL_PROPRIETARY_MODULE", Bool(base.commonProperties.Proprietary))
609 if Bool(base.commonProperties.Vendor) || Bool(base.commonProperties.Soc_specific) {
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700610 a.SetString("LOCAL_VENDOR_MODULE", "true")
611 }
Colin Crossf1f763a2021-10-21 16:14:19 -0700612 a.SetBoolIfTrue("LOCAL_ODM_MODULE", Bool(base.commonProperties.Device_specific))
613 a.SetBoolIfTrue("LOCAL_PRODUCT_MODULE", Bool(base.commonProperties.Product_specific))
614 a.SetBoolIfTrue("LOCAL_SYSTEM_EXT_MODULE", Bool(base.commonProperties.System_ext_specific))
615 if base.commonProperties.Owner != nil {
616 a.SetString("LOCAL_MODULE_OWNER", *base.commonProperties.Owner)
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700617 }
618 }
619
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700620 if host {
Colin Crossf1f763a2021-10-21 16:14:19 -0700621 makeOs := base.Os().String()
622 if base.Os() == Linux || base.Os() == LinuxBionic || base.Os() == LinuxMusl {
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700623 makeOs = "linux"
624 }
625 a.SetString("LOCAL_MODULE_HOST_OS", makeOs)
626 a.SetString("LOCAL_IS_HOST_MODULE", "true")
627 }
628
629 prefix := ""
Colin Crossf1f763a2021-10-21 16:14:19 -0700630 if base.ArchSpecific() {
631 switch base.Os().Class {
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700632 case Host:
Colin Crossf1f763a2021-10-21 16:14:19 -0700633 if base.Target().HostCross {
Jiyong Park1613e552020-09-14 19:43:17 +0900634 prefix = "HOST_CROSS_"
635 } else {
636 prefix = "HOST_"
637 }
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700638 case Device:
639 prefix = "TARGET_"
640
641 }
642
Colin Crossf1f763a2021-10-21 16:14:19 -0700643 if base.Arch().ArchType != ctx.Config().Targets[base.Os()][0].Arch.ArchType {
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700644 prefix = "2ND_" + prefix
645 }
646 }
Colin Crossaa255532020-07-03 13:18:24 -0700647
Yu Liu663e4502024-08-12 18:23:59 +0000648 if licenseMetadata, ok := OtherModuleProvider(ctx, mod, LicenseMetadataProvider); ok {
Colin Cross4acaea92021-12-10 23:05:02 +0000649 a.SetPath("LOCAL_SOONG_LICENSE_METADATA", licenseMetadata.LicenseMetadataPath)
650 }
651
Yu Liu663e4502024-08-12 18:23:59 +0000652 if _, ok := OtherModuleProvider(ctx, mod, ModuleInfoJSONProvider); ok {
Colin Crossd6fd0132023-11-06 13:54:06 -0800653 a.SetBool("LOCAL_SOONG_MODULE_INFO_JSON", true)
654 }
655
Colin Crossaa255532020-07-03 13:18:24 -0700656 extraCtx := &androidMkExtraEntriesContext{
657 ctx: ctx,
658 mod: mod,
659 }
660
Jaewoong Junge0dc8df2019-08-27 17:33:16 -0700661 for _, extra := range a.ExtraEntries {
Colin Crossaa255532020-07-03 13:18:24 -0700662 extra(extraCtx, a)
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700663 }
664
665 // Write to footer.
666 fmt.Fprintln(&a.footer, "include "+a.Include)
Colin Crossaa255532020-07-03 13:18:24 -0700667 blueprintDir := ctx.ModuleDir(mod)
Jaewoong Jungb0c127c2019-08-29 14:56:03 -0700668 for _, footerFunc := range a.ExtraFooters {
Jaewoong Jung02b11a62020-12-07 10:23:54 -0800669 footerFunc(&a.footer, name, prefix, blueprintDir)
Jaewoong Jungb0c127c2019-08-29 14:56:03 -0700670 }
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700671}
672
Colin Crossd6fd0132023-11-06 13:54:06 -0800673func (a *AndroidMkEntries) disabled() bool {
674 return a.Disabled || !a.OutputFile.Valid()
675}
676
Jaewoong Jung7ef4a902020-11-16 12:50:29 -0800677// write flushes the AndroidMkEntries's in-struct data populated by AndroidMkEntries into the
678// given Writer object.
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700679func (a *AndroidMkEntries) write(w io.Writer) {
Colin Crossd6fd0132023-11-06 13:54:06 -0800680 if a.disabled() {
Jaewoong Jungb0c127c2019-08-29 14:56:03 -0700681 return
682 }
683
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700684 w.Write(a.header.Bytes())
685 for _, name := range a.entryOrder {
Sasha Smundakdcb61292022-12-08 10:41:33 -0800686 AndroidMkEmitAssignList(w, name, a.EntryMap[name])
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700687 }
688 w.Write(a.footer.Bytes())
689}
690
Jaewoong Jungb0c127c2019-08-29 14:56:03 -0700691func (a *AndroidMkEntries) FooterLinesForTests() []string {
692 return strings.Split(string(a.footer.Bytes()), "\n")
693}
694
Jaewoong Jung7ef4a902020-11-16 12:50:29 -0800695// AndroidMkSingleton is a singleton to collect Android.mk data from all modules and dump them into
696// the final Android-<product_name>.mk file output.
Colin Cross0875c522017-11-28 17:34:01 -0800697func AndroidMkSingleton() Singleton {
Dan Willemsen218f6562015-07-08 18:13:11 -0700698 return &androidMkSingleton{}
699}
700
701type androidMkSingleton struct{}
702
Colin Cross0875c522017-11-28 17:34:01 -0800703func (c *androidMkSingleton) GenerateBuildActions(ctx SingletonContext) {
Jaewoong Jung7ef4a902020-11-16 12:50:29 -0800704 // Skip if Soong wasn't invoked from Make.
Jingwen Chencda22c92020-11-23 00:22:30 -0500705 if !ctx.Config().KatiEnabled() {
Dan Willemsen5ba07e82015-12-11 13:51:06 -0800706 return
707 }
708
Colin Cross2465c3d2018-09-28 10:19:18 -0700709 var androidMkModulesList []blueprint.Module
Colin Cross4f6e4e62016-01-11 12:55:55 -0800710
Colin Cross2465c3d2018-09-28 10:19:18 -0700711 ctx.VisitAllModulesBlueprint(func(module blueprint.Module) {
Colin Cross0875c522017-11-28 17:34:01 -0800712 androidMkModulesList = append(androidMkModulesList, module)
Colin Cross4f6e4e62016-01-11 12:55:55 -0800713 })
Dan Willemsen218f6562015-07-08 18:13:11 -0700714
Jaewoong Jung7ef4a902020-11-16 12:50:29 -0800715 // Sort the module list by the module names to eliminate random churns, which may erroneously
716 // invoke additional build processes.
Colin Cross1ad81422019-01-14 12:47:35 -0800717 sort.SliceStable(androidMkModulesList, func(i, j int) bool {
718 return ctx.ModuleName(androidMkModulesList[i]) < ctx.ModuleName(androidMkModulesList[j])
719 })
Colin Crossd779da42015-12-17 18:00:23 -0800720
Dan Willemsen45133ac2018-03-09 21:22:06 -0800721 transMk := PathForOutput(ctx, "Android"+String(ctx.Config().productVariables.Make_suffix)+".mk")
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700722 if ctx.Failed() {
723 return
724 }
Dan Willemsen218f6562015-07-08 18:13:11 -0700725
Colin Crossd6fd0132023-11-06 13:54:06 -0800726 moduleInfoJSON := PathForOutput(ctx, "module-info"+String(ctx.Config().productVariables.Make_suffix)+".json")
727
728 err := translateAndroidMk(ctx, absolutePath(transMk.String()), moduleInfoJSON, androidMkModulesList)
Dan Willemsen218f6562015-07-08 18:13:11 -0700729 if err != nil {
730 ctx.Errorf(err.Error())
731 }
732
Colin Cross0875c522017-11-28 17:34:01 -0800733 ctx.Build(pctx, BuildParams{
734 Rule: blueprint.Phony,
735 Output: transMk,
Dan Willemsen218f6562015-07-08 18:13:11 -0700736 })
737}
738
Colin Crossd6fd0132023-11-06 13:54:06 -0800739func translateAndroidMk(ctx SingletonContext, absMkFile string, moduleInfoJSONPath WritablePath, mods []blueprint.Module) error {
Dan Willemsen218f6562015-07-08 18:13:11 -0700740 buf := &bytes.Buffer{}
741
Colin Crossd6fd0132023-11-06 13:54:06 -0800742 var moduleInfoJSONs []*ModuleInfoJSON
743
Dan Willemsen97750522016-02-09 17:43:51 -0800744 fmt.Fprintln(buf, "LOCAL_MODULE_MAKEFILE := $(lastword $(MAKEFILE_LIST))")
Dan Willemsen218f6562015-07-08 18:13:11 -0700745
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800746 typeStats := make(map[string]int)
Dan Willemsen218f6562015-07-08 18:13:11 -0700747 for _, mod := range mods {
Colin Crossd6fd0132023-11-06 13:54:06 -0800748 err := translateAndroidMkModule(ctx, buf, &moduleInfoJSONs, mod)
Dan Willemsen218f6562015-07-08 18:13:11 -0700749 if err != nil {
Colin Cross836e3872021-11-09 12:30:59 -0800750 os.Remove(absMkFile)
Dan Willemsen218f6562015-07-08 18:13:11 -0700751 return err
752 }
Dan Willemsen70e17fa2016-07-25 16:00:20 -0700753
Colin Cross2465c3d2018-09-28 10:19:18 -0700754 if amod, ok := mod.(Module); ok && ctx.PrimaryModule(amod) == amod {
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800755 typeStats[ctx.ModuleType(amod)] += 1
Dan Willemsen70e17fa2016-07-25 16:00:20 -0700756 }
757 }
758
759 keys := []string{}
760 fmt.Fprintln(buf, "\nSTATS.SOONG_MODULE_TYPE :=")
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800761 for k := range typeStats {
Dan Willemsen70e17fa2016-07-25 16:00:20 -0700762 keys = append(keys, k)
763 }
764 sort.Strings(keys)
765 for _, mod_type := range keys {
766 fmt.Fprintln(buf, "STATS.SOONG_MODULE_TYPE +=", mod_type)
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800767 fmt.Fprintf(buf, "STATS.SOONG_MODULE_TYPE.%s := %d\n", mod_type, typeStats[mod_type])
Dan Willemsen218f6562015-07-08 18:13:11 -0700768 }
769
Colin Crossd6fd0132023-11-06 13:54:06 -0800770 err := pathtools.WriteFileIfChanged(absMkFile, buf.Bytes(), 0666)
771 if err != nil {
772 return err
773 }
774
775 return writeModuleInfoJSON(ctx, moduleInfoJSONs, moduleInfoJSONPath)
Dan Willemsen218f6562015-07-08 18:13:11 -0700776}
777
Colin Crossd6fd0132023-11-06 13:54:06 -0800778func writeModuleInfoJSON(ctx SingletonContext, moduleInfoJSONs []*ModuleInfoJSON, moduleInfoJSONPath WritablePath) error {
779 moduleInfoJSONBuf := &strings.Builder{}
780 moduleInfoJSONBuf.WriteString("[")
781 for i, moduleInfoJSON := range moduleInfoJSONs {
782 if i != 0 {
783 moduleInfoJSONBuf.WriteString(",\n")
784 }
785 moduleInfoJSONBuf.WriteString("{")
786 moduleInfoJSONBuf.WriteString(strconv.Quote(moduleInfoJSON.core.RegisterName))
787 moduleInfoJSONBuf.WriteString(":")
788 err := encodeModuleInfoJSON(moduleInfoJSONBuf, moduleInfoJSON)
789 moduleInfoJSONBuf.WriteString("}")
790 if err != nil {
791 return err
792 }
793 }
794 moduleInfoJSONBuf.WriteString("]")
795 WriteFileRule(ctx, moduleInfoJSONPath, moduleInfoJSONBuf.String())
796 return nil
797}
798
799func translateAndroidMkModule(ctx SingletonContext, w io.Writer, moduleInfoJSONs *[]*ModuleInfoJSON, mod blueprint.Module) error {
Colin Cross953d3a22018-09-05 16:23:54 -0700800 defer func() {
801 if r := recover(); r != nil {
802 panic(fmt.Errorf("%s in translateAndroidMkModule for module %s variant %s",
803 r, ctx.ModuleName(mod), ctx.ModuleSubDir(mod)))
804 }
805 }()
806
Bob Badourb4999222021-01-07 03:34:31 +0000807 // Additional cases here require review for correct license propagation to make.
Colin Crossd6fd0132023-11-06 13:54:06 -0800808 var err error
Colin Cross2465c3d2018-09-28 10:19:18 -0700809 switch x := mod.(type) {
810 case AndroidMkDataProvider:
Colin Crossd6fd0132023-11-06 13:54:06 -0800811 err = translateAndroidModule(ctx, w, moduleInfoJSONs, mod, x)
Colin Cross2465c3d2018-09-28 10:19:18 -0700812 case bootstrap.GoBinaryTool:
Colin Crossd6fd0132023-11-06 13:54:06 -0800813 err = translateGoBinaryModule(ctx, w, mod, x)
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700814 case AndroidMkEntriesProvider:
Colin Crossd6fd0132023-11-06 13:54:06 -0800815 err = translateAndroidMkEntriesModule(ctx, w, moduleInfoJSONs, mod, x)
Colin Cross2465c3d2018-09-28 10:19:18 -0700816 default:
Bob Badourb4999222021-01-07 03:34:31 +0000817 // Not exported to make so no make variables to set.
Dan Willemsen218f6562015-07-08 18:13:11 -0700818 }
Colin Crossd6fd0132023-11-06 13:54:06 -0800819
820 if err != nil {
821 return err
822 }
823
824 return err
Colin Cross2465c3d2018-09-28 10:19:18 -0700825}
826
Jaewoong Jung7ef4a902020-11-16 12:50:29 -0800827// A simple, special Android.mk entry output func to make it possible to build blueprint tools using
828// m by making them phony targets.
Colin Cross2465c3d2018-09-28 10:19:18 -0700829func translateGoBinaryModule(ctx SingletonContext, w io.Writer, mod blueprint.Module,
830 goBinary bootstrap.GoBinaryTool) error {
831
832 name := ctx.ModuleName(mod)
833 fmt.Fprintln(w, ".PHONY:", name)
834 fmt.Fprintln(w, name+":", goBinary.InstallPath())
835 fmt.Fprintln(w, "")
Bob Badourb4999222021-01-07 03:34:31 +0000836 // Assuming no rules in make include go binaries in distributables.
837 // If the assumption is wrong, make will fail to build without the necessary .meta_lic and .meta_module files.
838 // In that case, add the targets and rules here to build a .meta_lic file for `name` and a .meta_module for
839 // `goBinary.InstallPath()` pointing to the `name`.meta_lic file.
Colin Cross2465c3d2018-09-28 10:19:18 -0700840
841 return nil
842}
843
Colin Crossaa255532020-07-03 13:18:24 -0700844func (data *AndroidMkData) fillInData(ctx fillInEntriesContext, mod blueprint.Module) {
Jooyung Han12df5fb2019-07-11 16:18:47 +0900845 // Get the preamble content through AndroidMkEntries logic.
Jooyung Han2ed99d02020-06-24 23:26:26 +0900846 data.Entries = AndroidMkEntries{
Jooyung Han12df5fb2019-07-11 16:18:47 +0900847 Class: data.Class,
848 SubName: data.SubName,
Jingwen Chen40fd90a2020-06-15 05:24:19 +0000849 DistFiles: data.DistFiles,
Jooyung Han12df5fb2019-07-11 16:18:47 +0900850 OutputFile: data.OutputFile,
851 Disabled: data.Disabled,
852 Include: data.Include,
853 Required: data.Required,
854 Host_required: data.Host_required,
855 Target_required: data.Target_required,
856 }
Colin Crossaa255532020-07-03 13:18:24 -0700857 data.Entries.fillInEntries(ctx, mod)
Jooyung Han12df5fb2019-07-11 16:18:47 +0900858
859 // copy entries back to data since it is used in Custom
Jooyung Han2ed99d02020-06-24 23:26:26 +0900860 data.Required = data.Entries.Required
861 data.Host_required = data.Entries.Host_required
862 data.Target_required = data.Entries.Target_required
Jooyung Han12df5fb2019-07-11 16:18:47 +0900863}
864
Jaewoong Jung7ef4a902020-11-16 12:50:29 -0800865// A support func for the deprecated AndroidMkDataProvider interface. Use AndroidMkEntryProvider
866// instead.
Colin Crossd6fd0132023-11-06 13:54:06 -0800867func translateAndroidModule(ctx SingletonContext, w io.Writer, moduleInfoJSONs *[]*ModuleInfoJSON,
868 mod blueprint.Module, provider AndroidMkDataProvider) error {
Dan Willemsen218f6562015-07-08 18:13:11 -0700869
Colin Cross635c3b02016-05-18 15:37:25 -0700870 amod := mod.(Module).base()
Cole Fausta963b942024-04-11 17:43:00 -0700871 if shouldSkipAndroidMkProcessing(ctx, amod) {
Jeff Gaston088e29e2017-11-29 16:47:17 -0800872 return nil
873 }
874
Colin Cross91825d22017-08-10 16:59:47 -0700875 data := provider.AndroidMk()
Yu Liuddc28332024-08-09 22:48:30 +0000876
Colin Cross53499412017-09-07 13:20:25 -0700877 if data.Include == "" {
878 data.Include = "$(BUILD_PREBUILT)"
879 }
880
Colin Crossaa255532020-07-03 13:18:24 -0700881 data.fillInData(ctx, mod)
LaMont Jonesb5099382024-01-10 23:42:36 +0000882 aconfigUpdateAndroidMkData(ctx, mod.(Module), &data)
Dan Willemsen01a405a2016-06-13 17:19:03 -0700883
Colin Cross0f86d182017-08-10 17:07:28 -0700884 prefix := ""
885 if amod.ArchSpecific() {
886 switch amod.Os().Class {
887 case Host:
Jiyong Park1613e552020-09-14 19:43:17 +0900888 if amod.Target().HostCross {
889 prefix = "HOST_CROSS_"
890 } else {
891 prefix = "HOST_"
892 }
Colin Cross0f86d182017-08-10 17:07:28 -0700893 case Device:
894 prefix = "TARGET_"
Colin Crossa2344662016-03-24 13:14:12 -0700895
Dan Willemsen218f6562015-07-08 18:13:11 -0700896 }
897
Dan Willemsen0ef639b2018-10-10 17:02:29 -0700898 if amod.Arch().ArchType != ctx.Config().Targets[amod.Os()][0].Arch.ArchType {
Colin Cross0f86d182017-08-10 17:07:28 -0700899 prefix = "2ND_" + prefix
900 }
Dan Willemsen218f6562015-07-08 18:13:11 -0700901 }
902
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700903 name := provider.BaseModuleName()
Colin Cross0f86d182017-08-10 17:07:28 -0700904 blueprintDir := filepath.Dir(ctx.BlueprintFile(mod))
905
906 if data.Custom != nil {
Bob Badourb4999222021-01-07 03:34:31 +0000907 // List of module types allowed to use .Custom(...)
908 // Additions to the list require careful review for proper license handling.
Colin Crossaa255532020-07-03 13:18:24 -0700909 switch reflect.TypeOf(mod).String() { // ctx.ModuleType(mod) doesn't work: aidl_interface creates phony without type
Bob Badourb4999222021-01-07 03:34:31 +0000910 case "*aidl.aidlApi": // writes non-custom before adding .phony
911 case "*aidl.aidlMapping": // writes non-custom before adding .phony
912 case "*android.customModule": // appears in tests only
Dan Willemsen9fe14102021-07-13 21:52:04 -0700913 case "*android_sdk.sdkRepoHost": // doesn't go through base_rules
Bob Badourb4999222021-01-07 03:34:31 +0000914 case "*apex.apexBundle": // license properties written
915 case "*bpf.bpf": // license properties written (both for module and objs)
Neill Kapron41efab72024-07-31 22:17:36 +0000916 case "*libbpf_prog.libbpfProg": // license properties written (both for module and objs)
Bob Badourb4999222021-01-07 03:34:31 +0000917 case "*genrule.Module": // writes non-custom before adding .phony
918 case "*java.SystemModules": // doesn't go through base_rules
919 case "*java.systemModulesImport": // doesn't go through base_rules
920 case "*phony.phony": // license properties written
Nelson Lif3c70682023-12-20 02:37:52 +0000921 case "*phony.PhonyRule": // writes phony deps and acts like `.PHONY`
Bob Badourb4999222021-01-07 03:34:31 +0000922 case "*selinux.selinuxContextsModule": // license properties written
923 case "*sysprop.syspropLibrary": // license properties written
924 default:
Bob Badour65ee90a2021-09-02 15:33:10 -0700925 if !ctx.Config().IsEnvFalse("ANDROID_REQUIRE_LICENSES") {
Bob Badourb4999222021-01-07 03:34:31 +0000926 return fmt.Errorf("custom make rules not allowed for %q (%q) module %q", ctx.ModuleType(mod), reflect.TypeOf(mod), ctx.ModuleName(mod))
927 }
928 }
Colin Cross0f86d182017-08-10 17:07:28 -0700929 data.Custom(w, name, prefix, blueprintDir, data)
930 } else {
931 WriteAndroidMkData(w, data)
932 }
933
Colin Crossd6fd0132023-11-06 13:54:06 -0800934 if !data.Entries.disabled() {
Yu Liu663e4502024-08-12 18:23:59 +0000935 if moduleInfoJSON, ok := OtherModuleProvider(ctx, mod, ModuleInfoJSONProvider); ok {
Colin Crossd6fd0132023-11-06 13:54:06 -0800936 *moduleInfoJSONs = append(*moduleInfoJSONs, moduleInfoJSON)
937 }
938 }
939
Colin Cross0f86d182017-08-10 17:07:28 -0700940 return nil
941}
942
Jaewoong Jung7ef4a902020-11-16 12:50:29 -0800943// A support func for the deprecated AndroidMkDataProvider interface. Use AndroidMkEntryProvider
944// instead.
Colin Cross0f86d182017-08-10 17:07:28 -0700945func WriteAndroidMkData(w io.Writer, data AndroidMkData) {
Colin Crossd6fd0132023-11-06 13:54:06 -0800946 if data.Entries.disabled() {
Colin Cross0f86d182017-08-10 17:07:28 -0700947 return
948 }
949
Jooyung Han2ed99d02020-06-24 23:26:26 +0900950 // write preamble via Entries
951 data.Entries.footer = bytes.Buffer{}
952 data.Entries.write(w)
Colin Cross0f86d182017-08-10 17:07:28 -0700953
Colin Crossca860ac2016-01-04 14:34:37 -0800954 for _, extra := range data.Extra {
Colin Cross27a4b052017-08-10 16:32:23 -0700955 extra(w, data.OutputFile.Path())
Dan Willemsen97750522016-02-09 17:43:51 -0800956 }
957
Colin Cross53499412017-09-07 13:20:25 -0700958 fmt.Fprintln(w, "include "+data.Include)
Dan Willemsen218f6562015-07-08 18:13:11 -0700959}
Sasha Smundakb6d23052019-04-01 18:37:36 -0700960
Colin Crossd6fd0132023-11-06 13:54:06 -0800961func translateAndroidMkEntriesModule(ctx SingletonContext, w io.Writer, moduleInfoJSONs *[]*ModuleInfoJSON,
962 mod blueprint.Module, provider AndroidMkEntriesProvider) error {
Cole Fausta963b942024-04-11 17:43:00 -0700963 if shouldSkipAndroidMkProcessing(ctx, mod.(Module).base()) {
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700964 return nil
Sasha Smundakb6d23052019-04-01 18:37:36 -0700965 }
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700966
Colin Crossd6fd0132023-11-06 13:54:06 -0800967 entriesList := provider.AndroidMkEntries()
LaMont Jonesb5099382024-01-10 23:42:36 +0000968 aconfigUpdateAndroidMkEntries(ctx, mod.(Module), &entriesList)
Colin Crossd6fd0132023-11-06 13:54:06 -0800969
Bob Badourb4999222021-01-07 03:34:31 +0000970 // Any new or special cases here need review to verify correct propagation of license information.
Colin Crossd6fd0132023-11-06 13:54:06 -0800971 for _, entries := range entriesList {
Colin Crossaa255532020-07-03 13:18:24 -0700972 entries.fillInEntries(ctx, mod)
Jiyong Park0b0e1b92019-12-03 13:24:29 +0900973 entries.write(w)
974 }
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700975
Colin Crossd6fd0132023-11-06 13:54:06 -0800976 if len(entriesList) > 0 && !entriesList[0].disabled() {
Yu Liu663e4502024-08-12 18:23:59 +0000977 if moduleInfoJSON, ok := OtherModuleProvider(ctx, mod, ModuleInfoJSONProvider); ok {
Colin Crossd6fd0132023-11-06 13:54:06 -0800978 *moduleInfoJSONs = append(*moduleInfoJSONs, moduleInfoJSON)
979 }
980 }
981
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700982 return nil
983}
984
Cole Fausta963b942024-04-11 17:43:00 -0700985func ShouldSkipAndroidMkProcessing(ctx ConfigAndErrorContext, module Module) bool {
986 return shouldSkipAndroidMkProcessing(ctx, module.base())
Chih-Hung Hsieh80783772021-10-11 16:46:56 -0700987}
988
Cole Fausta963b942024-04-11 17:43:00 -0700989func shouldSkipAndroidMkProcessing(ctx ConfigAndErrorContext, module *ModuleBase) bool {
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700990 if !module.commonProperties.NamespaceExportedToMake {
991 // TODO(jeffrygaston) do we want to validate that there are no modules being
992 // exported to Kati that depend on this module?
993 return true
Sasha Smundakb6d23052019-04-01 18:37:36 -0700994 }
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700995
Dan Willemsendef7b5d2021-10-17 00:22:33 -0700996 // On Mac, only expose host darwin modules to Make, as that's all we claim to support.
997 // In reality, some of them depend on device-built (Java) modules, so we can't disable all
998 // device modules in Soong, but we can hide them from Make (and thus the build user interface)
999 if runtime.GOOS == "darwin" && module.Os() != Darwin {
1000 return true
1001 }
1002
Dan Willemsen8528f4e2021-10-19 00:22:06 -07001003 // Only expose the primary Darwin target, as Make does not understand Darwin+Arm64
1004 if module.Os() == Darwin && module.Target().HostCross {
1005 return true
1006 }
1007
Cole Fausta963b942024-04-11 17:43:00 -07001008 return !module.Enabled(ctx) ||
Colin Crossa9c8c9f2020-12-16 10:20:23 -08001009 module.commonProperties.HideFromMake ||
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -07001010 // Make does not understand LinuxBionic
Colin Cross9a027be2022-06-24 18:45:58 -07001011 module.Os() == LinuxBionic ||
1012 // Make does not understand LinuxMusl, except when we are building with USE_HOST_MUSL=true
1013 // and all host binaries are LinuxMusl
1014 (module.Os() == LinuxMusl && module.Target().HostCross)
Sasha Smundakb6d23052019-04-01 18:37:36 -07001015}
Dan Shi31949122020-09-21 12:11:02 -07001016
Jaewoong Jung7ef4a902020-11-16 12:50:29 -08001017// A utility func to format LOCAL_TEST_DATA outputs. See the comments on DataPath to understand how
1018// to use this func.
Colin Cross5c1d5fb2023-11-15 12:39:40 -08001019func androidMkDataPaths(data []DataPath) []string {
Dan Shi31949122020-09-21 12:11:02 -07001020 var testFiles []string
1021 for _, d := range data {
1022 rel := d.SrcPath.Rel()
Colin Cross5c1d5fb2023-11-15 12:39:40 -08001023 if d.WithoutRel {
1024 rel = d.SrcPath.Base()
1025 }
Dan Shi31949122020-09-21 12:11:02 -07001026 path := d.SrcPath.String()
Jaewoong Jung7ef4a902020-11-16 12:50:29 -08001027 // LOCAL_TEST_DATA requires the rel portion of the path to be removed from the path.
Dan Shi31949122020-09-21 12:11:02 -07001028 if !strings.HasSuffix(path, rel) {
1029 panic(fmt.Errorf("path %q does not end with %q", path, rel))
1030 }
1031 path = strings.TrimSuffix(path, rel)
1032 testFileString := path + ":" + rel
1033 if len(d.RelativeInstallPath) > 0 {
1034 testFileString += ":" + d.RelativeInstallPath
1035 }
1036 testFiles = append(testFiles, testFileString)
1037 }
1038 return testFiles
1039}
Sasha Smundakdcb61292022-12-08 10:41:33 -08001040
1041// AndroidMkEmitAssignList emits the line
1042//
1043// VAR := ITEM ...
1044//
1045// Items are the elements to the given set of lists
1046// If all the passed lists are empty, no line will be emitted
1047func AndroidMkEmitAssignList(w io.Writer, varName string, lists ...[]string) {
1048 doPrint := false
1049 for _, l := range lists {
1050 if doPrint = len(l) > 0; doPrint {
1051 break
1052 }
1053 }
1054 if !doPrint {
1055 return
1056 }
1057 fmt.Fprint(w, varName, " :=")
1058 for _, l := range lists {
1059 for _, item := range l {
1060 fmt.Fprint(w, " ", item)
1061 }
1062 }
1063 fmt.Fprintln(w)
1064}