blob: 72b6584ab50a7ba7f13e850d8e354f66520b4fe4 [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"
Dan Willemsen0fda89f2016-06-01 15:25:32 -070033 "strings"
Dan Willemsen218f6562015-07-08 18:13:11 -070034
Dan Willemsen218f6562015-07-08 18:13:11 -070035 "github.com/google/blueprint"
Colin Cross2465c3d2018-09-28 10:19:18 -070036 "github.com/google/blueprint/bootstrap"
Colin Cross836e3872021-11-09 12:30:59 -080037 "github.com/google/blueprint/pathtools"
Dan Willemsen218f6562015-07-08 18:13:11 -070038)
39
40func init() {
Paul Duffin8c3fec42020-03-04 20:15:08 +000041 RegisterAndroidMkBuildComponents(InitRegistrationContext)
42}
43
44func RegisterAndroidMkBuildComponents(ctx RegistrationContext) {
45 ctx.RegisterSingletonType("androidmk", AndroidMkSingleton)
Dan Willemsen218f6562015-07-08 18:13:11 -070046}
47
Paul Duffin6c9da042021-03-07 15:44:41 +000048// Enable androidmk support.
49// * Register the singleton
50// * Configure that we are inside make
51var PrepareForTestWithAndroidMk = GroupFixturePreparers(
52 FixtureRegisterWithContext(RegisterAndroidMkBuildComponents),
53 FixtureModifyConfig(SetKatiEnabledForTests),
54)
55
Jaewoong Jung7ef4a902020-11-16 12:50:29 -080056// Deprecated: Use AndroidMkEntriesProvider instead, especially if you're not going to use the
57// Custom function. It's easier to use and test.
Dan Willemsen218f6562015-07-08 18:13:11 -070058type AndroidMkDataProvider interface {
Colin Crossa18e9cf2017-08-10 17:00:19 -070059 AndroidMk() AndroidMkData
Colin Crossce75d2c2016-10-06 16:12:58 -070060 BaseModuleName() string
Dan Willemsen218f6562015-07-08 18:13:11 -070061}
62
63type AndroidMkData struct {
Sasha Smundakb6d23052019-04-01 18:37:36 -070064 Class string
65 SubName string
Jingwen Chen40fd90a2020-06-15 05:24:19 +000066 DistFiles TaggedDistFiles
Sasha Smundakb6d23052019-04-01 18:37:36 -070067 OutputFile OptionalPath
68 Disabled bool
69 Include string
70 Required []string
71 Host_required []string
72 Target_required []string
Dan Willemsen218f6562015-07-08 18:13:11 -070073
Colin Cross0f86d182017-08-10 17:07:28 -070074 Custom func(w io.Writer, name, prefix, moduleDir string, data AndroidMkData)
Dan Willemsen218f6562015-07-08 18:13:11 -070075
Colin Cross27a4b052017-08-10 16:32:23 -070076 Extra []AndroidMkExtraFunc
Colin Cross0f86d182017-08-10 17:07:28 -070077
Jooyung Han2ed99d02020-06-24 23:26:26 +090078 Entries AndroidMkEntries
Dan Willemsen218f6562015-07-08 18:13:11 -070079}
80
Colin Cross27a4b052017-08-10 16:32:23 -070081type AndroidMkExtraFunc func(w io.Writer, outputFile Path)
82
Jaewoong Jung7ef4a902020-11-16 12:50:29 -080083// Interface for modules to declare their Android.mk outputs. Note that every module needs to
84// implement this in order to be included in the final Android-<product_name>.mk output, even if
85// they only need to output the common set of entries without any customizations.
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -070086type AndroidMkEntriesProvider interface {
Jaewoong Jung7ef4a902020-11-16 12:50:29 -080087 // Returns AndroidMkEntries objects that contain all basic info plus extra customization data
88 // if needed. This is the core func to implement.
89 // Note that one can return multiple objects. For example, java_library may return an additional
90 // AndroidMkEntries object for its hostdex sub-module.
Jiyong Park0b0e1b92019-12-03 13:24:29 +090091 AndroidMkEntries() []AndroidMkEntries
Jaewoong Jung7ef4a902020-11-16 12:50:29 -080092 // Modules don't need to implement this as it's already implemented by ModuleBase.
93 // AndroidMkEntries uses BaseModuleName() instead of ModuleName() because certain modules
94 // e.g. Prebuilts, override the Name() func and return modified names.
95 // If a different name is preferred, use SubName or OverrideName in AndroidMkEntries.
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -070096 BaseModuleName() string
97}
98
Jaewoong Jung7ef4a902020-11-16 12:50:29 -080099// The core data struct that modules use to provide their Android.mk data.
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700100type AndroidMkEntries struct {
Jaewoong Jung7ef4a902020-11-16 12:50:29 -0800101 // Android.mk class string, e.g EXECUTABLES, JAVA_LIBRARIES, ETC
102 Class string
103 // Optional suffix to append to the module name. Useful when a module wants to return multiple
104 // AndroidMkEntries objects. For example, when a java_library returns an additional entry for
105 // its hostdex sub-module, this SubName field is set to "-hostdex" so that it can have a
106 // different name than the parent's.
107 SubName string
108 // If set, this value overrides the base module name. SubName is still appended.
109 OverrideName string
110 // Dist files to output
111 DistFiles TaggedDistFiles
112 // The output file for Kati to process and/or install. If absent, the module is skipped.
113 OutputFile OptionalPath
114 // If true, the module is skipped and does not appear on the final Android-<product name>.mk
115 // file. Useful when a module needs to be skipped conditionally.
116 Disabled bool
Ivan Lozanod06cc742021-11-12 13:27:58 -0500117 // The postprocessing mk file to include, e.g. $(BUILD_SYSTEM)/soong_cc_rust_prebuilt.mk
Jaewoong Jung7ef4a902020-11-16 12:50:29 -0800118 // If not set, $(BUILD_SYSTEM)/prebuilt.mk is used.
119 Include string
120 // Required modules that need to be built and included in the final build output when building
121 // this module.
122 Required []string
123 // Required host modules that need to be built and included in the final build output when
124 // building this module.
125 Host_required []string
126 // Required device modules that need to be built and included in the final build output when
127 // building this module.
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700128 Target_required []string
129
130 header bytes.Buffer
131 footer bytes.Buffer
132
Jaewoong Jung7ef4a902020-11-16 12:50:29 -0800133 // Funcs to append additional Android.mk entries or modify the common ones. Multiple funcs are
134 // accepted so that common logic can be factored out as a shared func.
Jaewoong Junge0dc8df2019-08-27 17:33:16 -0700135 ExtraEntries []AndroidMkExtraEntriesFunc
Jaewoong Jung7ef4a902020-11-16 12:50:29 -0800136 // Funcs to add extra lines to the module's Android.mk output. Unlike AndroidMkExtraEntriesFunc,
137 // which simply sets Make variable values, this can be used for anything since it can write any
138 // Make statements directly to the final Android-*.mk file.
139 // Primarily used to call macros or declare/update Make targets.
Jaewoong Jungb0c127c2019-08-29 14:56:03 -0700140 ExtraFooters []AndroidMkExtraFootersFunc
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700141
Jaewoong Jung7ef4a902020-11-16 12:50:29 -0800142 // A map that holds the up-to-date Make variable values. Can be accessed from tests.
143 EntryMap map[string][]string
144 // A list of EntryMap keys in insertion order. This serves a few purposes:
145 // 1. Prevents churns. Golang map doesn't provide consistent iteration order, so without this,
146 // the outputted Android-*.mk file may change even though there have been no content changes.
147 // 2. Allows modules to refer to other variables, like LOCAL_BAR_VAR := $(LOCAL_FOO_VAR),
148 // without worrying about the variables being mixed up in the actual mk file.
149 // 3. Makes troubleshooting and spotting errors easier.
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700150 entryOrder []string
151}
152
Colin Crossaa255532020-07-03 13:18:24 -0700153type AndroidMkExtraEntriesContext interface {
154 Provider(provider blueprint.ProviderKey) interface{}
155}
156
157type androidMkExtraEntriesContext struct {
158 ctx fillInEntriesContext
159 mod blueprint.Module
160}
161
162func (a *androidMkExtraEntriesContext) Provider(provider blueprint.ProviderKey) interface{} {
163 return a.ctx.ModuleProvider(a.mod, provider)
164}
165
166type AndroidMkExtraEntriesFunc func(ctx AndroidMkExtraEntriesContext, entries *AndroidMkEntries)
Jaewoong Jung02b11a62020-12-07 10:23:54 -0800167type AndroidMkExtraFootersFunc func(w io.Writer, name, prefix, moduleDir string)
Jaewoong Junge0dc8df2019-08-27 17:33:16 -0700168
Jaewoong Jung7ef4a902020-11-16 12:50:29 -0800169// Utility funcs to manipulate Android.mk variable entries.
170
171// SetString sets a Make variable with the given name to the given value.
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700172func (a *AndroidMkEntries) SetString(name, value string) {
173 if _, ok := a.EntryMap[name]; !ok {
174 a.entryOrder = append(a.entryOrder, name)
175 }
176 a.EntryMap[name] = []string{value}
177}
178
Jaewoong Jung7ef4a902020-11-16 12:50:29 -0800179// SetPath sets a Make variable with the given name to the given path string.
Jaewoong Jung9a1e8bd2019-09-04 20:17:54 -0700180func (a *AndroidMkEntries) SetPath(name string, path Path) {
181 if _, ok := a.EntryMap[name]; !ok {
182 a.entryOrder = append(a.entryOrder, name)
183 }
184 a.EntryMap[name] = []string{path.String()}
185}
186
Jaewoong Jung7ef4a902020-11-16 12:50:29 -0800187// SetOptionalPath sets a Make variable with the given name to the given path string if it is valid.
188// It is a no-op if the given path is invalid.
Colin Crossc0efd1d2020-07-03 11:56:24 -0700189func (a *AndroidMkEntries) SetOptionalPath(name string, path OptionalPath) {
190 if path.Valid() {
191 a.SetPath(name, path.Path())
192 }
193}
194
Jaewoong Jung7ef4a902020-11-16 12:50:29 -0800195// AddPath appends the given path string to a Make variable with the given name.
Colin Crossc0efd1d2020-07-03 11:56:24 -0700196func (a *AndroidMkEntries) AddPath(name string, path Path) {
197 if _, ok := a.EntryMap[name]; !ok {
198 a.entryOrder = append(a.entryOrder, name)
199 }
200 a.EntryMap[name] = append(a.EntryMap[name], path.String())
201}
202
Jaewoong Jung7ef4a902020-11-16 12:50:29 -0800203// AddOptionalPath appends the given path string to a Make variable with the given name if it is
204// valid. It is a no-op if the given path is invalid.
Colin Crossc0efd1d2020-07-03 11:56:24 -0700205func (a *AndroidMkEntries) AddOptionalPath(name string, path OptionalPath) {
206 if path.Valid() {
207 a.AddPath(name, path.Path())
208 }
209}
210
Jaewoong Jung7ef4a902020-11-16 12:50:29 -0800211// SetPaths sets a Make variable with the given name to a slice of the given path strings.
Colin Cross08dca382020-07-21 20:31:17 -0700212func (a *AndroidMkEntries) SetPaths(name string, paths Paths) {
213 if _, ok := a.EntryMap[name]; !ok {
214 a.entryOrder = append(a.entryOrder, name)
215 }
216 a.EntryMap[name] = paths.Strings()
217}
218
Jaewoong Jung7ef4a902020-11-16 12:50:29 -0800219// SetOptionalPaths sets a Make variable with the given name to a slice of the given path strings
220// only if there are a non-zero amount of paths.
Colin Cross08dca382020-07-21 20:31:17 -0700221func (a *AndroidMkEntries) SetOptionalPaths(name string, paths Paths) {
222 if len(paths) > 0 {
223 a.SetPaths(name, paths)
224 }
225}
226
Jaewoong Jung7ef4a902020-11-16 12:50:29 -0800227// AddPaths appends the given path strings to a Make variable with the given name.
Colin Cross08dca382020-07-21 20:31:17 -0700228func (a *AndroidMkEntries) AddPaths(name string, paths Paths) {
229 if _, ok := a.EntryMap[name]; !ok {
230 a.entryOrder = append(a.entryOrder, name)
231 }
232 a.EntryMap[name] = append(a.EntryMap[name], paths.Strings()...)
233}
234
Jaewoong Jung7ef4a902020-11-16 12:50:29 -0800235// SetBoolIfTrue sets a Make variable with the given name to true if the given flag is true.
236// It is a no-op if the given flag is false.
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700237func (a *AndroidMkEntries) SetBoolIfTrue(name string, flag bool) {
238 if flag {
239 if _, ok := a.EntryMap[name]; !ok {
240 a.entryOrder = append(a.entryOrder, name)
241 }
242 a.EntryMap[name] = []string{"true"}
243 }
244}
245
Jaewoong Jung7ef4a902020-11-16 12:50:29 -0800246// SetBool sets a Make variable with the given name to if the given bool flag value.
Jaewoong Jung9a1e8bd2019-09-04 20:17:54 -0700247func (a *AndroidMkEntries) SetBool(name string, flag bool) {
248 if _, ok := a.EntryMap[name]; !ok {
249 a.entryOrder = append(a.entryOrder, name)
250 }
251 if flag {
252 a.EntryMap[name] = []string{"true"}
253 } else {
254 a.EntryMap[name] = []string{"false"}
255 }
256}
257
Jaewoong Jung7ef4a902020-11-16 12:50:29 -0800258// AddStrings appends the given strings to a Make variable with the given name.
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700259func (a *AndroidMkEntries) AddStrings(name string, value ...string) {
260 if len(value) == 0 {
261 return
262 }
263 if _, ok := a.EntryMap[name]; !ok {
264 a.entryOrder = append(a.entryOrder, name)
265 }
266 a.EntryMap[name] = append(a.EntryMap[name], value...)
267}
268
Liz Kammer57f5b332020-11-24 12:42:58 -0800269// AddCompatibilityTestSuites adds the supplied test suites to the EntryMap, with special handling
270// for partial MTS test suites.
271func (a *AndroidMkEntries) AddCompatibilityTestSuites(suites ...string) {
272 // MTS supports a full test suite and partial per-module MTS test suites, with naming mts-${MODULE}.
273 // To reduce repetition, if we find a partial MTS test suite without an full MTS test suite,
274 // we add the full test suite to our list.
275 if PrefixInList(suites, "mts-") && !InList("mts", suites) {
276 suites = append(suites, "mts")
277 }
278 a.AddStrings("LOCAL_COMPATIBILITY_SUITE", suites...)
279}
280
Paul Duffin8b0349c2020-11-26 14:33:21 +0000281// The contributions to the dist.
282type distContributions struct {
283 // List of goals and the dist copy instructions.
284 copiesForGoals []*copiesForGoals
285}
286
287// getCopiesForGoals returns a copiesForGoals into which copy instructions that
288// must be processed when building one or more of those goals can be added.
289func (d *distContributions) getCopiesForGoals(goals string) *copiesForGoals {
290 copiesForGoals := &copiesForGoals{goals: goals}
291 d.copiesForGoals = append(d.copiesForGoals, copiesForGoals)
292 return copiesForGoals
293}
294
295// Associates a list of dist copy instructions with a set of goals for which they
296// should be run.
297type copiesForGoals struct {
298 // goals are a space separated list of build targets that will trigger the
299 // copy instructions.
300 goals string
301
302 // A list of instructions to copy a module's output files to somewhere in the
303 // dist directory.
304 copies []distCopy
305}
306
307// Adds a copy instruction.
308func (d *copiesForGoals) addCopyInstruction(from Path, dest string) {
309 d.copies = append(d.copies, distCopy{from, dest})
310}
311
312// Instruction on a path that must be copied into the dist.
313type distCopy struct {
314 // The path to copy from.
315 from Path
316
317 // The destination within the dist directory to copy to.
318 dest string
319}
320
321// Compute the contributions that the module makes to the dist.
322func (a *AndroidMkEntries) getDistContributions(mod blueprint.Module) *distContributions {
Jingwen Chen40fd90a2020-06-15 05:24:19 +0000323 amod := mod.(Module).base()
324 name := amod.BaseModuleName()
325
Paul Duffin74f05592020-11-25 16:37:46 +0000326 // Collate the set of associated tag/paths available for copying to the dist.
327 // Start with an empty (nil) set.
Jingwen Chen7b27ca72020-07-24 09:13:49 +0000328 var availableTaggedDists TaggedDistFiles
Jingwen Chen40fd90a2020-06-15 05:24:19 +0000329
Paul Duffin74f05592020-11-25 16:37:46 +0000330 // Then merge in any that are provided explicitly by the module.
Jingwen Chen84811862020-07-21 11:32:19 +0000331 if a.DistFiles != nil {
Paul Duffin74f05592020-11-25 16:37:46 +0000332 // Merge the DistFiles into the set.
333 availableTaggedDists = availableTaggedDists.merge(a.DistFiles)
334 }
335
336 // If no paths have been provided for the DefaultDistTag and the output file is
337 // valid then add that as the default dist path.
338 if _, ok := availableTaggedDists[DefaultDistTag]; !ok && a.OutputFile.Valid() {
339 availableTaggedDists = availableTaggedDists.addPathsForTag(DefaultDistTag, a.OutputFile.Path())
340 }
341
Paul Duffinaf970a22020-11-23 23:32:56 +0000342 // If the distFiles created by GenerateTaggedDistFiles contains paths for the
343 // DefaultDistTag then that takes priority so delete any existing paths.
344 if _, ok := amod.distFiles[DefaultDistTag]; ok {
345 delete(availableTaggedDists, DefaultDistTag)
346 }
347
348 // Finally, merge the distFiles created by GenerateTaggedDistFiles.
349 availableTaggedDists = availableTaggedDists.merge(amod.distFiles)
350
Paul Duffin74f05592020-11-25 16:37:46 +0000351 if len(availableTaggedDists) == 0 {
Jingwen Chen7b27ca72020-07-24 09:13:49 +0000352 // Nothing dist-able for this module.
353 return nil
Jingwen Chen40fd90a2020-06-15 05:24:19 +0000354 }
355
Paul Duffin8b0349c2020-11-26 14:33:21 +0000356 // Collate the contributions this module makes to the dist.
357 distContributions := &distContributions{}
358
Jingwen Chen40fd90a2020-06-15 05:24:19 +0000359 // Iterate over this module's dist structs, merged from the dist and dists properties.
360 for _, dist := range amod.Dists() {
361 // Get the list of goals this dist should be enabled for. e.g. sdk, droidcore
362 goals := strings.Join(dist.Targets, " ")
363
364 // Get the tag representing the output files to be dist'd. e.g. ".jar", ".proguard_map"
365 var tag string
366 if dist.Tag == nil {
367 // If the dist struct does not specify a tag, use the default output files tag.
Paul Duffin74f05592020-11-25 16:37:46 +0000368 tag = DefaultDistTag
Jingwen Chen40fd90a2020-06-15 05:24:19 +0000369 } else {
370 tag = *dist.Tag
371 }
372
373 // Get the paths of the output files to be dist'd, represented by the tag.
374 // Can be an empty list.
375 tagPaths := availableTaggedDists[tag]
376 if len(tagPaths) == 0 {
377 // Nothing to dist for this tag, continue to the next dist.
378 continue
379 }
380
381 if len(tagPaths) > 1 && (dist.Dest != nil || dist.Suffix != nil) {
Paul Duffin74f05592020-11-25 16:37:46 +0000382 errorMessage := "%s: Cannot apply dest/suffix for more than one dist " +
383 "file for %q goals tag %q in module %s. The list of dist files, " +
Jingwen Chen40fd90a2020-06-15 05:24:19 +0000384 "which should have a single element, is:\n%s"
Paul Duffin74f05592020-11-25 16:37:46 +0000385 panic(fmt.Errorf(errorMessage, mod, goals, tag, name, tagPaths))
Jingwen Chen40fd90a2020-06-15 05:24:19 +0000386 }
387
Paul Duffin8b0349c2020-11-26 14:33:21 +0000388 copiesForGoals := distContributions.getCopiesForGoals(goals)
Jingwen Chen40fd90a2020-06-15 05:24:19 +0000389
Paul Duffin8b0349c2020-11-26 14:33:21 +0000390 // Iterate over each path adding a copy instruction to copiesForGoals
Jingwen Chen40fd90a2020-06-15 05:24:19 +0000391 for _, path := range tagPaths {
392 // It's possible that the Path is nil from errant modules. Be defensive here.
393 if path == nil {
394 tagName := "default" // for error message readability
395 if dist.Tag != nil {
396 tagName = *dist.Tag
397 }
398 panic(fmt.Errorf("Dist file should not be nil for the %s tag in %s", tagName, name))
399 }
400
401 dest := filepath.Base(path.String())
402
403 if dist.Dest != nil {
404 var err error
405 if dest, err = validateSafePath(*dist.Dest); err != nil {
406 // This was checked in ModuleBase.GenerateBuildActions
407 panic(err)
408 }
409 }
410
411 if dist.Suffix != nil {
412 ext := filepath.Ext(dest)
413 suffix := *dist.Suffix
414 dest = strings.TrimSuffix(dest, ext) + suffix + ext
415 }
416
417 if dist.Dir != nil {
418 var err error
419 if dest, err = validateSafePath(*dist.Dir, dest); err != nil {
420 // This was checked in ModuleBase.GenerateBuildActions
421 panic(err)
422 }
423 }
424
Paul Duffin8b0349c2020-11-26 14:33:21 +0000425 copiesForGoals.addCopyInstruction(path, dest)
426 }
427 }
428
429 return distContributions
430}
431
432// generateDistContributionsForMake generates make rules that will generate the
433// dist according to the instructions in the supplied distContribution.
434func generateDistContributionsForMake(distContributions *distContributions) []string {
435 var ret []string
436 for _, d := range distContributions.copiesForGoals {
437 ret = append(ret, fmt.Sprintf(".PHONY: %s\n", d.goals))
438 // Create dist-for-goals calls for each of the copy instructions.
439 for _, c := range d.copies {
Jingwen Chen40fd90a2020-06-15 05:24:19 +0000440 ret = append(
441 ret,
Paul Duffin8b0349c2020-11-26 14:33:21 +0000442 fmt.Sprintf("$(call dist-for-goals,%s,%s:%s)\n", d.goals, c.from.String(), c.dest))
Jingwen Chen40fd90a2020-06-15 05:24:19 +0000443 }
444 }
445
446 return ret
447}
448
Paul Duffin8b0349c2020-11-26 14:33:21 +0000449// Compute the list of Make strings to declare phony goals and dist-for-goals
450// calls from the module's dist and dists properties.
451func (a *AndroidMkEntries) GetDistForGoals(mod blueprint.Module) []string {
452 distContributions := a.getDistContributions(mod)
453 if distContributions == nil {
454 return nil
455 }
456
457 return generateDistContributionsForMake(distContributions)
458}
459
Bob Badourb4999222021-01-07 03:34:31 +0000460// Write the license variables to Make for AndroidMkData.Custom(..) methods that do not call WriteAndroidMkData(..)
461// It's required to propagate the license metadata even for module types that have non-standard interfaces to Make.
462func (a *AndroidMkEntries) WriteLicenseVariables(w io.Writer) {
463 fmt.Fprintln(w, "LOCAL_LICENSE_KINDS :=", strings.Join(a.EntryMap["LOCAL_LICENSE_KINDS"], " "))
464 fmt.Fprintln(w, "LOCAL_LICENSE_CONDITIONS :=", strings.Join(a.EntryMap["LOCAL_LICENSE_CONDITIONS"], " "))
465 fmt.Fprintln(w, "LOCAL_NOTICE_FILE :=", strings.Join(a.EntryMap["LOCAL_NOTICE_FILE"], " "))
466 if pn, ok := a.EntryMap["LOCAL_LICENSE_PACKAGE_NAME"]; ok {
467 fmt.Fprintln(w, "LOCAL_LICENSE_PACKAGE_NAME :=", strings.Join(pn, " "))
468 }
469}
470
Jaewoong Jung7ef4a902020-11-16 12:50:29 -0800471// fillInEntries goes through the common variable processing and calls the extra data funcs to
472// generate and fill in AndroidMkEntries's in-struct data, ready to be flushed to a file.
Colin Crossaa255532020-07-03 13:18:24 -0700473type fillInEntriesContext interface {
474 ModuleDir(module blueprint.Module) string
475 Config() Config
476 ModuleProvider(module blueprint.Module, provider blueprint.ProviderKey) interface{}
Colin Cross4acaea92021-12-10 23:05:02 +0000477 ModuleHasProvider(module blueprint.Module, provider blueprint.ProviderKey) bool
Colin Crossaa255532020-07-03 13:18:24 -0700478}
479
480func (a *AndroidMkEntries) fillInEntries(ctx fillInEntriesContext, mod blueprint.Module) {
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700481 a.EntryMap = make(map[string][]string)
Colin Crossf1f763a2021-10-21 16:14:19 -0700482 amod := mod.(Module)
483 base := amod.base()
484 name := base.BaseModuleName()
Colin Cross0477b422020-10-13 18:43:54 -0700485 if a.OverrideName != "" {
486 name = a.OverrideName
487 }
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700488
489 if a.Include == "" {
490 a.Include = "$(BUILD_PREBUILT)"
491 }
Colin Crossf1f763a2021-10-21 16:14:19 -0700492 a.Required = append(a.Required, amod.RequiredModuleNames()...)
493 a.Host_required = append(a.Host_required, amod.HostRequiredModuleNames()...)
494 a.Target_required = append(a.Target_required, amod.TargetRequiredModuleNames()...)
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700495
Jingwen Chen40fd90a2020-06-15 05:24:19 +0000496 for _, distString := range a.GetDistForGoals(mod) {
497 fmt.Fprintf(&a.header, distString)
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700498 }
499
500 fmt.Fprintln(&a.header, "\ninclude $(CLEAR_VARS)")
501
502 // Collect make variable assignment entries.
Colin Crossaa255532020-07-03 13:18:24 -0700503 a.SetString("LOCAL_PATH", ctx.ModuleDir(mod))
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700504 a.SetString("LOCAL_MODULE", name+a.SubName)
Colin Crossf1f763a2021-10-21 16:14:19 -0700505 a.AddStrings("LOCAL_LICENSE_KINDS", base.commonProperties.Effective_license_kinds...)
506 a.AddStrings("LOCAL_LICENSE_CONDITIONS", base.commonProperties.Effective_license_conditions...)
507 a.AddStrings("LOCAL_NOTICE_FILE", base.commonProperties.Effective_license_text.Strings()...)
Bob Badourb4999222021-01-07 03:34:31 +0000508 // TODO(b/151177513): Does this code need to set LOCAL_MODULE_IS_CONTAINER ?
Colin Crossf1f763a2021-10-21 16:14:19 -0700509 if base.commonProperties.Effective_package_name != nil {
510 a.SetString("LOCAL_LICENSE_PACKAGE_NAME", *base.commonProperties.Effective_package_name)
511 } else if len(base.commonProperties.Effective_licenses) > 0 {
512 a.SetString("LOCAL_LICENSE_PACKAGE_NAME", strings.Join(base.commonProperties.Effective_licenses, " "))
Bob Badourb4999222021-01-07 03:34:31 +0000513 }
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700514 a.SetString("LOCAL_MODULE_CLASS", a.Class)
515 a.SetString("LOCAL_PREBUILT_MODULE_FILE", a.OutputFile.String())
516 a.AddStrings("LOCAL_REQUIRED_MODULES", a.Required...)
517 a.AddStrings("LOCAL_HOST_REQUIRED_MODULES", a.Host_required...)
518 a.AddStrings("LOCAL_TARGET_REQUIRED_MODULES", a.Target_required...)
519
Colin Cross6301c3c2021-09-28 17:40:21 -0700520 // If the install rule was generated by Soong tell Make about it.
Colin Crossc68db4b2021-11-11 18:59:15 -0800521 if len(base.katiInstalls) > 0 {
Colin Cross6301c3c2021-09-28 17:40:21 -0700522 // Assume the primary install file is last since it probably needs to depend on any other
523 // installed files. If that is not the case we can add a method to specify the primary
524 // installed file.
525 a.SetPath("LOCAL_SOONG_INSTALLED_MODULE", base.katiInstalls[len(base.katiInstalls)-1].to)
526 a.SetString("LOCAL_SOONG_INSTALL_PAIRS", base.katiInstalls.BuiltInstalled())
527 a.SetPaths("LOCAL_SOONG_INSTALL_SYMLINKS", base.katiSymlinks.InstallPaths().Paths())
528 }
529
Jiyong Park89e850a2020-04-07 16:37:39 +0900530 if am, ok := mod.(ApexModule); ok {
531 a.SetBoolIfTrue("LOCAL_NOT_AVAILABLE_FOR_PLATFORM", am.NotAvailableForPlatform())
532 }
533
Colin Crossf1f763a2021-10-21 16:14:19 -0700534 archStr := base.Arch().ArchType.String()
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700535 host := false
Colin Crossf1f763a2021-10-21 16:14:19 -0700536 switch base.Os().Class {
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700537 case Host:
Colin Crossf1f763a2021-10-21 16:14:19 -0700538 if base.Target().HostCross {
Jiyong Park1613e552020-09-14 19:43:17 +0900539 // Make cannot identify LOCAL_MODULE_HOST_CROSS_ARCH:= common.
Colin Crossf1f763a2021-10-21 16:14:19 -0700540 if base.Arch().ArchType != Common {
Jiyong Park1613e552020-09-14 19:43:17 +0900541 a.SetString("LOCAL_MODULE_HOST_CROSS_ARCH", archStr)
542 }
543 } else {
544 // Make cannot identify LOCAL_MODULE_HOST_ARCH:= common.
Colin Crossf1f763a2021-10-21 16:14:19 -0700545 if base.Arch().ArchType != Common {
Jiyong Park1613e552020-09-14 19:43:17 +0900546 a.SetString("LOCAL_MODULE_HOST_ARCH", archStr)
547 }
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700548 }
549 host = true
550 case Device:
551 // Make cannot identify LOCAL_MODULE_TARGET_ARCH:= common.
Colin Crossf1f763a2021-10-21 16:14:19 -0700552 if base.Arch().ArchType != Common {
553 if base.Target().NativeBridge {
554 hostArchStr := base.Target().NativeBridgeHostArchName
dimitry1f33e402019-03-26 12:39:31 +0100555 if hostArchStr != "" {
556 a.SetString("LOCAL_MODULE_TARGET_ARCH", hostArchStr)
557 }
558 } else {
559 a.SetString("LOCAL_MODULE_TARGET_ARCH", archStr)
560 }
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700561 }
562
Colin Crossf1f763a2021-10-21 16:14:19 -0700563 if !base.InRamdisk() && !base.InVendorRamdisk() {
564 a.AddPaths("LOCAL_FULL_INIT_RC", base.initRcPaths)
Yifan Hong919dae12020-12-02 18:55:06 -0800565 }
Colin Crossf1f763a2021-10-21 16:14:19 -0700566 if len(base.vintfFragmentsPaths) > 0 {
567 a.AddPaths("LOCAL_FULL_VINTF_FRAGMENTS", base.vintfFragmentsPaths)
Liz Kammer7b3dc8a2021-04-16 16:41:59 -0400568 }
Colin Crossf1f763a2021-10-21 16:14:19 -0700569 a.SetBoolIfTrue("LOCAL_PROPRIETARY_MODULE", Bool(base.commonProperties.Proprietary))
570 if Bool(base.commonProperties.Vendor) || Bool(base.commonProperties.Soc_specific) {
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700571 a.SetString("LOCAL_VENDOR_MODULE", "true")
572 }
Colin Crossf1f763a2021-10-21 16:14:19 -0700573 a.SetBoolIfTrue("LOCAL_ODM_MODULE", Bool(base.commonProperties.Device_specific))
574 a.SetBoolIfTrue("LOCAL_PRODUCT_MODULE", Bool(base.commonProperties.Product_specific))
575 a.SetBoolIfTrue("LOCAL_SYSTEM_EXT_MODULE", Bool(base.commonProperties.System_ext_specific))
576 if base.commonProperties.Owner != nil {
577 a.SetString("LOCAL_MODULE_OWNER", *base.commonProperties.Owner)
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700578 }
579 }
580
Colin Crossf1f763a2021-10-21 16:14:19 -0700581 if len(base.noticeFiles) > 0 {
582 a.SetString("LOCAL_NOTICE_FILE", strings.Join(base.noticeFiles.Strings(), " "))
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700583 }
584
585 if host {
Colin Crossf1f763a2021-10-21 16:14:19 -0700586 makeOs := base.Os().String()
587 if base.Os() == Linux || base.Os() == LinuxBionic || base.Os() == LinuxMusl {
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700588 makeOs = "linux"
589 }
590 a.SetString("LOCAL_MODULE_HOST_OS", makeOs)
591 a.SetString("LOCAL_IS_HOST_MODULE", "true")
592 }
593
594 prefix := ""
Colin Crossf1f763a2021-10-21 16:14:19 -0700595 if base.ArchSpecific() {
596 switch base.Os().Class {
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700597 case Host:
Colin Crossf1f763a2021-10-21 16:14:19 -0700598 if base.Target().HostCross {
Jiyong Park1613e552020-09-14 19:43:17 +0900599 prefix = "HOST_CROSS_"
600 } else {
601 prefix = "HOST_"
602 }
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700603 case Device:
604 prefix = "TARGET_"
605
606 }
607
Colin Crossf1f763a2021-10-21 16:14:19 -0700608 if base.Arch().ArchType != ctx.Config().Targets[base.Os()][0].Arch.ArchType {
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700609 prefix = "2ND_" + prefix
610 }
611 }
Colin Crossaa255532020-07-03 13:18:24 -0700612
Colin Cross4acaea92021-12-10 23:05:02 +0000613 if ctx.ModuleHasProvider(mod, LicenseMetadataProvider) {
614 licenseMetadata := ctx.ModuleProvider(mod, LicenseMetadataProvider).(*LicenseMetadataInfo)
615 a.SetPath("LOCAL_SOONG_LICENSE_METADATA", licenseMetadata.LicenseMetadataPath)
616 }
617
Colin Crossaa255532020-07-03 13:18:24 -0700618 extraCtx := &androidMkExtraEntriesContext{
619 ctx: ctx,
620 mod: mod,
621 }
622
Jaewoong Junge0dc8df2019-08-27 17:33:16 -0700623 for _, extra := range a.ExtraEntries {
Colin Crossaa255532020-07-03 13:18:24 -0700624 extra(extraCtx, a)
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700625 }
626
627 // Write to footer.
628 fmt.Fprintln(&a.footer, "include "+a.Include)
Colin Crossaa255532020-07-03 13:18:24 -0700629 blueprintDir := ctx.ModuleDir(mod)
Jaewoong Jungb0c127c2019-08-29 14:56:03 -0700630 for _, footerFunc := range a.ExtraFooters {
Jaewoong Jung02b11a62020-12-07 10:23:54 -0800631 footerFunc(&a.footer, name, prefix, blueprintDir)
Jaewoong Jungb0c127c2019-08-29 14:56:03 -0700632 }
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700633}
634
Jaewoong Jung7ef4a902020-11-16 12:50:29 -0800635// write flushes the AndroidMkEntries's in-struct data populated by AndroidMkEntries into the
636// given Writer object.
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700637func (a *AndroidMkEntries) write(w io.Writer) {
Jaewoong Jungb0c127c2019-08-29 14:56:03 -0700638 if a.Disabled {
639 return
640 }
641
642 if !a.OutputFile.Valid() {
643 return
644 }
645
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700646 w.Write(a.header.Bytes())
647 for _, name := range a.entryOrder {
648 fmt.Fprintln(w, name+" := "+strings.Join(a.EntryMap[name], " "))
649 }
650 w.Write(a.footer.Bytes())
651}
652
Jaewoong Jungb0c127c2019-08-29 14:56:03 -0700653func (a *AndroidMkEntries) FooterLinesForTests() []string {
654 return strings.Split(string(a.footer.Bytes()), "\n")
655}
656
Jaewoong Jung7ef4a902020-11-16 12:50:29 -0800657// AndroidMkSingleton is a singleton to collect Android.mk data from all modules and dump them into
658// the final Android-<product_name>.mk file output.
Colin Cross0875c522017-11-28 17:34:01 -0800659func AndroidMkSingleton() Singleton {
Dan Willemsen218f6562015-07-08 18:13:11 -0700660 return &androidMkSingleton{}
661}
662
663type androidMkSingleton struct{}
664
Colin Cross0875c522017-11-28 17:34:01 -0800665func (c *androidMkSingleton) GenerateBuildActions(ctx SingletonContext) {
Jaewoong Jung7ef4a902020-11-16 12:50:29 -0800666 // Skip if Soong wasn't invoked from Make.
Jingwen Chencda22c92020-11-23 00:22:30 -0500667 if !ctx.Config().KatiEnabled() {
Dan Willemsen5ba07e82015-12-11 13:51:06 -0800668 return
669 }
670
Colin Cross2465c3d2018-09-28 10:19:18 -0700671 var androidMkModulesList []blueprint.Module
Colin Cross4f6e4e62016-01-11 12:55:55 -0800672
Colin Cross2465c3d2018-09-28 10:19:18 -0700673 ctx.VisitAllModulesBlueprint(func(module blueprint.Module) {
Colin Cross0875c522017-11-28 17:34:01 -0800674 androidMkModulesList = append(androidMkModulesList, module)
Colin Cross4f6e4e62016-01-11 12:55:55 -0800675 })
Dan Willemsen218f6562015-07-08 18:13:11 -0700676
Jaewoong Jung7ef4a902020-11-16 12:50:29 -0800677 // Sort the module list by the module names to eliminate random churns, which may erroneously
678 // invoke additional build processes.
Colin Cross1ad81422019-01-14 12:47:35 -0800679 sort.SliceStable(androidMkModulesList, func(i, j int) bool {
680 return ctx.ModuleName(androidMkModulesList[i]) < ctx.ModuleName(androidMkModulesList[j])
681 })
Colin Crossd779da42015-12-17 18:00:23 -0800682
Dan Willemsen45133ac2018-03-09 21:22:06 -0800683 transMk := PathForOutput(ctx, "Android"+String(ctx.Config().productVariables.Make_suffix)+".mk")
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700684 if ctx.Failed() {
685 return
686 }
Dan Willemsen218f6562015-07-08 18:13:11 -0700687
Colin Cross988414c2020-01-11 01:11:46 +0000688 err := translateAndroidMk(ctx, absolutePath(transMk.String()), androidMkModulesList)
Dan Willemsen218f6562015-07-08 18:13:11 -0700689 if err != nil {
690 ctx.Errorf(err.Error())
691 }
692
Colin Cross0875c522017-11-28 17:34:01 -0800693 ctx.Build(pctx, BuildParams{
694 Rule: blueprint.Phony,
695 Output: transMk,
Dan Willemsen218f6562015-07-08 18:13:11 -0700696 })
697}
698
Colin Cross836e3872021-11-09 12:30:59 -0800699func translateAndroidMk(ctx SingletonContext, absMkFile string, mods []blueprint.Module) error {
Dan Willemsen218f6562015-07-08 18:13:11 -0700700 buf := &bytes.Buffer{}
701
Dan Willemsen97750522016-02-09 17:43:51 -0800702 fmt.Fprintln(buf, "LOCAL_MODULE_MAKEFILE := $(lastword $(MAKEFILE_LIST))")
Dan Willemsen218f6562015-07-08 18:13:11 -0700703
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800704 typeStats := make(map[string]int)
Dan Willemsen218f6562015-07-08 18:13:11 -0700705 for _, mod := range mods {
706 err := translateAndroidMkModule(ctx, buf, mod)
707 if err != nil {
Colin Cross836e3872021-11-09 12:30:59 -0800708 os.Remove(absMkFile)
Dan Willemsen218f6562015-07-08 18:13:11 -0700709 return err
710 }
Dan Willemsen70e17fa2016-07-25 16:00:20 -0700711
Colin Cross2465c3d2018-09-28 10:19:18 -0700712 if amod, ok := mod.(Module); ok && ctx.PrimaryModule(amod) == amod {
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800713 typeStats[ctx.ModuleType(amod)] += 1
Dan Willemsen70e17fa2016-07-25 16:00:20 -0700714 }
715 }
716
717 keys := []string{}
718 fmt.Fprintln(buf, "\nSTATS.SOONG_MODULE_TYPE :=")
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800719 for k := range typeStats {
Dan Willemsen70e17fa2016-07-25 16:00:20 -0700720 keys = append(keys, k)
721 }
722 sort.Strings(keys)
723 for _, mod_type := range keys {
724 fmt.Fprintln(buf, "STATS.SOONG_MODULE_TYPE +=", mod_type)
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800725 fmt.Fprintf(buf, "STATS.SOONG_MODULE_TYPE.%s := %d\n", mod_type, typeStats[mod_type])
Dan Willemsen218f6562015-07-08 18:13:11 -0700726 }
727
Colin Cross836e3872021-11-09 12:30:59 -0800728 return pathtools.WriteFileIfChanged(absMkFile, buf.Bytes(), 0666)
Dan Willemsen218f6562015-07-08 18:13:11 -0700729}
730
Colin Cross0875c522017-11-28 17:34:01 -0800731func translateAndroidMkModule(ctx SingletonContext, w io.Writer, mod blueprint.Module) error {
Colin Cross953d3a22018-09-05 16:23:54 -0700732 defer func() {
733 if r := recover(); r != nil {
734 panic(fmt.Errorf("%s in translateAndroidMkModule for module %s variant %s",
735 r, ctx.ModuleName(mod), ctx.ModuleSubDir(mod)))
736 }
737 }()
738
Bob Badourb4999222021-01-07 03:34:31 +0000739 // Additional cases here require review for correct license propagation to make.
Colin Cross2465c3d2018-09-28 10:19:18 -0700740 switch x := mod.(type) {
741 case AndroidMkDataProvider:
742 return translateAndroidModule(ctx, w, mod, x)
743 case bootstrap.GoBinaryTool:
744 return translateGoBinaryModule(ctx, w, mod, x)
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700745 case AndroidMkEntriesProvider:
746 return translateAndroidMkEntriesModule(ctx, w, mod, x)
Colin Cross2465c3d2018-09-28 10:19:18 -0700747 default:
Bob Badourb4999222021-01-07 03:34:31 +0000748 // Not exported to make so no make variables to set.
Dan Willemsen218f6562015-07-08 18:13:11 -0700749 return nil
750 }
Colin Cross2465c3d2018-09-28 10:19:18 -0700751}
752
Jaewoong Jung7ef4a902020-11-16 12:50:29 -0800753// A simple, special Android.mk entry output func to make it possible to build blueprint tools using
754// m by making them phony targets.
Colin Cross2465c3d2018-09-28 10:19:18 -0700755func translateGoBinaryModule(ctx SingletonContext, w io.Writer, mod blueprint.Module,
756 goBinary bootstrap.GoBinaryTool) error {
757
758 name := ctx.ModuleName(mod)
759 fmt.Fprintln(w, ".PHONY:", name)
760 fmt.Fprintln(w, name+":", goBinary.InstallPath())
761 fmt.Fprintln(w, "")
Bob Badourb4999222021-01-07 03:34:31 +0000762 // Assuming no rules in make include go binaries in distributables.
763 // If the assumption is wrong, make will fail to build without the necessary .meta_lic and .meta_module files.
764 // In that case, add the targets and rules here to build a .meta_lic file for `name` and a .meta_module for
765 // `goBinary.InstallPath()` pointing to the `name`.meta_lic file.
Colin Cross2465c3d2018-09-28 10:19:18 -0700766
767 return nil
768}
769
Colin Crossaa255532020-07-03 13:18:24 -0700770func (data *AndroidMkData) fillInData(ctx fillInEntriesContext, mod blueprint.Module) {
Jooyung Han12df5fb2019-07-11 16:18:47 +0900771 // Get the preamble content through AndroidMkEntries logic.
Jooyung Han2ed99d02020-06-24 23:26:26 +0900772 data.Entries = AndroidMkEntries{
Jooyung Han12df5fb2019-07-11 16:18:47 +0900773 Class: data.Class,
774 SubName: data.SubName,
Jingwen Chen40fd90a2020-06-15 05:24:19 +0000775 DistFiles: data.DistFiles,
Jooyung Han12df5fb2019-07-11 16:18:47 +0900776 OutputFile: data.OutputFile,
777 Disabled: data.Disabled,
778 Include: data.Include,
779 Required: data.Required,
780 Host_required: data.Host_required,
781 Target_required: data.Target_required,
782 }
Colin Crossaa255532020-07-03 13:18:24 -0700783 data.Entries.fillInEntries(ctx, mod)
Jooyung Han12df5fb2019-07-11 16:18:47 +0900784
785 // copy entries back to data since it is used in Custom
Jooyung Han2ed99d02020-06-24 23:26:26 +0900786 data.Required = data.Entries.Required
787 data.Host_required = data.Entries.Host_required
788 data.Target_required = data.Entries.Target_required
Jooyung Han12df5fb2019-07-11 16:18:47 +0900789}
790
Jaewoong Jung7ef4a902020-11-16 12:50:29 -0800791// A support func for the deprecated AndroidMkDataProvider interface. Use AndroidMkEntryProvider
792// instead.
Colin Cross2465c3d2018-09-28 10:19:18 -0700793func translateAndroidModule(ctx SingletonContext, w io.Writer, mod blueprint.Module,
794 provider AndroidMkDataProvider) error {
Dan Willemsen218f6562015-07-08 18:13:11 -0700795
Colin Cross635c3b02016-05-18 15:37:25 -0700796 amod := mod.(Module).base()
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700797 if shouldSkipAndroidMkProcessing(amod) {
Jeff Gaston088e29e2017-11-29 16:47:17 -0800798 return nil
799 }
800
Colin Cross91825d22017-08-10 16:59:47 -0700801 data := provider.AndroidMk()
Colin Cross53499412017-09-07 13:20:25 -0700802 if data.Include == "" {
803 data.Include = "$(BUILD_PREBUILT)"
804 }
805
Colin Crossaa255532020-07-03 13:18:24 -0700806 data.fillInData(ctx, mod)
Dan Willemsen01a405a2016-06-13 17:19:03 -0700807
Colin Cross0f86d182017-08-10 17:07:28 -0700808 prefix := ""
809 if amod.ArchSpecific() {
810 switch amod.Os().Class {
811 case Host:
Jiyong Park1613e552020-09-14 19:43:17 +0900812 if amod.Target().HostCross {
813 prefix = "HOST_CROSS_"
814 } else {
815 prefix = "HOST_"
816 }
Colin Cross0f86d182017-08-10 17:07:28 -0700817 case Device:
818 prefix = "TARGET_"
Colin Crossa2344662016-03-24 13:14:12 -0700819
Dan Willemsen218f6562015-07-08 18:13:11 -0700820 }
821
Dan Willemsen0ef639b2018-10-10 17:02:29 -0700822 if amod.Arch().ArchType != ctx.Config().Targets[amod.Os()][0].Arch.ArchType {
Colin Cross0f86d182017-08-10 17:07:28 -0700823 prefix = "2ND_" + prefix
824 }
Dan Willemsen218f6562015-07-08 18:13:11 -0700825 }
826
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700827 name := provider.BaseModuleName()
Colin Cross0f86d182017-08-10 17:07:28 -0700828 blueprintDir := filepath.Dir(ctx.BlueprintFile(mod))
829
830 if data.Custom != nil {
Bob Badourb4999222021-01-07 03:34:31 +0000831 // List of module types allowed to use .Custom(...)
832 // Additions to the list require careful review for proper license handling.
Colin Crossaa255532020-07-03 13:18:24 -0700833 switch reflect.TypeOf(mod).String() { // ctx.ModuleType(mod) doesn't work: aidl_interface creates phony without type
Bob Badourb4999222021-01-07 03:34:31 +0000834 case "*aidl.aidlApi": // writes non-custom before adding .phony
835 case "*aidl.aidlMapping": // writes non-custom before adding .phony
836 case "*android.customModule": // appears in tests only
Dan Willemsen9fe14102021-07-13 21:52:04 -0700837 case "*android_sdk.sdkRepoHost": // doesn't go through base_rules
Bob Badourb4999222021-01-07 03:34:31 +0000838 case "*apex.apexBundle": // license properties written
839 case "*bpf.bpf": // license properties written (both for module and objs)
840 case "*genrule.Module": // writes non-custom before adding .phony
841 case "*java.SystemModules": // doesn't go through base_rules
842 case "*java.systemModulesImport": // doesn't go through base_rules
843 case "*phony.phony": // license properties written
844 case "*selinux.selinuxContextsModule": // license properties written
845 case "*sysprop.syspropLibrary": // license properties written
846 default:
Bob Badour65ee90a2021-09-02 15:33:10 -0700847 if !ctx.Config().IsEnvFalse("ANDROID_REQUIRE_LICENSES") {
Bob Badourb4999222021-01-07 03:34:31 +0000848 return fmt.Errorf("custom make rules not allowed for %q (%q) module %q", ctx.ModuleType(mod), reflect.TypeOf(mod), ctx.ModuleName(mod))
849 }
850 }
Colin Cross0f86d182017-08-10 17:07:28 -0700851 data.Custom(w, name, prefix, blueprintDir, data)
852 } else {
853 WriteAndroidMkData(w, data)
854 }
855
856 return nil
857}
858
Jaewoong Jung7ef4a902020-11-16 12:50:29 -0800859// A support func for the deprecated AndroidMkDataProvider interface. Use AndroidMkEntryProvider
860// instead.
Colin Cross0f86d182017-08-10 17:07:28 -0700861func WriteAndroidMkData(w io.Writer, data AndroidMkData) {
862 if data.Disabled {
863 return
864 }
865
866 if !data.OutputFile.Valid() {
867 return
868 }
869
Jooyung Han2ed99d02020-06-24 23:26:26 +0900870 // write preamble via Entries
871 data.Entries.footer = bytes.Buffer{}
872 data.Entries.write(w)
Colin Cross0f86d182017-08-10 17:07:28 -0700873
Colin Crossca860ac2016-01-04 14:34:37 -0800874 for _, extra := range data.Extra {
Colin Cross27a4b052017-08-10 16:32:23 -0700875 extra(w, data.OutputFile.Path())
Dan Willemsen97750522016-02-09 17:43:51 -0800876 }
877
Colin Cross53499412017-09-07 13:20:25 -0700878 fmt.Fprintln(w, "include "+data.Include)
Dan Willemsen218f6562015-07-08 18:13:11 -0700879}
Sasha Smundakb6d23052019-04-01 18:37:36 -0700880
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700881func translateAndroidMkEntriesModule(ctx SingletonContext, w io.Writer, mod blueprint.Module,
882 provider AndroidMkEntriesProvider) error {
883 if shouldSkipAndroidMkProcessing(mod.(Module).base()) {
884 return nil
Sasha Smundakb6d23052019-04-01 18:37:36 -0700885 }
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700886
Bob Badourb4999222021-01-07 03:34:31 +0000887 // Any new or special cases here need review to verify correct propagation of license information.
Jiyong Park0b0e1b92019-12-03 13:24:29 +0900888 for _, entries := range provider.AndroidMkEntries() {
Colin Crossaa255532020-07-03 13:18:24 -0700889 entries.fillInEntries(ctx, mod)
Jiyong Park0b0e1b92019-12-03 13:24:29 +0900890 entries.write(w)
891 }
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700892
893 return nil
894}
895
Chih-Hung Hsieh80783772021-10-11 16:46:56 -0700896func ShouldSkipAndroidMkProcessing(module Module) bool {
897 return shouldSkipAndroidMkProcessing(module.base())
898}
899
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700900func shouldSkipAndroidMkProcessing(module *ModuleBase) bool {
901 if !module.commonProperties.NamespaceExportedToMake {
902 // TODO(jeffrygaston) do we want to validate that there are no modules being
903 // exported to Kati that depend on this module?
904 return true
Sasha Smundakb6d23052019-04-01 18:37:36 -0700905 }
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700906
Dan Willemsendef7b5d2021-10-17 00:22:33 -0700907 // On Mac, only expose host darwin modules to Make, as that's all we claim to support.
908 // In reality, some of them depend on device-built (Java) modules, so we can't disable all
909 // device modules in Soong, but we can hide them from Make (and thus the build user interface)
910 if runtime.GOOS == "darwin" && module.Os() != Darwin {
911 return true
912 }
913
Dan Willemsen8528f4e2021-10-19 00:22:06 -0700914 // Only expose the primary Darwin target, as Make does not understand Darwin+Arm64
915 if module.Os() == Darwin && module.Target().HostCross {
916 return true
917 }
918
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700919 return !module.Enabled() ||
Colin Crossa9c8c9f2020-12-16 10:20:23 -0800920 module.commonProperties.HideFromMake ||
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700921 // Make does not understand LinuxBionic
922 module.Os() == LinuxBionic
Sasha Smundakb6d23052019-04-01 18:37:36 -0700923}
Dan Shi31949122020-09-21 12:11:02 -0700924
Jaewoong Jung7ef4a902020-11-16 12:50:29 -0800925// A utility func to format LOCAL_TEST_DATA outputs. See the comments on DataPath to understand how
926// to use this func.
Dan Shi31949122020-09-21 12:11:02 -0700927func AndroidMkDataPaths(data []DataPath) []string {
928 var testFiles []string
929 for _, d := range data {
930 rel := d.SrcPath.Rel()
931 path := d.SrcPath.String()
Jaewoong Jung7ef4a902020-11-16 12:50:29 -0800932 // LOCAL_TEST_DATA requires the rel portion of the path to be removed from the path.
Dan Shi31949122020-09-21 12:11:02 -0700933 if !strings.HasSuffix(path, rel) {
934 panic(fmt.Errorf("path %q does not end with %q", path, rel))
935 }
936 path = strings.TrimSuffix(path, rel)
937 testFileString := path + ":" + rel
938 if len(d.RelativeInstallPath) > 0 {
939 testFileString += ":" + d.RelativeInstallPath
940 }
941 testFiles = append(testFiles, testFileString)
942 }
943 return testFiles
944}