blob: f648c557b5147a4ea219ba5e11d4f7d60fa5810a [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.
184 buildDir() string
185
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
Liz Kammer356f7d42021-01-26 09:18:53 -0500343 OtherModuleName(m blueprint.Module) string
344 OtherModuleDir(m blueprint.Module) string
345}
346
347// BazelLabelForModuleDeps returns a Bazel-compatible label for the requested modules which
348// correspond to dependencies on the module within the given ctx.
349func BazelLabelForModuleDeps(ctx BazelConversionPathContext, modules []string) bazel.LabelList {
350 var labels bazel.LabelList
351 for _, module := range modules {
352 bpText := module
353 if m := SrcIsModule(module); m == "" {
354 module = ":" + module
355 }
356 if m, t := SrcIsModuleWithTag(module); m != "" {
357 l := getOtherModuleLabel(ctx, m, t)
358 l.Bp_text = bpText
359 labels.Includes = append(labels.Includes, l)
360 } else {
361 ctx.ModuleErrorf("%q, is not a module reference", module)
362 }
363 }
364 return labels
365}
366
367// BazelLabelForModuleSrc returns bazel.LabelList with paths rooted from the module's local source
368// directory. It expands globs, and resolves references to modules using the ":name" syntax to
369// bazel-compatible labels. Properties passed as the paths or excludes argument must have been
370// annotated with struct tag `android:"path"` so that dependencies on other modules will have
371// already been handled by the path_properties mutator.
372func BazelLabelForModuleSrc(ctx BazelConversionPathContext, paths []string) bazel.LabelList {
373 return BazelLabelForModuleSrcExcludes(ctx, paths, []string(nil))
374}
375
376// BazelLabelForModuleSrcExcludes returns bazel.LabelList with paths rooted from the module's local
377// source directory, excluding labels included in the excludes argument. It expands globs, and
378// resolves references to modules using the ":name" syntax to bazel-compatible labels. Properties
379// passed as the paths or excludes argument must have been annotated with struct tag
380// `android:"path"` so that dependencies on other modules will have already been handled by the
381// path_properties mutator.
382func BazelLabelForModuleSrcExcludes(ctx BazelConversionPathContext, paths, excludes []string) bazel.LabelList {
383 excludeLabels := expandSrcsForBazel(ctx, excludes, []string(nil))
384 excluded := make([]string, 0, len(excludeLabels.Includes))
385 for _, e := range excludeLabels.Includes {
386 excluded = append(excluded, e.Label)
387 }
388 labels := expandSrcsForBazel(ctx, paths, excluded)
389 labels.Excludes = excludeLabels.Includes
390 return labels
391}
392
393// expandSrcsForBazel returns bazel.LabelList with paths rooted from the module's local
394// source directory, excluding labels included in the excludes argument. It expands globs, and
395// resolves references to modules using the ":name" syntax to bazel-compatible labels. Properties
396// passed as the paths or excludes argument must have been annotated with struct tag
397// `android:"path"` so that dependencies on other modules will have already been handled by the
398// path_properties mutator.
399func expandSrcsForBazel(ctx BazelConversionPathContext, paths, expandedExcludes []string) bazel.LabelList {
Liz Kammerebfcf672021-02-16 15:00:05 -0500400 if paths == nil {
401 return bazel.LabelList{}
402 }
Liz Kammer356f7d42021-01-26 09:18:53 -0500403 labels := bazel.LabelList{
404 Includes: []bazel.Label{},
405 }
406 for _, p := range paths {
407 if m, tag := SrcIsModuleWithTag(p); m != "" {
408 l := getOtherModuleLabel(ctx, m, tag)
409 if !InList(l.Label, expandedExcludes) {
410 l.Bp_text = fmt.Sprintf(":%s", m)
411 labels.Includes = append(labels.Includes, l)
412 }
413 } else {
414 var expandedPaths []bazel.Label
415 if pathtools.IsGlob(p) {
416 globbedPaths := GlobFiles(ctx, pathForModuleSrc(ctx, p).String(), expandedExcludes)
417 globbedPaths = PathsWithModuleSrcSubDir(ctx, globbedPaths, "")
418 for _, path := range globbedPaths {
419 s := path.Rel()
420 expandedPaths = append(expandedPaths, bazel.Label{Label: s})
421 }
422 } else {
423 if !InList(p, expandedExcludes) {
424 expandedPaths = append(expandedPaths, bazel.Label{Label: p})
425 }
426 }
427 labels.Includes = append(labels.Includes, expandedPaths...)
428 }
429 }
430 return labels
431}
432
433// getOtherModuleLabel returns a bazel.Label for the given dependency/tag combination for the
434// module. The label will be relative to the current directory if appropriate. The dependency must
435// already be resolved by either deps mutator or path deps mutator.
436func getOtherModuleLabel(ctx BazelConversionPathContext, dep, tag string) bazel.Label {
437 m, _ := ctx.GetDirectDep(dep)
Liz Kammerbdc60992021-02-24 16:55:11 -0500438 otherLabel := bazelModuleLabel(ctx, m, tag)
439 label := bazelModuleLabel(ctx, ctx.Module(), "")
440 if samePackage(label, otherLabel) {
441 otherLabel = bazelShortLabel(otherLabel)
Liz Kammer356f7d42021-01-26 09:18:53 -0500442 }
Liz Kammerbdc60992021-02-24 16:55:11 -0500443
444 return bazel.Label{
445 Label: otherLabel,
446 }
447}
448
449func bazelModuleLabel(ctx BazelConversionPathContext, module blueprint.Module, tag string) string {
450 // TODO(b/165114590): Convert tag (":name{.tag}") to corresponding Bazel implicit output targets.
451 b, ok := module.(Bazelable)
452 // TODO(b/181155349): perhaps return an error here if the module can't be/isn't being converted
453 if !ok || !b.ConvertedToBazel() {
454 return bp2buildModuleLabel(ctx, module)
455 }
456 return b.GetBazelLabel(ctx, module)
457}
458
459func bazelShortLabel(label string) string {
460 i := strings.Index(label, ":")
461 return label[i:]
462}
463
464func bazelPackage(label string) string {
465 i := strings.Index(label, ":")
466 return label[0:i]
467}
468
469func samePackage(label1, label2 string) bool {
470 return bazelPackage(label1) == bazelPackage(label2)
471}
472
473func bp2buildModuleLabel(ctx BazelConversionPathContext, module blueprint.Module) string {
474 moduleName := ctx.OtherModuleName(module)
475 moduleDir := ctx.OtherModuleDir(module)
476 return fmt.Sprintf("//%s:%s", moduleDir, moduleName)
Liz Kammer356f7d42021-01-26 09:18:53 -0500477}
478
Ulya Trafimovich4d2eeed2019-11-08 10:54:21 +0000479// OutputPaths is a slice of OutputPath objects, with helpers to operate on the collection.
480type OutputPaths []OutputPath
481
482// Paths returns the OutputPaths as a Paths
483func (p OutputPaths) Paths() Paths {
484 if p == nil {
485 return nil
486 }
487 ret := make(Paths, len(p))
488 for i, path := range p {
489 ret[i] = path
490 }
491 return ret
492}
493
494// Strings returns the string forms of the writable paths.
495func (p OutputPaths) Strings() []string {
496 if p == nil {
497 return nil
498 }
499 ret := make([]string, len(p))
500 for i, path := range p {
501 ret[i] = path.String()
502 }
503 return ret
504}
505
Liz Kammera830f3a2020-11-10 10:50:34 -0800506// Expands Paths to a SourceFileProducer or OutputFileProducer module dependency referenced via ":name" or ":name{.tag}" syntax.
507// If the dependency is not found, a missingErrorDependency is returned.
508// If the module dependency is not a SourceFileProducer or OutputFileProducer, appropriate errors will be returned.
509func getPathsFromModuleDep(ctx ModuleWithDepsPathContext, path, moduleName, tag string) (Paths, error) {
510 module := ctx.GetDirectDepWithTag(moduleName, sourceOrOutputDepTag(tag))
511 if module == nil {
512 return nil, missingDependencyError{[]string{moduleName}}
513 }
514 if outProducer, ok := module.(OutputFileProducer); ok {
515 outputFiles, err := outProducer.OutputFiles(tag)
516 if err != nil {
517 return nil, fmt.Errorf("path dependency %q: %s", path, err)
518 }
519 return outputFiles, nil
520 } else if tag != "" {
521 return nil, fmt.Errorf("path dependency %q is not an output file producing module", path)
522 } else if srcProducer, ok := module.(SourceFileProducer); ok {
523 return srcProducer.Srcs(), nil
524 } else {
525 return nil, fmt.Errorf("path dependency %q is not a source file producing module", path)
526 }
527}
528
Colin Crossba71a3f2019-03-18 12:12:48 -0700529// PathsAndMissingDepsForModuleSrcExcludes returns Paths rooted from the module's local source directory, excluding
Colin Cross41955e82019-05-29 14:40:35 -0700530// paths listed in the excludes arguments, and a list of missing dependencies. It expands globs, references to
531// SourceFileProducer modules using the ":name" syntax, and references to OutputFileProducer modules using the
532// ":name{.tag}" syntax. Properties passed as the paths or excludes argument must have been annotated with struct tag
533// `android:"path"` so that dependencies on SourceFileProducer modules will have already been handled by the
534// path_properties mutator. If ctx.Config().AllowMissingDependencies() is true then any missing SourceFileProducer or
535// OutputFileProducer dependencies will be returned, and they will NOT cause the module to be marked as having missing
536// dependencies.
Liz Kammera830f3a2020-11-10 10:50:34 -0800537func PathsAndMissingDepsForModuleSrcExcludes(ctx ModuleWithDepsPathContext, paths, excludes []string) (Paths, []string) {
Colin Cross8a497952019-03-05 22:25:09 -0800538 prefix := pathForModuleSrc(ctx).String()
539
540 var expandedExcludes []string
541 if excludes != nil {
542 expandedExcludes = make([]string, 0, len(excludes))
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700543 }
Colin Cross8a497952019-03-05 22:25:09 -0800544
Colin Crossba71a3f2019-03-18 12:12:48 -0700545 var missingExcludeDeps []string
546
Colin Cross8a497952019-03-05 22:25:09 -0800547 for _, e := range excludes {
Colin Cross41955e82019-05-29 14:40:35 -0700548 if m, t := SrcIsModuleWithTag(e); m != "" {
Liz Kammera830f3a2020-11-10 10:50:34 -0800549 modulePaths, err := getPathsFromModuleDep(ctx, e, m, t)
550 if m, ok := err.(missingDependencyError); ok {
551 missingExcludeDeps = append(missingExcludeDeps, m.missingDeps...)
552 } else if err != nil {
553 reportPathError(ctx, err)
Colin Cross8a497952019-03-05 22:25:09 -0800554 } else {
Liz Kammera830f3a2020-11-10 10:50:34 -0800555 expandedExcludes = append(expandedExcludes, modulePaths.Strings()...)
Colin Cross8a497952019-03-05 22:25:09 -0800556 }
557 } else {
558 expandedExcludes = append(expandedExcludes, filepath.Join(prefix, e))
559 }
560 }
561
562 if paths == nil {
Colin Crossba71a3f2019-03-18 12:12:48 -0700563 return nil, missingExcludeDeps
Colin Cross8a497952019-03-05 22:25:09 -0800564 }
565
Colin Crossba71a3f2019-03-18 12:12:48 -0700566 var missingDeps []string
567
Colin Cross8a497952019-03-05 22:25:09 -0800568 expandedSrcFiles := make(Paths, 0, len(paths))
569 for _, s := range paths {
570 srcFiles, err := expandOneSrcPath(ctx, s, expandedExcludes)
571 if depErr, ok := err.(missingDependencyError); ok {
Colin Crossba71a3f2019-03-18 12:12:48 -0700572 missingDeps = append(missingDeps, depErr.missingDeps...)
Colin Cross8a497952019-03-05 22:25:09 -0800573 } else if err != nil {
574 reportPathError(ctx, err)
575 }
576 expandedSrcFiles = append(expandedSrcFiles, srcFiles...)
577 }
Colin Crossba71a3f2019-03-18 12:12:48 -0700578
579 return expandedSrcFiles, append(missingDeps, missingExcludeDeps...)
Colin Cross8a497952019-03-05 22:25:09 -0800580}
581
582type missingDependencyError struct {
583 missingDeps []string
584}
585
586func (e missingDependencyError) Error() string {
587 return "missing dependencies: " + strings.Join(e.missingDeps, ", ")
588}
589
Liz Kammera830f3a2020-11-10 10:50:34 -0800590// Expands one path string to Paths rooted from the module's local source
591// directory, excluding those listed in the expandedExcludes.
592// Expands globs, references to SourceFileProducer or OutputFileProducer modules using the ":name" and ":name{.tag}" syntax.
593func expandOneSrcPath(ctx ModuleWithDepsPathContext, sPath string, expandedExcludes []string) (Paths, error) {
Jooyung Han7607dd32020-07-05 10:23:14 +0900594 excludePaths := func(paths Paths) Paths {
595 if len(expandedExcludes) == 0 {
596 return paths
597 }
598 remainder := make(Paths, 0, len(paths))
599 for _, p := range paths {
600 if !InList(p.String(), expandedExcludes) {
601 remainder = append(remainder, p)
602 }
603 }
604 return remainder
605 }
Liz Kammera830f3a2020-11-10 10:50:34 -0800606 if m, t := SrcIsModuleWithTag(sPath); m != "" {
607 modulePaths, err := getPathsFromModuleDep(ctx, sPath, m, t)
608 if err != nil {
609 return nil, err
Colin Cross8a497952019-03-05 22:25:09 -0800610 } else {
Liz Kammera830f3a2020-11-10 10:50:34 -0800611 return excludePaths(modulePaths), nil
Colin Cross8a497952019-03-05 22:25:09 -0800612 }
Liz Kammera830f3a2020-11-10 10:50:34 -0800613 } else if pathtools.IsGlob(sPath) {
614 paths := GlobFiles(ctx, pathForModuleSrc(ctx, sPath).String(), expandedExcludes)
Colin Cross8a497952019-03-05 22:25:09 -0800615 return PathsWithModuleSrcSubDir(ctx, paths, ""), nil
616 } else {
Liz Kammera830f3a2020-11-10 10:50:34 -0800617 p := pathForModuleSrc(ctx, sPath)
Colin Cross988414c2020-01-11 01:11:46 +0000618 if exists, _, err := ctx.Config().fs.Exists(p.String()); err != nil {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +0100619 ReportPathErrorf(ctx, "%s: %s", p, err.Error())
Pedro Loureiro5d190cc2021-02-15 15:41:33 +0000620 } else if !exists && !ctx.Config().TestAllowNonExistentPaths {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +0100621 ReportPathErrorf(ctx, "module source path %q does not exist", p)
Colin Cross8a497952019-03-05 22:25:09 -0800622 }
623
Jooyung Han7607dd32020-07-05 10:23:14 +0900624 if InList(p.String(), expandedExcludes) {
Colin Cross8a497952019-03-05 22:25:09 -0800625 return nil, nil
626 }
627 return Paths{p}, nil
628 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700629}
630
631// pathsForModuleSrcFromFullPath returns Paths rooted from the module's local
632// source directory, but strip the local source directory from the beginning of
Dan Willemsen540a78c2018-02-26 21:50:08 -0800633// each string. If incDirs is false, strip paths with a trailing '/' from the list.
Colin Crossfe4bc362018-09-12 10:02:13 -0700634// It intended for use in globs that only list files that exist, so it allows '$' in
635// filenames.
Liz Kammera830f3a2020-11-10 10:50:34 -0800636func pathsForModuleSrcFromFullPath(ctx EarlyModulePathContext, paths []string, incDirs bool) Paths {
Colin Cross6510f912017-11-29 00:27:14 -0800637 prefix := filepath.Join(ctx.Config().srcDir, ctx.ModuleDir()) + "/"
Colin Cross0f37af02017-09-27 17:42:05 -0700638 if prefix == "./" {
639 prefix = ""
640 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700641 ret := make(Paths, 0, len(paths))
642 for _, p := range paths {
Dan Willemsen540a78c2018-02-26 21:50:08 -0800643 if !incDirs && strings.HasSuffix(p, "/") {
644 continue
645 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700646 path := filepath.Clean(p)
647 if !strings.HasPrefix(path, prefix) {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +0100648 ReportPathErrorf(ctx, "Path %q is not in module source directory %q", p, prefix)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700649 continue
650 }
Colin Crosse3924e12018-08-15 20:18:53 -0700651
Colin Crossfe4bc362018-09-12 10:02:13 -0700652 srcPath, err := safePathForSource(ctx, ctx.ModuleDir(), path[len(prefix):])
Colin Crosse3924e12018-08-15 20:18:53 -0700653 if err != nil {
654 reportPathError(ctx, err)
655 continue
656 }
657
Colin Cross07e51612019-03-05 12:46:40 -0800658 srcPath.basePath.rel = srcPath.path
Colin Crosse3924e12018-08-15 20:18:53 -0700659
Colin Cross07e51612019-03-05 12:46:40 -0800660 ret = append(ret, srcPath)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700661 }
662 return ret
663}
664
Liz Kammera830f3a2020-11-10 10:50:34 -0800665// PathsWithOptionalDefaultForModuleSrc returns Paths rooted from the module's local source
666// directory. If input is nil, use the default if it exists. If input is empty, returns nil.
667func PathsWithOptionalDefaultForModuleSrc(ctx ModuleMissingDepsPathContext, input []string, def string) Paths {
Colin Cross0ddae7f2019-02-07 15:30:01 -0800668 if input != nil {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700669 return PathsForModuleSrc(ctx, input)
670 }
671 // Use Glob so that if the default doesn't exist, a dependency is added so that when it
672 // is created, we're run again.
Colin Cross6510f912017-11-29 00:27:14 -0800673 path := filepath.Join(ctx.Config().srcDir, ctx.ModuleDir(), def)
Liz Kammera830f3a2020-11-10 10:50:34 -0800674 return Glob(ctx, path, nil)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700675}
676
677// Strings returns the Paths in string form
678func (p Paths) Strings() []string {
679 if p == nil {
680 return nil
681 }
682 ret := make([]string, len(p))
683 for i, path := range p {
684 ret[i] = path.String()
685 }
686 return ret
687}
688
Colin Crossc0efd1d2020-07-03 11:56:24 -0700689func CopyOfPaths(paths Paths) Paths {
690 return append(Paths(nil), paths...)
691}
692
Colin Crossb6715442017-10-24 11:13:31 -0700693// FirstUniquePaths returns all unique elements of a Paths, keeping the first copy of each. It
694// modifies the Paths slice contents in place, and returns a subslice of the original slice.
Dan Willemsenfe92c962017-08-29 12:28:37 -0700695func FirstUniquePaths(list Paths) Paths {
Colin Cross27027c72020-02-28 15:34:17 -0800696 // 128 was chosen based on BenchmarkFirstUniquePaths results.
697 if len(list) > 128 {
698 return firstUniquePathsMap(list)
699 }
700 return firstUniquePathsList(list)
701}
702
Colin Crossc0efd1d2020-07-03 11:56:24 -0700703// SortedUniquePaths returns all unique elements of a Paths in sorted order. It modifies the
704// Paths slice contents in place, and returns a subslice of the original slice.
Jiyong Park33c77362020-05-29 22:00:16 +0900705func SortedUniquePaths(list Paths) Paths {
706 unique := FirstUniquePaths(list)
707 sort.Slice(unique, func(i, j int) bool {
708 return unique[i].String() < unique[j].String()
709 })
710 return unique
711}
712
Colin Cross27027c72020-02-28 15:34:17 -0800713func firstUniquePathsList(list Paths) Paths {
Dan Willemsenfe92c962017-08-29 12:28:37 -0700714 k := 0
715outer:
716 for i := 0; i < len(list); i++ {
717 for j := 0; j < k; j++ {
718 if list[i] == list[j] {
719 continue outer
720 }
721 }
722 list[k] = list[i]
723 k++
724 }
725 return list[:k]
726}
727
Colin Cross27027c72020-02-28 15:34:17 -0800728func firstUniquePathsMap(list Paths) Paths {
729 k := 0
730 seen := make(map[Path]bool, len(list))
731 for i := 0; i < len(list); i++ {
732 if seen[list[i]] {
733 continue
734 }
735 seen[list[i]] = true
736 list[k] = list[i]
737 k++
738 }
739 return list[:k]
740}
741
Colin Cross5d583952020-11-24 16:21:24 -0800742// FirstUniqueInstallPaths returns all unique elements of an InstallPaths, keeping the first copy of each. It
743// modifies the InstallPaths slice contents in place, and returns a subslice of the original slice.
744func FirstUniqueInstallPaths(list InstallPaths) InstallPaths {
745 // 128 was chosen based on BenchmarkFirstUniquePaths results.
746 if len(list) > 128 {
747 return firstUniqueInstallPathsMap(list)
748 }
749 return firstUniqueInstallPathsList(list)
750}
751
752func firstUniqueInstallPathsList(list InstallPaths) InstallPaths {
753 k := 0
754outer:
755 for i := 0; i < len(list); i++ {
756 for j := 0; j < k; j++ {
757 if list[i] == list[j] {
758 continue outer
759 }
760 }
761 list[k] = list[i]
762 k++
763 }
764 return list[:k]
765}
766
767func firstUniqueInstallPathsMap(list InstallPaths) InstallPaths {
768 k := 0
769 seen := make(map[InstallPath]bool, len(list))
770 for i := 0; i < len(list); i++ {
771 if seen[list[i]] {
772 continue
773 }
774 seen[list[i]] = true
775 list[k] = list[i]
776 k++
777 }
778 return list[:k]
779}
780
Colin Crossb6715442017-10-24 11:13:31 -0700781// LastUniquePaths returns all unique elements of a Paths, keeping the last copy of each. It
782// modifies the Paths slice contents in place, and returns a subslice of the original slice.
783func LastUniquePaths(list Paths) Paths {
784 totalSkip := 0
785 for i := len(list) - 1; i >= totalSkip; i-- {
786 skip := 0
787 for j := i - 1; j >= totalSkip; j-- {
788 if list[i] == list[j] {
789 skip++
790 } else {
791 list[j+skip] = list[j]
792 }
793 }
794 totalSkip += skip
795 }
796 return list[totalSkip:]
797}
798
Colin Crossa140bb02018-04-17 10:52:26 -0700799// ReversePaths returns a copy of a Paths in reverse order.
800func ReversePaths(list Paths) Paths {
801 if list == nil {
802 return nil
803 }
804 ret := make(Paths, len(list))
805 for i := range list {
806 ret[i] = list[len(list)-1-i]
807 }
808 return ret
809}
810
Jeff Gaston294356f2017-09-27 17:05:30 -0700811func indexPathList(s Path, list []Path) int {
812 for i, l := range list {
813 if l == s {
814 return i
815 }
816 }
817
818 return -1
819}
820
821func inPathList(p Path, list []Path) bool {
822 return indexPathList(p, list) != -1
823}
824
825func FilterPathList(list []Path, filter []Path) (remainder []Path, filtered []Path) {
Paul Duffin57b9e1d2019-12-13 00:03:35 +0000826 return FilterPathListPredicate(list, func(p Path) bool { return inPathList(p, filter) })
827}
828
829func FilterPathListPredicate(list []Path, predicate func(Path) bool) (remainder []Path, filtered []Path) {
Jeff Gaston294356f2017-09-27 17:05:30 -0700830 for _, l := range list {
Paul Duffin57b9e1d2019-12-13 00:03:35 +0000831 if predicate(l) {
Jeff Gaston294356f2017-09-27 17:05:30 -0700832 filtered = append(filtered, l)
833 } else {
834 remainder = append(remainder, l)
835 }
836 }
837
838 return
839}
840
Colin Cross93e85952017-08-15 13:34:18 -0700841// HasExt returns true of any of the paths have extension ext, otherwise false
842func (p Paths) HasExt(ext string) bool {
843 for _, path := range p {
844 if path.Ext() == ext {
845 return true
846 }
847 }
848
849 return false
850}
851
852// FilterByExt returns the subset of the paths that have extension ext
853func (p Paths) FilterByExt(ext string) Paths {
854 ret := make(Paths, 0, len(p))
855 for _, path := range p {
856 if path.Ext() == ext {
857 ret = append(ret, path)
858 }
859 }
860 return ret
861}
862
863// FilterOutByExt returns the subset of the paths that do not have extension ext
864func (p Paths) FilterOutByExt(ext string) Paths {
865 ret := make(Paths, 0, len(p))
866 for _, path := range p {
867 if path.Ext() != ext {
868 ret = append(ret, path)
869 }
870 }
871 return ret
872}
873
Colin Cross5e6cfbe2017-11-03 15:20:35 -0700874// DirectorySortedPaths is a slice of paths that are sorted such that all files in a directory
875// (including subdirectories) are in a contiguous subslice of the list, and can be found in
876// O(log(N)) time using a binary search on the directory prefix.
877type DirectorySortedPaths Paths
878
879func PathsToDirectorySortedPaths(paths Paths) DirectorySortedPaths {
880 ret := append(DirectorySortedPaths(nil), paths...)
881 sort.Slice(ret, func(i, j int) bool {
882 return ret[i].String() < ret[j].String()
883 })
884 return ret
885}
886
887// PathsInDirectory returns a subslice of the DirectorySortedPaths as a Paths that contains all entries
888// that are in the specified directory and its subdirectories.
889func (p DirectorySortedPaths) PathsInDirectory(dir string) Paths {
890 prefix := filepath.Clean(dir) + "/"
891 start := sort.Search(len(p), func(i int) bool {
892 return prefix < p[i].String()
893 })
894
895 ret := p[start:]
896
897 end := sort.Search(len(ret), func(i int) bool {
898 return !strings.HasPrefix(ret[i].String(), prefix)
899 })
900
901 ret = ret[:end]
902
903 return Paths(ret)
904}
905
Alex Humesky29e3bbe2020-11-20 21:30:13 -0500906// WritablePaths is a slice of WritablePath, used for multiple outputs.
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700907type WritablePaths []WritablePath
908
909// Strings returns the string forms of the writable paths.
910func (p WritablePaths) Strings() []string {
911 if p == nil {
912 return nil
913 }
914 ret := make([]string, len(p))
915 for i, path := range p {
916 ret[i] = path.String()
917 }
918 return ret
919}
920
Colin Cross3bc7ffa2017-11-22 16:19:37 -0800921// Paths returns the WritablePaths as a Paths
922func (p WritablePaths) Paths() Paths {
923 if p == nil {
924 return nil
925 }
926 ret := make(Paths, len(p))
927 for i, path := range p {
928 ret[i] = path
929 }
930 return ret
931}
932
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700933type basePath struct {
934 path string
935 config Config
Colin Crossfaeb7aa2017-02-01 14:12:44 -0800936 rel string
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700937}
938
939func (p basePath) Ext() string {
940 return filepath.Ext(p.path)
941}
942
Colin Cross4f6fc9c2016-10-26 10:05:25 -0700943func (p basePath) Base() string {
944 return filepath.Base(p.path)
945}
946
Colin Crossfaeb7aa2017-02-01 14:12:44 -0800947func (p basePath) Rel() string {
948 if p.rel != "" {
949 return p.rel
950 }
951 return p.path
952}
953
Colin Cross0875c522017-11-28 17:34:01 -0800954func (p basePath) String() string {
955 return p.path
956}
957
Colin Cross0db55682017-12-05 15:36:55 -0800958func (p basePath) withRel(rel string) basePath {
959 p.path = filepath.Join(p.path, rel)
960 p.rel = rel
961 return p
962}
963
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700964// SourcePath is a Path representing a file path rooted from SrcDir
965type SourcePath struct {
966 basePath
967}
968
969var _ Path = SourcePath{}
970
Colin Cross0db55682017-12-05 15:36:55 -0800971func (p SourcePath) withRel(rel string) SourcePath {
972 p.basePath = p.basePath.withRel(rel)
973 return p
974}
975
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700976// safePathForSource is for paths that we expect are safe -- only for use by go
977// code that is embedding ninja variables in paths
Colin Crossfe4bc362018-09-12 10:02:13 -0700978func safePathForSource(ctx PathContext, pathComponents ...string) (SourcePath, error) {
979 p, err := validateSafePath(pathComponents...)
Colin Crossaabf6792017-11-29 00:27:14 -0800980 ret := SourcePath{basePath{p, ctx.Config(), ""}}
Colin Crossfe4bc362018-09-12 10:02:13 -0700981 if err != nil {
982 return ret, err
983 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700984
Colin Cross7b3dcc32019-01-24 13:14:39 -0800985 // absolute path already checked by validateSafePath
986 if strings.HasPrefix(ret.String(), ctx.Config().buildDir) {
Mikhail Naganovab1f5182019-02-08 13:17:55 -0800987 return ret, fmt.Errorf("source path %q is in output", ret.String())
Colin Cross6e18ca42015-07-14 18:55:36 -0700988 }
989
Colin Crossfe4bc362018-09-12 10:02:13 -0700990 return ret, err
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700991}
992
Colin Cross192e97a2018-02-22 14:21:02 -0800993// pathForSource creates a SourcePath from pathComponents, but does not check that it exists.
994func pathForSource(ctx PathContext, pathComponents ...string) (SourcePath, error) {
Colin Crossc48c1432018-02-23 07:09:01 +0000995 p, err := validatePath(pathComponents...)
996 ret := SourcePath{basePath{p, ctx.Config(), ""}}
Colin Cross94a32102018-02-22 14:21:02 -0800997 if err != nil {
Colin Cross192e97a2018-02-22 14:21:02 -0800998 return ret, err
Colin Cross94a32102018-02-22 14:21:02 -0800999 }
1000
Colin Cross7b3dcc32019-01-24 13:14:39 -08001001 // absolute path already checked by validatePath
1002 if strings.HasPrefix(ret.String(), ctx.Config().buildDir) {
Mikhail Naganovab1f5182019-02-08 13:17:55 -08001003 return ret, fmt.Errorf("source path %q is in output", ret.String())
Colin Crossc48c1432018-02-23 07:09:01 +00001004 }
1005
Colin Cross192e97a2018-02-22 14:21:02 -08001006 return ret, nil
1007}
1008
1009// existsWithDependencies returns true if the path exists, and adds appropriate dependencies to rerun if the
1010// path does not exist.
1011func existsWithDependencies(ctx PathContext, path SourcePath) (exists bool, err error) {
1012 var files []string
1013
1014 if gctx, ok := ctx.(PathGlobContext); ok {
1015 // Use glob to produce proper dependencies, even though we only want
1016 // a single file.
1017 files, err = gctx.GlobWithDeps(path.String(), nil)
1018 } else {
1019 var deps []string
1020 // We cannot add build statements in this context, so we fall back to
1021 // AddNinjaFileDeps
Colin Cross988414c2020-01-11 01:11:46 +00001022 files, deps, err = ctx.Config().fs.Glob(path.String(), nil, pathtools.FollowSymlinks)
Colin Cross192e97a2018-02-22 14:21:02 -08001023 ctx.AddNinjaFileDeps(deps...)
1024 }
1025
1026 if err != nil {
1027 return false, fmt.Errorf("glob: %s", err.Error())
1028 }
1029
1030 return len(files) > 0, nil
1031}
1032
1033// PathForSource joins the provided path components and validates that the result
1034// neither escapes the source dir nor is in the out dir.
1035// On error, it will return a usable, but invalid SourcePath, and report a ModuleError.
1036func PathForSource(ctx PathContext, pathComponents ...string) SourcePath {
1037 path, err := pathForSource(ctx, pathComponents...)
1038 if err != nil {
1039 reportPathError(ctx, err)
1040 }
1041
Colin Crosse3924e12018-08-15 20:18:53 -07001042 if pathtools.IsGlob(path.String()) {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001043 ReportPathErrorf(ctx, "path may not contain a glob: %s", path.String())
Colin Crosse3924e12018-08-15 20:18:53 -07001044 }
1045
Liz Kammera830f3a2020-11-10 10:50:34 -08001046 if modCtx, ok := ctx.(ModuleMissingDepsPathContext); ok && ctx.Config().AllowMissingDependencies() {
Colin Cross192e97a2018-02-22 14:21:02 -08001047 exists, err := existsWithDependencies(ctx, path)
1048 if err != nil {
1049 reportPathError(ctx, err)
1050 }
1051 if !exists {
1052 modCtx.AddMissingDependencies([]string{path.String()})
1053 }
Colin Cross988414c2020-01-11 01:11:46 +00001054 } else if exists, _, err := ctx.Config().fs.Exists(path.String()); err != nil {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001055 ReportPathErrorf(ctx, "%s: %s", path, err.Error())
Pedro Loureiro5d190cc2021-02-15 15:41:33 +00001056 } else if !exists && !ctx.Config().TestAllowNonExistentPaths {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001057 ReportPathErrorf(ctx, "source path %q does not exist", path)
Colin Cross192e97a2018-02-22 14:21:02 -08001058 }
1059 return path
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001060}
1061
Liz Kammer7aa52882021-02-11 09:16:14 -05001062// ExistentPathForSource returns an OptionalPath with the SourcePath, rooted from SrcDir, *not*
1063// rooted from the module's local source directory, if the path exists, or an empty OptionalPath if
1064// it doesn't exist. Dependencies are added so that the ninja file will be regenerated if the state
1065// of the path changes.
Colin Cross32f38982018-02-22 11:47:25 -08001066func ExistentPathForSource(ctx PathContext, pathComponents ...string) OptionalPath {
Colin Cross192e97a2018-02-22 14:21:02 -08001067 path, err := pathForSource(ctx, pathComponents...)
Colin Cross1ccfcc32018-02-22 13:54:26 -08001068 if err != nil {
1069 reportPathError(ctx, err)
1070 return OptionalPath{}
1071 }
Colin Crossc48c1432018-02-23 07:09:01 +00001072
Colin Crosse3924e12018-08-15 20:18:53 -07001073 if pathtools.IsGlob(path.String()) {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001074 ReportPathErrorf(ctx, "path may not contain a glob: %s", path.String())
Colin Crosse3924e12018-08-15 20:18:53 -07001075 return OptionalPath{}
1076 }
1077
Colin Cross192e97a2018-02-22 14:21:02 -08001078 exists, err := existsWithDependencies(ctx, path)
Colin Crossc48c1432018-02-23 07:09:01 +00001079 if err != nil {
1080 reportPathError(ctx, err)
1081 return OptionalPath{}
1082 }
Colin Cross192e97a2018-02-22 14:21:02 -08001083 if !exists {
Colin Crossc48c1432018-02-23 07:09:01 +00001084 return OptionalPath{}
1085 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001086 return OptionalPathForPath(path)
1087}
1088
1089func (p SourcePath) String() string {
1090 return filepath.Join(p.config.srcDir, p.path)
1091}
1092
1093// Join creates a new SourcePath with paths... joined with the current path. The
1094// provided paths... may not use '..' to escape from the current path.
1095func (p SourcePath) Join(ctx PathContext, paths ...string) SourcePath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001096 path, err := validatePath(paths...)
1097 if err != nil {
1098 reportPathError(ctx, err)
1099 }
Colin Cross0db55682017-12-05 15:36:55 -08001100 return p.withRel(path)
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001101}
1102
Colin Cross2fafa3e2019-03-05 12:39:51 -08001103// join is like Join but does less path validation.
1104func (p SourcePath) join(ctx PathContext, paths ...string) SourcePath {
1105 path, err := validateSafePath(paths...)
1106 if err != nil {
1107 reportPathError(ctx, err)
1108 }
1109 return p.withRel(path)
1110}
1111
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001112// OverlayPath returns the overlay for `path' if it exists. This assumes that the
1113// SourcePath is the path to a resource overlay directory.
Liz Kammera830f3a2020-11-10 10:50:34 -08001114func (p SourcePath) OverlayPath(ctx ModuleMissingDepsPathContext, path Path) OptionalPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001115 var relDir string
Colin Cross07e51612019-03-05 12:46:40 -08001116 if srcPath, ok := path.(SourcePath); ok {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001117 relDir = srcPath.path
1118 } else {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001119 ReportPathErrorf(ctx, "Cannot find relative path for %s(%s)", reflect.TypeOf(path).Name(), path)
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001120 return OptionalPath{}
1121 }
1122 dir := filepath.Join(p.config.srcDir, p.path, relDir)
1123 // Use Glob so that we are run again if the directory is added.
Colin Cross7f19f372016-11-01 11:10:25 -07001124 if pathtools.IsGlob(dir) {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001125 ReportPathErrorf(ctx, "Path may not contain a glob: %s", dir)
Dan Willemsen7b310ee2015-12-18 15:11:17 -08001126 }
Colin Cross461b4452018-02-23 09:22:42 -08001127 paths, err := ctx.GlobWithDeps(dir, nil)
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001128 if err != nil {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001129 ReportPathErrorf(ctx, "glob: %s", err.Error())
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001130 return OptionalPath{}
1131 }
1132 if len(paths) == 0 {
1133 return OptionalPath{}
1134 }
Colin Cross43f08db2018-11-12 10:13:39 -08001135 relPath := Rel(ctx, p.config.srcDir, paths[0])
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001136 return OptionalPathForPath(PathForSource(ctx, relPath))
1137}
1138
Colin Cross70dda7e2019-10-01 22:05:35 -07001139// OutputPath is a Path representing an intermediates file path rooted from the build directory
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001140type OutputPath struct {
1141 basePath
Colin Crossd63c9a72020-01-29 16:52:50 -08001142 fullPath string
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001143}
1144
Colin Cross702e0f82017-10-18 17:27:54 -07001145func (p OutputPath) withRel(rel string) OutputPath {
Colin Cross0db55682017-12-05 15:36:55 -08001146 p.basePath = p.basePath.withRel(rel)
Colin Crossd63c9a72020-01-29 16:52:50 -08001147 p.fullPath = filepath.Join(p.fullPath, rel)
Colin Cross702e0f82017-10-18 17:27:54 -07001148 return p
1149}
1150
Colin Cross3063b782018-08-15 11:19:12 -07001151func (p OutputPath) WithoutRel() OutputPath {
1152 p.basePath.rel = filepath.Base(p.basePath.path)
1153 return p
1154}
1155
Paul Duffin9b478b02019-12-10 13:41:51 +00001156func (p OutputPath) buildDir() string {
1157 return p.config.buildDir
1158}
1159
Paul Duffin0267d492021-02-02 10:05:52 +00001160func (p OutputPath) objPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleObjPath {
1161 return PathForModuleObj(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
1162}
1163
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001164var _ Path = OutputPath{}
Paul Duffin9b478b02019-12-10 13:41:51 +00001165var _ WritablePath = OutputPath{}
Paul Duffin0267d492021-02-02 10:05:52 +00001166var _ objPathProvider = OutputPath{}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001167
Chris Parsons8f232a22020-06-23 17:37:05 -04001168// toolDepPath is a Path representing a dependency of the build tool.
1169type toolDepPath struct {
1170 basePath
1171}
1172
1173var _ Path = toolDepPath{}
1174
1175// pathForBuildToolDep returns a toolDepPath representing the given path string.
1176// There is no validation for the path, as it is "trusted": It may fail
1177// normal validation checks. For example, it may be an absolute path.
1178// Only use this function to construct paths for dependencies of the build
1179// tool invocation.
1180func pathForBuildToolDep(ctx PathContext, path string) toolDepPath {
1181 return toolDepPath{basePath{path, ctx.Config(), ""}}
1182}
1183
Jeff Gaston734e3802017-04-10 15:47:24 -07001184// PathForOutput joins the provided paths and returns an OutputPath that is
1185// validated to not escape the build dir.
1186// On error, it will return a usable, but invalid OutputPath, and report a ModuleError.
1187func PathForOutput(ctx PathContext, pathComponents ...string) OutputPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001188 path, err := validatePath(pathComponents...)
1189 if err != nil {
1190 reportPathError(ctx, err)
1191 }
Colin Crossd63c9a72020-01-29 16:52:50 -08001192 fullPath := filepath.Join(ctx.Config().buildDir, path)
1193 path = fullPath[len(fullPath)-len(path):]
1194 return OutputPath{basePath{path, ctx.Config(), ""}, fullPath}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001195}
1196
Colin Cross40e33732019-02-15 11:08:35 -08001197// PathsForOutput returns Paths rooted from buildDir
1198func PathsForOutput(ctx PathContext, paths []string) WritablePaths {
1199 ret := make(WritablePaths, len(paths))
1200 for i, path := range paths {
1201 ret[i] = PathForOutput(ctx, path)
1202 }
1203 return ret
1204}
1205
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001206func (p OutputPath) writablePath() {}
1207
1208func (p OutputPath) String() string {
Colin Crossd63c9a72020-01-29 16:52:50 -08001209 return p.fullPath
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001210}
1211
1212// Join creates a new OutputPath with paths... joined with the current path. The
1213// provided paths... may not use '..' to escape from the current path.
1214func (p OutputPath) Join(ctx PathContext, paths ...string) OutputPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001215 path, err := validatePath(paths...)
1216 if err != nil {
1217 reportPathError(ctx, err)
1218 }
Colin Cross0db55682017-12-05 15:36:55 -08001219 return p.withRel(path)
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001220}
1221
Colin Cross8854a5a2019-02-11 14:14:16 -08001222// ReplaceExtension creates a new OutputPath with the extension replaced with ext.
1223func (p OutputPath) ReplaceExtension(ctx PathContext, ext string) OutputPath {
1224 if strings.Contains(ext, "/") {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001225 ReportPathErrorf(ctx, "extension %q cannot contain /", ext)
Colin Cross8854a5a2019-02-11 14:14:16 -08001226 }
1227 ret := PathForOutput(ctx, pathtools.ReplaceExtension(p.path, ext))
Colin Cross2cdd5df2019-02-25 10:25:24 -08001228 ret.rel = pathtools.ReplaceExtension(p.rel, ext)
Colin Cross8854a5a2019-02-11 14:14:16 -08001229 return ret
1230}
1231
Colin Cross40e33732019-02-15 11:08:35 -08001232// InSameDir creates a new OutputPath from the directory of the current OutputPath joined with the elements in paths.
1233func (p OutputPath) InSameDir(ctx PathContext, paths ...string) OutputPath {
1234 path, err := validatePath(paths...)
1235 if err != nil {
1236 reportPathError(ctx, err)
1237 }
1238
1239 ret := PathForOutput(ctx, filepath.Dir(p.path), path)
Colin Cross2cdd5df2019-02-25 10:25:24 -08001240 ret.rel = filepath.Join(filepath.Dir(p.rel), path)
Colin Cross40e33732019-02-15 11:08:35 -08001241 return ret
1242}
1243
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001244// PathForIntermediates returns an OutputPath representing the top-level
1245// intermediates directory.
1246func PathForIntermediates(ctx PathContext, paths ...string) OutputPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001247 path, err := validatePath(paths...)
1248 if err != nil {
1249 reportPathError(ctx, err)
1250 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001251 return PathForOutput(ctx, ".intermediates", path)
1252}
1253
Colin Cross07e51612019-03-05 12:46:40 -08001254var _ genPathProvider = SourcePath{}
1255var _ objPathProvider = SourcePath{}
1256var _ resPathProvider = SourcePath{}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001257
Colin Cross07e51612019-03-05 12:46:40 -08001258// PathForModuleSrc returns a Path representing the paths... under the
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001259// module's local source directory.
Liz Kammera830f3a2020-11-10 10:50:34 -08001260func PathForModuleSrc(ctx ModuleMissingDepsPathContext, pathComponents ...string) Path {
Colin Cross8a497952019-03-05 22:25:09 -08001261 p, err := validatePath(pathComponents...)
1262 if err != nil {
1263 reportPathError(ctx, err)
Colin Cross192e97a2018-02-22 14:21:02 -08001264 }
Colin Cross8a497952019-03-05 22:25:09 -08001265 paths, err := expandOneSrcPath(ctx, p, nil)
1266 if err != nil {
1267 if depErr, ok := err.(missingDependencyError); ok {
1268 if ctx.Config().AllowMissingDependencies() {
1269 ctx.AddMissingDependencies(depErr.missingDeps)
1270 } else {
1271 ctx.ModuleErrorf(`%s, is the property annotated with android:"path"?`, depErr.Error())
1272 }
1273 } else {
1274 reportPathError(ctx, err)
1275 }
1276 return nil
1277 } else if len(paths) == 0 {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001278 ReportPathErrorf(ctx, "%q produced no files, expected exactly one", p)
Colin Cross8a497952019-03-05 22:25:09 -08001279 return nil
1280 } else if len(paths) > 1 {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001281 ReportPathErrorf(ctx, "%q produced %d files, expected exactly one", p, len(paths))
Colin Cross8a497952019-03-05 22:25:09 -08001282 }
1283 return paths[0]
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001284}
1285
Liz Kammera830f3a2020-11-10 10:50:34 -08001286func pathForModuleSrc(ctx EarlyModulePathContext, paths ...string) SourcePath {
Colin Cross07e51612019-03-05 12:46:40 -08001287 p, err := validatePath(paths...)
1288 if err != nil {
1289 reportPathError(ctx, err)
1290 }
1291
1292 path, err := pathForSource(ctx, ctx.ModuleDir(), p)
1293 if err != nil {
1294 reportPathError(ctx, err)
1295 }
1296
1297 path.basePath.rel = p
1298
1299 return path
1300}
1301
Colin Cross2fafa3e2019-03-05 12:39:51 -08001302// PathsWithModuleSrcSubDir takes a list of Paths and returns a new list of Paths where Rel() on each path
1303// will return the path relative to subDir in the module's source directory. If any input paths are not located
1304// inside subDir then a path error will be reported.
Liz Kammera830f3a2020-11-10 10:50:34 -08001305func PathsWithModuleSrcSubDir(ctx EarlyModulePathContext, paths Paths, subDir string) Paths {
Colin Cross2fafa3e2019-03-05 12:39:51 -08001306 paths = append(Paths(nil), paths...)
Colin Cross07e51612019-03-05 12:46:40 -08001307 subDirFullPath := pathForModuleSrc(ctx, subDir)
Colin Cross2fafa3e2019-03-05 12:39:51 -08001308 for i, path := range paths {
1309 rel := Rel(ctx, subDirFullPath.String(), path.String())
1310 paths[i] = subDirFullPath.join(ctx, rel)
1311 }
1312 return paths
1313}
1314
1315// PathWithModuleSrcSubDir takes a Path and returns a Path where Rel() will return the path relative to subDir in the
1316// 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 -08001317func PathWithModuleSrcSubDir(ctx EarlyModulePathContext, path Path, subDir string) Path {
Colin Cross07e51612019-03-05 12:46:40 -08001318 subDirFullPath := pathForModuleSrc(ctx, subDir)
Colin Cross2fafa3e2019-03-05 12:39:51 -08001319 rel := Rel(ctx, subDirFullPath.String(), path.String())
1320 return subDirFullPath.Join(ctx, rel)
1321}
1322
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001323// OptionalPathForModuleSrc returns an OptionalPath. The OptionalPath contains a
1324// valid path if p is non-nil.
Liz Kammera830f3a2020-11-10 10:50:34 -08001325func OptionalPathForModuleSrc(ctx ModuleMissingDepsPathContext, p *string) OptionalPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001326 if p == nil {
1327 return OptionalPath{}
1328 }
1329 return OptionalPathForPath(PathForModuleSrc(ctx, *p))
1330}
1331
Liz Kammera830f3a2020-11-10 10:50:34 -08001332func (p SourcePath) genPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleGenPath {
Colin Cross7fc17db2017-02-01 14:07:55 -08001333 return PathForModuleGen(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001334}
1335
Liz Kammera830f3a2020-11-10 10:50:34 -08001336func (p SourcePath) objPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleObjPath {
Colin Cross7fc17db2017-02-01 14:07:55 -08001337 return PathForModuleObj(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001338}
1339
Liz Kammera830f3a2020-11-10 10:50:34 -08001340func (p SourcePath) resPathWithName(ctx ModuleOutPathContext, name string) ModuleResPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001341 // TODO: Use full directory if the new ctx is not the current ctx?
1342 return PathForModuleRes(ctx, p.path, name)
1343}
1344
1345// ModuleOutPath is a Path representing a module's output directory.
1346type ModuleOutPath struct {
1347 OutputPath
1348}
1349
1350var _ Path = ModuleOutPath{}
1351
Liz Kammera830f3a2020-11-10 10:50:34 -08001352func (p ModuleOutPath) objPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleObjPath {
Pete Bentleyfcf55bf2019-08-16 20:14:32 +01001353 return PathForModuleObj(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
1354}
1355
Liz Kammera830f3a2020-11-10 10:50:34 -08001356// ModuleOutPathContext Subset of ModuleContext functions necessary for output path methods.
1357type ModuleOutPathContext interface {
1358 PathContext
1359
1360 ModuleName() string
1361 ModuleDir() string
1362 ModuleSubDir() string
1363}
1364
1365func pathForModuleOut(ctx ModuleOutPathContext) OutputPath {
Colin Cross702e0f82017-10-18 17:27:54 -07001366 return PathForOutput(ctx, ".intermediates", ctx.ModuleDir(), ctx.ModuleName(), ctx.ModuleSubDir())
1367}
1368
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001369type BazelOutPath struct {
1370 OutputPath
1371}
1372
1373var _ Path = BazelOutPath{}
1374var _ objPathProvider = BazelOutPath{}
1375
Liz Kammera830f3a2020-11-10 10:50:34 -08001376func (p BazelOutPath) objPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleObjPath {
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001377 return PathForModuleObj(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
1378}
1379
Logan Chien7eefdc42018-07-11 18:10:41 +08001380// PathForVndkRefAbiDump returns an OptionalPath representing the path of the
1381// reference abi dump for the given module. This is not guaranteed to be valid.
Liz Kammera830f3a2020-11-10 10:50:34 -08001382func PathForVndkRefAbiDump(ctx ModuleInstallPathContext, version, fileName string,
Hsin-Yi Chen53489642019-07-31 17:10:45 +08001383 isNdk, isLlndkOrVndk, isGzip bool) OptionalPath {
Logan Chien7eefdc42018-07-11 18:10:41 +08001384
Jayant Chowdharyac066c62018-02-20 10:53:31 -08001385 arches := ctx.DeviceConfig().Arches()
Logan Chien7eefdc42018-07-11 18:10:41 +08001386 if len(arches) == 0 {
1387 panic("device build with no primary arch")
1388 }
Jayant Chowdharyac066c62018-02-20 10:53:31 -08001389 currentArch := ctx.Arch()
1390 archNameAndVariant := currentArch.ArchType.String()
1391 if currentArch.ArchVariant != "" {
1392 archNameAndVariant += "_" + currentArch.ArchVariant
1393 }
Logan Chien5237bed2018-07-11 17:15:57 +08001394
1395 var dirName string
Hsin-Yi Chen53489642019-07-31 17:10:45 +08001396 if isNdk {
Logan Chien5237bed2018-07-11 17:15:57 +08001397 dirName = "ndk"
Hsin-Yi Chen53489642019-07-31 17:10:45 +08001398 } else if isLlndkOrVndk {
Logan Chien5237bed2018-07-11 17:15:57 +08001399 dirName = "vndk"
Logan Chien41eabe62019-04-10 13:33:58 +08001400 } else {
1401 dirName = "platform" // opt-in libs
Jayant Chowdhary3e231fd2017-02-08 13:45:53 -08001402 }
Logan Chien5237bed2018-07-11 17:15:57 +08001403
Jayant Chowdhary34ce67d2018-03-08 11:00:50 -08001404 binderBitness := ctx.DeviceConfig().BinderBitness()
Logan Chien7eefdc42018-07-11 18:10:41 +08001405
1406 var ext string
1407 if isGzip {
1408 ext = ".lsdump.gz"
1409 } else {
1410 ext = ".lsdump"
1411 }
1412
1413 return ExistentPathForSource(ctx, "prebuilts", "abi-dumps", dirName,
1414 version, binderBitness, archNameAndVariant, "source-based",
1415 fileName+ext)
Jayant Chowdhary3e231fd2017-02-08 13:45:53 -08001416}
1417
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001418// PathForBazelOut returns a Path representing the paths... under an output directory dedicated to
1419// bazel-owned outputs.
1420func PathForBazelOut(ctx PathContext, paths ...string) BazelOutPath {
1421 execRootPathComponents := append([]string{"execroot", "__main__"}, paths...)
1422 execRootPath := filepath.Join(execRootPathComponents...)
1423 validatedExecRootPath, err := validatePath(execRootPath)
1424 if err != nil {
1425 reportPathError(ctx, err)
1426 }
1427
1428 outputPath := OutputPath{basePath{"", ctx.Config(), ""},
1429 ctx.Config().BazelContext.OutputBase()}
1430
1431 return BazelOutPath{
1432 OutputPath: outputPath.withRel(validatedExecRootPath),
1433 }
1434}
1435
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001436// PathForModuleOut returns a Path representing the paths... under the module's
1437// output directory.
Liz Kammera830f3a2020-11-10 10:50:34 -08001438func PathForModuleOut(ctx ModuleOutPathContext, paths ...string) ModuleOutPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001439 p, err := validatePath(paths...)
1440 if err != nil {
1441 reportPathError(ctx, err)
1442 }
Colin Cross702e0f82017-10-18 17:27:54 -07001443 return ModuleOutPath{
Liz Kammera830f3a2020-11-10 10:50:34 -08001444 OutputPath: pathForModuleOut(ctx).withRel(p),
Colin Cross702e0f82017-10-18 17:27:54 -07001445 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001446}
1447
1448// ModuleGenPath is a Path representing the 'gen' directory in a module's output
1449// directory. Mainly used for generated sources.
1450type ModuleGenPath struct {
1451 ModuleOutPath
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001452}
1453
1454var _ Path = ModuleGenPath{}
1455var _ genPathProvider = ModuleGenPath{}
1456var _ objPathProvider = ModuleGenPath{}
1457
1458// PathForModuleGen returns a Path representing the paths... under the module's
1459// `gen' directory.
Liz Kammera830f3a2020-11-10 10:50:34 -08001460func PathForModuleGen(ctx ModuleOutPathContext, paths ...string) ModuleGenPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001461 p, err := validatePath(paths...)
1462 if err != nil {
1463 reportPathError(ctx, err)
1464 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001465 return ModuleGenPath{
Colin Cross702e0f82017-10-18 17:27:54 -07001466 ModuleOutPath: ModuleOutPath{
Liz Kammera830f3a2020-11-10 10:50:34 -08001467 OutputPath: pathForModuleOut(ctx).withRel("gen").withRel(p),
Colin Cross702e0f82017-10-18 17:27:54 -07001468 },
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001469 }
1470}
1471
Liz Kammera830f3a2020-11-10 10:50:34 -08001472func (p ModuleGenPath) genPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleGenPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001473 // TODO: make a different path for local vs remote generated files?
Dan Willemsen21ec4902016-11-02 20:43:13 -07001474 return PathForModuleGen(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001475}
1476
Liz Kammera830f3a2020-11-10 10:50:34 -08001477func (p ModuleGenPath) objPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleObjPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001478 return PathForModuleObj(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
1479}
1480
1481// ModuleObjPath is a Path representing the 'obj' directory in a module's output
1482// directory. Used for compiled objects.
1483type ModuleObjPath struct {
1484 ModuleOutPath
1485}
1486
1487var _ Path = ModuleObjPath{}
1488
1489// PathForModuleObj returns a Path representing the paths... under the module's
1490// 'obj' directory.
Liz Kammera830f3a2020-11-10 10:50:34 -08001491func PathForModuleObj(ctx ModuleOutPathContext, pathComponents ...string) ModuleObjPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001492 p, err := validatePath(pathComponents...)
1493 if err != nil {
1494 reportPathError(ctx, err)
1495 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001496 return ModuleObjPath{PathForModuleOut(ctx, "obj", p)}
1497}
1498
1499// ModuleResPath is a a Path representing the 'res' directory in a module's
1500// output directory.
1501type ModuleResPath struct {
1502 ModuleOutPath
1503}
1504
1505var _ Path = ModuleResPath{}
1506
1507// PathForModuleRes returns a Path representing the paths... under the module's
1508// 'res' directory.
Liz Kammera830f3a2020-11-10 10:50:34 -08001509func PathForModuleRes(ctx ModuleOutPathContext, pathComponents ...string) ModuleResPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001510 p, err := validatePath(pathComponents...)
1511 if err != nil {
1512 reportPathError(ctx, err)
1513 }
1514
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001515 return ModuleResPath{PathForModuleOut(ctx, "res", p)}
1516}
1517
Colin Cross70dda7e2019-10-01 22:05:35 -07001518// InstallPath is a Path representing a installed file path rooted from the build directory
1519type InstallPath struct {
1520 basePath
Colin Crossff6c33d2019-10-02 16:01:35 -07001521
Jiyong Park957bcd92020-10-20 18:23:33 +09001522 // partitionDir is the part of the InstallPath that is automatically determined according to the context.
1523 // For example, it is host/<os>-<arch> for host modules, and target/product/<device>/<partition> for device modules.
1524 partitionDir string
1525
1526 // makePath indicates whether this path is for Soong (false) or Make (true).
1527 makePath bool
Colin Cross70dda7e2019-10-01 22:05:35 -07001528}
1529
Paul Duffin9b478b02019-12-10 13:41:51 +00001530func (p InstallPath) buildDir() string {
1531 return p.config.buildDir
1532}
1533
Hans MÃ¥nssond3f2bd72020-11-27 12:37:28 +01001534func (p InstallPath) ReplaceExtension(ctx PathContext, ext string) OutputPath {
1535 panic("Not implemented")
1536}
1537
Paul Duffin9b478b02019-12-10 13:41:51 +00001538var _ Path = InstallPath{}
1539var _ WritablePath = InstallPath{}
1540
Colin Cross70dda7e2019-10-01 22:05:35 -07001541func (p InstallPath) writablePath() {}
1542
1543func (p InstallPath) String() string {
Jiyong Park957bcd92020-10-20 18:23:33 +09001544 if p.makePath {
1545 // Make path starts with out/ instead of out/soong.
1546 return filepath.Join(p.config.buildDir, "../", p.path)
1547 } else {
1548 return filepath.Join(p.config.buildDir, p.path)
1549 }
1550}
1551
1552// PartitionDir returns the path to the partition where the install path is rooted at. It is
1553// out/soong/target/product/<device>/<partition> for device modules, and out/soong/host/<os>-<arch> for host modules.
1554// The ./soong is dropped if the install path is for Make.
1555func (p InstallPath) PartitionDir() string {
1556 if p.makePath {
1557 return filepath.Join(p.config.buildDir, "../", p.partitionDir)
1558 } else {
1559 return filepath.Join(p.config.buildDir, p.partitionDir)
1560 }
Colin Cross70dda7e2019-10-01 22:05:35 -07001561}
1562
1563// Join creates a new InstallPath with paths... joined with the current path. The
1564// provided paths... may not use '..' to escape from the current path.
1565func (p InstallPath) Join(ctx PathContext, paths ...string) InstallPath {
1566 path, err := validatePath(paths...)
1567 if err != nil {
1568 reportPathError(ctx, err)
1569 }
1570 return p.withRel(path)
1571}
1572
1573func (p InstallPath) withRel(rel string) InstallPath {
1574 p.basePath = p.basePath.withRel(rel)
1575 return p
1576}
1577
Colin Crossff6c33d2019-10-02 16:01:35 -07001578// ToMakePath returns a new InstallPath that points to Make's install directory instead of Soong's,
1579// i.e. out/ instead of out/soong/.
1580func (p InstallPath) ToMakePath() InstallPath {
Jiyong Park957bcd92020-10-20 18:23:33 +09001581 p.makePath = true
Colin Crossff6c33d2019-10-02 16:01:35 -07001582 return p
Colin Cross70dda7e2019-10-01 22:05:35 -07001583}
1584
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001585// PathForModuleInstall returns a Path representing the install path for the
1586// module appended with paths...
Colin Cross70dda7e2019-10-01 22:05:35 -07001587func PathForModuleInstall(ctx ModuleInstallPathContext, pathComponents ...string) InstallPath {
Colin Cross6e359402020-02-10 15:29:54 -08001588 os := ctx.Os()
Jiyong Park87788b52020-09-01 12:37:45 +09001589 arch := ctx.Arch().ArchType
1590 forceOS, forceArch := ctx.InstallForceOS()
1591 if forceOS != nil {
Colin Cross6e359402020-02-10 15:29:54 -08001592 os = *forceOS
1593 }
Jiyong Park87788b52020-09-01 12:37:45 +09001594 if forceArch != nil {
1595 arch = *forceArch
1596 }
Colin Cross6e359402020-02-10 15:29:54 -08001597 partition := modulePartition(ctx, os)
Colin Cross609c49a2020-02-13 13:20:11 -08001598
Jiyong Park87788b52020-09-01 12:37:45 +09001599 ret := pathForInstall(ctx, os, arch, partition, ctx.Debug(), pathComponents...)
Colin Cross609c49a2020-02-13 13:20:11 -08001600
Jingwen Chencda22c92020-11-23 00:22:30 -05001601 if ctx.InstallBypassMake() && ctx.Config().KatiEnabled() {
Colin Cross609c49a2020-02-13 13:20:11 -08001602 ret = ret.ToMakePath()
1603 }
1604
1605 return ret
1606}
1607
Jiyong Park87788b52020-09-01 12:37:45 +09001608func pathForInstall(ctx PathContext, os OsType, arch ArchType, partition string, debug bool,
Colin Cross609c49a2020-02-13 13:20:11 -08001609 pathComponents ...string) InstallPath {
1610
Jiyong Park957bcd92020-10-20 18:23:33 +09001611 var partionPaths []string
Colin Cross609c49a2020-02-13 13:20:11 -08001612
Colin Cross6e359402020-02-10 15:29:54 -08001613 if os.Class == Device {
Jiyong Park957bcd92020-10-20 18:23:33 +09001614 partionPaths = []string{"target", "product", ctx.Config().DeviceName(), partition}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001615 } else {
Jiyong Park87788b52020-09-01 12:37:45 +09001616 osName := os.String()
1617 if os == Linux {
1618 // instead of linux_glibc
1619 osName = "linux"
Dan Willemsen866b5632017-09-22 12:28:24 -07001620 }
Jiyong Park87788b52020-09-01 12:37:45 +09001621 // SOONG_HOST_OUT is set to out/host/$(HOST_OS)-$(HOST_PREBUILT_ARCH)
1622 // and HOST_PREBUILT_ARCH is forcibly set to x86 even on x86_64 hosts. We don't seem
1623 // to have a plan to fix it (see the comment in build/make/core/envsetup.mk).
1624 // Let's keep using x86 for the existing cases until we have a need to support
1625 // other architectures.
1626 archName := arch.String()
1627 if os.Class == Host && (arch == X86_64 || arch == Common) {
1628 archName = "x86"
1629 }
Jiyong Park957bcd92020-10-20 18:23:33 +09001630 partionPaths = []string{"host", osName + "-" + archName, partition}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001631 }
Colin Cross609c49a2020-02-13 13:20:11 -08001632 if debug {
Jiyong Park957bcd92020-10-20 18:23:33 +09001633 partionPaths = append([]string{"debug"}, partionPaths...)
Dan Willemsen782a2d12015-12-21 14:55:28 -08001634 }
Colin Cross70dda7e2019-10-01 22:05:35 -07001635
Jiyong Park957bcd92020-10-20 18:23:33 +09001636 partionPath, err := validatePath(partionPaths...)
Colin Cross70dda7e2019-10-01 22:05:35 -07001637 if err != nil {
1638 reportPathError(ctx, err)
1639 }
Colin Crossff6c33d2019-10-02 16:01:35 -07001640
Jiyong Park957bcd92020-10-20 18:23:33 +09001641 base := InstallPath{
1642 basePath: basePath{partionPath, ctx.Config(), ""},
1643 partitionDir: partionPath,
1644 makePath: false,
1645 }
Colin Crossff6c33d2019-10-02 16:01:35 -07001646
Jiyong Park957bcd92020-10-20 18:23:33 +09001647 return base.Join(ctx, pathComponents...)
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001648}
1649
Nicolas Geoffray1228e9c2020-02-27 13:45:35 +00001650func pathForNdkOrSdkInstall(ctx PathContext, prefix string, paths []string) InstallPath {
Jiyong Park957bcd92020-10-20 18:23:33 +09001651 base := InstallPath{
1652 basePath: basePath{prefix, ctx.Config(), ""},
1653 partitionDir: prefix,
1654 makePath: false,
Colin Cross70dda7e2019-10-01 22:05:35 -07001655 }
Jiyong Park957bcd92020-10-20 18:23:33 +09001656 return base.Join(ctx, paths...)
Colin Cross70dda7e2019-10-01 22:05:35 -07001657}
1658
Nicolas Geoffray1228e9c2020-02-27 13:45:35 +00001659func PathForNdkInstall(ctx PathContext, paths ...string) InstallPath {
1660 return pathForNdkOrSdkInstall(ctx, "ndk", paths)
1661}
1662
1663func PathForMainlineSdksInstall(ctx PathContext, paths ...string) InstallPath {
1664 return pathForNdkOrSdkInstall(ctx, "mainline-sdks", paths)
1665}
1666
Colin Cross70dda7e2019-10-01 22:05:35 -07001667func InstallPathToOnDevicePath(ctx PathContext, path InstallPath) string {
Colin Cross43f08db2018-11-12 10:13:39 -08001668 rel := Rel(ctx, PathForOutput(ctx, "target", "product", ctx.Config().DeviceName()).String(), path.String())
1669
1670 return "/" + rel
1671}
1672
Colin Cross6e359402020-02-10 15:29:54 -08001673func modulePartition(ctx ModuleInstallPathContext, os OsType) string {
Colin Cross43f08db2018-11-12 10:13:39 -08001674 var partition string
Colin Cross6e359402020-02-10 15:29:54 -08001675 if ctx.InstallInTestcases() {
1676 // "testcases" install directory can be used for host or device modules.
Jaewoong Jung0949f312019-09-11 10:25:18 -07001677 partition = "testcases"
Colin Cross6e359402020-02-10 15:29:54 -08001678 } else if os.Class == Device {
1679 if ctx.InstallInData() {
1680 partition = "data"
1681 } else if ctx.InstallInRamdisk() {
1682 if ctx.DeviceConfig().BoardUsesRecoveryAsBoot() {
1683 partition = "recovery/root/first_stage_ramdisk"
1684 } else {
1685 partition = "ramdisk"
1686 }
1687 if !ctx.InstallInRoot() {
1688 partition += "/system"
1689 }
Yifan Hong60e0cfb2020-10-21 15:17:56 -07001690 } else if ctx.InstallInVendorRamdisk() {
Yifan Hong39143a92020-10-26 12:43:12 -07001691 // The module is only available after switching root into
1692 // /first_stage_ramdisk. To expose the module before switching root
1693 // on a device without a dedicated recovery partition, install the
1694 // recovery variant.
Yifan Hongdd8dacc2020-10-21 15:40:17 -07001695 if ctx.DeviceConfig().BoardMoveRecoveryResourcesToVendorBoot() {
Petri Gyntherac229562021-03-02 23:44:02 -08001696 partition = "vendor_ramdisk/first_stage_ramdisk"
Yifan Hongdd8dacc2020-10-21 15:40:17 -07001697 } else {
Petri Gyntherac229562021-03-02 23:44:02 -08001698 partition = "vendor_ramdisk"
Yifan Hongdd8dacc2020-10-21 15:40:17 -07001699 }
1700 if !ctx.InstallInRoot() {
1701 partition += "/system"
1702 }
Colin Cross6e359402020-02-10 15:29:54 -08001703 } else if ctx.InstallInRecovery() {
1704 if ctx.InstallInRoot() {
1705 partition = "recovery/root"
1706 } else {
1707 // the layout of recovery partion is the same as that of system partition
1708 partition = "recovery/root/system"
1709 }
1710 } else if ctx.SocSpecific() {
1711 partition = ctx.DeviceConfig().VendorPath()
1712 } else if ctx.DeviceSpecific() {
1713 partition = ctx.DeviceConfig().OdmPath()
1714 } else if ctx.ProductSpecific() {
1715 partition = ctx.DeviceConfig().ProductPath()
1716 } else if ctx.SystemExtSpecific() {
1717 partition = ctx.DeviceConfig().SystemExtPath()
1718 } else if ctx.InstallInRoot() {
1719 partition = "root"
Yifan Hong82db7352020-01-21 16:12:26 -08001720 } else {
Colin Cross6e359402020-02-10 15:29:54 -08001721 partition = "system"
Yifan Hong82db7352020-01-21 16:12:26 -08001722 }
Colin Cross6e359402020-02-10 15:29:54 -08001723 if ctx.InstallInSanitizerDir() {
1724 partition = "data/asan/" + partition
Yifan Hong82db7352020-01-21 16:12:26 -08001725 }
Colin Cross43f08db2018-11-12 10:13:39 -08001726 }
1727 return partition
1728}
1729
Colin Cross609c49a2020-02-13 13:20:11 -08001730type InstallPaths []InstallPath
1731
1732// Paths returns the InstallPaths as a Paths
1733func (p InstallPaths) Paths() Paths {
1734 if p == nil {
1735 return nil
1736 }
1737 ret := make(Paths, len(p))
1738 for i, path := range p {
1739 ret[i] = path
1740 }
1741 return ret
1742}
1743
1744// Strings returns the string forms of the install paths.
1745func (p InstallPaths) Strings() []string {
1746 if p == nil {
1747 return nil
1748 }
1749 ret := make([]string, len(p))
1750 for i, path := range p {
1751 ret[i] = path.String()
1752 }
1753 return ret
1754}
1755
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001756// validateSafePath validates a path that we trust (may contain ninja variables).
Dan Willemsen80a7c2a2015-12-21 14:57:11 -08001757// Ensures that each path component does not attempt to leave its component.
Colin Cross1ccfcc32018-02-22 13:54:26 -08001758func validateSafePath(pathComponents ...string) (string, error) {
Jeff Gaston734e3802017-04-10 15:47:24 -07001759 for _, path := range pathComponents {
Dan Willemsen80a7c2a2015-12-21 14:57:11 -08001760 path := filepath.Clean(path)
1761 if path == ".." || strings.HasPrefix(path, "../") || strings.HasPrefix(path, "/") {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001762 return "", fmt.Errorf("Path is outside directory: %s", path)
Dan Willemsen80a7c2a2015-12-21 14:57:11 -08001763 }
1764 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001765 // TODO: filepath.Join isn't necessarily correct with embedded ninja
1766 // variables. '..' may remove the entire ninja variable, even if it
1767 // will be expanded to multiple nested directories.
Colin Cross1ccfcc32018-02-22 13:54:26 -08001768 return filepath.Join(pathComponents...), nil
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001769}
1770
Dan Willemsen80a7c2a2015-12-21 14:57:11 -08001771// validatePath validates that a path does not include ninja variables, and that
1772// each path component does not attempt to leave its component. Returns a joined
1773// version of each path component.
Colin Cross1ccfcc32018-02-22 13:54:26 -08001774func validatePath(pathComponents ...string) (string, error) {
Jeff Gaston734e3802017-04-10 15:47:24 -07001775 for _, path := range pathComponents {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001776 if strings.Contains(path, "$") {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001777 return "", fmt.Errorf("Path contains invalid character($): %s", path)
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001778 }
1779 }
Colin Cross1ccfcc32018-02-22 13:54:26 -08001780 return validateSafePath(pathComponents...)
Colin Cross6e18ca42015-07-14 18:55:36 -07001781}
Colin Cross5b529592017-05-09 13:34:34 -07001782
Colin Cross0875c522017-11-28 17:34:01 -08001783func PathForPhony(ctx PathContext, phony string) WritablePath {
1784 if strings.ContainsAny(phony, "$/") {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001785 ReportPathErrorf(ctx, "Phony target contains invalid character ($ or /): %s", phony)
Colin Cross0875c522017-11-28 17:34:01 -08001786 }
Colin Cross74e3fe42017-12-11 15:51:44 -08001787 return PhonyPath{basePath{phony, ctx.Config(), ""}}
Colin Cross0875c522017-11-28 17:34:01 -08001788}
1789
Colin Cross74e3fe42017-12-11 15:51:44 -08001790type PhonyPath struct {
1791 basePath
1792}
1793
1794func (p PhonyPath) writablePath() {}
1795
Paul Duffin9b478b02019-12-10 13:41:51 +00001796func (p PhonyPath) buildDir() string {
1797 return p.config.buildDir
1798}
1799
Hans MÃ¥nssond3f2bd72020-11-27 12:37:28 +01001800func (p PhonyPath) ReplaceExtension(ctx PathContext, ext string) OutputPath {
1801 panic("Not implemented")
1802}
1803
Colin Cross74e3fe42017-12-11 15:51:44 -08001804var _ Path = PhonyPath{}
1805var _ WritablePath = PhonyPath{}
1806
Colin Cross5b529592017-05-09 13:34:34 -07001807type testPath struct {
1808 basePath
1809}
1810
1811func (p testPath) String() string {
1812 return p.path
1813}
1814
Colin Cross40e33732019-02-15 11:08:35 -08001815// PathForTesting returns a Path constructed from joining the elements of paths with '/'. It should only be used from
1816// within tests.
Colin Cross5b529592017-05-09 13:34:34 -07001817func PathForTesting(paths ...string) Path {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001818 p, err := validateSafePath(paths...)
1819 if err != nil {
1820 panic(err)
1821 }
Colin Cross5b529592017-05-09 13:34:34 -07001822 return testPath{basePath{path: p, rel: p}}
1823}
1824
Colin Cross40e33732019-02-15 11:08:35 -08001825// PathsForTesting returns a Path constructed from each element in strs. It should only be used from within tests.
1826func PathsForTesting(strs ...string) Paths {
Colin Cross5b529592017-05-09 13:34:34 -07001827 p := make(Paths, len(strs))
1828 for i, s := range strs {
1829 p[i] = PathForTesting(s)
1830 }
1831
1832 return p
1833}
Colin Cross43f08db2018-11-12 10:13:39 -08001834
Colin Cross40e33732019-02-15 11:08:35 -08001835type testPathContext struct {
1836 config Config
Colin Cross40e33732019-02-15 11:08:35 -08001837}
1838
Colin Cross40e33732019-02-15 11:08:35 -08001839func (x *testPathContext) Config() Config { return x.config }
1840func (x *testPathContext) AddNinjaFileDeps(...string) {}
1841
1842// PathContextForTesting returns a PathContext that can be used in tests, for example to create an OutputPath with
1843// PathForOutput.
Colin Cross98be1bb2019-12-13 20:41:13 -08001844func PathContextForTesting(config Config) PathContext {
Colin Cross40e33732019-02-15 11:08:35 -08001845 return &testPathContext{
1846 config: config,
Colin Cross40e33732019-02-15 11:08:35 -08001847 }
1848}
1849
Ulya Trafimovichccc8c852020-10-14 11:29:07 +01001850type testModuleInstallPathContext struct {
1851 baseModuleContext
1852
1853 inData bool
1854 inTestcases bool
1855 inSanitizerDir bool
1856 inRamdisk bool
1857 inVendorRamdisk bool
1858 inRecovery bool
1859 inRoot bool
1860 forceOS *OsType
1861 forceArch *ArchType
1862}
1863
1864func (m testModuleInstallPathContext) Config() Config {
1865 return m.baseModuleContext.config
1866}
1867
1868func (testModuleInstallPathContext) AddNinjaFileDeps(deps ...string) {}
1869
1870func (m testModuleInstallPathContext) InstallInData() bool {
1871 return m.inData
1872}
1873
1874func (m testModuleInstallPathContext) InstallInTestcases() bool {
1875 return m.inTestcases
1876}
1877
1878func (m testModuleInstallPathContext) InstallInSanitizerDir() bool {
1879 return m.inSanitizerDir
1880}
1881
1882func (m testModuleInstallPathContext) InstallInRamdisk() bool {
1883 return m.inRamdisk
1884}
1885
1886func (m testModuleInstallPathContext) InstallInVendorRamdisk() bool {
1887 return m.inVendorRamdisk
1888}
1889
1890func (m testModuleInstallPathContext) InstallInRecovery() bool {
1891 return m.inRecovery
1892}
1893
1894func (m testModuleInstallPathContext) InstallInRoot() bool {
1895 return m.inRoot
1896}
1897
1898func (m testModuleInstallPathContext) InstallBypassMake() bool {
1899 return false
1900}
1901
1902func (m testModuleInstallPathContext) InstallForceOS() (*OsType, *ArchType) {
1903 return m.forceOS, m.forceArch
1904}
1905
1906// Construct a minimal ModuleInstallPathContext for testing. Note that baseModuleContext is
1907// default-initialized, which leaves blueprint.baseModuleContext set to nil, so methods that are
1908// delegated to it will panic.
1909func ModuleInstallPathContextForTesting(config Config) ModuleInstallPathContext {
1910 ctx := &testModuleInstallPathContext{}
1911 ctx.config = config
1912 ctx.os = Android
1913 return ctx
1914}
1915
Colin Cross43f08db2018-11-12 10:13:39 -08001916// Rel performs the same function as filepath.Rel, but reports errors to a PathContext, and reports an error if
1917// targetPath is not inside basePath.
1918func Rel(ctx PathContext, basePath string, targetPath string) string {
1919 rel, isRel := MaybeRel(ctx, basePath, targetPath)
1920 if !isRel {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001921 ReportPathErrorf(ctx, "path %q is not under path %q", targetPath, basePath)
Colin Cross43f08db2018-11-12 10:13:39 -08001922 return ""
1923 }
1924 return rel
1925}
1926
1927// MaybeRel performs the same function as filepath.Rel, but reports errors to a PathContext, and returns false if
1928// targetPath is not inside basePath.
1929func MaybeRel(ctx PathContext, basePath string, targetPath string) (string, bool) {
Dan Willemsen633c5022019-04-12 11:11:38 -07001930 rel, isRel, err := maybeRelErr(basePath, targetPath)
1931 if err != nil {
1932 reportPathError(ctx, err)
1933 }
1934 return rel, isRel
1935}
1936
1937func maybeRelErr(basePath string, targetPath string) (string, bool, error) {
Colin Cross43f08db2018-11-12 10:13:39 -08001938 // filepath.Rel returns an error if one path is absolute and the other is not, handle that case first.
1939 if filepath.IsAbs(basePath) != filepath.IsAbs(targetPath) {
Dan Willemsen633c5022019-04-12 11:11:38 -07001940 return "", false, nil
Colin Cross43f08db2018-11-12 10:13:39 -08001941 }
1942 rel, err := filepath.Rel(basePath, targetPath)
1943 if err != nil {
Dan Willemsen633c5022019-04-12 11:11:38 -07001944 return "", false, err
Colin Cross43f08db2018-11-12 10:13:39 -08001945 } else if rel == ".." || strings.HasPrefix(rel, "../") || strings.HasPrefix(rel, "/") {
Dan Willemsen633c5022019-04-12 11:11:38 -07001946 return "", false, nil
Colin Cross43f08db2018-11-12 10:13:39 -08001947 }
Dan Willemsen633c5022019-04-12 11:11:38 -07001948 return rel, true, nil
Colin Cross43f08db2018-11-12 10:13:39 -08001949}
Colin Cross988414c2020-01-11 01:11:46 +00001950
1951// Writes a file to the output directory. Attempting to write directly to the output directory
1952// will fail due to the sandbox of the soong_build process.
1953func WriteFileToOutputDir(path WritablePath, data []byte, perm os.FileMode) error {
1954 return ioutil.WriteFile(absolutePath(path.String()), data, perm)
1955}
1956
Liz Kammer2dd9ca42020-11-25 16:06:39 -08001957func RemoveAllOutputDir(path WritablePath) error {
1958 return os.RemoveAll(absolutePath(path.String()))
1959}
1960
1961func CreateOutputDirIfNonexistent(path WritablePath, perm os.FileMode) error {
1962 dir := absolutePath(path.String())
1963 if _, err := os.Stat(dir); os.IsNotExist(err) {
1964 return os.MkdirAll(dir, os.ModePerm)
1965 } else {
1966 return err
1967 }
1968}
1969
Colin Cross988414c2020-01-11 01:11:46 +00001970func absolutePath(path string) string {
1971 if filepath.IsAbs(path) {
1972 return path
1973 }
1974 return filepath.Join(absSrcDir, path)
1975}
Chris Parsons216e10a2020-07-09 17:12:52 -04001976
1977// A DataPath represents the path of a file to be used as data, for example
1978// a test library to be installed alongside a test.
1979// The data file should be installed (copied from `<SrcPath>`) to
1980// `<install_root>/<RelativeInstallPath>/<filename>`, or
1981// `<install_root>/<filename>` if RelativeInstallPath is empty.
1982type DataPath struct {
1983 // The path of the data file that should be copied into the data directory
1984 SrcPath Path
1985 // The install path of the data file, relative to the install root.
1986 RelativeInstallPath string
1987}
Colin Crossdcf71b22021-02-01 13:59:03 -08001988
1989// PathsIfNonNil returns a Paths containing only the non-nil input arguments.
1990func PathsIfNonNil(paths ...Path) Paths {
1991 if len(paths) == 0 {
1992 // Fast path for empty argument list
1993 return nil
1994 } else if len(paths) == 1 {
1995 // Fast path for a single argument
1996 if paths[0] != nil {
1997 return paths
1998 } else {
1999 return nil
2000 }
2001 }
2002 ret := make(Paths, 0, len(paths))
2003 for _, path := range paths {
2004 if path != nil {
2005 ret = append(ret, path)
2006 }
2007 }
2008 if len(ret) == 0 {
2009 return nil
2010 }
2011 return ret
2012}