blob: b3cf804d0166689a605ed780d7d6f68c8ec9f55d [file] [log] [blame]
Colin Cross3f40fa42015-01-30 17:27:36 -08001// 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
Colin Cross3f40fa42015-01-30 17:27:36 -080016
17import (
Liz Kammer356f7d42021-01-26 09:18:53 -050018 "android/soong/bazel"
Colin Cross6e18ca42015-07-14 18:55:36 -070019 "fmt"
Colin Cross988414c2020-01-11 01:11:46 +000020 "io/ioutil"
21 "os"
Colin Cross6a745c62015-06-16 16:38:10 -070022 "path/filepath"
Dan Willemsen34cc69e2015-09-23 15:26:20 -070023 "reflect"
Colin Cross5e6cfbe2017-11-03 15:20:35 -070024 "sort"
Dan Willemsen34cc69e2015-09-23 15:26:20 -070025 "strings"
26
27 "github.com/google/blueprint"
28 "github.com/google/blueprint/pathtools"
Colin Cross3f40fa42015-01-30 17:27:36 -080029)
30
Colin Cross988414c2020-01-11 01:11:46 +000031var absSrcDir string
32
Dan Willemsen34cc69e2015-09-23 15:26:20 -070033// PathContext is the subset of a (Module|Singleton)Context required by the
34// Path methods.
35type PathContext interface {
Colin Crossaabf6792017-11-29 00:27:14 -080036 Config() Config
Dan Willemsen7b310ee2015-12-18 15:11:17 -080037 AddNinjaFileDeps(deps ...string)
Colin Cross3f40fa42015-01-30 17:27:36 -080038}
39
Colin Cross7f19f372016-11-01 11:10:25 -070040type PathGlobContext interface {
41 GlobWithDeps(globPattern string, excludes []string) ([]string, error)
42}
43
Colin Crossaabf6792017-11-29 00:27:14 -080044var _ PathContext = SingletonContext(nil)
45var _ PathContext = ModuleContext(nil)
Dan Willemsen34cc69e2015-09-23 15:26:20 -070046
Ulya Trafimovich8640ab92020-05-11 18:06:15 +010047// "Null" path context is a minimal path context for a given config.
48type NullPathContext struct {
49 config Config
50}
51
52func (NullPathContext) AddNinjaFileDeps(...string) {}
53func (ctx NullPathContext) Config() Config { return ctx.config }
54
Liz Kammera830f3a2020-11-10 10:50:34 -080055// EarlyModulePathContext is a subset of EarlyModuleContext methods required by the
56// Path methods. These path methods can be called before any mutators have run.
57type EarlyModulePathContext interface {
58 PathContext
59 PathGlobContext
60
61 ModuleDir() string
62 ModuleErrorf(fmt string, args ...interface{})
63}
64
65var _ EarlyModulePathContext = ModuleContext(nil)
66
67// Glob globs files and directories matching globPattern relative to ModuleDir(),
68// paths in the excludes parameter will be omitted.
69func Glob(ctx EarlyModulePathContext, globPattern string, excludes []string) Paths {
70 ret, err := ctx.GlobWithDeps(globPattern, excludes)
71 if err != nil {
72 ctx.ModuleErrorf("glob: %s", err.Error())
73 }
74 return pathsForModuleSrcFromFullPath(ctx, ret, true)
75}
76
77// GlobFiles globs *only* files (not directories) matching globPattern relative to ModuleDir().
78// Paths in the excludes parameter will be omitted.
79func GlobFiles(ctx EarlyModulePathContext, globPattern string, excludes []string) Paths {
80 ret, err := ctx.GlobWithDeps(globPattern, excludes)
81 if err != nil {
82 ctx.ModuleErrorf("glob: %s", err.Error())
83 }
84 return pathsForModuleSrcFromFullPath(ctx, ret, false)
85}
86
87// ModuleWithDepsPathContext is a subset of *ModuleContext methods required by
88// the Path methods that rely on module dependencies having been resolved.
89type ModuleWithDepsPathContext interface {
90 EarlyModulePathContext
91 GetDirectDepWithTag(name string, tag blueprint.DependencyTag) blueprint.Module
92}
93
94// ModuleMissingDepsPathContext is a subset of *ModuleContext methods required by
95// the Path methods that rely on module dependencies having been resolved and ability to report
96// missing dependency errors.
97type ModuleMissingDepsPathContext interface {
98 ModuleWithDepsPathContext
99 AddMissingDependencies(missingDeps []string)
100}
101
Dan Willemsen00269f22017-07-06 16:59:48 -0700102type ModuleInstallPathContext interface {
Colin Cross0ea8ba82019-06-06 14:33:29 -0700103 BaseModuleContext
Dan Willemsen00269f22017-07-06 16:59:48 -0700104
105 InstallInData() bool
Jaewoong Jung0949f312019-09-11 10:25:18 -0700106 InstallInTestcases() bool
Dan Willemsen00269f22017-07-06 16:59:48 -0700107 InstallInSanitizerDir() bool
Yifan Hong1b3348d2020-01-21 15:53:22 -0800108 InstallInRamdisk() bool
Yifan Hong60e0cfb2020-10-21 15:17:56 -0700109 InstallInVendorRamdisk() bool
Jiyong Parkf9332f12018-02-01 00:54:12 +0900110 InstallInRecovery() bool
Colin Cross90ba5f42019-10-02 11:10:58 -0700111 InstallInRoot() bool
Colin Cross607d8582019-07-29 16:44:46 -0700112 InstallBypassMake() bool
Jiyong Park87788b52020-09-01 12:37:45 +0900113 InstallForceOS() (*OsType, *ArchType)
Dan Willemsen00269f22017-07-06 16:59:48 -0700114}
115
116var _ ModuleInstallPathContext = ModuleContext(nil)
117
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700118// errorfContext is the interface containing the Errorf method matching the
119// Errorf method in blueprint.SingletonContext.
120type errorfContext interface {
121 Errorf(format string, args ...interface{})
Colin Cross3f40fa42015-01-30 17:27:36 -0800122}
123
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700124var _ errorfContext = blueprint.SingletonContext(nil)
125
126// moduleErrorf is the interface containing the ModuleErrorf method matching
127// the ModuleErrorf method in blueprint.ModuleContext.
128type moduleErrorf interface {
129 ModuleErrorf(format string, args ...interface{})
Colin Cross3f40fa42015-01-30 17:27:36 -0800130}
131
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700132var _ moduleErrorf = blueprint.ModuleContext(nil)
133
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700134// reportPathError will register an error with the attached context. It
135// attempts ctx.ModuleErrorf for a better error message first, then falls
136// back to ctx.Errorf.
Colin Cross1ccfcc32018-02-22 13:54:26 -0800137func reportPathError(ctx PathContext, err error) {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +0100138 ReportPathErrorf(ctx, "%s", err.Error())
Colin Cross1ccfcc32018-02-22 13:54:26 -0800139}
140
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +0100141// ReportPathErrorf will register an error with the attached context. It
Colin Cross1ccfcc32018-02-22 13:54:26 -0800142// attempts ctx.ModuleErrorf for a better error message first, then falls
143// back to ctx.Errorf.
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +0100144func ReportPathErrorf(ctx PathContext, format string, args ...interface{}) {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700145 if mctx, ok := ctx.(moduleErrorf); ok {
146 mctx.ModuleErrorf(format, args...)
147 } else if ectx, ok := ctx.(errorfContext); ok {
148 ectx.Errorf(format, args...)
149 } else {
150 panic(fmt.Sprintf(format, args...))
Colin Crossf2298272015-05-12 11:36:53 -0700151 }
152}
153
Colin Cross5e708052019-08-06 13:59:50 -0700154func pathContextName(ctx PathContext, module blueprint.Module) string {
155 if x, ok := ctx.(interface{ ModuleName(blueprint.Module) string }); ok {
156 return x.ModuleName(module)
157 } else if x, ok := ctx.(interface{ OtherModuleName(blueprint.Module) string }); ok {
158 return x.OtherModuleName(module)
159 }
160 return "unknown"
161}
162
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700163type Path interface {
164 // Returns the path in string form
165 String() string
166
Colin Cross4f6fc9c2016-10-26 10:05:25 -0700167 // Ext returns the extension of the last element of the path
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700168 Ext() string
Colin Cross4f6fc9c2016-10-26 10:05:25 -0700169
170 // Base returns the last element of the path
171 Base() string
Colin Crossfaeb7aa2017-02-01 14:12:44 -0800172
173 // Rel returns the portion of the path relative to the directory it was created from. For
174 // example, Rel on a PathsForModuleSrc would return the path relative to the module source
Colin Cross0db55682017-12-05 15:36:55 -0800175 // directory, and OutputPath.Join("foo").Rel() would return "foo".
Colin Crossfaeb7aa2017-02-01 14:12:44 -0800176 Rel() string
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700177}
178
179// WritablePath is a type of path that can be used as an output for build rules.
180type WritablePath interface {
181 Path
182
Paul Duffin9b478b02019-12-10 13:41:51 +0000183 // return the path to the build directory.
Paul Duffind65c58b2021-03-24 09:22:07 +0000184 getBuildDir() string
Paul Duffin9b478b02019-12-10 13:41:51 +0000185
Jeff Gaston734e3802017-04-10 15:47:24 -0700186 // the writablePath method doesn't directly do anything,
187 // but it allows a struct to distinguish between whether or not it implements the WritablePath interface
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700188 writablePath()
Hans MÃ¥nssond3f2bd72020-11-27 12:37:28 +0100189
190 ReplaceExtension(ctx PathContext, ext string) OutputPath
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700191}
192
193type genPathProvider interface {
Liz Kammera830f3a2020-11-10 10:50:34 -0800194 genPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleGenPath
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700195}
196type objPathProvider interface {
Liz Kammera830f3a2020-11-10 10:50:34 -0800197 objPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleObjPath
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700198}
199type resPathProvider interface {
Liz Kammera830f3a2020-11-10 10:50:34 -0800200 resPathWithName(ctx ModuleOutPathContext, name string) ModuleResPath
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700201}
202
203// GenPathWithExt derives a new file path in ctx's generated sources directory
204// from the current path, but with the new extension.
Liz Kammera830f3a2020-11-10 10:50:34 -0800205func GenPathWithExt(ctx ModuleOutPathContext, subdir string, p Path, ext string) ModuleGenPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700206 if path, ok := p.(genPathProvider); ok {
Dan Willemsen21ec4902016-11-02 20:43:13 -0700207 return path.genPathWithExt(ctx, subdir, ext)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700208 }
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +0100209 ReportPathErrorf(ctx, "Tried to create generated file from unsupported path: %s(%s)", reflect.TypeOf(p).Name(), p)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700210 return PathForModuleGen(ctx)
211}
212
213// ObjPathWithExt derives a new file path in ctx's object directory from the
214// current path, but with the new extension.
Liz Kammera830f3a2020-11-10 10:50:34 -0800215func ObjPathWithExt(ctx ModuleOutPathContext, subdir string, p Path, ext string) ModuleObjPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700216 if path, ok := p.(objPathProvider); ok {
217 return path.objPathWithExt(ctx, subdir, ext)
218 }
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +0100219 ReportPathErrorf(ctx, "Tried to create object file from unsupported path: %s (%s)", reflect.TypeOf(p).Name(), p)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700220 return PathForModuleObj(ctx)
221}
222
223// ResPathWithName derives a new path in ctx's output resource directory, using
224// the current path to create the directory name, and the `name` argument for
225// the filename.
Liz Kammera830f3a2020-11-10 10:50:34 -0800226func ResPathWithName(ctx ModuleOutPathContext, p Path, name string) ModuleResPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700227 if path, ok := p.(resPathProvider); ok {
228 return path.resPathWithName(ctx, name)
229 }
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +0100230 ReportPathErrorf(ctx, "Tried to create res file from unsupported path: %s (%s)", reflect.TypeOf(p).Name(), p)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700231 return PathForModuleRes(ctx)
232}
233
234// OptionalPath is a container that may or may not contain a valid Path.
235type OptionalPath struct {
236 valid bool
237 path Path
238}
239
240// OptionalPathForPath returns an OptionalPath containing the path.
241func OptionalPathForPath(path Path) OptionalPath {
242 if path == nil {
243 return OptionalPath{}
244 }
245 return OptionalPath{valid: true, path: path}
246}
247
248// Valid returns whether there is a valid path
249func (p OptionalPath) Valid() bool {
250 return p.valid
251}
252
253// Path returns the Path embedded in this OptionalPath. You must be sure that
254// there is a valid path, since this method will panic if there is not.
255func (p OptionalPath) Path() Path {
256 if !p.valid {
257 panic("Requesting an invalid path")
258 }
259 return p.path
260}
261
262// String returns the string version of the Path, or "" if it isn't valid.
263func (p OptionalPath) String() string {
264 if p.valid {
265 return p.path.String()
266 } else {
267 return ""
Colin Crossf2298272015-05-12 11:36:53 -0700268 }
269}
Colin Cross6e18ca42015-07-14 18:55:36 -0700270
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700271// Paths is a slice of Path objects, with helpers to operate on the collection.
272type Paths []Path
273
Jingwen Chen40fd90a2020-06-15 05:24:19 +0000274func (paths Paths) containsPath(path Path) bool {
275 for _, p := range paths {
276 if p == path {
277 return true
278 }
279 }
280 return false
281}
282
Liz Kammer7aa52882021-02-11 09:16:14 -0500283// PathsForSource returns Paths rooted from SrcDir, *not* rooted from the module's local source
284// directory
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700285func PathsForSource(ctx PathContext, paths []string) Paths {
286 ret := make(Paths, len(paths))
287 for i, path := range paths {
288 ret[i] = PathForSource(ctx, path)
289 }
290 return ret
291}
292
Liz Kammer7aa52882021-02-11 09:16:14 -0500293// ExistentPathsForSources returns a list of Paths rooted from SrcDir, *not* rooted from the
294// module's local source directory, that are found in the tree. If any are not found, they are
295// omitted from the list, and dependencies are added so that we're re-run when they are added.
Colin Cross32f38982018-02-22 11:47:25 -0800296func ExistentPathsForSources(ctx PathContext, paths []string) Paths {
Dan Willemsen7b310ee2015-12-18 15:11:17 -0800297 ret := make(Paths, 0, len(paths))
298 for _, path := range paths {
Colin Cross32f38982018-02-22 11:47:25 -0800299 p := ExistentPathForSource(ctx, path)
Dan Willemsen7b310ee2015-12-18 15:11:17 -0800300 if p.Valid() {
301 ret = append(ret, p.Path())
302 }
303 }
304 return ret
305}
306
Colin Cross41955e82019-05-29 14:40:35 -0700307// PathsForModuleSrc returns Paths rooted from the module's local source directory. It expands globs, references to
308// SourceFileProducer modules using the ":name" syntax, and references to OutputFileProducer modules using the
309// ":name{.tag}" syntax. Properties passed as the paths argument must have been annotated with struct tag
310// `android:"path"` so that dependencies on SourceFileProducer modules will have already been handled by the
311// path_properties mutator. If ctx.Config().AllowMissingDependencies() is true then any missing SourceFileProducer or
312// OutputFileProducer dependencies will cause the module to be marked as having missing dependencies.
Liz Kammera830f3a2020-11-10 10:50:34 -0800313func PathsForModuleSrc(ctx ModuleMissingDepsPathContext, paths []string) Paths {
Colin Cross8a497952019-03-05 22:25:09 -0800314 return PathsForModuleSrcExcludes(ctx, paths, nil)
315}
316
Colin Crossba71a3f2019-03-18 12:12:48 -0700317// PathsForModuleSrcExcludes returns Paths rooted from the module's local source directory, excluding paths listed in
Colin Cross41955e82019-05-29 14:40:35 -0700318// the excludes arguments. It expands globs, references to SourceFileProducer modules using the ":name" syntax, and
319// references to OutputFileProducer modules using the ":name{.tag}" syntax. Properties passed as the paths or excludes
320// argument must have been annotated with struct tag `android:"path"` so that dependencies on SourceFileProducer modules
321// will have already been handled by the path_properties mutator. If ctx.Config().AllowMissingDependencies() is
Paul Duffin036cace2019-07-25 14:44:56 +0100322// true then any missing SourceFileProducer or OutputFileProducer dependencies will cause the module to be marked as
Colin Cross41955e82019-05-29 14:40:35 -0700323// having missing dependencies.
Liz Kammera830f3a2020-11-10 10:50:34 -0800324func PathsForModuleSrcExcludes(ctx ModuleMissingDepsPathContext, paths, excludes []string) Paths {
Colin Crossba71a3f2019-03-18 12:12:48 -0700325 ret, missingDeps := PathsAndMissingDepsForModuleSrcExcludes(ctx, paths, excludes)
326 if ctx.Config().AllowMissingDependencies() {
327 ctx.AddMissingDependencies(missingDeps)
328 } else {
329 for _, m := range missingDeps {
330 ctx.ModuleErrorf(`missing dependency on %q, is the property annotated with android:"path"?`, m)
331 }
332 }
333 return ret
334}
335
Liz Kammer356f7d42021-01-26 09:18:53 -0500336// A subset of the ModuleContext methods which are sufficient to resolve references to paths/deps in
337// order to form a Bazel-compatible label for conversion.
338type BazelConversionPathContext interface {
339 EarlyModulePathContext
340
341 GetDirectDep(name string) (blueprint.Module, blueprint.DependencyTag)
Liz Kammerbdc60992021-02-24 16:55:11 -0500342 Module() Module
Jingwen Chen12b4c272021-03-10 02:05:59 -0500343 ModuleType() string
Liz Kammer356f7d42021-01-26 09:18:53 -0500344 OtherModuleName(m blueprint.Module) string
345 OtherModuleDir(m blueprint.Module) string
346}
347
348// BazelLabelForModuleDeps returns a Bazel-compatible label for the requested modules which
349// correspond to dependencies on the module within the given ctx.
350func BazelLabelForModuleDeps(ctx BazelConversionPathContext, modules []string) bazel.LabelList {
351 var labels bazel.LabelList
352 for _, module := range modules {
353 bpText := module
354 if m := SrcIsModule(module); m == "" {
355 module = ":" + module
356 }
357 if m, t := SrcIsModuleWithTag(module); m != "" {
358 l := getOtherModuleLabel(ctx, m, t)
359 l.Bp_text = bpText
360 labels.Includes = append(labels.Includes, l)
361 } else {
362 ctx.ModuleErrorf("%q, is not a module reference", module)
363 }
364 }
365 return labels
366}
367
368// BazelLabelForModuleSrc returns bazel.LabelList with paths rooted from the module's local source
369// directory. It expands globs, and resolves references to modules using the ":name" syntax to
370// bazel-compatible labels. Properties passed as the paths or excludes argument must have been
371// annotated with struct tag `android:"path"` so that dependencies on other modules will have
372// already been handled by the path_properties mutator.
373func BazelLabelForModuleSrc(ctx BazelConversionPathContext, paths []string) bazel.LabelList {
374 return BazelLabelForModuleSrcExcludes(ctx, paths, []string(nil))
375}
376
377// BazelLabelForModuleSrcExcludes returns bazel.LabelList with paths rooted from the module's local
378// source directory, excluding labels included in the excludes argument. It expands globs, and
379// resolves references to modules using the ":name" syntax to bazel-compatible labels. Properties
380// passed as the paths or excludes argument must have been annotated with struct tag
381// `android:"path"` so that dependencies on other modules will have already been handled by the
382// path_properties mutator.
383func BazelLabelForModuleSrcExcludes(ctx BazelConversionPathContext, paths, excludes []string) bazel.LabelList {
384 excludeLabels := expandSrcsForBazel(ctx, excludes, []string(nil))
385 excluded := make([]string, 0, len(excludeLabels.Includes))
386 for _, e := range excludeLabels.Includes {
387 excluded = append(excluded, e.Label)
388 }
389 labels := expandSrcsForBazel(ctx, paths, excluded)
390 labels.Excludes = excludeLabels.Includes
391 return labels
392}
393
394// expandSrcsForBazel returns bazel.LabelList with paths rooted from the module's local
395// source directory, excluding labels included in the excludes argument. It expands globs, and
396// resolves references to modules using the ":name" syntax to bazel-compatible labels. Properties
397// passed as the paths or excludes argument must have been annotated with struct tag
398// `android:"path"` so that dependencies on other modules will have already been handled by the
399// path_properties mutator.
400func expandSrcsForBazel(ctx BazelConversionPathContext, paths, expandedExcludes []string) bazel.LabelList {
Liz Kammerebfcf672021-02-16 15:00:05 -0500401 if paths == nil {
402 return bazel.LabelList{}
403 }
Liz Kammer356f7d42021-01-26 09:18:53 -0500404 labels := bazel.LabelList{
405 Includes: []bazel.Label{},
406 }
407 for _, p := range paths {
408 if m, tag := SrcIsModuleWithTag(p); m != "" {
409 l := getOtherModuleLabel(ctx, m, tag)
410 if !InList(l.Label, expandedExcludes) {
411 l.Bp_text = fmt.Sprintf(":%s", m)
412 labels.Includes = append(labels.Includes, l)
413 }
414 } else {
415 var expandedPaths []bazel.Label
416 if pathtools.IsGlob(p) {
417 globbedPaths := GlobFiles(ctx, pathForModuleSrc(ctx, p).String(), expandedExcludes)
418 globbedPaths = PathsWithModuleSrcSubDir(ctx, globbedPaths, "")
419 for _, path := range globbedPaths {
420 s := path.Rel()
421 expandedPaths = append(expandedPaths, bazel.Label{Label: s})
422 }
423 } else {
424 if !InList(p, expandedExcludes) {
425 expandedPaths = append(expandedPaths, bazel.Label{Label: p})
426 }
427 }
428 labels.Includes = append(labels.Includes, expandedPaths...)
429 }
430 }
431 return labels
432}
433
434// getOtherModuleLabel returns a bazel.Label for the given dependency/tag combination for the
435// module. The label will be relative to the current directory if appropriate. The dependency must
436// already be resolved by either deps mutator or path deps mutator.
437func getOtherModuleLabel(ctx BazelConversionPathContext, dep, tag string) bazel.Label {
438 m, _ := ctx.GetDirectDep(dep)
Liz Kammerbdc60992021-02-24 16:55:11 -0500439 otherLabel := bazelModuleLabel(ctx, m, tag)
440 label := bazelModuleLabel(ctx, ctx.Module(), "")
441 if samePackage(label, otherLabel) {
442 otherLabel = bazelShortLabel(otherLabel)
Liz Kammer356f7d42021-01-26 09:18:53 -0500443 }
Liz Kammerbdc60992021-02-24 16:55:11 -0500444
445 return bazel.Label{
446 Label: otherLabel,
447 }
448}
449
450func bazelModuleLabel(ctx BazelConversionPathContext, module blueprint.Module, tag string) string {
451 // TODO(b/165114590): Convert tag (":name{.tag}") to corresponding Bazel implicit output targets.
452 b, ok := module.(Bazelable)
453 // TODO(b/181155349): perhaps return an error here if the module can't be/isn't being converted
Jingwen Chen12b4c272021-03-10 02:05:59 -0500454 if !ok || !b.ConvertedToBazel(ctx) {
Liz Kammerbdc60992021-02-24 16:55:11 -0500455 return bp2buildModuleLabel(ctx, module)
456 }
457 return b.GetBazelLabel(ctx, module)
458}
459
460func bazelShortLabel(label string) string {
461 i := strings.Index(label, ":")
462 return label[i:]
463}
464
465func bazelPackage(label string) string {
466 i := strings.Index(label, ":")
467 return label[0:i]
468}
469
470func samePackage(label1, label2 string) bool {
471 return bazelPackage(label1) == bazelPackage(label2)
472}
473
474func bp2buildModuleLabel(ctx BazelConversionPathContext, module blueprint.Module) string {
475 moduleName := ctx.OtherModuleName(module)
476 moduleDir := ctx.OtherModuleDir(module)
477 return fmt.Sprintf("//%s:%s", moduleDir, moduleName)
Liz Kammer356f7d42021-01-26 09:18:53 -0500478}
479
Ulya Trafimovich4d2eeed2019-11-08 10:54:21 +0000480// OutputPaths is a slice of OutputPath objects, with helpers to operate on the collection.
481type OutputPaths []OutputPath
482
483// Paths returns the OutputPaths as a Paths
484func (p OutputPaths) Paths() Paths {
485 if p == nil {
486 return nil
487 }
488 ret := make(Paths, len(p))
489 for i, path := range p {
490 ret[i] = path
491 }
492 return ret
493}
494
495// Strings returns the string forms of the writable paths.
496func (p OutputPaths) Strings() []string {
497 if p == nil {
498 return nil
499 }
500 ret := make([]string, len(p))
501 for i, path := range p {
502 ret[i] = path.String()
503 }
504 return ret
505}
506
Liz Kammera830f3a2020-11-10 10:50:34 -0800507// Expands Paths to a SourceFileProducer or OutputFileProducer module dependency referenced via ":name" or ":name{.tag}" syntax.
508// If the dependency is not found, a missingErrorDependency is returned.
509// If the module dependency is not a SourceFileProducer or OutputFileProducer, appropriate errors will be returned.
510func getPathsFromModuleDep(ctx ModuleWithDepsPathContext, path, moduleName, tag string) (Paths, error) {
511 module := ctx.GetDirectDepWithTag(moduleName, sourceOrOutputDepTag(tag))
512 if module == nil {
513 return nil, missingDependencyError{[]string{moduleName}}
514 }
Colin Crossfa65cee2021-03-22 17:05:59 -0700515 if aModule, ok := module.(Module); ok && !aModule.Enabled() {
516 return nil, missingDependencyError{[]string{moduleName}}
517 }
Liz Kammera830f3a2020-11-10 10:50:34 -0800518 if outProducer, ok := module.(OutputFileProducer); ok {
519 outputFiles, err := outProducer.OutputFiles(tag)
520 if err != nil {
521 return nil, fmt.Errorf("path dependency %q: %s", path, err)
522 }
523 return outputFiles, nil
524 } else if tag != "" {
525 return nil, fmt.Errorf("path dependency %q is not an output file producing module", path)
526 } else if srcProducer, ok := module.(SourceFileProducer); ok {
527 return srcProducer.Srcs(), nil
528 } else {
529 return nil, fmt.Errorf("path dependency %q is not a source file producing module", path)
530 }
531}
532
Colin Crossba71a3f2019-03-18 12:12:48 -0700533// PathsAndMissingDepsForModuleSrcExcludes returns Paths rooted from the module's local source directory, excluding
Colin Cross41955e82019-05-29 14:40:35 -0700534// paths listed in the excludes arguments, and a list of missing dependencies. It expands globs, references to
535// SourceFileProducer modules using the ":name" syntax, and references to OutputFileProducer modules using the
536// ":name{.tag}" syntax. Properties passed as the paths or excludes argument must have been annotated with struct tag
537// `android:"path"` so that dependencies on SourceFileProducer modules will have already been handled by the
538// path_properties mutator. If ctx.Config().AllowMissingDependencies() is true then any missing SourceFileProducer or
539// OutputFileProducer dependencies will be returned, and they will NOT cause the module to be marked as having missing
540// dependencies.
Liz Kammera830f3a2020-11-10 10:50:34 -0800541func PathsAndMissingDepsForModuleSrcExcludes(ctx ModuleWithDepsPathContext, paths, excludes []string) (Paths, []string) {
Colin Cross8a497952019-03-05 22:25:09 -0800542 prefix := pathForModuleSrc(ctx).String()
543
544 var expandedExcludes []string
545 if excludes != nil {
546 expandedExcludes = make([]string, 0, len(excludes))
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700547 }
Colin Cross8a497952019-03-05 22:25:09 -0800548
Colin Crossba71a3f2019-03-18 12:12:48 -0700549 var missingExcludeDeps []string
550
Colin Cross8a497952019-03-05 22:25:09 -0800551 for _, e := range excludes {
Colin Cross41955e82019-05-29 14:40:35 -0700552 if m, t := SrcIsModuleWithTag(e); m != "" {
Liz Kammera830f3a2020-11-10 10:50:34 -0800553 modulePaths, err := getPathsFromModuleDep(ctx, e, m, t)
554 if m, ok := err.(missingDependencyError); ok {
555 missingExcludeDeps = append(missingExcludeDeps, m.missingDeps...)
556 } else if err != nil {
557 reportPathError(ctx, err)
Colin Cross8a497952019-03-05 22:25:09 -0800558 } else {
Liz Kammera830f3a2020-11-10 10:50:34 -0800559 expandedExcludes = append(expandedExcludes, modulePaths.Strings()...)
Colin Cross8a497952019-03-05 22:25:09 -0800560 }
561 } else {
562 expandedExcludes = append(expandedExcludes, filepath.Join(prefix, e))
563 }
564 }
565
566 if paths == nil {
Colin Crossba71a3f2019-03-18 12:12:48 -0700567 return nil, missingExcludeDeps
Colin Cross8a497952019-03-05 22:25:09 -0800568 }
569
Colin Crossba71a3f2019-03-18 12:12:48 -0700570 var missingDeps []string
571
Colin Cross8a497952019-03-05 22:25:09 -0800572 expandedSrcFiles := make(Paths, 0, len(paths))
573 for _, s := range paths {
574 srcFiles, err := expandOneSrcPath(ctx, s, expandedExcludes)
575 if depErr, ok := err.(missingDependencyError); ok {
Colin Crossba71a3f2019-03-18 12:12:48 -0700576 missingDeps = append(missingDeps, depErr.missingDeps...)
Colin Cross8a497952019-03-05 22:25:09 -0800577 } else if err != nil {
578 reportPathError(ctx, err)
579 }
580 expandedSrcFiles = append(expandedSrcFiles, srcFiles...)
581 }
Colin Crossba71a3f2019-03-18 12:12:48 -0700582
583 return expandedSrcFiles, append(missingDeps, missingExcludeDeps...)
Colin Cross8a497952019-03-05 22:25:09 -0800584}
585
586type missingDependencyError struct {
587 missingDeps []string
588}
589
590func (e missingDependencyError) Error() string {
591 return "missing dependencies: " + strings.Join(e.missingDeps, ", ")
592}
593
Liz Kammera830f3a2020-11-10 10:50:34 -0800594// Expands one path string to Paths rooted from the module's local source
595// directory, excluding those listed in the expandedExcludes.
596// Expands globs, references to SourceFileProducer or OutputFileProducer modules using the ":name" and ":name{.tag}" syntax.
597func expandOneSrcPath(ctx ModuleWithDepsPathContext, sPath string, expandedExcludes []string) (Paths, error) {
Jooyung Han7607dd32020-07-05 10:23:14 +0900598 excludePaths := func(paths Paths) Paths {
599 if len(expandedExcludes) == 0 {
600 return paths
601 }
602 remainder := make(Paths, 0, len(paths))
603 for _, p := range paths {
604 if !InList(p.String(), expandedExcludes) {
605 remainder = append(remainder, p)
606 }
607 }
608 return remainder
609 }
Liz Kammera830f3a2020-11-10 10:50:34 -0800610 if m, t := SrcIsModuleWithTag(sPath); m != "" {
611 modulePaths, err := getPathsFromModuleDep(ctx, sPath, m, t)
612 if err != nil {
613 return nil, err
Colin Cross8a497952019-03-05 22:25:09 -0800614 } else {
Liz Kammera830f3a2020-11-10 10:50:34 -0800615 return excludePaths(modulePaths), nil
Colin Cross8a497952019-03-05 22:25:09 -0800616 }
Liz Kammera830f3a2020-11-10 10:50:34 -0800617 } else if pathtools.IsGlob(sPath) {
618 paths := GlobFiles(ctx, pathForModuleSrc(ctx, sPath).String(), expandedExcludes)
Colin Cross8a497952019-03-05 22:25:09 -0800619 return PathsWithModuleSrcSubDir(ctx, paths, ""), nil
620 } else {
Liz Kammera830f3a2020-11-10 10:50:34 -0800621 p := pathForModuleSrc(ctx, sPath)
Colin Cross988414c2020-01-11 01:11:46 +0000622 if exists, _, err := ctx.Config().fs.Exists(p.String()); err != nil {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +0100623 ReportPathErrorf(ctx, "%s: %s", p, err.Error())
Pedro Loureiro5d190cc2021-02-15 15:41:33 +0000624 } else if !exists && !ctx.Config().TestAllowNonExistentPaths {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +0100625 ReportPathErrorf(ctx, "module source path %q does not exist", p)
Colin Cross8a497952019-03-05 22:25:09 -0800626 }
627
Jooyung Han7607dd32020-07-05 10:23:14 +0900628 if InList(p.String(), expandedExcludes) {
Colin Cross8a497952019-03-05 22:25:09 -0800629 return nil, nil
630 }
631 return Paths{p}, nil
632 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700633}
634
635// pathsForModuleSrcFromFullPath returns Paths rooted from the module's local
636// source directory, but strip the local source directory from the beginning of
Dan Willemsen540a78c2018-02-26 21:50:08 -0800637// each string. If incDirs is false, strip paths with a trailing '/' from the list.
Colin Crossfe4bc362018-09-12 10:02:13 -0700638// It intended for use in globs that only list files that exist, so it allows '$' in
639// filenames.
Liz Kammera830f3a2020-11-10 10:50:34 -0800640func pathsForModuleSrcFromFullPath(ctx EarlyModulePathContext, paths []string, incDirs bool) Paths {
Colin Cross6510f912017-11-29 00:27:14 -0800641 prefix := filepath.Join(ctx.Config().srcDir, ctx.ModuleDir()) + "/"
Colin Cross0f37af02017-09-27 17:42:05 -0700642 if prefix == "./" {
643 prefix = ""
644 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700645 ret := make(Paths, 0, len(paths))
646 for _, p := range paths {
Dan Willemsen540a78c2018-02-26 21:50:08 -0800647 if !incDirs && strings.HasSuffix(p, "/") {
648 continue
649 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700650 path := filepath.Clean(p)
651 if !strings.HasPrefix(path, prefix) {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +0100652 ReportPathErrorf(ctx, "Path %q is not in module source directory %q", p, prefix)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700653 continue
654 }
Colin Crosse3924e12018-08-15 20:18:53 -0700655
Colin Crossfe4bc362018-09-12 10:02:13 -0700656 srcPath, err := safePathForSource(ctx, ctx.ModuleDir(), path[len(prefix):])
Colin Crosse3924e12018-08-15 20:18:53 -0700657 if err != nil {
658 reportPathError(ctx, err)
659 continue
660 }
661
Colin Cross07e51612019-03-05 12:46:40 -0800662 srcPath.basePath.rel = srcPath.path
Colin Crosse3924e12018-08-15 20:18:53 -0700663
Colin Cross07e51612019-03-05 12:46:40 -0800664 ret = append(ret, srcPath)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700665 }
666 return ret
667}
668
Liz Kammera830f3a2020-11-10 10:50:34 -0800669// PathsWithOptionalDefaultForModuleSrc returns Paths rooted from the module's local source
670// directory. If input is nil, use the default if it exists. If input is empty, returns nil.
671func PathsWithOptionalDefaultForModuleSrc(ctx ModuleMissingDepsPathContext, input []string, def string) Paths {
Colin Cross0ddae7f2019-02-07 15:30:01 -0800672 if input != nil {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700673 return PathsForModuleSrc(ctx, input)
674 }
675 // Use Glob so that if the default doesn't exist, a dependency is added so that when it
676 // is created, we're run again.
Colin Cross6510f912017-11-29 00:27:14 -0800677 path := filepath.Join(ctx.Config().srcDir, ctx.ModuleDir(), def)
Liz Kammera830f3a2020-11-10 10:50:34 -0800678 return Glob(ctx, path, nil)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700679}
680
681// Strings returns the Paths in string form
682func (p Paths) Strings() []string {
683 if p == nil {
684 return nil
685 }
686 ret := make([]string, len(p))
687 for i, path := range p {
688 ret[i] = path.String()
689 }
690 return ret
691}
692
Colin Crossc0efd1d2020-07-03 11:56:24 -0700693func CopyOfPaths(paths Paths) Paths {
694 return append(Paths(nil), paths...)
695}
696
Colin Crossb6715442017-10-24 11:13:31 -0700697// FirstUniquePaths returns all unique elements of a Paths, keeping the first copy of each. It
698// modifies the Paths slice contents in place, and returns a subslice of the original slice.
Dan Willemsenfe92c962017-08-29 12:28:37 -0700699func FirstUniquePaths(list Paths) Paths {
Colin Cross27027c72020-02-28 15:34:17 -0800700 // 128 was chosen based on BenchmarkFirstUniquePaths results.
701 if len(list) > 128 {
702 return firstUniquePathsMap(list)
703 }
704 return firstUniquePathsList(list)
705}
706
Colin Crossc0efd1d2020-07-03 11:56:24 -0700707// SortedUniquePaths returns all unique elements of a Paths in sorted order. It modifies the
708// Paths slice contents in place, and returns a subslice of the original slice.
Jiyong Park33c77362020-05-29 22:00:16 +0900709func SortedUniquePaths(list Paths) Paths {
710 unique := FirstUniquePaths(list)
711 sort.Slice(unique, func(i, j int) bool {
712 return unique[i].String() < unique[j].String()
713 })
714 return unique
715}
716
Colin Cross27027c72020-02-28 15:34:17 -0800717func firstUniquePathsList(list Paths) Paths {
Dan Willemsenfe92c962017-08-29 12:28:37 -0700718 k := 0
719outer:
720 for i := 0; i < len(list); i++ {
721 for j := 0; j < k; j++ {
722 if list[i] == list[j] {
723 continue outer
724 }
725 }
726 list[k] = list[i]
727 k++
728 }
729 return list[:k]
730}
731
Colin Cross27027c72020-02-28 15:34:17 -0800732func firstUniquePathsMap(list Paths) Paths {
733 k := 0
734 seen := make(map[Path]bool, len(list))
735 for i := 0; i < len(list); i++ {
736 if seen[list[i]] {
737 continue
738 }
739 seen[list[i]] = true
740 list[k] = list[i]
741 k++
742 }
743 return list[:k]
744}
745
Colin Cross5d583952020-11-24 16:21:24 -0800746// FirstUniqueInstallPaths returns all unique elements of an InstallPaths, keeping the first copy of each. It
747// modifies the InstallPaths slice contents in place, and returns a subslice of the original slice.
748func FirstUniqueInstallPaths(list InstallPaths) InstallPaths {
749 // 128 was chosen based on BenchmarkFirstUniquePaths results.
750 if len(list) > 128 {
751 return firstUniqueInstallPathsMap(list)
752 }
753 return firstUniqueInstallPathsList(list)
754}
755
756func firstUniqueInstallPathsList(list InstallPaths) InstallPaths {
757 k := 0
758outer:
759 for i := 0; i < len(list); i++ {
760 for j := 0; j < k; j++ {
761 if list[i] == list[j] {
762 continue outer
763 }
764 }
765 list[k] = list[i]
766 k++
767 }
768 return list[:k]
769}
770
771func firstUniqueInstallPathsMap(list InstallPaths) InstallPaths {
772 k := 0
773 seen := make(map[InstallPath]bool, len(list))
774 for i := 0; i < len(list); i++ {
775 if seen[list[i]] {
776 continue
777 }
778 seen[list[i]] = true
779 list[k] = list[i]
780 k++
781 }
782 return list[:k]
783}
784
Colin Crossb6715442017-10-24 11:13:31 -0700785// LastUniquePaths returns all unique elements of a Paths, keeping the last copy of each. It
786// modifies the Paths slice contents in place, and returns a subslice of the original slice.
787func LastUniquePaths(list Paths) Paths {
788 totalSkip := 0
789 for i := len(list) - 1; i >= totalSkip; i-- {
790 skip := 0
791 for j := i - 1; j >= totalSkip; j-- {
792 if list[i] == list[j] {
793 skip++
794 } else {
795 list[j+skip] = list[j]
796 }
797 }
798 totalSkip += skip
799 }
800 return list[totalSkip:]
801}
802
Colin Crossa140bb02018-04-17 10:52:26 -0700803// ReversePaths returns a copy of a Paths in reverse order.
804func ReversePaths(list Paths) Paths {
805 if list == nil {
806 return nil
807 }
808 ret := make(Paths, len(list))
809 for i := range list {
810 ret[i] = list[len(list)-1-i]
811 }
812 return ret
813}
814
Jeff Gaston294356f2017-09-27 17:05:30 -0700815func indexPathList(s Path, list []Path) int {
816 for i, l := range list {
817 if l == s {
818 return i
819 }
820 }
821
822 return -1
823}
824
825func inPathList(p Path, list []Path) bool {
826 return indexPathList(p, list) != -1
827}
828
829func FilterPathList(list []Path, filter []Path) (remainder []Path, filtered []Path) {
Paul Duffin57b9e1d2019-12-13 00:03:35 +0000830 return FilterPathListPredicate(list, func(p Path) bool { return inPathList(p, filter) })
831}
832
833func FilterPathListPredicate(list []Path, predicate func(Path) bool) (remainder []Path, filtered []Path) {
Jeff Gaston294356f2017-09-27 17:05:30 -0700834 for _, l := range list {
Paul Duffin57b9e1d2019-12-13 00:03:35 +0000835 if predicate(l) {
Jeff Gaston294356f2017-09-27 17:05:30 -0700836 filtered = append(filtered, l)
837 } else {
838 remainder = append(remainder, l)
839 }
840 }
841
842 return
843}
844
Colin Cross93e85952017-08-15 13:34:18 -0700845// HasExt returns true of any of the paths have extension ext, otherwise false
846func (p Paths) HasExt(ext string) bool {
847 for _, path := range p {
848 if path.Ext() == ext {
849 return true
850 }
851 }
852
853 return false
854}
855
856// FilterByExt returns the subset of the paths that have extension ext
857func (p Paths) FilterByExt(ext string) Paths {
858 ret := make(Paths, 0, len(p))
859 for _, path := range p {
860 if path.Ext() == ext {
861 ret = append(ret, path)
862 }
863 }
864 return ret
865}
866
867// FilterOutByExt returns the subset of the paths that do not have extension ext
868func (p Paths) FilterOutByExt(ext string) Paths {
869 ret := make(Paths, 0, len(p))
870 for _, path := range p {
871 if path.Ext() != ext {
872 ret = append(ret, path)
873 }
874 }
875 return ret
876}
877
Colin Cross5e6cfbe2017-11-03 15:20:35 -0700878// DirectorySortedPaths is a slice of paths that are sorted such that all files in a directory
879// (including subdirectories) are in a contiguous subslice of the list, and can be found in
880// O(log(N)) time using a binary search on the directory prefix.
881type DirectorySortedPaths Paths
882
883func PathsToDirectorySortedPaths(paths Paths) DirectorySortedPaths {
884 ret := append(DirectorySortedPaths(nil), paths...)
885 sort.Slice(ret, func(i, j int) bool {
886 return ret[i].String() < ret[j].String()
887 })
888 return ret
889}
890
891// PathsInDirectory returns a subslice of the DirectorySortedPaths as a Paths that contains all entries
892// that are in the specified directory and its subdirectories.
893func (p DirectorySortedPaths) PathsInDirectory(dir string) Paths {
894 prefix := filepath.Clean(dir) + "/"
895 start := sort.Search(len(p), func(i int) bool {
896 return prefix < p[i].String()
897 })
898
899 ret := p[start:]
900
901 end := sort.Search(len(ret), func(i int) bool {
902 return !strings.HasPrefix(ret[i].String(), prefix)
903 })
904
905 ret = ret[:end]
906
907 return Paths(ret)
908}
909
Alex Humesky29e3bbe2020-11-20 21:30:13 -0500910// WritablePaths is a slice of WritablePath, used for multiple outputs.
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700911type WritablePaths []WritablePath
912
913// Strings returns the string forms of the writable paths.
914func (p WritablePaths) Strings() []string {
915 if p == nil {
916 return nil
917 }
918 ret := make([]string, len(p))
919 for i, path := range p {
920 ret[i] = path.String()
921 }
922 return ret
923}
924
Colin Cross3bc7ffa2017-11-22 16:19:37 -0800925// Paths returns the WritablePaths as a Paths
926func (p WritablePaths) Paths() Paths {
927 if p == nil {
928 return nil
929 }
930 ret := make(Paths, len(p))
931 for i, path := range p {
932 ret[i] = path
933 }
934 return ret
935}
936
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700937type basePath struct {
Paul Duffin74abc5d2021-03-24 09:24:59 +0000938 path string
939 rel string
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700940}
941
942func (p basePath) Ext() string {
943 return filepath.Ext(p.path)
944}
945
Colin Cross4f6fc9c2016-10-26 10:05:25 -0700946func (p basePath) Base() string {
947 return filepath.Base(p.path)
948}
949
Colin Crossfaeb7aa2017-02-01 14:12:44 -0800950func (p basePath) Rel() string {
951 if p.rel != "" {
952 return p.rel
953 }
954 return p.path
955}
956
Colin Cross0875c522017-11-28 17:34:01 -0800957func (p basePath) String() string {
958 return p.path
959}
960
Colin Cross0db55682017-12-05 15:36:55 -0800961func (p basePath) withRel(rel string) basePath {
962 p.path = filepath.Join(p.path, rel)
963 p.rel = rel
964 return p
965}
966
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700967// SourcePath is a Path representing a file path rooted from SrcDir
968type SourcePath struct {
969 basePath
Paul Duffin580efc82021-03-24 09:04:03 +0000970
971 // The sources root, i.e. Config.SrcDir()
972 srcDir string
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700973}
974
975var _ Path = SourcePath{}
976
Colin Cross0db55682017-12-05 15:36:55 -0800977func (p SourcePath) withRel(rel string) SourcePath {
978 p.basePath = p.basePath.withRel(rel)
979 return p
980}
981
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700982// safePathForSource is for paths that we expect are safe -- only for use by go
983// code that is embedding ninja variables in paths
Colin Crossfe4bc362018-09-12 10:02:13 -0700984func safePathForSource(ctx PathContext, pathComponents ...string) (SourcePath, error) {
985 p, err := validateSafePath(pathComponents...)
Paul Duffin74abc5d2021-03-24 09:24:59 +0000986 ret := SourcePath{basePath{p, ""}, ctx.Config().srcDir}
Colin Crossfe4bc362018-09-12 10:02:13 -0700987 if err != nil {
988 return ret, err
989 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700990
Colin Cross7b3dcc32019-01-24 13:14:39 -0800991 // absolute path already checked by validateSafePath
992 if strings.HasPrefix(ret.String(), ctx.Config().buildDir) {
Mikhail Naganovab1f5182019-02-08 13:17:55 -0800993 return ret, fmt.Errorf("source path %q is in output", ret.String())
Colin Cross6e18ca42015-07-14 18:55:36 -0700994 }
995
Colin Crossfe4bc362018-09-12 10:02:13 -0700996 return ret, err
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700997}
998
Colin Cross192e97a2018-02-22 14:21:02 -0800999// pathForSource creates a SourcePath from pathComponents, but does not check that it exists.
1000func pathForSource(ctx PathContext, pathComponents ...string) (SourcePath, error) {
Colin Crossc48c1432018-02-23 07:09:01 +00001001 p, err := validatePath(pathComponents...)
Paul Duffin74abc5d2021-03-24 09:24:59 +00001002 ret := SourcePath{basePath{p, ""}, ctx.Config().srcDir}
Colin Cross94a32102018-02-22 14:21:02 -08001003 if err != nil {
Colin Cross192e97a2018-02-22 14:21:02 -08001004 return ret, err
Colin Cross94a32102018-02-22 14:21:02 -08001005 }
1006
Colin Cross7b3dcc32019-01-24 13:14:39 -08001007 // absolute path already checked by validatePath
1008 if strings.HasPrefix(ret.String(), ctx.Config().buildDir) {
Mikhail Naganovab1f5182019-02-08 13:17:55 -08001009 return ret, fmt.Errorf("source path %q is in output", ret.String())
Colin Crossc48c1432018-02-23 07:09:01 +00001010 }
1011
Colin Cross192e97a2018-02-22 14:21:02 -08001012 return ret, nil
1013}
1014
1015// existsWithDependencies returns true if the path exists, and adds appropriate dependencies to rerun if the
1016// path does not exist.
1017func existsWithDependencies(ctx PathContext, path SourcePath) (exists bool, err error) {
1018 var files []string
1019
1020 if gctx, ok := ctx.(PathGlobContext); ok {
1021 // Use glob to produce proper dependencies, even though we only want
1022 // a single file.
1023 files, err = gctx.GlobWithDeps(path.String(), nil)
1024 } else {
1025 var deps []string
1026 // We cannot add build statements in this context, so we fall back to
1027 // AddNinjaFileDeps
Colin Cross988414c2020-01-11 01:11:46 +00001028 files, deps, err = ctx.Config().fs.Glob(path.String(), nil, pathtools.FollowSymlinks)
Colin Cross192e97a2018-02-22 14:21:02 -08001029 ctx.AddNinjaFileDeps(deps...)
1030 }
1031
1032 if err != nil {
1033 return false, fmt.Errorf("glob: %s", err.Error())
1034 }
1035
1036 return len(files) > 0, nil
1037}
1038
1039// PathForSource joins the provided path components and validates that the result
1040// neither escapes the source dir nor is in the out dir.
1041// On error, it will return a usable, but invalid SourcePath, and report a ModuleError.
1042func PathForSource(ctx PathContext, pathComponents ...string) SourcePath {
1043 path, err := pathForSource(ctx, pathComponents...)
1044 if err != nil {
1045 reportPathError(ctx, err)
1046 }
1047
Colin Crosse3924e12018-08-15 20:18:53 -07001048 if pathtools.IsGlob(path.String()) {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001049 ReportPathErrorf(ctx, "path may not contain a glob: %s", path.String())
Colin Crosse3924e12018-08-15 20:18:53 -07001050 }
1051
Liz Kammera830f3a2020-11-10 10:50:34 -08001052 if modCtx, ok := ctx.(ModuleMissingDepsPathContext); ok && ctx.Config().AllowMissingDependencies() {
Colin Cross192e97a2018-02-22 14:21:02 -08001053 exists, err := existsWithDependencies(ctx, path)
1054 if err != nil {
1055 reportPathError(ctx, err)
1056 }
1057 if !exists {
1058 modCtx.AddMissingDependencies([]string{path.String()})
1059 }
Colin Cross988414c2020-01-11 01:11:46 +00001060 } else if exists, _, err := ctx.Config().fs.Exists(path.String()); err != nil {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001061 ReportPathErrorf(ctx, "%s: %s", path, err.Error())
Pedro Loureiro5d190cc2021-02-15 15:41:33 +00001062 } else if !exists && !ctx.Config().TestAllowNonExistentPaths {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001063 ReportPathErrorf(ctx, "source path %q does not exist", path)
Colin Cross192e97a2018-02-22 14:21:02 -08001064 }
1065 return path
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001066}
1067
Liz Kammer7aa52882021-02-11 09:16:14 -05001068// ExistentPathForSource returns an OptionalPath with the SourcePath, rooted from SrcDir, *not*
1069// rooted from the module's local source directory, if the path exists, or an empty OptionalPath if
1070// it doesn't exist. Dependencies are added so that the ninja file will be regenerated if the state
1071// of the path changes.
Colin Cross32f38982018-02-22 11:47:25 -08001072func ExistentPathForSource(ctx PathContext, pathComponents ...string) OptionalPath {
Colin Cross192e97a2018-02-22 14:21:02 -08001073 path, err := pathForSource(ctx, pathComponents...)
Colin Cross1ccfcc32018-02-22 13:54:26 -08001074 if err != nil {
1075 reportPathError(ctx, err)
1076 return OptionalPath{}
1077 }
Colin Crossc48c1432018-02-23 07:09:01 +00001078
Colin Crosse3924e12018-08-15 20:18:53 -07001079 if pathtools.IsGlob(path.String()) {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001080 ReportPathErrorf(ctx, "path may not contain a glob: %s", path.String())
Colin Crosse3924e12018-08-15 20:18:53 -07001081 return OptionalPath{}
1082 }
1083
Colin Cross192e97a2018-02-22 14:21:02 -08001084 exists, err := existsWithDependencies(ctx, path)
Colin Crossc48c1432018-02-23 07:09:01 +00001085 if err != nil {
1086 reportPathError(ctx, err)
1087 return OptionalPath{}
1088 }
Colin Cross192e97a2018-02-22 14:21:02 -08001089 if !exists {
Colin Crossc48c1432018-02-23 07:09:01 +00001090 return OptionalPath{}
1091 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001092 return OptionalPathForPath(path)
1093}
1094
1095func (p SourcePath) String() string {
Paul Duffin580efc82021-03-24 09:04:03 +00001096 return filepath.Join(p.srcDir, p.path)
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001097}
1098
1099// Join creates a new SourcePath with paths... joined with the current path. The
1100// provided paths... may not use '..' to escape from the current path.
1101func (p SourcePath) Join(ctx PathContext, paths ...string) SourcePath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001102 path, err := validatePath(paths...)
1103 if err != nil {
1104 reportPathError(ctx, err)
1105 }
Colin Cross0db55682017-12-05 15:36:55 -08001106 return p.withRel(path)
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001107}
1108
Colin Cross2fafa3e2019-03-05 12:39:51 -08001109// join is like Join but does less path validation.
1110func (p SourcePath) join(ctx PathContext, paths ...string) SourcePath {
1111 path, err := validateSafePath(paths...)
1112 if err != nil {
1113 reportPathError(ctx, err)
1114 }
1115 return p.withRel(path)
1116}
1117
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001118// OverlayPath returns the overlay for `path' if it exists. This assumes that the
1119// SourcePath is the path to a resource overlay directory.
Liz Kammera830f3a2020-11-10 10:50:34 -08001120func (p SourcePath) OverlayPath(ctx ModuleMissingDepsPathContext, path Path) OptionalPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001121 var relDir string
Colin Cross07e51612019-03-05 12:46:40 -08001122 if srcPath, ok := path.(SourcePath); ok {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001123 relDir = srcPath.path
1124 } else {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001125 ReportPathErrorf(ctx, "Cannot find relative path for %s(%s)", reflect.TypeOf(path).Name(), path)
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001126 return OptionalPath{}
1127 }
Paul Duffin580efc82021-03-24 09:04:03 +00001128 dir := filepath.Join(p.srcDir, p.path, relDir)
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001129 // Use Glob so that we are run again if the directory is added.
Colin Cross7f19f372016-11-01 11:10:25 -07001130 if pathtools.IsGlob(dir) {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001131 ReportPathErrorf(ctx, "Path may not contain a glob: %s", dir)
Dan Willemsen7b310ee2015-12-18 15:11:17 -08001132 }
Colin Cross461b4452018-02-23 09:22:42 -08001133 paths, err := ctx.GlobWithDeps(dir, nil)
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001134 if err != nil {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001135 ReportPathErrorf(ctx, "glob: %s", err.Error())
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001136 return OptionalPath{}
1137 }
1138 if len(paths) == 0 {
1139 return OptionalPath{}
1140 }
Paul Duffin580efc82021-03-24 09:04:03 +00001141 relPath := Rel(ctx, p.srcDir, paths[0])
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001142 return OptionalPathForPath(PathForSource(ctx, relPath))
1143}
1144
Colin Cross70dda7e2019-10-01 22:05:35 -07001145// OutputPath is a Path representing an intermediates file path rooted from the build directory
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001146type OutputPath struct {
1147 basePath
Paul Duffind65c58b2021-03-24 09:22:07 +00001148
1149 // The soong build directory, i.e. Config.BuildDir()
1150 buildDir string
1151
Colin Crossd63c9a72020-01-29 16:52:50 -08001152 fullPath string
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001153}
1154
Colin Cross702e0f82017-10-18 17:27:54 -07001155func (p OutputPath) withRel(rel string) OutputPath {
Colin Cross0db55682017-12-05 15:36:55 -08001156 p.basePath = p.basePath.withRel(rel)
Colin Crossd63c9a72020-01-29 16:52:50 -08001157 p.fullPath = filepath.Join(p.fullPath, rel)
Colin Cross702e0f82017-10-18 17:27:54 -07001158 return p
1159}
1160
Colin Cross3063b782018-08-15 11:19:12 -07001161func (p OutputPath) WithoutRel() OutputPath {
1162 p.basePath.rel = filepath.Base(p.basePath.path)
1163 return p
1164}
1165
Paul Duffind65c58b2021-03-24 09:22:07 +00001166func (p OutputPath) getBuildDir() string {
1167 return p.buildDir
Paul Duffin9b478b02019-12-10 13:41:51 +00001168}
1169
Paul Duffin0267d492021-02-02 10:05:52 +00001170func (p OutputPath) objPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleObjPath {
1171 return PathForModuleObj(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
1172}
1173
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001174var _ Path = OutputPath{}
Paul Duffin9b478b02019-12-10 13:41:51 +00001175var _ WritablePath = OutputPath{}
Paul Duffin0267d492021-02-02 10:05:52 +00001176var _ objPathProvider = OutputPath{}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001177
Chris Parsons8f232a22020-06-23 17:37:05 -04001178// toolDepPath is a Path representing a dependency of the build tool.
1179type toolDepPath struct {
1180 basePath
1181}
1182
1183var _ Path = toolDepPath{}
1184
1185// pathForBuildToolDep returns a toolDepPath representing the given path string.
1186// There is no validation for the path, as it is "trusted": It may fail
1187// normal validation checks. For example, it may be an absolute path.
1188// Only use this function to construct paths for dependencies of the build
1189// tool invocation.
1190func pathForBuildToolDep(ctx PathContext, path string) toolDepPath {
Paul Duffin74abc5d2021-03-24 09:24:59 +00001191 return toolDepPath{basePath{path, ""}}
Chris Parsons8f232a22020-06-23 17:37:05 -04001192}
1193
Jeff Gaston734e3802017-04-10 15:47:24 -07001194// PathForOutput joins the provided paths and returns an OutputPath that is
1195// validated to not escape the build dir.
1196// On error, it will return a usable, but invalid OutputPath, and report a ModuleError.
1197func PathForOutput(ctx PathContext, pathComponents ...string) OutputPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001198 path, err := validatePath(pathComponents...)
1199 if err != nil {
1200 reportPathError(ctx, err)
1201 }
Colin Crossd63c9a72020-01-29 16:52:50 -08001202 fullPath := filepath.Join(ctx.Config().buildDir, path)
1203 path = fullPath[len(fullPath)-len(path):]
Paul Duffin74abc5d2021-03-24 09:24:59 +00001204 return OutputPath{basePath{path, ""}, ctx.Config().buildDir, fullPath}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001205}
1206
Colin Cross40e33732019-02-15 11:08:35 -08001207// PathsForOutput returns Paths rooted from buildDir
1208func PathsForOutput(ctx PathContext, paths []string) WritablePaths {
1209 ret := make(WritablePaths, len(paths))
1210 for i, path := range paths {
1211 ret[i] = PathForOutput(ctx, path)
1212 }
1213 return ret
1214}
1215
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001216func (p OutputPath) writablePath() {}
1217
1218func (p OutputPath) String() string {
Colin Crossd63c9a72020-01-29 16:52:50 -08001219 return p.fullPath
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001220}
1221
1222// Join creates a new OutputPath with paths... joined with the current path. The
1223// provided paths... may not use '..' to escape from the current path.
1224func (p OutputPath) Join(ctx PathContext, paths ...string) OutputPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001225 path, err := validatePath(paths...)
1226 if err != nil {
1227 reportPathError(ctx, err)
1228 }
Colin Cross0db55682017-12-05 15:36:55 -08001229 return p.withRel(path)
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001230}
1231
Colin Cross8854a5a2019-02-11 14:14:16 -08001232// ReplaceExtension creates a new OutputPath with the extension replaced with ext.
1233func (p OutputPath) ReplaceExtension(ctx PathContext, ext string) OutputPath {
1234 if strings.Contains(ext, "/") {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001235 ReportPathErrorf(ctx, "extension %q cannot contain /", ext)
Colin Cross8854a5a2019-02-11 14:14:16 -08001236 }
1237 ret := PathForOutput(ctx, pathtools.ReplaceExtension(p.path, ext))
Colin Cross2cdd5df2019-02-25 10:25:24 -08001238 ret.rel = pathtools.ReplaceExtension(p.rel, ext)
Colin Cross8854a5a2019-02-11 14:14:16 -08001239 return ret
1240}
1241
Colin Cross40e33732019-02-15 11:08:35 -08001242// InSameDir creates a new OutputPath from the directory of the current OutputPath joined with the elements in paths.
1243func (p OutputPath) InSameDir(ctx PathContext, paths ...string) OutputPath {
1244 path, err := validatePath(paths...)
1245 if err != nil {
1246 reportPathError(ctx, err)
1247 }
1248
1249 ret := PathForOutput(ctx, filepath.Dir(p.path), path)
Colin Cross2cdd5df2019-02-25 10:25:24 -08001250 ret.rel = filepath.Join(filepath.Dir(p.rel), path)
Colin Cross40e33732019-02-15 11:08:35 -08001251 return ret
1252}
1253
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001254// PathForIntermediates returns an OutputPath representing the top-level
1255// intermediates directory.
1256func PathForIntermediates(ctx PathContext, paths ...string) OutputPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001257 path, err := validatePath(paths...)
1258 if err != nil {
1259 reportPathError(ctx, err)
1260 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001261 return PathForOutput(ctx, ".intermediates", path)
1262}
1263
Colin Cross07e51612019-03-05 12:46:40 -08001264var _ genPathProvider = SourcePath{}
1265var _ objPathProvider = SourcePath{}
1266var _ resPathProvider = SourcePath{}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001267
Colin Cross07e51612019-03-05 12:46:40 -08001268// PathForModuleSrc returns a Path representing the paths... under the
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001269// module's local source directory.
Liz Kammera830f3a2020-11-10 10:50:34 -08001270func PathForModuleSrc(ctx ModuleMissingDepsPathContext, pathComponents ...string) Path {
Colin Cross8a497952019-03-05 22:25:09 -08001271 p, err := validatePath(pathComponents...)
1272 if err != nil {
1273 reportPathError(ctx, err)
Colin Cross192e97a2018-02-22 14:21:02 -08001274 }
Colin Cross8a497952019-03-05 22:25:09 -08001275 paths, err := expandOneSrcPath(ctx, p, nil)
1276 if err != nil {
1277 if depErr, ok := err.(missingDependencyError); ok {
1278 if ctx.Config().AllowMissingDependencies() {
1279 ctx.AddMissingDependencies(depErr.missingDeps)
1280 } else {
1281 ctx.ModuleErrorf(`%s, is the property annotated with android:"path"?`, depErr.Error())
1282 }
1283 } else {
1284 reportPathError(ctx, err)
1285 }
1286 return nil
1287 } else if len(paths) == 0 {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001288 ReportPathErrorf(ctx, "%q produced no files, expected exactly one", p)
Colin Cross8a497952019-03-05 22:25:09 -08001289 return nil
1290 } else if len(paths) > 1 {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001291 ReportPathErrorf(ctx, "%q produced %d files, expected exactly one", p, len(paths))
Colin Cross8a497952019-03-05 22:25:09 -08001292 }
1293 return paths[0]
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001294}
1295
Liz Kammera830f3a2020-11-10 10:50:34 -08001296func pathForModuleSrc(ctx EarlyModulePathContext, paths ...string) SourcePath {
Colin Cross07e51612019-03-05 12:46:40 -08001297 p, err := validatePath(paths...)
1298 if err != nil {
1299 reportPathError(ctx, err)
1300 }
1301
1302 path, err := pathForSource(ctx, ctx.ModuleDir(), p)
1303 if err != nil {
1304 reportPathError(ctx, err)
1305 }
1306
1307 path.basePath.rel = p
1308
1309 return path
1310}
1311
Colin Cross2fafa3e2019-03-05 12:39:51 -08001312// PathsWithModuleSrcSubDir takes a list of Paths and returns a new list of Paths where Rel() on each path
1313// will return the path relative to subDir in the module's source directory. If any input paths are not located
1314// inside subDir then a path error will be reported.
Liz Kammera830f3a2020-11-10 10:50:34 -08001315func PathsWithModuleSrcSubDir(ctx EarlyModulePathContext, paths Paths, subDir string) Paths {
Colin Cross2fafa3e2019-03-05 12:39:51 -08001316 paths = append(Paths(nil), paths...)
Colin Cross07e51612019-03-05 12:46:40 -08001317 subDirFullPath := pathForModuleSrc(ctx, subDir)
Colin Cross2fafa3e2019-03-05 12:39:51 -08001318 for i, path := range paths {
1319 rel := Rel(ctx, subDirFullPath.String(), path.String())
1320 paths[i] = subDirFullPath.join(ctx, rel)
1321 }
1322 return paths
1323}
1324
1325// PathWithModuleSrcSubDir takes a Path and returns a Path where Rel() will return the path relative to subDir in the
1326// module's source directory. If the input path is not located inside subDir then a path error will be reported.
Liz Kammera830f3a2020-11-10 10:50:34 -08001327func PathWithModuleSrcSubDir(ctx EarlyModulePathContext, path Path, subDir string) Path {
Colin Cross07e51612019-03-05 12:46:40 -08001328 subDirFullPath := pathForModuleSrc(ctx, subDir)
Colin Cross2fafa3e2019-03-05 12:39:51 -08001329 rel := Rel(ctx, subDirFullPath.String(), path.String())
1330 return subDirFullPath.Join(ctx, rel)
1331}
1332
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001333// OptionalPathForModuleSrc returns an OptionalPath. The OptionalPath contains a
1334// valid path if p is non-nil.
Liz Kammera830f3a2020-11-10 10:50:34 -08001335func OptionalPathForModuleSrc(ctx ModuleMissingDepsPathContext, p *string) OptionalPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001336 if p == nil {
1337 return OptionalPath{}
1338 }
1339 return OptionalPathForPath(PathForModuleSrc(ctx, *p))
1340}
1341
Liz Kammera830f3a2020-11-10 10:50:34 -08001342func (p SourcePath) genPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleGenPath {
Colin Cross7fc17db2017-02-01 14:07:55 -08001343 return PathForModuleGen(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001344}
1345
Liz Kammera830f3a2020-11-10 10:50:34 -08001346func (p SourcePath) objPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleObjPath {
Colin Cross7fc17db2017-02-01 14:07:55 -08001347 return PathForModuleObj(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001348}
1349
Liz Kammera830f3a2020-11-10 10:50:34 -08001350func (p SourcePath) resPathWithName(ctx ModuleOutPathContext, name string) ModuleResPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001351 // TODO: Use full directory if the new ctx is not the current ctx?
1352 return PathForModuleRes(ctx, p.path, name)
1353}
1354
1355// ModuleOutPath is a Path representing a module's output directory.
1356type ModuleOutPath struct {
1357 OutputPath
1358}
1359
1360var _ Path = ModuleOutPath{}
1361
Liz Kammera830f3a2020-11-10 10:50:34 -08001362func (p ModuleOutPath) objPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleObjPath {
Pete Bentleyfcf55bf2019-08-16 20:14:32 +01001363 return PathForModuleObj(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
1364}
1365
Liz Kammera830f3a2020-11-10 10:50:34 -08001366// ModuleOutPathContext Subset of ModuleContext functions necessary for output path methods.
1367type ModuleOutPathContext interface {
1368 PathContext
1369
1370 ModuleName() string
1371 ModuleDir() string
1372 ModuleSubDir() string
1373}
1374
1375func pathForModuleOut(ctx ModuleOutPathContext) OutputPath {
Colin Cross702e0f82017-10-18 17:27:54 -07001376 return PathForOutput(ctx, ".intermediates", ctx.ModuleDir(), ctx.ModuleName(), ctx.ModuleSubDir())
1377}
1378
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001379type BazelOutPath struct {
1380 OutputPath
1381}
1382
1383var _ Path = BazelOutPath{}
1384var _ objPathProvider = BazelOutPath{}
1385
Liz Kammera830f3a2020-11-10 10:50:34 -08001386func (p BazelOutPath) objPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleObjPath {
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001387 return PathForModuleObj(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
1388}
1389
Logan Chien7eefdc42018-07-11 18:10:41 +08001390// PathForVndkRefAbiDump returns an OptionalPath representing the path of the
1391// reference abi dump for the given module. This is not guaranteed to be valid.
Liz Kammera830f3a2020-11-10 10:50:34 -08001392func PathForVndkRefAbiDump(ctx ModuleInstallPathContext, version, fileName string,
Hsin-Yi Chen53489642019-07-31 17:10:45 +08001393 isNdk, isLlndkOrVndk, isGzip bool) OptionalPath {
Logan Chien7eefdc42018-07-11 18:10:41 +08001394
Jayant Chowdharyac066c62018-02-20 10:53:31 -08001395 arches := ctx.DeviceConfig().Arches()
Logan Chien7eefdc42018-07-11 18:10:41 +08001396 if len(arches) == 0 {
1397 panic("device build with no primary arch")
1398 }
Jayant Chowdharyac066c62018-02-20 10:53:31 -08001399 currentArch := ctx.Arch()
1400 archNameAndVariant := currentArch.ArchType.String()
1401 if currentArch.ArchVariant != "" {
1402 archNameAndVariant += "_" + currentArch.ArchVariant
1403 }
Logan Chien5237bed2018-07-11 17:15:57 +08001404
1405 var dirName string
Hsin-Yi Chen53489642019-07-31 17:10:45 +08001406 if isNdk {
Logan Chien5237bed2018-07-11 17:15:57 +08001407 dirName = "ndk"
Hsin-Yi Chen53489642019-07-31 17:10:45 +08001408 } else if isLlndkOrVndk {
Logan Chien5237bed2018-07-11 17:15:57 +08001409 dirName = "vndk"
Logan Chien41eabe62019-04-10 13:33:58 +08001410 } else {
1411 dirName = "platform" // opt-in libs
Jayant Chowdhary3e231fd2017-02-08 13:45:53 -08001412 }
Logan Chien5237bed2018-07-11 17:15:57 +08001413
Jayant Chowdhary34ce67d2018-03-08 11:00:50 -08001414 binderBitness := ctx.DeviceConfig().BinderBitness()
Logan Chien7eefdc42018-07-11 18:10:41 +08001415
1416 var ext string
1417 if isGzip {
1418 ext = ".lsdump.gz"
1419 } else {
1420 ext = ".lsdump"
1421 }
1422
1423 return ExistentPathForSource(ctx, "prebuilts", "abi-dumps", dirName,
1424 version, binderBitness, archNameAndVariant, "source-based",
1425 fileName+ext)
Jayant Chowdhary3e231fd2017-02-08 13:45:53 -08001426}
1427
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001428// PathForBazelOut returns a Path representing the paths... under an output directory dedicated to
1429// bazel-owned outputs.
1430func PathForBazelOut(ctx PathContext, paths ...string) BazelOutPath {
1431 execRootPathComponents := append([]string{"execroot", "__main__"}, paths...)
1432 execRootPath := filepath.Join(execRootPathComponents...)
1433 validatedExecRootPath, err := validatePath(execRootPath)
1434 if err != nil {
1435 reportPathError(ctx, err)
1436 }
1437
Paul Duffin74abc5d2021-03-24 09:24:59 +00001438 outputPath := OutputPath{basePath{"", ""},
Paul Duffind65c58b2021-03-24 09:22:07 +00001439 ctx.Config().buildDir,
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001440 ctx.Config().BazelContext.OutputBase()}
1441
1442 return BazelOutPath{
1443 OutputPath: outputPath.withRel(validatedExecRootPath),
1444 }
1445}
1446
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001447// PathForModuleOut returns a Path representing the paths... under the module's
1448// output directory.
Liz Kammera830f3a2020-11-10 10:50:34 -08001449func PathForModuleOut(ctx ModuleOutPathContext, paths ...string) ModuleOutPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001450 p, err := validatePath(paths...)
1451 if err != nil {
1452 reportPathError(ctx, err)
1453 }
Colin Cross702e0f82017-10-18 17:27:54 -07001454 return ModuleOutPath{
Liz Kammera830f3a2020-11-10 10:50:34 -08001455 OutputPath: pathForModuleOut(ctx).withRel(p),
Colin Cross702e0f82017-10-18 17:27:54 -07001456 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001457}
1458
1459// ModuleGenPath is a Path representing the 'gen' directory in a module's output
1460// directory. Mainly used for generated sources.
1461type ModuleGenPath struct {
1462 ModuleOutPath
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001463}
1464
1465var _ Path = ModuleGenPath{}
1466var _ genPathProvider = ModuleGenPath{}
1467var _ objPathProvider = ModuleGenPath{}
1468
1469// PathForModuleGen returns a Path representing the paths... under the module's
1470// `gen' directory.
Liz Kammera830f3a2020-11-10 10:50:34 -08001471func PathForModuleGen(ctx ModuleOutPathContext, paths ...string) ModuleGenPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001472 p, err := validatePath(paths...)
1473 if err != nil {
1474 reportPathError(ctx, err)
1475 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001476 return ModuleGenPath{
Colin Cross702e0f82017-10-18 17:27:54 -07001477 ModuleOutPath: ModuleOutPath{
Liz Kammera830f3a2020-11-10 10:50:34 -08001478 OutputPath: pathForModuleOut(ctx).withRel("gen").withRel(p),
Colin Cross702e0f82017-10-18 17:27:54 -07001479 },
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001480 }
1481}
1482
Liz Kammera830f3a2020-11-10 10:50:34 -08001483func (p ModuleGenPath) genPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleGenPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001484 // TODO: make a different path for local vs remote generated files?
Dan Willemsen21ec4902016-11-02 20:43:13 -07001485 return PathForModuleGen(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001486}
1487
Liz Kammera830f3a2020-11-10 10:50:34 -08001488func (p ModuleGenPath) objPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleObjPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001489 return PathForModuleObj(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
1490}
1491
1492// ModuleObjPath is a Path representing the 'obj' directory in a module's output
1493// directory. Used for compiled objects.
1494type ModuleObjPath struct {
1495 ModuleOutPath
1496}
1497
1498var _ Path = ModuleObjPath{}
1499
1500// PathForModuleObj returns a Path representing the paths... under the module's
1501// 'obj' directory.
Liz Kammera830f3a2020-11-10 10:50:34 -08001502func PathForModuleObj(ctx ModuleOutPathContext, pathComponents ...string) ModuleObjPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001503 p, err := validatePath(pathComponents...)
1504 if err != nil {
1505 reportPathError(ctx, err)
1506 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001507 return ModuleObjPath{PathForModuleOut(ctx, "obj", p)}
1508}
1509
1510// ModuleResPath is a a Path representing the 'res' directory in a module's
1511// output directory.
1512type ModuleResPath struct {
1513 ModuleOutPath
1514}
1515
1516var _ Path = ModuleResPath{}
1517
1518// PathForModuleRes returns a Path representing the paths... under the module's
1519// 'res' directory.
Liz Kammera830f3a2020-11-10 10:50:34 -08001520func PathForModuleRes(ctx ModuleOutPathContext, pathComponents ...string) ModuleResPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001521 p, err := validatePath(pathComponents...)
1522 if err != nil {
1523 reportPathError(ctx, err)
1524 }
1525
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001526 return ModuleResPath{PathForModuleOut(ctx, "res", p)}
1527}
1528
Colin Cross70dda7e2019-10-01 22:05:35 -07001529// InstallPath is a Path representing a installed file path rooted from the build directory
1530type InstallPath struct {
1531 basePath
Colin Crossff6c33d2019-10-02 16:01:35 -07001532
Paul Duffind65c58b2021-03-24 09:22:07 +00001533 // The soong build directory, i.e. Config.BuildDir()
1534 buildDir string
1535
Jiyong Park957bcd92020-10-20 18:23:33 +09001536 // partitionDir is the part of the InstallPath that is automatically determined according to the context.
1537 // For example, it is host/<os>-<arch> for host modules, and target/product/<device>/<partition> for device modules.
1538 partitionDir string
1539
1540 // makePath indicates whether this path is for Soong (false) or Make (true).
1541 makePath bool
Colin Cross70dda7e2019-10-01 22:05:35 -07001542}
1543
Paul Duffind65c58b2021-03-24 09:22:07 +00001544func (p InstallPath) getBuildDir() string {
1545 return p.buildDir
Paul Duffin9b478b02019-12-10 13:41:51 +00001546}
1547
Hans MÃ¥nssond3f2bd72020-11-27 12:37:28 +01001548func (p InstallPath) ReplaceExtension(ctx PathContext, ext string) OutputPath {
1549 panic("Not implemented")
1550}
1551
Paul Duffin9b478b02019-12-10 13:41:51 +00001552var _ Path = InstallPath{}
1553var _ WritablePath = InstallPath{}
1554
Colin Cross70dda7e2019-10-01 22:05:35 -07001555func (p InstallPath) writablePath() {}
1556
1557func (p InstallPath) String() string {
Jiyong Park957bcd92020-10-20 18:23:33 +09001558 if p.makePath {
1559 // Make path starts with out/ instead of out/soong.
Paul Duffind65c58b2021-03-24 09:22:07 +00001560 return filepath.Join(p.buildDir, "../", p.path)
Jiyong Park957bcd92020-10-20 18:23:33 +09001561 } else {
Paul Duffind65c58b2021-03-24 09:22:07 +00001562 return filepath.Join(p.buildDir, p.path)
Jiyong Park957bcd92020-10-20 18:23:33 +09001563 }
1564}
1565
1566// PartitionDir returns the path to the partition where the install path is rooted at. It is
1567// out/soong/target/product/<device>/<partition> for device modules, and out/soong/host/<os>-<arch> for host modules.
1568// The ./soong is dropped if the install path is for Make.
1569func (p InstallPath) PartitionDir() string {
1570 if p.makePath {
Paul Duffind65c58b2021-03-24 09:22:07 +00001571 return filepath.Join(p.buildDir, "../", p.partitionDir)
Jiyong Park957bcd92020-10-20 18:23:33 +09001572 } else {
Paul Duffind65c58b2021-03-24 09:22:07 +00001573 return filepath.Join(p.buildDir, p.partitionDir)
Jiyong Park957bcd92020-10-20 18:23:33 +09001574 }
Colin Cross70dda7e2019-10-01 22:05:35 -07001575}
1576
1577// Join creates a new InstallPath with paths... joined with the current path. The
1578// provided paths... may not use '..' to escape from the current path.
1579func (p InstallPath) Join(ctx PathContext, paths ...string) InstallPath {
1580 path, err := validatePath(paths...)
1581 if err != nil {
1582 reportPathError(ctx, err)
1583 }
1584 return p.withRel(path)
1585}
1586
1587func (p InstallPath) withRel(rel string) InstallPath {
1588 p.basePath = p.basePath.withRel(rel)
1589 return p
1590}
1591
Colin Crossff6c33d2019-10-02 16:01:35 -07001592// ToMakePath returns a new InstallPath that points to Make's install directory instead of Soong's,
1593// i.e. out/ instead of out/soong/.
1594func (p InstallPath) ToMakePath() InstallPath {
Jiyong Park957bcd92020-10-20 18:23:33 +09001595 p.makePath = true
Colin Crossff6c33d2019-10-02 16:01:35 -07001596 return p
Colin Cross70dda7e2019-10-01 22:05:35 -07001597}
1598
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001599// PathForModuleInstall returns a Path representing the install path for the
1600// module appended with paths...
Colin Cross70dda7e2019-10-01 22:05:35 -07001601func PathForModuleInstall(ctx ModuleInstallPathContext, pathComponents ...string) InstallPath {
Colin Cross6e359402020-02-10 15:29:54 -08001602 os := ctx.Os()
Jiyong Park87788b52020-09-01 12:37:45 +09001603 arch := ctx.Arch().ArchType
1604 forceOS, forceArch := ctx.InstallForceOS()
1605 if forceOS != nil {
Colin Cross6e359402020-02-10 15:29:54 -08001606 os = *forceOS
1607 }
Jiyong Park87788b52020-09-01 12:37:45 +09001608 if forceArch != nil {
1609 arch = *forceArch
1610 }
Colin Cross6e359402020-02-10 15:29:54 -08001611 partition := modulePartition(ctx, os)
Colin Cross609c49a2020-02-13 13:20:11 -08001612
Jiyong Park87788b52020-09-01 12:37:45 +09001613 ret := pathForInstall(ctx, os, arch, partition, ctx.Debug(), pathComponents...)
Colin Cross609c49a2020-02-13 13:20:11 -08001614
Jingwen Chencda22c92020-11-23 00:22:30 -05001615 if ctx.InstallBypassMake() && ctx.Config().KatiEnabled() {
Colin Cross609c49a2020-02-13 13:20:11 -08001616 ret = ret.ToMakePath()
1617 }
1618
1619 return ret
1620}
1621
Jiyong Park87788b52020-09-01 12:37:45 +09001622func pathForInstall(ctx PathContext, os OsType, arch ArchType, partition string, debug bool,
Colin Cross609c49a2020-02-13 13:20:11 -08001623 pathComponents ...string) InstallPath {
1624
Jiyong Park957bcd92020-10-20 18:23:33 +09001625 var partionPaths []string
Colin Cross609c49a2020-02-13 13:20:11 -08001626
Colin Cross6e359402020-02-10 15:29:54 -08001627 if os.Class == Device {
Jiyong Park957bcd92020-10-20 18:23:33 +09001628 partionPaths = []string{"target", "product", ctx.Config().DeviceName(), partition}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001629 } else {
Jiyong Park87788b52020-09-01 12:37:45 +09001630 osName := os.String()
1631 if os == Linux {
1632 // instead of linux_glibc
1633 osName = "linux"
Dan Willemsen866b5632017-09-22 12:28:24 -07001634 }
Jiyong Park87788b52020-09-01 12:37:45 +09001635 // SOONG_HOST_OUT is set to out/host/$(HOST_OS)-$(HOST_PREBUILT_ARCH)
1636 // and HOST_PREBUILT_ARCH is forcibly set to x86 even on x86_64 hosts. We don't seem
1637 // to have a plan to fix it (see the comment in build/make/core/envsetup.mk).
1638 // Let's keep using x86 for the existing cases until we have a need to support
1639 // other architectures.
1640 archName := arch.String()
1641 if os.Class == Host && (arch == X86_64 || arch == Common) {
1642 archName = "x86"
1643 }
Jiyong Park957bcd92020-10-20 18:23:33 +09001644 partionPaths = []string{"host", osName + "-" + archName, partition}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001645 }
Colin Cross609c49a2020-02-13 13:20:11 -08001646 if debug {
Jiyong Park957bcd92020-10-20 18:23:33 +09001647 partionPaths = append([]string{"debug"}, partionPaths...)
Dan Willemsen782a2d12015-12-21 14:55:28 -08001648 }
Colin Cross70dda7e2019-10-01 22:05:35 -07001649
Jiyong Park957bcd92020-10-20 18:23:33 +09001650 partionPath, err := validatePath(partionPaths...)
Colin Cross70dda7e2019-10-01 22:05:35 -07001651 if err != nil {
1652 reportPathError(ctx, err)
1653 }
Colin Crossff6c33d2019-10-02 16:01:35 -07001654
Jiyong Park957bcd92020-10-20 18:23:33 +09001655 base := InstallPath{
Paul Duffin74abc5d2021-03-24 09:24:59 +00001656 basePath: basePath{partionPath, ""},
Paul Duffind65c58b2021-03-24 09:22:07 +00001657 buildDir: ctx.Config().buildDir,
Jiyong Park957bcd92020-10-20 18:23:33 +09001658 partitionDir: partionPath,
1659 makePath: false,
1660 }
Colin Crossff6c33d2019-10-02 16:01:35 -07001661
Jiyong Park957bcd92020-10-20 18:23:33 +09001662 return base.Join(ctx, pathComponents...)
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001663}
1664
Nicolas Geoffray1228e9c2020-02-27 13:45:35 +00001665func pathForNdkOrSdkInstall(ctx PathContext, prefix string, paths []string) InstallPath {
Jiyong Park957bcd92020-10-20 18:23:33 +09001666 base := InstallPath{
Paul Duffin74abc5d2021-03-24 09:24:59 +00001667 basePath: basePath{prefix, ""},
Paul Duffind65c58b2021-03-24 09:22:07 +00001668 buildDir: ctx.Config().buildDir,
Jiyong Park957bcd92020-10-20 18:23:33 +09001669 partitionDir: prefix,
1670 makePath: false,
Colin Cross70dda7e2019-10-01 22:05:35 -07001671 }
Jiyong Park957bcd92020-10-20 18:23:33 +09001672 return base.Join(ctx, paths...)
Colin Cross70dda7e2019-10-01 22:05:35 -07001673}
1674
Nicolas Geoffray1228e9c2020-02-27 13:45:35 +00001675func PathForNdkInstall(ctx PathContext, paths ...string) InstallPath {
1676 return pathForNdkOrSdkInstall(ctx, "ndk", paths)
1677}
1678
1679func PathForMainlineSdksInstall(ctx PathContext, paths ...string) InstallPath {
1680 return pathForNdkOrSdkInstall(ctx, "mainline-sdks", paths)
1681}
1682
Colin Cross70dda7e2019-10-01 22:05:35 -07001683func InstallPathToOnDevicePath(ctx PathContext, path InstallPath) string {
Colin Cross43f08db2018-11-12 10:13:39 -08001684 rel := Rel(ctx, PathForOutput(ctx, "target", "product", ctx.Config().DeviceName()).String(), path.String())
1685
1686 return "/" + rel
1687}
1688
Colin Cross6e359402020-02-10 15:29:54 -08001689func modulePartition(ctx ModuleInstallPathContext, os OsType) string {
Colin Cross43f08db2018-11-12 10:13:39 -08001690 var partition string
Colin Cross6e359402020-02-10 15:29:54 -08001691 if ctx.InstallInTestcases() {
1692 // "testcases" install directory can be used for host or device modules.
Jaewoong Jung0949f312019-09-11 10:25:18 -07001693 partition = "testcases"
Colin Cross6e359402020-02-10 15:29:54 -08001694 } else if os.Class == Device {
1695 if ctx.InstallInData() {
1696 partition = "data"
1697 } else if ctx.InstallInRamdisk() {
1698 if ctx.DeviceConfig().BoardUsesRecoveryAsBoot() {
1699 partition = "recovery/root/first_stage_ramdisk"
1700 } else {
1701 partition = "ramdisk"
1702 }
1703 if !ctx.InstallInRoot() {
1704 partition += "/system"
1705 }
Yifan Hong60e0cfb2020-10-21 15:17:56 -07001706 } else if ctx.InstallInVendorRamdisk() {
Yifan Hong39143a92020-10-26 12:43:12 -07001707 // The module is only available after switching root into
1708 // /first_stage_ramdisk. To expose the module before switching root
1709 // on a device without a dedicated recovery partition, install the
1710 // recovery variant.
Yifan Hongdd8dacc2020-10-21 15:40:17 -07001711 if ctx.DeviceConfig().BoardMoveRecoveryResourcesToVendorBoot() {
Petri Gyntherac229562021-03-02 23:44:02 -08001712 partition = "vendor_ramdisk/first_stage_ramdisk"
Yifan Hongdd8dacc2020-10-21 15:40:17 -07001713 } else {
Petri Gyntherac229562021-03-02 23:44:02 -08001714 partition = "vendor_ramdisk"
Yifan Hongdd8dacc2020-10-21 15:40:17 -07001715 }
1716 if !ctx.InstallInRoot() {
1717 partition += "/system"
1718 }
Colin Cross6e359402020-02-10 15:29:54 -08001719 } else if ctx.InstallInRecovery() {
1720 if ctx.InstallInRoot() {
1721 partition = "recovery/root"
1722 } else {
1723 // the layout of recovery partion is the same as that of system partition
1724 partition = "recovery/root/system"
1725 }
1726 } else if ctx.SocSpecific() {
1727 partition = ctx.DeviceConfig().VendorPath()
1728 } else if ctx.DeviceSpecific() {
1729 partition = ctx.DeviceConfig().OdmPath()
1730 } else if ctx.ProductSpecific() {
1731 partition = ctx.DeviceConfig().ProductPath()
1732 } else if ctx.SystemExtSpecific() {
1733 partition = ctx.DeviceConfig().SystemExtPath()
1734 } else if ctx.InstallInRoot() {
1735 partition = "root"
Yifan Hong82db7352020-01-21 16:12:26 -08001736 } else {
Colin Cross6e359402020-02-10 15:29:54 -08001737 partition = "system"
Yifan Hong82db7352020-01-21 16:12:26 -08001738 }
Colin Cross6e359402020-02-10 15:29:54 -08001739 if ctx.InstallInSanitizerDir() {
1740 partition = "data/asan/" + partition
Yifan Hong82db7352020-01-21 16:12:26 -08001741 }
Colin Cross43f08db2018-11-12 10:13:39 -08001742 }
1743 return partition
1744}
1745
Colin Cross609c49a2020-02-13 13:20:11 -08001746type InstallPaths []InstallPath
1747
1748// Paths returns the InstallPaths as a Paths
1749func (p InstallPaths) Paths() Paths {
1750 if p == nil {
1751 return nil
1752 }
1753 ret := make(Paths, len(p))
1754 for i, path := range p {
1755 ret[i] = path
1756 }
1757 return ret
1758}
1759
1760// Strings returns the string forms of the install paths.
1761func (p InstallPaths) Strings() []string {
1762 if p == nil {
1763 return nil
1764 }
1765 ret := make([]string, len(p))
1766 for i, path := range p {
1767 ret[i] = path.String()
1768 }
1769 return ret
1770}
1771
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001772// validateSafePath validates a path that we trust (may contain ninja variables).
Dan Willemsen80a7c2a2015-12-21 14:57:11 -08001773// Ensures that each path component does not attempt to leave its component.
Colin Cross1ccfcc32018-02-22 13:54:26 -08001774func validateSafePath(pathComponents ...string) (string, error) {
Jeff Gaston734e3802017-04-10 15:47:24 -07001775 for _, path := range pathComponents {
Dan Willemsen80a7c2a2015-12-21 14:57:11 -08001776 path := filepath.Clean(path)
1777 if path == ".." || strings.HasPrefix(path, "../") || strings.HasPrefix(path, "/") {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001778 return "", fmt.Errorf("Path is outside directory: %s", path)
Dan Willemsen80a7c2a2015-12-21 14:57:11 -08001779 }
1780 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001781 // TODO: filepath.Join isn't necessarily correct with embedded ninja
1782 // variables. '..' may remove the entire ninja variable, even if it
1783 // will be expanded to multiple nested directories.
Colin Cross1ccfcc32018-02-22 13:54:26 -08001784 return filepath.Join(pathComponents...), nil
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001785}
1786
Dan Willemsen80a7c2a2015-12-21 14:57:11 -08001787// validatePath validates that a path does not include ninja variables, and that
1788// each path component does not attempt to leave its component. Returns a joined
1789// version of each path component.
Colin Cross1ccfcc32018-02-22 13:54:26 -08001790func validatePath(pathComponents ...string) (string, error) {
Jeff Gaston734e3802017-04-10 15:47:24 -07001791 for _, path := range pathComponents {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001792 if strings.Contains(path, "$") {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001793 return "", fmt.Errorf("Path contains invalid character($): %s", path)
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001794 }
1795 }
Colin Cross1ccfcc32018-02-22 13:54:26 -08001796 return validateSafePath(pathComponents...)
Colin Cross6e18ca42015-07-14 18:55:36 -07001797}
Colin Cross5b529592017-05-09 13:34:34 -07001798
Colin Cross0875c522017-11-28 17:34:01 -08001799func PathForPhony(ctx PathContext, phony string) WritablePath {
1800 if strings.ContainsAny(phony, "$/") {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001801 ReportPathErrorf(ctx, "Phony target contains invalid character ($ or /): %s", phony)
Colin Cross0875c522017-11-28 17:34:01 -08001802 }
Paul Duffin74abc5d2021-03-24 09:24:59 +00001803 return PhonyPath{basePath{phony, ""}}
Colin Cross0875c522017-11-28 17:34:01 -08001804}
1805
Colin Cross74e3fe42017-12-11 15:51:44 -08001806type PhonyPath struct {
1807 basePath
1808}
1809
1810func (p PhonyPath) writablePath() {}
1811
Paul Duffind65c58b2021-03-24 09:22:07 +00001812func (p PhonyPath) getBuildDir() string {
1813 // A phone path cannot contain any / so cannot be relative to the build directory.
1814 return ""
Paul Duffin9b478b02019-12-10 13:41:51 +00001815}
1816
Hans MÃ¥nssond3f2bd72020-11-27 12:37:28 +01001817func (p PhonyPath) ReplaceExtension(ctx PathContext, ext string) OutputPath {
1818 panic("Not implemented")
1819}
1820
Colin Cross74e3fe42017-12-11 15:51:44 -08001821var _ Path = PhonyPath{}
1822var _ WritablePath = PhonyPath{}
1823
Colin Cross5b529592017-05-09 13:34:34 -07001824type testPath struct {
1825 basePath
1826}
1827
1828func (p testPath) String() string {
1829 return p.path
1830}
1831
Colin Cross40e33732019-02-15 11:08:35 -08001832// PathForTesting returns a Path constructed from joining the elements of paths with '/'. It should only be used from
1833// within tests.
Colin Cross5b529592017-05-09 13:34:34 -07001834func PathForTesting(paths ...string) Path {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001835 p, err := validateSafePath(paths...)
1836 if err != nil {
1837 panic(err)
1838 }
Colin Cross5b529592017-05-09 13:34:34 -07001839 return testPath{basePath{path: p, rel: p}}
1840}
1841
Colin Cross40e33732019-02-15 11:08:35 -08001842// PathsForTesting returns a Path constructed from each element in strs. It should only be used from within tests.
1843func PathsForTesting(strs ...string) Paths {
Colin Cross5b529592017-05-09 13:34:34 -07001844 p := make(Paths, len(strs))
1845 for i, s := range strs {
1846 p[i] = PathForTesting(s)
1847 }
1848
1849 return p
1850}
Colin Cross43f08db2018-11-12 10:13:39 -08001851
Colin Cross40e33732019-02-15 11:08:35 -08001852type testPathContext struct {
1853 config Config
Colin Cross40e33732019-02-15 11:08:35 -08001854}
1855
Colin Cross40e33732019-02-15 11:08:35 -08001856func (x *testPathContext) Config() Config { return x.config }
1857func (x *testPathContext) AddNinjaFileDeps(...string) {}
1858
1859// PathContextForTesting returns a PathContext that can be used in tests, for example to create an OutputPath with
1860// PathForOutput.
Colin Cross98be1bb2019-12-13 20:41:13 -08001861func PathContextForTesting(config Config) PathContext {
Colin Cross40e33732019-02-15 11:08:35 -08001862 return &testPathContext{
1863 config: config,
Colin Cross40e33732019-02-15 11:08:35 -08001864 }
1865}
1866
Ulya Trafimovichccc8c852020-10-14 11:29:07 +01001867type testModuleInstallPathContext struct {
1868 baseModuleContext
1869
1870 inData bool
1871 inTestcases bool
1872 inSanitizerDir bool
1873 inRamdisk bool
1874 inVendorRamdisk bool
1875 inRecovery bool
1876 inRoot bool
1877 forceOS *OsType
1878 forceArch *ArchType
1879}
1880
1881func (m testModuleInstallPathContext) Config() Config {
1882 return m.baseModuleContext.config
1883}
1884
1885func (testModuleInstallPathContext) AddNinjaFileDeps(deps ...string) {}
1886
1887func (m testModuleInstallPathContext) InstallInData() bool {
1888 return m.inData
1889}
1890
1891func (m testModuleInstallPathContext) InstallInTestcases() bool {
1892 return m.inTestcases
1893}
1894
1895func (m testModuleInstallPathContext) InstallInSanitizerDir() bool {
1896 return m.inSanitizerDir
1897}
1898
1899func (m testModuleInstallPathContext) InstallInRamdisk() bool {
1900 return m.inRamdisk
1901}
1902
1903func (m testModuleInstallPathContext) InstallInVendorRamdisk() bool {
1904 return m.inVendorRamdisk
1905}
1906
1907func (m testModuleInstallPathContext) InstallInRecovery() bool {
1908 return m.inRecovery
1909}
1910
1911func (m testModuleInstallPathContext) InstallInRoot() bool {
1912 return m.inRoot
1913}
1914
1915func (m testModuleInstallPathContext) InstallBypassMake() bool {
1916 return false
1917}
1918
1919func (m testModuleInstallPathContext) InstallForceOS() (*OsType, *ArchType) {
1920 return m.forceOS, m.forceArch
1921}
1922
1923// Construct a minimal ModuleInstallPathContext for testing. Note that baseModuleContext is
1924// default-initialized, which leaves blueprint.baseModuleContext set to nil, so methods that are
1925// delegated to it will panic.
1926func ModuleInstallPathContextForTesting(config Config) ModuleInstallPathContext {
1927 ctx := &testModuleInstallPathContext{}
1928 ctx.config = config
1929 ctx.os = Android
1930 return ctx
1931}
1932
Colin Cross43f08db2018-11-12 10:13:39 -08001933// Rel performs the same function as filepath.Rel, but reports errors to a PathContext, and reports an error if
1934// targetPath is not inside basePath.
1935func Rel(ctx PathContext, basePath string, targetPath string) string {
1936 rel, isRel := MaybeRel(ctx, basePath, targetPath)
1937 if !isRel {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001938 ReportPathErrorf(ctx, "path %q is not under path %q", targetPath, basePath)
Colin Cross43f08db2018-11-12 10:13:39 -08001939 return ""
1940 }
1941 return rel
1942}
1943
1944// MaybeRel performs the same function as filepath.Rel, but reports errors to a PathContext, and returns false if
1945// targetPath is not inside basePath.
1946func MaybeRel(ctx PathContext, basePath string, targetPath string) (string, bool) {
Dan Willemsen633c5022019-04-12 11:11:38 -07001947 rel, isRel, err := maybeRelErr(basePath, targetPath)
1948 if err != nil {
1949 reportPathError(ctx, err)
1950 }
1951 return rel, isRel
1952}
1953
1954func maybeRelErr(basePath string, targetPath string) (string, bool, error) {
Colin Cross43f08db2018-11-12 10:13:39 -08001955 // filepath.Rel returns an error if one path is absolute and the other is not, handle that case first.
1956 if filepath.IsAbs(basePath) != filepath.IsAbs(targetPath) {
Dan Willemsen633c5022019-04-12 11:11:38 -07001957 return "", false, nil
Colin Cross43f08db2018-11-12 10:13:39 -08001958 }
1959 rel, err := filepath.Rel(basePath, targetPath)
1960 if err != nil {
Dan Willemsen633c5022019-04-12 11:11:38 -07001961 return "", false, err
Colin Cross43f08db2018-11-12 10:13:39 -08001962 } else if rel == ".." || strings.HasPrefix(rel, "../") || strings.HasPrefix(rel, "/") {
Dan Willemsen633c5022019-04-12 11:11:38 -07001963 return "", false, nil
Colin Cross43f08db2018-11-12 10:13:39 -08001964 }
Dan Willemsen633c5022019-04-12 11:11:38 -07001965 return rel, true, nil
Colin Cross43f08db2018-11-12 10:13:39 -08001966}
Colin Cross988414c2020-01-11 01:11:46 +00001967
1968// Writes a file to the output directory. Attempting to write directly to the output directory
1969// will fail due to the sandbox of the soong_build process.
1970func WriteFileToOutputDir(path WritablePath, data []byte, perm os.FileMode) error {
1971 return ioutil.WriteFile(absolutePath(path.String()), data, perm)
1972}
1973
Liz Kammer2dd9ca42020-11-25 16:06:39 -08001974func RemoveAllOutputDir(path WritablePath) error {
1975 return os.RemoveAll(absolutePath(path.String()))
1976}
1977
1978func CreateOutputDirIfNonexistent(path WritablePath, perm os.FileMode) error {
1979 dir := absolutePath(path.String())
1980 if _, err := os.Stat(dir); os.IsNotExist(err) {
1981 return os.MkdirAll(dir, os.ModePerm)
1982 } else {
1983 return err
1984 }
1985}
1986
Colin Cross988414c2020-01-11 01:11:46 +00001987func absolutePath(path string) string {
1988 if filepath.IsAbs(path) {
1989 return path
1990 }
1991 return filepath.Join(absSrcDir, path)
1992}
Chris Parsons216e10a2020-07-09 17:12:52 -04001993
1994// A DataPath represents the path of a file to be used as data, for example
1995// a test library to be installed alongside a test.
1996// The data file should be installed (copied from `<SrcPath>`) to
1997// `<install_root>/<RelativeInstallPath>/<filename>`, or
1998// `<install_root>/<filename>` if RelativeInstallPath is empty.
1999type DataPath struct {
2000 // The path of the data file that should be copied into the data directory
2001 SrcPath Path
2002 // The install path of the data file, relative to the install root.
2003 RelativeInstallPath string
2004}
Colin Crossdcf71b22021-02-01 13:59:03 -08002005
2006// PathsIfNonNil returns a Paths containing only the non-nil input arguments.
2007func PathsIfNonNil(paths ...Path) Paths {
2008 if len(paths) == 0 {
2009 // Fast path for empty argument list
2010 return nil
2011 } else if len(paths) == 1 {
2012 // Fast path for a single argument
2013 if paths[0] != nil {
2014 return paths
2015 } else {
2016 return nil
2017 }
2018 }
2019 ret := make(Paths, 0, len(paths))
2020 for _, path := range paths {
2021 if path != nil {
2022 ret = append(ret, path)
2023 }
2024 }
2025 if len(ret) == 0 {
2026 return nil
2027 }
2028 return ret
2029}