blob: ada4da692faa959b0f48f5387c838bb999b77873 [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)
342 OtherModuleName(m blueprint.Module) string
343 OtherModuleDir(m blueprint.Module) string
344}
345
346// BazelLabelForModuleDeps returns a Bazel-compatible label for the requested modules which
347// correspond to dependencies on the module within the given ctx.
348func BazelLabelForModuleDeps(ctx BazelConversionPathContext, modules []string) bazel.LabelList {
349 var labels bazel.LabelList
350 for _, module := range modules {
351 bpText := module
352 if m := SrcIsModule(module); m == "" {
353 module = ":" + module
354 }
355 if m, t := SrcIsModuleWithTag(module); m != "" {
356 l := getOtherModuleLabel(ctx, m, t)
357 l.Bp_text = bpText
358 labels.Includes = append(labels.Includes, l)
359 } else {
360 ctx.ModuleErrorf("%q, is not a module reference", module)
361 }
362 }
363 return labels
364}
365
366// BazelLabelForModuleSrc returns bazel.LabelList with paths rooted from the module's local source
367// directory. It expands globs, and resolves references to modules using the ":name" syntax to
368// bazel-compatible labels. Properties passed as the paths or excludes argument must have been
369// annotated with struct tag `android:"path"` so that dependencies on other modules will have
370// already been handled by the path_properties mutator.
371func BazelLabelForModuleSrc(ctx BazelConversionPathContext, paths []string) bazel.LabelList {
372 return BazelLabelForModuleSrcExcludes(ctx, paths, []string(nil))
373}
374
375// BazelLabelForModuleSrcExcludes returns bazel.LabelList with paths rooted from the module's local
376// source directory, excluding labels included in the excludes argument. It expands globs, and
377// resolves references to modules using the ":name" syntax to bazel-compatible labels. Properties
378// passed as the paths or excludes argument must have been annotated with struct tag
379// `android:"path"` so that dependencies on other modules will have already been handled by the
380// path_properties mutator.
381func BazelLabelForModuleSrcExcludes(ctx BazelConversionPathContext, paths, excludes []string) bazel.LabelList {
382 excludeLabels := expandSrcsForBazel(ctx, excludes, []string(nil))
383 excluded := make([]string, 0, len(excludeLabels.Includes))
384 for _, e := range excludeLabels.Includes {
385 excluded = append(excluded, e.Label)
386 }
387 labels := expandSrcsForBazel(ctx, paths, excluded)
388 labels.Excludes = excludeLabels.Includes
389 return labels
390}
391
392// expandSrcsForBazel returns bazel.LabelList with paths rooted from the module's local
393// source directory, excluding labels included in the excludes argument. It expands globs, and
394// resolves references to modules using the ":name" syntax to bazel-compatible labels. Properties
395// passed as the paths or excludes argument must have been annotated with struct tag
396// `android:"path"` so that dependencies on other modules will have already been handled by the
397// path_properties mutator.
398func expandSrcsForBazel(ctx BazelConversionPathContext, paths, expandedExcludes []string) bazel.LabelList {
Liz Kammerebfcf672021-02-16 15:00:05 -0500399 if paths == nil {
400 return bazel.LabelList{}
401 }
Liz Kammer356f7d42021-01-26 09:18:53 -0500402 labels := bazel.LabelList{
403 Includes: []bazel.Label{},
404 }
405 for _, p := range paths {
406 if m, tag := SrcIsModuleWithTag(p); m != "" {
407 l := getOtherModuleLabel(ctx, m, tag)
408 if !InList(l.Label, expandedExcludes) {
409 l.Bp_text = fmt.Sprintf(":%s", m)
410 labels.Includes = append(labels.Includes, l)
411 }
412 } else {
413 var expandedPaths []bazel.Label
414 if pathtools.IsGlob(p) {
415 globbedPaths := GlobFiles(ctx, pathForModuleSrc(ctx, p).String(), expandedExcludes)
416 globbedPaths = PathsWithModuleSrcSubDir(ctx, globbedPaths, "")
417 for _, path := range globbedPaths {
418 s := path.Rel()
419 expandedPaths = append(expandedPaths, bazel.Label{Label: s})
420 }
421 } else {
422 if !InList(p, expandedExcludes) {
423 expandedPaths = append(expandedPaths, bazel.Label{Label: p})
424 }
425 }
426 labels.Includes = append(labels.Includes, expandedPaths...)
427 }
428 }
429 return labels
430}
431
432// getOtherModuleLabel returns a bazel.Label for the given dependency/tag combination for the
433// module. The label will be relative to the current directory if appropriate. The dependency must
434// already be resolved by either deps mutator or path deps mutator.
435func getOtherModuleLabel(ctx BazelConversionPathContext, dep, tag string) bazel.Label {
436 m, _ := ctx.GetDirectDep(dep)
437 // TODO(b/165114590): Convert tag (":name{.tag}") to corresponding Bazel implicit output targets.
438 otherModuleName := ctx.OtherModuleName(m)
439 var label bazel.Label
440 if otherDir, dir := ctx.OtherModuleDir(m), ctx.ModuleDir(); otherDir != dir {
441 label.Label = fmt.Sprintf("//%s:%s", otherDir, otherModuleName)
442 } else {
443 label.Label = fmt.Sprintf(":%s", otherModuleName)
444 }
445 return label
446}
447
Ulya Trafimovich4d2eeed2019-11-08 10:54:21 +0000448// OutputPaths is a slice of OutputPath objects, with helpers to operate on the collection.
449type OutputPaths []OutputPath
450
451// Paths returns the OutputPaths as a Paths
452func (p OutputPaths) Paths() Paths {
453 if p == nil {
454 return nil
455 }
456 ret := make(Paths, len(p))
457 for i, path := range p {
458 ret[i] = path
459 }
460 return ret
461}
462
463// Strings returns the string forms of the writable paths.
464func (p OutputPaths) Strings() []string {
465 if p == nil {
466 return nil
467 }
468 ret := make([]string, len(p))
469 for i, path := range p {
470 ret[i] = path.String()
471 }
472 return ret
473}
474
Liz Kammera830f3a2020-11-10 10:50:34 -0800475// Expands Paths to a SourceFileProducer or OutputFileProducer module dependency referenced via ":name" or ":name{.tag}" syntax.
476// If the dependency is not found, a missingErrorDependency is returned.
477// If the module dependency is not a SourceFileProducer or OutputFileProducer, appropriate errors will be returned.
478func getPathsFromModuleDep(ctx ModuleWithDepsPathContext, path, moduleName, tag string) (Paths, error) {
479 module := ctx.GetDirectDepWithTag(moduleName, sourceOrOutputDepTag(tag))
480 if module == nil {
481 return nil, missingDependencyError{[]string{moduleName}}
482 }
483 if outProducer, ok := module.(OutputFileProducer); ok {
484 outputFiles, err := outProducer.OutputFiles(tag)
485 if err != nil {
486 return nil, fmt.Errorf("path dependency %q: %s", path, err)
487 }
488 return outputFiles, nil
489 } else if tag != "" {
490 return nil, fmt.Errorf("path dependency %q is not an output file producing module", path)
491 } else if srcProducer, ok := module.(SourceFileProducer); ok {
492 return srcProducer.Srcs(), nil
493 } else {
494 return nil, fmt.Errorf("path dependency %q is not a source file producing module", path)
495 }
496}
497
Colin Crossba71a3f2019-03-18 12:12:48 -0700498// PathsAndMissingDepsForModuleSrcExcludes returns Paths rooted from the module's local source directory, excluding
Colin Cross41955e82019-05-29 14:40:35 -0700499// paths listed in the excludes arguments, and a list of missing dependencies. It expands globs, references to
500// SourceFileProducer modules using the ":name" syntax, and references to OutputFileProducer modules using the
501// ":name{.tag}" syntax. Properties passed as the paths or excludes argument must have been annotated with struct tag
502// `android:"path"` so that dependencies on SourceFileProducer modules will have already been handled by the
503// path_properties mutator. If ctx.Config().AllowMissingDependencies() is true then any missing SourceFileProducer or
504// OutputFileProducer dependencies will be returned, and they will NOT cause the module to be marked as having missing
505// dependencies.
Liz Kammera830f3a2020-11-10 10:50:34 -0800506func PathsAndMissingDepsForModuleSrcExcludes(ctx ModuleWithDepsPathContext, paths, excludes []string) (Paths, []string) {
Colin Cross8a497952019-03-05 22:25:09 -0800507 prefix := pathForModuleSrc(ctx).String()
508
509 var expandedExcludes []string
510 if excludes != nil {
511 expandedExcludes = make([]string, 0, len(excludes))
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700512 }
Colin Cross8a497952019-03-05 22:25:09 -0800513
Colin Crossba71a3f2019-03-18 12:12:48 -0700514 var missingExcludeDeps []string
515
Colin Cross8a497952019-03-05 22:25:09 -0800516 for _, e := range excludes {
Colin Cross41955e82019-05-29 14:40:35 -0700517 if m, t := SrcIsModuleWithTag(e); m != "" {
Liz Kammera830f3a2020-11-10 10:50:34 -0800518 modulePaths, err := getPathsFromModuleDep(ctx, e, m, t)
519 if m, ok := err.(missingDependencyError); ok {
520 missingExcludeDeps = append(missingExcludeDeps, m.missingDeps...)
521 } else if err != nil {
522 reportPathError(ctx, err)
Colin Cross8a497952019-03-05 22:25:09 -0800523 } else {
Liz Kammera830f3a2020-11-10 10:50:34 -0800524 expandedExcludes = append(expandedExcludes, modulePaths.Strings()...)
Colin Cross8a497952019-03-05 22:25:09 -0800525 }
526 } else {
527 expandedExcludes = append(expandedExcludes, filepath.Join(prefix, e))
528 }
529 }
530
531 if paths == nil {
Colin Crossba71a3f2019-03-18 12:12:48 -0700532 return nil, missingExcludeDeps
Colin Cross8a497952019-03-05 22:25:09 -0800533 }
534
Colin Crossba71a3f2019-03-18 12:12:48 -0700535 var missingDeps []string
536
Colin Cross8a497952019-03-05 22:25:09 -0800537 expandedSrcFiles := make(Paths, 0, len(paths))
538 for _, s := range paths {
539 srcFiles, err := expandOneSrcPath(ctx, s, expandedExcludes)
540 if depErr, ok := err.(missingDependencyError); ok {
Colin Crossba71a3f2019-03-18 12:12:48 -0700541 missingDeps = append(missingDeps, depErr.missingDeps...)
Colin Cross8a497952019-03-05 22:25:09 -0800542 } else if err != nil {
543 reportPathError(ctx, err)
544 }
545 expandedSrcFiles = append(expandedSrcFiles, srcFiles...)
546 }
Colin Crossba71a3f2019-03-18 12:12:48 -0700547
548 return expandedSrcFiles, append(missingDeps, missingExcludeDeps...)
Colin Cross8a497952019-03-05 22:25:09 -0800549}
550
551type missingDependencyError struct {
552 missingDeps []string
553}
554
555func (e missingDependencyError) Error() string {
556 return "missing dependencies: " + strings.Join(e.missingDeps, ", ")
557}
558
Liz Kammera830f3a2020-11-10 10:50:34 -0800559// Expands one path string to Paths rooted from the module's local source
560// directory, excluding those listed in the expandedExcludes.
561// Expands globs, references to SourceFileProducer or OutputFileProducer modules using the ":name" and ":name{.tag}" syntax.
562func expandOneSrcPath(ctx ModuleWithDepsPathContext, sPath string, expandedExcludes []string) (Paths, error) {
Jooyung Han7607dd32020-07-05 10:23:14 +0900563 excludePaths := func(paths Paths) Paths {
564 if len(expandedExcludes) == 0 {
565 return paths
566 }
567 remainder := make(Paths, 0, len(paths))
568 for _, p := range paths {
569 if !InList(p.String(), expandedExcludes) {
570 remainder = append(remainder, p)
571 }
572 }
573 return remainder
574 }
Liz Kammera830f3a2020-11-10 10:50:34 -0800575 if m, t := SrcIsModuleWithTag(sPath); m != "" {
576 modulePaths, err := getPathsFromModuleDep(ctx, sPath, m, t)
577 if err != nil {
578 return nil, err
Colin Cross8a497952019-03-05 22:25:09 -0800579 } else {
Liz Kammera830f3a2020-11-10 10:50:34 -0800580 return excludePaths(modulePaths), nil
Colin Cross8a497952019-03-05 22:25:09 -0800581 }
Liz Kammera830f3a2020-11-10 10:50:34 -0800582 } else if pathtools.IsGlob(sPath) {
583 paths := GlobFiles(ctx, pathForModuleSrc(ctx, sPath).String(), expandedExcludes)
Colin Cross8a497952019-03-05 22:25:09 -0800584 return PathsWithModuleSrcSubDir(ctx, paths, ""), nil
585 } else {
Liz Kammera830f3a2020-11-10 10:50:34 -0800586 p := pathForModuleSrc(ctx, sPath)
Colin Cross988414c2020-01-11 01:11:46 +0000587 if exists, _, err := ctx.Config().fs.Exists(p.String()); err != nil {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +0100588 ReportPathErrorf(ctx, "%s: %s", p, err.Error())
Pedro Loureiro5d190cc2021-02-15 15:41:33 +0000589 } else if !exists && !ctx.Config().TestAllowNonExistentPaths {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +0100590 ReportPathErrorf(ctx, "module source path %q does not exist", p)
Colin Cross8a497952019-03-05 22:25:09 -0800591 }
592
Jooyung Han7607dd32020-07-05 10:23:14 +0900593 if InList(p.String(), expandedExcludes) {
Colin Cross8a497952019-03-05 22:25:09 -0800594 return nil, nil
595 }
596 return Paths{p}, nil
597 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700598}
599
600// pathsForModuleSrcFromFullPath returns Paths rooted from the module's local
601// source directory, but strip the local source directory from the beginning of
Dan Willemsen540a78c2018-02-26 21:50:08 -0800602// each string. If incDirs is false, strip paths with a trailing '/' from the list.
Colin Crossfe4bc362018-09-12 10:02:13 -0700603// It intended for use in globs that only list files that exist, so it allows '$' in
604// filenames.
Liz Kammera830f3a2020-11-10 10:50:34 -0800605func pathsForModuleSrcFromFullPath(ctx EarlyModulePathContext, paths []string, incDirs bool) Paths {
Colin Cross6510f912017-11-29 00:27:14 -0800606 prefix := filepath.Join(ctx.Config().srcDir, ctx.ModuleDir()) + "/"
Colin Cross0f37af02017-09-27 17:42:05 -0700607 if prefix == "./" {
608 prefix = ""
609 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700610 ret := make(Paths, 0, len(paths))
611 for _, p := range paths {
Dan Willemsen540a78c2018-02-26 21:50:08 -0800612 if !incDirs && strings.HasSuffix(p, "/") {
613 continue
614 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700615 path := filepath.Clean(p)
616 if !strings.HasPrefix(path, prefix) {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +0100617 ReportPathErrorf(ctx, "Path %q is not in module source directory %q", p, prefix)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700618 continue
619 }
Colin Crosse3924e12018-08-15 20:18:53 -0700620
Colin Crossfe4bc362018-09-12 10:02:13 -0700621 srcPath, err := safePathForSource(ctx, ctx.ModuleDir(), path[len(prefix):])
Colin Crosse3924e12018-08-15 20:18:53 -0700622 if err != nil {
623 reportPathError(ctx, err)
624 continue
625 }
626
Colin Cross07e51612019-03-05 12:46:40 -0800627 srcPath.basePath.rel = srcPath.path
Colin Crosse3924e12018-08-15 20:18:53 -0700628
Colin Cross07e51612019-03-05 12:46:40 -0800629 ret = append(ret, srcPath)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700630 }
631 return ret
632}
633
Liz Kammera830f3a2020-11-10 10:50:34 -0800634// PathsWithOptionalDefaultForModuleSrc returns Paths rooted from the module's local source
635// directory. If input is nil, use the default if it exists. If input is empty, returns nil.
636func PathsWithOptionalDefaultForModuleSrc(ctx ModuleMissingDepsPathContext, input []string, def string) Paths {
Colin Cross0ddae7f2019-02-07 15:30:01 -0800637 if input != nil {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700638 return PathsForModuleSrc(ctx, input)
639 }
640 // Use Glob so that if the default doesn't exist, a dependency is added so that when it
641 // is created, we're run again.
Colin Cross6510f912017-11-29 00:27:14 -0800642 path := filepath.Join(ctx.Config().srcDir, ctx.ModuleDir(), def)
Liz Kammera830f3a2020-11-10 10:50:34 -0800643 return Glob(ctx, path, nil)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700644}
645
646// Strings returns the Paths in string form
647func (p Paths) Strings() []string {
648 if p == nil {
649 return nil
650 }
651 ret := make([]string, len(p))
652 for i, path := range p {
653 ret[i] = path.String()
654 }
655 return ret
656}
657
Colin Crossc0efd1d2020-07-03 11:56:24 -0700658func CopyOfPaths(paths Paths) Paths {
659 return append(Paths(nil), paths...)
660}
661
Colin Crossb6715442017-10-24 11:13:31 -0700662// FirstUniquePaths returns all unique elements of a Paths, keeping the first copy of each. It
663// modifies the Paths slice contents in place, and returns a subslice of the original slice.
Dan Willemsenfe92c962017-08-29 12:28:37 -0700664func FirstUniquePaths(list Paths) Paths {
Colin Cross27027c72020-02-28 15:34:17 -0800665 // 128 was chosen based on BenchmarkFirstUniquePaths results.
666 if len(list) > 128 {
667 return firstUniquePathsMap(list)
668 }
669 return firstUniquePathsList(list)
670}
671
Colin Crossc0efd1d2020-07-03 11:56:24 -0700672// SortedUniquePaths returns all unique elements of a Paths in sorted order. It modifies the
673// Paths slice contents in place, and returns a subslice of the original slice.
Jiyong Park33c77362020-05-29 22:00:16 +0900674func SortedUniquePaths(list Paths) Paths {
675 unique := FirstUniquePaths(list)
676 sort.Slice(unique, func(i, j int) bool {
677 return unique[i].String() < unique[j].String()
678 })
679 return unique
680}
681
Colin Cross27027c72020-02-28 15:34:17 -0800682func firstUniquePathsList(list Paths) Paths {
Dan Willemsenfe92c962017-08-29 12:28:37 -0700683 k := 0
684outer:
685 for i := 0; i < len(list); i++ {
686 for j := 0; j < k; j++ {
687 if list[i] == list[j] {
688 continue outer
689 }
690 }
691 list[k] = list[i]
692 k++
693 }
694 return list[:k]
695}
696
Colin Cross27027c72020-02-28 15:34:17 -0800697func firstUniquePathsMap(list Paths) Paths {
698 k := 0
699 seen := make(map[Path]bool, len(list))
700 for i := 0; i < len(list); i++ {
701 if seen[list[i]] {
702 continue
703 }
704 seen[list[i]] = true
705 list[k] = list[i]
706 k++
707 }
708 return list[:k]
709}
710
Colin Cross5d583952020-11-24 16:21:24 -0800711// FirstUniqueInstallPaths returns all unique elements of an InstallPaths, keeping the first copy of each. It
712// modifies the InstallPaths slice contents in place, and returns a subslice of the original slice.
713func FirstUniqueInstallPaths(list InstallPaths) InstallPaths {
714 // 128 was chosen based on BenchmarkFirstUniquePaths results.
715 if len(list) > 128 {
716 return firstUniqueInstallPathsMap(list)
717 }
718 return firstUniqueInstallPathsList(list)
719}
720
721func firstUniqueInstallPathsList(list InstallPaths) InstallPaths {
722 k := 0
723outer:
724 for i := 0; i < len(list); i++ {
725 for j := 0; j < k; j++ {
726 if list[i] == list[j] {
727 continue outer
728 }
729 }
730 list[k] = list[i]
731 k++
732 }
733 return list[:k]
734}
735
736func firstUniqueInstallPathsMap(list InstallPaths) InstallPaths {
737 k := 0
738 seen := make(map[InstallPath]bool, len(list))
739 for i := 0; i < len(list); i++ {
740 if seen[list[i]] {
741 continue
742 }
743 seen[list[i]] = true
744 list[k] = list[i]
745 k++
746 }
747 return list[:k]
748}
749
Colin Crossb6715442017-10-24 11:13:31 -0700750// LastUniquePaths returns all unique elements of a Paths, keeping the last copy of each. It
751// modifies the Paths slice contents in place, and returns a subslice of the original slice.
752func LastUniquePaths(list Paths) Paths {
753 totalSkip := 0
754 for i := len(list) - 1; i >= totalSkip; i-- {
755 skip := 0
756 for j := i - 1; j >= totalSkip; j-- {
757 if list[i] == list[j] {
758 skip++
759 } else {
760 list[j+skip] = list[j]
761 }
762 }
763 totalSkip += skip
764 }
765 return list[totalSkip:]
766}
767
Colin Crossa140bb02018-04-17 10:52:26 -0700768// ReversePaths returns a copy of a Paths in reverse order.
769func ReversePaths(list Paths) Paths {
770 if list == nil {
771 return nil
772 }
773 ret := make(Paths, len(list))
774 for i := range list {
775 ret[i] = list[len(list)-1-i]
776 }
777 return ret
778}
779
Jeff Gaston294356f2017-09-27 17:05:30 -0700780func indexPathList(s Path, list []Path) int {
781 for i, l := range list {
782 if l == s {
783 return i
784 }
785 }
786
787 return -1
788}
789
790func inPathList(p Path, list []Path) bool {
791 return indexPathList(p, list) != -1
792}
793
794func FilterPathList(list []Path, filter []Path) (remainder []Path, filtered []Path) {
Paul Duffin57b9e1d2019-12-13 00:03:35 +0000795 return FilterPathListPredicate(list, func(p Path) bool { return inPathList(p, filter) })
796}
797
798func FilterPathListPredicate(list []Path, predicate func(Path) bool) (remainder []Path, filtered []Path) {
Jeff Gaston294356f2017-09-27 17:05:30 -0700799 for _, l := range list {
Paul Duffin57b9e1d2019-12-13 00:03:35 +0000800 if predicate(l) {
Jeff Gaston294356f2017-09-27 17:05:30 -0700801 filtered = append(filtered, l)
802 } else {
803 remainder = append(remainder, l)
804 }
805 }
806
807 return
808}
809
Colin Cross93e85952017-08-15 13:34:18 -0700810// HasExt returns true of any of the paths have extension ext, otherwise false
811func (p Paths) HasExt(ext string) bool {
812 for _, path := range p {
813 if path.Ext() == ext {
814 return true
815 }
816 }
817
818 return false
819}
820
821// FilterByExt returns the subset of the paths that have extension ext
822func (p Paths) FilterByExt(ext string) Paths {
823 ret := make(Paths, 0, len(p))
824 for _, path := range p {
825 if path.Ext() == ext {
826 ret = append(ret, path)
827 }
828 }
829 return ret
830}
831
832// FilterOutByExt returns the subset of the paths that do not have extension ext
833func (p Paths) FilterOutByExt(ext string) Paths {
834 ret := make(Paths, 0, len(p))
835 for _, path := range p {
836 if path.Ext() != ext {
837 ret = append(ret, path)
838 }
839 }
840 return ret
841}
842
Colin Cross5e6cfbe2017-11-03 15:20:35 -0700843// DirectorySortedPaths is a slice of paths that are sorted such that all files in a directory
844// (including subdirectories) are in a contiguous subslice of the list, and can be found in
845// O(log(N)) time using a binary search on the directory prefix.
846type DirectorySortedPaths Paths
847
848func PathsToDirectorySortedPaths(paths Paths) DirectorySortedPaths {
849 ret := append(DirectorySortedPaths(nil), paths...)
850 sort.Slice(ret, func(i, j int) bool {
851 return ret[i].String() < ret[j].String()
852 })
853 return ret
854}
855
856// PathsInDirectory returns a subslice of the DirectorySortedPaths as a Paths that contains all entries
857// that are in the specified directory and its subdirectories.
858func (p DirectorySortedPaths) PathsInDirectory(dir string) Paths {
859 prefix := filepath.Clean(dir) + "/"
860 start := sort.Search(len(p), func(i int) bool {
861 return prefix < p[i].String()
862 })
863
864 ret := p[start:]
865
866 end := sort.Search(len(ret), func(i int) bool {
867 return !strings.HasPrefix(ret[i].String(), prefix)
868 })
869
870 ret = ret[:end]
871
872 return Paths(ret)
873}
874
Alex Humesky29e3bbe2020-11-20 21:30:13 -0500875// WritablePaths is a slice of WritablePath, used for multiple outputs.
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700876type WritablePaths []WritablePath
877
878// Strings returns the string forms of the writable paths.
879func (p WritablePaths) Strings() []string {
880 if p == nil {
881 return nil
882 }
883 ret := make([]string, len(p))
884 for i, path := range p {
885 ret[i] = path.String()
886 }
887 return ret
888}
889
Colin Cross3bc7ffa2017-11-22 16:19:37 -0800890// Paths returns the WritablePaths as a Paths
891func (p WritablePaths) Paths() Paths {
892 if p == nil {
893 return nil
894 }
895 ret := make(Paths, len(p))
896 for i, path := range p {
897 ret[i] = path
898 }
899 return ret
900}
901
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700902type basePath struct {
903 path string
904 config Config
Colin Crossfaeb7aa2017-02-01 14:12:44 -0800905 rel string
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700906}
907
908func (p basePath) Ext() string {
909 return filepath.Ext(p.path)
910}
911
Colin Cross4f6fc9c2016-10-26 10:05:25 -0700912func (p basePath) Base() string {
913 return filepath.Base(p.path)
914}
915
Colin Crossfaeb7aa2017-02-01 14:12:44 -0800916func (p basePath) Rel() string {
917 if p.rel != "" {
918 return p.rel
919 }
920 return p.path
921}
922
Colin Cross0875c522017-11-28 17:34:01 -0800923func (p basePath) String() string {
924 return p.path
925}
926
Colin Cross0db55682017-12-05 15:36:55 -0800927func (p basePath) withRel(rel string) basePath {
928 p.path = filepath.Join(p.path, rel)
929 p.rel = rel
930 return p
931}
932
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700933// SourcePath is a Path representing a file path rooted from SrcDir
934type SourcePath struct {
935 basePath
936}
937
938var _ Path = SourcePath{}
939
Colin Cross0db55682017-12-05 15:36:55 -0800940func (p SourcePath) withRel(rel string) SourcePath {
941 p.basePath = p.basePath.withRel(rel)
942 return p
943}
944
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700945// safePathForSource is for paths that we expect are safe -- only for use by go
946// code that is embedding ninja variables in paths
Colin Crossfe4bc362018-09-12 10:02:13 -0700947func safePathForSource(ctx PathContext, pathComponents ...string) (SourcePath, error) {
948 p, err := validateSafePath(pathComponents...)
Colin Crossaabf6792017-11-29 00:27:14 -0800949 ret := SourcePath{basePath{p, ctx.Config(), ""}}
Colin Crossfe4bc362018-09-12 10:02:13 -0700950 if err != nil {
951 return ret, err
952 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700953
Colin Cross7b3dcc32019-01-24 13:14:39 -0800954 // absolute path already checked by validateSafePath
955 if strings.HasPrefix(ret.String(), ctx.Config().buildDir) {
Mikhail Naganovab1f5182019-02-08 13:17:55 -0800956 return ret, fmt.Errorf("source path %q is in output", ret.String())
Colin Cross6e18ca42015-07-14 18:55:36 -0700957 }
958
Colin Crossfe4bc362018-09-12 10:02:13 -0700959 return ret, err
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700960}
961
Colin Cross192e97a2018-02-22 14:21:02 -0800962// pathForSource creates a SourcePath from pathComponents, but does not check that it exists.
963func pathForSource(ctx PathContext, pathComponents ...string) (SourcePath, error) {
Colin Crossc48c1432018-02-23 07:09:01 +0000964 p, err := validatePath(pathComponents...)
965 ret := SourcePath{basePath{p, ctx.Config(), ""}}
Colin Cross94a32102018-02-22 14:21:02 -0800966 if err != nil {
Colin Cross192e97a2018-02-22 14:21:02 -0800967 return ret, err
Colin Cross94a32102018-02-22 14:21:02 -0800968 }
969
Colin Cross7b3dcc32019-01-24 13:14:39 -0800970 // absolute path already checked by validatePath
971 if strings.HasPrefix(ret.String(), ctx.Config().buildDir) {
Mikhail Naganovab1f5182019-02-08 13:17:55 -0800972 return ret, fmt.Errorf("source path %q is in output", ret.String())
Colin Crossc48c1432018-02-23 07:09:01 +0000973 }
974
Colin Cross192e97a2018-02-22 14:21:02 -0800975 return ret, nil
976}
977
978// existsWithDependencies returns true if the path exists, and adds appropriate dependencies to rerun if the
979// path does not exist.
980func existsWithDependencies(ctx PathContext, path SourcePath) (exists bool, err error) {
981 var files []string
982
983 if gctx, ok := ctx.(PathGlobContext); ok {
984 // Use glob to produce proper dependencies, even though we only want
985 // a single file.
986 files, err = gctx.GlobWithDeps(path.String(), nil)
987 } else {
988 var deps []string
989 // We cannot add build statements in this context, so we fall back to
990 // AddNinjaFileDeps
Colin Cross988414c2020-01-11 01:11:46 +0000991 files, deps, err = ctx.Config().fs.Glob(path.String(), nil, pathtools.FollowSymlinks)
Colin Cross192e97a2018-02-22 14:21:02 -0800992 ctx.AddNinjaFileDeps(deps...)
993 }
994
995 if err != nil {
996 return false, fmt.Errorf("glob: %s", err.Error())
997 }
998
999 return len(files) > 0, nil
1000}
1001
1002// PathForSource joins the provided path components and validates that the result
1003// neither escapes the source dir nor is in the out dir.
1004// On error, it will return a usable, but invalid SourcePath, and report a ModuleError.
1005func PathForSource(ctx PathContext, pathComponents ...string) SourcePath {
1006 path, err := pathForSource(ctx, pathComponents...)
1007 if err != nil {
1008 reportPathError(ctx, err)
1009 }
1010
Colin Crosse3924e12018-08-15 20:18:53 -07001011 if pathtools.IsGlob(path.String()) {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001012 ReportPathErrorf(ctx, "path may not contain a glob: %s", path.String())
Colin Crosse3924e12018-08-15 20:18:53 -07001013 }
1014
Liz Kammera830f3a2020-11-10 10:50:34 -08001015 if modCtx, ok := ctx.(ModuleMissingDepsPathContext); ok && ctx.Config().AllowMissingDependencies() {
Colin Cross192e97a2018-02-22 14:21:02 -08001016 exists, err := existsWithDependencies(ctx, path)
1017 if err != nil {
1018 reportPathError(ctx, err)
1019 }
1020 if !exists {
1021 modCtx.AddMissingDependencies([]string{path.String()})
1022 }
Colin Cross988414c2020-01-11 01:11:46 +00001023 } else if exists, _, err := ctx.Config().fs.Exists(path.String()); err != nil {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001024 ReportPathErrorf(ctx, "%s: %s", path, err.Error())
Pedro Loureiro5d190cc2021-02-15 15:41:33 +00001025 } else if !exists && !ctx.Config().TestAllowNonExistentPaths {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001026 ReportPathErrorf(ctx, "source path %q does not exist", path)
Colin Cross192e97a2018-02-22 14:21:02 -08001027 }
1028 return path
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001029}
1030
Liz Kammer7aa52882021-02-11 09:16:14 -05001031// ExistentPathForSource returns an OptionalPath with the SourcePath, rooted from SrcDir, *not*
1032// rooted from the module's local source directory, if the path exists, or an empty OptionalPath if
1033// it doesn't exist. Dependencies are added so that the ninja file will be regenerated if the state
1034// of the path changes.
Colin Cross32f38982018-02-22 11:47:25 -08001035func ExistentPathForSource(ctx PathContext, pathComponents ...string) OptionalPath {
Colin Cross192e97a2018-02-22 14:21:02 -08001036 path, err := pathForSource(ctx, pathComponents...)
Colin Cross1ccfcc32018-02-22 13:54:26 -08001037 if err != nil {
1038 reportPathError(ctx, err)
1039 return OptionalPath{}
1040 }
Colin Crossc48c1432018-02-23 07:09:01 +00001041
Colin Crosse3924e12018-08-15 20:18:53 -07001042 if pathtools.IsGlob(path.String()) {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001043 ReportPathErrorf(ctx, "path may not contain a glob: %s", path.String())
Colin Crosse3924e12018-08-15 20:18:53 -07001044 return OptionalPath{}
1045 }
1046
Colin Cross192e97a2018-02-22 14:21:02 -08001047 exists, err := existsWithDependencies(ctx, path)
Colin Crossc48c1432018-02-23 07:09:01 +00001048 if err != nil {
1049 reportPathError(ctx, err)
1050 return OptionalPath{}
1051 }
Colin Cross192e97a2018-02-22 14:21:02 -08001052 if !exists {
Colin Crossc48c1432018-02-23 07:09:01 +00001053 return OptionalPath{}
1054 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001055 return OptionalPathForPath(path)
1056}
1057
1058func (p SourcePath) String() string {
1059 return filepath.Join(p.config.srcDir, p.path)
1060}
1061
1062// Join creates a new SourcePath with paths... joined with the current path. The
1063// provided paths... may not use '..' to escape from the current path.
1064func (p SourcePath) Join(ctx PathContext, paths ...string) SourcePath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001065 path, err := validatePath(paths...)
1066 if err != nil {
1067 reportPathError(ctx, err)
1068 }
Colin Cross0db55682017-12-05 15:36:55 -08001069 return p.withRel(path)
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001070}
1071
Colin Cross2fafa3e2019-03-05 12:39:51 -08001072// join is like Join but does less path validation.
1073func (p SourcePath) join(ctx PathContext, paths ...string) SourcePath {
1074 path, err := validateSafePath(paths...)
1075 if err != nil {
1076 reportPathError(ctx, err)
1077 }
1078 return p.withRel(path)
1079}
1080
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001081// OverlayPath returns the overlay for `path' if it exists. This assumes that the
1082// SourcePath is the path to a resource overlay directory.
Liz Kammera830f3a2020-11-10 10:50:34 -08001083func (p SourcePath) OverlayPath(ctx ModuleMissingDepsPathContext, path Path) OptionalPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001084 var relDir string
Colin Cross07e51612019-03-05 12:46:40 -08001085 if srcPath, ok := path.(SourcePath); ok {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001086 relDir = srcPath.path
1087 } else {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001088 ReportPathErrorf(ctx, "Cannot find relative path for %s(%s)", reflect.TypeOf(path).Name(), path)
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001089 return OptionalPath{}
1090 }
1091 dir := filepath.Join(p.config.srcDir, p.path, relDir)
1092 // Use Glob so that we are run again if the directory is added.
Colin Cross7f19f372016-11-01 11:10:25 -07001093 if pathtools.IsGlob(dir) {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001094 ReportPathErrorf(ctx, "Path may not contain a glob: %s", dir)
Dan Willemsen7b310ee2015-12-18 15:11:17 -08001095 }
Colin Cross461b4452018-02-23 09:22:42 -08001096 paths, err := ctx.GlobWithDeps(dir, nil)
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001097 if err != nil {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001098 ReportPathErrorf(ctx, "glob: %s", err.Error())
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001099 return OptionalPath{}
1100 }
1101 if len(paths) == 0 {
1102 return OptionalPath{}
1103 }
Colin Cross43f08db2018-11-12 10:13:39 -08001104 relPath := Rel(ctx, p.config.srcDir, paths[0])
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001105 return OptionalPathForPath(PathForSource(ctx, relPath))
1106}
1107
Colin Cross70dda7e2019-10-01 22:05:35 -07001108// OutputPath is a Path representing an intermediates file path rooted from the build directory
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001109type OutputPath struct {
1110 basePath
Colin Crossd63c9a72020-01-29 16:52:50 -08001111 fullPath string
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001112}
1113
Colin Cross702e0f82017-10-18 17:27:54 -07001114func (p OutputPath) withRel(rel string) OutputPath {
Colin Cross0db55682017-12-05 15:36:55 -08001115 p.basePath = p.basePath.withRel(rel)
Colin Crossd63c9a72020-01-29 16:52:50 -08001116 p.fullPath = filepath.Join(p.fullPath, rel)
Colin Cross702e0f82017-10-18 17:27:54 -07001117 return p
1118}
1119
Colin Cross3063b782018-08-15 11:19:12 -07001120func (p OutputPath) WithoutRel() OutputPath {
1121 p.basePath.rel = filepath.Base(p.basePath.path)
1122 return p
1123}
1124
Paul Duffin9b478b02019-12-10 13:41:51 +00001125func (p OutputPath) buildDir() string {
1126 return p.config.buildDir
1127}
1128
Paul Duffin0267d492021-02-02 10:05:52 +00001129func (p OutputPath) objPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleObjPath {
1130 return PathForModuleObj(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
1131}
1132
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001133var _ Path = OutputPath{}
Paul Duffin9b478b02019-12-10 13:41:51 +00001134var _ WritablePath = OutputPath{}
Paul Duffin0267d492021-02-02 10:05:52 +00001135var _ objPathProvider = OutputPath{}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001136
Chris Parsons8f232a22020-06-23 17:37:05 -04001137// toolDepPath is a Path representing a dependency of the build tool.
1138type toolDepPath struct {
1139 basePath
1140}
1141
1142var _ Path = toolDepPath{}
1143
1144// pathForBuildToolDep returns a toolDepPath representing the given path string.
1145// There is no validation for the path, as it is "trusted": It may fail
1146// normal validation checks. For example, it may be an absolute path.
1147// Only use this function to construct paths for dependencies of the build
1148// tool invocation.
1149func pathForBuildToolDep(ctx PathContext, path string) toolDepPath {
1150 return toolDepPath{basePath{path, ctx.Config(), ""}}
1151}
1152
Jeff Gaston734e3802017-04-10 15:47:24 -07001153// PathForOutput joins the provided paths and returns an OutputPath that is
1154// validated to not escape the build dir.
1155// On error, it will return a usable, but invalid OutputPath, and report a ModuleError.
1156func PathForOutput(ctx PathContext, pathComponents ...string) OutputPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001157 path, err := validatePath(pathComponents...)
1158 if err != nil {
1159 reportPathError(ctx, err)
1160 }
Colin Crossd63c9a72020-01-29 16:52:50 -08001161 fullPath := filepath.Join(ctx.Config().buildDir, path)
1162 path = fullPath[len(fullPath)-len(path):]
1163 return OutputPath{basePath{path, ctx.Config(), ""}, fullPath}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001164}
1165
Colin Cross40e33732019-02-15 11:08:35 -08001166// PathsForOutput returns Paths rooted from buildDir
1167func PathsForOutput(ctx PathContext, paths []string) WritablePaths {
1168 ret := make(WritablePaths, len(paths))
1169 for i, path := range paths {
1170 ret[i] = PathForOutput(ctx, path)
1171 }
1172 return ret
1173}
1174
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001175func (p OutputPath) writablePath() {}
1176
1177func (p OutputPath) String() string {
Colin Crossd63c9a72020-01-29 16:52:50 -08001178 return p.fullPath
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001179}
1180
1181// Join creates a new OutputPath with paths... joined with the current path. The
1182// provided paths... may not use '..' to escape from the current path.
1183func (p OutputPath) Join(ctx PathContext, paths ...string) OutputPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001184 path, err := validatePath(paths...)
1185 if err != nil {
1186 reportPathError(ctx, err)
1187 }
Colin Cross0db55682017-12-05 15:36:55 -08001188 return p.withRel(path)
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001189}
1190
Colin Cross8854a5a2019-02-11 14:14:16 -08001191// ReplaceExtension creates a new OutputPath with the extension replaced with ext.
1192func (p OutputPath) ReplaceExtension(ctx PathContext, ext string) OutputPath {
1193 if strings.Contains(ext, "/") {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001194 ReportPathErrorf(ctx, "extension %q cannot contain /", ext)
Colin Cross8854a5a2019-02-11 14:14:16 -08001195 }
1196 ret := PathForOutput(ctx, pathtools.ReplaceExtension(p.path, ext))
Colin Cross2cdd5df2019-02-25 10:25:24 -08001197 ret.rel = pathtools.ReplaceExtension(p.rel, ext)
Colin Cross8854a5a2019-02-11 14:14:16 -08001198 return ret
1199}
1200
Colin Cross40e33732019-02-15 11:08:35 -08001201// InSameDir creates a new OutputPath from the directory of the current OutputPath joined with the elements in paths.
1202func (p OutputPath) InSameDir(ctx PathContext, paths ...string) OutputPath {
1203 path, err := validatePath(paths...)
1204 if err != nil {
1205 reportPathError(ctx, err)
1206 }
1207
1208 ret := PathForOutput(ctx, filepath.Dir(p.path), path)
Colin Cross2cdd5df2019-02-25 10:25:24 -08001209 ret.rel = filepath.Join(filepath.Dir(p.rel), path)
Colin Cross40e33732019-02-15 11:08:35 -08001210 return ret
1211}
1212
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001213// PathForIntermediates returns an OutputPath representing the top-level
1214// intermediates directory.
1215func PathForIntermediates(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 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001220 return PathForOutput(ctx, ".intermediates", path)
1221}
1222
Colin Cross07e51612019-03-05 12:46:40 -08001223var _ genPathProvider = SourcePath{}
1224var _ objPathProvider = SourcePath{}
1225var _ resPathProvider = SourcePath{}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001226
Colin Cross07e51612019-03-05 12:46:40 -08001227// PathForModuleSrc returns a Path representing the paths... under the
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001228// module's local source directory.
Liz Kammera830f3a2020-11-10 10:50:34 -08001229func PathForModuleSrc(ctx ModuleMissingDepsPathContext, pathComponents ...string) Path {
Colin Cross8a497952019-03-05 22:25:09 -08001230 p, err := validatePath(pathComponents...)
1231 if err != nil {
1232 reportPathError(ctx, err)
Colin Cross192e97a2018-02-22 14:21:02 -08001233 }
Colin Cross8a497952019-03-05 22:25:09 -08001234 paths, err := expandOneSrcPath(ctx, p, nil)
1235 if err != nil {
1236 if depErr, ok := err.(missingDependencyError); ok {
1237 if ctx.Config().AllowMissingDependencies() {
1238 ctx.AddMissingDependencies(depErr.missingDeps)
1239 } else {
1240 ctx.ModuleErrorf(`%s, is the property annotated with android:"path"?`, depErr.Error())
1241 }
1242 } else {
1243 reportPathError(ctx, err)
1244 }
1245 return nil
1246 } else if len(paths) == 0 {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001247 ReportPathErrorf(ctx, "%q produced no files, expected exactly one", p)
Colin Cross8a497952019-03-05 22:25:09 -08001248 return nil
1249 } else if len(paths) > 1 {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001250 ReportPathErrorf(ctx, "%q produced %d files, expected exactly one", p, len(paths))
Colin Cross8a497952019-03-05 22:25:09 -08001251 }
1252 return paths[0]
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001253}
1254
Liz Kammera830f3a2020-11-10 10:50:34 -08001255func pathForModuleSrc(ctx EarlyModulePathContext, paths ...string) SourcePath {
Colin Cross07e51612019-03-05 12:46:40 -08001256 p, err := validatePath(paths...)
1257 if err != nil {
1258 reportPathError(ctx, err)
1259 }
1260
1261 path, err := pathForSource(ctx, ctx.ModuleDir(), p)
1262 if err != nil {
1263 reportPathError(ctx, err)
1264 }
1265
1266 path.basePath.rel = p
1267
1268 return path
1269}
1270
Colin Cross2fafa3e2019-03-05 12:39:51 -08001271// PathsWithModuleSrcSubDir takes a list of Paths and returns a new list of Paths where Rel() on each path
1272// will return the path relative to subDir in the module's source directory. If any input paths are not located
1273// inside subDir then a path error will be reported.
Liz Kammera830f3a2020-11-10 10:50:34 -08001274func PathsWithModuleSrcSubDir(ctx EarlyModulePathContext, paths Paths, subDir string) Paths {
Colin Cross2fafa3e2019-03-05 12:39:51 -08001275 paths = append(Paths(nil), paths...)
Colin Cross07e51612019-03-05 12:46:40 -08001276 subDirFullPath := pathForModuleSrc(ctx, subDir)
Colin Cross2fafa3e2019-03-05 12:39:51 -08001277 for i, path := range paths {
1278 rel := Rel(ctx, subDirFullPath.String(), path.String())
1279 paths[i] = subDirFullPath.join(ctx, rel)
1280 }
1281 return paths
1282}
1283
1284// PathWithModuleSrcSubDir takes a Path and returns a Path where Rel() will return the path relative to subDir in the
1285// 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 -08001286func PathWithModuleSrcSubDir(ctx EarlyModulePathContext, path Path, subDir string) Path {
Colin Cross07e51612019-03-05 12:46:40 -08001287 subDirFullPath := pathForModuleSrc(ctx, subDir)
Colin Cross2fafa3e2019-03-05 12:39:51 -08001288 rel := Rel(ctx, subDirFullPath.String(), path.String())
1289 return subDirFullPath.Join(ctx, rel)
1290}
1291
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001292// OptionalPathForModuleSrc returns an OptionalPath. The OptionalPath contains a
1293// valid path if p is non-nil.
Liz Kammera830f3a2020-11-10 10:50:34 -08001294func OptionalPathForModuleSrc(ctx ModuleMissingDepsPathContext, p *string) OptionalPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001295 if p == nil {
1296 return OptionalPath{}
1297 }
1298 return OptionalPathForPath(PathForModuleSrc(ctx, *p))
1299}
1300
Liz Kammera830f3a2020-11-10 10:50:34 -08001301func (p SourcePath) genPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleGenPath {
Colin Cross7fc17db2017-02-01 14:07:55 -08001302 return PathForModuleGen(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001303}
1304
Liz Kammera830f3a2020-11-10 10:50:34 -08001305func (p SourcePath) objPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleObjPath {
Colin Cross7fc17db2017-02-01 14:07:55 -08001306 return PathForModuleObj(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001307}
1308
Liz Kammera830f3a2020-11-10 10:50:34 -08001309func (p SourcePath) resPathWithName(ctx ModuleOutPathContext, name string) ModuleResPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001310 // TODO: Use full directory if the new ctx is not the current ctx?
1311 return PathForModuleRes(ctx, p.path, name)
1312}
1313
1314// ModuleOutPath is a Path representing a module's output directory.
1315type ModuleOutPath struct {
1316 OutputPath
1317}
1318
1319var _ Path = ModuleOutPath{}
1320
Liz Kammera830f3a2020-11-10 10:50:34 -08001321func (p ModuleOutPath) objPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleObjPath {
Pete Bentleyfcf55bf2019-08-16 20:14:32 +01001322 return PathForModuleObj(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
1323}
1324
Liz Kammera830f3a2020-11-10 10:50:34 -08001325// ModuleOutPathContext Subset of ModuleContext functions necessary for output path methods.
1326type ModuleOutPathContext interface {
1327 PathContext
1328
1329 ModuleName() string
1330 ModuleDir() string
1331 ModuleSubDir() string
1332}
1333
1334func pathForModuleOut(ctx ModuleOutPathContext) OutputPath {
Colin Cross702e0f82017-10-18 17:27:54 -07001335 return PathForOutput(ctx, ".intermediates", ctx.ModuleDir(), ctx.ModuleName(), ctx.ModuleSubDir())
1336}
1337
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001338type BazelOutPath struct {
1339 OutputPath
1340}
1341
1342var _ Path = BazelOutPath{}
1343var _ objPathProvider = BazelOutPath{}
1344
Liz Kammera830f3a2020-11-10 10:50:34 -08001345func (p BazelOutPath) objPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleObjPath {
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001346 return PathForModuleObj(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
1347}
1348
Logan Chien7eefdc42018-07-11 18:10:41 +08001349// PathForVndkRefAbiDump returns an OptionalPath representing the path of the
1350// reference abi dump for the given module. This is not guaranteed to be valid.
Liz Kammera830f3a2020-11-10 10:50:34 -08001351func PathForVndkRefAbiDump(ctx ModuleInstallPathContext, version, fileName string,
Hsin-Yi Chen53489642019-07-31 17:10:45 +08001352 isNdk, isLlndkOrVndk, isGzip bool) OptionalPath {
Logan Chien7eefdc42018-07-11 18:10:41 +08001353
Jayant Chowdharyac066c62018-02-20 10:53:31 -08001354 arches := ctx.DeviceConfig().Arches()
Logan Chien7eefdc42018-07-11 18:10:41 +08001355 if len(arches) == 0 {
1356 panic("device build with no primary arch")
1357 }
Jayant Chowdharyac066c62018-02-20 10:53:31 -08001358 currentArch := ctx.Arch()
1359 archNameAndVariant := currentArch.ArchType.String()
1360 if currentArch.ArchVariant != "" {
1361 archNameAndVariant += "_" + currentArch.ArchVariant
1362 }
Logan Chien5237bed2018-07-11 17:15:57 +08001363
1364 var dirName string
Hsin-Yi Chen53489642019-07-31 17:10:45 +08001365 if isNdk {
Logan Chien5237bed2018-07-11 17:15:57 +08001366 dirName = "ndk"
Hsin-Yi Chen53489642019-07-31 17:10:45 +08001367 } else if isLlndkOrVndk {
Logan Chien5237bed2018-07-11 17:15:57 +08001368 dirName = "vndk"
Logan Chien41eabe62019-04-10 13:33:58 +08001369 } else {
1370 dirName = "platform" // opt-in libs
Jayant Chowdhary3e231fd2017-02-08 13:45:53 -08001371 }
Logan Chien5237bed2018-07-11 17:15:57 +08001372
Jayant Chowdhary34ce67d2018-03-08 11:00:50 -08001373 binderBitness := ctx.DeviceConfig().BinderBitness()
Logan Chien7eefdc42018-07-11 18:10:41 +08001374
1375 var ext string
1376 if isGzip {
1377 ext = ".lsdump.gz"
1378 } else {
1379 ext = ".lsdump"
1380 }
1381
1382 return ExistentPathForSource(ctx, "prebuilts", "abi-dumps", dirName,
1383 version, binderBitness, archNameAndVariant, "source-based",
1384 fileName+ext)
Jayant Chowdhary3e231fd2017-02-08 13:45:53 -08001385}
1386
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001387// PathForBazelOut returns a Path representing the paths... under an output directory dedicated to
1388// bazel-owned outputs.
1389func PathForBazelOut(ctx PathContext, paths ...string) BazelOutPath {
1390 execRootPathComponents := append([]string{"execroot", "__main__"}, paths...)
1391 execRootPath := filepath.Join(execRootPathComponents...)
1392 validatedExecRootPath, err := validatePath(execRootPath)
1393 if err != nil {
1394 reportPathError(ctx, err)
1395 }
1396
1397 outputPath := OutputPath{basePath{"", ctx.Config(), ""},
1398 ctx.Config().BazelContext.OutputBase()}
1399
1400 return BazelOutPath{
1401 OutputPath: outputPath.withRel(validatedExecRootPath),
1402 }
1403}
1404
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001405// PathForModuleOut returns a Path representing the paths... under the module's
1406// output directory.
Liz Kammera830f3a2020-11-10 10:50:34 -08001407func PathForModuleOut(ctx ModuleOutPathContext, paths ...string) ModuleOutPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001408 p, err := validatePath(paths...)
1409 if err != nil {
1410 reportPathError(ctx, err)
1411 }
Colin Cross702e0f82017-10-18 17:27:54 -07001412 return ModuleOutPath{
Liz Kammera830f3a2020-11-10 10:50:34 -08001413 OutputPath: pathForModuleOut(ctx).withRel(p),
Colin Cross702e0f82017-10-18 17:27:54 -07001414 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001415}
1416
1417// ModuleGenPath is a Path representing the 'gen' directory in a module's output
1418// directory. Mainly used for generated sources.
1419type ModuleGenPath struct {
1420 ModuleOutPath
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001421}
1422
1423var _ Path = ModuleGenPath{}
1424var _ genPathProvider = ModuleGenPath{}
1425var _ objPathProvider = ModuleGenPath{}
1426
1427// PathForModuleGen returns a Path representing the paths... under the module's
1428// `gen' directory.
Liz Kammera830f3a2020-11-10 10:50:34 -08001429func PathForModuleGen(ctx ModuleOutPathContext, paths ...string) ModuleGenPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001430 p, err := validatePath(paths...)
1431 if err != nil {
1432 reportPathError(ctx, err)
1433 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001434 return ModuleGenPath{
Colin Cross702e0f82017-10-18 17:27:54 -07001435 ModuleOutPath: ModuleOutPath{
Liz Kammera830f3a2020-11-10 10:50:34 -08001436 OutputPath: pathForModuleOut(ctx).withRel("gen").withRel(p),
Colin Cross702e0f82017-10-18 17:27:54 -07001437 },
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001438 }
1439}
1440
Liz Kammera830f3a2020-11-10 10:50:34 -08001441func (p ModuleGenPath) genPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleGenPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001442 // TODO: make a different path for local vs remote generated files?
Dan Willemsen21ec4902016-11-02 20:43:13 -07001443 return PathForModuleGen(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001444}
1445
Liz Kammera830f3a2020-11-10 10:50:34 -08001446func (p ModuleGenPath) objPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleObjPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001447 return PathForModuleObj(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
1448}
1449
1450// ModuleObjPath is a Path representing the 'obj' directory in a module's output
1451// directory. Used for compiled objects.
1452type ModuleObjPath struct {
1453 ModuleOutPath
1454}
1455
1456var _ Path = ModuleObjPath{}
1457
1458// PathForModuleObj returns a Path representing the paths... under the module's
1459// 'obj' directory.
Liz Kammera830f3a2020-11-10 10:50:34 -08001460func PathForModuleObj(ctx ModuleOutPathContext, pathComponents ...string) ModuleObjPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001461 p, err := validatePath(pathComponents...)
1462 if err != nil {
1463 reportPathError(ctx, err)
1464 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001465 return ModuleObjPath{PathForModuleOut(ctx, "obj", p)}
1466}
1467
1468// ModuleResPath is a a Path representing the 'res' directory in a module's
1469// output directory.
1470type ModuleResPath struct {
1471 ModuleOutPath
1472}
1473
1474var _ Path = ModuleResPath{}
1475
1476// PathForModuleRes returns a Path representing the paths... under the module's
1477// 'res' directory.
Liz Kammera830f3a2020-11-10 10:50:34 -08001478func PathForModuleRes(ctx ModuleOutPathContext, pathComponents ...string) ModuleResPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001479 p, err := validatePath(pathComponents...)
1480 if err != nil {
1481 reportPathError(ctx, err)
1482 }
1483
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001484 return ModuleResPath{PathForModuleOut(ctx, "res", p)}
1485}
1486
Colin Cross70dda7e2019-10-01 22:05:35 -07001487// InstallPath is a Path representing a installed file path rooted from the build directory
1488type InstallPath struct {
1489 basePath
Colin Crossff6c33d2019-10-02 16:01:35 -07001490
Jiyong Park957bcd92020-10-20 18:23:33 +09001491 // partitionDir is the part of the InstallPath that is automatically determined according to the context.
1492 // For example, it is host/<os>-<arch> for host modules, and target/product/<device>/<partition> for device modules.
1493 partitionDir string
1494
1495 // makePath indicates whether this path is for Soong (false) or Make (true).
1496 makePath bool
Colin Cross70dda7e2019-10-01 22:05:35 -07001497}
1498
Paul Duffin9b478b02019-12-10 13:41:51 +00001499func (p InstallPath) buildDir() string {
1500 return p.config.buildDir
1501}
1502
Hans MÃ¥nssond3f2bd72020-11-27 12:37:28 +01001503func (p InstallPath) ReplaceExtension(ctx PathContext, ext string) OutputPath {
1504 panic("Not implemented")
1505}
1506
Paul Duffin9b478b02019-12-10 13:41:51 +00001507var _ Path = InstallPath{}
1508var _ WritablePath = InstallPath{}
1509
Colin Cross70dda7e2019-10-01 22:05:35 -07001510func (p InstallPath) writablePath() {}
1511
1512func (p InstallPath) String() string {
Jiyong Park957bcd92020-10-20 18:23:33 +09001513 if p.makePath {
1514 // Make path starts with out/ instead of out/soong.
1515 return filepath.Join(p.config.buildDir, "../", p.path)
1516 } else {
1517 return filepath.Join(p.config.buildDir, p.path)
1518 }
1519}
1520
1521// PartitionDir returns the path to the partition where the install path is rooted at. It is
1522// out/soong/target/product/<device>/<partition> for device modules, and out/soong/host/<os>-<arch> for host modules.
1523// The ./soong is dropped if the install path is for Make.
1524func (p InstallPath) PartitionDir() string {
1525 if p.makePath {
1526 return filepath.Join(p.config.buildDir, "../", p.partitionDir)
1527 } else {
1528 return filepath.Join(p.config.buildDir, p.partitionDir)
1529 }
Colin Cross70dda7e2019-10-01 22:05:35 -07001530}
1531
1532// Join creates a new InstallPath with paths... joined with the current path. The
1533// provided paths... may not use '..' to escape from the current path.
1534func (p InstallPath) Join(ctx PathContext, paths ...string) InstallPath {
1535 path, err := validatePath(paths...)
1536 if err != nil {
1537 reportPathError(ctx, err)
1538 }
1539 return p.withRel(path)
1540}
1541
1542func (p InstallPath) withRel(rel string) InstallPath {
1543 p.basePath = p.basePath.withRel(rel)
1544 return p
1545}
1546
Colin Crossff6c33d2019-10-02 16:01:35 -07001547// ToMakePath returns a new InstallPath that points to Make's install directory instead of Soong's,
1548// i.e. out/ instead of out/soong/.
1549func (p InstallPath) ToMakePath() InstallPath {
Jiyong Park957bcd92020-10-20 18:23:33 +09001550 p.makePath = true
Colin Crossff6c33d2019-10-02 16:01:35 -07001551 return p
Colin Cross70dda7e2019-10-01 22:05:35 -07001552}
1553
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001554// PathForModuleInstall returns a Path representing the install path for the
1555// module appended with paths...
Colin Cross70dda7e2019-10-01 22:05:35 -07001556func PathForModuleInstall(ctx ModuleInstallPathContext, pathComponents ...string) InstallPath {
Colin Cross6e359402020-02-10 15:29:54 -08001557 os := ctx.Os()
Jiyong Park87788b52020-09-01 12:37:45 +09001558 arch := ctx.Arch().ArchType
1559 forceOS, forceArch := ctx.InstallForceOS()
1560 if forceOS != nil {
Colin Cross6e359402020-02-10 15:29:54 -08001561 os = *forceOS
1562 }
Jiyong Park87788b52020-09-01 12:37:45 +09001563 if forceArch != nil {
1564 arch = *forceArch
1565 }
Colin Cross6e359402020-02-10 15:29:54 -08001566 partition := modulePartition(ctx, os)
Colin Cross609c49a2020-02-13 13:20:11 -08001567
Jiyong Park87788b52020-09-01 12:37:45 +09001568 ret := pathForInstall(ctx, os, arch, partition, ctx.Debug(), pathComponents...)
Colin Cross609c49a2020-02-13 13:20:11 -08001569
Jingwen Chencda22c92020-11-23 00:22:30 -05001570 if ctx.InstallBypassMake() && ctx.Config().KatiEnabled() {
Colin Cross609c49a2020-02-13 13:20:11 -08001571 ret = ret.ToMakePath()
1572 }
1573
1574 return ret
1575}
1576
Jiyong Park87788b52020-09-01 12:37:45 +09001577func pathForInstall(ctx PathContext, os OsType, arch ArchType, partition string, debug bool,
Colin Cross609c49a2020-02-13 13:20:11 -08001578 pathComponents ...string) InstallPath {
1579
Jiyong Park957bcd92020-10-20 18:23:33 +09001580 var partionPaths []string
Colin Cross609c49a2020-02-13 13:20:11 -08001581
Colin Cross6e359402020-02-10 15:29:54 -08001582 if os.Class == Device {
Jiyong Park957bcd92020-10-20 18:23:33 +09001583 partionPaths = []string{"target", "product", ctx.Config().DeviceName(), partition}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001584 } else {
Jiyong Park87788b52020-09-01 12:37:45 +09001585 osName := os.String()
1586 if os == Linux {
1587 // instead of linux_glibc
1588 osName = "linux"
Dan Willemsen866b5632017-09-22 12:28:24 -07001589 }
Jiyong Park87788b52020-09-01 12:37:45 +09001590 // SOONG_HOST_OUT is set to out/host/$(HOST_OS)-$(HOST_PREBUILT_ARCH)
1591 // and HOST_PREBUILT_ARCH is forcibly set to x86 even on x86_64 hosts. We don't seem
1592 // to have a plan to fix it (see the comment in build/make/core/envsetup.mk).
1593 // Let's keep using x86 for the existing cases until we have a need to support
1594 // other architectures.
1595 archName := arch.String()
1596 if os.Class == Host && (arch == X86_64 || arch == Common) {
1597 archName = "x86"
1598 }
Jiyong Park957bcd92020-10-20 18:23:33 +09001599 partionPaths = []string{"host", osName + "-" + archName, partition}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001600 }
Colin Cross609c49a2020-02-13 13:20:11 -08001601 if debug {
Jiyong Park957bcd92020-10-20 18:23:33 +09001602 partionPaths = append([]string{"debug"}, partionPaths...)
Dan Willemsen782a2d12015-12-21 14:55:28 -08001603 }
Colin Cross70dda7e2019-10-01 22:05:35 -07001604
Jiyong Park957bcd92020-10-20 18:23:33 +09001605 partionPath, err := validatePath(partionPaths...)
Colin Cross70dda7e2019-10-01 22:05:35 -07001606 if err != nil {
1607 reportPathError(ctx, err)
1608 }
Colin Crossff6c33d2019-10-02 16:01:35 -07001609
Jiyong Park957bcd92020-10-20 18:23:33 +09001610 base := InstallPath{
1611 basePath: basePath{partionPath, ctx.Config(), ""},
1612 partitionDir: partionPath,
1613 makePath: false,
1614 }
Colin Crossff6c33d2019-10-02 16:01:35 -07001615
Jiyong Park957bcd92020-10-20 18:23:33 +09001616 return base.Join(ctx, pathComponents...)
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001617}
1618
Nicolas Geoffray1228e9c2020-02-27 13:45:35 +00001619func pathForNdkOrSdkInstall(ctx PathContext, prefix string, paths []string) InstallPath {
Jiyong Park957bcd92020-10-20 18:23:33 +09001620 base := InstallPath{
1621 basePath: basePath{prefix, ctx.Config(), ""},
1622 partitionDir: prefix,
1623 makePath: false,
Colin Cross70dda7e2019-10-01 22:05:35 -07001624 }
Jiyong Park957bcd92020-10-20 18:23:33 +09001625 return base.Join(ctx, paths...)
Colin Cross70dda7e2019-10-01 22:05:35 -07001626}
1627
Nicolas Geoffray1228e9c2020-02-27 13:45:35 +00001628func PathForNdkInstall(ctx PathContext, paths ...string) InstallPath {
1629 return pathForNdkOrSdkInstall(ctx, "ndk", paths)
1630}
1631
1632func PathForMainlineSdksInstall(ctx PathContext, paths ...string) InstallPath {
1633 return pathForNdkOrSdkInstall(ctx, "mainline-sdks", paths)
1634}
1635
Colin Cross70dda7e2019-10-01 22:05:35 -07001636func InstallPathToOnDevicePath(ctx PathContext, path InstallPath) string {
Colin Cross43f08db2018-11-12 10:13:39 -08001637 rel := Rel(ctx, PathForOutput(ctx, "target", "product", ctx.Config().DeviceName()).String(), path.String())
1638
1639 return "/" + rel
1640}
1641
Colin Cross6e359402020-02-10 15:29:54 -08001642func modulePartition(ctx ModuleInstallPathContext, os OsType) string {
Colin Cross43f08db2018-11-12 10:13:39 -08001643 var partition string
Colin Cross6e359402020-02-10 15:29:54 -08001644 if ctx.InstallInTestcases() {
1645 // "testcases" install directory can be used for host or device modules.
Jaewoong Jung0949f312019-09-11 10:25:18 -07001646 partition = "testcases"
Colin Cross6e359402020-02-10 15:29:54 -08001647 } else if os.Class == Device {
1648 if ctx.InstallInData() {
1649 partition = "data"
1650 } else if ctx.InstallInRamdisk() {
1651 if ctx.DeviceConfig().BoardUsesRecoveryAsBoot() {
1652 partition = "recovery/root/first_stage_ramdisk"
1653 } else {
1654 partition = "ramdisk"
1655 }
1656 if !ctx.InstallInRoot() {
1657 partition += "/system"
1658 }
Yifan Hong60e0cfb2020-10-21 15:17:56 -07001659 } else if ctx.InstallInVendorRamdisk() {
Yifan Hong39143a92020-10-26 12:43:12 -07001660 // The module is only available after switching root into
1661 // /first_stage_ramdisk. To expose the module before switching root
1662 // on a device without a dedicated recovery partition, install the
1663 // recovery variant.
Yifan Hongdd8dacc2020-10-21 15:40:17 -07001664 if ctx.DeviceConfig().BoardMoveRecoveryResourcesToVendorBoot() {
Yifan Hong39143a92020-10-26 12:43:12 -07001665 partition = "vendor-ramdisk/first_stage_ramdisk"
Yifan Hongdd8dacc2020-10-21 15:40:17 -07001666 } else {
1667 partition = "vendor-ramdisk"
1668 }
1669 if !ctx.InstallInRoot() {
1670 partition += "/system"
1671 }
Colin Cross6e359402020-02-10 15:29:54 -08001672 } else if ctx.InstallInRecovery() {
1673 if ctx.InstallInRoot() {
1674 partition = "recovery/root"
1675 } else {
1676 // the layout of recovery partion is the same as that of system partition
1677 partition = "recovery/root/system"
1678 }
1679 } else if ctx.SocSpecific() {
1680 partition = ctx.DeviceConfig().VendorPath()
1681 } else if ctx.DeviceSpecific() {
1682 partition = ctx.DeviceConfig().OdmPath()
1683 } else if ctx.ProductSpecific() {
1684 partition = ctx.DeviceConfig().ProductPath()
1685 } else if ctx.SystemExtSpecific() {
1686 partition = ctx.DeviceConfig().SystemExtPath()
1687 } else if ctx.InstallInRoot() {
1688 partition = "root"
Yifan Hong82db7352020-01-21 16:12:26 -08001689 } else {
Colin Cross6e359402020-02-10 15:29:54 -08001690 partition = "system"
Yifan Hong82db7352020-01-21 16:12:26 -08001691 }
Colin Cross6e359402020-02-10 15:29:54 -08001692 if ctx.InstallInSanitizerDir() {
1693 partition = "data/asan/" + partition
Yifan Hong82db7352020-01-21 16:12:26 -08001694 }
Colin Cross43f08db2018-11-12 10:13:39 -08001695 }
1696 return partition
1697}
1698
Colin Cross609c49a2020-02-13 13:20:11 -08001699type InstallPaths []InstallPath
1700
1701// Paths returns the InstallPaths as a Paths
1702func (p InstallPaths) Paths() Paths {
1703 if p == nil {
1704 return nil
1705 }
1706 ret := make(Paths, len(p))
1707 for i, path := range p {
1708 ret[i] = path
1709 }
1710 return ret
1711}
1712
1713// Strings returns the string forms of the install paths.
1714func (p InstallPaths) Strings() []string {
1715 if p == nil {
1716 return nil
1717 }
1718 ret := make([]string, len(p))
1719 for i, path := range p {
1720 ret[i] = path.String()
1721 }
1722 return ret
1723}
1724
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001725// validateSafePath validates a path that we trust (may contain ninja variables).
Dan Willemsen80a7c2a2015-12-21 14:57:11 -08001726// Ensures that each path component does not attempt to leave its component.
Colin Cross1ccfcc32018-02-22 13:54:26 -08001727func validateSafePath(pathComponents ...string) (string, error) {
Jeff Gaston734e3802017-04-10 15:47:24 -07001728 for _, path := range pathComponents {
Dan Willemsen80a7c2a2015-12-21 14:57:11 -08001729 path := filepath.Clean(path)
1730 if path == ".." || strings.HasPrefix(path, "../") || strings.HasPrefix(path, "/") {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001731 return "", fmt.Errorf("Path is outside directory: %s", path)
Dan Willemsen80a7c2a2015-12-21 14:57:11 -08001732 }
1733 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001734 // TODO: filepath.Join isn't necessarily correct with embedded ninja
1735 // variables. '..' may remove the entire ninja variable, even if it
1736 // will be expanded to multiple nested directories.
Colin Cross1ccfcc32018-02-22 13:54:26 -08001737 return filepath.Join(pathComponents...), nil
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001738}
1739
Dan Willemsen80a7c2a2015-12-21 14:57:11 -08001740// validatePath validates that a path does not include ninja variables, and that
1741// each path component does not attempt to leave its component. Returns a joined
1742// version of each path component.
Colin Cross1ccfcc32018-02-22 13:54:26 -08001743func validatePath(pathComponents ...string) (string, error) {
Jeff Gaston734e3802017-04-10 15:47:24 -07001744 for _, path := range pathComponents {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001745 if strings.Contains(path, "$") {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001746 return "", fmt.Errorf("Path contains invalid character($): %s", path)
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001747 }
1748 }
Colin Cross1ccfcc32018-02-22 13:54:26 -08001749 return validateSafePath(pathComponents...)
Colin Cross6e18ca42015-07-14 18:55:36 -07001750}
Colin Cross5b529592017-05-09 13:34:34 -07001751
Colin Cross0875c522017-11-28 17:34:01 -08001752func PathForPhony(ctx PathContext, phony string) WritablePath {
1753 if strings.ContainsAny(phony, "$/") {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001754 ReportPathErrorf(ctx, "Phony target contains invalid character ($ or /): %s", phony)
Colin Cross0875c522017-11-28 17:34:01 -08001755 }
Colin Cross74e3fe42017-12-11 15:51:44 -08001756 return PhonyPath{basePath{phony, ctx.Config(), ""}}
Colin Cross0875c522017-11-28 17:34:01 -08001757}
1758
Colin Cross74e3fe42017-12-11 15:51:44 -08001759type PhonyPath struct {
1760 basePath
1761}
1762
1763func (p PhonyPath) writablePath() {}
1764
Paul Duffin9b478b02019-12-10 13:41:51 +00001765func (p PhonyPath) buildDir() string {
1766 return p.config.buildDir
1767}
1768
Hans MÃ¥nssond3f2bd72020-11-27 12:37:28 +01001769func (p PhonyPath) ReplaceExtension(ctx PathContext, ext string) OutputPath {
1770 panic("Not implemented")
1771}
1772
Colin Cross74e3fe42017-12-11 15:51:44 -08001773var _ Path = PhonyPath{}
1774var _ WritablePath = PhonyPath{}
1775
Colin Cross5b529592017-05-09 13:34:34 -07001776type testPath struct {
1777 basePath
1778}
1779
1780func (p testPath) String() string {
1781 return p.path
1782}
1783
Colin Cross40e33732019-02-15 11:08:35 -08001784// PathForTesting returns a Path constructed from joining the elements of paths with '/'. It should only be used from
1785// within tests.
Colin Cross5b529592017-05-09 13:34:34 -07001786func PathForTesting(paths ...string) Path {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001787 p, err := validateSafePath(paths...)
1788 if err != nil {
1789 panic(err)
1790 }
Colin Cross5b529592017-05-09 13:34:34 -07001791 return testPath{basePath{path: p, rel: p}}
1792}
1793
Colin Cross40e33732019-02-15 11:08:35 -08001794// PathsForTesting returns a Path constructed from each element in strs. It should only be used from within tests.
1795func PathsForTesting(strs ...string) Paths {
Colin Cross5b529592017-05-09 13:34:34 -07001796 p := make(Paths, len(strs))
1797 for i, s := range strs {
1798 p[i] = PathForTesting(s)
1799 }
1800
1801 return p
1802}
Colin Cross43f08db2018-11-12 10:13:39 -08001803
Colin Cross40e33732019-02-15 11:08:35 -08001804type testPathContext struct {
1805 config Config
Colin Cross40e33732019-02-15 11:08:35 -08001806}
1807
Colin Cross40e33732019-02-15 11:08:35 -08001808func (x *testPathContext) Config() Config { return x.config }
1809func (x *testPathContext) AddNinjaFileDeps(...string) {}
1810
1811// PathContextForTesting returns a PathContext that can be used in tests, for example to create an OutputPath with
1812// PathForOutput.
Colin Cross98be1bb2019-12-13 20:41:13 -08001813func PathContextForTesting(config Config) PathContext {
Colin Cross40e33732019-02-15 11:08:35 -08001814 return &testPathContext{
1815 config: config,
Colin Cross40e33732019-02-15 11:08:35 -08001816 }
1817}
1818
Ulya Trafimovichccc8c852020-10-14 11:29:07 +01001819type testModuleInstallPathContext struct {
1820 baseModuleContext
1821
1822 inData bool
1823 inTestcases bool
1824 inSanitizerDir bool
1825 inRamdisk bool
1826 inVendorRamdisk bool
1827 inRecovery bool
1828 inRoot bool
1829 forceOS *OsType
1830 forceArch *ArchType
1831}
1832
1833func (m testModuleInstallPathContext) Config() Config {
1834 return m.baseModuleContext.config
1835}
1836
1837func (testModuleInstallPathContext) AddNinjaFileDeps(deps ...string) {}
1838
1839func (m testModuleInstallPathContext) InstallInData() bool {
1840 return m.inData
1841}
1842
1843func (m testModuleInstallPathContext) InstallInTestcases() bool {
1844 return m.inTestcases
1845}
1846
1847func (m testModuleInstallPathContext) InstallInSanitizerDir() bool {
1848 return m.inSanitizerDir
1849}
1850
1851func (m testModuleInstallPathContext) InstallInRamdisk() bool {
1852 return m.inRamdisk
1853}
1854
1855func (m testModuleInstallPathContext) InstallInVendorRamdisk() bool {
1856 return m.inVendorRamdisk
1857}
1858
1859func (m testModuleInstallPathContext) InstallInRecovery() bool {
1860 return m.inRecovery
1861}
1862
1863func (m testModuleInstallPathContext) InstallInRoot() bool {
1864 return m.inRoot
1865}
1866
1867func (m testModuleInstallPathContext) InstallBypassMake() bool {
1868 return false
1869}
1870
1871func (m testModuleInstallPathContext) InstallForceOS() (*OsType, *ArchType) {
1872 return m.forceOS, m.forceArch
1873}
1874
1875// Construct a minimal ModuleInstallPathContext for testing. Note that baseModuleContext is
1876// default-initialized, which leaves blueprint.baseModuleContext set to nil, so methods that are
1877// delegated to it will panic.
1878func ModuleInstallPathContextForTesting(config Config) ModuleInstallPathContext {
1879 ctx := &testModuleInstallPathContext{}
1880 ctx.config = config
1881 ctx.os = Android
1882 return ctx
1883}
1884
Colin Cross43f08db2018-11-12 10:13:39 -08001885// Rel performs the same function as filepath.Rel, but reports errors to a PathContext, and reports an error if
1886// targetPath is not inside basePath.
1887func Rel(ctx PathContext, basePath string, targetPath string) string {
1888 rel, isRel := MaybeRel(ctx, basePath, targetPath)
1889 if !isRel {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001890 ReportPathErrorf(ctx, "path %q is not under path %q", targetPath, basePath)
Colin Cross43f08db2018-11-12 10:13:39 -08001891 return ""
1892 }
1893 return rel
1894}
1895
1896// MaybeRel performs the same function as filepath.Rel, but reports errors to a PathContext, and returns false if
1897// targetPath is not inside basePath.
1898func MaybeRel(ctx PathContext, basePath string, targetPath string) (string, bool) {
Dan Willemsen633c5022019-04-12 11:11:38 -07001899 rel, isRel, err := maybeRelErr(basePath, targetPath)
1900 if err != nil {
1901 reportPathError(ctx, err)
1902 }
1903 return rel, isRel
1904}
1905
1906func maybeRelErr(basePath string, targetPath string) (string, bool, error) {
Colin Cross43f08db2018-11-12 10:13:39 -08001907 // filepath.Rel returns an error if one path is absolute and the other is not, handle that case first.
1908 if filepath.IsAbs(basePath) != filepath.IsAbs(targetPath) {
Dan Willemsen633c5022019-04-12 11:11:38 -07001909 return "", false, nil
Colin Cross43f08db2018-11-12 10:13:39 -08001910 }
1911 rel, err := filepath.Rel(basePath, targetPath)
1912 if err != nil {
Dan Willemsen633c5022019-04-12 11:11:38 -07001913 return "", false, err
Colin Cross43f08db2018-11-12 10:13:39 -08001914 } else if rel == ".." || strings.HasPrefix(rel, "../") || strings.HasPrefix(rel, "/") {
Dan Willemsen633c5022019-04-12 11:11:38 -07001915 return "", false, nil
Colin Cross43f08db2018-11-12 10:13:39 -08001916 }
Dan Willemsen633c5022019-04-12 11:11:38 -07001917 return rel, true, nil
Colin Cross43f08db2018-11-12 10:13:39 -08001918}
Colin Cross988414c2020-01-11 01:11:46 +00001919
1920// Writes a file to the output directory. Attempting to write directly to the output directory
1921// will fail due to the sandbox of the soong_build process.
1922func WriteFileToOutputDir(path WritablePath, data []byte, perm os.FileMode) error {
1923 return ioutil.WriteFile(absolutePath(path.String()), data, perm)
1924}
1925
Liz Kammer2dd9ca42020-11-25 16:06:39 -08001926func RemoveAllOutputDir(path WritablePath) error {
1927 return os.RemoveAll(absolutePath(path.String()))
1928}
1929
1930func CreateOutputDirIfNonexistent(path WritablePath, perm os.FileMode) error {
1931 dir := absolutePath(path.String())
1932 if _, err := os.Stat(dir); os.IsNotExist(err) {
1933 return os.MkdirAll(dir, os.ModePerm)
1934 } else {
1935 return err
1936 }
1937}
1938
Colin Cross988414c2020-01-11 01:11:46 +00001939func absolutePath(path string) string {
1940 if filepath.IsAbs(path) {
1941 return path
1942 }
1943 return filepath.Join(absSrcDir, path)
1944}
Chris Parsons216e10a2020-07-09 17:12:52 -04001945
1946// A DataPath represents the path of a file to be used as data, for example
1947// a test library to be installed alongside a test.
1948// The data file should be installed (copied from `<SrcPath>`) to
1949// `<install_root>/<RelativeInstallPath>/<filename>`, or
1950// `<install_root>/<filename>` if RelativeInstallPath is empty.
1951type DataPath struct {
1952 // The path of the data file that should be copied into the data directory
1953 SrcPath Path
1954 // The install path of the data file, relative to the install root.
1955 RelativeInstallPath string
1956}
Colin Crossdcf71b22021-02-01 13:59:03 -08001957
1958// PathsIfNonNil returns a Paths containing only the non-nil input arguments.
1959func PathsIfNonNil(paths ...Path) Paths {
1960 if len(paths) == 0 {
1961 // Fast path for empty argument list
1962 return nil
1963 } else if len(paths) == 1 {
1964 // Fast path for a single argument
1965 if paths[0] != nil {
1966 return paths
1967 } else {
1968 return nil
1969 }
1970 }
1971 ret := make(Paths, 0, len(paths))
1972 for _, path := range paths {
1973 if path != nil {
1974 ret = append(ret, path)
1975 }
1976 }
1977 if len(ret) == 0 {
1978 return nil
1979 }
1980 return ret
1981}