blob: 4039e7edbbaddd48736fa619baec5688615d0ca7 [file] [log] [blame]
Dan Willemsen4b7d5de2016-01-12 23:20:28 -08001// Copyright 2016 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 Willemsen4b7d5de2016-01-12 23:20:28 -080016
17import (
18 "bytes"
Colin Crossd9bbf4b2023-11-17 16:23:48 -080019 "cmp"
Dan Willemsen4b7d5de2016-01-12 23:20:28 -080020 "fmt"
Colin Cross6301c3c2021-09-28 17:40:21 -070021 "path/filepath"
22 "runtime"
Colin Crossd9bbf4b2023-11-17 16:23:48 -080023 "slices"
Dan Willemsen6a6478d2020-07-17 19:28:53 -070024 "sort"
Colin Cross31656952018-05-24 16:11:20 -070025 "strings"
Dan Willemsen4b7d5de2016-01-12 23:20:28 -080026
Colin Cross65494b92019-02-07 14:25:51 -080027 "github.com/google/blueprint"
Colin Crossc3d87d32020-06-04 13:25:17 -070028 "github.com/google/blueprint/pathtools"
Dan Willemsen4b7d5de2016-01-12 23:20:28 -080029 "github.com/google/blueprint/proptools"
30)
31
Dan Albertf5415d72017-08-17 16:19:59 -070032func init() {
33 RegisterMakeVarsProvider(pctx, androidMakeVarsProvider)
34}
35
36func androidMakeVarsProvider(ctx MakeVarsContext) {
Dan Albert1a246272020-07-06 14:49:35 -070037 ctx.Strict("MIN_SUPPORTED_SDK_VERSION", ctx.Config().MinSupportedSdkVersion().String())
Dan Albertf5415d72017-08-17 16:19:59 -070038}
39
Paul Duffin8eb45732022-10-04 19:03:31 +010040// /////////////////////////////////////////////////////////////////////////////
Dan Willemsen6a6478d2020-07-17 19:28:53 -070041
42// BaseMakeVarsContext contains the common functions for other packages to use
43// to declare make variables
44type BaseMakeVarsContext interface {
Dan Willemsen4b7d5de2016-01-12 23:20:28 -080045 Config() Config
Dan Willemsen3fb1fae2018-03-12 15:30:26 -070046 DeviceConfig() DeviceConfig
Colin Cross65494b92019-02-07 14:25:51 -080047 AddNinjaFileDeps(deps ...string)
Colin Cross65494b92019-02-07 14:25:51 -080048
Colin Cross65494b92019-02-07 14:25:51 -080049 Failed() bool
50
Dan Willemsen558e5172016-05-19 16:58:46 -070051 // These are equivalent to Strict and Check, but do not attempt to
52 // evaluate the values before writing them to the Makefile. They can
53 // be used when all ninja variables have already been evaluated through
54 // Eval().
55 StrictRaw(name, value string)
56 CheckRaw(name, value string)
Colin Cross8177ad22019-11-04 10:27:48 -080057
58 // GlobWithDeps returns a list of files that match the specified pattern but do not match any
59 // of the patterns in excludes. It also adds efficient dependencies to rerun the primary
60 // builder whenever a file matching the pattern as added or removed, without rerunning if a
61 // file that does not match the pattern is added to a searched directory.
62 GlobWithDeps(pattern string, excludes []string) ([]string, error)
Colin Crossc3d87d32020-06-04 13:25:17 -070063
64 // Phony creates a phony rule in Make, which will allow additional DistForGoal
65 // dependencies to be added to it. Phony can be called on the same name multiple
66 // times to add additional dependencies.
67 Phony(names string, deps ...Path)
Colin Cross3cda0d82019-09-24 13:40:07 -070068
69 // DistForGoal creates a rule to copy one or more Paths to the artifacts
70 // directory on the build server when the specified goal is built.
71 DistForGoal(goal string, paths ...Path)
72
73 // DistForGoalWithFilename creates a rule to copy a Path to the artifacts
74 // directory on the build server with the given filename when the specified
75 // goal is built.
76 DistForGoalWithFilename(goal string, path Path, filename string)
77
78 // DistForGoals creates a rule to copy one or more Paths to the artifacts
79 // directory on the build server when any of the specified goals are built.
80 DistForGoals(goals []string, paths ...Path)
81
82 // DistForGoalsWithFilename creates a rule to copy a Path to the artifacts
83 // directory on the build server with the given filename when any of the
84 // specified goals are built.
85 DistForGoalsWithFilename(goals []string, path Path, filename string)
Dan Willemsen4b7d5de2016-01-12 23:20:28 -080086}
87
Dan Willemsen6a6478d2020-07-17 19:28:53 -070088// MakeVarsContext contains the set of functions available for MakeVarsProvider
89// and SingletonMakeVarsProvider implementations.
90type MakeVarsContext interface {
91 BaseMakeVarsContext
92
93 ModuleName(module blueprint.Module) string
94 ModuleDir(module blueprint.Module) string
95 ModuleSubDir(module blueprint.Module) string
96 ModuleType(module blueprint.Module) string
Colin Cross3c0a83d2023-12-12 14:13:26 -080097 moduleProvider(module blueprint.Module, key blueprint.AnyProviderKey) (any, bool)
Dan Willemsen6a6478d2020-07-17 19:28:53 -070098 BlueprintFile(module blueprint.Module) string
99
100 ModuleErrorf(module blueprint.Module, format string, args ...interface{})
101 Errorf(format string, args ...interface{})
102
103 VisitAllModules(visit func(Module))
104 VisitAllModulesIf(pred func(Module) bool, visit func(Module))
105
106 // Verify the make variable matches the Soong version, fail the build
107 // if it does not. If the make variable is empty, just set it.
108 Strict(name, ninjaStr string)
109 // Check to see if the make variable matches the Soong version, warn if
110 // it does not. If the make variable is empty, just set it.
111 Check(name, ninjaStr string)
112
113 // These are equivalent to the above, but sort the make and soong
114 // variables before comparing them. They also show the unique entries
115 // in each list when displaying the difference, instead of the entire
116 // string.
117 StrictSorted(name, ninjaStr string)
118 CheckSorted(name, ninjaStr string)
119
120 // Evaluates a ninja string and returns the result. Used if more
121 // complicated modification needs to happen before giving it to Make.
122 Eval(ninjaStr string) (string, error)
123}
124
125// MakeVarsModuleContext contains the set of functions available for modules
126// implementing the ModuleMakeVarsProvider interface.
127type MakeVarsModuleContext interface {
128 BaseMakeVarsContext
129}
130
Colin Cross65494b92019-02-07 14:25:51 -0800131var _ PathContext = MakeVarsContext(nil)
132
Dan Willemsen4b7d5de2016-01-12 23:20:28 -0800133type MakeVarsProvider func(ctx MakeVarsContext)
134
Colin Cross0875c522017-11-28 17:34:01 -0800135func RegisterMakeVarsProvider(pctx PackageContext, provider MakeVarsProvider) {
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400136 makeVarsInitProviders = append(makeVarsInitProviders, makeVarsProvider{pctx, provider})
Dan Willemsen4b7d5de2016-01-12 23:20:28 -0800137}
138
Colin Crossed023ec2019-02-19 12:38:45 -0800139// SingletonMakeVarsProvider is a Singleton with an extra method to provide extra values to be exported to Make.
140type SingletonMakeVarsProvider interface {
Colin Crossed023ec2019-02-19 12:38:45 -0800141 // MakeVars uses a MakeVarsContext to provide extra values to be exported to Make.
142 MakeVars(ctx MakeVarsContext)
143}
144
Colin Cross06fa5882020-10-29 18:21:38 -0700145var singletonMakeVarsProvidersKey = NewOnceKey("singletonMakeVarsProvidersKey")
146
Colin Cross6ac95762021-11-09 13:17:44 -0800147func getSingletonMakevarsProviders(config Config) *[]makeVarsProvider {
148 return config.Once(singletonMakeVarsProvidersKey, func() interface{} {
149 return &[]makeVarsProvider{}
150 }).(*[]makeVarsProvider)
151}
152
Colin Cross06fa5882020-10-29 18:21:38 -0700153// registerSingletonMakeVarsProvider adds a singleton that implements SingletonMakeVarsProvider to
154// the list of MakeVarsProviders to run.
155func registerSingletonMakeVarsProvider(config Config, singleton SingletonMakeVarsProvider) {
156 // Singletons are registered on the Context and may be different between different Contexts,
157 // for example when running multiple tests. Store the SingletonMakeVarsProviders in the
158 // Config so they are attached to the Context.
Colin Cross6ac95762021-11-09 13:17:44 -0800159 singletonMakeVarsProviders := getSingletonMakevarsProviders(config)
Colin Cross06fa5882020-10-29 18:21:38 -0700160
161 *singletonMakeVarsProviders = append(*singletonMakeVarsProviders,
162 makeVarsProvider{pctx, singletonMakeVarsProviderAdapter(singleton)})
Colin Crossed023ec2019-02-19 12:38:45 -0800163}
164
Colin Cross06fa5882020-10-29 18:21:38 -0700165// singletonMakeVarsProviderAdapter converts a SingletonMakeVarsProvider to a MakeVarsProvider.
166func singletonMakeVarsProviderAdapter(singleton SingletonMakeVarsProvider) MakeVarsProvider {
Colin Crossed023ec2019-02-19 12:38:45 -0800167 return func(ctx MakeVarsContext) { singleton.MakeVars(ctx) }
168}
169
Dan Willemsen6a6478d2020-07-17 19:28:53 -0700170// ModuleMakeVarsProvider is a Module with an extra method to provide extra values to be exported to Make.
171type ModuleMakeVarsProvider interface {
172 Module
173
174 // MakeVars uses a MakeVarsModuleContext to provide extra values to be exported to Make.
175 MakeVars(ctx MakeVarsModuleContext)
176}
177
Paul Duffin8eb45732022-10-04 19:03:31 +0100178// /////////////////////////////////////////////////////////////////////////////
Dan Willemsen4b7d5de2016-01-12 23:20:28 -0800179
Colin Cross0875c522017-11-28 17:34:01 -0800180func makeVarsSingletonFunc() Singleton {
Dan Willemsen4b7d5de2016-01-12 23:20:28 -0800181 return &makeVarsSingleton{}
182}
183
Colin Cross6ac95762021-11-09 13:17:44 -0800184type makeVarsSingleton struct {
Paul Duffin8eb45732022-10-04 19:03:31 +0100185 varsForTesting []makeVarsVariable
Colin Cross6ac95762021-11-09 13:17:44 -0800186 installsForTesting []byte
187}
Dan Willemsen4b7d5de2016-01-12 23:20:28 -0800188
189type makeVarsProvider struct {
Colin Cross0875c522017-11-28 17:34:01 -0800190 pctx PackageContext
Dan Willemsen4b7d5de2016-01-12 23:20:28 -0800191 call MakeVarsProvider
192}
193
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400194// Collection of makevars providers that are registered in init() methods.
195var makeVarsInitProviders []makeVarsProvider
196
Dan Willemsen4b7d5de2016-01-12 23:20:28 -0800197type makeVarsContext struct {
Colin Cross65494b92019-02-07 14:25:51 -0800198 SingletonContext
Colin Crossc3d87d32020-06-04 13:25:17 -0700199 config Config
200 pctx PackageContext
201 vars []makeVarsVariable
202 phonies []phony
Colin Cross3cda0d82019-09-24 13:40:07 -0700203 dists []dist
Dan Willemsen4b7d5de2016-01-12 23:20:28 -0800204}
205
206var _ MakeVarsContext = &makeVarsContext{}
207
208type makeVarsVariable struct {
209 name string
210 value string
211 sort bool
212 strict bool
213}
214
Colin Crossc3d87d32020-06-04 13:25:17 -0700215type phony struct {
216 name string
217 deps []string
218}
219
Colin Cross3cda0d82019-09-24 13:40:07 -0700220type dist struct {
221 goals []string
222 paths []string
223}
224
Colin Cross0875c522017-11-28 17:34:01 -0800225func (s *makeVarsSingleton) GenerateBuildActions(ctx SingletonContext) {
Jingwen Chencda22c92020-11-23 00:22:30 -0500226 if !ctx.Config().KatiEnabled() {
Dan Willemsen4b7d5de2016-01-12 23:20:28 -0800227 return
228 }
229
Colin Cross988414c2020-01-11 01:11:46 +0000230 outFile := absolutePath(PathForOutput(ctx,
231 "make_vars"+proptools.String(ctx.Config().productVariables.Make_suffix)+".mk").String())
Dan Willemsen4b7d5de2016-01-12 23:20:28 -0800232
Colin Crossc3d87d32020-06-04 13:25:17 -0700233 lateOutFile := absolutePath(PathForOutput(ctx,
234 "late"+proptools.String(ctx.Config().productVariables.Make_suffix)+".mk").String())
235
Colin Cross6301c3c2021-09-28 17:40:21 -0700236 installsFile := absolutePath(PathForOutput(ctx,
237 "installs"+proptools.String(ctx.Config().productVariables.Make_suffix)+".mk").String())
238
Dan Willemsen4b7d5de2016-01-12 23:20:28 -0800239 if ctx.Failed() {
240 return
241 }
242
Colin Cross3cda0d82019-09-24 13:40:07 -0700243 var vars []makeVarsVariable
244 var dists []dist
Colin Crossc3d87d32020-06-04 13:25:17 -0700245 var phonies []phony
Colin Cross6301c3c2021-09-28 17:40:21 -0700246 var katiInstalls []katiInstall
Colin Crossd9bbf4b2023-11-17 16:23:48 -0800247 var katiInitRcInstalls []katiInstall
248 var katiVintfManifestInstalls []katiInstall
Colin Cross6301c3c2021-09-28 17:40:21 -0700249 var katiSymlinks []katiInstall
Colin Cross06fa5882020-10-29 18:21:38 -0700250
251 providers := append([]makeVarsProvider(nil), makeVarsInitProviders...)
Colin Cross6ac95762021-11-09 13:17:44 -0800252 providers = append(providers, *getSingletonMakevarsProviders(ctx.Config())...)
Colin Cross06fa5882020-10-29 18:21:38 -0700253
254 for _, provider := range providers {
Dan Willemsen4b7d5de2016-01-12 23:20:28 -0800255 mctx := &makeVarsContext{
Colin Cross65494b92019-02-07 14:25:51 -0800256 SingletonContext: ctx,
257 pctx: provider.pctx,
Dan Willemsen4b7d5de2016-01-12 23:20:28 -0800258 }
259
260 provider.call(mctx)
261
262 vars = append(vars, mctx.vars...)
Colin Crossc3d87d32020-06-04 13:25:17 -0700263 phonies = append(phonies, mctx.phonies...)
Colin Cross3cda0d82019-09-24 13:40:07 -0700264 dists = append(dists, mctx.dists...)
Dan Willemsen4b7d5de2016-01-12 23:20:28 -0800265 }
266
Dan Willemsen6a6478d2020-07-17 19:28:53 -0700267 ctx.VisitAllModules(func(m Module) {
Jiyong Parkf78531b2020-09-09 17:14:28 +0900268 if provider, ok := m.(ModuleMakeVarsProvider); ok && m.Enabled() {
Dan Willemsen6a6478d2020-07-17 19:28:53 -0700269 mctx := &makeVarsContext{
270 SingletonContext: ctx,
271 }
272
273 provider.MakeVars(mctx)
274
275 vars = append(vars, mctx.vars...)
276 phonies = append(phonies, mctx.phonies...)
277 dists = append(dists, mctx.dists...)
278 }
Colin Cross6301c3c2021-09-28 17:40:21 -0700279
280 if m.ExportedToMake() {
281 katiInstalls = append(katiInstalls, m.base().katiInstalls...)
Colin Crossd9bbf4b2023-11-17 16:23:48 -0800282 katiInitRcInstalls = append(katiInitRcInstalls, m.base().katiInitRcInstalls...)
283 katiVintfManifestInstalls = append(katiVintfManifestInstalls, m.base().katiVintfInstalls...)
Colin Cross6301c3c2021-09-28 17:40:21 -0700284 katiSymlinks = append(katiSymlinks, m.base().katiSymlinks...)
285 }
Dan Willemsen6a6478d2020-07-17 19:28:53 -0700286 })
287
Colin Crossd9bbf4b2023-11-17 16:23:48 -0800288 compareKatiInstalls := func(a, b katiInstall) int {
289 aTo, bTo := a.to.String(), b.to.String()
290 if cmpTo := cmp.Compare(aTo, bTo); cmpTo != 0 {
291 return cmpTo
292 }
293
294 aFrom, bFrom := a.from.String(), b.from.String()
295 return cmp.Compare(aFrom, bFrom)
296 }
297
298 slices.SortFunc(katiInitRcInstalls, compareKatiInstalls)
299 katiInitRcInstalls = slices.CompactFunc(katiInitRcInstalls, func(a, b katiInstall) bool {
300 return compareKatiInstalls(a, b) == 0
301 })
302 katiInstalls = append(katiInstalls, katiInitRcInstalls...)
303
304 slices.SortFunc(katiVintfManifestInstalls, compareKatiInstalls)
305 katiVintfManifestInstalls = slices.CompactFunc(katiVintfManifestInstalls, func(a, b katiInstall) bool {
306 return compareKatiInstalls(a, b) == 0
307 })
308
Dan Willemsen4b7d5de2016-01-12 23:20:28 -0800309 if ctx.Failed() {
310 return
311 }
312
Dan Willemsen6a6478d2020-07-17 19:28:53 -0700313 sort.Slice(vars, func(i, j int) bool {
314 return vars[i].name < vars[j].name
315 })
316 sort.Slice(phonies, func(i, j int) bool {
317 return phonies[i].name < phonies[j].name
318 })
319 lessArr := func(a, b []string) bool {
320 if len(a) == len(b) {
321 for i := range a {
322 if a[i] < b[i] {
323 return true
324 }
325 }
326 return false
327 }
328 return len(a) < len(b)
329 }
330 sort.Slice(dists, func(i, j int) bool {
331 return lessArr(dists[i].goals, dists[j].goals) || lessArr(dists[i].paths, dists[j].paths)
332 })
333
Dan Willemsen4b7d5de2016-01-12 23:20:28 -0800334 outBytes := s.writeVars(vars)
335
Colin Crossc3d87d32020-06-04 13:25:17 -0700336 if err := pathtools.WriteFileIfChanged(outFile, outBytes, 0666); err != nil {
Dan Willemsen4b7d5de2016-01-12 23:20:28 -0800337 ctx.Errorf(err.Error())
338 }
Colin Crossc3d87d32020-06-04 13:25:17 -0700339
Colin Cross3cda0d82019-09-24 13:40:07 -0700340 lateOutBytes := s.writeLate(phonies, dists)
Colin Crossc3d87d32020-06-04 13:25:17 -0700341
342 if err := pathtools.WriteFileIfChanged(lateOutFile, lateOutBytes, 0666); err != nil {
343 ctx.Errorf(err.Error())
344 }
345
Colin Crossd9bbf4b2023-11-17 16:23:48 -0800346 installsBytes := s.writeInstalls(katiInstalls, katiSymlinks, katiVintfManifestInstalls)
Colin Cross6301c3c2021-09-28 17:40:21 -0700347 if err := pathtools.WriteFileIfChanged(installsFile, installsBytes, 0666); err != nil {
348 ctx.Errorf(err.Error())
349 }
Colin Cross6ac95762021-11-09 13:17:44 -0800350
Paul Duffin8eb45732022-10-04 19:03:31 +0100351 // Only save state for tests when testing.
352 if ctx.Config().RunningInsideUnitTest() {
353 s.varsForTesting = vars
354 s.installsForTesting = installsBytes
355 }
Dan Willemsen4b7d5de2016-01-12 23:20:28 -0800356}
357
358func (s *makeVarsSingleton) writeVars(vars []makeVarsVariable) []byte {
359 buf := &bytes.Buffer{}
360
Dan Willemsen59339a22018-07-22 21:18:45 -0700361 fmt.Fprint(buf, `# Autogenerated file
Dan Willemsen4b7d5de2016-01-12 23:20:28 -0800362
363# Compares SOONG_$(1) against $(1), and warns if they are not equal.
364#
365# If the original variable is empty, then just set it to the SOONG_ version.
366#
367# $(1): Name of the variable to check
368# $(2): If not-empty, sort the values before comparing
369# $(3): Extra snippet to run if it does not match
370define soong-compare-var
371ifneq ($$($(1)),)
Dan Willemsen558e5172016-05-19 16:58:46 -0700372 my_val_make := $$(strip $(if $(2),$$(sort $$($(1))),$$($(1))))
Dan Willemsen4b7d5de2016-01-12 23:20:28 -0800373 my_val_soong := $(if $(2),$$(sort $$(SOONG_$(1))),$$(SOONG_$(1)))
374 ifneq ($$(my_val_make),$$(my_val_soong))
375 $$(warning $(1) does not match between Make and Soong:)
376 $(if $(2),$$(warning Make adds: $$(filter-out $$(my_val_soong),$$(my_val_make))),$$(warning Make : $$(my_val_make)))
377 $(if $(2),$$(warning Soong adds: $$(filter-out $$(my_val_make),$$(my_val_soong))),$$(warning Soong: $$(my_val_soong)))
378 $(3)
379 endif
380 my_val_make :=
381 my_val_soong :=
382else
383 $(1) := $$(SOONG_$(1))
384endif
Dan Willemsende18f472016-09-30 10:16:38 -0700385.KATI_READONLY := $(1) SOONG_$(1)
Dan Willemsen4b7d5de2016-01-12 23:20:28 -0800386endef
387
388my_check_failed := false
389
390`)
391
392 // Write all the strict checks out first so that if one of them errors,
393 // we get all of the strict errors printed, but not the non-strict
394 // warnings.
395 for _, v := range vars {
396 if !v.strict {
397 continue
398 }
399
400 sort := ""
401 if v.sort {
402 sort = "true"
403 }
404
405 fmt.Fprintf(buf, "SOONG_%s := %s\n", v.name, v.value)
406 fmt.Fprintf(buf, "$(eval $(call soong-compare-var,%s,%s,my_check_failed := true))\n\n", v.name, sort)
407 }
408
Dan Willemsen59339a22018-07-22 21:18:45 -0700409 fmt.Fprint(buf, `
Dan Willemsen4b7d5de2016-01-12 23:20:28 -0800410ifneq ($(my_check_failed),false)
411 $(error Soong variable check failed)
412endif
413my_check_failed :=
414
415
416`)
417
418 for _, v := range vars {
419 if v.strict {
420 continue
421 }
422
423 sort := ""
424 if v.sort {
425 sort = "true"
426 }
427
428 fmt.Fprintf(buf, "SOONG_%s := %s\n", v.name, v.value)
429 fmt.Fprintf(buf, "$(eval $(call soong-compare-var,%s,%s))\n\n", v.name, sort)
430 }
431
432 fmt.Fprintln(buf, "\nsoong-compare-var :=")
433
Colin Crossc3d87d32020-06-04 13:25:17 -0700434 fmt.Fprintln(buf)
435
436 return buf.Bytes()
437}
438
Colin Cross3cda0d82019-09-24 13:40:07 -0700439func (s *makeVarsSingleton) writeLate(phonies []phony, dists []dist) []byte {
Colin Crossc3d87d32020-06-04 13:25:17 -0700440 buf := &bytes.Buffer{}
441
442 fmt.Fprint(buf, `# Autogenerated file
443
444# Values written by Soong read after parsing all Android.mk files.
445
446
447`)
448
449 for _, phony := range phonies {
450 fmt.Fprintf(buf, ".PHONY: %s\n", phony.name)
451 fmt.Fprintf(buf, "%s: %s\n", phony.name, strings.Join(phony.deps, "\\\n "))
452 }
453
Colin Cross3cda0d82019-09-24 13:40:07 -0700454 fmt.Fprintln(buf)
455
456 for _, dist := range dists {
Colin Crossb5399c82021-11-11 16:33:24 -0800457 fmt.Fprintf(buf, ".PHONY: %s\n", strings.Join(dist.goals, " "))
Colin Cross3cda0d82019-09-24 13:40:07 -0700458 fmt.Fprintf(buf, "$(call dist-for-goals,%s,%s)\n",
459 strings.Join(dist.goals, " "), strings.Join(dist.paths, " "))
460 }
461
Dan Willemsen4b7d5de2016-01-12 23:20:28 -0800462 return buf.Bytes()
463}
464
Colin Cross6301c3c2021-09-28 17:40:21 -0700465// writeInstalls writes the list of install rules generated by Soong to a makefile. The rules
466// are exported to Make instead of written directly to the ninja file so that main.mk can add
467// the dependencies from the `required` property that are hard to resolve in Soong.
Colin Crossd9bbf4b2023-11-17 16:23:48 -0800468func (s *makeVarsSingleton) writeInstalls(installs, symlinks, katiVintfManifestInstalls []katiInstall) []byte {
Colin Cross6301c3c2021-09-28 17:40:21 -0700469 buf := &bytes.Buffer{}
470
471 fmt.Fprint(buf, `# Autogenerated file
472
473# Values written by Soong to generate install rules that can be amended by Kati.
474
475
476`)
477
478 preserveSymlinksFlag := "-d"
479 if runtime.GOOS == "darwin" {
480 preserveSymlinksFlag = "-R"
481 }
482
483 for _, install := range installs {
484 // Write a rule for each install request in the form:
485 // to: from [ deps ] [ | order only deps ]
486 // cp -f -d $< $@ [ && chmod +x $@ ]
487 fmt.Fprintf(buf, "%s: %s", install.to.String(), install.from.String())
488 for _, dep := range install.implicitDeps {
489 fmt.Fprintf(buf, " %s", dep.String())
490 }
Colin Cross50ed1f92021-11-12 17:41:02 -0800491 if extraFiles := install.extraFiles; extraFiles != nil {
492 fmt.Fprintf(buf, " %s", extraFiles.zip.String())
493 }
Colin Cross6301c3c2021-09-28 17:40:21 -0700494 if len(install.orderOnlyDeps) > 0 {
495 fmt.Fprintf(buf, " |")
496 }
497 for _, dep := range install.orderOnlyDeps {
498 fmt.Fprintf(buf, " %s", dep.String())
499 }
500 fmt.Fprintln(buf)
Alessandro Astone2b17a232022-10-25 11:44:59 +0200501 fmt.Fprintln(buf, "\t@echo \"Install: $@\"")
Colin Cross50ed1f92021-11-12 17:41:02 -0800502 fmt.Fprintf(buf, "\trm -f $@ && cp -f %s $< $@\n", preserveSymlinksFlag)
Colin Cross6301c3c2021-09-28 17:40:21 -0700503 if install.executable {
Colin Cross50ed1f92021-11-12 17:41:02 -0800504 fmt.Fprintf(buf, "\tchmod +x $@\n")
Colin Cross6301c3c2021-09-28 17:40:21 -0700505 }
Colin Cross50ed1f92021-11-12 17:41:02 -0800506 if extraFiles := install.extraFiles; extraFiles != nil {
Romain Jobredeaux1cef6292022-05-19 11:11:51 -0400507 fmt.Fprintf(buf, "\t( unzip -qDD -d '%s' '%s' 2>&1 | grep -v \"zipfile is empty\"; exit $${PIPESTATUS[0]} ) || \\\n", extraFiles.dir.String(), extraFiles.zip.String())
508 fmt.Fprintf(buf, "\t ( code=$$?; if [ $$code -ne 0 -a $$code -ne 1 ]; then exit $$code; fi )\n")
Colin Cross50ed1f92021-11-12 17:41:02 -0800509 }
Colin Cross6301c3c2021-09-28 17:40:21 -0700510 fmt.Fprintln(buf)
511 }
512
513 for _, symlink := range symlinks {
514 fmt.Fprintf(buf, "%s:", symlink.to.String())
Colin Cross64002af2021-11-09 16:37:52 -0800515 if symlink.from != nil {
Colin Crossd9bbf4b2023-11-17 16:23:48 -0800516 // The katiVintfManifestInstall doesn't need updating when the target is modified, but we sometimes
517 // have a dependency on a katiVintfManifestInstall to a binary instead of to the binary directly, and
518 // the mtime of the katiVintfManifestInstall must be updated when the binary is modified, so use a
Colin Cross64002af2021-11-09 16:37:52 -0800519 // normal dependency here instead of an order-only dependency.
520 fmt.Fprintf(buf, " %s", symlink.from.String())
521 }
Colin Cross6301c3c2021-09-28 17:40:21 -0700522 for _, dep := range symlink.implicitDeps {
523 fmt.Fprintf(buf, " %s", dep.String())
524 }
Colin Cross64002af2021-11-09 16:37:52 -0800525 if len(symlink.orderOnlyDeps) > 0 {
Colin Cross6301c3c2021-09-28 17:40:21 -0700526 fmt.Fprintf(buf, " |")
527 }
Colin Cross6301c3c2021-09-28 17:40:21 -0700528 for _, dep := range symlink.orderOnlyDeps {
529 fmt.Fprintf(buf, " %s", dep.String())
530 }
531 fmt.Fprintln(buf)
532
533 fromStr := ""
534 if symlink.from != nil {
535 rel, err := filepath.Rel(filepath.Dir(symlink.to.String()), symlink.from.String())
536 if err != nil {
Colin Crossd9bbf4b2023-11-17 16:23:48 -0800537 panic(fmt.Errorf("failed to find relative path for katiVintfManifestInstall from %q to %q: %w",
Colin Cross6301c3c2021-09-28 17:40:21 -0700538 symlink.from.String(), symlink.to.String(), err))
539 }
540 fromStr = rel
541 } else {
542 fromStr = symlink.absFrom
543 }
544
Alessandro Astone2b17a232022-10-25 11:44:59 +0200545 fmt.Fprintln(buf, "\t@echo \"Symlink: $@\"")
Colin Cross6301c3c2021-09-28 17:40:21 -0700546 fmt.Fprintf(buf, "\trm -f $@ && ln -sfn %s $@", fromStr)
547 fmt.Fprintln(buf)
548 fmt.Fprintln(buf)
549 }
550
Colin Crossd9bbf4b2023-11-17 16:23:48 -0800551 for _, install := range katiVintfManifestInstalls {
552 // Write a rule for each vintf install request that calls the copy-vintf-manifest-chedk make function.
553 fmt.Fprintf(buf, "$(eval $(call copy-vintf-manifest-checked, %s, %s))\n", install.from.String(), install.to.String())
554
555 if len(install.implicitDeps) > 0 {
556 panic(fmt.Errorf("unsupported implicitDeps %q in vintf install rule %q", install.implicitDeps, install.to))
557 }
558 if len(install.orderOnlyDeps) > 0 {
559 panic(fmt.Errorf("unsupported orderOnlyDeps %q in vintf install rule %q", install.orderOnlyDeps, install.to))
560 }
561
562 fmt.Fprintln(buf)
563 }
Colin Cross6301c3c2021-09-28 17:40:21 -0700564 return buf.Bytes()
565}
566
Dan Willemsen3fb1fae2018-03-12 15:30:26 -0700567func (c *makeVarsContext) DeviceConfig() DeviceConfig {
Colin Cross65494b92019-02-07 14:25:51 -0800568 return DeviceConfig{c.Config().deviceConfig}
Jiyong Park374510b2018-03-19 18:23:01 +0900569}
570
Colin Cross31656952018-05-24 16:11:20 -0700571var ninjaDescaper = strings.NewReplacer("$$", "$")
572
Dan Willemsen558e5172016-05-19 16:58:46 -0700573func (c *makeVarsContext) Eval(ninjaStr string) (string, error) {
Colin Cross65494b92019-02-07 14:25:51 -0800574 s, err := c.SingletonContext.Eval(c.pctx, ninjaStr)
Colin Cross31656952018-05-24 16:11:20 -0700575 if err != nil {
576 return "", err
577 }
578 // SingletonContext.Eval returns an exapnded string that is valid for a ninja file, de-escape $$ to $ for use
579 // in a Makefile
580 return ninjaDescaper.Replace(s), nil
Dan Willemsen558e5172016-05-19 16:58:46 -0700581}
582
583func (c *makeVarsContext) addVariableRaw(name, value string, strict, sort bool) {
Dan Willemsen4b7d5de2016-01-12 23:20:28 -0800584 c.vars = append(c.vars, makeVarsVariable{
585 name: name,
586 value: value,
587 strict: strict,
588 sort: sort,
589 })
590}
591
Dan Willemsen558e5172016-05-19 16:58:46 -0700592func (c *makeVarsContext) addVariable(name, ninjaStr string, strict, sort bool) {
593 value, err := c.Eval(ninjaStr)
594 if err != nil {
Colin Cross65494b92019-02-07 14:25:51 -0800595 c.SingletonContext.Errorf(err.Error())
Dan Willemsen558e5172016-05-19 16:58:46 -0700596 }
597 c.addVariableRaw(name, value, strict, sort)
598}
599
Colin Crossc3d87d32020-06-04 13:25:17 -0700600func (c *makeVarsContext) addPhony(name string, deps []string) {
601 c.phonies = append(c.phonies, phony{name, deps})
602}
603
Colin Cross3cda0d82019-09-24 13:40:07 -0700604func (c *makeVarsContext) addDist(goals []string, paths []string) {
605 c.dists = append(c.dists, dist{
606 goals: goals,
607 paths: paths,
608 })
609}
610
Dan Willemsen4b7d5de2016-01-12 23:20:28 -0800611func (c *makeVarsContext) Strict(name, ninjaStr string) {
612 c.addVariable(name, ninjaStr, true, false)
613}
614func (c *makeVarsContext) StrictSorted(name, ninjaStr string) {
615 c.addVariable(name, ninjaStr, true, true)
616}
Dan Willemsen558e5172016-05-19 16:58:46 -0700617func (c *makeVarsContext) StrictRaw(name, value string) {
618 c.addVariableRaw(name, value, true, false)
619}
Dan Willemsen4b7d5de2016-01-12 23:20:28 -0800620
621func (c *makeVarsContext) Check(name, ninjaStr string) {
622 c.addVariable(name, ninjaStr, false, false)
623}
624func (c *makeVarsContext) CheckSorted(name, ninjaStr string) {
625 c.addVariable(name, ninjaStr, false, true)
626}
Dan Willemsen558e5172016-05-19 16:58:46 -0700627func (c *makeVarsContext) CheckRaw(name, value string) {
628 c.addVariableRaw(name, value, false, false)
629}
Colin Crossc3d87d32020-06-04 13:25:17 -0700630
631func (c *makeVarsContext) Phony(name string, deps ...Path) {
632 c.addPhony(name, Paths(deps).Strings())
633}
Colin Cross3cda0d82019-09-24 13:40:07 -0700634
635func (c *makeVarsContext) DistForGoal(goal string, paths ...Path) {
636 c.DistForGoals([]string{goal}, paths...)
637}
638
639func (c *makeVarsContext) DistForGoalWithFilename(goal string, path Path, filename string) {
640 c.DistForGoalsWithFilename([]string{goal}, path, filename)
641}
642
643func (c *makeVarsContext) DistForGoals(goals []string, paths ...Path) {
644 c.addDist(goals, Paths(paths).Strings())
645}
646
647func (c *makeVarsContext) DistForGoalsWithFilename(goals []string, path Path, filename string) {
648 c.addDist(goals, []string{path.String() + ":" + filename})
649}