blob: 472038efde24aee499e79edf1dc2d61a5a6cd7f6 [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"
28 "io/ioutil"
29 "os"
30 "path/filepath"
31 "sort"
Dan Willemsen0fda89f2016-06-01 15:25:32 -070032 "strings"
Dan Willemsen218f6562015-07-08 18:13:11 -070033
Dan Willemsen218f6562015-07-08 18:13:11 -070034 "github.com/google/blueprint"
Colin Cross2465c3d2018-09-28 10:19:18 -070035 "github.com/google/blueprint/bootstrap"
Dan Willemsen218f6562015-07-08 18:13:11 -070036)
37
38func init() {
Paul Duffin8c3fec42020-03-04 20:15:08 +000039 RegisterAndroidMkBuildComponents(InitRegistrationContext)
40}
41
42func RegisterAndroidMkBuildComponents(ctx RegistrationContext) {
43 ctx.RegisterSingletonType("androidmk", AndroidMkSingleton)
Dan Willemsen218f6562015-07-08 18:13:11 -070044}
45
Jaewoong Jung7ef4a902020-11-16 12:50:29 -080046// Deprecated: Use AndroidMkEntriesProvider instead, especially if you're not going to use the
47// Custom function. It's easier to use and test.
Dan Willemsen218f6562015-07-08 18:13:11 -070048type AndroidMkDataProvider interface {
Colin Crossa18e9cf2017-08-10 17:00:19 -070049 AndroidMk() AndroidMkData
Colin Crossce75d2c2016-10-06 16:12:58 -070050 BaseModuleName() string
Dan Willemsen218f6562015-07-08 18:13:11 -070051}
52
53type AndroidMkData struct {
Sasha Smundakb6d23052019-04-01 18:37:36 -070054 Class string
55 SubName string
Jingwen Chen40fd90a2020-06-15 05:24:19 +000056 DistFiles TaggedDistFiles
Sasha Smundakb6d23052019-04-01 18:37:36 -070057 OutputFile OptionalPath
58 Disabled bool
59 Include string
60 Required []string
61 Host_required []string
62 Target_required []string
Dan Willemsen218f6562015-07-08 18:13:11 -070063
Colin Cross0f86d182017-08-10 17:07:28 -070064 Custom func(w io.Writer, name, prefix, moduleDir string, data AndroidMkData)
Dan Willemsen218f6562015-07-08 18:13:11 -070065
Colin Cross27a4b052017-08-10 16:32:23 -070066 Extra []AndroidMkExtraFunc
Colin Cross0f86d182017-08-10 17:07:28 -070067
Jooyung Han2ed99d02020-06-24 23:26:26 +090068 Entries AndroidMkEntries
Dan Willemsen218f6562015-07-08 18:13:11 -070069}
70
Colin Cross27a4b052017-08-10 16:32:23 -070071type AndroidMkExtraFunc func(w io.Writer, outputFile Path)
72
Jaewoong Jung7ef4a902020-11-16 12:50:29 -080073// Interface for modules to declare their Android.mk outputs. Note that every module needs to
74// implement this in order to be included in the final Android-<product_name>.mk output, even if
75// they only need to output the common set of entries without any customizations.
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -070076type AndroidMkEntriesProvider interface {
Jaewoong Jung7ef4a902020-11-16 12:50:29 -080077 // Returns AndroidMkEntries objects that contain all basic info plus extra customization data
78 // if needed. This is the core func to implement.
79 // Note that one can return multiple objects. For example, java_library may return an additional
80 // AndroidMkEntries object for its hostdex sub-module.
Jiyong Park0b0e1b92019-12-03 13:24:29 +090081 AndroidMkEntries() []AndroidMkEntries
Jaewoong Jung7ef4a902020-11-16 12:50:29 -080082 // Modules don't need to implement this as it's already implemented by ModuleBase.
83 // AndroidMkEntries uses BaseModuleName() instead of ModuleName() because certain modules
84 // e.g. Prebuilts, override the Name() func and return modified names.
85 // If a different name is preferred, use SubName or OverrideName in AndroidMkEntries.
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -070086 BaseModuleName() string
87}
88
Jaewoong Jung7ef4a902020-11-16 12:50:29 -080089// The core data struct that modules use to provide their Android.mk data.
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -070090type AndroidMkEntries struct {
Jaewoong Jung7ef4a902020-11-16 12:50:29 -080091 // Android.mk class string, e.g EXECUTABLES, JAVA_LIBRARIES, ETC
92 Class string
93 // Optional suffix to append to the module name. Useful when a module wants to return multiple
94 // AndroidMkEntries objects. For example, when a java_library returns an additional entry for
95 // its hostdex sub-module, this SubName field is set to "-hostdex" so that it can have a
96 // different name than the parent's.
97 SubName string
98 // If set, this value overrides the base module name. SubName is still appended.
99 OverrideName string
100 // Dist files to output
101 DistFiles TaggedDistFiles
102 // The output file for Kati to process and/or install. If absent, the module is skipped.
103 OutputFile OptionalPath
104 // If true, the module is skipped and does not appear on the final Android-<product name>.mk
105 // file. Useful when a module needs to be skipped conditionally.
106 Disabled bool
107 // The postprocessing mk file to include, e.g. $(BUILD_SYSTEM)/soong_cc_prebuilt.mk
108 // If not set, $(BUILD_SYSTEM)/prebuilt.mk is used.
109 Include string
110 // Required modules that need to be built and included in the final build output when building
111 // this module.
112 Required []string
113 // Required host modules that need to be built and included in the final build output when
114 // building this module.
115 Host_required []string
116 // Required device modules that need to be built and included in the final build output when
117 // building this module.
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700118 Target_required []string
119
120 header bytes.Buffer
121 footer bytes.Buffer
122
Jaewoong Jung7ef4a902020-11-16 12:50:29 -0800123 // Funcs to append additional Android.mk entries or modify the common ones. Multiple funcs are
124 // accepted so that common logic can be factored out as a shared func.
Jaewoong Junge0dc8df2019-08-27 17:33:16 -0700125 ExtraEntries []AndroidMkExtraEntriesFunc
Jaewoong Jung7ef4a902020-11-16 12:50:29 -0800126 // Funcs to add extra lines to the module's Android.mk output. Unlike AndroidMkExtraEntriesFunc,
127 // which simply sets Make variable values, this can be used for anything since it can write any
128 // Make statements directly to the final Android-*.mk file.
129 // Primarily used to call macros or declare/update Make targets.
Jaewoong Jungb0c127c2019-08-29 14:56:03 -0700130 ExtraFooters []AndroidMkExtraFootersFunc
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700131
Jaewoong Jung7ef4a902020-11-16 12:50:29 -0800132 // A map that holds the up-to-date Make variable values. Can be accessed from tests.
133 EntryMap map[string][]string
134 // A list of EntryMap keys in insertion order. This serves a few purposes:
135 // 1. Prevents churns. Golang map doesn't provide consistent iteration order, so without this,
136 // the outputted Android-*.mk file may change even though there have been no content changes.
137 // 2. Allows modules to refer to other variables, like LOCAL_BAR_VAR := $(LOCAL_FOO_VAR),
138 // without worrying about the variables being mixed up in the actual mk file.
139 // 3. Makes troubleshooting and spotting errors easier.
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700140 entryOrder []string
141}
142
Jaewoong Junge0dc8df2019-08-27 17:33:16 -0700143type AndroidMkExtraEntriesFunc func(entries *AndroidMkEntries)
Jaewoong Jungb0c127c2019-08-29 14:56:03 -0700144type AndroidMkExtraFootersFunc func(w io.Writer, name, prefix, moduleDir string, entries *AndroidMkEntries)
Jaewoong Junge0dc8df2019-08-27 17:33:16 -0700145
Jaewoong Jung7ef4a902020-11-16 12:50:29 -0800146// Utility funcs to manipulate Android.mk variable entries.
147
148// SetString sets a Make variable with the given name to the given value.
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700149func (a *AndroidMkEntries) SetString(name, value string) {
150 if _, ok := a.EntryMap[name]; !ok {
151 a.entryOrder = append(a.entryOrder, name)
152 }
153 a.EntryMap[name] = []string{value}
154}
155
Jaewoong Jung7ef4a902020-11-16 12:50:29 -0800156// SetPath sets a Make variable with the given name to the given path string.
Jaewoong Jung9a1e8bd2019-09-04 20:17:54 -0700157func (a *AndroidMkEntries) SetPath(name string, path Path) {
158 if _, ok := a.EntryMap[name]; !ok {
159 a.entryOrder = append(a.entryOrder, name)
160 }
161 a.EntryMap[name] = []string{path.String()}
162}
163
Jaewoong Jung7ef4a902020-11-16 12:50:29 -0800164// SetOptionalPath sets a Make variable with the given name to the given path string if it is valid.
165// It is a no-op if the given path is invalid.
Colin Crossc0efd1d2020-07-03 11:56:24 -0700166func (a *AndroidMkEntries) SetOptionalPath(name string, path OptionalPath) {
167 if path.Valid() {
168 a.SetPath(name, path.Path())
169 }
170}
171
Jaewoong Jung7ef4a902020-11-16 12:50:29 -0800172// AddPath appends the given path string to a Make variable with the given name.
Colin Crossc0efd1d2020-07-03 11:56:24 -0700173func (a *AndroidMkEntries) AddPath(name string, path Path) {
174 if _, ok := a.EntryMap[name]; !ok {
175 a.entryOrder = append(a.entryOrder, name)
176 }
177 a.EntryMap[name] = append(a.EntryMap[name], path.String())
178}
179
Jaewoong Jung7ef4a902020-11-16 12:50:29 -0800180// AddOptionalPath appends the given path string to a Make variable with the given name if it is
181// valid. It is a no-op if the given path is invalid.
Colin Crossc0efd1d2020-07-03 11:56:24 -0700182func (a *AndroidMkEntries) AddOptionalPath(name string, path OptionalPath) {
183 if path.Valid() {
184 a.AddPath(name, path.Path())
185 }
186}
187
Jaewoong Jung7ef4a902020-11-16 12:50:29 -0800188// SetPaths sets a Make variable with the given name to a slice of the given path strings.
Colin Cross08dca382020-07-21 20:31:17 -0700189func (a *AndroidMkEntries) SetPaths(name string, paths Paths) {
190 if _, ok := a.EntryMap[name]; !ok {
191 a.entryOrder = append(a.entryOrder, name)
192 }
193 a.EntryMap[name] = paths.Strings()
194}
195
Jaewoong Jung7ef4a902020-11-16 12:50:29 -0800196// SetOptionalPaths sets a Make variable with the given name to a slice of the given path strings
197// only if there are a non-zero amount of paths.
Colin Cross08dca382020-07-21 20:31:17 -0700198func (a *AndroidMkEntries) SetOptionalPaths(name string, paths Paths) {
199 if len(paths) > 0 {
200 a.SetPaths(name, paths)
201 }
202}
203
Jaewoong Jung7ef4a902020-11-16 12:50:29 -0800204// AddPaths appends the given path strings to a Make variable with the given name.
Colin Cross08dca382020-07-21 20:31:17 -0700205func (a *AndroidMkEntries) AddPaths(name string, paths Paths) {
206 if _, ok := a.EntryMap[name]; !ok {
207 a.entryOrder = append(a.entryOrder, name)
208 }
209 a.EntryMap[name] = append(a.EntryMap[name], paths.Strings()...)
210}
211
Jaewoong Jung7ef4a902020-11-16 12:50:29 -0800212// SetBoolIfTrue sets a Make variable with the given name to true if the given flag is true.
213// It is a no-op if the given flag is false.
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700214func (a *AndroidMkEntries) SetBoolIfTrue(name string, flag bool) {
215 if flag {
216 if _, ok := a.EntryMap[name]; !ok {
217 a.entryOrder = append(a.entryOrder, name)
218 }
219 a.EntryMap[name] = []string{"true"}
220 }
221}
222
Jaewoong Jung7ef4a902020-11-16 12:50:29 -0800223// SetBool sets a Make variable with the given name to if the given bool flag value.
Jaewoong Jung9a1e8bd2019-09-04 20:17:54 -0700224func (a *AndroidMkEntries) SetBool(name string, flag bool) {
225 if _, ok := a.EntryMap[name]; !ok {
226 a.entryOrder = append(a.entryOrder, name)
227 }
228 if flag {
229 a.EntryMap[name] = []string{"true"}
230 } else {
231 a.EntryMap[name] = []string{"false"}
232 }
233}
234
Jaewoong Jung7ef4a902020-11-16 12:50:29 -0800235// AddStrings appends the given strings to a Make variable with the given name.
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700236func (a *AndroidMkEntries) AddStrings(name string, value ...string) {
237 if len(value) == 0 {
238 return
239 }
240 if _, ok := a.EntryMap[name]; !ok {
241 a.entryOrder = append(a.entryOrder, name)
242 }
243 a.EntryMap[name] = append(a.EntryMap[name], value...)
244}
245
Paul Duffin8b0349c2020-11-26 14:33:21 +0000246// The contributions to the dist.
247type distContributions struct {
248 // List of goals and the dist copy instructions.
249 copiesForGoals []*copiesForGoals
250}
251
252// getCopiesForGoals returns a copiesForGoals into which copy instructions that
253// must be processed when building one or more of those goals can be added.
254func (d *distContributions) getCopiesForGoals(goals string) *copiesForGoals {
255 copiesForGoals := &copiesForGoals{goals: goals}
256 d.copiesForGoals = append(d.copiesForGoals, copiesForGoals)
257 return copiesForGoals
258}
259
260// Associates a list of dist copy instructions with a set of goals for which they
261// should be run.
262type copiesForGoals struct {
263 // goals are a space separated list of build targets that will trigger the
264 // copy instructions.
265 goals string
266
267 // A list of instructions to copy a module's output files to somewhere in the
268 // dist directory.
269 copies []distCopy
270}
271
272// Adds a copy instruction.
273func (d *copiesForGoals) addCopyInstruction(from Path, dest string) {
274 d.copies = append(d.copies, distCopy{from, dest})
275}
276
277// Instruction on a path that must be copied into the dist.
278type distCopy struct {
279 // The path to copy from.
280 from Path
281
282 // The destination within the dist directory to copy to.
283 dest string
284}
285
286// Compute the contributions that the module makes to the dist.
287func (a *AndroidMkEntries) getDistContributions(mod blueprint.Module) *distContributions {
Jingwen Chen40fd90a2020-06-15 05:24:19 +0000288 amod := mod.(Module).base()
289 name := amod.BaseModuleName()
290
Paul Duffin74f05592020-11-25 16:37:46 +0000291 // Collate the set of associated tag/paths available for copying to the dist.
292 // Start with an empty (nil) set.
Jingwen Chen7b27ca72020-07-24 09:13:49 +0000293 var availableTaggedDists TaggedDistFiles
Jingwen Chen40fd90a2020-06-15 05:24:19 +0000294
Paul Duffin74f05592020-11-25 16:37:46 +0000295 // Then merge in any that are provided explicitly by the module.
Jingwen Chen84811862020-07-21 11:32:19 +0000296 if a.DistFiles != nil {
Paul Duffin74f05592020-11-25 16:37:46 +0000297 // Merge the DistFiles into the set.
298 availableTaggedDists = availableTaggedDists.merge(a.DistFiles)
299 }
300
301 // If no paths have been provided for the DefaultDistTag and the output file is
302 // valid then add that as the default dist path.
303 if _, ok := availableTaggedDists[DefaultDistTag]; !ok && a.OutputFile.Valid() {
304 availableTaggedDists = availableTaggedDists.addPathsForTag(DefaultDistTag, a.OutputFile.Path())
305 }
306
Paul Duffinaf970a22020-11-23 23:32:56 +0000307 // If the distFiles created by GenerateTaggedDistFiles contains paths for the
308 // DefaultDistTag then that takes priority so delete any existing paths.
309 if _, ok := amod.distFiles[DefaultDistTag]; ok {
310 delete(availableTaggedDists, DefaultDistTag)
311 }
312
313 // Finally, merge the distFiles created by GenerateTaggedDistFiles.
314 availableTaggedDists = availableTaggedDists.merge(amod.distFiles)
315
Paul Duffin74f05592020-11-25 16:37:46 +0000316 if len(availableTaggedDists) == 0 {
Jingwen Chen7b27ca72020-07-24 09:13:49 +0000317 // Nothing dist-able for this module.
318 return nil
Jingwen Chen40fd90a2020-06-15 05:24:19 +0000319 }
320
Paul Duffin8b0349c2020-11-26 14:33:21 +0000321 // Collate the contributions this module makes to the dist.
322 distContributions := &distContributions{}
323
Jingwen Chen40fd90a2020-06-15 05:24:19 +0000324 // Iterate over this module's dist structs, merged from the dist and dists properties.
325 for _, dist := range amod.Dists() {
326 // Get the list of goals this dist should be enabled for. e.g. sdk, droidcore
327 goals := strings.Join(dist.Targets, " ")
328
329 // Get the tag representing the output files to be dist'd. e.g. ".jar", ".proguard_map"
330 var tag string
331 if dist.Tag == nil {
332 // If the dist struct does not specify a tag, use the default output files tag.
Paul Duffin74f05592020-11-25 16:37:46 +0000333 tag = DefaultDistTag
Jingwen Chen40fd90a2020-06-15 05:24:19 +0000334 } else {
335 tag = *dist.Tag
336 }
337
338 // Get the paths of the output files to be dist'd, represented by the tag.
339 // Can be an empty list.
340 tagPaths := availableTaggedDists[tag]
341 if len(tagPaths) == 0 {
342 // Nothing to dist for this tag, continue to the next dist.
343 continue
344 }
345
346 if len(tagPaths) > 1 && (dist.Dest != nil || dist.Suffix != nil) {
Paul Duffin74f05592020-11-25 16:37:46 +0000347 errorMessage := "%s: Cannot apply dest/suffix for more than one dist " +
348 "file for %q goals tag %q in module %s. The list of dist files, " +
Jingwen Chen40fd90a2020-06-15 05:24:19 +0000349 "which should have a single element, is:\n%s"
Paul Duffin74f05592020-11-25 16:37:46 +0000350 panic(fmt.Errorf(errorMessage, mod, goals, tag, name, tagPaths))
Jingwen Chen40fd90a2020-06-15 05:24:19 +0000351 }
352
Paul Duffin8b0349c2020-11-26 14:33:21 +0000353 copiesForGoals := distContributions.getCopiesForGoals(goals)
Jingwen Chen40fd90a2020-06-15 05:24:19 +0000354
Paul Duffin8b0349c2020-11-26 14:33:21 +0000355 // Iterate over each path adding a copy instruction to copiesForGoals
Jingwen Chen40fd90a2020-06-15 05:24:19 +0000356 for _, path := range tagPaths {
357 // It's possible that the Path is nil from errant modules. Be defensive here.
358 if path == nil {
359 tagName := "default" // for error message readability
360 if dist.Tag != nil {
361 tagName = *dist.Tag
362 }
363 panic(fmt.Errorf("Dist file should not be nil for the %s tag in %s", tagName, name))
364 }
365
366 dest := filepath.Base(path.String())
367
368 if dist.Dest != nil {
369 var err error
370 if dest, err = validateSafePath(*dist.Dest); err != nil {
371 // This was checked in ModuleBase.GenerateBuildActions
372 panic(err)
373 }
374 }
375
376 if dist.Suffix != nil {
377 ext := filepath.Ext(dest)
378 suffix := *dist.Suffix
379 dest = strings.TrimSuffix(dest, ext) + suffix + ext
380 }
381
382 if dist.Dir != nil {
383 var err error
384 if dest, err = validateSafePath(*dist.Dir, dest); err != nil {
385 // This was checked in ModuleBase.GenerateBuildActions
386 panic(err)
387 }
388 }
389
Paul Duffin8b0349c2020-11-26 14:33:21 +0000390 copiesForGoals.addCopyInstruction(path, dest)
391 }
392 }
393
394 return distContributions
395}
396
397// generateDistContributionsForMake generates make rules that will generate the
398// dist according to the instructions in the supplied distContribution.
399func generateDistContributionsForMake(distContributions *distContributions) []string {
400 var ret []string
401 for _, d := range distContributions.copiesForGoals {
402 ret = append(ret, fmt.Sprintf(".PHONY: %s\n", d.goals))
403 // Create dist-for-goals calls for each of the copy instructions.
404 for _, c := range d.copies {
Jingwen Chen40fd90a2020-06-15 05:24:19 +0000405 ret = append(
406 ret,
Paul Duffin8b0349c2020-11-26 14:33:21 +0000407 fmt.Sprintf("$(call dist-for-goals,%s,%s:%s)\n", d.goals, c.from.String(), c.dest))
Jingwen Chen40fd90a2020-06-15 05:24:19 +0000408 }
409 }
410
411 return ret
412}
413
Paul Duffin8b0349c2020-11-26 14:33:21 +0000414// Compute the list of Make strings to declare phony goals and dist-for-goals
415// calls from the module's dist and dists properties.
416func (a *AndroidMkEntries) GetDistForGoals(mod blueprint.Module) []string {
417 distContributions := a.getDistContributions(mod)
418 if distContributions == nil {
419 return nil
420 }
421
422 return generateDistContributionsForMake(distContributions)
423}
424
Jaewoong Jung7ef4a902020-11-16 12:50:29 -0800425// fillInEntries goes through the common variable processing and calls the extra data funcs to
426// generate and fill in AndroidMkEntries's in-struct data, ready to be flushed to a file.
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700427func (a *AndroidMkEntries) fillInEntries(config Config, bpPath string, mod blueprint.Module) {
428 a.EntryMap = make(map[string][]string)
429 amod := mod.(Module).base()
430 name := amod.BaseModuleName()
Colin Cross0477b422020-10-13 18:43:54 -0700431 if a.OverrideName != "" {
432 name = a.OverrideName
433 }
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700434
435 if a.Include == "" {
436 a.Include = "$(BUILD_PREBUILT)"
437 }
438 a.Required = append(a.Required, amod.commonProperties.Required...)
439 a.Host_required = append(a.Host_required, amod.commonProperties.Host_required...)
440 a.Target_required = append(a.Target_required, amod.commonProperties.Target_required...)
441
Jingwen Chen40fd90a2020-06-15 05:24:19 +0000442 for _, distString := range a.GetDistForGoals(mod) {
443 fmt.Fprintf(&a.header, distString)
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700444 }
445
446 fmt.Fprintln(&a.header, "\ninclude $(CLEAR_VARS)")
447
448 // Collect make variable assignment entries.
449 a.SetString("LOCAL_PATH", filepath.Dir(bpPath))
450 a.SetString("LOCAL_MODULE", name+a.SubName)
451 a.SetString("LOCAL_MODULE_CLASS", a.Class)
452 a.SetString("LOCAL_PREBUILT_MODULE_FILE", a.OutputFile.String())
453 a.AddStrings("LOCAL_REQUIRED_MODULES", a.Required...)
454 a.AddStrings("LOCAL_HOST_REQUIRED_MODULES", a.Host_required...)
455 a.AddStrings("LOCAL_TARGET_REQUIRED_MODULES", a.Target_required...)
456
Jiyong Park89e850a2020-04-07 16:37:39 +0900457 if am, ok := mod.(ApexModule); ok {
458 a.SetBoolIfTrue("LOCAL_NOT_AVAILABLE_FOR_PLATFORM", am.NotAvailableForPlatform())
459 }
460
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700461 archStr := amod.Arch().ArchType.String()
462 host := false
463 switch amod.Os().Class {
464 case Host:
Jiyong Park1613e552020-09-14 19:43:17 +0900465 if amod.Target().HostCross {
466 // Make cannot identify LOCAL_MODULE_HOST_CROSS_ARCH:= common.
467 if amod.Arch().ArchType != Common {
468 a.SetString("LOCAL_MODULE_HOST_CROSS_ARCH", archStr)
469 }
470 } else {
471 // Make cannot identify LOCAL_MODULE_HOST_ARCH:= common.
472 if amod.Arch().ArchType != Common {
473 a.SetString("LOCAL_MODULE_HOST_ARCH", archStr)
474 }
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700475 }
476 host = true
477 case Device:
478 // Make cannot identify LOCAL_MODULE_TARGET_ARCH:= common.
Colin Cross0f7d2ef2019-10-16 11:03:10 -0700479 if amod.Arch().ArchType != Common {
dimitry1f33e402019-03-26 12:39:31 +0100480 if amod.Target().NativeBridge {
dimitry8d6dde82019-07-11 10:23:53 +0200481 hostArchStr := amod.Target().NativeBridgeHostArchName
dimitry1f33e402019-03-26 12:39:31 +0100482 if hostArchStr != "" {
483 a.SetString("LOCAL_MODULE_TARGET_ARCH", hostArchStr)
484 }
485 } else {
486 a.SetString("LOCAL_MODULE_TARGET_ARCH", archStr)
487 }
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700488 }
489
490 a.AddStrings("LOCAL_INIT_RC", amod.commonProperties.Init_rc...)
491 a.AddStrings("LOCAL_VINTF_FRAGMENTS", amod.commonProperties.Vintf_fragments...)
492 a.SetBoolIfTrue("LOCAL_PROPRIETARY_MODULE", Bool(amod.commonProperties.Proprietary))
493 if Bool(amod.commonProperties.Vendor) || Bool(amod.commonProperties.Soc_specific) {
494 a.SetString("LOCAL_VENDOR_MODULE", "true")
495 }
496 a.SetBoolIfTrue("LOCAL_ODM_MODULE", Bool(amod.commonProperties.Device_specific))
497 a.SetBoolIfTrue("LOCAL_PRODUCT_MODULE", Bool(amod.commonProperties.Product_specific))
Justin Yund5f6c822019-06-25 16:47:17 +0900498 a.SetBoolIfTrue("LOCAL_SYSTEM_EXT_MODULE", Bool(amod.commonProperties.System_ext_specific))
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700499 if amod.commonProperties.Owner != nil {
500 a.SetString("LOCAL_MODULE_OWNER", *amod.commonProperties.Owner)
501 }
502 }
503
Bob Badoura75b0572020-02-18 20:21:55 -0800504 if len(amod.noticeFiles) > 0 {
505 a.SetString("LOCAL_NOTICE_FILE", strings.Join(amod.noticeFiles.Strings(), " "))
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700506 }
507
508 if host {
509 makeOs := amod.Os().String()
510 if amod.Os() == Linux || amod.Os() == LinuxBionic {
511 makeOs = "linux"
512 }
513 a.SetString("LOCAL_MODULE_HOST_OS", makeOs)
514 a.SetString("LOCAL_IS_HOST_MODULE", "true")
515 }
516
517 prefix := ""
518 if amod.ArchSpecific() {
519 switch amod.Os().Class {
520 case Host:
Jiyong Park1613e552020-09-14 19:43:17 +0900521 if amod.Target().HostCross {
522 prefix = "HOST_CROSS_"
523 } else {
524 prefix = "HOST_"
525 }
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700526 case Device:
527 prefix = "TARGET_"
528
529 }
530
531 if amod.Arch().ArchType != config.Targets[amod.Os()][0].Arch.ArchType {
532 prefix = "2ND_" + prefix
533 }
534 }
Jaewoong Junge0dc8df2019-08-27 17:33:16 -0700535 for _, extra := range a.ExtraEntries {
536 extra(a)
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700537 }
538
539 // Write to footer.
540 fmt.Fprintln(&a.footer, "include "+a.Include)
Jaewoong Jungb0c127c2019-08-29 14:56:03 -0700541 blueprintDir := filepath.Dir(bpPath)
542 for _, footerFunc := range a.ExtraFooters {
543 footerFunc(&a.footer, name, prefix, blueprintDir, a)
544 }
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700545}
546
Jaewoong Jung7ef4a902020-11-16 12:50:29 -0800547// write flushes the AndroidMkEntries's in-struct data populated by AndroidMkEntries into the
548// given Writer object.
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700549func (a *AndroidMkEntries) write(w io.Writer) {
Jaewoong Jungb0c127c2019-08-29 14:56:03 -0700550 if a.Disabled {
551 return
552 }
553
554 if !a.OutputFile.Valid() {
555 return
556 }
557
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700558 w.Write(a.header.Bytes())
559 for _, name := range a.entryOrder {
560 fmt.Fprintln(w, name+" := "+strings.Join(a.EntryMap[name], " "))
561 }
562 w.Write(a.footer.Bytes())
563}
564
Jaewoong Jungb0c127c2019-08-29 14:56:03 -0700565func (a *AndroidMkEntries) FooterLinesForTests() []string {
566 return strings.Split(string(a.footer.Bytes()), "\n")
567}
568
Jaewoong Jung7ef4a902020-11-16 12:50:29 -0800569// AndroidMkSingleton is a singleton to collect Android.mk data from all modules and dump them into
570// the final Android-<product_name>.mk file output.
Colin Cross0875c522017-11-28 17:34:01 -0800571func AndroidMkSingleton() Singleton {
Dan Willemsen218f6562015-07-08 18:13:11 -0700572 return &androidMkSingleton{}
573}
574
575type androidMkSingleton struct{}
576
Colin Cross0875c522017-11-28 17:34:01 -0800577func (c *androidMkSingleton) GenerateBuildActions(ctx SingletonContext) {
Jaewoong Jung7ef4a902020-11-16 12:50:29 -0800578 // Skip if Soong wasn't invoked from Make.
Jingwen Chencda22c92020-11-23 00:22:30 -0500579 if !ctx.Config().KatiEnabled() {
Dan Willemsen5ba07e82015-12-11 13:51:06 -0800580 return
581 }
582
Colin Cross2465c3d2018-09-28 10:19:18 -0700583 var androidMkModulesList []blueprint.Module
Colin Cross4f6e4e62016-01-11 12:55:55 -0800584
Colin Cross2465c3d2018-09-28 10:19:18 -0700585 ctx.VisitAllModulesBlueprint(func(module blueprint.Module) {
Colin Cross0875c522017-11-28 17:34:01 -0800586 androidMkModulesList = append(androidMkModulesList, module)
Colin Cross4f6e4e62016-01-11 12:55:55 -0800587 })
Dan Willemsen218f6562015-07-08 18:13:11 -0700588
Jaewoong Jung7ef4a902020-11-16 12:50:29 -0800589 // Sort the module list by the module names to eliminate random churns, which may erroneously
590 // invoke additional build processes.
Colin Cross1ad81422019-01-14 12:47:35 -0800591 sort.SliceStable(androidMkModulesList, func(i, j int) bool {
592 return ctx.ModuleName(androidMkModulesList[i]) < ctx.ModuleName(androidMkModulesList[j])
593 })
Colin Crossd779da42015-12-17 18:00:23 -0800594
Dan Willemsen45133ac2018-03-09 21:22:06 -0800595 transMk := PathForOutput(ctx, "Android"+String(ctx.Config().productVariables.Make_suffix)+".mk")
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700596 if ctx.Failed() {
597 return
598 }
Dan Willemsen218f6562015-07-08 18:13:11 -0700599
Colin Cross988414c2020-01-11 01:11:46 +0000600 err := translateAndroidMk(ctx, absolutePath(transMk.String()), androidMkModulesList)
Dan Willemsen218f6562015-07-08 18:13:11 -0700601 if err != nil {
602 ctx.Errorf(err.Error())
603 }
604
Colin Cross0875c522017-11-28 17:34:01 -0800605 ctx.Build(pctx, BuildParams{
606 Rule: blueprint.Phony,
607 Output: transMk,
Dan Willemsen218f6562015-07-08 18:13:11 -0700608 })
609}
610
Colin Cross2465c3d2018-09-28 10:19:18 -0700611func translateAndroidMk(ctx SingletonContext, mkFile string, mods []blueprint.Module) error {
Dan Willemsen218f6562015-07-08 18:13:11 -0700612 buf := &bytes.Buffer{}
613
Dan Willemsen97750522016-02-09 17:43:51 -0800614 fmt.Fprintln(buf, "LOCAL_MODULE_MAKEFILE := $(lastword $(MAKEFILE_LIST))")
Dan Willemsen218f6562015-07-08 18:13:11 -0700615
Dan Willemsen70e17fa2016-07-25 16:00:20 -0700616 type_stats := make(map[string]int)
Dan Willemsen218f6562015-07-08 18:13:11 -0700617 for _, mod := range mods {
618 err := translateAndroidMkModule(ctx, buf, mod)
619 if err != nil {
620 os.Remove(mkFile)
621 return err
622 }
Dan Willemsen70e17fa2016-07-25 16:00:20 -0700623
Colin Cross2465c3d2018-09-28 10:19:18 -0700624 if amod, ok := mod.(Module); ok && ctx.PrimaryModule(amod) == amod {
625 type_stats[ctx.ModuleType(amod)] += 1
Dan Willemsen70e17fa2016-07-25 16:00:20 -0700626 }
627 }
628
629 keys := []string{}
630 fmt.Fprintln(buf, "\nSTATS.SOONG_MODULE_TYPE :=")
631 for k := range type_stats {
632 keys = append(keys, k)
633 }
634 sort.Strings(keys)
635 for _, mod_type := range keys {
636 fmt.Fprintln(buf, "STATS.SOONG_MODULE_TYPE +=", mod_type)
637 fmt.Fprintf(buf, "STATS.SOONG_MODULE_TYPE.%s := %d\n", mod_type, type_stats[mod_type])
Dan Willemsen218f6562015-07-08 18:13:11 -0700638 }
639
640 // Don't write to the file if it hasn't changed
Colin Cross988414c2020-01-11 01:11:46 +0000641 if _, err := os.Stat(absolutePath(mkFile)); !os.IsNotExist(err) {
642 if data, err := ioutil.ReadFile(absolutePath(mkFile)); err == nil {
Dan Willemsen218f6562015-07-08 18:13:11 -0700643 matches := buf.Len() == len(data)
644
645 if matches {
646 for i, value := range buf.Bytes() {
647 if value != data[i] {
648 matches = false
649 break
650 }
651 }
652 }
653
654 if matches {
655 return nil
656 }
657 }
658 }
659
Colin Cross988414c2020-01-11 01:11:46 +0000660 return ioutil.WriteFile(absolutePath(mkFile), buf.Bytes(), 0666)
Dan Willemsen218f6562015-07-08 18:13:11 -0700661}
662
Colin Cross0875c522017-11-28 17:34:01 -0800663func translateAndroidMkModule(ctx SingletonContext, w io.Writer, mod blueprint.Module) error {
Colin Cross953d3a22018-09-05 16:23:54 -0700664 defer func() {
665 if r := recover(); r != nil {
666 panic(fmt.Errorf("%s in translateAndroidMkModule for module %s variant %s",
667 r, ctx.ModuleName(mod), ctx.ModuleSubDir(mod)))
668 }
669 }()
670
Colin Cross2465c3d2018-09-28 10:19:18 -0700671 switch x := mod.(type) {
672 case AndroidMkDataProvider:
673 return translateAndroidModule(ctx, w, mod, x)
674 case bootstrap.GoBinaryTool:
675 return translateGoBinaryModule(ctx, w, mod, x)
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700676 case AndroidMkEntriesProvider:
677 return translateAndroidMkEntriesModule(ctx, w, mod, x)
Colin Cross2465c3d2018-09-28 10:19:18 -0700678 default:
Dan Willemsen218f6562015-07-08 18:13:11 -0700679 return nil
680 }
Colin Cross2465c3d2018-09-28 10:19:18 -0700681}
682
Jaewoong Jung7ef4a902020-11-16 12:50:29 -0800683// A simple, special Android.mk entry output func to make it possible to build blueprint tools using
684// m by making them phony targets.
Colin Cross2465c3d2018-09-28 10:19:18 -0700685func translateGoBinaryModule(ctx SingletonContext, w io.Writer, mod blueprint.Module,
686 goBinary bootstrap.GoBinaryTool) error {
687
688 name := ctx.ModuleName(mod)
689 fmt.Fprintln(w, ".PHONY:", name)
690 fmt.Fprintln(w, name+":", goBinary.InstallPath())
691 fmt.Fprintln(w, "")
692
693 return nil
694}
695
Jooyung Han12df5fb2019-07-11 16:18:47 +0900696func (data *AndroidMkData) fillInData(config Config, bpPath string, mod blueprint.Module) {
697 // Get the preamble content through AndroidMkEntries logic.
Jooyung Han2ed99d02020-06-24 23:26:26 +0900698 data.Entries = AndroidMkEntries{
Jooyung Han12df5fb2019-07-11 16:18:47 +0900699 Class: data.Class,
700 SubName: data.SubName,
Jingwen Chen40fd90a2020-06-15 05:24:19 +0000701 DistFiles: data.DistFiles,
Jooyung Han12df5fb2019-07-11 16:18:47 +0900702 OutputFile: data.OutputFile,
703 Disabled: data.Disabled,
704 Include: data.Include,
705 Required: data.Required,
706 Host_required: data.Host_required,
707 Target_required: data.Target_required,
708 }
Jooyung Han2ed99d02020-06-24 23:26:26 +0900709 data.Entries.fillInEntries(config, bpPath, mod)
Jooyung Han12df5fb2019-07-11 16:18:47 +0900710
711 // copy entries back to data since it is used in Custom
Jooyung Han2ed99d02020-06-24 23:26:26 +0900712 data.Required = data.Entries.Required
713 data.Host_required = data.Entries.Host_required
714 data.Target_required = data.Entries.Target_required
Jooyung Han12df5fb2019-07-11 16:18:47 +0900715}
716
Jaewoong Jung7ef4a902020-11-16 12:50:29 -0800717// A support func for the deprecated AndroidMkDataProvider interface. Use AndroidMkEntryProvider
718// instead.
Colin Cross2465c3d2018-09-28 10:19:18 -0700719func translateAndroidModule(ctx SingletonContext, w io.Writer, mod blueprint.Module,
720 provider AndroidMkDataProvider) error {
Dan Willemsen218f6562015-07-08 18:13:11 -0700721
Colin Cross635c3b02016-05-18 15:37:25 -0700722 amod := mod.(Module).base()
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700723 if shouldSkipAndroidMkProcessing(amod) {
Jeff Gaston088e29e2017-11-29 16:47:17 -0800724 return nil
725 }
726
Colin Cross91825d22017-08-10 16:59:47 -0700727 data := provider.AndroidMk()
Colin Cross53499412017-09-07 13:20:25 -0700728 if data.Include == "" {
729 data.Include = "$(BUILD_PREBUILT)"
730 }
731
Jooyung Han12df5fb2019-07-11 16:18:47 +0900732 data.fillInData(ctx.Config(), ctx.BlueprintFile(mod), mod)
Dan Willemsen01a405a2016-06-13 17:19:03 -0700733
Colin Cross0f86d182017-08-10 17:07:28 -0700734 prefix := ""
735 if amod.ArchSpecific() {
736 switch amod.Os().Class {
737 case Host:
Jiyong Park1613e552020-09-14 19:43:17 +0900738 if amod.Target().HostCross {
739 prefix = "HOST_CROSS_"
740 } else {
741 prefix = "HOST_"
742 }
Colin Cross0f86d182017-08-10 17:07:28 -0700743 case Device:
744 prefix = "TARGET_"
Colin Crossa2344662016-03-24 13:14:12 -0700745
Dan Willemsen218f6562015-07-08 18:13:11 -0700746 }
747
Dan Willemsen0ef639b2018-10-10 17:02:29 -0700748 if amod.Arch().ArchType != ctx.Config().Targets[amod.Os()][0].Arch.ArchType {
Colin Cross0f86d182017-08-10 17:07:28 -0700749 prefix = "2ND_" + prefix
750 }
Dan Willemsen218f6562015-07-08 18:13:11 -0700751 }
752
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700753 name := provider.BaseModuleName()
Colin Cross0f86d182017-08-10 17:07:28 -0700754 blueprintDir := filepath.Dir(ctx.BlueprintFile(mod))
755
756 if data.Custom != nil {
757 data.Custom(w, name, prefix, blueprintDir, data)
758 } else {
759 WriteAndroidMkData(w, data)
760 }
761
762 return nil
763}
764
Jaewoong Jung7ef4a902020-11-16 12:50:29 -0800765// A support func for the deprecated AndroidMkDataProvider interface. Use AndroidMkEntryProvider
766// instead.
Colin Cross0f86d182017-08-10 17:07:28 -0700767func WriteAndroidMkData(w io.Writer, data AndroidMkData) {
768 if data.Disabled {
769 return
770 }
771
772 if !data.OutputFile.Valid() {
773 return
774 }
775
Jooyung Han2ed99d02020-06-24 23:26:26 +0900776 // write preamble via Entries
777 data.Entries.footer = bytes.Buffer{}
778 data.Entries.write(w)
Colin Cross0f86d182017-08-10 17:07:28 -0700779
Colin Crossca860ac2016-01-04 14:34:37 -0800780 for _, extra := range data.Extra {
Colin Cross27a4b052017-08-10 16:32:23 -0700781 extra(w, data.OutputFile.Path())
Dan Willemsen97750522016-02-09 17:43:51 -0800782 }
783
Colin Cross53499412017-09-07 13:20:25 -0700784 fmt.Fprintln(w, "include "+data.Include)
Dan Willemsen218f6562015-07-08 18:13:11 -0700785}
Sasha Smundakb6d23052019-04-01 18:37:36 -0700786
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700787func translateAndroidMkEntriesModule(ctx SingletonContext, w io.Writer, mod blueprint.Module,
788 provider AndroidMkEntriesProvider) error {
789 if shouldSkipAndroidMkProcessing(mod.(Module).base()) {
790 return nil
Sasha Smundakb6d23052019-04-01 18:37:36 -0700791 }
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700792
Jiyong Park0b0e1b92019-12-03 13:24:29 +0900793 for _, entries := range provider.AndroidMkEntries() {
794 entries.fillInEntries(ctx.Config(), ctx.BlueprintFile(mod), mod)
795 entries.write(w)
796 }
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700797
798 return nil
799}
800
801func shouldSkipAndroidMkProcessing(module *ModuleBase) bool {
802 if !module.commonProperties.NamespaceExportedToMake {
803 // TODO(jeffrygaston) do we want to validate that there are no modules being
804 // exported to Kati that depend on this module?
805 return true
Sasha Smundakb6d23052019-04-01 18:37:36 -0700806 }
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700807
808 return !module.Enabled() ||
809 module.commonProperties.SkipInstall ||
810 // Make does not understand LinuxBionic
811 module.Os() == LinuxBionic
Sasha Smundakb6d23052019-04-01 18:37:36 -0700812}
Dan Shi31949122020-09-21 12:11:02 -0700813
Jaewoong Jung7ef4a902020-11-16 12:50:29 -0800814// A utility func to format LOCAL_TEST_DATA outputs. See the comments on DataPath to understand how
815// to use this func.
Dan Shi31949122020-09-21 12:11:02 -0700816func AndroidMkDataPaths(data []DataPath) []string {
817 var testFiles []string
818 for _, d := range data {
819 rel := d.SrcPath.Rel()
820 path := d.SrcPath.String()
Jaewoong Jung7ef4a902020-11-16 12:50:29 -0800821 // LOCAL_TEST_DATA requires the rel portion of the path to be removed from the path.
Dan Shi31949122020-09-21 12:11:02 -0700822 if !strings.HasSuffix(path, rel) {
823 panic(fmt.Errorf("path %q does not end with %q", path, rel))
824 }
825 path = strings.TrimSuffix(path, rel)
826 testFileString := path + ":" + rel
827 if len(d.RelativeInstallPath) > 0 {
828 testFileString += ":" + d.RelativeInstallPath
829 }
830 testFiles = append(testFiles, testFileString)
831 }
832 return testFiles
833}