blob: 42593bac44c84c4e2f6ffd03061012fa01ce5e7f [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
Colin Cross635c3b02016-05-18 15:37:25 -070015package android
Dan Willemsen218f6562015-07-08 18:13:11 -070016
17import (
18 "bytes"
Dan Willemsen97750522016-02-09 17:43:51 -080019 "fmt"
Dan Willemsen218f6562015-07-08 18:13:11 -070020 "io"
21 "io/ioutil"
22 "os"
23 "path/filepath"
24 "sort"
Dan Willemsen0fda89f2016-06-01 15:25:32 -070025 "strings"
Dan Willemsen218f6562015-07-08 18:13:11 -070026
Dan Willemsen218f6562015-07-08 18:13:11 -070027 "github.com/google/blueprint"
Colin Cross2465c3d2018-09-28 10:19:18 -070028 "github.com/google/blueprint/bootstrap"
Dan Willemsen218f6562015-07-08 18:13:11 -070029)
30
31func init() {
Paul Duffin8c3fec42020-03-04 20:15:08 +000032 RegisterAndroidMkBuildComponents(InitRegistrationContext)
33}
34
35func RegisterAndroidMkBuildComponents(ctx RegistrationContext) {
36 ctx.RegisterSingletonType("androidmk", AndroidMkSingleton)
Dan Willemsen218f6562015-07-08 18:13:11 -070037}
38
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -070039// Deprecated: consider using AndroidMkEntriesProvider instead, especially if you're not going to
40// use the Custom function.
Dan Willemsen218f6562015-07-08 18:13:11 -070041type AndroidMkDataProvider interface {
Colin Crossa18e9cf2017-08-10 17:00:19 -070042 AndroidMk() AndroidMkData
Colin Crossce75d2c2016-10-06 16:12:58 -070043 BaseModuleName() string
Dan Willemsen218f6562015-07-08 18:13:11 -070044}
45
46type AndroidMkData struct {
Sasha Smundakb6d23052019-04-01 18:37:36 -070047 Class string
48 SubName string
Jingwen Chen40fd90a2020-06-15 05:24:19 +000049 DistFiles TaggedDistFiles
Sasha Smundakb6d23052019-04-01 18:37:36 -070050 OutputFile OptionalPath
51 Disabled bool
52 Include string
53 Required []string
54 Host_required []string
55 Target_required []string
Dan Willemsen218f6562015-07-08 18:13:11 -070056
Colin Cross0f86d182017-08-10 17:07:28 -070057 Custom func(w io.Writer, name, prefix, moduleDir string, data AndroidMkData)
Dan Willemsen218f6562015-07-08 18:13:11 -070058
Colin Cross27a4b052017-08-10 16:32:23 -070059 Extra []AndroidMkExtraFunc
Colin Cross0f86d182017-08-10 17:07:28 -070060
Jooyung Han2ed99d02020-06-24 23:26:26 +090061 Entries AndroidMkEntries
Dan Willemsen218f6562015-07-08 18:13:11 -070062}
63
Colin Cross27a4b052017-08-10 16:32:23 -070064type AndroidMkExtraFunc func(w io.Writer, outputFile Path)
65
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -070066// Allows modules to customize their Android*.mk output.
67type AndroidMkEntriesProvider interface {
Jiyong Park0b0e1b92019-12-03 13:24:29 +090068 AndroidMkEntries() []AndroidMkEntries
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -070069 BaseModuleName() string
70}
71
72type AndroidMkEntries struct {
73 Class string
74 SubName string
Colin Cross0477b422020-10-13 18:43:54 -070075 OverrideName string
Jingwen Chen40fd90a2020-06-15 05:24:19 +000076 DistFiles TaggedDistFiles
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -070077 OutputFile OptionalPath
78 Disabled bool
79 Include string
80 Required []string
81 Host_required []string
82 Target_required []string
83
84 header bytes.Buffer
85 footer bytes.Buffer
86
Jaewoong Junge0dc8df2019-08-27 17:33:16 -070087 ExtraEntries []AndroidMkExtraEntriesFunc
Jaewoong Jungb0c127c2019-08-29 14:56:03 -070088 ExtraFooters []AndroidMkExtraFootersFunc
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -070089
90 EntryMap map[string][]string
91 entryOrder []string
92}
93
Jaewoong Junge0dc8df2019-08-27 17:33:16 -070094type AndroidMkExtraEntriesFunc func(entries *AndroidMkEntries)
Jaewoong Jungb0c127c2019-08-29 14:56:03 -070095type AndroidMkExtraFootersFunc func(w io.Writer, name, prefix, moduleDir string, entries *AndroidMkEntries)
Jaewoong Junge0dc8df2019-08-27 17:33:16 -070096
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -070097func (a *AndroidMkEntries) SetString(name, value string) {
98 if _, ok := a.EntryMap[name]; !ok {
99 a.entryOrder = append(a.entryOrder, name)
100 }
101 a.EntryMap[name] = []string{value}
102}
103
Jaewoong Jung9a1e8bd2019-09-04 20:17:54 -0700104func (a *AndroidMkEntries) SetPath(name string, path Path) {
105 if _, ok := a.EntryMap[name]; !ok {
106 a.entryOrder = append(a.entryOrder, name)
107 }
108 a.EntryMap[name] = []string{path.String()}
109}
110
Colin Crossc0efd1d2020-07-03 11:56:24 -0700111func (a *AndroidMkEntries) SetOptionalPath(name string, path OptionalPath) {
112 if path.Valid() {
113 a.SetPath(name, path.Path())
114 }
115}
116
117func (a *AndroidMkEntries) AddPath(name string, path Path) {
118 if _, ok := a.EntryMap[name]; !ok {
119 a.entryOrder = append(a.entryOrder, name)
120 }
121 a.EntryMap[name] = append(a.EntryMap[name], path.String())
122}
123
124func (a *AndroidMkEntries) AddOptionalPath(name string, path OptionalPath) {
125 if path.Valid() {
126 a.AddPath(name, path.Path())
127 }
128}
129
Colin Cross08dca382020-07-21 20:31:17 -0700130func (a *AndroidMkEntries) SetPaths(name string, paths Paths) {
131 if _, ok := a.EntryMap[name]; !ok {
132 a.entryOrder = append(a.entryOrder, name)
133 }
134 a.EntryMap[name] = paths.Strings()
135}
136
137func (a *AndroidMkEntries) SetOptionalPaths(name string, paths Paths) {
138 if len(paths) > 0 {
139 a.SetPaths(name, paths)
140 }
141}
142
143func (a *AndroidMkEntries) AddPaths(name string, paths Paths) {
144 if _, ok := a.EntryMap[name]; !ok {
145 a.entryOrder = append(a.entryOrder, name)
146 }
147 a.EntryMap[name] = append(a.EntryMap[name], paths.Strings()...)
148}
149
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700150func (a *AndroidMkEntries) SetBoolIfTrue(name string, flag bool) {
151 if flag {
152 if _, ok := a.EntryMap[name]; !ok {
153 a.entryOrder = append(a.entryOrder, name)
154 }
155 a.EntryMap[name] = []string{"true"}
156 }
157}
158
Jaewoong Jung9a1e8bd2019-09-04 20:17:54 -0700159func (a *AndroidMkEntries) SetBool(name string, flag bool) {
160 if _, ok := a.EntryMap[name]; !ok {
161 a.entryOrder = append(a.entryOrder, name)
162 }
163 if flag {
164 a.EntryMap[name] = []string{"true"}
165 } else {
166 a.EntryMap[name] = []string{"false"}
167 }
168}
169
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700170func (a *AndroidMkEntries) AddStrings(name string, value ...string) {
171 if len(value) == 0 {
172 return
173 }
174 if _, ok := a.EntryMap[name]; !ok {
175 a.entryOrder = append(a.entryOrder, name)
176 }
177 a.EntryMap[name] = append(a.EntryMap[name], value...)
178}
179
Paul Duffin8b0349c2020-11-26 14:33:21 +0000180// The contributions to the dist.
181type distContributions struct {
182 // List of goals and the dist copy instructions.
183 copiesForGoals []*copiesForGoals
184}
185
186// getCopiesForGoals returns a copiesForGoals into which copy instructions that
187// must be processed when building one or more of those goals can be added.
188func (d *distContributions) getCopiesForGoals(goals string) *copiesForGoals {
189 copiesForGoals := &copiesForGoals{goals: goals}
190 d.copiesForGoals = append(d.copiesForGoals, copiesForGoals)
191 return copiesForGoals
192}
193
194// Associates a list of dist copy instructions with a set of goals for which they
195// should be run.
196type copiesForGoals struct {
197 // goals are a space separated list of build targets that will trigger the
198 // copy instructions.
199 goals string
200
201 // A list of instructions to copy a module's output files to somewhere in the
202 // dist directory.
203 copies []distCopy
204}
205
206// Adds a copy instruction.
207func (d *copiesForGoals) addCopyInstruction(from Path, dest string) {
208 d.copies = append(d.copies, distCopy{from, dest})
209}
210
211// Instruction on a path that must be copied into the dist.
212type distCopy struct {
213 // The path to copy from.
214 from Path
215
216 // The destination within the dist directory to copy to.
217 dest string
218}
219
220// Compute the contributions that the module makes to the dist.
221func (a *AndroidMkEntries) getDistContributions(mod blueprint.Module) *distContributions {
Jingwen Chen40fd90a2020-06-15 05:24:19 +0000222 amod := mod.(Module).base()
223 name := amod.BaseModuleName()
224
Paul Duffin74f05592020-11-25 16:37:46 +0000225 // Collate the set of associated tag/paths available for copying to the dist.
226 // Start with an empty (nil) set.
Jingwen Chen7b27ca72020-07-24 09:13:49 +0000227 var availableTaggedDists TaggedDistFiles
Jingwen Chen40fd90a2020-06-15 05:24:19 +0000228
Paul Duffin74f05592020-11-25 16:37:46 +0000229 // Then merge in any that are provided explicitly by the module.
Jingwen Chen84811862020-07-21 11:32:19 +0000230 if a.DistFiles != nil {
Paul Duffin74f05592020-11-25 16:37:46 +0000231 // Merge the DistFiles into the set.
232 availableTaggedDists = availableTaggedDists.merge(a.DistFiles)
233 }
234
235 // If no paths have been provided for the DefaultDistTag and the output file is
236 // valid then add that as the default dist path.
237 if _, ok := availableTaggedDists[DefaultDistTag]; !ok && a.OutputFile.Valid() {
238 availableTaggedDists = availableTaggedDists.addPathsForTag(DefaultDistTag, a.OutputFile.Path())
239 }
240
241 if len(availableTaggedDists) == 0 {
Jingwen Chen7b27ca72020-07-24 09:13:49 +0000242 // Nothing dist-able for this module.
243 return nil
Jingwen Chen40fd90a2020-06-15 05:24:19 +0000244 }
245
Paul Duffin8b0349c2020-11-26 14:33:21 +0000246 // Collate the contributions this module makes to the dist.
247 distContributions := &distContributions{}
248
Jingwen Chen40fd90a2020-06-15 05:24:19 +0000249 // Iterate over this module's dist structs, merged from the dist and dists properties.
250 for _, dist := range amod.Dists() {
251 // Get the list of goals this dist should be enabled for. e.g. sdk, droidcore
252 goals := strings.Join(dist.Targets, " ")
253
254 // Get the tag representing the output files to be dist'd. e.g. ".jar", ".proguard_map"
255 var tag string
256 if dist.Tag == nil {
257 // If the dist struct does not specify a tag, use the default output files tag.
Paul Duffin74f05592020-11-25 16:37:46 +0000258 tag = DefaultDistTag
Jingwen Chen40fd90a2020-06-15 05:24:19 +0000259 } else {
260 tag = *dist.Tag
261 }
262
263 // Get the paths of the output files to be dist'd, represented by the tag.
264 // Can be an empty list.
265 tagPaths := availableTaggedDists[tag]
266 if len(tagPaths) == 0 {
267 // Nothing to dist for this tag, continue to the next dist.
268 continue
269 }
270
271 if len(tagPaths) > 1 && (dist.Dest != nil || dist.Suffix != nil) {
Paul Duffin74f05592020-11-25 16:37:46 +0000272 errorMessage := "%s: Cannot apply dest/suffix for more than one dist " +
273 "file for %q goals tag %q in module %s. The list of dist files, " +
Jingwen Chen40fd90a2020-06-15 05:24:19 +0000274 "which should have a single element, is:\n%s"
Paul Duffin74f05592020-11-25 16:37:46 +0000275 panic(fmt.Errorf(errorMessage, mod, goals, tag, name, tagPaths))
Jingwen Chen40fd90a2020-06-15 05:24:19 +0000276 }
277
Paul Duffin8b0349c2020-11-26 14:33:21 +0000278 copiesForGoals := distContributions.getCopiesForGoals(goals)
Jingwen Chen40fd90a2020-06-15 05:24:19 +0000279
Paul Duffin8b0349c2020-11-26 14:33:21 +0000280 // Iterate over each path adding a copy instruction to copiesForGoals
Jingwen Chen40fd90a2020-06-15 05:24:19 +0000281 for _, path := range tagPaths {
282 // It's possible that the Path is nil from errant modules. Be defensive here.
283 if path == nil {
284 tagName := "default" // for error message readability
285 if dist.Tag != nil {
286 tagName = *dist.Tag
287 }
288 panic(fmt.Errorf("Dist file should not be nil for the %s tag in %s", tagName, name))
289 }
290
291 dest := filepath.Base(path.String())
292
293 if dist.Dest != nil {
294 var err error
295 if dest, err = validateSafePath(*dist.Dest); err != nil {
296 // This was checked in ModuleBase.GenerateBuildActions
297 panic(err)
298 }
299 }
300
301 if dist.Suffix != nil {
302 ext := filepath.Ext(dest)
303 suffix := *dist.Suffix
304 dest = strings.TrimSuffix(dest, ext) + suffix + ext
305 }
306
307 if dist.Dir != nil {
308 var err error
309 if dest, err = validateSafePath(*dist.Dir, dest); err != nil {
310 // This was checked in ModuleBase.GenerateBuildActions
311 panic(err)
312 }
313 }
314
Paul Duffin8b0349c2020-11-26 14:33:21 +0000315 copiesForGoals.addCopyInstruction(path, dest)
316 }
317 }
318
319 return distContributions
320}
321
322// generateDistContributionsForMake generates make rules that will generate the
323// dist according to the instructions in the supplied distContribution.
324func generateDistContributionsForMake(distContributions *distContributions) []string {
325 var ret []string
326 for _, d := range distContributions.copiesForGoals {
327 ret = append(ret, fmt.Sprintf(".PHONY: %s\n", d.goals))
328 // Create dist-for-goals calls for each of the copy instructions.
329 for _, c := range d.copies {
Jingwen Chen40fd90a2020-06-15 05:24:19 +0000330 ret = append(
331 ret,
Paul Duffin8b0349c2020-11-26 14:33:21 +0000332 fmt.Sprintf("$(call dist-for-goals,%s,%s:%s)\n", d.goals, c.from.String(), c.dest))
Jingwen Chen40fd90a2020-06-15 05:24:19 +0000333 }
334 }
335
336 return ret
337}
338
Paul Duffin8b0349c2020-11-26 14:33:21 +0000339// Compute the list of Make strings to declare phony goals and dist-for-goals
340// calls from the module's dist and dists properties.
341func (a *AndroidMkEntries) GetDistForGoals(mod blueprint.Module) []string {
342 distContributions := a.getDistContributions(mod)
343 if distContributions == nil {
344 return nil
345 }
346
347 return generateDistContributionsForMake(distContributions)
348}
349
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700350func (a *AndroidMkEntries) fillInEntries(config Config, bpPath string, mod blueprint.Module) {
351 a.EntryMap = make(map[string][]string)
352 amod := mod.(Module).base()
353 name := amod.BaseModuleName()
Colin Cross0477b422020-10-13 18:43:54 -0700354 if a.OverrideName != "" {
355 name = a.OverrideName
356 }
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700357
358 if a.Include == "" {
359 a.Include = "$(BUILD_PREBUILT)"
360 }
361 a.Required = append(a.Required, amod.commonProperties.Required...)
362 a.Host_required = append(a.Host_required, amod.commonProperties.Host_required...)
363 a.Target_required = append(a.Target_required, amod.commonProperties.Target_required...)
364
Jingwen Chen40fd90a2020-06-15 05:24:19 +0000365 for _, distString := range a.GetDistForGoals(mod) {
366 fmt.Fprintf(&a.header, distString)
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700367 }
368
369 fmt.Fprintln(&a.header, "\ninclude $(CLEAR_VARS)")
370
371 // Collect make variable assignment entries.
372 a.SetString("LOCAL_PATH", filepath.Dir(bpPath))
373 a.SetString("LOCAL_MODULE", name+a.SubName)
374 a.SetString("LOCAL_MODULE_CLASS", a.Class)
375 a.SetString("LOCAL_PREBUILT_MODULE_FILE", a.OutputFile.String())
376 a.AddStrings("LOCAL_REQUIRED_MODULES", a.Required...)
377 a.AddStrings("LOCAL_HOST_REQUIRED_MODULES", a.Host_required...)
378 a.AddStrings("LOCAL_TARGET_REQUIRED_MODULES", a.Target_required...)
379
Jiyong Park89e850a2020-04-07 16:37:39 +0900380 if am, ok := mod.(ApexModule); ok {
381 a.SetBoolIfTrue("LOCAL_NOT_AVAILABLE_FOR_PLATFORM", am.NotAvailableForPlatform())
382 }
383
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700384 archStr := amod.Arch().ArchType.String()
385 host := false
386 switch amod.Os().Class {
387 case Host:
Jiyong Park1613e552020-09-14 19:43:17 +0900388 if amod.Target().HostCross {
389 // Make cannot identify LOCAL_MODULE_HOST_CROSS_ARCH:= common.
390 if amod.Arch().ArchType != Common {
391 a.SetString("LOCAL_MODULE_HOST_CROSS_ARCH", archStr)
392 }
393 } else {
394 // Make cannot identify LOCAL_MODULE_HOST_ARCH:= common.
395 if amod.Arch().ArchType != Common {
396 a.SetString("LOCAL_MODULE_HOST_ARCH", archStr)
397 }
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700398 }
399 host = true
400 case Device:
401 // Make cannot identify LOCAL_MODULE_TARGET_ARCH:= common.
Colin Cross0f7d2ef2019-10-16 11:03:10 -0700402 if amod.Arch().ArchType != Common {
dimitry1f33e402019-03-26 12:39:31 +0100403 if amod.Target().NativeBridge {
dimitry8d6dde82019-07-11 10:23:53 +0200404 hostArchStr := amod.Target().NativeBridgeHostArchName
dimitry1f33e402019-03-26 12:39:31 +0100405 if hostArchStr != "" {
406 a.SetString("LOCAL_MODULE_TARGET_ARCH", hostArchStr)
407 }
408 } else {
409 a.SetString("LOCAL_MODULE_TARGET_ARCH", archStr)
410 }
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700411 }
412
413 a.AddStrings("LOCAL_INIT_RC", amod.commonProperties.Init_rc...)
414 a.AddStrings("LOCAL_VINTF_FRAGMENTS", amod.commonProperties.Vintf_fragments...)
415 a.SetBoolIfTrue("LOCAL_PROPRIETARY_MODULE", Bool(amod.commonProperties.Proprietary))
416 if Bool(amod.commonProperties.Vendor) || Bool(amod.commonProperties.Soc_specific) {
417 a.SetString("LOCAL_VENDOR_MODULE", "true")
418 }
419 a.SetBoolIfTrue("LOCAL_ODM_MODULE", Bool(amod.commonProperties.Device_specific))
420 a.SetBoolIfTrue("LOCAL_PRODUCT_MODULE", Bool(amod.commonProperties.Product_specific))
Justin Yund5f6c822019-06-25 16:47:17 +0900421 a.SetBoolIfTrue("LOCAL_SYSTEM_EXT_MODULE", Bool(amod.commonProperties.System_ext_specific))
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700422 if amod.commonProperties.Owner != nil {
423 a.SetString("LOCAL_MODULE_OWNER", *amod.commonProperties.Owner)
424 }
425 }
426
Bob Badoura75b0572020-02-18 20:21:55 -0800427 if len(amod.noticeFiles) > 0 {
428 a.SetString("LOCAL_NOTICE_FILE", strings.Join(amod.noticeFiles.Strings(), " "))
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700429 }
430
431 if host {
432 makeOs := amod.Os().String()
433 if amod.Os() == Linux || amod.Os() == LinuxBionic {
434 makeOs = "linux"
435 }
436 a.SetString("LOCAL_MODULE_HOST_OS", makeOs)
437 a.SetString("LOCAL_IS_HOST_MODULE", "true")
438 }
439
440 prefix := ""
441 if amod.ArchSpecific() {
442 switch amod.Os().Class {
443 case Host:
Jiyong Park1613e552020-09-14 19:43:17 +0900444 if amod.Target().HostCross {
445 prefix = "HOST_CROSS_"
446 } else {
447 prefix = "HOST_"
448 }
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700449 case Device:
450 prefix = "TARGET_"
451
452 }
453
454 if amod.Arch().ArchType != config.Targets[amod.Os()][0].Arch.ArchType {
455 prefix = "2ND_" + prefix
456 }
457 }
Jaewoong Junge0dc8df2019-08-27 17:33:16 -0700458 for _, extra := range a.ExtraEntries {
459 extra(a)
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700460 }
461
462 // Write to footer.
463 fmt.Fprintln(&a.footer, "include "+a.Include)
Jaewoong Jungb0c127c2019-08-29 14:56:03 -0700464 blueprintDir := filepath.Dir(bpPath)
465 for _, footerFunc := range a.ExtraFooters {
466 footerFunc(&a.footer, name, prefix, blueprintDir, a)
467 }
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700468}
469
470func (a *AndroidMkEntries) write(w io.Writer) {
Jaewoong Jungb0c127c2019-08-29 14:56:03 -0700471 if a.Disabled {
472 return
473 }
474
475 if !a.OutputFile.Valid() {
476 return
477 }
478
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700479 w.Write(a.header.Bytes())
480 for _, name := range a.entryOrder {
481 fmt.Fprintln(w, name+" := "+strings.Join(a.EntryMap[name], " "))
482 }
483 w.Write(a.footer.Bytes())
484}
485
Jaewoong Jungb0c127c2019-08-29 14:56:03 -0700486func (a *AndroidMkEntries) FooterLinesForTests() []string {
487 return strings.Split(string(a.footer.Bytes()), "\n")
488}
489
Colin Cross0875c522017-11-28 17:34:01 -0800490func AndroidMkSingleton() Singleton {
Dan Willemsen218f6562015-07-08 18:13:11 -0700491 return &androidMkSingleton{}
492}
493
494type androidMkSingleton struct{}
495
Colin Cross0875c522017-11-28 17:34:01 -0800496func (c *androidMkSingleton) GenerateBuildActions(ctx SingletonContext) {
Jingwen Chencda22c92020-11-23 00:22:30 -0500497 if !ctx.Config().KatiEnabled() {
Dan Willemsen5ba07e82015-12-11 13:51:06 -0800498 return
499 }
500
Colin Cross2465c3d2018-09-28 10:19:18 -0700501 var androidMkModulesList []blueprint.Module
Colin Cross4f6e4e62016-01-11 12:55:55 -0800502
Colin Cross2465c3d2018-09-28 10:19:18 -0700503 ctx.VisitAllModulesBlueprint(func(module blueprint.Module) {
Colin Cross0875c522017-11-28 17:34:01 -0800504 androidMkModulesList = append(androidMkModulesList, module)
Colin Cross4f6e4e62016-01-11 12:55:55 -0800505 })
Dan Willemsen218f6562015-07-08 18:13:11 -0700506
Colin Cross1ad81422019-01-14 12:47:35 -0800507 sort.SliceStable(androidMkModulesList, func(i, j int) bool {
508 return ctx.ModuleName(androidMkModulesList[i]) < ctx.ModuleName(androidMkModulesList[j])
509 })
Colin Crossd779da42015-12-17 18:00:23 -0800510
Dan Willemsen45133ac2018-03-09 21:22:06 -0800511 transMk := PathForOutput(ctx, "Android"+String(ctx.Config().productVariables.Make_suffix)+".mk")
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700512 if ctx.Failed() {
513 return
514 }
Dan Willemsen218f6562015-07-08 18:13:11 -0700515
Colin Cross988414c2020-01-11 01:11:46 +0000516 err := translateAndroidMk(ctx, absolutePath(transMk.String()), androidMkModulesList)
Dan Willemsen218f6562015-07-08 18:13:11 -0700517 if err != nil {
518 ctx.Errorf(err.Error())
519 }
520
Colin Cross0875c522017-11-28 17:34:01 -0800521 ctx.Build(pctx, BuildParams{
522 Rule: blueprint.Phony,
523 Output: transMk,
Dan Willemsen218f6562015-07-08 18:13:11 -0700524 })
525}
526
Colin Cross2465c3d2018-09-28 10:19:18 -0700527func translateAndroidMk(ctx SingletonContext, mkFile string, mods []blueprint.Module) error {
Dan Willemsen218f6562015-07-08 18:13:11 -0700528 buf := &bytes.Buffer{}
529
Dan Willemsen97750522016-02-09 17:43:51 -0800530 fmt.Fprintln(buf, "LOCAL_MODULE_MAKEFILE := $(lastword $(MAKEFILE_LIST))")
Dan Willemsen218f6562015-07-08 18:13:11 -0700531
Dan Willemsen70e17fa2016-07-25 16:00:20 -0700532 type_stats := make(map[string]int)
Dan Willemsen218f6562015-07-08 18:13:11 -0700533 for _, mod := range mods {
534 err := translateAndroidMkModule(ctx, buf, mod)
535 if err != nil {
536 os.Remove(mkFile)
537 return err
538 }
Dan Willemsen70e17fa2016-07-25 16:00:20 -0700539
Colin Cross2465c3d2018-09-28 10:19:18 -0700540 if amod, ok := mod.(Module); ok && ctx.PrimaryModule(amod) == amod {
541 type_stats[ctx.ModuleType(amod)] += 1
Dan Willemsen70e17fa2016-07-25 16:00:20 -0700542 }
543 }
544
545 keys := []string{}
546 fmt.Fprintln(buf, "\nSTATS.SOONG_MODULE_TYPE :=")
547 for k := range type_stats {
548 keys = append(keys, k)
549 }
550 sort.Strings(keys)
551 for _, mod_type := range keys {
552 fmt.Fprintln(buf, "STATS.SOONG_MODULE_TYPE +=", mod_type)
553 fmt.Fprintf(buf, "STATS.SOONG_MODULE_TYPE.%s := %d\n", mod_type, type_stats[mod_type])
Dan Willemsen218f6562015-07-08 18:13:11 -0700554 }
555
556 // Don't write to the file if it hasn't changed
Colin Cross988414c2020-01-11 01:11:46 +0000557 if _, err := os.Stat(absolutePath(mkFile)); !os.IsNotExist(err) {
558 if data, err := ioutil.ReadFile(absolutePath(mkFile)); err == nil {
Dan Willemsen218f6562015-07-08 18:13:11 -0700559 matches := buf.Len() == len(data)
560
561 if matches {
562 for i, value := range buf.Bytes() {
563 if value != data[i] {
564 matches = false
565 break
566 }
567 }
568 }
569
570 if matches {
571 return nil
572 }
573 }
574 }
575
Colin Cross988414c2020-01-11 01:11:46 +0000576 return ioutil.WriteFile(absolutePath(mkFile), buf.Bytes(), 0666)
Dan Willemsen218f6562015-07-08 18:13:11 -0700577}
578
Colin Cross0875c522017-11-28 17:34:01 -0800579func translateAndroidMkModule(ctx SingletonContext, w io.Writer, mod blueprint.Module) error {
Colin Cross953d3a22018-09-05 16:23:54 -0700580 defer func() {
581 if r := recover(); r != nil {
582 panic(fmt.Errorf("%s in translateAndroidMkModule for module %s variant %s",
583 r, ctx.ModuleName(mod), ctx.ModuleSubDir(mod)))
584 }
585 }()
586
Colin Cross2465c3d2018-09-28 10:19:18 -0700587 switch x := mod.(type) {
588 case AndroidMkDataProvider:
589 return translateAndroidModule(ctx, w, mod, x)
590 case bootstrap.GoBinaryTool:
591 return translateGoBinaryModule(ctx, w, mod, x)
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700592 case AndroidMkEntriesProvider:
593 return translateAndroidMkEntriesModule(ctx, w, mod, x)
Colin Cross2465c3d2018-09-28 10:19:18 -0700594 default:
Dan Willemsen218f6562015-07-08 18:13:11 -0700595 return nil
596 }
Colin Cross2465c3d2018-09-28 10:19:18 -0700597}
598
599func translateGoBinaryModule(ctx SingletonContext, w io.Writer, mod blueprint.Module,
600 goBinary bootstrap.GoBinaryTool) error {
601
602 name := ctx.ModuleName(mod)
603 fmt.Fprintln(w, ".PHONY:", name)
604 fmt.Fprintln(w, name+":", goBinary.InstallPath())
605 fmt.Fprintln(w, "")
606
607 return nil
608}
609
Jooyung Han12df5fb2019-07-11 16:18:47 +0900610func (data *AndroidMkData) fillInData(config Config, bpPath string, mod blueprint.Module) {
611 // Get the preamble content through AndroidMkEntries logic.
Jooyung Han2ed99d02020-06-24 23:26:26 +0900612 data.Entries = AndroidMkEntries{
Jooyung Han12df5fb2019-07-11 16:18:47 +0900613 Class: data.Class,
614 SubName: data.SubName,
Jingwen Chen40fd90a2020-06-15 05:24:19 +0000615 DistFiles: data.DistFiles,
Jooyung Han12df5fb2019-07-11 16:18:47 +0900616 OutputFile: data.OutputFile,
617 Disabled: data.Disabled,
618 Include: data.Include,
619 Required: data.Required,
620 Host_required: data.Host_required,
621 Target_required: data.Target_required,
622 }
Jooyung Han2ed99d02020-06-24 23:26:26 +0900623 data.Entries.fillInEntries(config, bpPath, mod)
Jooyung Han12df5fb2019-07-11 16:18:47 +0900624
625 // copy entries back to data since it is used in Custom
Jooyung Han2ed99d02020-06-24 23:26:26 +0900626 data.Required = data.Entries.Required
627 data.Host_required = data.Entries.Host_required
628 data.Target_required = data.Entries.Target_required
Jooyung Han12df5fb2019-07-11 16:18:47 +0900629}
630
Colin Cross2465c3d2018-09-28 10:19:18 -0700631func translateAndroidModule(ctx SingletonContext, w io.Writer, mod blueprint.Module,
632 provider AndroidMkDataProvider) error {
Dan Willemsen218f6562015-07-08 18:13:11 -0700633
Colin Cross635c3b02016-05-18 15:37:25 -0700634 amod := mod.(Module).base()
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700635 if shouldSkipAndroidMkProcessing(amod) {
Jeff Gaston088e29e2017-11-29 16:47:17 -0800636 return nil
637 }
638
Colin Cross91825d22017-08-10 16:59:47 -0700639 data := provider.AndroidMk()
Colin Cross53499412017-09-07 13:20:25 -0700640 if data.Include == "" {
641 data.Include = "$(BUILD_PREBUILT)"
642 }
643
Jooyung Han12df5fb2019-07-11 16:18:47 +0900644 data.fillInData(ctx.Config(), ctx.BlueprintFile(mod), mod)
Dan Willemsen01a405a2016-06-13 17:19:03 -0700645
Colin Cross0f86d182017-08-10 17:07:28 -0700646 prefix := ""
647 if amod.ArchSpecific() {
648 switch amod.Os().Class {
649 case Host:
Jiyong Park1613e552020-09-14 19:43:17 +0900650 if amod.Target().HostCross {
651 prefix = "HOST_CROSS_"
652 } else {
653 prefix = "HOST_"
654 }
Colin Cross0f86d182017-08-10 17:07:28 -0700655 case Device:
656 prefix = "TARGET_"
Colin Crossa2344662016-03-24 13:14:12 -0700657
Dan Willemsen218f6562015-07-08 18:13:11 -0700658 }
659
Dan Willemsen0ef639b2018-10-10 17:02:29 -0700660 if amod.Arch().ArchType != ctx.Config().Targets[amod.Os()][0].Arch.ArchType {
Colin Cross0f86d182017-08-10 17:07:28 -0700661 prefix = "2ND_" + prefix
662 }
Dan Willemsen218f6562015-07-08 18:13:11 -0700663 }
664
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700665 name := provider.BaseModuleName()
Colin Cross0f86d182017-08-10 17:07:28 -0700666 blueprintDir := filepath.Dir(ctx.BlueprintFile(mod))
667
668 if data.Custom != nil {
669 data.Custom(w, name, prefix, blueprintDir, data)
670 } else {
671 WriteAndroidMkData(w, data)
672 }
673
674 return nil
675}
676
677func WriteAndroidMkData(w io.Writer, data AndroidMkData) {
678 if data.Disabled {
679 return
680 }
681
682 if !data.OutputFile.Valid() {
683 return
684 }
685
Jooyung Han2ed99d02020-06-24 23:26:26 +0900686 // write preamble via Entries
687 data.Entries.footer = bytes.Buffer{}
688 data.Entries.write(w)
Colin Cross0f86d182017-08-10 17:07:28 -0700689
Colin Crossca860ac2016-01-04 14:34:37 -0800690 for _, extra := range data.Extra {
Colin Cross27a4b052017-08-10 16:32:23 -0700691 extra(w, data.OutputFile.Path())
Dan Willemsen97750522016-02-09 17:43:51 -0800692 }
693
Colin Cross53499412017-09-07 13:20:25 -0700694 fmt.Fprintln(w, "include "+data.Include)
Dan Willemsen218f6562015-07-08 18:13:11 -0700695}
Sasha Smundakb6d23052019-04-01 18:37:36 -0700696
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700697func translateAndroidMkEntriesModule(ctx SingletonContext, w io.Writer, mod blueprint.Module,
698 provider AndroidMkEntriesProvider) error {
699 if shouldSkipAndroidMkProcessing(mod.(Module).base()) {
700 return nil
Sasha Smundakb6d23052019-04-01 18:37:36 -0700701 }
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700702
Jiyong Park0b0e1b92019-12-03 13:24:29 +0900703 for _, entries := range provider.AndroidMkEntries() {
704 entries.fillInEntries(ctx.Config(), ctx.BlueprintFile(mod), mod)
705 entries.write(w)
706 }
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700707
708 return nil
709}
710
711func shouldSkipAndroidMkProcessing(module *ModuleBase) bool {
712 if !module.commonProperties.NamespaceExportedToMake {
713 // TODO(jeffrygaston) do we want to validate that there are no modules being
714 // exported to Kati that depend on this module?
715 return true
Sasha Smundakb6d23052019-04-01 18:37:36 -0700716 }
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700717
718 return !module.Enabled() ||
719 module.commonProperties.SkipInstall ||
720 // Make does not understand LinuxBionic
721 module.Os() == LinuxBionic
Sasha Smundakb6d23052019-04-01 18:37:36 -0700722}
Dan Shi31949122020-09-21 12:11:02 -0700723
724func AndroidMkDataPaths(data []DataPath) []string {
725 var testFiles []string
726 for _, d := range data {
727 rel := d.SrcPath.Rel()
728 path := d.SrcPath.String()
729 if !strings.HasSuffix(path, rel) {
730 panic(fmt.Errorf("path %q does not end with %q", path, rel))
731 }
732 path = strings.TrimSuffix(path, rel)
733 testFileString := path + ":" + rel
734 if len(d.RelativeInstallPath) > 0 {
735 testFileString += ":" + d.RelativeInstallPath
736 }
737 testFiles = append(testFiles, testFileString)
738 }
739 return testFiles
740}