blob: 7a54e01570ddc223dd71af75aa83150e11059a78 [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
Jingwen Chen12b4c272021-03-10 02:05:59 -0500343 ModuleType() string
Liz Kammer356f7d42021-01-26 09:18:53 -0500344 OtherModuleName(m blueprint.Module) string
345 OtherModuleDir(m blueprint.Module) string
346}
347
348// BazelLabelForModuleDeps returns a Bazel-compatible label for the requested modules which
349// correspond to dependencies on the module within the given ctx.
350func BazelLabelForModuleDeps(ctx BazelConversionPathContext, modules []string) bazel.LabelList {
351 var labels bazel.LabelList
352 for _, module := range modules {
353 bpText := module
354 if m := SrcIsModule(module); m == "" {
355 module = ":" + module
356 }
357 if m, t := SrcIsModuleWithTag(module); m != "" {
358 l := getOtherModuleLabel(ctx, m, t)
359 l.Bp_text = bpText
360 labels.Includes = append(labels.Includes, l)
361 } else {
362 ctx.ModuleErrorf("%q, is not a module reference", module)
363 }
364 }
365 return labels
366}
367
368// BazelLabelForModuleSrc returns bazel.LabelList with paths rooted from the module's local source
369// directory. It expands globs, and resolves references to modules using the ":name" syntax to
370// bazel-compatible labels. Properties passed as the paths or excludes argument must have been
371// annotated with struct tag `android:"path"` so that dependencies on other modules will have
372// already been handled by the path_properties mutator.
373func BazelLabelForModuleSrc(ctx BazelConversionPathContext, paths []string) bazel.LabelList {
374 return BazelLabelForModuleSrcExcludes(ctx, paths, []string(nil))
375}
376
377// BazelLabelForModuleSrcExcludes returns bazel.LabelList with paths rooted from the module's local
378// source directory, excluding labels included in the excludes argument. It expands globs, and
379// resolves references to modules using the ":name" syntax to bazel-compatible labels. Properties
380// passed as the paths or excludes argument must have been annotated with struct tag
381// `android:"path"` so that dependencies on other modules will have already been handled by the
382// path_properties mutator.
383func BazelLabelForModuleSrcExcludes(ctx BazelConversionPathContext, paths, excludes []string) bazel.LabelList {
384 excludeLabels := expandSrcsForBazel(ctx, excludes, []string(nil))
385 excluded := make([]string, 0, len(excludeLabels.Includes))
386 for _, e := range excludeLabels.Includes {
387 excluded = append(excluded, e.Label)
388 }
389 labels := expandSrcsForBazel(ctx, paths, excluded)
390 labels.Excludes = excludeLabels.Includes
391 return labels
392}
393
394// expandSrcsForBazel returns bazel.LabelList with paths rooted from the module's local
395// source directory, excluding labels included in the excludes argument. It expands globs, and
396// resolves references to modules using the ":name" syntax to bazel-compatible labels. Properties
397// passed as the paths or excludes argument must have been annotated with struct tag
398// `android:"path"` so that dependencies on other modules will have already been handled by the
399// path_properties mutator.
400func expandSrcsForBazel(ctx BazelConversionPathContext, paths, expandedExcludes []string) bazel.LabelList {
Liz Kammerebfcf672021-02-16 15:00:05 -0500401 if paths == nil {
402 return bazel.LabelList{}
403 }
Liz Kammer356f7d42021-01-26 09:18:53 -0500404 labels := bazel.LabelList{
405 Includes: []bazel.Label{},
406 }
407 for _, p := range paths {
408 if m, tag := SrcIsModuleWithTag(p); m != "" {
409 l := getOtherModuleLabel(ctx, m, tag)
410 if !InList(l.Label, expandedExcludes) {
411 l.Bp_text = fmt.Sprintf(":%s", m)
412 labels.Includes = append(labels.Includes, l)
413 }
414 } else {
415 var expandedPaths []bazel.Label
416 if pathtools.IsGlob(p) {
417 globbedPaths := GlobFiles(ctx, pathForModuleSrc(ctx, p).String(), expandedExcludes)
418 globbedPaths = PathsWithModuleSrcSubDir(ctx, globbedPaths, "")
419 for _, path := range globbedPaths {
420 s := path.Rel()
421 expandedPaths = append(expandedPaths, bazel.Label{Label: s})
422 }
423 } else {
424 if !InList(p, expandedExcludes) {
425 expandedPaths = append(expandedPaths, bazel.Label{Label: p})
426 }
427 }
428 labels.Includes = append(labels.Includes, expandedPaths...)
429 }
430 }
431 return labels
432}
433
434// getOtherModuleLabel returns a bazel.Label for the given dependency/tag combination for the
435// module. The label will be relative to the current directory if appropriate. The dependency must
436// already be resolved by either deps mutator or path deps mutator.
437func getOtherModuleLabel(ctx BazelConversionPathContext, dep, tag string) bazel.Label {
438 m, _ := ctx.GetDirectDep(dep)
Liz Kammerbdc60992021-02-24 16:55:11 -0500439 otherLabel := bazelModuleLabel(ctx, m, tag)
440 label := bazelModuleLabel(ctx, ctx.Module(), "")
441 if samePackage(label, otherLabel) {
442 otherLabel = bazelShortLabel(otherLabel)
Liz Kammer356f7d42021-01-26 09:18:53 -0500443 }
Liz Kammerbdc60992021-02-24 16:55:11 -0500444
445 return bazel.Label{
446 Label: otherLabel,
447 }
448}
449
450func bazelModuleLabel(ctx BazelConversionPathContext, module blueprint.Module, tag string) string {
451 // TODO(b/165114590): Convert tag (":name{.tag}") to corresponding Bazel implicit output targets.
452 b, ok := module.(Bazelable)
453 // TODO(b/181155349): perhaps return an error here if the module can't be/isn't being converted
Jingwen Chen12b4c272021-03-10 02:05:59 -0500454 if !ok || !b.ConvertedToBazel(ctx) {
Liz Kammerbdc60992021-02-24 16:55:11 -0500455 return bp2buildModuleLabel(ctx, module)
456 }
457 return b.GetBazelLabel(ctx, module)
458}
459
460func bazelShortLabel(label string) string {
461 i := strings.Index(label, ":")
462 return label[i:]
463}
464
465func bazelPackage(label string) string {
466 i := strings.Index(label, ":")
467 return label[0:i]
468}
469
470func samePackage(label1, label2 string) bool {
471 return bazelPackage(label1) == bazelPackage(label2)
472}
473
474func bp2buildModuleLabel(ctx BazelConversionPathContext, module blueprint.Module) string {
475 moduleName := ctx.OtherModuleName(module)
476 moduleDir := ctx.OtherModuleDir(module)
477 return fmt.Sprintf("//%s:%s", moduleDir, moduleName)
Liz Kammer356f7d42021-01-26 09:18:53 -0500478}
479
Ulya Trafimovich4d2eeed2019-11-08 10:54:21 +0000480// OutputPaths is a slice of OutputPath objects, with helpers to operate on the collection.
481type OutputPaths []OutputPath
482
483// Paths returns the OutputPaths as a Paths
484func (p OutputPaths) Paths() Paths {
485 if p == nil {
486 return nil
487 }
488 ret := make(Paths, len(p))
489 for i, path := range p {
490 ret[i] = path
491 }
492 return ret
493}
494
495// Strings returns the string forms of the writable paths.
496func (p OutputPaths) Strings() []string {
497 if p == nil {
498 return nil
499 }
500 ret := make([]string, len(p))
501 for i, path := range p {
502 ret[i] = path.String()
503 }
504 return ret
505}
506
Liz Kammera830f3a2020-11-10 10:50:34 -0800507// Expands Paths to a SourceFileProducer or OutputFileProducer module dependency referenced via ":name" or ":name{.tag}" syntax.
508// If the dependency is not found, a missingErrorDependency is returned.
509// If the module dependency is not a SourceFileProducer or OutputFileProducer, appropriate errors will be returned.
510func getPathsFromModuleDep(ctx ModuleWithDepsPathContext, path, moduleName, tag string) (Paths, error) {
511 module := ctx.GetDirectDepWithTag(moduleName, sourceOrOutputDepTag(tag))
512 if module == nil {
513 return nil, missingDependencyError{[]string{moduleName}}
514 }
515 if outProducer, ok := module.(OutputFileProducer); ok {
516 outputFiles, err := outProducer.OutputFiles(tag)
517 if err != nil {
518 return nil, fmt.Errorf("path dependency %q: %s", path, err)
519 }
520 return outputFiles, nil
521 } else if tag != "" {
522 return nil, fmt.Errorf("path dependency %q is not an output file producing module", path)
523 } else if srcProducer, ok := module.(SourceFileProducer); ok {
524 return srcProducer.Srcs(), nil
525 } else {
526 return nil, fmt.Errorf("path dependency %q is not a source file producing module", path)
527 }
528}
529
Colin Crossba71a3f2019-03-18 12:12:48 -0700530// PathsAndMissingDepsForModuleSrcExcludes returns Paths rooted from the module's local source directory, excluding
Colin Cross41955e82019-05-29 14:40:35 -0700531// paths listed in the excludes arguments, and a list of missing dependencies. It expands globs, references to
532// SourceFileProducer modules using the ":name" syntax, and references to OutputFileProducer modules using the
533// ":name{.tag}" syntax. Properties passed as the paths or excludes argument must have been annotated with struct tag
534// `android:"path"` so that dependencies on SourceFileProducer modules will have already been handled by the
535// path_properties mutator. If ctx.Config().AllowMissingDependencies() is true then any missing SourceFileProducer or
536// OutputFileProducer dependencies will be returned, and they will NOT cause the module to be marked as having missing
537// dependencies.
Liz Kammera830f3a2020-11-10 10:50:34 -0800538func PathsAndMissingDepsForModuleSrcExcludes(ctx ModuleWithDepsPathContext, paths, excludes []string) (Paths, []string) {
Colin Cross8a497952019-03-05 22:25:09 -0800539 prefix := pathForModuleSrc(ctx).String()
540
541 var expandedExcludes []string
542 if excludes != nil {
543 expandedExcludes = make([]string, 0, len(excludes))
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700544 }
Colin Cross8a497952019-03-05 22:25:09 -0800545
Colin Crossba71a3f2019-03-18 12:12:48 -0700546 var missingExcludeDeps []string
547
Colin Cross8a497952019-03-05 22:25:09 -0800548 for _, e := range excludes {
Colin Cross41955e82019-05-29 14:40:35 -0700549 if m, t := SrcIsModuleWithTag(e); m != "" {
Liz Kammera830f3a2020-11-10 10:50:34 -0800550 modulePaths, err := getPathsFromModuleDep(ctx, e, m, t)
551 if m, ok := err.(missingDependencyError); ok {
552 missingExcludeDeps = append(missingExcludeDeps, m.missingDeps...)
553 } else if err != nil {
554 reportPathError(ctx, err)
Colin Cross8a497952019-03-05 22:25:09 -0800555 } else {
Liz Kammera830f3a2020-11-10 10:50:34 -0800556 expandedExcludes = append(expandedExcludes, modulePaths.Strings()...)
Colin Cross8a497952019-03-05 22:25:09 -0800557 }
558 } else {
559 expandedExcludes = append(expandedExcludes, filepath.Join(prefix, e))
560 }
561 }
562
563 if paths == nil {
Colin Crossba71a3f2019-03-18 12:12:48 -0700564 return nil, missingExcludeDeps
Colin Cross8a497952019-03-05 22:25:09 -0800565 }
566
Colin Crossba71a3f2019-03-18 12:12:48 -0700567 var missingDeps []string
568
Colin Cross8a497952019-03-05 22:25:09 -0800569 expandedSrcFiles := make(Paths, 0, len(paths))
570 for _, s := range paths {
571 srcFiles, err := expandOneSrcPath(ctx, s, expandedExcludes)
572 if depErr, ok := err.(missingDependencyError); ok {
Colin Crossba71a3f2019-03-18 12:12:48 -0700573 missingDeps = append(missingDeps, depErr.missingDeps...)
Colin Cross8a497952019-03-05 22:25:09 -0800574 } else if err != nil {
575 reportPathError(ctx, err)
576 }
577 expandedSrcFiles = append(expandedSrcFiles, srcFiles...)
578 }
Colin Crossba71a3f2019-03-18 12:12:48 -0700579
580 return expandedSrcFiles, append(missingDeps, missingExcludeDeps...)
Colin Cross8a497952019-03-05 22:25:09 -0800581}
582
583type missingDependencyError struct {
584 missingDeps []string
585}
586
587func (e missingDependencyError) Error() string {
588 return "missing dependencies: " + strings.Join(e.missingDeps, ", ")
589}
590
Liz Kammera830f3a2020-11-10 10:50:34 -0800591// Expands one path string to Paths rooted from the module's local source
592// directory, excluding those listed in the expandedExcludes.
593// Expands globs, references to SourceFileProducer or OutputFileProducer modules using the ":name" and ":name{.tag}" syntax.
594func expandOneSrcPath(ctx ModuleWithDepsPathContext, sPath string, expandedExcludes []string) (Paths, error) {
Jooyung Han7607dd32020-07-05 10:23:14 +0900595 excludePaths := func(paths Paths) Paths {
596 if len(expandedExcludes) == 0 {
597 return paths
598 }
599 remainder := make(Paths, 0, len(paths))
600 for _, p := range paths {
601 if !InList(p.String(), expandedExcludes) {
602 remainder = append(remainder, p)
603 }
604 }
605 return remainder
606 }
Liz Kammera830f3a2020-11-10 10:50:34 -0800607 if m, t := SrcIsModuleWithTag(sPath); m != "" {
608 modulePaths, err := getPathsFromModuleDep(ctx, sPath, m, t)
609 if err != nil {
610 return nil, err
Colin Cross8a497952019-03-05 22:25:09 -0800611 } else {
Liz Kammera830f3a2020-11-10 10:50:34 -0800612 return excludePaths(modulePaths), nil
Colin Cross8a497952019-03-05 22:25:09 -0800613 }
Liz Kammera830f3a2020-11-10 10:50:34 -0800614 } else if pathtools.IsGlob(sPath) {
615 paths := GlobFiles(ctx, pathForModuleSrc(ctx, sPath).String(), expandedExcludes)
Colin Cross8a497952019-03-05 22:25:09 -0800616 return PathsWithModuleSrcSubDir(ctx, paths, ""), nil
617 } else {
Liz Kammera830f3a2020-11-10 10:50:34 -0800618 p := pathForModuleSrc(ctx, sPath)
Colin Cross988414c2020-01-11 01:11:46 +0000619 if exists, _, err := ctx.Config().fs.Exists(p.String()); err != nil {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +0100620 ReportPathErrorf(ctx, "%s: %s", p, err.Error())
Pedro Loureiro5d190cc2021-02-15 15:41:33 +0000621 } else if !exists && !ctx.Config().TestAllowNonExistentPaths {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +0100622 ReportPathErrorf(ctx, "module source path %q does not exist", p)
Colin Cross8a497952019-03-05 22:25:09 -0800623 }
624
Jooyung Han7607dd32020-07-05 10:23:14 +0900625 if InList(p.String(), expandedExcludes) {
Colin Cross8a497952019-03-05 22:25:09 -0800626 return nil, nil
627 }
628 return Paths{p}, nil
629 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700630}
631
632// pathsForModuleSrcFromFullPath returns Paths rooted from the module's local
633// source directory, but strip the local source directory from the beginning of
Dan Willemsen540a78c2018-02-26 21:50:08 -0800634// each string. If incDirs is false, strip paths with a trailing '/' from the list.
Colin Crossfe4bc362018-09-12 10:02:13 -0700635// It intended for use in globs that only list files that exist, so it allows '$' in
636// filenames.
Liz Kammera830f3a2020-11-10 10:50:34 -0800637func pathsForModuleSrcFromFullPath(ctx EarlyModulePathContext, paths []string, incDirs bool) Paths {
Colin Cross6510f912017-11-29 00:27:14 -0800638 prefix := filepath.Join(ctx.Config().srcDir, ctx.ModuleDir()) + "/"
Colin Cross0f37af02017-09-27 17:42:05 -0700639 if prefix == "./" {
640 prefix = ""
641 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700642 ret := make(Paths, 0, len(paths))
643 for _, p := range paths {
Dan Willemsen540a78c2018-02-26 21:50:08 -0800644 if !incDirs && strings.HasSuffix(p, "/") {
645 continue
646 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700647 path := filepath.Clean(p)
648 if !strings.HasPrefix(path, prefix) {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +0100649 ReportPathErrorf(ctx, "Path %q is not in module source directory %q", p, prefix)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700650 continue
651 }
Colin Crosse3924e12018-08-15 20:18:53 -0700652
Colin Crossfe4bc362018-09-12 10:02:13 -0700653 srcPath, err := safePathForSource(ctx, ctx.ModuleDir(), path[len(prefix):])
Colin Crosse3924e12018-08-15 20:18:53 -0700654 if err != nil {
655 reportPathError(ctx, err)
656 continue
657 }
658
Colin Cross07e51612019-03-05 12:46:40 -0800659 srcPath.basePath.rel = srcPath.path
Colin Crosse3924e12018-08-15 20:18:53 -0700660
Colin Cross07e51612019-03-05 12:46:40 -0800661 ret = append(ret, srcPath)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700662 }
663 return ret
664}
665
Liz Kammera830f3a2020-11-10 10:50:34 -0800666// PathsWithOptionalDefaultForModuleSrc returns Paths rooted from the module's local source
667// directory. If input is nil, use the default if it exists. If input is empty, returns nil.
668func PathsWithOptionalDefaultForModuleSrc(ctx ModuleMissingDepsPathContext, input []string, def string) Paths {
Colin Cross0ddae7f2019-02-07 15:30:01 -0800669 if input != nil {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700670 return PathsForModuleSrc(ctx, input)
671 }
672 // Use Glob so that if the default doesn't exist, a dependency is added so that when it
673 // is created, we're run again.
Colin Cross6510f912017-11-29 00:27:14 -0800674 path := filepath.Join(ctx.Config().srcDir, ctx.ModuleDir(), def)
Liz Kammera830f3a2020-11-10 10:50:34 -0800675 return Glob(ctx, path, nil)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700676}
677
678// Strings returns the Paths in string form
679func (p Paths) Strings() []string {
680 if p == nil {
681 return nil
682 }
683 ret := make([]string, len(p))
684 for i, path := range p {
685 ret[i] = path.String()
686 }
687 return ret
688}
689
Colin Crossc0efd1d2020-07-03 11:56:24 -0700690func CopyOfPaths(paths Paths) Paths {
691 return append(Paths(nil), paths...)
692}
693
Colin Crossb6715442017-10-24 11:13:31 -0700694// FirstUniquePaths returns all unique elements of a Paths, keeping the first copy of each. It
695// modifies the Paths slice contents in place, and returns a subslice of the original slice.
Dan Willemsenfe92c962017-08-29 12:28:37 -0700696func FirstUniquePaths(list Paths) Paths {
Colin Cross27027c72020-02-28 15:34:17 -0800697 // 128 was chosen based on BenchmarkFirstUniquePaths results.
698 if len(list) > 128 {
699 return firstUniquePathsMap(list)
700 }
701 return firstUniquePathsList(list)
702}
703
Colin Crossc0efd1d2020-07-03 11:56:24 -0700704// SortedUniquePaths returns all unique elements of a Paths in sorted order. It modifies the
705// Paths slice contents in place, and returns a subslice of the original slice.
Jiyong Park33c77362020-05-29 22:00:16 +0900706func SortedUniquePaths(list Paths) Paths {
707 unique := FirstUniquePaths(list)
708 sort.Slice(unique, func(i, j int) bool {
709 return unique[i].String() < unique[j].String()
710 })
711 return unique
712}
713
Colin Cross27027c72020-02-28 15:34:17 -0800714func firstUniquePathsList(list Paths) Paths {
Dan Willemsenfe92c962017-08-29 12:28:37 -0700715 k := 0
716outer:
717 for i := 0; i < len(list); i++ {
718 for j := 0; j < k; j++ {
719 if list[i] == list[j] {
720 continue outer
721 }
722 }
723 list[k] = list[i]
724 k++
725 }
726 return list[:k]
727}
728
Colin Cross27027c72020-02-28 15:34:17 -0800729func firstUniquePathsMap(list Paths) Paths {
730 k := 0
731 seen := make(map[Path]bool, len(list))
732 for i := 0; i < len(list); i++ {
733 if seen[list[i]] {
734 continue
735 }
736 seen[list[i]] = true
737 list[k] = list[i]
738 k++
739 }
740 return list[:k]
741}
742
Colin Cross5d583952020-11-24 16:21:24 -0800743// FirstUniqueInstallPaths returns all unique elements of an InstallPaths, keeping the first copy of each. It
744// modifies the InstallPaths slice contents in place, and returns a subslice of the original slice.
745func FirstUniqueInstallPaths(list InstallPaths) InstallPaths {
746 // 128 was chosen based on BenchmarkFirstUniquePaths results.
747 if len(list) > 128 {
748 return firstUniqueInstallPathsMap(list)
749 }
750 return firstUniqueInstallPathsList(list)
751}
752
753func firstUniqueInstallPathsList(list InstallPaths) InstallPaths {
754 k := 0
755outer:
756 for i := 0; i < len(list); i++ {
757 for j := 0; j < k; j++ {
758 if list[i] == list[j] {
759 continue outer
760 }
761 }
762 list[k] = list[i]
763 k++
764 }
765 return list[:k]
766}
767
768func firstUniqueInstallPathsMap(list InstallPaths) InstallPaths {
769 k := 0
770 seen := make(map[InstallPath]bool, len(list))
771 for i := 0; i < len(list); i++ {
772 if seen[list[i]] {
773 continue
774 }
775 seen[list[i]] = true
776 list[k] = list[i]
777 k++
778 }
779 return list[:k]
780}
781
Colin Crossb6715442017-10-24 11:13:31 -0700782// LastUniquePaths returns all unique elements of a Paths, keeping the last copy of each. It
783// modifies the Paths slice contents in place, and returns a subslice of the original slice.
784func LastUniquePaths(list Paths) Paths {
785 totalSkip := 0
786 for i := len(list) - 1; i >= totalSkip; i-- {
787 skip := 0
788 for j := i - 1; j >= totalSkip; j-- {
789 if list[i] == list[j] {
790 skip++
791 } else {
792 list[j+skip] = list[j]
793 }
794 }
795 totalSkip += skip
796 }
797 return list[totalSkip:]
798}
799
Colin Crossa140bb02018-04-17 10:52:26 -0700800// ReversePaths returns a copy of a Paths in reverse order.
801func ReversePaths(list Paths) Paths {
802 if list == nil {
803 return nil
804 }
805 ret := make(Paths, len(list))
806 for i := range list {
807 ret[i] = list[len(list)-1-i]
808 }
809 return ret
810}
811
Jeff Gaston294356f2017-09-27 17:05:30 -0700812func indexPathList(s Path, list []Path) int {
813 for i, l := range list {
814 if l == s {
815 return i
816 }
817 }
818
819 return -1
820}
821
822func inPathList(p Path, list []Path) bool {
823 return indexPathList(p, list) != -1
824}
825
826func FilterPathList(list []Path, filter []Path) (remainder []Path, filtered []Path) {
Paul Duffin57b9e1d2019-12-13 00:03:35 +0000827 return FilterPathListPredicate(list, func(p Path) bool { return inPathList(p, filter) })
828}
829
830func FilterPathListPredicate(list []Path, predicate func(Path) bool) (remainder []Path, filtered []Path) {
Jeff Gaston294356f2017-09-27 17:05:30 -0700831 for _, l := range list {
Paul Duffin57b9e1d2019-12-13 00:03:35 +0000832 if predicate(l) {
Jeff Gaston294356f2017-09-27 17:05:30 -0700833 filtered = append(filtered, l)
834 } else {
835 remainder = append(remainder, l)
836 }
837 }
838
839 return
840}
841
Colin Cross93e85952017-08-15 13:34:18 -0700842// HasExt returns true of any of the paths have extension ext, otherwise false
843func (p Paths) HasExt(ext string) bool {
844 for _, path := range p {
845 if path.Ext() == ext {
846 return true
847 }
848 }
849
850 return false
851}
852
853// FilterByExt returns the subset of the paths that have extension ext
854func (p Paths) FilterByExt(ext string) Paths {
855 ret := make(Paths, 0, len(p))
856 for _, path := range p {
857 if path.Ext() == ext {
858 ret = append(ret, path)
859 }
860 }
861 return ret
862}
863
864// FilterOutByExt returns the subset of the paths that do not have extension ext
865func (p Paths) FilterOutByExt(ext string) Paths {
866 ret := make(Paths, 0, len(p))
867 for _, path := range p {
868 if path.Ext() != ext {
869 ret = append(ret, path)
870 }
871 }
872 return ret
873}
874
Colin Cross5e6cfbe2017-11-03 15:20:35 -0700875// DirectorySortedPaths is a slice of paths that are sorted such that all files in a directory
876// (including subdirectories) are in a contiguous subslice of the list, and can be found in
877// O(log(N)) time using a binary search on the directory prefix.
878type DirectorySortedPaths Paths
879
880func PathsToDirectorySortedPaths(paths Paths) DirectorySortedPaths {
881 ret := append(DirectorySortedPaths(nil), paths...)
882 sort.Slice(ret, func(i, j int) bool {
883 return ret[i].String() < ret[j].String()
884 })
885 return ret
886}
887
888// PathsInDirectory returns a subslice of the DirectorySortedPaths as a Paths that contains all entries
889// that are in the specified directory and its subdirectories.
890func (p DirectorySortedPaths) PathsInDirectory(dir string) Paths {
891 prefix := filepath.Clean(dir) + "/"
892 start := sort.Search(len(p), func(i int) bool {
893 return prefix < p[i].String()
894 })
895
896 ret := p[start:]
897
898 end := sort.Search(len(ret), func(i int) bool {
899 return !strings.HasPrefix(ret[i].String(), prefix)
900 })
901
902 ret = ret[:end]
903
904 return Paths(ret)
905}
906
Alex Humesky29e3bbe2020-11-20 21:30:13 -0500907// WritablePaths is a slice of WritablePath, used for multiple outputs.
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700908type WritablePaths []WritablePath
909
910// Strings returns the string forms of the writable paths.
911func (p WritablePaths) Strings() []string {
912 if p == nil {
913 return nil
914 }
915 ret := make([]string, len(p))
916 for i, path := range p {
917 ret[i] = path.String()
918 }
919 return ret
920}
921
Colin Cross3bc7ffa2017-11-22 16:19:37 -0800922// Paths returns the WritablePaths as a Paths
923func (p WritablePaths) Paths() Paths {
924 if p == nil {
925 return nil
926 }
927 ret := make(Paths, len(p))
928 for i, path := range p {
929 ret[i] = path
930 }
931 return ret
932}
933
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700934type basePath struct {
935 path string
936 config Config
Colin Crossfaeb7aa2017-02-01 14:12:44 -0800937 rel string
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700938}
939
940func (p basePath) Ext() string {
941 return filepath.Ext(p.path)
942}
943
Colin Cross4f6fc9c2016-10-26 10:05:25 -0700944func (p basePath) Base() string {
945 return filepath.Base(p.path)
946}
947
Colin Crossfaeb7aa2017-02-01 14:12:44 -0800948func (p basePath) Rel() string {
949 if p.rel != "" {
950 return p.rel
951 }
952 return p.path
953}
954
Colin Cross0875c522017-11-28 17:34:01 -0800955func (p basePath) String() string {
956 return p.path
957}
958
Colin Cross0db55682017-12-05 15:36:55 -0800959func (p basePath) withRel(rel string) basePath {
960 p.path = filepath.Join(p.path, rel)
961 p.rel = rel
962 return p
963}
964
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700965// SourcePath is a Path representing a file path rooted from SrcDir
966type SourcePath struct {
967 basePath
968}
969
970var _ Path = SourcePath{}
971
Colin Cross0db55682017-12-05 15:36:55 -0800972func (p SourcePath) withRel(rel string) SourcePath {
973 p.basePath = p.basePath.withRel(rel)
974 return p
975}
976
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700977// safePathForSource is for paths that we expect are safe -- only for use by go
978// code that is embedding ninja variables in paths
Colin Crossfe4bc362018-09-12 10:02:13 -0700979func safePathForSource(ctx PathContext, pathComponents ...string) (SourcePath, error) {
980 p, err := validateSafePath(pathComponents...)
Colin Crossaabf6792017-11-29 00:27:14 -0800981 ret := SourcePath{basePath{p, ctx.Config(), ""}}
Colin Crossfe4bc362018-09-12 10:02:13 -0700982 if err != nil {
983 return ret, err
984 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700985
Colin Cross7b3dcc32019-01-24 13:14:39 -0800986 // absolute path already checked by validateSafePath
987 if strings.HasPrefix(ret.String(), ctx.Config().buildDir) {
Mikhail Naganovab1f5182019-02-08 13:17:55 -0800988 return ret, fmt.Errorf("source path %q is in output", ret.String())
Colin Cross6e18ca42015-07-14 18:55:36 -0700989 }
990
Colin Crossfe4bc362018-09-12 10:02:13 -0700991 return ret, err
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700992}
993
Colin Cross192e97a2018-02-22 14:21:02 -0800994// pathForSource creates a SourcePath from pathComponents, but does not check that it exists.
995func pathForSource(ctx PathContext, pathComponents ...string) (SourcePath, error) {
Colin Crossc48c1432018-02-23 07:09:01 +0000996 p, err := validatePath(pathComponents...)
997 ret := SourcePath{basePath{p, ctx.Config(), ""}}
Colin Cross94a32102018-02-22 14:21:02 -0800998 if err != nil {
Colin Cross192e97a2018-02-22 14:21:02 -0800999 return ret, err
Colin Cross94a32102018-02-22 14:21:02 -08001000 }
1001
Colin Cross7b3dcc32019-01-24 13:14:39 -08001002 // absolute path already checked by validatePath
1003 if strings.HasPrefix(ret.String(), ctx.Config().buildDir) {
Mikhail Naganovab1f5182019-02-08 13:17:55 -08001004 return ret, fmt.Errorf("source path %q is in output", ret.String())
Colin Crossc48c1432018-02-23 07:09:01 +00001005 }
1006
Colin Cross192e97a2018-02-22 14:21:02 -08001007 return ret, nil
1008}
1009
1010// existsWithDependencies returns true if the path exists, and adds appropriate dependencies to rerun if the
1011// path does not exist.
1012func existsWithDependencies(ctx PathContext, path SourcePath) (exists bool, err error) {
1013 var files []string
1014
1015 if gctx, ok := ctx.(PathGlobContext); ok {
1016 // Use glob to produce proper dependencies, even though we only want
1017 // a single file.
1018 files, err = gctx.GlobWithDeps(path.String(), nil)
1019 } else {
1020 var deps []string
1021 // We cannot add build statements in this context, so we fall back to
1022 // AddNinjaFileDeps
Colin Cross988414c2020-01-11 01:11:46 +00001023 files, deps, err = ctx.Config().fs.Glob(path.String(), nil, pathtools.FollowSymlinks)
Colin Cross192e97a2018-02-22 14:21:02 -08001024 ctx.AddNinjaFileDeps(deps...)
1025 }
1026
1027 if err != nil {
1028 return false, fmt.Errorf("glob: %s", err.Error())
1029 }
1030
1031 return len(files) > 0, nil
1032}
1033
1034// PathForSource joins the provided path components and validates that the result
1035// neither escapes the source dir nor is in the out dir.
1036// On error, it will return a usable, but invalid SourcePath, and report a ModuleError.
1037func PathForSource(ctx PathContext, pathComponents ...string) SourcePath {
1038 path, err := pathForSource(ctx, pathComponents...)
1039 if err != nil {
1040 reportPathError(ctx, err)
1041 }
1042
Colin Crosse3924e12018-08-15 20:18:53 -07001043 if pathtools.IsGlob(path.String()) {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001044 ReportPathErrorf(ctx, "path may not contain a glob: %s", path.String())
Colin Crosse3924e12018-08-15 20:18:53 -07001045 }
1046
Liz Kammera830f3a2020-11-10 10:50:34 -08001047 if modCtx, ok := ctx.(ModuleMissingDepsPathContext); ok && ctx.Config().AllowMissingDependencies() {
Colin Cross192e97a2018-02-22 14:21:02 -08001048 exists, err := existsWithDependencies(ctx, path)
1049 if err != nil {
1050 reportPathError(ctx, err)
1051 }
1052 if !exists {
1053 modCtx.AddMissingDependencies([]string{path.String()})
1054 }
Colin Cross988414c2020-01-11 01:11:46 +00001055 } else if exists, _, err := ctx.Config().fs.Exists(path.String()); err != nil {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001056 ReportPathErrorf(ctx, "%s: %s", path, err.Error())
Pedro Loureiro5d190cc2021-02-15 15:41:33 +00001057 } else if !exists && !ctx.Config().TestAllowNonExistentPaths {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001058 ReportPathErrorf(ctx, "source path %q does not exist", path)
Colin Cross192e97a2018-02-22 14:21:02 -08001059 }
1060 return path
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001061}
1062
Liz Kammer7aa52882021-02-11 09:16:14 -05001063// ExistentPathForSource returns an OptionalPath with the SourcePath, rooted from SrcDir, *not*
1064// rooted from the module's local source directory, if the path exists, or an empty OptionalPath if
1065// it doesn't exist. Dependencies are added so that the ninja file will be regenerated if the state
1066// of the path changes.
Colin Cross32f38982018-02-22 11:47:25 -08001067func ExistentPathForSource(ctx PathContext, pathComponents ...string) OptionalPath {
Colin Cross192e97a2018-02-22 14:21:02 -08001068 path, err := pathForSource(ctx, pathComponents...)
Colin Cross1ccfcc32018-02-22 13:54:26 -08001069 if err != nil {
1070 reportPathError(ctx, err)
1071 return OptionalPath{}
1072 }
Colin Crossc48c1432018-02-23 07:09:01 +00001073
Colin Crosse3924e12018-08-15 20:18:53 -07001074 if pathtools.IsGlob(path.String()) {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001075 ReportPathErrorf(ctx, "path may not contain a glob: %s", path.String())
Colin Crosse3924e12018-08-15 20:18:53 -07001076 return OptionalPath{}
1077 }
1078
Colin Cross192e97a2018-02-22 14:21:02 -08001079 exists, err := existsWithDependencies(ctx, path)
Colin Crossc48c1432018-02-23 07:09:01 +00001080 if err != nil {
1081 reportPathError(ctx, err)
1082 return OptionalPath{}
1083 }
Colin Cross192e97a2018-02-22 14:21:02 -08001084 if !exists {
Colin Crossc48c1432018-02-23 07:09:01 +00001085 return OptionalPath{}
1086 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001087 return OptionalPathForPath(path)
1088}
1089
1090func (p SourcePath) String() string {
1091 return filepath.Join(p.config.srcDir, p.path)
1092}
1093
1094// Join creates a new SourcePath with paths... joined with the current path. The
1095// provided paths... may not use '..' to escape from the current path.
1096func (p SourcePath) Join(ctx PathContext, paths ...string) SourcePath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001097 path, err := validatePath(paths...)
1098 if err != nil {
1099 reportPathError(ctx, err)
1100 }
Colin Cross0db55682017-12-05 15:36:55 -08001101 return p.withRel(path)
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001102}
1103
Colin Cross2fafa3e2019-03-05 12:39:51 -08001104// join is like Join but does less path validation.
1105func (p SourcePath) join(ctx PathContext, paths ...string) SourcePath {
1106 path, err := validateSafePath(paths...)
1107 if err != nil {
1108 reportPathError(ctx, err)
1109 }
1110 return p.withRel(path)
1111}
1112
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001113// OverlayPath returns the overlay for `path' if it exists. This assumes that the
1114// SourcePath is the path to a resource overlay directory.
Liz Kammera830f3a2020-11-10 10:50:34 -08001115func (p SourcePath) OverlayPath(ctx ModuleMissingDepsPathContext, path Path) OptionalPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001116 var relDir string
Colin Cross07e51612019-03-05 12:46:40 -08001117 if srcPath, ok := path.(SourcePath); ok {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001118 relDir = srcPath.path
1119 } else {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001120 ReportPathErrorf(ctx, "Cannot find relative path for %s(%s)", reflect.TypeOf(path).Name(), path)
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001121 return OptionalPath{}
1122 }
1123 dir := filepath.Join(p.config.srcDir, p.path, relDir)
1124 // Use Glob so that we are run again if the directory is added.
Colin Cross7f19f372016-11-01 11:10:25 -07001125 if pathtools.IsGlob(dir) {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001126 ReportPathErrorf(ctx, "Path may not contain a glob: %s", dir)
Dan Willemsen7b310ee2015-12-18 15:11:17 -08001127 }
Colin Cross461b4452018-02-23 09:22:42 -08001128 paths, err := ctx.GlobWithDeps(dir, nil)
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001129 if err != nil {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001130 ReportPathErrorf(ctx, "glob: %s", err.Error())
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001131 return OptionalPath{}
1132 }
1133 if len(paths) == 0 {
1134 return OptionalPath{}
1135 }
Colin Cross43f08db2018-11-12 10:13:39 -08001136 relPath := Rel(ctx, p.config.srcDir, paths[0])
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001137 return OptionalPathForPath(PathForSource(ctx, relPath))
1138}
1139
Colin Cross70dda7e2019-10-01 22:05:35 -07001140// OutputPath is a Path representing an intermediates file path rooted from the build directory
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001141type OutputPath struct {
1142 basePath
Colin Crossd63c9a72020-01-29 16:52:50 -08001143 fullPath string
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001144}
1145
Colin Cross702e0f82017-10-18 17:27:54 -07001146func (p OutputPath) withRel(rel string) OutputPath {
Colin Cross0db55682017-12-05 15:36:55 -08001147 p.basePath = p.basePath.withRel(rel)
Colin Crossd63c9a72020-01-29 16:52:50 -08001148 p.fullPath = filepath.Join(p.fullPath, rel)
Colin Cross702e0f82017-10-18 17:27:54 -07001149 return p
1150}
1151
Colin Cross3063b782018-08-15 11:19:12 -07001152func (p OutputPath) WithoutRel() OutputPath {
1153 p.basePath.rel = filepath.Base(p.basePath.path)
1154 return p
1155}
1156
Paul Duffin9b478b02019-12-10 13:41:51 +00001157func (p OutputPath) buildDir() string {
1158 return p.config.buildDir
1159}
1160
Paul Duffin0267d492021-02-02 10:05:52 +00001161func (p OutputPath) objPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleObjPath {
1162 return PathForModuleObj(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
1163}
1164
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001165var _ Path = OutputPath{}
Paul Duffin9b478b02019-12-10 13:41:51 +00001166var _ WritablePath = OutputPath{}
Paul Duffin0267d492021-02-02 10:05:52 +00001167var _ objPathProvider = OutputPath{}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001168
Chris Parsons8f232a22020-06-23 17:37:05 -04001169// toolDepPath is a Path representing a dependency of the build tool.
1170type toolDepPath struct {
1171 basePath
1172}
1173
1174var _ Path = toolDepPath{}
1175
1176// pathForBuildToolDep returns a toolDepPath representing the given path string.
1177// There is no validation for the path, as it is "trusted": It may fail
1178// normal validation checks. For example, it may be an absolute path.
1179// Only use this function to construct paths for dependencies of the build
1180// tool invocation.
1181func pathForBuildToolDep(ctx PathContext, path string) toolDepPath {
1182 return toolDepPath{basePath{path, ctx.Config(), ""}}
1183}
1184
Jeff Gaston734e3802017-04-10 15:47:24 -07001185// PathForOutput joins the provided paths and returns an OutputPath that is
1186// validated to not escape the build dir.
1187// On error, it will return a usable, but invalid OutputPath, and report a ModuleError.
1188func PathForOutput(ctx PathContext, pathComponents ...string) OutputPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001189 path, err := validatePath(pathComponents...)
1190 if err != nil {
1191 reportPathError(ctx, err)
1192 }
Colin Crossd63c9a72020-01-29 16:52:50 -08001193 fullPath := filepath.Join(ctx.Config().buildDir, path)
1194 path = fullPath[len(fullPath)-len(path):]
1195 return OutputPath{basePath{path, ctx.Config(), ""}, fullPath}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001196}
1197
Colin Cross40e33732019-02-15 11:08:35 -08001198// PathsForOutput returns Paths rooted from buildDir
1199func PathsForOutput(ctx PathContext, paths []string) WritablePaths {
1200 ret := make(WritablePaths, len(paths))
1201 for i, path := range paths {
1202 ret[i] = PathForOutput(ctx, path)
1203 }
1204 return ret
1205}
1206
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001207func (p OutputPath) writablePath() {}
1208
1209func (p OutputPath) String() string {
Colin Crossd63c9a72020-01-29 16:52:50 -08001210 return p.fullPath
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001211}
1212
1213// Join creates a new OutputPath with paths... joined with the current path. The
1214// provided paths... may not use '..' to escape from the current path.
1215func (p OutputPath) Join(ctx PathContext, paths ...string) OutputPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001216 path, err := validatePath(paths...)
1217 if err != nil {
1218 reportPathError(ctx, err)
1219 }
Colin Cross0db55682017-12-05 15:36:55 -08001220 return p.withRel(path)
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001221}
1222
Colin Cross8854a5a2019-02-11 14:14:16 -08001223// ReplaceExtension creates a new OutputPath with the extension replaced with ext.
1224func (p OutputPath) ReplaceExtension(ctx PathContext, ext string) OutputPath {
1225 if strings.Contains(ext, "/") {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001226 ReportPathErrorf(ctx, "extension %q cannot contain /", ext)
Colin Cross8854a5a2019-02-11 14:14:16 -08001227 }
1228 ret := PathForOutput(ctx, pathtools.ReplaceExtension(p.path, ext))
Colin Cross2cdd5df2019-02-25 10:25:24 -08001229 ret.rel = pathtools.ReplaceExtension(p.rel, ext)
Colin Cross8854a5a2019-02-11 14:14:16 -08001230 return ret
1231}
1232
Colin Cross40e33732019-02-15 11:08:35 -08001233// InSameDir creates a new OutputPath from the directory of the current OutputPath joined with the elements in paths.
1234func (p OutputPath) InSameDir(ctx PathContext, paths ...string) OutputPath {
1235 path, err := validatePath(paths...)
1236 if err != nil {
1237 reportPathError(ctx, err)
1238 }
1239
1240 ret := PathForOutput(ctx, filepath.Dir(p.path), path)
Colin Cross2cdd5df2019-02-25 10:25:24 -08001241 ret.rel = filepath.Join(filepath.Dir(p.rel), path)
Colin Cross40e33732019-02-15 11:08:35 -08001242 return ret
1243}
1244
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001245// PathForIntermediates returns an OutputPath representing the top-level
1246// intermediates directory.
1247func PathForIntermediates(ctx PathContext, paths ...string) OutputPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001248 path, err := validatePath(paths...)
1249 if err != nil {
1250 reportPathError(ctx, err)
1251 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001252 return PathForOutput(ctx, ".intermediates", path)
1253}
1254
Colin Cross07e51612019-03-05 12:46:40 -08001255var _ genPathProvider = SourcePath{}
1256var _ objPathProvider = SourcePath{}
1257var _ resPathProvider = SourcePath{}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001258
Colin Cross07e51612019-03-05 12:46:40 -08001259// PathForModuleSrc returns a Path representing the paths... under the
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001260// module's local source directory.
Liz Kammera830f3a2020-11-10 10:50:34 -08001261func PathForModuleSrc(ctx ModuleMissingDepsPathContext, pathComponents ...string) Path {
Colin Cross8a497952019-03-05 22:25:09 -08001262 p, err := validatePath(pathComponents...)
1263 if err != nil {
1264 reportPathError(ctx, err)
Colin Cross192e97a2018-02-22 14:21:02 -08001265 }
Colin Cross8a497952019-03-05 22:25:09 -08001266 paths, err := expandOneSrcPath(ctx, p, nil)
1267 if err != nil {
1268 if depErr, ok := err.(missingDependencyError); ok {
1269 if ctx.Config().AllowMissingDependencies() {
1270 ctx.AddMissingDependencies(depErr.missingDeps)
1271 } else {
1272 ctx.ModuleErrorf(`%s, is the property annotated with android:"path"?`, depErr.Error())
1273 }
1274 } else {
1275 reportPathError(ctx, err)
1276 }
1277 return nil
1278 } else if len(paths) == 0 {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001279 ReportPathErrorf(ctx, "%q produced no files, expected exactly one", p)
Colin Cross8a497952019-03-05 22:25:09 -08001280 return nil
1281 } else if len(paths) > 1 {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001282 ReportPathErrorf(ctx, "%q produced %d files, expected exactly one", p, len(paths))
Colin Cross8a497952019-03-05 22:25:09 -08001283 }
1284 return paths[0]
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001285}
1286
Liz Kammera830f3a2020-11-10 10:50:34 -08001287func pathForModuleSrc(ctx EarlyModulePathContext, paths ...string) SourcePath {
Colin Cross07e51612019-03-05 12:46:40 -08001288 p, err := validatePath(paths...)
1289 if err != nil {
1290 reportPathError(ctx, err)
1291 }
1292
1293 path, err := pathForSource(ctx, ctx.ModuleDir(), p)
1294 if err != nil {
1295 reportPathError(ctx, err)
1296 }
1297
1298 path.basePath.rel = p
1299
1300 return path
1301}
1302
Colin Cross2fafa3e2019-03-05 12:39:51 -08001303// PathsWithModuleSrcSubDir takes a list of Paths and returns a new list of Paths where Rel() on each path
1304// will return the path relative to subDir in the module's source directory. If any input paths are not located
1305// inside subDir then a path error will be reported.
Liz Kammera830f3a2020-11-10 10:50:34 -08001306func PathsWithModuleSrcSubDir(ctx EarlyModulePathContext, paths Paths, subDir string) Paths {
Colin Cross2fafa3e2019-03-05 12:39:51 -08001307 paths = append(Paths(nil), paths...)
Colin Cross07e51612019-03-05 12:46:40 -08001308 subDirFullPath := pathForModuleSrc(ctx, subDir)
Colin Cross2fafa3e2019-03-05 12:39:51 -08001309 for i, path := range paths {
1310 rel := Rel(ctx, subDirFullPath.String(), path.String())
1311 paths[i] = subDirFullPath.join(ctx, rel)
1312 }
1313 return paths
1314}
1315
1316// PathWithModuleSrcSubDir takes a Path and returns a Path where Rel() will return the path relative to subDir in the
1317// 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 -08001318func PathWithModuleSrcSubDir(ctx EarlyModulePathContext, path Path, subDir string) Path {
Colin Cross07e51612019-03-05 12:46:40 -08001319 subDirFullPath := pathForModuleSrc(ctx, subDir)
Colin Cross2fafa3e2019-03-05 12:39:51 -08001320 rel := Rel(ctx, subDirFullPath.String(), path.String())
1321 return subDirFullPath.Join(ctx, rel)
1322}
1323
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001324// OptionalPathForModuleSrc returns an OptionalPath. The OptionalPath contains a
1325// valid path if p is non-nil.
Liz Kammera830f3a2020-11-10 10:50:34 -08001326func OptionalPathForModuleSrc(ctx ModuleMissingDepsPathContext, p *string) OptionalPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001327 if p == nil {
1328 return OptionalPath{}
1329 }
1330 return OptionalPathForPath(PathForModuleSrc(ctx, *p))
1331}
1332
Liz Kammera830f3a2020-11-10 10:50:34 -08001333func (p SourcePath) genPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleGenPath {
Colin Cross7fc17db2017-02-01 14:07:55 -08001334 return PathForModuleGen(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001335}
1336
Liz Kammera830f3a2020-11-10 10:50:34 -08001337func (p SourcePath) objPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleObjPath {
Colin Cross7fc17db2017-02-01 14:07:55 -08001338 return PathForModuleObj(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001339}
1340
Liz Kammera830f3a2020-11-10 10:50:34 -08001341func (p SourcePath) resPathWithName(ctx ModuleOutPathContext, name string) ModuleResPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001342 // TODO: Use full directory if the new ctx is not the current ctx?
1343 return PathForModuleRes(ctx, p.path, name)
1344}
1345
1346// ModuleOutPath is a Path representing a module's output directory.
1347type ModuleOutPath struct {
1348 OutputPath
1349}
1350
1351var _ Path = ModuleOutPath{}
1352
Liz Kammera830f3a2020-11-10 10:50:34 -08001353func (p ModuleOutPath) objPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleObjPath {
Pete Bentleyfcf55bf2019-08-16 20:14:32 +01001354 return PathForModuleObj(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
1355}
1356
Liz Kammera830f3a2020-11-10 10:50:34 -08001357// ModuleOutPathContext Subset of ModuleContext functions necessary for output path methods.
1358type ModuleOutPathContext interface {
1359 PathContext
1360
1361 ModuleName() string
1362 ModuleDir() string
1363 ModuleSubDir() string
1364}
1365
1366func pathForModuleOut(ctx ModuleOutPathContext) OutputPath {
Colin Cross702e0f82017-10-18 17:27:54 -07001367 return PathForOutput(ctx, ".intermediates", ctx.ModuleDir(), ctx.ModuleName(), ctx.ModuleSubDir())
1368}
1369
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001370type BazelOutPath struct {
1371 OutputPath
1372}
1373
1374var _ Path = BazelOutPath{}
1375var _ objPathProvider = BazelOutPath{}
1376
Liz Kammera830f3a2020-11-10 10:50:34 -08001377func (p BazelOutPath) objPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleObjPath {
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001378 return PathForModuleObj(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
1379}
1380
Logan Chien7eefdc42018-07-11 18:10:41 +08001381// PathForVndkRefAbiDump returns an OptionalPath representing the path of the
1382// reference abi dump for the given module. This is not guaranteed to be valid.
Liz Kammera830f3a2020-11-10 10:50:34 -08001383func PathForVndkRefAbiDump(ctx ModuleInstallPathContext, version, fileName string,
Hsin-Yi Chen53489642019-07-31 17:10:45 +08001384 isNdk, isLlndkOrVndk, isGzip bool) OptionalPath {
Logan Chien7eefdc42018-07-11 18:10:41 +08001385
Jayant Chowdharyac066c62018-02-20 10:53:31 -08001386 arches := ctx.DeviceConfig().Arches()
Logan Chien7eefdc42018-07-11 18:10:41 +08001387 if len(arches) == 0 {
1388 panic("device build with no primary arch")
1389 }
Jayant Chowdharyac066c62018-02-20 10:53:31 -08001390 currentArch := ctx.Arch()
1391 archNameAndVariant := currentArch.ArchType.String()
1392 if currentArch.ArchVariant != "" {
1393 archNameAndVariant += "_" + currentArch.ArchVariant
1394 }
Logan Chien5237bed2018-07-11 17:15:57 +08001395
1396 var dirName string
Hsin-Yi Chen53489642019-07-31 17:10:45 +08001397 if isNdk {
Logan Chien5237bed2018-07-11 17:15:57 +08001398 dirName = "ndk"
Hsin-Yi Chen53489642019-07-31 17:10:45 +08001399 } else if isLlndkOrVndk {
Logan Chien5237bed2018-07-11 17:15:57 +08001400 dirName = "vndk"
Logan Chien41eabe62019-04-10 13:33:58 +08001401 } else {
1402 dirName = "platform" // opt-in libs
Jayant Chowdhary3e231fd2017-02-08 13:45:53 -08001403 }
Logan Chien5237bed2018-07-11 17:15:57 +08001404
Jayant Chowdhary34ce67d2018-03-08 11:00:50 -08001405 binderBitness := ctx.DeviceConfig().BinderBitness()
Logan Chien7eefdc42018-07-11 18:10:41 +08001406
1407 var ext string
1408 if isGzip {
1409 ext = ".lsdump.gz"
1410 } else {
1411 ext = ".lsdump"
1412 }
1413
1414 return ExistentPathForSource(ctx, "prebuilts", "abi-dumps", dirName,
1415 version, binderBitness, archNameAndVariant, "source-based",
1416 fileName+ext)
Jayant Chowdhary3e231fd2017-02-08 13:45:53 -08001417}
1418
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001419// PathForBazelOut returns a Path representing the paths... under an output directory dedicated to
1420// bazel-owned outputs.
1421func PathForBazelOut(ctx PathContext, paths ...string) BazelOutPath {
1422 execRootPathComponents := append([]string{"execroot", "__main__"}, paths...)
1423 execRootPath := filepath.Join(execRootPathComponents...)
1424 validatedExecRootPath, err := validatePath(execRootPath)
1425 if err != nil {
1426 reportPathError(ctx, err)
1427 }
1428
1429 outputPath := OutputPath{basePath{"", ctx.Config(), ""},
1430 ctx.Config().BazelContext.OutputBase()}
1431
1432 return BazelOutPath{
1433 OutputPath: outputPath.withRel(validatedExecRootPath),
1434 }
1435}
1436
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001437// PathForModuleOut returns a Path representing the paths... under the module's
1438// output directory.
Liz Kammera830f3a2020-11-10 10:50:34 -08001439func PathForModuleOut(ctx ModuleOutPathContext, paths ...string) ModuleOutPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001440 p, err := validatePath(paths...)
1441 if err != nil {
1442 reportPathError(ctx, err)
1443 }
Colin Cross702e0f82017-10-18 17:27:54 -07001444 return ModuleOutPath{
Liz Kammera830f3a2020-11-10 10:50:34 -08001445 OutputPath: pathForModuleOut(ctx).withRel(p),
Colin Cross702e0f82017-10-18 17:27:54 -07001446 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001447}
1448
1449// ModuleGenPath is a Path representing the 'gen' directory in a module's output
1450// directory. Mainly used for generated sources.
1451type ModuleGenPath struct {
1452 ModuleOutPath
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001453}
1454
1455var _ Path = ModuleGenPath{}
1456var _ genPathProvider = ModuleGenPath{}
1457var _ objPathProvider = ModuleGenPath{}
1458
1459// PathForModuleGen returns a Path representing the paths... under the module's
1460// `gen' directory.
Liz Kammera830f3a2020-11-10 10:50:34 -08001461func PathForModuleGen(ctx ModuleOutPathContext, paths ...string) ModuleGenPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001462 p, err := validatePath(paths...)
1463 if err != nil {
1464 reportPathError(ctx, err)
1465 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001466 return ModuleGenPath{
Colin Cross702e0f82017-10-18 17:27:54 -07001467 ModuleOutPath: ModuleOutPath{
Liz Kammera830f3a2020-11-10 10:50:34 -08001468 OutputPath: pathForModuleOut(ctx).withRel("gen").withRel(p),
Colin Cross702e0f82017-10-18 17:27:54 -07001469 },
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001470 }
1471}
1472
Liz Kammera830f3a2020-11-10 10:50:34 -08001473func (p ModuleGenPath) genPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleGenPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001474 // TODO: make a different path for local vs remote generated files?
Dan Willemsen21ec4902016-11-02 20:43:13 -07001475 return PathForModuleGen(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001476}
1477
Liz Kammera830f3a2020-11-10 10:50:34 -08001478func (p ModuleGenPath) objPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleObjPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001479 return PathForModuleObj(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
1480}
1481
1482// ModuleObjPath is a Path representing the 'obj' directory in a module's output
1483// directory. Used for compiled objects.
1484type ModuleObjPath struct {
1485 ModuleOutPath
1486}
1487
1488var _ Path = ModuleObjPath{}
1489
1490// PathForModuleObj returns a Path representing the paths... under the module's
1491// 'obj' directory.
Liz Kammera830f3a2020-11-10 10:50:34 -08001492func PathForModuleObj(ctx ModuleOutPathContext, pathComponents ...string) ModuleObjPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001493 p, err := validatePath(pathComponents...)
1494 if err != nil {
1495 reportPathError(ctx, err)
1496 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001497 return ModuleObjPath{PathForModuleOut(ctx, "obj", p)}
1498}
1499
1500// ModuleResPath is a a Path representing the 'res' directory in a module's
1501// output directory.
1502type ModuleResPath struct {
1503 ModuleOutPath
1504}
1505
1506var _ Path = ModuleResPath{}
1507
1508// PathForModuleRes returns a Path representing the paths... under the module's
1509// 'res' directory.
Liz Kammera830f3a2020-11-10 10:50:34 -08001510func PathForModuleRes(ctx ModuleOutPathContext, pathComponents ...string) ModuleResPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001511 p, err := validatePath(pathComponents...)
1512 if err != nil {
1513 reportPathError(ctx, err)
1514 }
1515
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001516 return ModuleResPath{PathForModuleOut(ctx, "res", p)}
1517}
1518
Colin Cross70dda7e2019-10-01 22:05:35 -07001519// InstallPath is a Path representing a installed file path rooted from the build directory
1520type InstallPath struct {
1521 basePath
Colin Crossff6c33d2019-10-02 16:01:35 -07001522
Jiyong Park957bcd92020-10-20 18:23:33 +09001523 // partitionDir is the part of the InstallPath that is automatically determined according to the context.
1524 // For example, it is host/<os>-<arch> for host modules, and target/product/<device>/<partition> for device modules.
1525 partitionDir string
1526
1527 // makePath indicates whether this path is for Soong (false) or Make (true).
1528 makePath bool
Colin Cross70dda7e2019-10-01 22:05:35 -07001529}
1530
Paul Duffin9b478b02019-12-10 13:41:51 +00001531func (p InstallPath) buildDir() string {
1532 return p.config.buildDir
1533}
1534
Hans MÃ¥nssond3f2bd72020-11-27 12:37:28 +01001535func (p InstallPath) ReplaceExtension(ctx PathContext, ext string) OutputPath {
1536 panic("Not implemented")
1537}
1538
Paul Duffin9b478b02019-12-10 13:41:51 +00001539var _ Path = InstallPath{}
1540var _ WritablePath = InstallPath{}
1541
Colin Cross70dda7e2019-10-01 22:05:35 -07001542func (p InstallPath) writablePath() {}
1543
1544func (p InstallPath) String() string {
Jiyong Park957bcd92020-10-20 18:23:33 +09001545 if p.makePath {
1546 // Make path starts with out/ instead of out/soong.
1547 return filepath.Join(p.config.buildDir, "../", p.path)
1548 } else {
1549 return filepath.Join(p.config.buildDir, p.path)
1550 }
1551}
1552
1553// PartitionDir returns the path to the partition where the install path is rooted at. It is
1554// out/soong/target/product/<device>/<partition> for device modules, and out/soong/host/<os>-<arch> for host modules.
1555// The ./soong is dropped if the install path is for Make.
1556func (p InstallPath) PartitionDir() string {
1557 if p.makePath {
1558 return filepath.Join(p.config.buildDir, "../", p.partitionDir)
1559 } else {
1560 return filepath.Join(p.config.buildDir, p.partitionDir)
1561 }
Colin Cross70dda7e2019-10-01 22:05:35 -07001562}
1563
1564// Join creates a new InstallPath with paths... joined with the current path. The
1565// provided paths... may not use '..' to escape from the current path.
1566func (p InstallPath) Join(ctx PathContext, paths ...string) InstallPath {
1567 path, err := validatePath(paths...)
1568 if err != nil {
1569 reportPathError(ctx, err)
1570 }
1571 return p.withRel(path)
1572}
1573
1574func (p InstallPath) withRel(rel string) InstallPath {
1575 p.basePath = p.basePath.withRel(rel)
1576 return p
1577}
1578
Colin Crossff6c33d2019-10-02 16:01:35 -07001579// ToMakePath returns a new InstallPath that points to Make's install directory instead of Soong's,
1580// i.e. out/ instead of out/soong/.
1581func (p InstallPath) ToMakePath() InstallPath {
Jiyong Park957bcd92020-10-20 18:23:33 +09001582 p.makePath = true
Colin Crossff6c33d2019-10-02 16:01:35 -07001583 return p
Colin Cross70dda7e2019-10-01 22:05:35 -07001584}
1585
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001586// PathForModuleInstall returns a Path representing the install path for the
1587// module appended with paths...
Colin Cross70dda7e2019-10-01 22:05:35 -07001588func PathForModuleInstall(ctx ModuleInstallPathContext, pathComponents ...string) InstallPath {
Colin Cross6e359402020-02-10 15:29:54 -08001589 os := ctx.Os()
Jiyong Park87788b52020-09-01 12:37:45 +09001590 arch := ctx.Arch().ArchType
1591 forceOS, forceArch := ctx.InstallForceOS()
1592 if forceOS != nil {
Colin Cross6e359402020-02-10 15:29:54 -08001593 os = *forceOS
1594 }
Jiyong Park87788b52020-09-01 12:37:45 +09001595 if forceArch != nil {
1596 arch = *forceArch
1597 }
Colin Cross6e359402020-02-10 15:29:54 -08001598 partition := modulePartition(ctx, os)
Colin Cross609c49a2020-02-13 13:20:11 -08001599
Jiyong Park87788b52020-09-01 12:37:45 +09001600 ret := pathForInstall(ctx, os, arch, partition, ctx.Debug(), pathComponents...)
Colin Cross609c49a2020-02-13 13:20:11 -08001601
Jingwen Chencda22c92020-11-23 00:22:30 -05001602 if ctx.InstallBypassMake() && ctx.Config().KatiEnabled() {
Colin Cross609c49a2020-02-13 13:20:11 -08001603 ret = ret.ToMakePath()
1604 }
1605
1606 return ret
1607}
1608
Jiyong Park87788b52020-09-01 12:37:45 +09001609func pathForInstall(ctx PathContext, os OsType, arch ArchType, partition string, debug bool,
Colin Cross609c49a2020-02-13 13:20:11 -08001610 pathComponents ...string) InstallPath {
1611
Jiyong Park957bcd92020-10-20 18:23:33 +09001612 var partionPaths []string
Colin Cross609c49a2020-02-13 13:20:11 -08001613
Colin Cross6e359402020-02-10 15:29:54 -08001614 if os.Class == Device {
Jiyong Park957bcd92020-10-20 18:23:33 +09001615 partionPaths = []string{"target", "product", ctx.Config().DeviceName(), partition}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001616 } else {
Jiyong Park87788b52020-09-01 12:37:45 +09001617 osName := os.String()
1618 if os == Linux {
1619 // instead of linux_glibc
1620 osName = "linux"
Dan Willemsen866b5632017-09-22 12:28:24 -07001621 }
Jiyong Park87788b52020-09-01 12:37:45 +09001622 // SOONG_HOST_OUT is set to out/host/$(HOST_OS)-$(HOST_PREBUILT_ARCH)
1623 // and HOST_PREBUILT_ARCH is forcibly set to x86 even on x86_64 hosts. We don't seem
1624 // to have a plan to fix it (see the comment in build/make/core/envsetup.mk).
1625 // Let's keep using x86 for the existing cases until we have a need to support
1626 // other architectures.
1627 archName := arch.String()
1628 if os.Class == Host && (arch == X86_64 || arch == Common) {
1629 archName = "x86"
1630 }
Jiyong Park957bcd92020-10-20 18:23:33 +09001631 partionPaths = []string{"host", osName + "-" + archName, partition}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001632 }
Colin Cross609c49a2020-02-13 13:20:11 -08001633 if debug {
Jiyong Park957bcd92020-10-20 18:23:33 +09001634 partionPaths = append([]string{"debug"}, partionPaths...)
Dan Willemsen782a2d12015-12-21 14:55:28 -08001635 }
Colin Cross70dda7e2019-10-01 22:05:35 -07001636
Jiyong Park957bcd92020-10-20 18:23:33 +09001637 partionPath, err := validatePath(partionPaths...)
Colin Cross70dda7e2019-10-01 22:05:35 -07001638 if err != nil {
1639 reportPathError(ctx, err)
1640 }
Colin Crossff6c33d2019-10-02 16:01:35 -07001641
Jiyong Park957bcd92020-10-20 18:23:33 +09001642 base := InstallPath{
1643 basePath: basePath{partionPath, ctx.Config(), ""},
1644 partitionDir: partionPath,
1645 makePath: false,
1646 }
Colin Crossff6c33d2019-10-02 16:01:35 -07001647
Jiyong Park957bcd92020-10-20 18:23:33 +09001648 return base.Join(ctx, pathComponents...)
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001649}
1650
Nicolas Geoffray1228e9c2020-02-27 13:45:35 +00001651func pathForNdkOrSdkInstall(ctx PathContext, prefix string, paths []string) InstallPath {
Jiyong Park957bcd92020-10-20 18:23:33 +09001652 base := InstallPath{
1653 basePath: basePath{prefix, ctx.Config(), ""},
1654 partitionDir: prefix,
1655 makePath: false,
Colin Cross70dda7e2019-10-01 22:05:35 -07001656 }
Jiyong Park957bcd92020-10-20 18:23:33 +09001657 return base.Join(ctx, paths...)
Colin Cross70dda7e2019-10-01 22:05:35 -07001658}
1659
Nicolas Geoffray1228e9c2020-02-27 13:45:35 +00001660func PathForNdkInstall(ctx PathContext, paths ...string) InstallPath {
1661 return pathForNdkOrSdkInstall(ctx, "ndk", paths)
1662}
1663
1664func PathForMainlineSdksInstall(ctx PathContext, paths ...string) InstallPath {
1665 return pathForNdkOrSdkInstall(ctx, "mainline-sdks", paths)
1666}
1667
Colin Cross70dda7e2019-10-01 22:05:35 -07001668func InstallPathToOnDevicePath(ctx PathContext, path InstallPath) string {
Colin Cross43f08db2018-11-12 10:13:39 -08001669 rel := Rel(ctx, PathForOutput(ctx, "target", "product", ctx.Config().DeviceName()).String(), path.String())
1670
1671 return "/" + rel
1672}
1673
Colin Cross6e359402020-02-10 15:29:54 -08001674func modulePartition(ctx ModuleInstallPathContext, os OsType) string {
Colin Cross43f08db2018-11-12 10:13:39 -08001675 var partition string
Colin Cross6e359402020-02-10 15:29:54 -08001676 if ctx.InstallInTestcases() {
1677 // "testcases" install directory can be used for host or device modules.
Jaewoong Jung0949f312019-09-11 10:25:18 -07001678 partition = "testcases"
Colin Cross6e359402020-02-10 15:29:54 -08001679 } else if os.Class == Device {
1680 if ctx.InstallInData() {
1681 partition = "data"
1682 } else if ctx.InstallInRamdisk() {
1683 if ctx.DeviceConfig().BoardUsesRecoveryAsBoot() {
1684 partition = "recovery/root/first_stage_ramdisk"
1685 } else {
1686 partition = "ramdisk"
1687 }
1688 if !ctx.InstallInRoot() {
1689 partition += "/system"
1690 }
Yifan Hong60e0cfb2020-10-21 15:17:56 -07001691 } else if ctx.InstallInVendorRamdisk() {
Yifan Hong39143a92020-10-26 12:43:12 -07001692 // The module is only available after switching root into
1693 // /first_stage_ramdisk. To expose the module before switching root
1694 // on a device without a dedicated recovery partition, install the
1695 // recovery variant.
Yifan Hongdd8dacc2020-10-21 15:40:17 -07001696 if ctx.DeviceConfig().BoardMoveRecoveryResourcesToVendorBoot() {
Petri Gyntherac229562021-03-02 23:44:02 -08001697 partition = "vendor_ramdisk/first_stage_ramdisk"
Yifan Hongdd8dacc2020-10-21 15:40:17 -07001698 } else {
Petri Gyntherac229562021-03-02 23:44:02 -08001699 partition = "vendor_ramdisk"
Yifan Hongdd8dacc2020-10-21 15:40:17 -07001700 }
1701 if !ctx.InstallInRoot() {
1702 partition += "/system"
1703 }
Colin Cross6e359402020-02-10 15:29:54 -08001704 } else if ctx.InstallInRecovery() {
1705 if ctx.InstallInRoot() {
1706 partition = "recovery/root"
1707 } else {
1708 // the layout of recovery partion is the same as that of system partition
1709 partition = "recovery/root/system"
1710 }
1711 } else if ctx.SocSpecific() {
1712 partition = ctx.DeviceConfig().VendorPath()
1713 } else if ctx.DeviceSpecific() {
1714 partition = ctx.DeviceConfig().OdmPath()
1715 } else if ctx.ProductSpecific() {
1716 partition = ctx.DeviceConfig().ProductPath()
1717 } else if ctx.SystemExtSpecific() {
1718 partition = ctx.DeviceConfig().SystemExtPath()
1719 } else if ctx.InstallInRoot() {
1720 partition = "root"
Yifan Hong82db7352020-01-21 16:12:26 -08001721 } else {
Colin Cross6e359402020-02-10 15:29:54 -08001722 partition = "system"
Yifan Hong82db7352020-01-21 16:12:26 -08001723 }
Colin Cross6e359402020-02-10 15:29:54 -08001724 if ctx.InstallInSanitizerDir() {
1725 partition = "data/asan/" + partition
Yifan Hong82db7352020-01-21 16:12:26 -08001726 }
Colin Cross43f08db2018-11-12 10:13:39 -08001727 }
1728 return partition
1729}
1730
Colin Cross609c49a2020-02-13 13:20:11 -08001731type InstallPaths []InstallPath
1732
1733// Paths returns the InstallPaths as a Paths
1734func (p InstallPaths) Paths() Paths {
1735 if p == nil {
1736 return nil
1737 }
1738 ret := make(Paths, len(p))
1739 for i, path := range p {
1740 ret[i] = path
1741 }
1742 return ret
1743}
1744
1745// Strings returns the string forms of the install paths.
1746func (p InstallPaths) Strings() []string {
1747 if p == nil {
1748 return nil
1749 }
1750 ret := make([]string, len(p))
1751 for i, path := range p {
1752 ret[i] = path.String()
1753 }
1754 return ret
1755}
1756
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001757// validateSafePath validates a path that we trust (may contain ninja variables).
Dan Willemsen80a7c2a2015-12-21 14:57:11 -08001758// Ensures that each path component does not attempt to leave its component.
Colin Cross1ccfcc32018-02-22 13:54:26 -08001759func validateSafePath(pathComponents ...string) (string, error) {
Jeff Gaston734e3802017-04-10 15:47:24 -07001760 for _, path := range pathComponents {
Dan Willemsen80a7c2a2015-12-21 14:57:11 -08001761 path := filepath.Clean(path)
1762 if path == ".." || strings.HasPrefix(path, "../") || strings.HasPrefix(path, "/") {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001763 return "", fmt.Errorf("Path is outside directory: %s", path)
Dan Willemsen80a7c2a2015-12-21 14:57:11 -08001764 }
1765 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001766 // TODO: filepath.Join isn't necessarily correct with embedded ninja
1767 // variables. '..' may remove the entire ninja variable, even if it
1768 // will be expanded to multiple nested directories.
Colin Cross1ccfcc32018-02-22 13:54:26 -08001769 return filepath.Join(pathComponents...), nil
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001770}
1771
Dan Willemsen80a7c2a2015-12-21 14:57:11 -08001772// validatePath validates that a path does not include ninja variables, and that
1773// each path component does not attempt to leave its component. Returns a joined
1774// version of each path component.
Colin Cross1ccfcc32018-02-22 13:54:26 -08001775func validatePath(pathComponents ...string) (string, error) {
Jeff Gaston734e3802017-04-10 15:47:24 -07001776 for _, path := range pathComponents {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001777 if strings.Contains(path, "$") {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001778 return "", fmt.Errorf("Path contains invalid character($): %s", path)
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001779 }
1780 }
Colin Cross1ccfcc32018-02-22 13:54:26 -08001781 return validateSafePath(pathComponents...)
Colin Cross6e18ca42015-07-14 18:55:36 -07001782}
Colin Cross5b529592017-05-09 13:34:34 -07001783
Colin Cross0875c522017-11-28 17:34:01 -08001784func PathForPhony(ctx PathContext, phony string) WritablePath {
1785 if strings.ContainsAny(phony, "$/") {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001786 ReportPathErrorf(ctx, "Phony target contains invalid character ($ or /): %s", phony)
Colin Cross0875c522017-11-28 17:34:01 -08001787 }
Colin Cross74e3fe42017-12-11 15:51:44 -08001788 return PhonyPath{basePath{phony, ctx.Config(), ""}}
Colin Cross0875c522017-11-28 17:34:01 -08001789}
1790
Colin Cross74e3fe42017-12-11 15:51:44 -08001791type PhonyPath struct {
1792 basePath
1793}
1794
1795func (p PhonyPath) writablePath() {}
1796
Paul Duffin9b478b02019-12-10 13:41:51 +00001797func (p PhonyPath) buildDir() string {
1798 return p.config.buildDir
1799}
1800
Hans MÃ¥nssond3f2bd72020-11-27 12:37:28 +01001801func (p PhonyPath) ReplaceExtension(ctx PathContext, ext string) OutputPath {
1802 panic("Not implemented")
1803}
1804
Colin Cross74e3fe42017-12-11 15:51:44 -08001805var _ Path = PhonyPath{}
1806var _ WritablePath = PhonyPath{}
1807
Colin Cross5b529592017-05-09 13:34:34 -07001808type testPath struct {
1809 basePath
1810}
1811
1812func (p testPath) String() string {
1813 return p.path
1814}
1815
Colin Cross40e33732019-02-15 11:08:35 -08001816// PathForTesting returns a Path constructed from joining the elements of paths with '/'. It should only be used from
1817// within tests.
Colin Cross5b529592017-05-09 13:34:34 -07001818func PathForTesting(paths ...string) Path {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001819 p, err := validateSafePath(paths...)
1820 if err != nil {
1821 panic(err)
1822 }
Colin Cross5b529592017-05-09 13:34:34 -07001823 return testPath{basePath{path: p, rel: p}}
1824}
1825
Colin Cross40e33732019-02-15 11:08:35 -08001826// PathsForTesting returns a Path constructed from each element in strs. It should only be used from within tests.
1827func PathsForTesting(strs ...string) Paths {
Colin Cross5b529592017-05-09 13:34:34 -07001828 p := make(Paths, len(strs))
1829 for i, s := range strs {
1830 p[i] = PathForTesting(s)
1831 }
1832
1833 return p
1834}
Colin Cross43f08db2018-11-12 10:13:39 -08001835
Colin Cross40e33732019-02-15 11:08:35 -08001836type testPathContext struct {
1837 config Config
Colin Cross40e33732019-02-15 11:08:35 -08001838}
1839
Colin Cross40e33732019-02-15 11:08:35 -08001840func (x *testPathContext) Config() Config { return x.config }
1841func (x *testPathContext) AddNinjaFileDeps(...string) {}
1842
1843// PathContextForTesting returns a PathContext that can be used in tests, for example to create an OutputPath with
1844// PathForOutput.
Colin Cross98be1bb2019-12-13 20:41:13 -08001845func PathContextForTesting(config Config) PathContext {
Colin Cross40e33732019-02-15 11:08:35 -08001846 return &testPathContext{
1847 config: config,
Colin Cross40e33732019-02-15 11:08:35 -08001848 }
1849}
1850
Ulya Trafimovichccc8c852020-10-14 11:29:07 +01001851type testModuleInstallPathContext struct {
1852 baseModuleContext
1853
1854 inData bool
1855 inTestcases bool
1856 inSanitizerDir bool
1857 inRamdisk bool
1858 inVendorRamdisk bool
1859 inRecovery bool
1860 inRoot bool
1861 forceOS *OsType
1862 forceArch *ArchType
1863}
1864
1865func (m testModuleInstallPathContext) Config() Config {
1866 return m.baseModuleContext.config
1867}
1868
1869func (testModuleInstallPathContext) AddNinjaFileDeps(deps ...string) {}
1870
1871func (m testModuleInstallPathContext) InstallInData() bool {
1872 return m.inData
1873}
1874
1875func (m testModuleInstallPathContext) InstallInTestcases() bool {
1876 return m.inTestcases
1877}
1878
1879func (m testModuleInstallPathContext) InstallInSanitizerDir() bool {
1880 return m.inSanitizerDir
1881}
1882
1883func (m testModuleInstallPathContext) InstallInRamdisk() bool {
1884 return m.inRamdisk
1885}
1886
1887func (m testModuleInstallPathContext) InstallInVendorRamdisk() bool {
1888 return m.inVendorRamdisk
1889}
1890
1891func (m testModuleInstallPathContext) InstallInRecovery() bool {
1892 return m.inRecovery
1893}
1894
1895func (m testModuleInstallPathContext) InstallInRoot() bool {
1896 return m.inRoot
1897}
1898
1899func (m testModuleInstallPathContext) InstallBypassMake() bool {
1900 return false
1901}
1902
1903func (m testModuleInstallPathContext) InstallForceOS() (*OsType, *ArchType) {
1904 return m.forceOS, m.forceArch
1905}
1906
1907// Construct a minimal ModuleInstallPathContext for testing. Note that baseModuleContext is
1908// default-initialized, which leaves blueprint.baseModuleContext set to nil, so methods that are
1909// delegated to it will panic.
1910func ModuleInstallPathContextForTesting(config Config) ModuleInstallPathContext {
1911 ctx := &testModuleInstallPathContext{}
1912 ctx.config = config
1913 ctx.os = Android
1914 return ctx
1915}
1916
Colin Cross43f08db2018-11-12 10:13:39 -08001917// Rel performs the same function as filepath.Rel, but reports errors to a PathContext, and reports an error if
1918// targetPath is not inside basePath.
1919func Rel(ctx PathContext, basePath string, targetPath string) string {
1920 rel, isRel := MaybeRel(ctx, basePath, targetPath)
1921 if !isRel {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001922 ReportPathErrorf(ctx, "path %q is not under path %q", targetPath, basePath)
Colin Cross43f08db2018-11-12 10:13:39 -08001923 return ""
1924 }
1925 return rel
1926}
1927
1928// MaybeRel performs the same function as filepath.Rel, but reports errors to a PathContext, and returns false if
1929// targetPath is not inside basePath.
1930func MaybeRel(ctx PathContext, basePath string, targetPath string) (string, bool) {
Dan Willemsen633c5022019-04-12 11:11:38 -07001931 rel, isRel, err := maybeRelErr(basePath, targetPath)
1932 if err != nil {
1933 reportPathError(ctx, err)
1934 }
1935 return rel, isRel
1936}
1937
1938func maybeRelErr(basePath string, targetPath string) (string, bool, error) {
Colin Cross43f08db2018-11-12 10:13:39 -08001939 // filepath.Rel returns an error if one path is absolute and the other is not, handle that case first.
1940 if filepath.IsAbs(basePath) != filepath.IsAbs(targetPath) {
Dan Willemsen633c5022019-04-12 11:11:38 -07001941 return "", false, nil
Colin Cross43f08db2018-11-12 10:13:39 -08001942 }
1943 rel, err := filepath.Rel(basePath, targetPath)
1944 if err != nil {
Dan Willemsen633c5022019-04-12 11:11:38 -07001945 return "", false, err
Colin Cross43f08db2018-11-12 10:13:39 -08001946 } else if rel == ".." || strings.HasPrefix(rel, "../") || strings.HasPrefix(rel, "/") {
Dan Willemsen633c5022019-04-12 11:11:38 -07001947 return "", false, nil
Colin Cross43f08db2018-11-12 10:13:39 -08001948 }
Dan Willemsen633c5022019-04-12 11:11:38 -07001949 return rel, true, nil
Colin Cross43f08db2018-11-12 10:13:39 -08001950}
Colin Cross988414c2020-01-11 01:11:46 +00001951
1952// Writes a file to the output directory. Attempting to write directly to the output directory
1953// will fail due to the sandbox of the soong_build process.
1954func WriteFileToOutputDir(path WritablePath, data []byte, perm os.FileMode) error {
1955 return ioutil.WriteFile(absolutePath(path.String()), data, perm)
1956}
1957
Liz Kammer2dd9ca42020-11-25 16:06:39 -08001958func RemoveAllOutputDir(path WritablePath) error {
1959 return os.RemoveAll(absolutePath(path.String()))
1960}
1961
1962func CreateOutputDirIfNonexistent(path WritablePath, perm os.FileMode) error {
1963 dir := absolutePath(path.String())
1964 if _, err := os.Stat(dir); os.IsNotExist(err) {
1965 return os.MkdirAll(dir, os.ModePerm)
1966 } else {
1967 return err
1968 }
1969}
1970
Colin Cross988414c2020-01-11 01:11:46 +00001971func absolutePath(path string) string {
1972 if filepath.IsAbs(path) {
1973 return path
1974 }
1975 return filepath.Join(absSrcDir, path)
1976}
Chris Parsons216e10a2020-07-09 17:12:52 -04001977
1978// A DataPath represents the path of a file to be used as data, for example
1979// a test library to be installed alongside a test.
1980// The data file should be installed (copied from `<SrcPath>`) to
1981// `<install_root>/<RelativeInstallPath>/<filename>`, or
1982// `<install_root>/<filename>` if RelativeInstallPath is empty.
1983type DataPath struct {
1984 // The path of the data file that should be copied into the data directory
1985 SrcPath Path
1986 // The install path of the data file, relative to the install root.
1987 RelativeInstallPath string
1988}
Colin Crossdcf71b22021-02-01 13:59:03 -08001989
1990// PathsIfNonNil returns a Paths containing only the non-nil input arguments.
1991func PathsIfNonNil(paths ...Path) Paths {
1992 if len(paths) == 0 {
1993 // Fast path for empty argument list
1994 return nil
1995 } else if len(paths) == 1 {
1996 // Fast path for a single argument
1997 if paths[0] != nil {
1998 return paths
1999 } else {
2000 return nil
2001 }
2002 }
2003 ret := make(Paths, 0, len(paths))
2004 for _, path := range paths {
2005 if path != nil {
2006 ret = append(ret, path)
2007 }
2008 }
2009 if len(ret) == 0 {
2010 return nil
2011 }
2012 return ret
2013}