blob: c3fa61a0981b4857f06983e11d5d035f5255f199 [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 {
398 labels := bazel.LabelList{
399 Includes: []bazel.Label{},
400 }
401 for _, p := range paths {
402 if m, tag := SrcIsModuleWithTag(p); m != "" {
403 l := getOtherModuleLabel(ctx, m, tag)
404 if !InList(l.Label, expandedExcludes) {
405 l.Bp_text = fmt.Sprintf(":%s", m)
406 labels.Includes = append(labels.Includes, l)
407 }
408 } else {
409 var expandedPaths []bazel.Label
410 if pathtools.IsGlob(p) {
411 globbedPaths := GlobFiles(ctx, pathForModuleSrc(ctx, p).String(), expandedExcludes)
412 globbedPaths = PathsWithModuleSrcSubDir(ctx, globbedPaths, "")
413 for _, path := range globbedPaths {
414 s := path.Rel()
415 expandedPaths = append(expandedPaths, bazel.Label{Label: s})
416 }
417 } else {
418 if !InList(p, expandedExcludes) {
419 expandedPaths = append(expandedPaths, bazel.Label{Label: p})
420 }
421 }
422 labels.Includes = append(labels.Includes, expandedPaths...)
423 }
424 }
425 return labels
426}
427
428// getOtherModuleLabel returns a bazel.Label for the given dependency/tag combination for the
429// module. The label will be relative to the current directory if appropriate. The dependency must
430// already be resolved by either deps mutator or path deps mutator.
431func getOtherModuleLabel(ctx BazelConversionPathContext, dep, tag string) bazel.Label {
432 m, _ := ctx.GetDirectDep(dep)
433 // TODO(b/165114590): Convert tag (":name{.tag}") to corresponding Bazel implicit output targets.
434 otherModuleName := ctx.OtherModuleName(m)
435 var label bazel.Label
436 if otherDir, dir := ctx.OtherModuleDir(m), ctx.ModuleDir(); otherDir != dir {
437 label.Label = fmt.Sprintf("//%s:%s", otherDir, otherModuleName)
438 } else {
439 label.Label = fmt.Sprintf(":%s", otherModuleName)
440 }
441 return label
442}
443
Ulya Trafimovich4d2eeed2019-11-08 10:54:21 +0000444// OutputPaths is a slice of OutputPath objects, with helpers to operate on the collection.
445type OutputPaths []OutputPath
446
447// Paths returns the OutputPaths as a Paths
448func (p OutputPaths) Paths() Paths {
449 if p == nil {
450 return nil
451 }
452 ret := make(Paths, len(p))
453 for i, path := range p {
454 ret[i] = path
455 }
456 return ret
457}
458
459// Strings returns the string forms of the writable paths.
460func (p OutputPaths) Strings() []string {
461 if p == nil {
462 return nil
463 }
464 ret := make([]string, len(p))
465 for i, path := range p {
466 ret[i] = path.String()
467 }
468 return ret
469}
470
Liz Kammera830f3a2020-11-10 10:50:34 -0800471// Expands Paths to a SourceFileProducer or OutputFileProducer module dependency referenced via ":name" or ":name{.tag}" syntax.
472// If the dependency is not found, a missingErrorDependency is returned.
473// If the module dependency is not a SourceFileProducer or OutputFileProducer, appropriate errors will be returned.
474func getPathsFromModuleDep(ctx ModuleWithDepsPathContext, path, moduleName, tag string) (Paths, error) {
475 module := ctx.GetDirectDepWithTag(moduleName, sourceOrOutputDepTag(tag))
476 if module == nil {
477 return nil, missingDependencyError{[]string{moduleName}}
478 }
479 if outProducer, ok := module.(OutputFileProducer); ok {
480 outputFiles, err := outProducer.OutputFiles(tag)
481 if err != nil {
482 return nil, fmt.Errorf("path dependency %q: %s", path, err)
483 }
484 return outputFiles, nil
485 } else if tag != "" {
486 return nil, fmt.Errorf("path dependency %q is not an output file producing module", path)
487 } else if srcProducer, ok := module.(SourceFileProducer); ok {
488 return srcProducer.Srcs(), nil
489 } else {
490 return nil, fmt.Errorf("path dependency %q is not a source file producing module", path)
491 }
492}
493
Colin Crossba71a3f2019-03-18 12:12:48 -0700494// PathsAndMissingDepsForModuleSrcExcludes returns Paths rooted from the module's local source directory, excluding
Colin Cross41955e82019-05-29 14:40:35 -0700495// paths listed in the excludes arguments, and a list of missing dependencies. It expands globs, references to
496// SourceFileProducer modules using the ":name" syntax, and references to OutputFileProducer modules using the
497// ":name{.tag}" syntax. Properties passed as the paths or excludes argument must have been annotated with struct tag
498// `android:"path"` so that dependencies on SourceFileProducer modules will have already been handled by the
499// path_properties mutator. If ctx.Config().AllowMissingDependencies() is true then any missing SourceFileProducer or
500// OutputFileProducer dependencies will be returned, and they will NOT cause the module to be marked as having missing
501// dependencies.
Liz Kammera830f3a2020-11-10 10:50:34 -0800502func PathsAndMissingDepsForModuleSrcExcludes(ctx ModuleWithDepsPathContext, paths, excludes []string) (Paths, []string) {
Colin Cross8a497952019-03-05 22:25:09 -0800503 prefix := pathForModuleSrc(ctx).String()
504
505 var expandedExcludes []string
506 if excludes != nil {
507 expandedExcludes = make([]string, 0, len(excludes))
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700508 }
Colin Cross8a497952019-03-05 22:25:09 -0800509
Colin Crossba71a3f2019-03-18 12:12:48 -0700510 var missingExcludeDeps []string
511
Colin Cross8a497952019-03-05 22:25:09 -0800512 for _, e := range excludes {
Colin Cross41955e82019-05-29 14:40:35 -0700513 if m, t := SrcIsModuleWithTag(e); m != "" {
Liz Kammera830f3a2020-11-10 10:50:34 -0800514 modulePaths, err := getPathsFromModuleDep(ctx, e, m, t)
515 if m, ok := err.(missingDependencyError); ok {
516 missingExcludeDeps = append(missingExcludeDeps, m.missingDeps...)
517 } else if err != nil {
518 reportPathError(ctx, err)
Colin Cross8a497952019-03-05 22:25:09 -0800519 } else {
Liz Kammera830f3a2020-11-10 10:50:34 -0800520 expandedExcludes = append(expandedExcludes, modulePaths.Strings()...)
Colin Cross8a497952019-03-05 22:25:09 -0800521 }
522 } else {
523 expandedExcludes = append(expandedExcludes, filepath.Join(prefix, e))
524 }
525 }
526
527 if paths == nil {
Colin Crossba71a3f2019-03-18 12:12:48 -0700528 return nil, missingExcludeDeps
Colin Cross8a497952019-03-05 22:25:09 -0800529 }
530
Colin Crossba71a3f2019-03-18 12:12:48 -0700531 var missingDeps []string
532
Colin Cross8a497952019-03-05 22:25:09 -0800533 expandedSrcFiles := make(Paths, 0, len(paths))
534 for _, s := range paths {
535 srcFiles, err := expandOneSrcPath(ctx, s, expandedExcludes)
536 if depErr, ok := err.(missingDependencyError); ok {
Colin Crossba71a3f2019-03-18 12:12:48 -0700537 missingDeps = append(missingDeps, depErr.missingDeps...)
Colin Cross8a497952019-03-05 22:25:09 -0800538 } else if err != nil {
539 reportPathError(ctx, err)
540 }
541 expandedSrcFiles = append(expandedSrcFiles, srcFiles...)
542 }
Colin Crossba71a3f2019-03-18 12:12:48 -0700543
544 return expandedSrcFiles, append(missingDeps, missingExcludeDeps...)
Colin Cross8a497952019-03-05 22:25:09 -0800545}
546
547type missingDependencyError struct {
548 missingDeps []string
549}
550
551func (e missingDependencyError) Error() string {
552 return "missing dependencies: " + strings.Join(e.missingDeps, ", ")
553}
554
Liz Kammera830f3a2020-11-10 10:50:34 -0800555// Expands one path string to Paths rooted from the module's local source
556// directory, excluding those listed in the expandedExcludes.
557// Expands globs, references to SourceFileProducer or OutputFileProducer modules using the ":name" and ":name{.tag}" syntax.
558func expandOneSrcPath(ctx ModuleWithDepsPathContext, sPath string, expandedExcludes []string) (Paths, error) {
Jooyung Han7607dd32020-07-05 10:23:14 +0900559 excludePaths := func(paths Paths) Paths {
560 if len(expandedExcludes) == 0 {
561 return paths
562 }
563 remainder := make(Paths, 0, len(paths))
564 for _, p := range paths {
565 if !InList(p.String(), expandedExcludes) {
566 remainder = append(remainder, p)
567 }
568 }
569 return remainder
570 }
Liz Kammera830f3a2020-11-10 10:50:34 -0800571 if m, t := SrcIsModuleWithTag(sPath); m != "" {
572 modulePaths, err := getPathsFromModuleDep(ctx, sPath, m, t)
573 if err != nil {
574 return nil, err
Colin Cross8a497952019-03-05 22:25:09 -0800575 } else {
Liz Kammera830f3a2020-11-10 10:50:34 -0800576 return excludePaths(modulePaths), nil
Colin Cross8a497952019-03-05 22:25:09 -0800577 }
Liz Kammera830f3a2020-11-10 10:50:34 -0800578 } else if pathtools.IsGlob(sPath) {
579 paths := GlobFiles(ctx, pathForModuleSrc(ctx, sPath).String(), expandedExcludes)
Colin Cross8a497952019-03-05 22:25:09 -0800580 return PathsWithModuleSrcSubDir(ctx, paths, ""), nil
581 } else {
Liz Kammera830f3a2020-11-10 10:50:34 -0800582 p := pathForModuleSrc(ctx, sPath)
Colin Cross988414c2020-01-11 01:11:46 +0000583 if exists, _, err := ctx.Config().fs.Exists(p.String()); err != nil {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +0100584 ReportPathErrorf(ctx, "%s: %s", p, err.Error())
Colin Cross5e6a7972020-06-07 16:56:32 -0700585 } else if !exists && !ctx.Config().testAllowNonExistentPaths {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +0100586 ReportPathErrorf(ctx, "module source path %q does not exist", p)
Colin Cross8a497952019-03-05 22:25:09 -0800587 }
588
Jooyung Han7607dd32020-07-05 10:23:14 +0900589 if InList(p.String(), expandedExcludes) {
Colin Cross8a497952019-03-05 22:25:09 -0800590 return nil, nil
591 }
592 return Paths{p}, nil
593 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700594}
595
596// pathsForModuleSrcFromFullPath returns Paths rooted from the module's local
597// source directory, but strip the local source directory from the beginning of
Dan Willemsen540a78c2018-02-26 21:50:08 -0800598// each string. If incDirs is false, strip paths with a trailing '/' from the list.
Colin Crossfe4bc362018-09-12 10:02:13 -0700599// It intended for use in globs that only list files that exist, so it allows '$' in
600// filenames.
Liz Kammera830f3a2020-11-10 10:50:34 -0800601func pathsForModuleSrcFromFullPath(ctx EarlyModulePathContext, paths []string, incDirs bool) Paths {
Colin Cross6510f912017-11-29 00:27:14 -0800602 prefix := filepath.Join(ctx.Config().srcDir, ctx.ModuleDir()) + "/"
Colin Cross0f37af02017-09-27 17:42:05 -0700603 if prefix == "./" {
604 prefix = ""
605 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700606 ret := make(Paths, 0, len(paths))
607 for _, p := range paths {
Dan Willemsen540a78c2018-02-26 21:50:08 -0800608 if !incDirs && strings.HasSuffix(p, "/") {
609 continue
610 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700611 path := filepath.Clean(p)
612 if !strings.HasPrefix(path, prefix) {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +0100613 ReportPathErrorf(ctx, "Path %q is not in module source directory %q", p, prefix)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700614 continue
615 }
Colin Crosse3924e12018-08-15 20:18:53 -0700616
Colin Crossfe4bc362018-09-12 10:02:13 -0700617 srcPath, err := safePathForSource(ctx, ctx.ModuleDir(), path[len(prefix):])
Colin Crosse3924e12018-08-15 20:18:53 -0700618 if err != nil {
619 reportPathError(ctx, err)
620 continue
621 }
622
Colin Cross07e51612019-03-05 12:46:40 -0800623 srcPath.basePath.rel = srcPath.path
Colin Crosse3924e12018-08-15 20:18:53 -0700624
Colin Cross07e51612019-03-05 12:46:40 -0800625 ret = append(ret, srcPath)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700626 }
627 return ret
628}
629
Liz Kammera830f3a2020-11-10 10:50:34 -0800630// PathsWithOptionalDefaultForModuleSrc returns Paths rooted from the module's local source
631// directory. If input is nil, use the default if it exists. If input is empty, returns nil.
632func PathsWithOptionalDefaultForModuleSrc(ctx ModuleMissingDepsPathContext, input []string, def string) Paths {
Colin Cross0ddae7f2019-02-07 15:30:01 -0800633 if input != nil {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700634 return PathsForModuleSrc(ctx, input)
635 }
636 // Use Glob so that if the default doesn't exist, a dependency is added so that when it
637 // is created, we're run again.
Colin Cross6510f912017-11-29 00:27:14 -0800638 path := filepath.Join(ctx.Config().srcDir, ctx.ModuleDir(), def)
Liz Kammera830f3a2020-11-10 10:50:34 -0800639 return Glob(ctx, path, nil)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700640}
641
642// Strings returns the Paths in string form
643func (p Paths) Strings() []string {
644 if p == nil {
645 return nil
646 }
647 ret := make([]string, len(p))
648 for i, path := range p {
649 ret[i] = path.String()
650 }
651 return ret
652}
653
Colin Crossc0efd1d2020-07-03 11:56:24 -0700654func CopyOfPaths(paths Paths) Paths {
655 return append(Paths(nil), paths...)
656}
657
Colin Crossb6715442017-10-24 11:13:31 -0700658// FirstUniquePaths returns all unique elements of a Paths, keeping the first copy of each. It
659// modifies the Paths slice contents in place, and returns a subslice of the original slice.
Dan Willemsenfe92c962017-08-29 12:28:37 -0700660func FirstUniquePaths(list Paths) Paths {
Colin Cross27027c72020-02-28 15:34:17 -0800661 // 128 was chosen based on BenchmarkFirstUniquePaths results.
662 if len(list) > 128 {
663 return firstUniquePathsMap(list)
664 }
665 return firstUniquePathsList(list)
666}
667
Colin Crossc0efd1d2020-07-03 11:56:24 -0700668// SortedUniquePaths returns all unique elements of a Paths in sorted order. It modifies the
669// Paths slice contents in place, and returns a subslice of the original slice.
Jiyong Park33c77362020-05-29 22:00:16 +0900670func SortedUniquePaths(list Paths) Paths {
671 unique := FirstUniquePaths(list)
672 sort.Slice(unique, func(i, j int) bool {
673 return unique[i].String() < unique[j].String()
674 })
675 return unique
676}
677
Colin Cross27027c72020-02-28 15:34:17 -0800678func firstUniquePathsList(list Paths) Paths {
Dan Willemsenfe92c962017-08-29 12:28:37 -0700679 k := 0
680outer:
681 for i := 0; i < len(list); i++ {
682 for j := 0; j < k; j++ {
683 if list[i] == list[j] {
684 continue outer
685 }
686 }
687 list[k] = list[i]
688 k++
689 }
690 return list[:k]
691}
692
Colin Cross27027c72020-02-28 15:34:17 -0800693func firstUniquePathsMap(list Paths) Paths {
694 k := 0
695 seen := make(map[Path]bool, len(list))
696 for i := 0; i < len(list); i++ {
697 if seen[list[i]] {
698 continue
699 }
700 seen[list[i]] = true
701 list[k] = list[i]
702 k++
703 }
704 return list[:k]
705}
706
Colin Cross5d583952020-11-24 16:21:24 -0800707// FirstUniqueInstallPaths returns all unique elements of an InstallPaths, keeping the first copy of each. It
708// modifies the InstallPaths slice contents in place, and returns a subslice of the original slice.
709func FirstUniqueInstallPaths(list InstallPaths) InstallPaths {
710 // 128 was chosen based on BenchmarkFirstUniquePaths results.
711 if len(list) > 128 {
712 return firstUniqueInstallPathsMap(list)
713 }
714 return firstUniqueInstallPathsList(list)
715}
716
717func firstUniqueInstallPathsList(list InstallPaths) InstallPaths {
718 k := 0
719outer:
720 for i := 0; i < len(list); i++ {
721 for j := 0; j < k; j++ {
722 if list[i] == list[j] {
723 continue outer
724 }
725 }
726 list[k] = list[i]
727 k++
728 }
729 return list[:k]
730}
731
732func firstUniqueInstallPathsMap(list InstallPaths) InstallPaths {
733 k := 0
734 seen := make(map[InstallPath]bool, len(list))
735 for i := 0; i < len(list); i++ {
736 if seen[list[i]] {
737 continue
738 }
739 seen[list[i]] = true
740 list[k] = list[i]
741 k++
742 }
743 return list[:k]
744}
745
Colin Crossb6715442017-10-24 11:13:31 -0700746// LastUniquePaths returns all unique elements of a Paths, keeping the last copy of each. It
747// modifies the Paths slice contents in place, and returns a subslice of the original slice.
748func LastUniquePaths(list Paths) Paths {
749 totalSkip := 0
750 for i := len(list) - 1; i >= totalSkip; i-- {
751 skip := 0
752 for j := i - 1; j >= totalSkip; j-- {
753 if list[i] == list[j] {
754 skip++
755 } else {
756 list[j+skip] = list[j]
757 }
758 }
759 totalSkip += skip
760 }
761 return list[totalSkip:]
762}
763
Colin Crossa140bb02018-04-17 10:52:26 -0700764// ReversePaths returns a copy of a Paths in reverse order.
765func ReversePaths(list Paths) Paths {
766 if list == nil {
767 return nil
768 }
769 ret := make(Paths, len(list))
770 for i := range list {
771 ret[i] = list[len(list)-1-i]
772 }
773 return ret
774}
775
Jeff Gaston294356f2017-09-27 17:05:30 -0700776func indexPathList(s Path, list []Path) int {
777 for i, l := range list {
778 if l == s {
779 return i
780 }
781 }
782
783 return -1
784}
785
786func inPathList(p Path, list []Path) bool {
787 return indexPathList(p, list) != -1
788}
789
790func FilterPathList(list []Path, filter []Path) (remainder []Path, filtered []Path) {
Paul Duffin57b9e1d2019-12-13 00:03:35 +0000791 return FilterPathListPredicate(list, func(p Path) bool { return inPathList(p, filter) })
792}
793
794func FilterPathListPredicate(list []Path, predicate func(Path) bool) (remainder []Path, filtered []Path) {
Jeff Gaston294356f2017-09-27 17:05:30 -0700795 for _, l := range list {
Paul Duffin57b9e1d2019-12-13 00:03:35 +0000796 if predicate(l) {
Jeff Gaston294356f2017-09-27 17:05:30 -0700797 filtered = append(filtered, l)
798 } else {
799 remainder = append(remainder, l)
800 }
801 }
802
803 return
804}
805
Colin Cross93e85952017-08-15 13:34:18 -0700806// HasExt returns true of any of the paths have extension ext, otherwise false
807func (p Paths) HasExt(ext string) bool {
808 for _, path := range p {
809 if path.Ext() == ext {
810 return true
811 }
812 }
813
814 return false
815}
816
817// FilterByExt returns the subset of the paths that have extension ext
818func (p Paths) FilterByExt(ext string) Paths {
819 ret := make(Paths, 0, len(p))
820 for _, path := range p {
821 if path.Ext() == ext {
822 ret = append(ret, path)
823 }
824 }
825 return ret
826}
827
828// FilterOutByExt returns the subset of the paths that do not have extension ext
829func (p Paths) FilterOutByExt(ext string) Paths {
830 ret := make(Paths, 0, len(p))
831 for _, path := range p {
832 if path.Ext() != ext {
833 ret = append(ret, path)
834 }
835 }
836 return ret
837}
838
Colin Cross5e6cfbe2017-11-03 15:20:35 -0700839// DirectorySortedPaths is a slice of paths that are sorted such that all files in a directory
840// (including subdirectories) are in a contiguous subslice of the list, and can be found in
841// O(log(N)) time using a binary search on the directory prefix.
842type DirectorySortedPaths Paths
843
844func PathsToDirectorySortedPaths(paths Paths) DirectorySortedPaths {
845 ret := append(DirectorySortedPaths(nil), paths...)
846 sort.Slice(ret, func(i, j int) bool {
847 return ret[i].String() < ret[j].String()
848 })
849 return ret
850}
851
852// PathsInDirectory returns a subslice of the DirectorySortedPaths as a Paths that contains all entries
853// that are in the specified directory and its subdirectories.
854func (p DirectorySortedPaths) PathsInDirectory(dir string) Paths {
855 prefix := filepath.Clean(dir) + "/"
856 start := sort.Search(len(p), func(i int) bool {
857 return prefix < p[i].String()
858 })
859
860 ret := p[start:]
861
862 end := sort.Search(len(ret), func(i int) bool {
863 return !strings.HasPrefix(ret[i].String(), prefix)
864 })
865
866 ret = ret[:end]
867
868 return Paths(ret)
869}
870
Alex Humesky29e3bbe2020-11-20 21:30:13 -0500871// WritablePaths is a slice of WritablePath, used for multiple outputs.
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700872type WritablePaths []WritablePath
873
874// Strings returns the string forms of the writable paths.
875func (p WritablePaths) Strings() []string {
876 if p == nil {
877 return nil
878 }
879 ret := make([]string, len(p))
880 for i, path := range p {
881 ret[i] = path.String()
882 }
883 return ret
884}
885
Colin Cross3bc7ffa2017-11-22 16:19:37 -0800886// Paths returns the WritablePaths as a Paths
887func (p WritablePaths) Paths() Paths {
888 if p == nil {
889 return nil
890 }
891 ret := make(Paths, len(p))
892 for i, path := range p {
893 ret[i] = path
894 }
895 return ret
896}
897
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700898type basePath struct {
899 path string
900 config Config
Colin Crossfaeb7aa2017-02-01 14:12:44 -0800901 rel string
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700902}
903
904func (p basePath) Ext() string {
905 return filepath.Ext(p.path)
906}
907
Colin Cross4f6fc9c2016-10-26 10:05:25 -0700908func (p basePath) Base() string {
909 return filepath.Base(p.path)
910}
911
Colin Crossfaeb7aa2017-02-01 14:12:44 -0800912func (p basePath) Rel() string {
913 if p.rel != "" {
914 return p.rel
915 }
916 return p.path
917}
918
Colin Cross0875c522017-11-28 17:34:01 -0800919func (p basePath) String() string {
920 return p.path
921}
922
Colin Cross0db55682017-12-05 15:36:55 -0800923func (p basePath) withRel(rel string) basePath {
924 p.path = filepath.Join(p.path, rel)
925 p.rel = rel
926 return p
927}
928
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700929// SourcePath is a Path representing a file path rooted from SrcDir
930type SourcePath struct {
931 basePath
932}
933
934var _ Path = SourcePath{}
935
Colin Cross0db55682017-12-05 15:36:55 -0800936func (p SourcePath) withRel(rel string) SourcePath {
937 p.basePath = p.basePath.withRel(rel)
938 return p
939}
940
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700941// safePathForSource is for paths that we expect are safe -- only for use by go
942// code that is embedding ninja variables in paths
Colin Crossfe4bc362018-09-12 10:02:13 -0700943func safePathForSource(ctx PathContext, pathComponents ...string) (SourcePath, error) {
944 p, err := validateSafePath(pathComponents...)
Colin Crossaabf6792017-11-29 00:27:14 -0800945 ret := SourcePath{basePath{p, ctx.Config(), ""}}
Colin Crossfe4bc362018-09-12 10:02:13 -0700946 if err != nil {
947 return ret, err
948 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700949
Colin Cross7b3dcc32019-01-24 13:14:39 -0800950 // absolute path already checked by validateSafePath
951 if strings.HasPrefix(ret.String(), ctx.Config().buildDir) {
Mikhail Naganovab1f5182019-02-08 13:17:55 -0800952 return ret, fmt.Errorf("source path %q is in output", ret.String())
Colin Cross6e18ca42015-07-14 18:55:36 -0700953 }
954
Colin Crossfe4bc362018-09-12 10:02:13 -0700955 return ret, err
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700956}
957
Colin Cross192e97a2018-02-22 14:21:02 -0800958// pathForSource creates a SourcePath from pathComponents, but does not check that it exists.
959func pathForSource(ctx PathContext, pathComponents ...string) (SourcePath, error) {
Colin Crossc48c1432018-02-23 07:09:01 +0000960 p, err := validatePath(pathComponents...)
961 ret := SourcePath{basePath{p, ctx.Config(), ""}}
Colin Cross94a32102018-02-22 14:21:02 -0800962 if err != nil {
Colin Cross192e97a2018-02-22 14:21:02 -0800963 return ret, err
Colin Cross94a32102018-02-22 14:21:02 -0800964 }
965
Colin Cross7b3dcc32019-01-24 13:14:39 -0800966 // absolute path already checked by validatePath
967 if strings.HasPrefix(ret.String(), ctx.Config().buildDir) {
Mikhail Naganovab1f5182019-02-08 13:17:55 -0800968 return ret, fmt.Errorf("source path %q is in output", ret.String())
Colin Crossc48c1432018-02-23 07:09:01 +0000969 }
970
Colin Cross192e97a2018-02-22 14:21:02 -0800971 return ret, nil
972}
973
974// existsWithDependencies returns true if the path exists, and adds appropriate dependencies to rerun if the
975// path does not exist.
976func existsWithDependencies(ctx PathContext, path SourcePath) (exists bool, err error) {
977 var files []string
978
979 if gctx, ok := ctx.(PathGlobContext); ok {
980 // Use glob to produce proper dependencies, even though we only want
981 // a single file.
982 files, err = gctx.GlobWithDeps(path.String(), nil)
983 } else {
984 var deps []string
985 // We cannot add build statements in this context, so we fall back to
986 // AddNinjaFileDeps
Colin Cross988414c2020-01-11 01:11:46 +0000987 files, deps, err = ctx.Config().fs.Glob(path.String(), nil, pathtools.FollowSymlinks)
Colin Cross192e97a2018-02-22 14:21:02 -0800988 ctx.AddNinjaFileDeps(deps...)
989 }
990
991 if err != nil {
992 return false, fmt.Errorf("glob: %s", err.Error())
993 }
994
995 return len(files) > 0, nil
996}
997
998// PathForSource joins the provided path components and validates that the result
999// neither escapes the source dir nor is in the out dir.
1000// On error, it will return a usable, but invalid SourcePath, and report a ModuleError.
1001func PathForSource(ctx PathContext, pathComponents ...string) SourcePath {
1002 path, err := pathForSource(ctx, pathComponents...)
1003 if err != nil {
1004 reportPathError(ctx, err)
1005 }
1006
Colin Crosse3924e12018-08-15 20:18:53 -07001007 if pathtools.IsGlob(path.String()) {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001008 ReportPathErrorf(ctx, "path may not contain a glob: %s", path.String())
Colin Crosse3924e12018-08-15 20:18:53 -07001009 }
1010
Liz Kammera830f3a2020-11-10 10:50:34 -08001011 if modCtx, ok := ctx.(ModuleMissingDepsPathContext); ok && ctx.Config().AllowMissingDependencies() {
Colin Cross192e97a2018-02-22 14:21:02 -08001012 exists, err := existsWithDependencies(ctx, path)
1013 if err != nil {
1014 reportPathError(ctx, err)
1015 }
1016 if !exists {
1017 modCtx.AddMissingDependencies([]string{path.String()})
1018 }
Colin Cross988414c2020-01-11 01:11:46 +00001019 } else if exists, _, err := ctx.Config().fs.Exists(path.String()); err != nil {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001020 ReportPathErrorf(ctx, "%s: %s", path, err.Error())
Colin Cross5e6a7972020-06-07 16:56:32 -07001021 } else if !exists && !ctx.Config().testAllowNonExistentPaths {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001022 ReportPathErrorf(ctx, "source path %q does not exist", path)
Colin Cross192e97a2018-02-22 14:21:02 -08001023 }
1024 return path
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001025}
1026
Jeff Gaston734e3802017-04-10 15:47:24 -07001027// ExistentPathForSource returns an OptionalPath with the SourcePath if the
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001028// path exists, or an empty OptionalPath if it doesn't exist. Dependencies are added
1029// so that the ninja file will be regenerated if the state of the path changes.
Colin Cross32f38982018-02-22 11:47:25 -08001030func ExistentPathForSource(ctx PathContext, pathComponents ...string) OptionalPath {
Colin Cross192e97a2018-02-22 14:21:02 -08001031 path, err := pathForSource(ctx, pathComponents...)
Colin Cross1ccfcc32018-02-22 13:54:26 -08001032 if err != nil {
1033 reportPathError(ctx, err)
1034 return OptionalPath{}
1035 }
Colin Crossc48c1432018-02-23 07:09:01 +00001036
Colin Crosse3924e12018-08-15 20:18:53 -07001037 if pathtools.IsGlob(path.String()) {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001038 ReportPathErrorf(ctx, "path may not contain a glob: %s", path.String())
Colin Crosse3924e12018-08-15 20:18:53 -07001039 return OptionalPath{}
1040 }
1041
Colin Cross192e97a2018-02-22 14:21:02 -08001042 exists, err := existsWithDependencies(ctx, path)
Colin Crossc48c1432018-02-23 07:09:01 +00001043 if err != nil {
1044 reportPathError(ctx, err)
1045 return OptionalPath{}
1046 }
Colin Cross192e97a2018-02-22 14:21:02 -08001047 if !exists {
Colin Crossc48c1432018-02-23 07:09:01 +00001048 return OptionalPath{}
1049 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001050 return OptionalPathForPath(path)
1051}
1052
1053func (p SourcePath) String() string {
1054 return filepath.Join(p.config.srcDir, p.path)
1055}
1056
1057// Join creates a new SourcePath with paths... joined with the current path. The
1058// provided paths... may not use '..' to escape from the current path.
1059func (p SourcePath) Join(ctx PathContext, paths ...string) SourcePath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001060 path, err := validatePath(paths...)
1061 if err != nil {
1062 reportPathError(ctx, err)
1063 }
Colin Cross0db55682017-12-05 15:36:55 -08001064 return p.withRel(path)
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001065}
1066
Colin Cross2fafa3e2019-03-05 12:39:51 -08001067// join is like Join but does less path validation.
1068func (p SourcePath) join(ctx PathContext, paths ...string) SourcePath {
1069 path, err := validateSafePath(paths...)
1070 if err != nil {
1071 reportPathError(ctx, err)
1072 }
1073 return p.withRel(path)
1074}
1075
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001076// OverlayPath returns the overlay for `path' if it exists. This assumes that the
1077// SourcePath is the path to a resource overlay directory.
Liz Kammera830f3a2020-11-10 10:50:34 -08001078func (p SourcePath) OverlayPath(ctx ModuleMissingDepsPathContext, path Path) OptionalPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001079 var relDir string
Colin Cross07e51612019-03-05 12:46:40 -08001080 if srcPath, ok := path.(SourcePath); ok {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001081 relDir = srcPath.path
1082 } else {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001083 ReportPathErrorf(ctx, "Cannot find relative path for %s(%s)", reflect.TypeOf(path).Name(), path)
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001084 return OptionalPath{}
1085 }
1086 dir := filepath.Join(p.config.srcDir, p.path, relDir)
1087 // Use Glob so that we are run again if the directory is added.
Colin Cross7f19f372016-11-01 11:10:25 -07001088 if pathtools.IsGlob(dir) {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001089 ReportPathErrorf(ctx, "Path may not contain a glob: %s", dir)
Dan Willemsen7b310ee2015-12-18 15:11:17 -08001090 }
Colin Cross461b4452018-02-23 09:22:42 -08001091 paths, err := ctx.GlobWithDeps(dir, nil)
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001092 if err != nil {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001093 ReportPathErrorf(ctx, "glob: %s", err.Error())
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001094 return OptionalPath{}
1095 }
1096 if len(paths) == 0 {
1097 return OptionalPath{}
1098 }
Colin Cross43f08db2018-11-12 10:13:39 -08001099 relPath := Rel(ctx, p.config.srcDir, paths[0])
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001100 return OptionalPathForPath(PathForSource(ctx, relPath))
1101}
1102
Colin Cross70dda7e2019-10-01 22:05:35 -07001103// OutputPath is a Path representing an intermediates file path rooted from the build directory
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001104type OutputPath struct {
1105 basePath
Colin Crossd63c9a72020-01-29 16:52:50 -08001106 fullPath string
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001107}
1108
Colin Cross702e0f82017-10-18 17:27:54 -07001109func (p OutputPath) withRel(rel string) OutputPath {
Colin Cross0db55682017-12-05 15:36:55 -08001110 p.basePath = p.basePath.withRel(rel)
Colin Crossd63c9a72020-01-29 16:52:50 -08001111 p.fullPath = filepath.Join(p.fullPath, rel)
Colin Cross702e0f82017-10-18 17:27:54 -07001112 return p
1113}
1114
Colin Cross3063b782018-08-15 11:19:12 -07001115func (p OutputPath) WithoutRel() OutputPath {
1116 p.basePath.rel = filepath.Base(p.basePath.path)
1117 return p
1118}
1119
Paul Duffin9b478b02019-12-10 13:41:51 +00001120func (p OutputPath) buildDir() string {
1121 return p.config.buildDir
1122}
1123
Paul Duffin0267d492021-02-02 10:05:52 +00001124func (p OutputPath) objPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleObjPath {
1125 return PathForModuleObj(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
1126}
1127
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001128var _ Path = OutputPath{}
Paul Duffin9b478b02019-12-10 13:41:51 +00001129var _ WritablePath = OutputPath{}
Paul Duffin0267d492021-02-02 10:05:52 +00001130var _ objPathProvider = OutputPath{}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001131
Chris Parsons8f232a22020-06-23 17:37:05 -04001132// toolDepPath is a Path representing a dependency of the build tool.
1133type toolDepPath struct {
1134 basePath
1135}
1136
1137var _ Path = toolDepPath{}
1138
1139// pathForBuildToolDep returns a toolDepPath representing the given path string.
1140// There is no validation for the path, as it is "trusted": It may fail
1141// normal validation checks. For example, it may be an absolute path.
1142// Only use this function to construct paths for dependencies of the build
1143// tool invocation.
1144func pathForBuildToolDep(ctx PathContext, path string) toolDepPath {
1145 return toolDepPath{basePath{path, ctx.Config(), ""}}
1146}
1147
Jeff Gaston734e3802017-04-10 15:47:24 -07001148// PathForOutput joins the provided paths and returns an OutputPath that is
1149// validated to not escape the build dir.
1150// On error, it will return a usable, but invalid OutputPath, and report a ModuleError.
1151func PathForOutput(ctx PathContext, pathComponents ...string) OutputPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001152 path, err := validatePath(pathComponents...)
1153 if err != nil {
1154 reportPathError(ctx, err)
1155 }
Colin Crossd63c9a72020-01-29 16:52:50 -08001156 fullPath := filepath.Join(ctx.Config().buildDir, path)
1157 path = fullPath[len(fullPath)-len(path):]
1158 return OutputPath{basePath{path, ctx.Config(), ""}, fullPath}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001159}
1160
Colin Cross40e33732019-02-15 11:08:35 -08001161// PathsForOutput returns Paths rooted from buildDir
1162func PathsForOutput(ctx PathContext, paths []string) WritablePaths {
1163 ret := make(WritablePaths, len(paths))
1164 for i, path := range paths {
1165 ret[i] = PathForOutput(ctx, path)
1166 }
1167 return ret
1168}
1169
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001170func (p OutputPath) writablePath() {}
1171
1172func (p OutputPath) String() string {
Colin Crossd63c9a72020-01-29 16:52:50 -08001173 return p.fullPath
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001174}
1175
1176// Join creates a new OutputPath with paths... joined with the current path. The
1177// provided paths... may not use '..' to escape from the current path.
1178func (p OutputPath) Join(ctx PathContext, paths ...string) OutputPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001179 path, err := validatePath(paths...)
1180 if err != nil {
1181 reportPathError(ctx, err)
1182 }
Colin Cross0db55682017-12-05 15:36:55 -08001183 return p.withRel(path)
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001184}
1185
Colin Cross8854a5a2019-02-11 14:14:16 -08001186// ReplaceExtension creates a new OutputPath with the extension replaced with ext.
1187func (p OutputPath) ReplaceExtension(ctx PathContext, ext string) OutputPath {
1188 if strings.Contains(ext, "/") {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001189 ReportPathErrorf(ctx, "extension %q cannot contain /", ext)
Colin Cross8854a5a2019-02-11 14:14:16 -08001190 }
1191 ret := PathForOutput(ctx, pathtools.ReplaceExtension(p.path, ext))
Colin Cross2cdd5df2019-02-25 10:25:24 -08001192 ret.rel = pathtools.ReplaceExtension(p.rel, ext)
Colin Cross8854a5a2019-02-11 14:14:16 -08001193 return ret
1194}
1195
Colin Cross40e33732019-02-15 11:08:35 -08001196// InSameDir creates a new OutputPath from the directory of the current OutputPath joined with the elements in paths.
1197func (p OutputPath) InSameDir(ctx PathContext, paths ...string) OutputPath {
1198 path, err := validatePath(paths...)
1199 if err != nil {
1200 reportPathError(ctx, err)
1201 }
1202
1203 ret := PathForOutput(ctx, filepath.Dir(p.path), path)
Colin Cross2cdd5df2019-02-25 10:25:24 -08001204 ret.rel = filepath.Join(filepath.Dir(p.rel), path)
Colin Cross40e33732019-02-15 11:08:35 -08001205 return ret
1206}
1207
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001208// PathForIntermediates returns an OutputPath representing the top-level
1209// intermediates directory.
1210func PathForIntermediates(ctx PathContext, paths ...string) OutputPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001211 path, err := validatePath(paths...)
1212 if err != nil {
1213 reportPathError(ctx, err)
1214 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001215 return PathForOutput(ctx, ".intermediates", path)
1216}
1217
Colin Cross07e51612019-03-05 12:46:40 -08001218var _ genPathProvider = SourcePath{}
1219var _ objPathProvider = SourcePath{}
1220var _ resPathProvider = SourcePath{}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001221
Colin Cross07e51612019-03-05 12:46:40 -08001222// PathForModuleSrc returns a Path representing the paths... under the
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001223// module's local source directory.
Liz Kammera830f3a2020-11-10 10:50:34 -08001224func PathForModuleSrc(ctx ModuleMissingDepsPathContext, pathComponents ...string) Path {
Colin Cross8a497952019-03-05 22:25:09 -08001225 p, err := validatePath(pathComponents...)
1226 if err != nil {
1227 reportPathError(ctx, err)
Colin Cross192e97a2018-02-22 14:21:02 -08001228 }
Colin Cross8a497952019-03-05 22:25:09 -08001229 paths, err := expandOneSrcPath(ctx, p, nil)
1230 if err != nil {
1231 if depErr, ok := err.(missingDependencyError); ok {
1232 if ctx.Config().AllowMissingDependencies() {
1233 ctx.AddMissingDependencies(depErr.missingDeps)
1234 } else {
1235 ctx.ModuleErrorf(`%s, is the property annotated with android:"path"?`, depErr.Error())
1236 }
1237 } else {
1238 reportPathError(ctx, err)
1239 }
1240 return nil
1241 } else if len(paths) == 0 {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001242 ReportPathErrorf(ctx, "%q produced no files, expected exactly one", p)
Colin Cross8a497952019-03-05 22:25:09 -08001243 return nil
1244 } else if len(paths) > 1 {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001245 ReportPathErrorf(ctx, "%q produced %d files, expected exactly one", p, len(paths))
Colin Cross8a497952019-03-05 22:25:09 -08001246 }
1247 return paths[0]
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001248}
1249
Liz Kammera830f3a2020-11-10 10:50:34 -08001250func pathForModuleSrc(ctx EarlyModulePathContext, paths ...string) SourcePath {
Colin Cross07e51612019-03-05 12:46:40 -08001251 p, err := validatePath(paths...)
1252 if err != nil {
1253 reportPathError(ctx, err)
1254 }
1255
1256 path, err := pathForSource(ctx, ctx.ModuleDir(), p)
1257 if err != nil {
1258 reportPathError(ctx, err)
1259 }
1260
1261 path.basePath.rel = p
1262
1263 return path
1264}
1265
Colin Cross2fafa3e2019-03-05 12:39:51 -08001266// PathsWithModuleSrcSubDir takes a list of Paths and returns a new list of Paths where Rel() on each path
1267// will return the path relative to subDir in the module's source directory. If any input paths are not located
1268// inside subDir then a path error will be reported.
Liz Kammera830f3a2020-11-10 10:50:34 -08001269func PathsWithModuleSrcSubDir(ctx EarlyModulePathContext, paths Paths, subDir string) Paths {
Colin Cross2fafa3e2019-03-05 12:39:51 -08001270 paths = append(Paths(nil), paths...)
Colin Cross07e51612019-03-05 12:46:40 -08001271 subDirFullPath := pathForModuleSrc(ctx, subDir)
Colin Cross2fafa3e2019-03-05 12:39:51 -08001272 for i, path := range paths {
1273 rel := Rel(ctx, subDirFullPath.String(), path.String())
1274 paths[i] = subDirFullPath.join(ctx, rel)
1275 }
1276 return paths
1277}
1278
1279// PathWithModuleSrcSubDir takes a Path and returns a Path where Rel() will return the path relative to subDir in the
1280// 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 -08001281func PathWithModuleSrcSubDir(ctx EarlyModulePathContext, path Path, subDir string) Path {
Colin Cross07e51612019-03-05 12:46:40 -08001282 subDirFullPath := pathForModuleSrc(ctx, subDir)
Colin Cross2fafa3e2019-03-05 12:39:51 -08001283 rel := Rel(ctx, subDirFullPath.String(), path.String())
1284 return subDirFullPath.Join(ctx, rel)
1285}
1286
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001287// OptionalPathForModuleSrc returns an OptionalPath. The OptionalPath contains a
1288// valid path if p is non-nil.
Liz Kammera830f3a2020-11-10 10:50:34 -08001289func OptionalPathForModuleSrc(ctx ModuleMissingDepsPathContext, p *string) OptionalPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001290 if p == nil {
1291 return OptionalPath{}
1292 }
1293 return OptionalPathForPath(PathForModuleSrc(ctx, *p))
1294}
1295
Liz Kammera830f3a2020-11-10 10:50:34 -08001296func (p SourcePath) genPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleGenPath {
Colin Cross7fc17db2017-02-01 14:07:55 -08001297 return PathForModuleGen(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001298}
1299
Liz Kammera830f3a2020-11-10 10:50:34 -08001300func (p SourcePath) objPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleObjPath {
Colin Cross7fc17db2017-02-01 14:07:55 -08001301 return PathForModuleObj(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001302}
1303
Liz Kammera830f3a2020-11-10 10:50:34 -08001304func (p SourcePath) resPathWithName(ctx ModuleOutPathContext, name string) ModuleResPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001305 // TODO: Use full directory if the new ctx is not the current ctx?
1306 return PathForModuleRes(ctx, p.path, name)
1307}
1308
1309// ModuleOutPath is a Path representing a module's output directory.
1310type ModuleOutPath struct {
1311 OutputPath
1312}
1313
1314var _ Path = ModuleOutPath{}
1315
Liz Kammera830f3a2020-11-10 10:50:34 -08001316func (p ModuleOutPath) objPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleObjPath {
Pete Bentleyfcf55bf2019-08-16 20:14:32 +01001317 return PathForModuleObj(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
1318}
1319
Liz Kammera830f3a2020-11-10 10:50:34 -08001320// ModuleOutPathContext Subset of ModuleContext functions necessary for output path methods.
1321type ModuleOutPathContext interface {
1322 PathContext
1323
1324 ModuleName() string
1325 ModuleDir() string
1326 ModuleSubDir() string
1327}
1328
1329func pathForModuleOut(ctx ModuleOutPathContext) OutputPath {
Colin Cross702e0f82017-10-18 17:27:54 -07001330 return PathForOutput(ctx, ".intermediates", ctx.ModuleDir(), ctx.ModuleName(), ctx.ModuleSubDir())
1331}
1332
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001333type BazelOutPath struct {
1334 OutputPath
1335}
1336
1337var _ Path = BazelOutPath{}
1338var _ objPathProvider = BazelOutPath{}
1339
Liz Kammera830f3a2020-11-10 10:50:34 -08001340func (p BazelOutPath) objPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleObjPath {
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001341 return PathForModuleObj(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
1342}
1343
Logan Chien7eefdc42018-07-11 18:10:41 +08001344// PathForVndkRefAbiDump returns an OptionalPath representing the path of the
1345// reference abi dump for the given module. This is not guaranteed to be valid.
Liz Kammera830f3a2020-11-10 10:50:34 -08001346func PathForVndkRefAbiDump(ctx ModuleInstallPathContext, version, fileName string,
Hsin-Yi Chen53489642019-07-31 17:10:45 +08001347 isNdk, isLlndkOrVndk, isGzip bool) OptionalPath {
Logan Chien7eefdc42018-07-11 18:10:41 +08001348
Jayant Chowdharyac066c62018-02-20 10:53:31 -08001349 arches := ctx.DeviceConfig().Arches()
Logan Chien7eefdc42018-07-11 18:10:41 +08001350 if len(arches) == 0 {
1351 panic("device build with no primary arch")
1352 }
Jayant Chowdharyac066c62018-02-20 10:53:31 -08001353 currentArch := ctx.Arch()
1354 archNameAndVariant := currentArch.ArchType.String()
1355 if currentArch.ArchVariant != "" {
1356 archNameAndVariant += "_" + currentArch.ArchVariant
1357 }
Logan Chien5237bed2018-07-11 17:15:57 +08001358
1359 var dirName string
Hsin-Yi Chen53489642019-07-31 17:10:45 +08001360 if isNdk {
Logan Chien5237bed2018-07-11 17:15:57 +08001361 dirName = "ndk"
Hsin-Yi Chen53489642019-07-31 17:10:45 +08001362 } else if isLlndkOrVndk {
Logan Chien5237bed2018-07-11 17:15:57 +08001363 dirName = "vndk"
Logan Chien41eabe62019-04-10 13:33:58 +08001364 } else {
1365 dirName = "platform" // opt-in libs
Jayant Chowdhary3e231fd2017-02-08 13:45:53 -08001366 }
Logan Chien5237bed2018-07-11 17:15:57 +08001367
Jayant Chowdhary34ce67d2018-03-08 11:00:50 -08001368 binderBitness := ctx.DeviceConfig().BinderBitness()
Logan Chien7eefdc42018-07-11 18:10:41 +08001369
1370 var ext string
1371 if isGzip {
1372 ext = ".lsdump.gz"
1373 } else {
1374 ext = ".lsdump"
1375 }
1376
1377 return ExistentPathForSource(ctx, "prebuilts", "abi-dumps", dirName,
1378 version, binderBitness, archNameAndVariant, "source-based",
1379 fileName+ext)
Jayant Chowdhary3e231fd2017-02-08 13:45:53 -08001380}
1381
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001382// PathForBazelOut returns a Path representing the paths... under an output directory dedicated to
1383// bazel-owned outputs.
1384func PathForBazelOut(ctx PathContext, paths ...string) BazelOutPath {
1385 execRootPathComponents := append([]string{"execroot", "__main__"}, paths...)
1386 execRootPath := filepath.Join(execRootPathComponents...)
1387 validatedExecRootPath, err := validatePath(execRootPath)
1388 if err != nil {
1389 reportPathError(ctx, err)
1390 }
1391
1392 outputPath := OutputPath{basePath{"", ctx.Config(), ""},
1393 ctx.Config().BazelContext.OutputBase()}
1394
1395 return BazelOutPath{
1396 OutputPath: outputPath.withRel(validatedExecRootPath),
1397 }
1398}
1399
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001400// PathForModuleOut returns a Path representing the paths... under the module's
1401// output directory.
Liz Kammera830f3a2020-11-10 10:50:34 -08001402func PathForModuleOut(ctx ModuleOutPathContext, paths ...string) ModuleOutPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001403 p, err := validatePath(paths...)
1404 if err != nil {
1405 reportPathError(ctx, err)
1406 }
Colin Cross702e0f82017-10-18 17:27:54 -07001407 return ModuleOutPath{
Liz Kammera830f3a2020-11-10 10:50:34 -08001408 OutputPath: pathForModuleOut(ctx).withRel(p),
Colin Cross702e0f82017-10-18 17:27:54 -07001409 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001410}
1411
1412// ModuleGenPath is a Path representing the 'gen' directory in a module's output
1413// directory. Mainly used for generated sources.
1414type ModuleGenPath struct {
1415 ModuleOutPath
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001416}
1417
1418var _ Path = ModuleGenPath{}
1419var _ genPathProvider = ModuleGenPath{}
1420var _ objPathProvider = ModuleGenPath{}
1421
1422// PathForModuleGen returns a Path representing the paths... under the module's
1423// `gen' directory.
Liz Kammera830f3a2020-11-10 10:50:34 -08001424func PathForModuleGen(ctx ModuleOutPathContext, paths ...string) ModuleGenPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001425 p, err := validatePath(paths...)
1426 if err != nil {
1427 reportPathError(ctx, err)
1428 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001429 return ModuleGenPath{
Colin Cross702e0f82017-10-18 17:27:54 -07001430 ModuleOutPath: ModuleOutPath{
Liz Kammera830f3a2020-11-10 10:50:34 -08001431 OutputPath: pathForModuleOut(ctx).withRel("gen").withRel(p),
Colin Cross702e0f82017-10-18 17:27:54 -07001432 },
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001433 }
1434}
1435
Liz Kammera830f3a2020-11-10 10:50:34 -08001436func (p ModuleGenPath) genPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleGenPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001437 // TODO: make a different path for local vs remote generated files?
Dan Willemsen21ec4902016-11-02 20:43:13 -07001438 return PathForModuleGen(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001439}
1440
Liz Kammera830f3a2020-11-10 10:50:34 -08001441func (p ModuleGenPath) objPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleObjPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001442 return PathForModuleObj(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
1443}
1444
1445// ModuleObjPath is a Path representing the 'obj' directory in a module's output
1446// directory. Used for compiled objects.
1447type ModuleObjPath struct {
1448 ModuleOutPath
1449}
1450
1451var _ Path = ModuleObjPath{}
1452
1453// PathForModuleObj returns a Path representing the paths... under the module's
1454// 'obj' directory.
Liz Kammera830f3a2020-11-10 10:50:34 -08001455func PathForModuleObj(ctx ModuleOutPathContext, pathComponents ...string) ModuleObjPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001456 p, err := validatePath(pathComponents...)
1457 if err != nil {
1458 reportPathError(ctx, err)
1459 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001460 return ModuleObjPath{PathForModuleOut(ctx, "obj", p)}
1461}
1462
1463// ModuleResPath is a a Path representing the 'res' directory in a module's
1464// output directory.
1465type ModuleResPath struct {
1466 ModuleOutPath
1467}
1468
1469var _ Path = ModuleResPath{}
1470
1471// PathForModuleRes returns a Path representing the paths... under the module's
1472// 'res' directory.
Liz Kammera830f3a2020-11-10 10:50:34 -08001473func PathForModuleRes(ctx ModuleOutPathContext, pathComponents ...string) ModuleResPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001474 p, err := validatePath(pathComponents...)
1475 if err != nil {
1476 reportPathError(ctx, err)
1477 }
1478
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001479 return ModuleResPath{PathForModuleOut(ctx, "res", p)}
1480}
1481
Colin Cross70dda7e2019-10-01 22:05:35 -07001482// InstallPath is a Path representing a installed file path rooted from the build directory
1483type InstallPath struct {
1484 basePath
Colin Crossff6c33d2019-10-02 16:01:35 -07001485
Jiyong Park957bcd92020-10-20 18:23:33 +09001486 // partitionDir is the part of the InstallPath that is automatically determined according to the context.
1487 // For example, it is host/<os>-<arch> for host modules, and target/product/<device>/<partition> for device modules.
1488 partitionDir string
1489
1490 // makePath indicates whether this path is for Soong (false) or Make (true).
1491 makePath bool
Colin Cross70dda7e2019-10-01 22:05:35 -07001492}
1493
Paul Duffin9b478b02019-12-10 13:41:51 +00001494func (p InstallPath) buildDir() string {
1495 return p.config.buildDir
1496}
1497
Hans MÃ¥nssond3f2bd72020-11-27 12:37:28 +01001498func (p InstallPath) ReplaceExtension(ctx PathContext, ext string) OutputPath {
1499 panic("Not implemented")
1500}
1501
Paul Duffin9b478b02019-12-10 13:41:51 +00001502var _ Path = InstallPath{}
1503var _ WritablePath = InstallPath{}
1504
Colin Cross70dda7e2019-10-01 22:05:35 -07001505func (p InstallPath) writablePath() {}
1506
1507func (p InstallPath) String() string {
Jiyong Park957bcd92020-10-20 18:23:33 +09001508 if p.makePath {
1509 // Make path starts with out/ instead of out/soong.
1510 return filepath.Join(p.config.buildDir, "../", p.path)
1511 } else {
1512 return filepath.Join(p.config.buildDir, p.path)
1513 }
1514}
1515
1516// PartitionDir returns the path to the partition where the install path is rooted at. It is
1517// out/soong/target/product/<device>/<partition> for device modules, and out/soong/host/<os>-<arch> for host modules.
1518// The ./soong is dropped if the install path is for Make.
1519func (p InstallPath) PartitionDir() string {
1520 if p.makePath {
1521 return filepath.Join(p.config.buildDir, "../", p.partitionDir)
1522 } else {
1523 return filepath.Join(p.config.buildDir, p.partitionDir)
1524 }
Colin Cross70dda7e2019-10-01 22:05:35 -07001525}
1526
1527// Join creates a new InstallPath with paths... joined with the current path. The
1528// provided paths... may not use '..' to escape from the current path.
1529func (p InstallPath) Join(ctx PathContext, paths ...string) InstallPath {
1530 path, err := validatePath(paths...)
1531 if err != nil {
1532 reportPathError(ctx, err)
1533 }
1534 return p.withRel(path)
1535}
1536
1537func (p InstallPath) withRel(rel string) InstallPath {
1538 p.basePath = p.basePath.withRel(rel)
1539 return p
1540}
1541
Colin Crossff6c33d2019-10-02 16:01:35 -07001542// ToMakePath returns a new InstallPath that points to Make's install directory instead of Soong's,
1543// i.e. out/ instead of out/soong/.
1544func (p InstallPath) ToMakePath() InstallPath {
Jiyong Park957bcd92020-10-20 18:23:33 +09001545 p.makePath = true
Colin Crossff6c33d2019-10-02 16:01:35 -07001546 return p
Colin Cross70dda7e2019-10-01 22:05:35 -07001547}
1548
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001549// PathForModuleInstall returns a Path representing the install path for the
1550// module appended with paths...
Colin Cross70dda7e2019-10-01 22:05:35 -07001551func PathForModuleInstall(ctx ModuleInstallPathContext, pathComponents ...string) InstallPath {
Colin Cross6e359402020-02-10 15:29:54 -08001552 os := ctx.Os()
Jiyong Park87788b52020-09-01 12:37:45 +09001553 arch := ctx.Arch().ArchType
1554 forceOS, forceArch := ctx.InstallForceOS()
1555 if forceOS != nil {
Colin Cross6e359402020-02-10 15:29:54 -08001556 os = *forceOS
1557 }
Jiyong Park87788b52020-09-01 12:37:45 +09001558 if forceArch != nil {
1559 arch = *forceArch
1560 }
Colin Cross6e359402020-02-10 15:29:54 -08001561 partition := modulePartition(ctx, os)
Colin Cross609c49a2020-02-13 13:20:11 -08001562
Jiyong Park87788b52020-09-01 12:37:45 +09001563 ret := pathForInstall(ctx, os, arch, partition, ctx.Debug(), pathComponents...)
Colin Cross609c49a2020-02-13 13:20:11 -08001564
Jingwen Chencda22c92020-11-23 00:22:30 -05001565 if ctx.InstallBypassMake() && ctx.Config().KatiEnabled() {
Colin Cross609c49a2020-02-13 13:20:11 -08001566 ret = ret.ToMakePath()
1567 }
1568
1569 return ret
1570}
1571
Jiyong Park87788b52020-09-01 12:37:45 +09001572func pathForInstall(ctx PathContext, os OsType, arch ArchType, partition string, debug bool,
Colin Cross609c49a2020-02-13 13:20:11 -08001573 pathComponents ...string) InstallPath {
1574
Jiyong Park957bcd92020-10-20 18:23:33 +09001575 var partionPaths []string
Colin Cross609c49a2020-02-13 13:20:11 -08001576
Colin Cross6e359402020-02-10 15:29:54 -08001577 if os.Class == Device {
Jiyong Park957bcd92020-10-20 18:23:33 +09001578 partionPaths = []string{"target", "product", ctx.Config().DeviceName(), partition}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001579 } else {
Jiyong Park87788b52020-09-01 12:37:45 +09001580 osName := os.String()
1581 if os == Linux {
1582 // instead of linux_glibc
1583 osName = "linux"
Dan Willemsen866b5632017-09-22 12:28:24 -07001584 }
Jiyong Park87788b52020-09-01 12:37:45 +09001585 // SOONG_HOST_OUT is set to out/host/$(HOST_OS)-$(HOST_PREBUILT_ARCH)
1586 // and HOST_PREBUILT_ARCH is forcibly set to x86 even on x86_64 hosts. We don't seem
1587 // to have a plan to fix it (see the comment in build/make/core/envsetup.mk).
1588 // Let's keep using x86 for the existing cases until we have a need to support
1589 // other architectures.
1590 archName := arch.String()
1591 if os.Class == Host && (arch == X86_64 || arch == Common) {
1592 archName = "x86"
1593 }
Jiyong Park957bcd92020-10-20 18:23:33 +09001594 partionPaths = []string{"host", osName + "-" + archName, partition}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001595 }
Colin Cross609c49a2020-02-13 13:20:11 -08001596 if debug {
Jiyong Park957bcd92020-10-20 18:23:33 +09001597 partionPaths = append([]string{"debug"}, partionPaths...)
Dan Willemsen782a2d12015-12-21 14:55:28 -08001598 }
Colin Cross70dda7e2019-10-01 22:05:35 -07001599
Jiyong Park957bcd92020-10-20 18:23:33 +09001600 partionPath, err := validatePath(partionPaths...)
Colin Cross70dda7e2019-10-01 22:05:35 -07001601 if err != nil {
1602 reportPathError(ctx, err)
1603 }
Colin Crossff6c33d2019-10-02 16:01:35 -07001604
Jiyong Park957bcd92020-10-20 18:23:33 +09001605 base := InstallPath{
1606 basePath: basePath{partionPath, ctx.Config(), ""},
1607 partitionDir: partionPath,
1608 makePath: false,
1609 }
Colin Crossff6c33d2019-10-02 16:01:35 -07001610
Jiyong Park957bcd92020-10-20 18:23:33 +09001611 return base.Join(ctx, pathComponents...)
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001612}
1613
Nicolas Geoffray1228e9c2020-02-27 13:45:35 +00001614func pathForNdkOrSdkInstall(ctx PathContext, prefix string, paths []string) InstallPath {
Jiyong Park957bcd92020-10-20 18:23:33 +09001615 base := InstallPath{
1616 basePath: basePath{prefix, ctx.Config(), ""},
1617 partitionDir: prefix,
1618 makePath: false,
Colin Cross70dda7e2019-10-01 22:05:35 -07001619 }
Jiyong Park957bcd92020-10-20 18:23:33 +09001620 return base.Join(ctx, paths...)
Colin Cross70dda7e2019-10-01 22:05:35 -07001621}
1622
Nicolas Geoffray1228e9c2020-02-27 13:45:35 +00001623func PathForNdkInstall(ctx PathContext, paths ...string) InstallPath {
1624 return pathForNdkOrSdkInstall(ctx, "ndk", paths)
1625}
1626
1627func PathForMainlineSdksInstall(ctx PathContext, paths ...string) InstallPath {
1628 return pathForNdkOrSdkInstall(ctx, "mainline-sdks", paths)
1629}
1630
Colin Cross70dda7e2019-10-01 22:05:35 -07001631func InstallPathToOnDevicePath(ctx PathContext, path InstallPath) string {
Colin Cross43f08db2018-11-12 10:13:39 -08001632 rel := Rel(ctx, PathForOutput(ctx, "target", "product", ctx.Config().DeviceName()).String(), path.String())
1633
1634 return "/" + rel
1635}
1636
Colin Cross6e359402020-02-10 15:29:54 -08001637func modulePartition(ctx ModuleInstallPathContext, os OsType) string {
Colin Cross43f08db2018-11-12 10:13:39 -08001638 var partition string
Colin Cross6e359402020-02-10 15:29:54 -08001639 if ctx.InstallInTestcases() {
1640 // "testcases" install directory can be used for host or device modules.
Jaewoong Jung0949f312019-09-11 10:25:18 -07001641 partition = "testcases"
Colin Cross6e359402020-02-10 15:29:54 -08001642 } else if os.Class == Device {
1643 if ctx.InstallInData() {
1644 partition = "data"
1645 } else if ctx.InstallInRamdisk() {
1646 if ctx.DeviceConfig().BoardUsesRecoveryAsBoot() {
1647 partition = "recovery/root/first_stage_ramdisk"
1648 } else {
1649 partition = "ramdisk"
1650 }
1651 if !ctx.InstallInRoot() {
1652 partition += "/system"
1653 }
Yifan Hong60e0cfb2020-10-21 15:17:56 -07001654 } else if ctx.InstallInVendorRamdisk() {
Yifan Hong39143a92020-10-26 12:43:12 -07001655 // The module is only available after switching root into
1656 // /first_stage_ramdisk. To expose the module before switching root
1657 // on a device without a dedicated recovery partition, install the
1658 // recovery variant.
Yifan Hongdd8dacc2020-10-21 15:40:17 -07001659 if ctx.DeviceConfig().BoardMoveRecoveryResourcesToVendorBoot() {
Yifan Hong39143a92020-10-26 12:43:12 -07001660 partition = "vendor-ramdisk/first_stage_ramdisk"
Yifan Hongdd8dacc2020-10-21 15:40:17 -07001661 } else {
1662 partition = "vendor-ramdisk"
1663 }
1664 if !ctx.InstallInRoot() {
1665 partition += "/system"
1666 }
Colin Cross6e359402020-02-10 15:29:54 -08001667 } else if ctx.InstallInRecovery() {
1668 if ctx.InstallInRoot() {
1669 partition = "recovery/root"
1670 } else {
1671 // the layout of recovery partion is the same as that of system partition
1672 partition = "recovery/root/system"
1673 }
1674 } else if ctx.SocSpecific() {
1675 partition = ctx.DeviceConfig().VendorPath()
1676 } else if ctx.DeviceSpecific() {
1677 partition = ctx.DeviceConfig().OdmPath()
1678 } else if ctx.ProductSpecific() {
1679 partition = ctx.DeviceConfig().ProductPath()
1680 } else if ctx.SystemExtSpecific() {
1681 partition = ctx.DeviceConfig().SystemExtPath()
1682 } else if ctx.InstallInRoot() {
1683 partition = "root"
Yifan Hong82db7352020-01-21 16:12:26 -08001684 } else {
Colin Cross6e359402020-02-10 15:29:54 -08001685 partition = "system"
Yifan Hong82db7352020-01-21 16:12:26 -08001686 }
Colin Cross6e359402020-02-10 15:29:54 -08001687 if ctx.InstallInSanitizerDir() {
1688 partition = "data/asan/" + partition
Yifan Hong82db7352020-01-21 16:12:26 -08001689 }
Colin Cross43f08db2018-11-12 10:13:39 -08001690 }
1691 return partition
1692}
1693
Colin Cross609c49a2020-02-13 13:20:11 -08001694type InstallPaths []InstallPath
1695
1696// Paths returns the InstallPaths as a Paths
1697func (p InstallPaths) Paths() Paths {
1698 if p == nil {
1699 return nil
1700 }
1701 ret := make(Paths, len(p))
1702 for i, path := range p {
1703 ret[i] = path
1704 }
1705 return ret
1706}
1707
1708// Strings returns the string forms of the install paths.
1709func (p InstallPaths) Strings() []string {
1710 if p == nil {
1711 return nil
1712 }
1713 ret := make([]string, len(p))
1714 for i, path := range p {
1715 ret[i] = path.String()
1716 }
1717 return ret
1718}
1719
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001720// validateSafePath validates a path that we trust (may contain ninja variables).
Dan Willemsen80a7c2a2015-12-21 14:57:11 -08001721// Ensures that each path component does not attempt to leave its component.
Colin Cross1ccfcc32018-02-22 13:54:26 -08001722func validateSafePath(pathComponents ...string) (string, error) {
Jeff Gaston734e3802017-04-10 15:47:24 -07001723 for _, path := range pathComponents {
Dan Willemsen80a7c2a2015-12-21 14:57:11 -08001724 path := filepath.Clean(path)
1725 if path == ".." || strings.HasPrefix(path, "../") || strings.HasPrefix(path, "/") {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001726 return "", fmt.Errorf("Path is outside directory: %s", path)
Dan Willemsen80a7c2a2015-12-21 14:57:11 -08001727 }
1728 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001729 // TODO: filepath.Join isn't necessarily correct with embedded ninja
1730 // variables. '..' may remove the entire ninja variable, even if it
1731 // will be expanded to multiple nested directories.
Colin Cross1ccfcc32018-02-22 13:54:26 -08001732 return filepath.Join(pathComponents...), nil
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001733}
1734
Dan Willemsen80a7c2a2015-12-21 14:57:11 -08001735// validatePath validates that a path does not include ninja variables, and that
1736// each path component does not attempt to leave its component. Returns a joined
1737// version of each path component.
Colin Cross1ccfcc32018-02-22 13:54:26 -08001738func validatePath(pathComponents ...string) (string, error) {
Jeff Gaston734e3802017-04-10 15:47:24 -07001739 for _, path := range pathComponents {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001740 if strings.Contains(path, "$") {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001741 return "", fmt.Errorf("Path contains invalid character($): %s", path)
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001742 }
1743 }
Colin Cross1ccfcc32018-02-22 13:54:26 -08001744 return validateSafePath(pathComponents...)
Colin Cross6e18ca42015-07-14 18:55:36 -07001745}
Colin Cross5b529592017-05-09 13:34:34 -07001746
Colin Cross0875c522017-11-28 17:34:01 -08001747func PathForPhony(ctx PathContext, phony string) WritablePath {
1748 if strings.ContainsAny(phony, "$/") {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001749 ReportPathErrorf(ctx, "Phony target contains invalid character ($ or /): %s", phony)
Colin Cross0875c522017-11-28 17:34:01 -08001750 }
Colin Cross74e3fe42017-12-11 15:51:44 -08001751 return PhonyPath{basePath{phony, ctx.Config(), ""}}
Colin Cross0875c522017-11-28 17:34:01 -08001752}
1753
Colin Cross74e3fe42017-12-11 15:51:44 -08001754type PhonyPath struct {
1755 basePath
1756}
1757
1758func (p PhonyPath) writablePath() {}
1759
Paul Duffin9b478b02019-12-10 13:41:51 +00001760func (p PhonyPath) buildDir() string {
1761 return p.config.buildDir
1762}
1763
Hans MÃ¥nssond3f2bd72020-11-27 12:37:28 +01001764func (p PhonyPath) ReplaceExtension(ctx PathContext, ext string) OutputPath {
1765 panic("Not implemented")
1766}
1767
Colin Cross74e3fe42017-12-11 15:51:44 -08001768var _ Path = PhonyPath{}
1769var _ WritablePath = PhonyPath{}
1770
Colin Cross5b529592017-05-09 13:34:34 -07001771type testPath struct {
1772 basePath
1773}
1774
1775func (p testPath) String() string {
1776 return p.path
1777}
1778
Colin Cross40e33732019-02-15 11:08:35 -08001779// PathForTesting returns a Path constructed from joining the elements of paths with '/'. It should only be used from
1780// within tests.
Colin Cross5b529592017-05-09 13:34:34 -07001781func PathForTesting(paths ...string) Path {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001782 p, err := validateSafePath(paths...)
1783 if err != nil {
1784 panic(err)
1785 }
Colin Cross5b529592017-05-09 13:34:34 -07001786 return testPath{basePath{path: p, rel: p}}
1787}
1788
Colin Cross40e33732019-02-15 11:08:35 -08001789// PathsForTesting returns a Path constructed from each element in strs. It should only be used from within tests.
1790func PathsForTesting(strs ...string) Paths {
Colin Cross5b529592017-05-09 13:34:34 -07001791 p := make(Paths, len(strs))
1792 for i, s := range strs {
1793 p[i] = PathForTesting(s)
1794 }
1795
1796 return p
1797}
Colin Cross43f08db2018-11-12 10:13:39 -08001798
Colin Cross40e33732019-02-15 11:08:35 -08001799type testPathContext struct {
1800 config Config
Colin Cross40e33732019-02-15 11:08:35 -08001801}
1802
Colin Cross40e33732019-02-15 11:08:35 -08001803func (x *testPathContext) Config() Config { return x.config }
1804func (x *testPathContext) AddNinjaFileDeps(...string) {}
1805
1806// PathContextForTesting returns a PathContext that can be used in tests, for example to create an OutputPath with
1807// PathForOutput.
Colin Cross98be1bb2019-12-13 20:41:13 -08001808func PathContextForTesting(config Config) PathContext {
Colin Cross40e33732019-02-15 11:08:35 -08001809 return &testPathContext{
1810 config: config,
Colin Cross40e33732019-02-15 11:08:35 -08001811 }
1812}
1813
Ulya Trafimovichccc8c852020-10-14 11:29:07 +01001814type testModuleInstallPathContext struct {
1815 baseModuleContext
1816
1817 inData bool
1818 inTestcases bool
1819 inSanitizerDir bool
1820 inRamdisk bool
1821 inVendorRamdisk bool
1822 inRecovery bool
1823 inRoot bool
1824 forceOS *OsType
1825 forceArch *ArchType
1826}
1827
1828func (m testModuleInstallPathContext) Config() Config {
1829 return m.baseModuleContext.config
1830}
1831
1832func (testModuleInstallPathContext) AddNinjaFileDeps(deps ...string) {}
1833
1834func (m testModuleInstallPathContext) InstallInData() bool {
1835 return m.inData
1836}
1837
1838func (m testModuleInstallPathContext) InstallInTestcases() bool {
1839 return m.inTestcases
1840}
1841
1842func (m testModuleInstallPathContext) InstallInSanitizerDir() bool {
1843 return m.inSanitizerDir
1844}
1845
1846func (m testModuleInstallPathContext) InstallInRamdisk() bool {
1847 return m.inRamdisk
1848}
1849
1850func (m testModuleInstallPathContext) InstallInVendorRamdisk() bool {
1851 return m.inVendorRamdisk
1852}
1853
1854func (m testModuleInstallPathContext) InstallInRecovery() bool {
1855 return m.inRecovery
1856}
1857
1858func (m testModuleInstallPathContext) InstallInRoot() bool {
1859 return m.inRoot
1860}
1861
1862func (m testModuleInstallPathContext) InstallBypassMake() bool {
1863 return false
1864}
1865
1866func (m testModuleInstallPathContext) InstallForceOS() (*OsType, *ArchType) {
1867 return m.forceOS, m.forceArch
1868}
1869
1870// Construct a minimal ModuleInstallPathContext for testing. Note that baseModuleContext is
1871// default-initialized, which leaves blueprint.baseModuleContext set to nil, so methods that are
1872// delegated to it will panic.
1873func ModuleInstallPathContextForTesting(config Config) ModuleInstallPathContext {
1874 ctx := &testModuleInstallPathContext{}
1875 ctx.config = config
1876 ctx.os = Android
1877 return ctx
1878}
1879
Colin Cross43f08db2018-11-12 10:13:39 -08001880// Rel performs the same function as filepath.Rel, but reports errors to a PathContext, and reports an error if
1881// targetPath is not inside basePath.
1882func Rel(ctx PathContext, basePath string, targetPath string) string {
1883 rel, isRel := MaybeRel(ctx, basePath, targetPath)
1884 if !isRel {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001885 ReportPathErrorf(ctx, "path %q is not under path %q", targetPath, basePath)
Colin Cross43f08db2018-11-12 10:13:39 -08001886 return ""
1887 }
1888 return rel
1889}
1890
1891// MaybeRel performs the same function as filepath.Rel, but reports errors to a PathContext, and returns false if
1892// targetPath is not inside basePath.
1893func MaybeRel(ctx PathContext, basePath string, targetPath string) (string, bool) {
Dan Willemsen633c5022019-04-12 11:11:38 -07001894 rel, isRel, err := maybeRelErr(basePath, targetPath)
1895 if err != nil {
1896 reportPathError(ctx, err)
1897 }
1898 return rel, isRel
1899}
1900
1901func maybeRelErr(basePath string, targetPath string) (string, bool, error) {
Colin Cross43f08db2018-11-12 10:13:39 -08001902 // filepath.Rel returns an error if one path is absolute and the other is not, handle that case first.
1903 if filepath.IsAbs(basePath) != filepath.IsAbs(targetPath) {
Dan Willemsen633c5022019-04-12 11:11:38 -07001904 return "", false, nil
Colin Cross43f08db2018-11-12 10:13:39 -08001905 }
1906 rel, err := filepath.Rel(basePath, targetPath)
1907 if err != nil {
Dan Willemsen633c5022019-04-12 11:11:38 -07001908 return "", false, err
Colin Cross43f08db2018-11-12 10:13:39 -08001909 } else if rel == ".." || strings.HasPrefix(rel, "../") || strings.HasPrefix(rel, "/") {
Dan Willemsen633c5022019-04-12 11:11:38 -07001910 return "", false, nil
Colin Cross43f08db2018-11-12 10:13:39 -08001911 }
Dan Willemsen633c5022019-04-12 11:11:38 -07001912 return rel, true, nil
Colin Cross43f08db2018-11-12 10:13:39 -08001913}
Colin Cross988414c2020-01-11 01:11:46 +00001914
1915// Writes a file to the output directory. Attempting to write directly to the output directory
1916// will fail due to the sandbox of the soong_build process.
1917func WriteFileToOutputDir(path WritablePath, data []byte, perm os.FileMode) error {
1918 return ioutil.WriteFile(absolutePath(path.String()), data, perm)
1919}
1920
Liz Kammer2dd9ca42020-11-25 16:06:39 -08001921func RemoveAllOutputDir(path WritablePath) error {
1922 return os.RemoveAll(absolutePath(path.String()))
1923}
1924
1925func CreateOutputDirIfNonexistent(path WritablePath, perm os.FileMode) error {
1926 dir := absolutePath(path.String())
1927 if _, err := os.Stat(dir); os.IsNotExist(err) {
1928 return os.MkdirAll(dir, os.ModePerm)
1929 } else {
1930 return err
1931 }
1932}
1933
Colin Cross988414c2020-01-11 01:11:46 +00001934func absolutePath(path string) string {
1935 if filepath.IsAbs(path) {
1936 return path
1937 }
1938 return filepath.Join(absSrcDir, path)
1939}
Chris Parsons216e10a2020-07-09 17:12:52 -04001940
1941// A DataPath represents the path of a file to be used as data, for example
1942// a test library to be installed alongside a test.
1943// The data file should be installed (copied from `<SrcPath>`) to
1944// `<install_root>/<RelativeInstallPath>/<filename>`, or
1945// `<install_root>/<filename>` if RelativeInstallPath is empty.
1946type DataPath struct {
1947 // The path of the data file that should be copied into the data directory
1948 SrcPath Path
1949 // The install path of the data file, relative to the install root.
1950 RelativeInstallPath string
1951}
Colin Crossdcf71b22021-02-01 13:59:03 -08001952
1953// PathsIfNonNil returns a Paths containing only the non-nil input arguments.
1954func PathsIfNonNil(paths ...Path) Paths {
1955 if len(paths) == 0 {
1956 // Fast path for empty argument list
1957 return nil
1958 } else if len(paths) == 1 {
1959 // Fast path for a single argument
1960 if paths[0] != nil {
1961 return paths
1962 } else {
1963 return nil
1964 }
1965 }
1966 ret := make(Paths, 0, len(paths))
1967 for _, path := range paths {
1968 if path != nil {
1969 ret = append(ret, path)
1970 }
1971 }
1972 if len(ret) == 0 {
1973 return nil
1974 }
1975 return ret
1976}