blob: 4495ad3de14bcf3ea11bce7c07034005814daaae [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
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700283// PathsForSource returns Paths rooted from SrcDir
284func PathsForSource(ctx PathContext, paths []string) Paths {
285 ret := make(Paths, len(paths))
286 for i, path := range paths {
287 ret[i] = PathForSource(ctx, path)
288 }
289 return ret
290}
291
Jeff Gaston734e3802017-04-10 15:47:24 -0700292// ExistentPathsForSources returns a list of Paths rooted from SrcDir that are
Dan Willemsen7b310ee2015-12-18 15:11:17 -0800293// found in the tree. If any are not found, they are omitted from the list,
294// and dependencies are added so that we're re-run when they are added.
Colin Cross32f38982018-02-22 11:47:25 -0800295func ExistentPathsForSources(ctx PathContext, paths []string) Paths {
Dan Willemsen7b310ee2015-12-18 15:11:17 -0800296 ret := make(Paths, 0, len(paths))
297 for _, path := range paths {
Colin Cross32f38982018-02-22 11:47:25 -0800298 p := ExistentPathForSource(ctx, path)
Dan Willemsen7b310ee2015-12-18 15:11:17 -0800299 if p.Valid() {
300 ret = append(ret, p.Path())
301 }
302 }
303 return ret
304}
305
Colin Cross41955e82019-05-29 14:40:35 -0700306// PathsForModuleSrc returns Paths rooted from the module's local source directory. It expands globs, references to
307// SourceFileProducer modules using the ":name" syntax, and references to OutputFileProducer modules using the
308// ":name{.tag}" syntax. Properties passed as the paths argument must have been annotated with struct tag
309// `android:"path"` so that dependencies on SourceFileProducer modules will have already been handled by the
310// path_properties mutator. If ctx.Config().AllowMissingDependencies() is true then any missing SourceFileProducer or
311// OutputFileProducer dependencies will cause the module to be marked as having missing dependencies.
Liz Kammera830f3a2020-11-10 10:50:34 -0800312func PathsForModuleSrc(ctx ModuleMissingDepsPathContext, paths []string) Paths {
Colin Cross8a497952019-03-05 22:25:09 -0800313 return PathsForModuleSrcExcludes(ctx, paths, nil)
314}
315
Colin Crossba71a3f2019-03-18 12:12:48 -0700316// PathsForModuleSrcExcludes returns Paths rooted from the module's local source directory, excluding paths listed in
Colin Cross41955e82019-05-29 14:40:35 -0700317// the excludes arguments. It expands globs, references to SourceFileProducer modules using the ":name" syntax, and
318// references to OutputFileProducer modules using the ":name{.tag}" syntax. Properties passed as the paths or excludes
319// argument must have been annotated with struct tag `android:"path"` so that dependencies on SourceFileProducer modules
320// will have already been handled by the path_properties mutator. If ctx.Config().AllowMissingDependencies() is
Paul Duffin036cace2019-07-25 14:44:56 +0100321// true then any missing SourceFileProducer or OutputFileProducer dependencies will cause the module to be marked as
Colin Cross41955e82019-05-29 14:40:35 -0700322// having missing dependencies.
Liz Kammera830f3a2020-11-10 10:50:34 -0800323func PathsForModuleSrcExcludes(ctx ModuleMissingDepsPathContext, paths, excludes []string) Paths {
Colin Crossba71a3f2019-03-18 12:12:48 -0700324 ret, missingDeps := PathsAndMissingDepsForModuleSrcExcludes(ctx, paths, excludes)
325 if ctx.Config().AllowMissingDependencies() {
326 ctx.AddMissingDependencies(missingDeps)
327 } else {
328 for _, m := range missingDeps {
329 ctx.ModuleErrorf(`missing dependency on %q, is the property annotated with android:"path"?`, m)
330 }
331 }
332 return ret
333}
334
Liz Kammer356f7d42021-01-26 09:18:53 -0500335// A subset of the ModuleContext methods which are sufficient to resolve references to paths/deps in
336// order to form a Bazel-compatible label for conversion.
337type BazelConversionPathContext interface {
338 EarlyModulePathContext
339
340 GetDirectDep(name string) (blueprint.Module, blueprint.DependencyTag)
341 OtherModuleName(m blueprint.Module) string
342 OtherModuleDir(m blueprint.Module) string
343}
344
345// BazelLabelForModuleDeps returns a Bazel-compatible label for the requested modules which
346// correspond to dependencies on the module within the given ctx.
347func BazelLabelForModuleDeps(ctx BazelConversionPathContext, modules []string) bazel.LabelList {
348 var labels bazel.LabelList
349 for _, module := range modules {
350 bpText := module
351 if m := SrcIsModule(module); m == "" {
352 module = ":" + module
353 }
354 if m, t := SrcIsModuleWithTag(module); m != "" {
355 l := getOtherModuleLabel(ctx, m, t)
356 l.Bp_text = bpText
357 labels.Includes = append(labels.Includes, l)
358 } else {
359 ctx.ModuleErrorf("%q, is not a module reference", module)
360 }
361 }
362 return labels
363}
364
365// BazelLabelForModuleSrc returns bazel.LabelList with paths rooted from the module's local source
366// directory. It expands globs, and resolves references to modules using the ":name" syntax to
367// bazel-compatible labels. Properties passed as the paths or excludes argument must have been
368// annotated with struct tag `android:"path"` so that dependencies on other modules will have
369// already been handled by the path_properties mutator.
370func BazelLabelForModuleSrc(ctx BazelConversionPathContext, paths []string) bazel.LabelList {
371 return BazelLabelForModuleSrcExcludes(ctx, paths, []string(nil))
372}
373
374// BazelLabelForModuleSrcExcludes returns bazel.LabelList with paths rooted from the module's local
375// source directory, excluding labels included in the excludes argument. It expands globs, and
376// resolves references to modules using the ":name" syntax to bazel-compatible labels. Properties
377// passed as the paths or excludes argument must have been annotated with struct tag
378// `android:"path"` so that dependencies on other modules will have already been handled by the
379// path_properties mutator.
380func BazelLabelForModuleSrcExcludes(ctx BazelConversionPathContext, paths, excludes []string) bazel.LabelList {
381 excludeLabels := expandSrcsForBazel(ctx, excludes, []string(nil))
382 excluded := make([]string, 0, len(excludeLabels.Includes))
383 for _, e := range excludeLabels.Includes {
384 excluded = append(excluded, e.Label)
385 }
386 labels := expandSrcsForBazel(ctx, paths, excluded)
387 labels.Excludes = excludeLabels.Includes
388 return labels
389}
390
391// expandSrcsForBazel returns bazel.LabelList with paths rooted from the module's local
392// source directory, excluding labels included in the excludes argument. It expands globs, and
393// resolves references to modules using the ":name" syntax to bazel-compatible labels. Properties
394// passed as the paths or excludes argument must have been annotated with struct tag
395// `android:"path"` so that dependencies on other modules will have already been handled by the
396// path_properties mutator.
397func expandSrcsForBazel(ctx BazelConversionPathContext, paths, expandedExcludes []string) bazel.LabelList {
Liz Kammerebfcf672021-02-16 15:00:05 -0500398 if paths == nil {
399 return bazel.LabelList{}
400 }
Liz Kammer356f7d42021-01-26 09:18:53 -0500401 labels := bazel.LabelList{
402 Includes: []bazel.Label{},
403 }
404 for _, p := range paths {
405 if m, tag := SrcIsModuleWithTag(p); m != "" {
406 l := getOtherModuleLabel(ctx, m, tag)
407 if !InList(l.Label, expandedExcludes) {
408 l.Bp_text = fmt.Sprintf(":%s", m)
409 labels.Includes = append(labels.Includes, l)
410 }
411 } else {
412 var expandedPaths []bazel.Label
413 if pathtools.IsGlob(p) {
414 globbedPaths := GlobFiles(ctx, pathForModuleSrc(ctx, p).String(), expandedExcludes)
415 globbedPaths = PathsWithModuleSrcSubDir(ctx, globbedPaths, "")
416 for _, path := range globbedPaths {
417 s := path.Rel()
418 expandedPaths = append(expandedPaths, bazel.Label{Label: s})
419 }
420 } else {
421 if !InList(p, expandedExcludes) {
422 expandedPaths = append(expandedPaths, bazel.Label{Label: p})
423 }
424 }
425 labels.Includes = append(labels.Includes, expandedPaths...)
426 }
427 }
428 return labels
429}
430
431// getOtherModuleLabel returns a bazel.Label for the given dependency/tag combination for the
432// module. The label will be relative to the current directory if appropriate. The dependency must
433// already be resolved by either deps mutator or path deps mutator.
434func getOtherModuleLabel(ctx BazelConversionPathContext, dep, tag string) bazel.Label {
435 m, _ := ctx.GetDirectDep(dep)
436 // TODO(b/165114590): Convert tag (":name{.tag}") to corresponding Bazel implicit output targets.
437 otherModuleName := ctx.OtherModuleName(m)
438 var label bazel.Label
439 if otherDir, dir := ctx.OtherModuleDir(m), ctx.ModuleDir(); otherDir != dir {
440 label.Label = fmt.Sprintf("//%s:%s", otherDir, otherModuleName)
441 } else {
442 label.Label = fmt.Sprintf(":%s", otherModuleName)
443 }
444 return label
445}
446
Ulya Trafimovich4d2eeed2019-11-08 10:54:21 +0000447// OutputPaths is a slice of OutputPath objects, with helpers to operate on the collection.
448type OutputPaths []OutputPath
449
450// Paths returns the OutputPaths as a Paths
451func (p OutputPaths) Paths() Paths {
452 if p == nil {
453 return nil
454 }
455 ret := make(Paths, len(p))
456 for i, path := range p {
457 ret[i] = path
458 }
459 return ret
460}
461
462// Strings returns the string forms of the writable paths.
463func (p OutputPaths) Strings() []string {
464 if p == nil {
465 return nil
466 }
467 ret := make([]string, len(p))
468 for i, path := range p {
469 ret[i] = path.String()
470 }
471 return ret
472}
473
Liz Kammera830f3a2020-11-10 10:50:34 -0800474// Expands Paths to a SourceFileProducer or OutputFileProducer module dependency referenced via ":name" or ":name{.tag}" syntax.
475// If the dependency is not found, a missingErrorDependency is returned.
476// If the module dependency is not a SourceFileProducer or OutputFileProducer, appropriate errors will be returned.
477func getPathsFromModuleDep(ctx ModuleWithDepsPathContext, path, moduleName, tag string) (Paths, error) {
478 module := ctx.GetDirectDepWithTag(moduleName, sourceOrOutputDepTag(tag))
479 if module == nil {
480 return nil, missingDependencyError{[]string{moduleName}}
481 }
482 if outProducer, ok := module.(OutputFileProducer); ok {
483 outputFiles, err := outProducer.OutputFiles(tag)
484 if err != nil {
485 return nil, fmt.Errorf("path dependency %q: %s", path, err)
486 }
487 return outputFiles, nil
488 } else if tag != "" {
489 return nil, fmt.Errorf("path dependency %q is not an output file producing module", path)
490 } else if srcProducer, ok := module.(SourceFileProducer); ok {
491 return srcProducer.Srcs(), nil
492 } else {
493 return nil, fmt.Errorf("path dependency %q is not a source file producing module", path)
494 }
495}
496
Colin Crossba71a3f2019-03-18 12:12:48 -0700497// PathsAndMissingDepsForModuleSrcExcludes returns Paths rooted from the module's local source directory, excluding
Colin Cross41955e82019-05-29 14:40:35 -0700498// paths listed in the excludes arguments, and a list of missing dependencies. It expands globs, references to
499// SourceFileProducer modules using the ":name" syntax, and references to OutputFileProducer modules using the
500// ":name{.tag}" syntax. Properties passed as the paths or excludes argument must have been annotated with struct tag
501// `android:"path"` so that dependencies on SourceFileProducer modules will have already been handled by the
502// path_properties mutator. If ctx.Config().AllowMissingDependencies() is true then any missing SourceFileProducer or
503// OutputFileProducer dependencies will be returned, and they will NOT cause the module to be marked as having missing
504// dependencies.
Liz Kammera830f3a2020-11-10 10:50:34 -0800505func PathsAndMissingDepsForModuleSrcExcludes(ctx ModuleWithDepsPathContext, paths, excludes []string) (Paths, []string) {
Colin Cross8a497952019-03-05 22:25:09 -0800506 prefix := pathForModuleSrc(ctx).String()
507
508 var expandedExcludes []string
509 if excludes != nil {
510 expandedExcludes = make([]string, 0, len(excludes))
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700511 }
Colin Cross8a497952019-03-05 22:25:09 -0800512
Colin Crossba71a3f2019-03-18 12:12:48 -0700513 var missingExcludeDeps []string
514
Colin Cross8a497952019-03-05 22:25:09 -0800515 for _, e := range excludes {
Colin Cross41955e82019-05-29 14:40:35 -0700516 if m, t := SrcIsModuleWithTag(e); m != "" {
Liz Kammera830f3a2020-11-10 10:50:34 -0800517 modulePaths, err := getPathsFromModuleDep(ctx, e, m, t)
518 if m, ok := err.(missingDependencyError); ok {
519 missingExcludeDeps = append(missingExcludeDeps, m.missingDeps...)
520 } else if err != nil {
521 reportPathError(ctx, err)
Colin Cross8a497952019-03-05 22:25:09 -0800522 } else {
Liz Kammera830f3a2020-11-10 10:50:34 -0800523 expandedExcludes = append(expandedExcludes, modulePaths.Strings()...)
Colin Cross8a497952019-03-05 22:25:09 -0800524 }
525 } else {
526 expandedExcludes = append(expandedExcludes, filepath.Join(prefix, e))
527 }
528 }
529
530 if paths == nil {
Colin Crossba71a3f2019-03-18 12:12:48 -0700531 return nil, missingExcludeDeps
Colin Cross8a497952019-03-05 22:25:09 -0800532 }
533
Colin Crossba71a3f2019-03-18 12:12:48 -0700534 var missingDeps []string
535
Colin Cross8a497952019-03-05 22:25:09 -0800536 expandedSrcFiles := make(Paths, 0, len(paths))
537 for _, s := range paths {
538 srcFiles, err := expandOneSrcPath(ctx, s, expandedExcludes)
539 if depErr, ok := err.(missingDependencyError); ok {
Colin Crossba71a3f2019-03-18 12:12:48 -0700540 missingDeps = append(missingDeps, depErr.missingDeps...)
Colin Cross8a497952019-03-05 22:25:09 -0800541 } else if err != nil {
542 reportPathError(ctx, err)
543 }
544 expandedSrcFiles = append(expandedSrcFiles, srcFiles...)
545 }
Colin Crossba71a3f2019-03-18 12:12:48 -0700546
547 return expandedSrcFiles, append(missingDeps, missingExcludeDeps...)
Colin Cross8a497952019-03-05 22:25:09 -0800548}
549
550type missingDependencyError struct {
551 missingDeps []string
552}
553
554func (e missingDependencyError) Error() string {
555 return "missing dependencies: " + strings.Join(e.missingDeps, ", ")
556}
557
Liz Kammera830f3a2020-11-10 10:50:34 -0800558// Expands one path string to Paths rooted from the module's local source
559// directory, excluding those listed in the expandedExcludes.
560// Expands globs, references to SourceFileProducer or OutputFileProducer modules using the ":name" and ":name{.tag}" syntax.
561func expandOneSrcPath(ctx ModuleWithDepsPathContext, sPath string, expandedExcludes []string) (Paths, error) {
Jooyung Han7607dd32020-07-05 10:23:14 +0900562 excludePaths := func(paths Paths) Paths {
563 if len(expandedExcludes) == 0 {
564 return paths
565 }
566 remainder := make(Paths, 0, len(paths))
567 for _, p := range paths {
568 if !InList(p.String(), expandedExcludes) {
569 remainder = append(remainder, p)
570 }
571 }
572 return remainder
573 }
Liz Kammera830f3a2020-11-10 10:50:34 -0800574 if m, t := SrcIsModuleWithTag(sPath); m != "" {
575 modulePaths, err := getPathsFromModuleDep(ctx, sPath, m, t)
576 if err != nil {
577 return nil, err
Colin Cross8a497952019-03-05 22:25:09 -0800578 } else {
Liz Kammera830f3a2020-11-10 10:50:34 -0800579 return excludePaths(modulePaths), nil
Colin Cross8a497952019-03-05 22:25:09 -0800580 }
Liz Kammera830f3a2020-11-10 10:50:34 -0800581 } else if pathtools.IsGlob(sPath) {
582 paths := GlobFiles(ctx, pathForModuleSrc(ctx, sPath).String(), expandedExcludes)
Colin Cross8a497952019-03-05 22:25:09 -0800583 return PathsWithModuleSrcSubDir(ctx, paths, ""), nil
584 } else {
Liz Kammera830f3a2020-11-10 10:50:34 -0800585 p := pathForModuleSrc(ctx, sPath)
Colin Cross988414c2020-01-11 01:11:46 +0000586 if exists, _, err := ctx.Config().fs.Exists(p.String()); err != nil {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +0100587 ReportPathErrorf(ctx, "%s: %s", p, err.Error())
Colin Cross5e6a7972020-06-07 16:56:32 -0700588 } else if !exists && !ctx.Config().testAllowNonExistentPaths {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +0100589 ReportPathErrorf(ctx, "module source path %q does not exist", p)
Colin Cross8a497952019-03-05 22:25:09 -0800590 }
591
Jooyung Han7607dd32020-07-05 10:23:14 +0900592 if InList(p.String(), expandedExcludes) {
Colin Cross8a497952019-03-05 22:25:09 -0800593 return nil, nil
594 }
595 return Paths{p}, nil
596 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700597}
598
599// pathsForModuleSrcFromFullPath returns Paths rooted from the module's local
600// source directory, but strip the local source directory from the beginning of
Dan Willemsen540a78c2018-02-26 21:50:08 -0800601// each string. If incDirs is false, strip paths with a trailing '/' from the list.
Colin Crossfe4bc362018-09-12 10:02:13 -0700602// It intended for use in globs that only list files that exist, so it allows '$' in
603// filenames.
Liz Kammera830f3a2020-11-10 10:50:34 -0800604func pathsForModuleSrcFromFullPath(ctx EarlyModulePathContext, paths []string, incDirs bool) Paths {
Colin Cross6510f912017-11-29 00:27:14 -0800605 prefix := filepath.Join(ctx.Config().srcDir, ctx.ModuleDir()) + "/"
Colin Cross0f37af02017-09-27 17:42:05 -0700606 if prefix == "./" {
607 prefix = ""
608 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700609 ret := make(Paths, 0, len(paths))
610 for _, p := range paths {
Dan Willemsen540a78c2018-02-26 21:50:08 -0800611 if !incDirs && strings.HasSuffix(p, "/") {
612 continue
613 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700614 path := filepath.Clean(p)
615 if !strings.HasPrefix(path, prefix) {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +0100616 ReportPathErrorf(ctx, "Path %q is not in module source directory %q", p, prefix)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700617 continue
618 }
Colin Crosse3924e12018-08-15 20:18:53 -0700619
Colin Crossfe4bc362018-09-12 10:02:13 -0700620 srcPath, err := safePathForSource(ctx, ctx.ModuleDir(), path[len(prefix):])
Colin Crosse3924e12018-08-15 20:18:53 -0700621 if err != nil {
622 reportPathError(ctx, err)
623 continue
624 }
625
Colin Cross07e51612019-03-05 12:46:40 -0800626 srcPath.basePath.rel = srcPath.path
Colin Crosse3924e12018-08-15 20:18:53 -0700627
Colin Cross07e51612019-03-05 12:46:40 -0800628 ret = append(ret, srcPath)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700629 }
630 return ret
631}
632
Liz Kammera830f3a2020-11-10 10:50:34 -0800633// PathsWithOptionalDefaultForModuleSrc returns Paths rooted from the module's local source
634// directory. If input is nil, use the default if it exists. If input is empty, returns nil.
635func PathsWithOptionalDefaultForModuleSrc(ctx ModuleMissingDepsPathContext, input []string, def string) Paths {
Colin Cross0ddae7f2019-02-07 15:30:01 -0800636 if input != nil {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700637 return PathsForModuleSrc(ctx, input)
638 }
639 // Use Glob so that if the default doesn't exist, a dependency is added so that when it
640 // is created, we're run again.
Colin Cross6510f912017-11-29 00:27:14 -0800641 path := filepath.Join(ctx.Config().srcDir, ctx.ModuleDir(), def)
Liz Kammera830f3a2020-11-10 10:50:34 -0800642 return Glob(ctx, path, nil)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700643}
644
645// Strings returns the Paths in string form
646func (p Paths) Strings() []string {
647 if p == nil {
648 return nil
649 }
650 ret := make([]string, len(p))
651 for i, path := range p {
652 ret[i] = path.String()
653 }
654 return ret
655}
656
Colin Crossc0efd1d2020-07-03 11:56:24 -0700657func CopyOfPaths(paths Paths) Paths {
658 return append(Paths(nil), paths...)
659}
660
Colin Crossb6715442017-10-24 11:13:31 -0700661// FirstUniquePaths returns all unique elements of a Paths, keeping the first copy of each. It
662// modifies the Paths slice contents in place, and returns a subslice of the original slice.
Dan Willemsenfe92c962017-08-29 12:28:37 -0700663func FirstUniquePaths(list Paths) Paths {
Colin Cross27027c72020-02-28 15:34:17 -0800664 // 128 was chosen based on BenchmarkFirstUniquePaths results.
665 if len(list) > 128 {
666 return firstUniquePathsMap(list)
667 }
668 return firstUniquePathsList(list)
669}
670
Colin Crossc0efd1d2020-07-03 11:56:24 -0700671// SortedUniquePaths returns all unique elements of a Paths in sorted order. It modifies the
672// Paths slice contents in place, and returns a subslice of the original slice.
Jiyong Park33c77362020-05-29 22:00:16 +0900673func SortedUniquePaths(list Paths) Paths {
674 unique := FirstUniquePaths(list)
675 sort.Slice(unique, func(i, j int) bool {
676 return unique[i].String() < unique[j].String()
677 })
678 return unique
679}
680
Colin Cross27027c72020-02-28 15:34:17 -0800681func firstUniquePathsList(list Paths) Paths {
Dan Willemsenfe92c962017-08-29 12:28:37 -0700682 k := 0
683outer:
684 for i := 0; i < len(list); i++ {
685 for j := 0; j < k; j++ {
686 if list[i] == list[j] {
687 continue outer
688 }
689 }
690 list[k] = list[i]
691 k++
692 }
693 return list[:k]
694}
695
Colin Cross27027c72020-02-28 15:34:17 -0800696func firstUniquePathsMap(list Paths) Paths {
697 k := 0
698 seen := make(map[Path]bool, len(list))
699 for i := 0; i < len(list); i++ {
700 if seen[list[i]] {
701 continue
702 }
703 seen[list[i]] = true
704 list[k] = list[i]
705 k++
706 }
707 return list[:k]
708}
709
Colin Cross5d583952020-11-24 16:21:24 -0800710// FirstUniqueInstallPaths returns all unique elements of an InstallPaths, keeping the first copy of each. It
711// modifies the InstallPaths slice contents in place, and returns a subslice of the original slice.
712func FirstUniqueInstallPaths(list InstallPaths) InstallPaths {
713 // 128 was chosen based on BenchmarkFirstUniquePaths results.
714 if len(list) > 128 {
715 return firstUniqueInstallPathsMap(list)
716 }
717 return firstUniqueInstallPathsList(list)
718}
719
720func firstUniqueInstallPathsList(list InstallPaths) InstallPaths {
721 k := 0
722outer:
723 for i := 0; i < len(list); i++ {
724 for j := 0; j < k; j++ {
725 if list[i] == list[j] {
726 continue outer
727 }
728 }
729 list[k] = list[i]
730 k++
731 }
732 return list[:k]
733}
734
735func firstUniqueInstallPathsMap(list InstallPaths) InstallPaths {
736 k := 0
737 seen := make(map[InstallPath]bool, len(list))
738 for i := 0; i < len(list); i++ {
739 if seen[list[i]] {
740 continue
741 }
742 seen[list[i]] = true
743 list[k] = list[i]
744 k++
745 }
746 return list[:k]
747}
748
Colin Crossb6715442017-10-24 11:13:31 -0700749// LastUniquePaths returns all unique elements of a Paths, keeping the last copy of each. It
750// modifies the Paths slice contents in place, and returns a subslice of the original slice.
751func LastUniquePaths(list Paths) Paths {
752 totalSkip := 0
753 for i := len(list) - 1; i >= totalSkip; i-- {
754 skip := 0
755 for j := i - 1; j >= totalSkip; j-- {
756 if list[i] == list[j] {
757 skip++
758 } else {
759 list[j+skip] = list[j]
760 }
761 }
762 totalSkip += skip
763 }
764 return list[totalSkip:]
765}
766
Colin Crossa140bb02018-04-17 10:52:26 -0700767// ReversePaths returns a copy of a Paths in reverse order.
768func ReversePaths(list Paths) Paths {
769 if list == nil {
770 return nil
771 }
772 ret := make(Paths, len(list))
773 for i := range list {
774 ret[i] = list[len(list)-1-i]
775 }
776 return ret
777}
778
Jeff Gaston294356f2017-09-27 17:05:30 -0700779func indexPathList(s Path, list []Path) int {
780 for i, l := range list {
781 if l == s {
782 return i
783 }
784 }
785
786 return -1
787}
788
789func inPathList(p Path, list []Path) bool {
790 return indexPathList(p, list) != -1
791}
792
793func FilterPathList(list []Path, filter []Path) (remainder []Path, filtered []Path) {
Paul Duffin57b9e1d2019-12-13 00:03:35 +0000794 return FilterPathListPredicate(list, func(p Path) bool { return inPathList(p, filter) })
795}
796
797func FilterPathListPredicate(list []Path, predicate func(Path) bool) (remainder []Path, filtered []Path) {
Jeff Gaston294356f2017-09-27 17:05:30 -0700798 for _, l := range list {
Paul Duffin57b9e1d2019-12-13 00:03:35 +0000799 if predicate(l) {
Jeff Gaston294356f2017-09-27 17:05:30 -0700800 filtered = append(filtered, l)
801 } else {
802 remainder = append(remainder, l)
803 }
804 }
805
806 return
807}
808
Colin Cross93e85952017-08-15 13:34:18 -0700809// HasExt returns true of any of the paths have extension ext, otherwise false
810func (p Paths) HasExt(ext string) bool {
811 for _, path := range p {
812 if path.Ext() == ext {
813 return true
814 }
815 }
816
817 return false
818}
819
820// FilterByExt returns the subset of the paths that have extension ext
821func (p Paths) FilterByExt(ext string) Paths {
822 ret := make(Paths, 0, len(p))
823 for _, path := range p {
824 if path.Ext() == ext {
825 ret = append(ret, path)
826 }
827 }
828 return ret
829}
830
831// FilterOutByExt returns the subset of the paths that do not have extension ext
832func (p Paths) FilterOutByExt(ext string) Paths {
833 ret := make(Paths, 0, len(p))
834 for _, path := range p {
835 if path.Ext() != ext {
836 ret = append(ret, path)
837 }
838 }
839 return ret
840}
841
Colin Cross5e6cfbe2017-11-03 15:20:35 -0700842// DirectorySortedPaths is a slice of paths that are sorted such that all files in a directory
843// (including subdirectories) are in a contiguous subslice of the list, and can be found in
844// O(log(N)) time using a binary search on the directory prefix.
845type DirectorySortedPaths Paths
846
847func PathsToDirectorySortedPaths(paths Paths) DirectorySortedPaths {
848 ret := append(DirectorySortedPaths(nil), paths...)
849 sort.Slice(ret, func(i, j int) bool {
850 return ret[i].String() < ret[j].String()
851 })
852 return ret
853}
854
855// PathsInDirectory returns a subslice of the DirectorySortedPaths as a Paths that contains all entries
856// that are in the specified directory and its subdirectories.
857func (p DirectorySortedPaths) PathsInDirectory(dir string) Paths {
858 prefix := filepath.Clean(dir) + "/"
859 start := sort.Search(len(p), func(i int) bool {
860 return prefix < p[i].String()
861 })
862
863 ret := p[start:]
864
865 end := sort.Search(len(ret), func(i int) bool {
866 return !strings.HasPrefix(ret[i].String(), prefix)
867 })
868
869 ret = ret[:end]
870
871 return Paths(ret)
872}
873
Alex Humesky29e3bbe2020-11-20 21:30:13 -0500874// WritablePaths is a slice of WritablePath, used for multiple outputs.
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700875type WritablePaths []WritablePath
876
877// Strings returns the string forms of the writable paths.
878func (p WritablePaths) Strings() []string {
879 if p == nil {
880 return nil
881 }
882 ret := make([]string, len(p))
883 for i, path := range p {
884 ret[i] = path.String()
885 }
886 return ret
887}
888
Colin Cross3bc7ffa2017-11-22 16:19:37 -0800889// Paths returns the WritablePaths as a Paths
890func (p WritablePaths) Paths() Paths {
891 if p == nil {
892 return nil
893 }
894 ret := make(Paths, len(p))
895 for i, path := range p {
896 ret[i] = path
897 }
898 return ret
899}
900
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700901type basePath struct {
902 path string
903 config Config
Colin Crossfaeb7aa2017-02-01 14:12:44 -0800904 rel string
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700905}
906
907func (p basePath) Ext() string {
908 return filepath.Ext(p.path)
909}
910
Colin Cross4f6fc9c2016-10-26 10:05:25 -0700911func (p basePath) Base() string {
912 return filepath.Base(p.path)
913}
914
Colin Crossfaeb7aa2017-02-01 14:12:44 -0800915func (p basePath) Rel() string {
916 if p.rel != "" {
917 return p.rel
918 }
919 return p.path
920}
921
Colin Cross0875c522017-11-28 17:34:01 -0800922func (p basePath) String() string {
923 return p.path
924}
925
Colin Cross0db55682017-12-05 15:36:55 -0800926func (p basePath) withRel(rel string) basePath {
927 p.path = filepath.Join(p.path, rel)
928 p.rel = rel
929 return p
930}
931
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700932// SourcePath is a Path representing a file path rooted from SrcDir
933type SourcePath struct {
934 basePath
935}
936
937var _ Path = SourcePath{}
938
Colin Cross0db55682017-12-05 15:36:55 -0800939func (p SourcePath) withRel(rel string) SourcePath {
940 p.basePath = p.basePath.withRel(rel)
941 return p
942}
943
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700944// safePathForSource is for paths that we expect are safe -- only for use by go
945// code that is embedding ninja variables in paths
Colin Crossfe4bc362018-09-12 10:02:13 -0700946func safePathForSource(ctx PathContext, pathComponents ...string) (SourcePath, error) {
947 p, err := validateSafePath(pathComponents...)
Colin Crossaabf6792017-11-29 00:27:14 -0800948 ret := SourcePath{basePath{p, ctx.Config(), ""}}
Colin Crossfe4bc362018-09-12 10:02:13 -0700949 if err != nil {
950 return ret, err
951 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700952
Colin Cross7b3dcc32019-01-24 13:14:39 -0800953 // absolute path already checked by validateSafePath
954 if strings.HasPrefix(ret.String(), ctx.Config().buildDir) {
Mikhail Naganovab1f5182019-02-08 13:17:55 -0800955 return ret, fmt.Errorf("source path %q is in output", ret.String())
Colin Cross6e18ca42015-07-14 18:55:36 -0700956 }
957
Colin Crossfe4bc362018-09-12 10:02:13 -0700958 return ret, err
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700959}
960
Colin Cross192e97a2018-02-22 14:21:02 -0800961// pathForSource creates a SourcePath from pathComponents, but does not check that it exists.
962func pathForSource(ctx PathContext, pathComponents ...string) (SourcePath, error) {
Colin Crossc48c1432018-02-23 07:09:01 +0000963 p, err := validatePath(pathComponents...)
964 ret := SourcePath{basePath{p, ctx.Config(), ""}}
Colin Cross94a32102018-02-22 14:21:02 -0800965 if err != nil {
Colin Cross192e97a2018-02-22 14:21:02 -0800966 return ret, err
Colin Cross94a32102018-02-22 14:21:02 -0800967 }
968
Colin Cross7b3dcc32019-01-24 13:14:39 -0800969 // absolute path already checked by validatePath
970 if strings.HasPrefix(ret.String(), ctx.Config().buildDir) {
Mikhail Naganovab1f5182019-02-08 13:17:55 -0800971 return ret, fmt.Errorf("source path %q is in output", ret.String())
Colin Crossc48c1432018-02-23 07:09:01 +0000972 }
973
Colin Cross192e97a2018-02-22 14:21:02 -0800974 return ret, nil
975}
976
977// existsWithDependencies returns true if the path exists, and adds appropriate dependencies to rerun if the
978// path does not exist.
979func existsWithDependencies(ctx PathContext, path SourcePath) (exists bool, err error) {
980 var files []string
981
982 if gctx, ok := ctx.(PathGlobContext); ok {
983 // Use glob to produce proper dependencies, even though we only want
984 // a single file.
985 files, err = gctx.GlobWithDeps(path.String(), nil)
986 } else {
987 var deps []string
988 // We cannot add build statements in this context, so we fall back to
989 // AddNinjaFileDeps
Colin Cross988414c2020-01-11 01:11:46 +0000990 files, deps, err = ctx.Config().fs.Glob(path.String(), nil, pathtools.FollowSymlinks)
Colin Cross192e97a2018-02-22 14:21:02 -0800991 ctx.AddNinjaFileDeps(deps...)
992 }
993
994 if err != nil {
995 return false, fmt.Errorf("glob: %s", err.Error())
996 }
997
998 return len(files) > 0, nil
999}
1000
1001// PathForSource joins the provided path components and validates that the result
1002// neither escapes the source dir nor is in the out dir.
1003// On error, it will return a usable, but invalid SourcePath, and report a ModuleError.
1004func PathForSource(ctx PathContext, pathComponents ...string) SourcePath {
1005 path, err := pathForSource(ctx, pathComponents...)
1006 if err != nil {
1007 reportPathError(ctx, err)
1008 }
1009
Colin Crosse3924e12018-08-15 20:18:53 -07001010 if pathtools.IsGlob(path.String()) {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001011 ReportPathErrorf(ctx, "path may not contain a glob: %s", path.String())
Colin Crosse3924e12018-08-15 20:18:53 -07001012 }
1013
Liz Kammera830f3a2020-11-10 10:50:34 -08001014 if modCtx, ok := ctx.(ModuleMissingDepsPathContext); ok && ctx.Config().AllowMissingDependencies() {
Colin Cross192e97a2018-02-22 14:21:02 -08001015 exists, err := existsWithDependencies(ctx, path)
1016 if err != nil {
1017 reportPathError(ctx, err)
1018 }
1019 if !exists {
1020 modCtx.AddMissingDependencies([]string{path.String()})
1021 }
Colin Cross988414c2020-01-11 01:11:46 +00001022 } else if exists, _, err := ctx.Config().fs.Exists(path.String()); err != nil {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001023 ReportPathErrorf(ctx, "%s: %s", path, err.Error())
Colin Cross5e6a7972020-06-07 16:56:32 -07001024 } else if !exists && !ctx.Config().testAllowNonExistentPaths {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001025 ReportPathErrorf(ctx, "source path %q does not exist", path)
Colin Cross192e97a2018-02-22 14:21:02 -08001026 }
1027 return path
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001028}
1029
Jeff Gaston734e3802017-04-10 15:47:24 -07001030// ExistentPathForSource returns an OptionalPath with the SourcePath if the
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001031// path exists, or an empty OptionalPath if it doesn't exist. Dependencies are added
1032// so that the ninja file will be regenerated if the state of the path changes.
Colin Cross32f38982018-02-22 11:47:25 -08001033func ExistentPathForSource(ctx PathContext, pathComponents ...string) OptionalPath {
Colin Cross192e97a2018-02-22 14:21:02 -08001034 path, err := pathForSource(ctx, pathComponents...)
Colin Cross1ccfcc32018-02-22 13:54:26 -08001035 if err != nil {
1036 reportPathError(ctx, err)
1037 return OptionalPath{}
1038 }
Colin Crossc48c1432018-02-23 07:09:01 +00001039
Colin Crosse3924e12018-08-15 20:18:53 -07001040 if pathtools.IsGlob(path.String()) {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001041 ReportPathErrorf(ctx, "path may not contain a glob: %s", path.String())
Colin Crosse3924e12018-08-15 20:18:53 -07001042 return OptionalPath{}
1043 }
1044
Colin Cross192e97a2018-02-22 14:21:02 -08001045 exists, err := existsWithDependencies(ctx, path)
Colin Crossc48c1432018-02-23 07:09:01 +00001046 if err != nil {
1047 reportPathError(ctx, err)
1048 return OptionalPath{}
1049 }
Colin Cross192e97a2018-02-22 14:21:02 -08001050 if !exists {
Colin Crossc48c1432018-02-23 07:09:01 +00001051 return OptionalPath{}
1052 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001053 return OptionalPathForPath(path)
1054}
1055
1056func (p SourcePath) String() string {
1057 return filepath.Join(p.config.srcDir, p.path)
1058}
1059
1060// Join creates a new SourcePath with paths... joined with the current path. The
1061// provided paths... may not use '..' to escape from the current path.
1062func (p SourcePath) Join(ctx PathContext, paths ...string) SourcePath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001063 path, err := validatePath(paths...)
1064 if err != nil {
1065 reportPathError(ctx, err)
1066 }
Colin Cross0db55682017-12-05 15:36:55 -08001067 return p.withRel(path)
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001068}
1069
Colin Cross2fafa3e2019-03-05 12:39:51 -08001070// join is like Join but does less path validation.
1071func (p SourcePath) join(ctx PathContext, paths ...string) SourcePath {
1072 path, err := validateSafePath(paths...)
1073 if err != nil {
1074 reportPathError(ctx, err)
1075 }
1076 return p.withRel(path)
1077}
1078
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001079// OverlayPath returns the overlay for `path' if it exists. This assumes that the
1080// SourcePath is the path to a resource overlay directory.
Liz Kammera830f3a2020-11-10 10:50:34 -08001081func (p SourcePath) OverlayPath(ctx ModuleMissingDepsPathContext, path Path) OptionalPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001082 var relDir string
Colin Cross07e51612019-03-05 12:46:40 -08001083 if srcPath, ok := path.(SourcePath); ok {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001084 relDir = srcPath.path
1085 } else {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001086 ReportPathErrorf(ctx, "Cannot find relative path for %s(%s)", reflect.TypeOf(path).Name(), path)
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001087 return OptionalPath{}
1088 }
1089 dir := filepath.Join(p.config.srcDir, p.path, relDir)
1090 // Use Glob so that we are run again if the directory is added.
Colin Cross7f19f372016-11-01 11:10:25 -07001091 if pathtools.IsGlob(dir) {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001092 ReportPathErrorf(ctx, "Path may not contain a glob: %s", dir)
Dan Willemsen7b310ee2015-12-18 15:11:17 -08001093 }
Colin Cross461b4452018-02-23 09:22:42 -08001094 paths, err := ctx.GlobWithDeps(dir, nil)
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001095 if err != nil {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001096 ReportPathErrorf(ctx, "glob: %s", err.Error())
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001097 return OptionalPath{}
1098 }
1099 if len(paths) == 0 {
1100 return OptionalPath{}
1101 }
Colin Cross43f08db2018-11-12 10:13:39 -08001102 relPath := Rel(ctx, p.config.srcDir, paths[0])
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001103 return OptionalPathForPath(PathForSource(ctx, relPath))
1104}
1105
Colin Cross70dda7e2019-10-01 22:05:35 -07001106// OutputPath is a Path representing an intermediates file path rooted from the build directory
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001107type OutputPath struct {
1108 basePath
Colin Crossd63c9a72020-01-29 16:52:50 -08001109 fullPath string
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001110}
1111
Colin Cross702e0f82017-10-18 17:27:54 -07001112func (p OutputPath) withRel(rel string) OutputPath {
Colin Cross0db55682017-12-05 15:36:55 -08001113 p.basePath = p.basePath.withRel(rel)
Colin Crossd63c9a72020-01-29 16:52:50 -08001114 p.fullPath = filepath.Join(p.fullPath, rel)
Colin Cross702e0f82017-10-18 17:27:54 -07001115 return p
1116}
1117
Colin Cross3063b782018-08-15 11:19:12 -07001118func (p OutputPath) WithoutRel() OutputPath {
1119 p.basePath.rel = filepath.Base(p.basePath.path)
1120 return p
1121}
1122
Paul Duffin9b478b02019-12-10 13:41:51 +00001123func (p OutputPath) buildDir() string {
1124 return p.config.buildDir
1125}
1126
Paul Duffin0267d492021-02-02 10:05:52 +00001127func (p OutputPath) objPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleObjPath {
1128 return PathForModuleObj(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
1129}
1130
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001131var _ Path = OutputPath{}
Paul Duffin9b478b02019-12-10 13:41:51 +00001132var _ WritablePath = OutputPath{}
Paul Duffin0267d492021-02-02 10:05:52 +00001133var _ objPathProvider = OutputPath{}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001134
Chris Parsons8f232a22020-06-23 17:37:05 -04001135// toolDepPath is a Path representing a dependency of the build tool.
1136type toolDepPath struct {
1137 basePath
1138}
1139
1140var _ Path = toolDepPath{}
1141
1142// pathForBuildToolDep returns a toolDepPath representing the given path string.
1143// There is no validation for the path, as it is "trusted": It may fail
1144// normal validation checks. For example, it may be an absolute path.
1145// Only use this function to construct paths for dependencies of the build
1146// tool invocation.
1147func pathForBuildToolDep(ctx PathContext, path string) toolDepPath {
1148 return toolDepPath{basePath{path, ctx.Config(), ""}}
1149}
1150
Jeff Gaston734e3802017-04-10 15:47:24 -07001151// PathForOutput joins the provided paths and returns an OutputPath that is
1152// validated to not escape the build dir.
1153// On error, it will return a usable, but invalid OutputPath, and report a ModuleError.
1154func PathForOutput(ctx PathContext, pathComponents ...string) OutputPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001155 path, err := validatePath(pathComponents...)
1156 if err != nil {
1157 reportPathError(ctx, err)
1158 }
Colin Crossd63c9a72020-01-29 16:52:50 -08001159 fullPath := filepath.Join(ctx.Config().buildDir, path)
1160 path = fullPath[len(fullPath)-len(path):]
1161 return OutputPath{basePath{path, ctx.Config(), ""}, fullPath}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001162}
1163
Colin Cross40e33732019-02-15 11:08:35 -08001164// PathsForOutput returns Paths rooted from buildDir
1165func PathsForOutput(ctx PathContext, paths []string) WritablePaths {
1166 ret := make(WritablePaths, len(paths))
1167 for i, path := range paths {
1168 ret[i] = PathForOutput(ctx, path)
1169 }
1170 return ret
1171}
1172
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001173func (p OutputPath) writablePath() {}
1174
1175func (p OutputPath) String() string {
Colin Crossd63c9a72020-01-29 16:52:50 -08001176 return p.fullPath
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001177}
1178
1179// Join creates a new OutputPath with paths... joined with the current path. The
1180// provided paths... may not use '..' to escape from the current path.
1181func (p OutputPath) Join(ctx PathContext, paths ...string) OutputPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001182 path, err := validatePath(paths...)
1183 if err != nil {
1184 reportPathError(ctx, err)
1185 }
Colin Cross0db55682017-12-05 15:36:55 -08001186 return p.withRel(path)
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001187}
1188
Colin Cross8854a5a2019-02-11 14:14:16 -08001189// ReplaceExtension creates a new OutputPath with the extension replaced with ext.
1190func (p OutputPath) ReplaceExtension(ctx PathContext, ext string) OutputPath {
1191 if strings.Contains(ext, "/") {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001192 ReportPathErrorf(ctx, "extension %q cannot contain /", ext)
Colin Cross8854a5a2019-02-11 14:14:16 -08001193 }
1194 ret := PathForOutput(ctx, pathtools.ReplaceExtension(p.path, ext))
Colin Cross2cdd5df2019-02-25 10:25:24 -08001195 ret.rel = pathtools.ReplaceExtension(p.rel, ext)
Colin Cross8854a5a2019-02-11 14:14:16 -08001196 return ret
1197}
1198
Colin Cross40e33732019-02-15 11:08:35 -08001199// InSameDir creates a new OutputPath from the directory of the current OutputPath joined with the elements in paths.
1200func (p OutputPath) InSameDir(ctx PathContext, paths ...string) OutputPath {
1201 path, err := validatePath(paths...)
1202 if err != nil {
1203 reportPathError(ctx, err)
1204 }
1205
1206 ret := PathForOutput(ctx, filepath.Dir(p.path), path)
Colin Cross2cdd5df2019-02-25 10:25:24 -08001207 ret.rel = filepath.Join(filepath.Dir(p.rel), path)
Colin Cross40e33732019-02-15 11:08:35 -08001208 return ret
1209}
1210
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001211// PathForIntermediates returns an OutputPath representing the top-level
1212// intermediates directory.
1213func PathForIntermediates(ctx PathContext, paths ...string) OutputPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001214 path, err := validatePath(paths...)
1215 if err != nil {
1216 reportPathError(ctx, err)
1217 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001218 return PathForOutput(ctx, ".intermediates", path)
1219}
1220
Colin Cross07e51612019-03-05 12:46:40 -08001221var _ genPathProvider = SourcePath{}
1222var _ objPathProvider = SourcePath{}
1223var _ resPathProvider = SourcePath{}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001224
Colin Cross07e51612019-03-05 12:46:40 -08001225// PathForModuleSrc returns a Path representing the paths... under the
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001226// module's local source directory.
Liz Kammera830f3a2020-11-10 10:50:34 -08001227func PathForModuleSrc(ctx ModuleMissingDepsPathContext, pathComponents ...string) Path {
Colin Cross8a497952019-03-05 22:25:09 -08001228 p, err := validatePath(pathComponents...)
1229 if err != nil {
1230 reportPathError(ctx, err)
Colin Cross192e97a2018-02-22 14:21:02 -08001231 }
Colin Cross8a497952019-03-05 22:25:09 -08001232 paths, err := expandOneSrcPath(ctx, p, nil)
1233 if err != nil {
1234 if depErr, ok := err.(missingDependencyError); ok {
1235 if ctx.Config().AllowMissingDependencies() {
1236 ctx.AddMissingDependencies(depErr.missingDeps)
1237 } else {
1238 ctx.ModuleErrorf(`%s, is the property annotated with android:"path"?`, depErr.Error())
1239 }
1240 } else {
1241 reportPathError(ctx, err)
1242 }
1243 return nil
1244 } else if len(paths) == 0 {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001245 ReportPathErrorf(ctx, "%q produced no files, expected exactly one", p)
Colin Cross8a497952019-03-05 22:25:09 -08001246 return nil
1247 } else if len(paths) > 1 {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001248 ReportPathErrorf(ctx, "%q produced %d files, expected exactly one", p, len(paths))
Colin Cross8a497952019-03-05 22:25:09 -08001249 }
1250 return paths[0]
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001251}
1252
Liz Kammera830f3a2020-11-10 10:50:34 -08001253func pathForModuleSrc(ctx EarlyModulePathContext, paths ...string) SourcePath {
Colin Cross07e51612019-03-05 12:46:40 -08001254 p, err := validatePath(paths...)
1255 if err != nil {
1256 reportPathError(ctx, err)
1257 }
1258
1259 path, err := pathForSource(ctx, ctx.ModuleDir(), p)
1260 if err != nil {
1261 reportPathError(ctx, err)
1262 }
1263
1264 path.basePath.rel = p
1265
1266 return path
1267}
1268
Colin Cross2fafa3e2019-03-05 12:39:51 -08001269// PathsWithModuleSrcSubDir takes a list of Paths and returns a new list of Paths where Rel() on each path
1270// will return the path relative to subDir in the module's source directory. If any input paths are not located
1271// inside subDir then a path error will be reported.
Liz Kammera830f3a2020-11-10 10:50:34 -08001272func PathsWithModuleSrcSubDir(ctx EarlyModulePathContext, paths Paths, subDir string) Paths {
Colin Cross2fafa3e2019-03-05 12:39:51 -08001273 paths = append(Paths(nil), paths...)
Colin Cross07e51612019-03-05 12:46:40 -08001274 subDirFullPath := pathForModuleSrc(ctx, subDir)
Colin Cross2fafa3e2019-03-05 12:39:51 -08001275 for i, path := range paths {
1276 rel := Rel(ctx, subDirFullPath.String(), path.String())
1277 paths[i] = subDirFullPath.join(ctx, rel)
1278 }
1279 return paths
1280}
1281
1282// PathWithModuleSrcSubDir takes a Path and returns a Path where Rel() will return the path relative to subDir in the
1283// 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 -08001284func PathWithModuleSrcSubDir(ctx EarlyModulePathContext, path Path, subDir string) Path {
Colin Cross07e51612019-03-05 12:46:40 -08001285 subDirFullPath := pathForModuleSrc(ctx, subDir)
Colin Cross2fafa3e2019-03-05 12:39:51 -08001286 rel := Rel(ctx, subDirFullPath.String(), path.String())
1287 return subDirFullPath.Join(ctx, rel)
1288}
1289
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001290// OptionalPathForModuleSrc returns an OptionalPath. The OptionalPath contains a
1291// valid path if p is non-nil.
Liz Kammera830f3a2020-11-10 10:50:34 -08001292func OptionalPathForModuleSrc(ctx ModuleMissingDepsPathContext, p *string) OptionalPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001293 if p == nil {
1294 return OptionalPath{}
1295 }
1296 return OptionalPathForPath(PathForModuleSrc(ctx, *p))
1297}
1298
Liz Kammera830f3a2020-11-10 10:50:34 -08001299func (p SourcePath) genPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleGenPath {
Colin Cross7fc17db2017-02-01 14:07:55 -08001300 return PathForModuleGen(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001301}
1302
Liz Kammera830f3a2020-11-10 10:50:34 -08001303func (p SourcePath) objPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleObjPath {
Colin Cross7fc17db2017-02-01 14:07:55 -08001304 return PathForModuleObj(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001305}
1306
Liz Kammera830f3a2020-11-10 10:50:34 -08001307func (p SourcePath) resPathWithName(ctx ModuleOutPathContext, name string) ModuleResPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001308 // TODO: Use full directory if the new ctx is not the current ctx?
1309 return PathForModuleRes(ctx, p.path, name)
1310}
1311
1312// ModuleOutPath is a Path representing a module's output directory.
1313type ModuleOutPath struct {
1314 OutputPath
1315}
1316
1317var _ Path = ModuleOutPath{}
1318
Liz Kammera830f3a2020-11-10 10:50:34 -08001319func (p ModuleOutPath) objPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleObjPath {
Pete Bentleyfcf55bf2019-08-16 20:14:32 +01001320 return PathForModuleObj(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
1321}
1322
Liz Kammera830f3a2020-11-10 10:50:34 -08001323// ModuleOutPathContext Subset of ModuleContext functions necessary for output path methods.
1324type ModuleOutPathContext interface {
1325 PathContext
1326
1327 ModuleName() string
1328 ModuleDir() string
1329 ModuleSubDir() string
1330}
1331
1332func pathForModuleOut(ctx ModuleOutPathContext) OutputPath {
Colin Cross702e0f82017-10-18 17:27:54 -07001333 return PathForOutput(ctx, ".intermediates", ctx.ModuleDir(), ctx.ModuleName(), ctx.ModuleSubDir())
1334}
1335
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001336type BazelOutPath struct {
1337 OutputPath
1338}
1339
1340var _ Path = BazelOutPath{}
1341var _ objPathProvider = BazelOutPath{}
1342
Liz Kammera830f3a2020-11-10 10:50:34 -08001343func (p BazelOutPath) objPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleObjPath {
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001344 return PathForModuleObj(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
1345}
1346
Logan Chien7eefdc42018-07-11 18:10:41 +08001347// PathForVndkRefAbiDump returns an OptionalPath representing the path of the
1348// reference abi dump for the given module. This is not guaranteed to be valid.
Liz Kammera830f3a2020-11-10 10:50:34 -08001349func PathForVndkRefAbiDump(ctx ModuleInstallPathContext, version, fileName string,
Hsin-Yi Chen53489642019-07-31 17:10:45 +08001350 isNdk, isLlndkOrVndk, isGzip bool) OptionalPath {
Logan Chien7eefdc42018-07-11 18:10:41 +08001351
Jayant Chowdharyac066c62018-02-20 10:53:31 -08001352 arches := ctx.DeviceConfig().Arches()
Logan Chien7eefdc42018-07-11 18:10:41 +08001353 if len(arches) == 0 {
1354 panic("device build with no primary arch")
1355 }
Jayant Chowdharyac066c62018-02-20 10:53:31 -08001356 currentArch := ctx.Arch()
1357 archNameAndVariant := currentArch.ArchType.String()
1358 if currentArch.ArchVariant != "" {
1359 archNameAndVariant += "_" + currentArch.ArchVariant
1360 }
Logan Chien5237bed2018-07-11 17:15:57 +08001361
1362 var dirName string
Hsin-Yi Chen53489642019-07-31 17:10:45 +08001363 if isNdk {
Logan Chien5237bed2018-07-11 17:15:57 +08001364 dirName = "ndk"
Hsin-Yi Chen53489642019-07-31 17:10:45 +08001365 } else if isLlndkOrVndk {
Logan Chien5237bed2018-07-11 17:15:57 +08001366 dirName = "vndk"
Logan Chien41eabe62019-04-10 13:33:58 +08001367 } else {
1368 dirName = "platform" // opt-in libs
Jayant Chowdhary3e231fd2017-02-08 13:45:53 -08001369 }
Logan Chien5237bed2018-07-11 17:15:57 +08001370
Jayant Chowdhary34ce67d2018-03-08 11:00:50 -08001371 binderBitness := ctx.DeviceConfig().BinderBitness()
Logan Chien7eefdc42018-07-11 18:10:41 +08001372
1373 var ext string
1374 if isGzip {
1375 ext = ".lsdump.gz"
1376 } else {
1377 ext = ".lsdump"
1378 }
1379
1380 return ExistentPathForSource(ctx, "prebuilts", "abi-dumps", dirName,
1381 version, binderBitness, archNameAndVariant, "source-based",
1382 fileName+ext)
Jayant Chowdhary3e231fd2017-02-08 13:45:53 -08001383}
1384
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001385// PathForBazelOut returns a Path representing the paths... under an output directory dedicated to
1386// bazel-owned outputs.
1387func PathForBazelOut(ctx PathContext, paths ...string) BazelOutPath {
1388 execRootPathComponents := append([]string{"execroot", "__main__"}, paths...)
1389 execRootPath := filepath.Join(execRootPathComponents...)
1390 validatedExecRootPath, err := validatePath(execRootPath)
1391 if err != nil {
1392 reportPathError(ctx, err)
1393 }
1394
1395 outputPath := OutputPath{basePath{"", ctx.Config(), ""},
1396 ctx.Config().BazelContext.OutputBase()}
1397
1398 return BazelOutPath{
1399 OutputPath: outputPath.withRel(validatedExecRootPath),
1400 }
1401}
1402
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001403// PathForModuleOut returns a Path representing the paths... under the module's
1404// output directory.
Liz Kammera830f3a2020-11-10 10:50:34 -08001405func PathForModuleOut(ctx ModuleOutPathContext, paths ...string) ModuleOutPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001406 p, err := validatePath(paths...)
1407 if err != nil {
1408 reportPathError(ctx, err)
1409 }
Colin Cross702e0f82017-10-18 17:27:54 -07001410 return ModuleOutPath{
Liz Kammera830f3a2020-11-10 10:50:34 -08001411 OutputPath: pathForModuleOut(ctx).withRel(p),
Colin Cross702e0f82017-10-18 17:27:54 -07001412 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001413}
1414
1415// ModuleGenPath is a Path representing the 'gen' directory in a module's output
1416// directory. Mainly used for generated sources.
1417type ModuleGenPath struct {
1418 ModuleOutPath
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001419}
1420
1421var _ Path = ModuleGenPath{}
1422var _ genPathProvider = ModuleGenPath{}
1423var _ objPathProvider = ModuleGenPath{}
1424
1425// PathForModuleGen returns a Path representing the paths... under the module's
1426// `gen' directory.
Liz Kammera830f3a2020-11-10 10:50:34 -08001427func PathForModuleGen(ctx ModuleOutPathContext, paths ...string) ModuleGenPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001428 p, err := validatePath(paths...)
1429 if err != nil {
1430 reportPathError(ctx, err)
1431 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001432 return ModuleGenPath{
Colin Cross702e0f82017-10-18 17:27:54 -07001433 ModuleOutPath: ModuleOutPath{
Liz Kammera830f3a2020-11-10 10:50:34 -08001434 OutputPath: pathForModuleOut(ctx).withRel("gen").withRel(p),
Colin Cross702e0f82017-10-18 17:27:54 -07001435 },
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001436 }
1437}
1438
Liz Kammera830f3a2020-11-10 10:50:34 -08001439func (p ModuleGenPath) genPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleGenPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001440 // TODO: make a different path for local vs remote generated files?
Dan Willemsen21ec4902016-11-02 20:43:13 -07001441 return PathForModuleGen(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001442}
1443
Liz Kammera830f3a2020-11-10 10:50:34 -08001444func (p ModuleGenPath) objPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleObjPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001445 return PathForModuleObj(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
1446}
1447
1448// ModuleObjPath is a Path representing the 'obj' directory in a module's output
1449// directory. Used for compiled objects.
1450type ModuleObjPath struct {
1451 ModuleOutPath
1452}
1453
1454var _ Path = ModuleObjPath{}
1455
1456// PathForModuleObj returns a Path representing the paths... under the module's
1457// 'obj' directory.
Liz Kammera830f3a2020-11-10 10:50:34 -08001458func PathForModuleObj(ctx ModuleOutPathContext, pathComponents ...string) ModuleObjPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001459 p, err := validatePath(pathComponents...)
1460 if err != nil {
1461 reportPathError(ctx, err)
1462 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001463 return ModuleObjPath{PathForModuleOut(ctx, "obj", p)}
1464}
1465
1466// ModuleResPath is a a Path representing the 'res' directory in a module's
1467// output directory.
1468type ModuleResPath struct {
1469 ModuleOutPath
1470}
1471
1472var _ Path = ModuleResPath{}
1473
1474// PathForModuleRes returns a Path representing the paths... under the module's
1475// 'res' directory.
Liz Kammera830f3a2020-11-10 10:50:34 -08001476func PathForModuleRes(ctx ModuleOutPathContext, pathComponents ...string) ModuleResPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001477 p, err := validatePath(pathComponents...)
1478 if err != nil {
1479 reportPathError(ctx, err)
1480 }
1481
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001482 return ModuleResPath{PathForModuleOut(ctx, "res", p)}
1483}
1484
Colin Cross70dda7e2019-10-01 22:05:35 -07001485// InstallPath is a Path representing a installed file path rooted from the build directory
1486type InstallPath struct {
1487 basePath
Colin Crossff6c33d2019-10-02 16:01:35 -07001488
Jiyong Park957bcd92020-10-20 18:23:33 +09001489 // partitionDir is the part of the InstallPath that is automatically determined according to the context.
1490 // For example, it is host/<os>-<arch> for host modules, and target/product/<device>/<partition> for device modules.
1491 partitionDir string
1492
1493 // makePath indicates whether this path is for Soong (false) or Make (true).
1494 makePath bool
Colin Cross70dda7e2019-10-01 22:05:35 -07001495}
1496
Paul Duffin9b478b02019-12-10 13:41:51 +00001497func (p InstallPath) buildDir() string {
1498 return p.config.buildDir
1499}
1500
Hans MÃ¥nssond3f2bd72020-11-27 12:37:28 +01001501func (p InstallPath) ReplaceExtension(ctx PathContext, ext string) OutputPath {
1502 panic("Not implemented")
1503}
1504
Paul Duffin9b478b02019-12-10 13:41:51 +00001505var _ Path = InstallPath{}
1506var _ WritablePath = InstallPath{}
1507
Colin Cross70dda7e2019-10-01 22:05:35 -07001508func (p InstallPath) writablePath() {}
1509
1510func (p InstallPath) String() string {
Jiyong Park957bcd92020-10-20 18:23:33 +09001511 if p.makePath {
1512 // Make path starts with out/ instead of out/soong.
1513 return filepath.Join(p.config.buildDir, "../", p.path)
1514 } else {
1515 return filepath.Join(p.config.buildDir, p.path)
1516 }
1517}
1518
1519// PartitionDir returns the path to the partition where the install path is rooted at. It is
1520// out/soong/target/product/<device>/<partition> for device modules, and out/soong/host/<os>-<arch> for host modules.
1521// The ./soong is dropped if the install path is for Make.
1522func (p InstallPath) PartitionDir() string {
1523 if p.makePath {
1524 return filepath.Join(p.config.buildDir, "../", p.partitionDir)
1525 } else {
1526 return filepath.Join(p.config.buildDir, p.partitionDir)
1527 }
Colin Cross70dda7e2019-10-01 22:05:35 -07001528}
1529
1530// Join creates a new InstallPath with paths... joined with the current path. The
1531// provided paths... may not use '..' to escape from the current path.
1532func (p InstallPath) Join(ctx PathContext, paths ...string) InstallPath {
1533 path, err := validatePath(paths...)
1534 if err != nil {
1535 reportPathError(ctx, err)
1536 }
1537 return p.withRel(path)
1538}
1539
1540func (p InstallPath) withRel(rel string) InstallPath {
1541 p.basePath = p.basePath.withRel(rel)
1542 return p
1543}
1544
Colin Crossff6c33d2019-10-02 16:01:35 -07001545// ToMakePath returns a new InstallPath that points to Make's install directory instead of Soong's,
1546// i.e. out/ instead of out/soong/.
1547func (p InstallPath) ToMakePath() InstallPath {
Jiyong Park957bcd92020-10-20 18:23:33 +09001548 p.makePath = true
Colin Crossff6c33d2019-10-02 16:01:35 -07001549 return p
Colin Cross70dda7e2019-10-01 22:05:35 -07001550}
1551
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001552// PathForModuleInstall returns a Path representing the install path for the
1553// module appended with paths...
Colin Cross70dda7e2019-10-01 22:05:35 -07001554func PathForModuleInstall(ctx ModuleInstallPathContext, pathComponents ...string) InstallPath {
Colin Cross6e359402020-02-10 15:29:54 -08001555 os := ctx.Os()
Jiyong Park87788b52020-09-01 12:37:45 +09001556 arch := ctx.Arch().ArchType
1557 forceOS, forceArch := ctx.InstallForceOS()
1558 if forceOS != nil {
Colin Cross6e359402020-02-10 15:29:54 -08001559 os = *forceOS
1560 }
Jiyong Park87788b52020-09-01 12:37:45 +09001561 if forceArch != nil {
1562 arch = *forceArch
1563 }
Colin Cross6e359402020-02-10 15:29:54 -08001564 partition := modulePartition(ctx, os)
Colin Cross609c49a2020-02-13 13:20:11 -08001565
Jiyong Park87788b52020-09-01 12:37:45 +09001566 ret := pathForInstall(ctx, os, arch, partition, ctx.Debug(), pathComponents...)
Colin Cross609c49a2020-02-13 13:20:11 -08001567
Jingwen Chencda22c92020-11-23 00:22:30 -05001568 if ctx.InstallBypassMake() && ctx.Config().KatiEnabled() {
Colin Cross609c49a2020-02-13 13:20:11 -08001569 ret = ret.ToMakePath()
1570 }
1571
1572 return ret
1573}
1574
Jiyong Park87788b52020-09-01 12:37:45 +09001575func pathForInstall(ctx PathContext, os OsType, arch ArchType, partition string, debug bool,
Colin Cross609c49a2020-02-13 13:20:11 -08001576 pathComponents ...string) InstallPath {
1577
Jiyong Park957bcd92020-10-20 18:23:33 +09001578 var partionPaths []string
Colin Cross609c49a2020-02-13 13:20:11 -08001579
Colin Cross6e359402020-02-10 15:29:54 -08001580 if os.Class == Device {
Jiyong Park957bcd92020-10-20 18:23:33 +09001581 partionPaths = []string{"target", "product", ctx.Config().DeviceName(), partition}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001582 } else {
Jiyong Park87788b52020-09-01 12:37:45 +09001583 osName := os.String()
1584 if os == Linux {
1585 // instead of linux_glibc
1586 osName = "linux"
Dan Willemsen866b5632017-09-22 12:28:24 -07001587 }
Jiyong Park87788b52020-09-01 12:37:45 +09001588 // SOONG_HOST_OUT is set to out/host/$(HOST_OS)-$(HOST_PREBUILT_ARCH)
1589 // and HOST_PREBUILT_ARCH is forcibly set to x86 even on x86_64 hosts. We don't seem
1590 // to have a plan to fix it (see the comment in build/make/core/envsetup.mk).
1591 // Let's keep using x86 for the existing cases until we have a need to support
1592 // other architectures.
1593 archName := arch.String()
1594 if os.Class == Host && (arch == X86_64 || arch == Common) {
1595 archName = "x86"
1596 }
Jiyong Park957bcd92020-10-20 18:23:33 +09001597 partionPaths = []string{"host", osName + "-" + archName, partition}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001598 }
Colin Cross609c49a2020-02-13 13:20:11 -08001599 if debug {
Jiyong Park957bcd92020-10-20 18:23:33 +09001600 partionPaths = append([]string{"debug"}, partionPaths...)
Dan Willemsen782a2d12015-12-21 14:55:28 -08001601 }
Colin Cross70dda7e2019-10-01 22:05:35 -07001602
Jiyong Park957bcd92020-10-20 18:23:33 +09001603 partionPath, err := validatePath(partionPaths...)
Colin Cross70dda7e2019-10-01 22:05:35 -07001604 if err != nil {
1605 reportPathError(ctx, err)
1606 }
Colin Crossff6c33d2019-10-02 16:01:35 -07001607
Jiyong Park957bcd92020-10-20 18:23:33 +09001608 base := InstallPath{
1609 basePath: basePath{partionPath, ctx.Config(), ""},
1610 partitionDir: partionPath,
1611 makePath: false,
1612 }
Colin Crossff6c33d2019-10-02 16:01:35 -07001613
Jiyong Park957bcd92020-10-20 18:23:33 +09001614 return base.Join(ctx, pathComponents...)
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001615}
1616
Nicolas Geoffray1228e9c2020-02-27 13:45:35 +00001617func pathForNdkOrSdkInstall(ctx PathContext, prefix string, paths []string) InstallPath {
Jiyong Park957bcd92020-10-20 18:23:33 +09001618 base := InstallPath{
1619 basePath: basePath{prefix, ctx.Config(), ""},
1620 partitionDir: prefix,
1621 makePath: false,
Colin Cross70dda7e2019-10-01 22:05:35 -07001622 }
Jiyong Park957bcd92020-10-20 18:23:33 +09001623 return base.Join(ctx, paths...)
Colin Cross70dda7e2019-10-01 22:05:35 -07001624}
1625
Nicolas Geoffray1228e9c2020-02-27 13:45:35 +00001626func PathForNdkInstall(ctx PathContext, paths ...string) InstallPath {
1627 return pathForNdkOrSdkInstall(ctx, "ndk", paths)
1628}
1629
1630func PathForMainlineSdksInstall(ctx PathContext, paths ...string) InstallPath {
1631 return pathForNdkOrSdkInstall(ctx, "mainline-sdks", paths)
1632}
1633
Colin Cross70dda7e2019-10-01 22:05:35 -07001634func InstallPathToOnDevicePath(ctx PathContext, path InstallPath) string {
Colin Cross43f08db2018-11-12 10:13:39 -08001635 rel := Rel(ctx, PathForOutput(ctx, "target", "product", ctx.Config().DeviceName()).String(), path.String())
1636
1637 return "/" + rel
1638}
1639
Colin Cross6e359402020-02-10 15:29:54 -08001640func modulePartition(ctx ModuleInstallPathContext, os OsType) string {
Colin Cross43f08db2018-11-12 10:13:39 -08001641 var partition string
Colin Cross6e359402020-02-10 15:29:54 -08001642 if ctx.InstallInTestcases() {
1643 // "testcases" install directory can be used for host or device modules.
Jaewoong Jung0949f312019-09-11 10:25:18 -07001644 partition = "testcases"
Colin Cross6e359402020-02-10 15:29:54 -08001645 } else if os.Class == Device {
1646 if ctx.InstallInData() {
1647 partition = "data"
1648 } else if ctx.InstallInRamdisk() {
1649 if ctx.DeviceConfig().BoardUsesRecoveryAsBoot() {
1650 partition = "recovery/root/first_stage_ramdisk"
1651 } else {
1652 partition = "ramdisk"
1653 }
1654 if !ctx.InstallInRoot() {
1655 partition += "/system"
1656 }
Yifan Hong60e0cfb2020-10-21 15:17:56 -07001657 } else if ctx.InstallInVendorRamdisk() {
Yifan Hong39143a92020-10-26 12:43:12 -07001658 // The module is only available after switching root into
1659 // /first_stage_ramdisk. To expose the module before switching root
1660 // on a device without a dedicated recovery partition, install the
1661 // recovery variant.
Yifan Hongdd8dacc2020-10-21 15:40:17 -07001662 if ctx.DeviceConfig().BoardMoveRecoveryResourcesToVendorBoot() {
Yifan Hong39143a92020-10-26 12:43:12 -07001663 partition = "vendor-ramdisk/first_stage_ramdisk"
Yifan Hongdd8dacc2020-10-21 15:40:17 -07001664 } else {
1665 partition = "vendor-ramdisk"
1666 }
1667 if !ctx.InstallInRoot() {
1668 partition += "/system"
1669 }
Colin Cross6e359402020-02-10 15:29:54 -08001670 } else if ctx.InstallInRecovery() {
1671 if ctx.InstallInRoot() {
1672 partition = "recovery/root"
1673 } else {
1674 // the layout of recovery partion is the same as that of system partition
1675 partition = "recovery/root/system"
1676 }
1677 } else if ctx.SocSpecific() {
1678 partition = ctx.DeviceConfig().VendorPath()
1679 } else if ctx.DeviceSpecific() {
1680 partition = ctx.DeviceConfig().OdmPath()
1681 } else if ctx.ProductSpecific() {
1682 partition = ctx.DeviceConfig().ProductPath()
1683 } else if ctx.SystemExtSpecific() {
1684 partition = ctx.DeviceConfig().SystemExtPath()
1685 } else if ctx.InstallInRoot() {
1686 partition = "root"
Yifan Hong82db7352020-01-21 16:12:26 -08001687 } else {
Colin Cross6e359402020-02-10 15:29:54 -08001688 partition = "system"
Yifan Hong82db7352020-01-21 16:12:26 -08001689 }
Colin Cross6e359402020-02-10 15:29:54 -08001690 if ctx.InstallInSanitizerDir() {
1691 partition = "data/asan/" + partition
Yifan Hong82db7352020-01-21 16:12:26 -08001692 }
Colin Cross43f08db2018-11-12 10:13:39 -08001693 }
1694 return partition
1695}
1696
Colin Cross609c49a2020-02-13 13:20:11 -08001697type InstallPaths []InstallPath
1698
1699// Paths returns the InstallPaths as a Paths
1700func (p InstallPaths) Paths() Paths {
1701 if p == nil {
1702 return nil
1703 }
1704 ret := make(Paths, len(p))
1705 for i, path := range p {
1706 ret[i] = path
1707 }
1708 return ret
1709}
1710
1711// Strings returns the string forms of the install paths.
1712func (p InstallPaths) Strings() []string {
1713 if p == nil {
1714 return nil
1715 }
1716 ret := make([]string, len(p))
1717 for i, path := range p {
1718 ret[i] = path.String()
1719 }
1720 return ret
1721}
1722
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001723// validateSafePath validates a path that we trust (may contain ninja variables).
Dan Willemsen80a7c2a2015-12-21 14:57:11 -08001724// Ensures that each path component does not attempt to leave its component.
Colin Cross1ccfcc32018-02-22 13:54:26 -08001725func validateSafePath(pathComponents ...string) (string, error) {
Jeff Gaston734e3802017-04-10 15:47:24 -07001726 for _, path := range pathComponents {
Dan Willemsen80a7c2a2015-12-21 14:57:11 -08001727 path := filepath.Clean(path)
1728 if path == ".." || strings.HasPrefix(path, "../") || strings.HasPrefix(path, "/") {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001729 return "", fmt.Errorf("Path is outside directory: %s", path)
Dan Willemsen80a7c2a2015-12-21 14:57:11 -08001730 }
1731 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001732 // TODO: filepath.Join isn't necessarily correct with embedded ninja
1733 // variables. '..' may remove the entire ninja variable, even if it
1734 // will be expanded to multiple nested directories.
Colin Cross1ccfcc32018-02-22 13:54:26 -08001735 return filepath.Join(pathComponents...), nil
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001736}
1737
Dan Willemsen80a7c2a2015-12-21 14:57:11 -08001738// validatePath validates that a path does not include ninja variables, and that
1739// each path component does not attempt to leave its component. Returns a joined
1740// version of each path component.
Colin Cross1ccfcc32018-02-22 13:54:26 -08001741func validatePath(pathComponents ...string) (string, error) {
Jeff Gaston734e3802017-04-10 15:47:24 -07001742 for _, path := range pathComponents {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001743 if strings.Contains(path, "$") {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001744 return "", fmt.Errorf("Path contains invalid character($): %s", path)
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001745 }
1746 }
Colin Cross1ccfcc32018-02-22 13:54:26 -08001747 return validateSafePath(pathComponents...)
Colin Cross6e18ca42015-07-14 18:55:36 -07001748}
Colin Cross5b529592017-05-09 13:34:34 -07001749
Colin Cross0875c522017-11-28 17:34:01 -08001750func PathForPhony(ctx PathContext, phony string) WritablePath {
1751 if strings.ContainsAny(phony, "$/") {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001752 ReportPathErrorf(ctx, "Phony target contains invalid character ($ or /): %s", phony)
Colin Cross0875c522017-11-28 17:34:01 -08001753 }
Colin Cross74e3fe42017-12-11 15:51:44 -08001754 return PhonyPath{basePath{phony, ctx.Config(), ""}}
Colin Cross0875c522017-11-28 17:34:01 -08001755}
1756
Colin Cross74e3fe42017-12-11 15:51:44 -08001757type PhonyPath struct {
1758 basePath
1759}
1760
1761func (p PhonyPath) writablePath() {}
1762
Paul Duffin9b478b02019-12-10 13:41:51 +00001763func (p PhonyPath) buildDir() string {
1764 return p.config.buildDir
1765}
1766
Hans MÃ¥nssond3f2bd72020-11-27 12:37:28 +01001767func (p PhonyPath) ReplaceExtension(ctx PathContext, ext string) OutputPath {
1768 panic("Not implemented")
1769}
1770
Colin Cross74e3fe42017-12-11 15:51:44 -08001771var _ Path = PhonyPath{}
1772var _ WritablePath = PhonyPath{}
1773
Colin Cross5b529592017-05-09 13:34:34 -07001774type testPath struct {
1775 basePath
1776}
1777
1778func (p testPath) String() string {
1779 return p.path
1780}
1781
Colin Cross40e33732019-02-15 11:08:35 -08001782// PathForTesting returns a Path constructed from joining the elements of paths with '/'. It should only be used from
1783// within tests.
Colin Cross5b529592017-05-09 13:34:34 -07001784func PathForTesting(paths ...string) Path {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001785 p, err := validateSafePath(paths...)
1786 if err != nil {
1787 panic(err)
1788 }
Colin Cross5b529592017-05-09 13:34:34 -07001789 return testPath{basePath{path: p, rel: p}}
1790}
1791
Colin Cross40e33732019-02-15 11:08:35 -08001792// PathsForTesting returns a Path constructed from each element in strs. It should only be used from within tests.
1793func PathsForTesting(strs ...string) Paths {
Colin Cross5b529592017-05-09 13:34:34 -07001794 p := make(Paths, len(strs))
1795 for i, s := range strs {
1796 p[i] = PathForTesting(s)
1797 }
1798
1799 return p
1800}
Colin Cross43f08db2018-11-12 10:13:39 -08001801
Colin Cross40e33732019-02-15 11:08:35 -08001802type testPathContext struct {
1803 config Config
Colin Cross40e33732019-02-15 11:08:35 -08001804}
1805
Colin Cross40e33732019-02-15 11:08:35 -08001806func (x *testPathContext) Config() Config { return x.config }
1807func (x *testPathContext) AddNinjaFileDeps(...string) {}
1808
1809// PathContextForTesting returns a PathContext that can be used in tests, for example to create an OutputPath with
1810// PathForOutput.
Colin Cross98be1bb2019-12-13 20:41:13 -08001811func PathContextForTesting(config Config) PathContext {
Colin Cross40e33732019-02-15 11:08:35 -08001812 return &testPathContext{
1813 config: config,
Colin Cross40e33732019-02-15 11:08:35 -08001814 }
1815}
1816
Ulya Trafimovichccc8c852020-10-14 11:29:07 +01001817type testModuleInstallPathContext struct {
1818 baseModuleContext
1819
1820 inData bool
1821 inTestcases bool
1822 inSanitizerDir bool
1823 inRamdisk bool
1824 inVendorRamdisk bool
1825 inRecovery bool
1826 inRoot bool
1827 forceOS *OsType
1828 forceArch *ArchType
1829}
1830
1831func (m testModuleInstallPathContext) Config() Config {
1832 return m.baseModuleContext.config
1833}
1834
1835func (testModuleInstallPathContext) AddNinjaFileDeps(deps ...string) {}
1836
1837func (m testModuleInstallPathContext) InstallInData() bool {
1838 return m.inData
1839}
1840
1841func (m testModuleInstallPathContext) InstallInTestcases() bool {
1842 return m.inTestcases
1843}
1844
1845func (m testModuleInstallPathContext) InstallInSanitizerDir() bool {
1846 return m.inSanitizerDir
1847}
1848
1849func (m testModuleInstallPathContext) InstallInRamdisk() bool {
1850 return m.inRamdisk
1851}
1852
1853func (m testModuleInstallPathContext) InstallInVendorRamdisk() bool {
1854 return m.inVendorRamdisk
1855}
1856
1857func (m testModuleInstallPathContext) InstallInRecovery() bool {
1858 return m.inRecovery
1859}
1860
1861func (m testModuleInstallPathContext) InstallInRoot() bool {
1862 return m.inRoot
1863}
1864
1865func (m testModuleInstallPathContext) InstallBypassMake() bool {
1866 return false
1867}
1868
1869func (m testModuleInstallPathContext) InstallForceOS() (*OsType, *ArchType) {
1870 return m.forceOS, m.forceArch
1871}
1872
1873// Construct a minimal ModuleInstallPathContext for testing. Note that baseModuleContext is
1874// default-initialized, which leaves blueprint.baseModuleContext set to nil, so methods that are
1875// delegated to it will panic.
1876func ModuleInstallPathContextForTesting(config Config) ModuleInstallPathContext {
1877 ctx := &testModuleInstallPathContext{}
1878 ctx.config = config
1879 ctx.os = Android
1880 return ctx
1881}
1882
Colin Cross43f08db2018-11-12 10:13:39 -08001883// Rel performs the same function as filepath.Rel, but reports errors to a PathContext, and reports an error if
1884// targetPath is not inside basePath.
1885func Rel(ctx PathContext, basePath string, targetPath string) string {
1886 rel, isRel := MaybeRel(ctx, basePath, targetPath)
1887 if !isRel {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001888 ReportPathErrorf(ctx, "path %q is not under path %q", targetPath, basePath)
Colin Cross43f08db2018-11-12 10:13:39 -08001889 return ""
1890 }
1891 return rel
1892}
1893
1894// MaybeRel performs the same function as filepath.Rel, but reports errors to a PathContext, and returns false if
1895// targetPath is not inside basePath.
1896func MaybeRel(ctx PathContext, basePath string, targetPath string) (string, bool) {
Dan Willemsen633c5022019-04-12 11:11:38 -07001897 rel, isRel, err := maybeRelErr(basePath, targetPath)
1898 if err != nil {
1899 reportPathError(ctx, err)
1900 }
1901 return rel, isRel
1902}
1903
1904func maybeRelErr(basePath string, targetPath string) (string, bool, error) {
Colin Cross43f08db2018-11-12 10:13:39 -08001905 // filepath.Rel returns an error if one path is absolute and the other is not, handle that case first.
1906 if filepath.IsAbs(basePath) != filepath.IsAbs(targetPath) {
Dan Willemsen633c5022019-04-12 11:11:38 -07001907 return "", false, nil
Colin Cross43f08db2018-11-12 10:13:39 -08001908 }
1909 rel, err := filepath.Rel(basePath, targetPath)
1910 if err != nil {
Dan Willemsen633c5022019-04-12 11:11:38 -07001911 return "", false, err
Colin Cross43f08db2018-11-12 10:13:39 -08001912 } else if rel == ".." || strings.HasPrefix(rel, "../") || strings.HasPrefix(rel, "/") {
Dan Willemsen633c5022019-04-12 11:11:38 -07001913 return "", false, nil
Colin Cross43f08db2018-11-12 10:13:39 -08001914 }
Dan Willemsen633c5022019-04-12 11:11:38 -07001915 return rel, true, nil
Colin Cross43f08db2018-11-12 10:13:39 -08001916}
Colin Cross988414c2020-01-11 01:11:46 +00001917
1918// Writes a file to the output directory. Attempting to write directly to the output directory
1919// will fail due to the sandbox of the soong_build process.
1920func WriteFileToOutputDir(path WritablePath, data []byte, perm os.FileMode) error {
1921 return ioutil.WriteFile(absolutePath(path.String()), data, perm)
1922}
1923
Liz Kammer2dd9ca42020-11-25 16:06:39 -08001924func RemoveAllOutputDir(path WritablePath) error {
1925 return os.RemoveAll(absolutePath(path.String()))
1926}
1927
1928func CreateOutputDirIfNonexistent(path WritablePath, perm os.FileMode) error {
1929 dir := absolutePath(path.String())
1930 if _, err := os.Stat(dir); os.IsNotExist(err) {
1931 return os.MkdirAll(dir, os.ModePerm)
1932 } else {
1933 return err
1934 }
1935}
1936
Colin Cross988414c2020-01-11 01:11:46 +00001937func absolutePath(path string) string {
1938 if filepath.IsAbs(path) {
1939 return path
1940 }
1941 return filepath.Join(absSrcDir, path)
1942}
Chris Parsons216e10a2020-07-09 17:12:52 -04001943
1944// A DataPath represents the path of a file to be used as data, for example
1945// a test library to be installed alongside a test.
1946// The data file should be installed (copied from `<SrcPath>`) to
1947// `<install_root>/<RelativeInstallPath>/<filename>`, or
1948// `<install_root>/<filename>` if RelativeInstallPath is empty.
1949type DataPath struct {
1950 // The path of the data file that should be copied into the data directory
1951 SrcPath Path
1952 // The install path of the data file, relative to the install root.
1953 RelativeInstallPath string
1954}
Colin Crossdcf71b22021-02-01 13:59:03 -08001955
1956// PathsIfNonNil returns a Paths containing only the non-nil input arguments.
1957func PathsIfNonNil(paths ...Path) Paths {
1958 if len(paths) == 0 {
1959 // Fast path for empty argument list
1960 return nil
1961 } else if len(paths) == 1 {
1962 // Fast path for a single argument
1963 if paths[0] != nil {
1964 return paths
1965 } else {
1966 return nil
1967 }
1968 }
1969 ret := make(Paths, 0, len(paths))
1970 for _, path := range paths {
1971 if path != nil {
1972 ret = append(ret, path)
1973 }
1974 }
1975 if len(ret) == 0 {
1976 return nil
1977 }
1978 return ret
1979}