blob: babf48c980b35ebc9620340057504c007d3d56f2 [file] [log] [blame]
Colin Cross3f40fa42015-01-30 17:27:36 -08001// Copyright 2015 Google Inc. All rights reserved.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
Colin Cross635c3b02016-05-18 15:37:25 -070015package android
Colin Cross3f40fa42015-01-30 17:27:36 -080016
17import (
Liz Kammer356f7d42021-01-26 09:18:53 -050018 "android/soong/bazel"
Colin Cross6e18ca42015-07-14 18:55:36 -070019 "fmt"
Colin Cross988414c2020-01-11 01:11:46 +000020 "io/ioutil"
21 "os"
Colin Cross6a745c62015-06-16 16:38:10 -070022 "path/filepath"
Dan Willemsen34cc69e2015-09-23 15:26:20 -070023 "reflect"
Colin Cross5e6cfbe2017-11-03 15:20:35 -070024 "sort"
Dan Willemsen34cc69e2015-09-23 15:26:20 -070025 "strings"
26
27 "github.com/google/blueprint"
28 "github.com/google/blueprint/pathtools"
Colin Cross3f40fa42015-01-30 17:27:36 -080029)
30
Colin Cross988414c2020-01-11 01:11:46 +000031var absSrcDir string
32
Dan Willemsen34cc69e2015-09-23 15:26:20 -070033// PathContext is the subset of a (Module|Singleton)Context required by the
34// Path methods.
35type PathContext interface {
Colin Crossaabf6792017-11-29 00:27:14 -080036 Config() Config
Dan Willemsen7b310ee2015-12-18 15:11:17 -080037 AddNinjaFileDeps(deps ...string)
Colin Cross3f40fa42015-01-30 17:27:36 -080038}
39
Colin Cross7f19f372016-11-01 11:10:25 -070040type PathGlobContext interface {
41 GlobWithDeps(globPattern string, excludes []string) ([]string, error)
42}
43
Colin Crossaabf6792017-11-29 00:27:14 -080044var _ PathContext = SingletonContext(nil)
45var _ PathContext = ModuleContext(nil)
Dan Willemsen34cc69e2015-09-23 15:26:20 -070046
Ulya Trafimovich8640ab92020-05-11 18:06:15 +010047// "Null" path context is a minimal path context for a given config.
48type NullPathContext struct {
49 config Config
50}
51
52func (NullPathContext) AddNinjaFileDeps(...string) {}
53func (ctx NullPathContext) Config() Config { return ctx.config }
54
Liz Kammera830f3a2020-11-10 10:50:34 -080055// EarlyModulePathContext is a subset of EarlyModuleContext methods required by the
56// Path methods. These path methods can be called before any mutators have run.
57type EarlyModulePathContext interface {
58 PathContext
59 PathGlobContext
60
61 ModuleDir() string
62 ModuleErrorf(fmt string, args ...interface{})
63}
64
65var _ EarlyModulePathContext = ModuleContext(nil)
66
67// Glob globs files and directories matching globPattern relative to ModuleDir(),
68// paths in the excludes parameter will be omitted.
69func Glob(ctx EarlyModulePathContext, globPattern string, excludes []string) Paths {
70 ret, err := ctx.GlobWithDeps(globPattern, excludes)
71 if err != nil {
72 ctx.ModuleErrorf("glob: %s", err.Error())
73 }
74 return pathsForModuleSrcFromFullPath(ctx, ret, true)
75}
76
77// GlobFiles globs *only* files (not directories) matching globPattern relative to ModuleDir().
78// Paths in the excludes parameter will be omitted.
79func GlobFiles(ctx EarlyModulePathContext, globPattern string, excludes []string) Paths {
80 ret, err := ctx.GlobWithDeps(globPattern, excludes)
81 if err != nil {
82 ctx.ModuleErrorf("glob: %s", err.Error())
83 }
84 return pathsForModuleSrcFromFullPath(ctx, ret, false)
85}
86
87// ModuleWithDepsPathContext is a subset of *ModuleContext methods required by
88// the Path methods that rely on module dependencies having been resolved.
89type ModuleWithDepsPathContext interface {
90 EarlyModulePathContext
91 GetDirectDepWithTag(name string, tag blueprint.DependencyTag) blueprint.Module
92}
93
94// ModuleMissingDepsPathContext is a subset of *ModuleContext methods required by
95// the Path methods that rely on module dependencies having been resolved and ability to report
96// missing dependency errors.
97type ModuleMissingDepsPathContext interface {
98 ModuleWithDepsPathContext
99 AddMissingDependencies(missingDeps []string)
100}
101
Dan Willemsen00269f22017-07-06 16:59:48 -0700102type ModuleInstallPathContext interface {
Colin Cross0ea8ba82019-06-06 14:33:29 -0700103 BaseModuleContext
Dan Willemsen00269f22017-07-06 16:59:48 -0700104
105 InstallInData() bool
Jaewoong Jung0949f312019-09-11 10:25:18 -0700106 InstallInTestcases() bool
Dan Willemsen00269f22017-07-06 16:59:48 -0700107 InstallInSanitizerDir() bool
Yifan Hong1b3348d2020-01-21 15:53:22 -0800108 InstallInRamdisk() bool
Yifan Hong60e0cfb2020-10-21 15:17:56 -0700109 InstallInVendorRamdisk() bool
Jiyong Parkf9332f12018-02-01 00:54:12 +0900110 InstallInRecovery() bool
Colin Cross90ba5f42019-10-02 11:10:58 -0700111 InstallInRoot() bool
Colin Cross607d8582019-07-29 16:44:46 -0700112 InstallBypassMake() bool
Jiyong Park87788b52020-09-01 12:37:45 +0900113 InstallForceOS() (*OsType, *ArchType)
Dan Willemsen00269f22017-07-06 16:59:48 -0700114}
115
116var _ ModuleInstallPathContext = ModuleContext(nil)
117
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700118// errorfContext is the interface containing the Errorf method matching the
119// Errorf method in blueprint.SingletonContext.
120type errorfContext interface {
121 Errorf(format string, args ...interface{})
Colin Cross3f40fa42015-01-30 17:27:36 -0800122}
123
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700124var _ errorfContext = blueprint.SingletonContext(nil)
125
126// moduleErrorf is the interface containing the ModuleErrorf method matching
127// the ModuleErrorf method in blueprint.ModuleContext.
128type moduleErrorf interface {
129 ModuleErrorf(format string, args ...interface{})
Colin Cross3f40fa42015-01-30 17:27:36 -0800130}
131
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700132var _ moduleErrorf = blueprint.ModuleContext(nil)
133
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700134// reportPathError will register an error with the attached context. It
135// attempts ctx.ModuleErrorf for a better error message first, then falls
136// back to ctx.Errorf.
Colin Cross1ccfcc32018-02-22 13:54:26 -0800137func reportPathError(ctx PathContext, err error) {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +0100138 ReportPathErrorf(ctx, "%s", err.Error())
Colin Cross1ccfcc32018-02-22 13:54:26 -0800139}
140
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +0100141// ReportPathErrorf will register an error with the attached context. It
Colin Cross1ccfcc32018-02-22 13:54:26 -0800142// attempts ctx.ModuleErrorf for a better error message first, then falls
143// back to ctx.Errorf.
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +0100144func ReportPathErrorf(ctx PathContext, format string, args ...interface{}) {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700145 if mctx, ok := ctx.(moduleErrorf); ok {
146 mctx.ModuleErrorf(format, args...)
147 } else if ectx, ok := ctx.(errorfContext); ok {
148 ectx.Errorf(format, args...)
149 } else {
150 panic(fmt.Sprintf(format, args...))
Colin Crossf2298272015-05-12 11:36:53 -0700151 }
152}
153
Colin Cross5e708052019-08-06 13:59:50 -0700154func pathContextName(ctx PathContext, module blueprint.Module) string {
155 if x, ok := ctx.(interface{ ModuleName(blueprint.Module) string }); ok {
156 return x.ModuleName(module)
157 } else if x, ok := ctx.(interface{ OtherModuleName(blueprint.Module) string }); ok {
158 return x.OtherModuleName(module)
159 }
160 return "unknown"
161}
162
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700163type Path interface {
164 // Returns the path in string form
165 String() string
166
Colin Cross4f6fc9c2016-10-26 10:05:25 -0700167 // Ext returns the extension of the last element of the path
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700168 Ext() string
Colin Cross4f6fc9c2016-10-26 10:05:25 -0700169
170 // Base returns the last element of the path
171 Base() string
Colin Crossfaeb7aa2017-02-01 14:12:44 -0800172
173 // Rel returns the portion of the path relative to the directory it was created from. For
174 // example, Rel on a PathsForModuleSrc would return the path relative to the module source
Colin Cross0db55682017-12-05 15:36:55 -0800175 // directory, and OutputPath.Join("foo").Rel() would return "foo".
Colin Crossfaeb7aa2017-02-01 14:12:44 -0800176 Rel() string
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700177}
178
179// WritablePath is a type of path that can be used as an output for build rules.
180type WritablePath interface {
181 Path
182
Paul Duffin9b478b02019-12-10 13:41:51 +0000183 // return the path to the build directory.
184 buildDir() string
185
Jeff Gaston734e3802017-04-10 15:47:24 -0700186 // the writablePath method doesn't directly do anything,
187 // but it allows a struct to distinguish between whether or not it implements the WritablePath interface
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700188 writablePath()
Hans MÃ¥nssond3f2bd72020-11-27 12:37:28 +0100189
190 ReplaceExtension(ctx PathContext, ext string) OutputPath
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700191}
192
193type genPathProvider interface {
Liz Kammera830f3a2020-11-10 10:50:34 -0800194 genPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleGenPath
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700195}
196type objPathProvider interface {
Liz Kammera830f3a2020-11-10 10:50:34 -0800197 objPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleObjPath
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700198}
199type resPathProvider interface {
Liz Kammera830f3a2020-11-10 10:50:34 -0800200 resPathWithName(ctx ModuleOutPathContext, name string) ModuleResPath
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700201}
202
203// GenPathWithExt derives a new file path in ctx's generated sources directory
204// from the current path, but with the new extension.
Liz Kammera830f3a2020-11-10 10:50:34 -0800205func GenPathWithExt(ctx ModuleOutPathContext, subdir string, p Path, ext string) ModuleGenPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700206 if path, ok := p.(genPathProvider); ok {
Dan Willemsen21ec4902016-11-02 20:43:13 -0700207 return path.genPathWithExt(ctx, subdir, ext)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700208 }
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +0100209 ReportPathErrorf(ctx, "Tried to create generated file from unsupported path: %s(%s)", reflect.TypeOf(p).Name(), p)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700210 return PathForModuleGen(ctx)
211}
212
213// ObjPathWithExt derives a new file path in ctx's object directory from the
214// current path, but with the new extension.
Liz Kammera830f3a2020-11-10 10:50:34 -0800215func ObjPathWithExt(ctx ModuleOutPathContext, subdir string, p Path, ext string) ModuleObjPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700216 if path, ok := p.(objPathProvider); ok {
217 return path.objPathWithExt(ctx, subdir, ext)
218 }
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +0100219 ReportPathErrorf(ctx, "Tried to create object file from unsupported path: %s (%s)", reflect.TypeOf(p).Name(), p)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700220 return PathForModuleObj(ctx)
221}
222
223// ResPathWithName derives a new path in ctx's output resource directory, using
224// the current path to create the directory name, and the `name` argument for
225// the filename.
Liz Kammera830f3a2020-11-10 10:50:34 -0800226func ResPathWithName(ctx ModuleOutPathContext, p Path, name string) ModuleResPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700227 if path, ok := p.(resPathProvider); ok {
228 return path.resPathWithName(ctx, name)
229 }
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +0100230 ReportPathErrorf(ctx, "Tried to create res file from unsupported path: %s (%s)", reflect.TypeOf(p).Name(), p)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700231 return PathForModuleRes(ctx)
232}
233
234// OptionalPath is a container that may or may not contain a valid Path.
235type OptionalPath struct {
236 valid bool
237 path Path
238}
239
240// OptionalPathForPath returns an OptionalPath containing the path.
241func OptionalPathForPath(path Path) OptionalPath {
242 if path == nil {
243 return OptionalPath{}
244 }
245 return OptionalPath{valid: true, path: path}
246}
247
248// Valid returns whether there is a valid path
249func (p OptionalPath) Valid() bool {
250 return p.valid
251}
252
253// Path returns the Path embedded in this OptionalPath. You must be sure that
254// there is a valid path, since this method will panic if there is not.
255func (p OptionalPath) Path() Path {
256 if !p.valid {
257 panic("Requesting an invalid path")
258 }
259 return p.path
260}
261
262// String returns the string version of the Path, or "" if it isn't valid.
263func (p OptionalPath) String() string {
264 if p.valid {
265 return p.path.String()
266 } else {
267 return ""
Colin Crossf2298272015-05-12 11:36:53 -0700268 }
269}
Colin Cross6e18ca42015-07-14 18:55:36 -0700270
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700271// Paths is a slice of Path objects, with helpers to operate on the collection.
272type Paths []Path
273
Jingwen Chen40fd90a2020-06-15 05:24:19 +0000274func (paths Paths) containsPath(path Path) bool {
275 for _, p := range paths {
276 if p == path {
277 return true
278 }
279 }
280 return false
281}
282
Liz Kammer7aa52882021-02-11 09:16:14 -0500283// PathsForSource returns Paths rooted from SrcDir, *not* rooted from the module's local source
284// directory
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700285func PathsForSource(ctx PathContext, paths []string) Paths {
286 ret := make(Paths, len(paths))
287 for i, path := range paths {
288 ret[i] = PathForSource(ctx, path)
289 }
290 return ret
291}
292
Liz Kammer7aa52882021-02-11 09:16:14 -0500293// ExistentPathsForSources returns a list of Paths rooted from SrcDir, *not* rooted from the
294// module's local source directory, that are found in the tree. If any are not found, they are
295// omitted from the list, and dependencies are added so that we're re-run when they are added.
Colin Cross32f38982018-02-22 11:47:25 -0800296func ExistentPathsForSources(ctx PathContext, paths []string) Paths {
Dan Willemsen7b310ee2015-12-18 15:11:17 -0800297 ret := make(Paths, 0, len(paths))
298 for _, path := range paths {
Colin Cross32f38982018-02-22 11:47:25 -0800299 p := ExistentPathForSource(ctx, path)
Dan Willemsen7b310ee2015-12-18 15:11:17 -0800300 if p.Valid() {
301 ret = append(ret, p.Path())
302 }
303 }
304 return ret
305}
306
Colin Cross41955e82019-05-29 14:40:35 -0700307// PathsForModuleSrc returns Paths rooted from the module's local source directory. It expands globs, references to
308// SourceFileProducer modules using the ":name" syntax, and references to OutputFileProducer modules using the
309// ":name{.tag}" syntax. Properties passed as the paths argument must have been annotated with struct tag
310// `android:"path"` so that dependencies on SourceFileProducer modules will have already been handled by the
311// path_properties mutator. If ctx.Config().AllowMissingDependencies() is true then any missing SourceFileProducer or
312// OutputFileProducer dependencies will cause the module to be marked as having missing dependencies.
Liz Kammera830f3a2020-11-10 10:50:34 -0800313func PathsForModuleSrc(ctx ModuleMissingDepsPathContext, paths []string) Paths {
Colin Cross8a497952019-03-05 22:25:09 -0800314 return PathsForModuleSrcExcludes(ctx, paths, nil)
315}
316
Colin Crossba71a3f2019-03-18 12:12:48 -0700317// PathsForModuleSrcExcludes returns Paths rooted from the module's local source directory, excluding paths listed in
Colin Cross41955e82019-05-29 14:40:35 -0700318// the excludes arguments. It expands globs, references to SourceFileProducer modules using the ":name" syntax, and
319// references to OutputFileProducer modules using the ":name{.tag}" syntax. Properties passed as the paths or excludes
320// argument must have been annotated with struct tag `android:"path"` so that dependencies on SourceFileProducer modules
321// will have already been handled by the path_properties mutator. If ctx.Config().AllowMissingDependencies() is
Paul Duffin036cace2019-07-25 14:44:56 +0100322// true then any missing SourceFileProducer or OutputFileProducer dependencies will cause the module to be marked as
Colin Cross41955e82019-05-29 14:40:35 -0700323// having missing dependencies.
Liz Kammera830f3a2020-11-10 10:50:34 -0800324func PathsForModuleSrcExcludes(ctx ModuleMissingDepsPathContext, paths, excludes []string) Paths {
Colin Crossba71a3f2019-03-18 12:12:48 -0700325 ret, missingDeps := PathsAndMissingDepsForModuleSrcExcludes(ctx, paths, excludes)
326 if ctx.Config().AllowMissingDependencies() {
327 ctx.AddMissingDependencies(missingDeps)
328 } else {
329 for _, m := range missingDeps {
330 ctx.ModuleErrorf(`missing dependency on %q, is the property annotated with android:"path"?`, m)
331 }
332 }
333 return ret
334}
335
Liz Kammer356f7d42021-01-26 09:18:53 -0500336// A subset of the ModuleContext methods which are sufficient to resolve references to paths/deps in
337// order to form a Bazel-compatible label for conversion.
338type BazelConversionPathContext interface {
339 EarlyModulePathContext
340
341 GetDirectDep(name string) (blueprint.Module, blueprint.DependencyTag)
Liz Kammerbdc60992021-02-24 16:55:11 -0500342 Module() Module
Liz Kammer356f7d42021-01-26 09:18:53 -0500343 OtherModuleName(m blueprint.Module) string
344 OtherModuleDir(m blueprint.Module) string
345}
346
347// BazelLabelForModuleDeps returns a Bazel-compatible label for the requested modules which
348// correspond to dependencies on the module within the given ctx.
349func BazelLabelForModuleDeps(ctx BazelConversionPathContext, modules []string) bazel.LabelList {
350 var labels bazel.LabelList
351 for _, module := range modules {
352 bpText := module
353 if m := SrcIsModule(module); m == "" {
354 module = ":" + module
355 }
356 if m, t := SrcIsModuleWithTag(module); m != "" {
357 l := getOtherModuleLabel(ctx, m, t)
358 l.Bp_text = bpText
359 labels.Includes = append(labels.Includes, l)
360 } else {
361 ctx.ModuleErrorf("%q, is not a module reference", module)
362 }
363 }
364 return labels
365}
366
367// BazelLabelForModuleSrc returns bazel.LabelList with paths rooted from the module's local source
368// directory. It expands globs, and resolves references to modules using the ":name" syntax to
369// bazel-compatible labels. Properties passed as the paths or excludes argument must have been
370// annotated with struct tag `android:"path"` so that dependencies on other modules will have
371// already been handled by the path_properties mutator.
372func BazelLabelForModuleSrc(ctx BazelConversionPathContext, paths []string) bazel.LabelList {
373 return BazelLabelForModuleSrcExcludes(ctx, paths, []string(nil))
374}
375
376// BazelLabelForModuleSrcExcludes returns bazel.LabelList with paths rooted from the module's local
377// source directory, excluding labels included in the excludes argument. It expands globs, and
378// resolves references to modules using the ":name" syntax to bazel-compatible labels. Properties
379// passed as the paths or excludes argument must have been annotated with struct tag
380// `android:"path"` so that dependencies on other modules will have already been handled by the
381// path_properties mutator.
382func BazelLabelForModuleSrcExcludes(ctx BazelConversionPathContext, paths, excludes []string) bazel.LabelList {
383 excludeLabels := expandSrcsForBazel(ctx, excludes, []string(nil))
384 excluded := make([]string, 0, len(excludeLabels.Includes))
385 for _, e := range excludeLabels.Includes {
386 excluded = append(excluded, e.Label)
387 }
388 labels := expandSrcsForBazel(ctx, paths, excluded)
389 labels.Excludes = excludeLabels.Includes
390 return labels
391}
392
393// expandSrcsForBazel returns bazel.LabelList with paths rooted from the module's local
394// source directory, excluding labels included in the excludes argument. It expands globs, and
395// resolves references to modules using the ":name" syntax to bazel-compatible labels. Properties
396// passed as the paths or excludes argument must have been annotated with struct tag
397// `android:"path"` so that dependencies on other modules will have already been handled by the
398// path_properties mutator.
399func expandSrcsForBazel(ctx BazelConversionPathContext, paths, expandedExcludes []string) bazel.LabelList {
Liz Kammerebfcf672021-02-16 15:00:05 -0500400 if paths == nil {
401 return bazel.LabelList{}
402 }
Liz Kammer356f7d42021-01-26 09:18:53 -0500403 labels := bazel.LabelList{
404 Includes: []bazel.Label{},
405 }
406 for _, p := range paths {
407 if m, tag := SrcIsModuleWithTag(p); m != "" {
408 l := getOtherModuleLabel(ctx, m, tag)
409 if !InList(l.Label, expandedExcludes) {
410 l.Bp_text = fmt.Sprintf(":%s", m)
411 labels.Includes = append(labels.Includes, l)
412 }
413 } else {
414 var expandedPaths []bazel.Label
415 if pathtools.IsGlob(p) {
416 globbedPaths := GlobFiles(ctx, pathForModuleSrc(ctx, p).String(), expandedExcludes)
417 globbedPaths = PathsWithModuleSrcSubDir(ctx, globbedPaths, "")
418 for _, path := range globbedPaths {
419 s := path.Rel()
420 expandedPaths = append(expandedPaths, bazel.Label{Label: s})
421 }
422 } else {
423 if !InList(p, expandedExcludes) {
424 expandedPaths = append(expandedPaths, bazel.Label{Label: p})
425 }
426 }
427 labels.Includes = append(labels.Includes, expandedPaths...)
428 }
429 }
430 return labels
431}
432
433// getOtherModuleLabel returns a bazel.Label for the given dependency/tag combination for the
434// module. The label will be relative to the current directory if appropriate. The dependency must
435// already be resolved by either deps mutator or path deps mutator.
436func getOtherModuleLabel(ctx BazelConversionPathContext, dep, tag string) bazel.Label {
437 m, _ := ctx.GetDirectDep(dep)
Liz Kammerbdc60992021-02-24 16:55:11 -0500438 otherLabel := bazelModuleLabel(ctx, m, tag)
439 label := bazelModuleLabel(ctx, ctx.Module(), "")
440 if samePackage(label, otherLabel) {
441 otherLabel = bazelShortLabel(otherLabel)
Liz Kammer356f7d42021-01-26 09:18:53 -0500442 }
Liz Kammerbdc60992021-02-24 16:55:11 -0500443
444 return bazel.Label{
445 Label: otherLabel,
446 }
447}
448
449func bazelModuleLabel(ctx BazelConversionPathContext, module blueprint.Module, tag string) string {
450 // TODO(b/165114590): Convert tag (":name{.tag}") to corresponding Bazel implicit output targets.
451 b, ok := module.(Bazelable)
452 // TODO(b/181155349): perhaps return an error here if the module can't be/isn't being converted
453 if !ok || !b.ConvertedToBazel() {
454 return bp2buildModuleLabel(ctx, module)
455 }
456 return b.GetBazelLabel(ctx, module)
457}
458
459func bazelShortLabel(label string) string {
460 i := strings.Index(label, ":")
461 return label[i:]
462}
463
464func bazelPackage(label string) string {
465 i := strings.Index(label, ":")
466 return label[0:i]
467}
468
469func samePackage(label1, label2 string) bool {
470 return bazelPackage(label1) == bazelPackage(label2)
471}
472
473func bp2buildModuleLabel(ctx BazelConversionPathContext, module blueprint.Module) string {
474 moduleName := ctx.OtherModuleName(module)
475 moduleDir := ctx.OtherModuleDir(module)
476 return fmt.Sprintf("//%s:%s", moduleDir, moduleName)
Liz Kammer356f7d42021-01-26 09:18:53 -0500477}
478
Ulya Trafimovich4d2eeed2019-11-08 10:54:21 +0000479// OutputPaths is a slice of OutputPath objects, with helpers to operate on the collection.
480type OutputPaths []OutputPath
481
482// Paths returns the OutputPaths as a Paths
483func (p OutputPaths) Paths() Paths {
484 if p == nil {
485 return nil
486 }
487 ret := make(Paths, len(p))
488 for i, path := range p {
489 ret[i] = path
490 }
491 return ret
492}
493
494// Strings returns the string forms of the writable paths.
495func (p OutputPaths) Strings() []string {
496 if p == nil {
497 return nil
498 }
499 ret := make([]string, len(p))
500 for i, path := range p {
501 ret[i] = path.String()
502 }
503 return ret
504}
505
Liz Kammera830f3a2020-11-10 10:50:34 -0800506// Expands Paths to a SourceFileProducer or OutputFileProducer module dependency referenced via ":name" or ":name{.tag}" syntax.
507// If the dependency is not found, a missingErrorDependency is returned.
508// If the module dependency is not a SourceFileProducer or OutputFileProducer, appropriate errors will be returned.
509func getPathsFromModuleDep(ctx ModuleWithDepsPathContext, path, moduleName, tag string) (Paths, error) {
510 module := ctx.GetDirectDepWithTag(moduleName, sourceOrOutputDepTag(tag))
511 if module == nil {
512 return nil, missingDependencyError{[]string{moduleName}}
513 }
Colin Crossfa65cee2021-03-22 17:05:59 -0700514 if aModule, ok := module.(Module); ok && !aModule.Enabled() {
515 return nil, missingDependencyError{[]string{moduleName}}
516 }
Liz Kammera830f3a2020-11-10 10:50:34 -0800517 if outProducer, ok := module.(OutputFileProducer); ok {
518 outputFiles, err := outProducer.OutputFiles(tag)
519 if err != nil {
520 return nil, fmt.Errorf("path dependency %q: %s", path, err)
521 }
522 return outputFiles, nil
523 } else if tag != "" {
524 return nil, fmt.Errorf("path dependency %q is not an output file producing module", path)
525 } else if srcProducer, ok := module.(SourceFileProducer); ok {
526 return srcProducer.Srcs(), nil
527 } else {
528 return nil, fmt.Errorf("path dependency %q is not a source file producing module", path)
529 }
530}
531
Colin Crossba71a3f2019-03-18 12:12:48 -0700532// PathsAndMissingDepsForModuleSrcExcludes returns Paths rooted from the module's local source directory, excluding
Colin Cross41955e82019-05-29 14:40:35 -0700533// paths listed in the excludes arguments, and a list of missing dependencies. It expands globs, references to
534// SourceFileProducer modules using the ":name" syntax, and references to OutputFileProducer modules using the
535// ":name{.tag}" syntax. Properties passed as the paths or excludes argument must have been annotated with struct tag
536// `android:"path"` so that dependencies on SourceFileProducer modules will have already been handled by the
537// path_properties mutator. If ctx.Config().AllowMissingDependencies() is true then any missing SourceFileProducer or
538// OutputFileProducer dependencies will be returned, and they will NOT cause the module to be marked as having missing
539// dependencies.
Liz Kammera830f3a2020-11-10 10:50:34 -0800540func PathsAndMissingDepsForModuleSrcExcludes(ctx ModuleWithDepsPathContext, paths, excludes []string) (Paths, []string) {
Colin Cross8a497952019-03-05 22:25:09 -0800541 prefix := pathForModuleSrc(ctx).String()
542
543 var expandedExcludes []string
544 if excludes != nil {
545 expandedExcludes = make([]string, 0, len(excludes))
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700546 }
Colin Cross8a497952019-03-05 22:25:09 -0800547
Colin Crossba71a3f2019-03-18 12:12:48 -0700548 var missingExcludeDeps []string
549
Colin Cross8a497952019-03-05 22:25:09 -0800550 for _, e := range excludes {
Colin Cross41955e82019-05-29 14:40:35 -0700551 if m, t := SrcIsModuleWithTag(e); m != "" {
Liz Kammera830f3a2020-11-10 10:50:34 -0800552 modulePaths, err := getPathsFromModuleDep(ctx, e, m, t)
553 if m, ok := err.(missingDependencyError); ok {
554 missingExcludeDeps = append(missingExcludeDeps, m.missingDeps...)
555 } else if err != nil {
556 reportPathError(ctx, err)
Colin Cross8a497952019-03-05 22:25:09 -0800557 } else {
Liz Kammera830f3a2020-11-10 10:50:34 -0800558 expandedExcludes = append(expandedExcludes, modulePaths.Strings()...)
Colin Cross8a497952019-03-05 22:25:09 -0800559 }
560 } else {
561 expandedExcludes = append(expandedExcludes, filepath.Join(prefix, e))
562 }
563 }
564
565 if paths == nil {
Colin Crossba71a3f2019-03-18 12:12:48 -0700566 return nil, missingExcludeDeps
Colin Cross8a497952019-03-05 22:25:09 -0800567 }
568
Colin Crossba71a3f2019-03-18 12:12:48 -0700569 var missingDeps []string
570
Colin Cross8a497952019-03-05 22:25:09 -0800571 expandedSrcFiles := make(Paths, 0, len(paths))
572 for _, s := range paths {
573 srcFiles, err := expandOneSrcPath(ctx, s, expandedExcludes)
574 if depErr, ok := err.(missingDependencyError); ok {
Colin Crossba71a3f2019-03-18 12:12:48 -0700575 missingDeps = append(missingDeps, depErr.missingDeps...)
Colin Cross8a497952019-03-05 22:25:09 -0800576 } else if err != nil {
577 reportPathError(ctx, err)
578 }
579 expandedSrcFiles = append(expandedSrcFiles, srcFiles...)
580 }
Colin Crossba71a3f2019-03-18 12:12:48 -0700581
582 return expandedSrcFiles, append(missingDeps, missingExcludeDeps...)
Colin Cross8a497952019-03-05 22:25:09 -0800583}
584
585type missingDependencyError struct {
586 missingDeps []string
587}
588
589func (e missingDependencyError) Error() string {
590 return "missing dependencies: " + strings.Join(e.missingDeps, ", ")
591}
592
Liz Kammera830f3a2020-11-10 10:50:34 -0800593// Expands one path string to Paths rooted from the module's local source
594// directory, excluding those listed in the expandedExcludes.
595// Expands globs, references to SourceFileProducer or OutputFileProducer modules using the ":name" and ":name{.tag}" syntax.
596func expandOneSrcPath(ctx ModuleWithDepsPathContext, sPath string, expandedExcludes []string) (Paths, error) {
Jooyung Han7607dd32020-07-05 10:23:14 +0900597 excludePaths := func(paths Paths) Paths {
598 if len(expandedExcludes) == 0 {
599 return paths
600 }
601 remainder := make(Paths, 0, len(paths))
602 for _, p := range paths {
603 if !InList(p.String(), expandedExcludes) {
604 remainder = append(remainder, p)
605 }
606 }
607 return remainder
608 }
Liz Kammera830f3a2020-11-10 10:50:34 -0800609 if m, t := SrcIsModuleWithTag(sPath); m != "" {
610 modulePaths, err := getPathsFromModuleDep(ctx, sPath, m, t)
611 if err != nil {
612 return nil, err
Colin Cross8a497952019-03-05 22:25:09 -0800613 } else {
Liz Kammera830f3a2020-11-10 10:50:34 -0800614 return excludePaths(modulePaths), nil
Colin Cross8a497952019-03-05 22:25:09 -0800615 }
Liz Kammera830f3a2020-11-10 10:50:34 -0800616 } else if pathtools.IsGlob(sPath) {
617 paths := GlobFiles(ctx, pathForModuleSrc(ctx, sPath).String(), expandedExcludes)
Colin Cross8a497952019-03-05 22:25:09 -0800618 return PathsWithModuleSrcSubDir(ctx, paths, ""), nil
619 } else {
Liz Kammera830f3a2020-11-10 10:50:34 -0800620 p := pathForModuleSrc(ctx, sPath)
Colin Cross988414c2020-01-11 01:11:46 +0000621 if exists, _, err := ctx.Config().fs.Exists(p.String()); err != nil {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +0100622 ReportPathErrorf(ctx, "%s: %s", p, err.Error())
Pedro Loureiro5d190cc2021-02-15 15:41:33 +0000623 } else if !exists && !ctx.Config().TestAllowNonExistentPaths {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +0100624 ReportPathErrorf(ctx, "module source path %q does not exist", p)
Colin Cross8a497952019-03-05 22:25:09 -0800625 }
626
Jooyung Han7607dd32020-07-05 10:23:14 +0900627 if InList(p.String(), expandedExcludes) {
Colin Cross8a497952019-03-05 22:25:09 -0800628 return nil, nil
629 }
630 return Paths{p}, nil
631 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700632}
633
634// pathsForModuleSrcFromFullPath returns Paths rooted from the module's local
635// source directory, but strip the local source directory from the beginning of
Dan Willemsen540a78c2018-02-26 21:50:08 -0800636// each string. If incDirs is false, strip paths with a trailing '/' from the list.
Colin Crossfe4bc362018-09-12 10:02:13 -0700637// It intended for use in globs that only list files that exist, so it allows '$' in
638// filenames.
Liz Kammera830f3a2020-11-10 10:50:34 -0800639func pathsForModuleSrcFromFullPath(ctx EarlyModulePathContext, paths []string, incDirs bool) Paths {
Colin Cross6510f912017-11-29 00:27:14 -0800640 prefix := filepath.Join(ctx.Config().srcDir, ctx.ModuleDir()) + "/"
Colin Cross0f37af02017-09-27 17:42:05 -0700641 if prefix == "./" {
642 prefix = ""
643 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700644 ret := make(Paths, 0, len(paths))
645 for _, p := range paths {
Dan Willemsen540a78c2018-02-26 21:50:08 -0800646 if !incDirs && strings.HasSuffix(p, "/") {
647 continue
648 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700649 path := filepath.Clean(p)
650 if !strings.HasPrefix(path, prefix) {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +0100651 ReportPathErrorf(ctx, "Path %q is not in module source directory %q", p, prefix)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700652 continue
653 }
Colin Crosse3924e12018-08-15 20:18:53 -0700654
Colin Crossfe4bc362018-09-12 10:02:13 -0700655 srcPath, err := safePathForSource(ctx, ctx.ModuleDir(), path[len(prefix):])
Colin Crosse3924e12018-08-15 20:18:53 -0700656 if err != nil {
657 reportPathError(ctx, err)
658 continue
659 }
660
Colin Cross07e51612019-03-05 12:46:40 -0800661 srcPath.basePath.rel = srcPath.path
Colin Crosse3924e12018-08-15 20:18:53 -0700662
Colin Cross07e51612019-03-05 12:46:40 -0800663 ret = append(ret, srcPath)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700664 }
665 return ret
666}
667
Liz Kammera830f3a2020-11-10 10:50:34 -0800668// PathsWithOptionalDefaultForModuleSrc returns Paths rooted from the module's local source
669// directory. If input is nil, use the default if it exists. If input is empty, returns nil.
670func PathsWithOptionalDefaultForModuleSrc(ctx ModuleMissingDepsPathContext, input []string, def string) Paths {
Colin Cross0ddae7f2019-02-07 15:30:01 -0800671 if input != nil {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700672 return PathsForModuleSrc(ctx, input)
673 }
674 // Use Glob so that if the default doesn't exist, a dependency is added so that when it
675 // is created, we're run again.
Colin Cross6510f912017-11-29 00:27:14 -0800676 path := filepath.Join(ctx.Config().srcDir, ctx.ModuleDir(), def)
Liz Kammera830f3a2020-11-10 10:50:34 -0800677 return Glob(ctx, path, nil)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700678}
679
680// Strings returns the Paths in string form
681func (p Paths) Strings() []string {
682 if p == nil {
683 return nil
684 }
685 ret := make([]string, len(p))
686 for i, path := range p {
687 ret[i] = path.String()
688 }
689 return ret
690}
691
Colin Crossc0efd1d2020-07-03 11:56:24 -0700692func CopyOfPaths(paths Paths) Paths {
693 return append(Paths(nil), paths...)
694}
695
Colin Crossb6715442017-10-24 11:13:31 -0700696// FirstUniquePaths returns all unique elements of a Paths, keeping the first copy of each. It
697// modifies the Paths slice contents in place, and returns a subslice of the original slice.
Dan Willemsenfe92c962017-08-29 12:28:37 -0700698func FirstUniquePaths(list Paths) Paths {
Colin Cross27027c72020-02-28 15:34:17 -0800699 // 128 was chosen based on BenchmarkFirstUniquePaths results.
700 if len(list) > 128 {
701 return firstUniquePathsMap(list)
702 }
703 return firstUniquePathsList(list)
704}
705
Colin Crossc0efd1d2020-07-03 11:56:24 -0700706// SortedUniquePaths returns all unique elements of a Paths in sorted order. It modifies the
707// Paths slice contents in place, and returns a subslice of the original slice.
Jiyong Park33c77362020-05-29 22:00:16 +0900708func SortedUniquePaths(list Paths) Paths {
709 unique := FirstUniquePaths(list)
710 sort.Slice(unique, func(i, j int) bool {
711 return unique[i].String() < unique[j].String()
712 })
713 return unique
714}
715
Colin Cross27027c72020-02-28 15:34:17 -0800716func firstUniquePathsList(list Paths) Paths {
Dan Willemsenfe92c962017-08-29 12:28:37 -0700717 k := 0
718outer:
719 for i := 0; i < len(list); i++ {
720 for j := 0; j < k; j++ {
721 if list[i] == list[j] {
722 continue outer
723 }
724 }
725 list[k] = list[i]
726 k++
727 }
728 return list[:k]
729}
730
Colin Cross27027c72020-02-28 15:34:17 -0800731func firstUniquePathsMap(list Paths) Paths {
732 k := 0
733 seen := make(map[Path]bool, len(list))
734 for i := 0; i < len(list); i++ {
735 if seen[list[i]] {
736 continue
737 }
738 seen[list[i]] = true
739 list[k] = list[i]
740 k++
741 }
742 return list[:k]
743}
744
Colin Cross5d583952020-11-24 16:21:24 -0800745// FirstUniqueInstallPaths returns all unique elements of an InstallPaths, keeping the first copy of each. It
746// modifies the InstallPaths slice contents in place, and returns a subslice of the original slice.
747func FirstUniqueInstallPaths(list InstallPaths) InstallPaths {
748 // 128 was chosen based on BenchmarkFirstUniquePaths results.
749 if len(list) > 128 {
750 return firstUniqueInstallPathsMap(list)
751 }
752 return firstUniqueInstallPathsList(list)
753}
754
755func firstUniqueInstallPathsList(list InstallPaths) InstallPaths {
756 k := 0
757outer:
758 for i := 0; i < len(list); i++ {
759 for j := 0; j < k; j++ {
760 if list[i] == list[j] {
761 continue outer
762 }
763 }
764 list[k] = list[i]
765 k++
766 }
767 return list[:k]
768}
769
770func firstUniqueInstallPathsMap(list InstallPaths) InstallPaths {
771 k := 0
772 seen := make(map[InstallPath]bool, len(list))
773 for i := 0; i < len(list); i++ {
774 if seen[list[i]] {
775 continue
776 }
777 seen[list[i]] = true
778 list[k] = list[i]
779 k++
780 }
781 return list[:k]
782}
783
Colin Crossb6715442017-10-24 11:13:31 -0700784// LastUniquePaths returns all unique elements of a Paths, keeping the last copy of each. It
785// modifies the Paths slice contents in place, and returns a subslice of the original slice.
786func LastUniquePaths(list Paths) Paths {
787 totalSkip := 0
788 for i := len(list) - 1; i >= totalSkip; i-- {
789 skip := 0
790 for j := i - 1; j >= totalSkip; j-- {
791 if list[i] == list[j] {
792 skip++
793 } else {
794 list[j+skip] = list[j]
795 }
796 }
797 totalSkip += skip
798 }
799 return list[totalSkip:]
800}
801
Colin Crossa140bb02018-04-17 10:52:26 -0700802// ReversePaths returns a copy of a Paths in reverse order.
803func ReversePaths(list Paths) Paths {
804 if list == nil {
805 return nil
806 }
807 ret := make(Paths, len(list))
808 for i := range list {
809 ret[i] = list[len(list)-1-i]
810 }
811 return ret
812}
813
Jeff Gaston294356f2017-09-27 17:05:30 -0700814func indexPathList(s Path, list []Path) int {
815 for i, l := range list {
816 if l == s {
817 return i
818 }
819 }
820
821 return -1
822}
823
824func inPathList(p Path, list []Path) bool {
825 return indexPathList(p, list) != -1
826}
827
828func FilterPathList(list []Path, filter []Path) (remainder []Path, filtered []Path) {
Paul Duffin57b9e1d2019-12-13 00:03:35 +0000829 return FilterPathListPredicate(list, func(p Path) bool { return inPathList(p, filter) })
830}
831
832func FilterPathListPredicate(list []Path, predicate func(Path) bool) (remainder []Path, filtered []Path) {
Jeff Gaston294356f2017-09-27 17:05:30 -0700833 for _, l := range list {
Paul Duffin57b9e1d2019-12-13 00:03:35 +0000834 if predicate(l) {
Jeff Gaston294356f2017-09-27 17:05:30 -0700835 filtered = append(filtered, l)
836 } else {
837 remainder = append(remainder, l)
838 }
839 }
840
841 return
842}
843
Colin Cross93e85952017-08-15 13:34:18 -0700844// HasExt returns true of any of the paths have extension ext, otherwise false
845func (p Paths) HasExt(ext string) bool {
846 for _, path := range p {
847 if path.Ext() == ext {
848 return true
849 }
850 }
851
852 return false
853}
854
855// FilterByExt returns the subset of the paths that have extension ext
856func (p Paths) FilterByExt(ext string) Paths {
857 ret := make(Paths, 0, len(p))
858 for _, path := range p {
859 if path.Ext() == ext {
860 ret = append(ret, path)
861 }
862 }
863 return ret
864}
865
866// FilterOutByExt returns the subset of the paths that do not have extension ext
867func (p Paths) FilterOutByExt(ext string) Paths {
868 ret := make(Paths, 0, len(p))
869 for _, path := range p {
870 if path.Ext() != ext {
871 ret = append(ret, path)
872 }
873 }
874 return ret
875}
876
Colin Cross5e6cfbe2017-11-03 15:20:35 -0700877// DirectorySortedPaths is a slice of paths that are sorted such that all files in a directory
878// (including subdirectories) are in a contiguous subslice of the list, and can be found in
879// O(log(N)) time using a binary search on the directory prefix.
880type DirectorySortedPaths Paths
881
882func PathsToDirectorySortedPaths(paths Paths) DirectorySortedPaths {
883 ret := append(DirectorySortedPaths(nil), paths...)
884 sort.Slice(ret, func(i, j int) bool {
885 return ret[i].String() < ret[j].String()
886 })
887 return ret
888}
889
890// PathsInDirectory returns a subslice of the DirectorySortedPaths as a Paths that contains all entries
891// that are in the specified directory and its subdirectories.
892func (p DirectorySortedPaths) PathsInDirectory(dir string) Paths {
893 prefix := filepath.Clean(dir) + "/"
894 start := sort.Search(len(p), func(i int) bool {
895 return prefix < p[i].String()
896 })
897
898 ret := p[start:]
899
900 end := sort.Search(len(ret), func(i int) bool {
901 return !strings.HasPrefix(ret[i].String(), prefix)
902 })
903
904 ret = ret[:end]
905
906 return Paths(ret)
907}
908
Alex Humesky29e3bbe2020-11-20 21:30:13 -0500909// WritablePaths is a slice of WritablePath, used for multiple outputs.
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700910type WritablePaths []WritablePath
911
912// Strings returns the string forms of the writable paths.
913func (p WritablePaths) Strings() []string {
914 if p == nil {
915 return nil
916 }
917 ret := make([]string, len(p))
918 for i, path := range p {
919 ret[i] = path.String()
920 }
921 return ret
922}
923
Colin Cross3bc7ffa2017-11-22 16:19:37 -0800924// Paths returns the WritablePaths as a Paths
925func (p WritablePaths) Paths() Paths {
926 if p == nil {
927 return nil
928 }
929 ret := make(Paths, len(p))
930 for i, path := range p {
931 ret[i] = path
932 }
933 return ret
934}
935
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700936type basePath struct {
937 path string
938 config Config
Colin Crossfaeb7aa2017-02-01 14:12:44 -0800939 rel string
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700940}
941
942func (p basePath) Ext() string {
943 return filepath.Ext(p.path)
944}
945
Colin Cross4f6fc9c2016-10-26 10:05:25 -0700946func (p basePath) Base() string {
947 return filepath.Base(p.path)
948}
949
Colin Crossfaeb7aa2017-02-01 14:12:44 -0800950func (p basePath) Rel() string {
951 if p.rel != "" {
952 return p.rel
953 }
954 return p.path
955}
956
Colin Cross0875c522017-11-28 17:34:01 -0800957func (p basePath) String() string {
958 return p.path
959}
960
Colin Cross0db55682017-12-05 15:36:55 -0800961func (p basePath) withRel(rel string) basePath {
962 p.path = filepath.Join(p.path, rel)
963 p.rel = rel
964 return p
965}
966
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700967// SourcePath is a Path representing a file path rooted from SrcDir
968type SourcePath struct {
969 basePath
970}
971
972var _ Path = SourcePath{}
973
Colin Cross0db55682017-12-05 15:36:55 -0800974func (p SourcePath) withRel(rel string) SourcePath {
975 p.basePath = p.basePath.withRel(rel)
976 return p
977}
978
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700979// safePathForSource is for paths that we expect are safe -- only for use by go
980// code that is embedding ninja variables in paths
Colin Crossfe4bc362018-09-12 10:02:13 -0700981func safePathForSource(ctx PathContext, pathComponents ...string) (SourcePath, error) {
982 p, err := validateSafePath(pathComponents...)
Colin Crossaabf6792017-11-29 00:27:14 -0800983 ret := SourcePath{basePath{p, ctx.Config(), ""}}
Colin Crossfe4bc362018-09-12 10:02:13 -0700984 if err != nil {
985 return ret, err
986 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700987
Colin Cross7b3dcc32019-01-24 13:14:39 -0800988 // absolute path already checked by validateSafePath
989 if strings.HasPrefix(ret.String(), ctx.Config().buildDir) {
Mikhail Naganovab1f5182019-02-08 13:17:55 -0800990 return ret, fmt.Errorf("source path %q is in output", ret.String())
Colin Cross6e18ca42015-07-14 18:55:36 -0700991 }
992
Colin Crossfe4bc362018-09-12 10:02:13 -0700993 return ret, err
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700994}
995
Colin Cross192e97a2018-02-22 14:21:02 -0800996// pathForSource creates a SourcePath from pathComponents, but does not check that it exists.
997func pathForSource(ctx PathContext, pathComponents ...string) (SourcePath, error) {
Colin Crossc48c1432018-02-23 07:09:01 +0000998 p, err := validatePath(pathComponents...)
999 ret := SourcePath{basePath{p, ctx.Config(), ""}}
Colin Cross94a32102018-02-22 14:21:02 -08001000 if err != nil {
Colin Cross192e97a2018-02-22 14:21:02 -08001001 return ret, err
Colin Cross94a32102018-02-22 14:21:02 -08001002 }
1003
Colin Cross7b3dcc32019-01-24 13:14:39 -08001004 // absolute path already checked by validatePath
1005 if strings.HasPrefix(ret.String(), ctx.Config().buildDir) {
Mikhail Naganovab1f5182019-02-08 13:17:55 -08001006 return ret, fmt.Errorf("source path %q is in output", ret.String())
Colin Crossc48c1432018-02-23 07:09:01 +00001007 }
1008
Colin Cross192e97a2018-02-22 14:21:02 -08001009 return ret, nil
1010}
1011
1012// existsWithDependencies returns true if the path exists, and adds appropriate dependencies to rerun if the
1013// path does not exist.
1014func existsWithDependencies(ctx PathContext, path SourcePath) (exists bool, err error) {
1015 var files []string
1016
1017 if gctx, ok := ctx.(PathGlobContext); ok {
1018 // Use glob to produce proper dependencies, even though we only want
1019 // a single file.
1020 files, err = gctx.GlobWithDeps(path.String(), nil)
1021 } else {
1022 var deps []string
1023 // We cannot add build statements in this context, so we fall back to
1024 // AddNinjaFileDeps
Colin Cross988414c2020-01-11 01:11:46 +00001025 files, deps, err = ctx.Config().fs.Glob(path.String(), nil, pathtools.FollowSymlinks)
Colin Cross192e97a2018-02-22 14:21:02 -08001026 ctx.AddNinjaFileDeps(deps...)
1027 }
1028
1029 if err != nil {
1030 return false, fmt.Errorf("glob: %s", err.Error())
1031 }
1032
1033 return len(files) > 0, nil
1034}
1035
1036// PathForSource joins the provided path components and validates that the result
1037// neither escapes the source dir nor is in the out dir.
1038// On error, it will return a usable, but invalid SourcePath, and report a ModuleError.
1039func PathForSource(ctx PathContext, pathComponents ...string) SourcePath {
1040 path, err := pathForSource(ctx, pathComponents...)
1041 if err != nil {
1042 reportPathError(ctx, err)
1043 }
1044
Colin Crosse3924e12018-08-15 20:18:53 -07001045 if pathtools.IsGlob(path.String()) {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001046 ReportPathErrorf(ctx, "path may not contain a glob: %s", path.String())
Colin Crosse3924e12018-08-15 20:18:53 -07001047 }
1048
Liz Kammera830f3a2020-11-10 10:50:34 -08001049 if modCtx, ok := ctx.(ModuleMissingDepsPathContext); ok && ctx.Config().AllowMissingDependencies() {
Colin Cross192e97a2018-02-22 14:21:02 -08001050 exists, err := existsWithDependencies(ctx, path)
1051 if err != nil {
1052 reportPathError(ctx, err)
1053 }
1054 if !exists {
1055 modCtx.AddMissingDependencies([]string{path.String()})
1056 }
Colin Cross988414c2020-01-11 01:11:46 +00001057 } else if exists, _, err := ctx.Config().fs.Exists(path.String()); err != nil {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001058 ReportPathErrorf(ctx, "%s: %s", path, err.Error())
Pedro Loureiro5d190cc2021-02-15 15:41:33 +00001059 } else if !exists && !ctx.Config().TestAllowNonExistentPaths {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001060 ReportPathErrorf(ctx, "source path %q does not exist", path)
Colin Cross192e97a2018-02-22 14:21:02 -08001061 }
1062 return path
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001063}
1064
Liz Kammer7aa52882021-02-11 09:16:14 -05001065// ExistentPathForSource returns an OptionalPath with the SourcePath, rooted from SrcDir, *not*
1066// rooted from the module's local source directory, if the path exists, or an empty OptionalPath if
1067// it doesn't exist. Dependencies are added so that the ninja file will be regenerated if the state
1068// of the path changes.
Colin Cross32f38982018-02-22 11:47:25 -08001069func ExistentPathForSource(ctx PathContext, pathComponents ...string) OptionalPath {
Colin Cross192e97a2018-02-22 14:21:02 -08001070 path, err := pathForSource(ctx, pathComponents...)
Colin Cross1ccfcc32018-02-22 13:54:26 -08001071 if err != nil {
1072 reportPathError(ctx, err)
1073 return OptionalPath{}
1074 }
Colin Crossc48c1432018-02-23 07:09:01 +00001075
Colin Crosse3924e12018-08-15 20:18:53 -07001076 if pathtools.IsGlob(path.String()) {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001077 ReportPathErrorf(ctx, "path may not contain a glob: %s", path.String())
Colin Crosse3924e12018-08-15 20:18:53 -07001078 return OptionalPath{}
1079 }
1080
Colin Cross192e97a2018-02-22 14:21:02 -08001081 exists, err := existsWithDependencies(ctx, path)
Colin Crossc48c1432018-02-23 07:09:01 +00001082 if err != nil {
1083 reportPathError(ctx, err)
1084 return OptionalPath{}
1085 }
Colin Cross192e97a2018-02-22 14:21:02 -08001086 if !exists {
Colin Crossc48c1432018-02-23 07:09:01 +00001087 return OptionalPath{}
1088 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001089 return OptionalPathForPath(path)
1090}
1091
1092func (p SourcePath) String() string {
1093 return filepath.Join(p.config.srcDir, p.path)
1094}
1095
1096// Join creates a new SourcePath with paths... joined with the current path. The
1097// provided paths... may not use '..' to escape from the current path.
1098func (p SourcePath) Join(ctx PathContext, paths ...string) SourcePath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001099 path, err := validatePath(paths...)
1100 if err != nil {
1101 reportPathError(ctx, err)
1102 }
Colin Cross0db55682017-12-05 15:36:55 -08001103 return p.withRel(path)
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001104}
1105
Colin Cross2fafa3e2019-03-05 12:39:51 -08001106// join is like Join but does less path validation.
1107func (p SourcePath) join(ctx PathContext, paths ...string) SourcePath {
1108 path, err := validateSafePath(paths...)
1109 if err != nil {
1110 reportPathError(ctx, err)
1111 }
1112 return p.withRel(path)
1113}
1114
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001115// OverlayPath returns the overlay for `path' if it exists. This assumes that the
1116// SourcePath is the path to a resource overlay directory.
Liz Kammera830f3a2020-11-10 10:50:34 -08001117func (p SourcePath) OverlayPath(ctx ModuleMissingDepsPathContext, path Path) OptionalPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001118 var relDir string
Colin Cross07e51612019-03-05 12:46:40 -08001119 if srcPath, ok := path.(SourcePath); ok {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001120 relDir = srcPath.path
1121 } else {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001122 ReportPathErrorf(ctx, "Cannot find relative path for %s(%s)", reflect.TypeOf(path).Name(), path)
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001123 return OptionalPath{}
1124 }
1125 dir := filepath.Join(p.config.srcDir, p.path, relDir)
1126 // Use Glob so that we are run again if the directory is added.
Colin Cross7f19f372016-11-01 11:10:25 -07001127 if pathtools.IsGlob(dir) {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001128 ReportPathErrorf(ctx, "Path may not contain a glob: %s", dir)
Dan Willemsen7b310ee2015-12-18 15:11:17 -08001129 }
Colin Cross461b4452018-02-23 09:22:42 -08001130 paths, err := ctx.GlobWithDeps(dir, nil)
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001131 if err != nil {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001132 ReportPathErrorf(ctx, "glob: %s", err.Error())
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001133 return OptionalPath{}
1134 }
1135 if len(paths) == 0 {
1136 return OptionalPath{}
1137 }
Colin Cross43f08db2018-11-12 10:13:39 -08001138 relPath := Rel(ctx, p.config.srcDir, paths[0])
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001139 return OptionalPathForPath(PathForSource(ctx, relPath))
1140}
1141
Colin Cross70dda7e2019-10-01 22:05:35 -07001142// OutputPath is a Path representing an intermediates file path rooted from the build directory
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001143type OutputPath struct {
1144 basePath
Colin Crossd63c9a72020-01-29 16:52:50 -08001145 fullPath string
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001146}
1147
Colin Cross702e0f82017-10-18 17:27:54 -07001148func (p OutputPath) withRel(rel string) OutputPath {
Colin Cross0db55682017-12-05 15:36:55 -08001149 p.basePath = p.basePath.withRel(rel)
Colin Crossd63c9a72020-01-29 16:52:50 -08001150 p.fullPath = filepath.Join(p.fullPath, rel)
Colin Cross702e0f82017-10-18 17:27:54 -07001151 return p
1152}
1153
Colin Cross3063b782018-08-15 11:19:12 -07001154func (p OutputPath) WithoutRel() OutputPath {
1155 p.basePath.rel = filepath.Base(p.basePath.path)
1156 return p
1157}
1158
Paul Duffin9b478b02019-12-10 13:41:51 +00001159func (p OutputPath) buildDir() string {
1160 return p.config.buildDir
1161}
1162
Paul Duffin0267d492021-02-02 10:05:52 +00001163func (p OutputPath) objPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleObjPath {
1164 return PathForModuleObj(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
1165}
1166
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001167var _ Path = OutputPath{}
Paul Duffin9b478b02019-12-10 13:41:51 +00001168var _ WritablePath = OutputPath{}
Paul Duffin0267d492021-02-02 10:05:52 +00001169var _ objPathProvider = OutputPath{}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001170
Chris Parsons8f232a22020-06-23 17:37:05 -04001171// toolDepPath is a Path representing a dependency of the build tool.
1172type toolDepPath struct {
1173 basePath
1174}
1175
1176var _ Path = toolDepPath{}
1177
1178// pathForBuildToolDep returns a toolDepPath representing the given path string.
1179// There is no validation for the path, as it is "trusted": It may fail
1180// normal validation checks. For example, it may be an absolute path.
1181// Only use this function to construct paths for dependencies of the build
1182// tool invocation.
1183func pathForBuildToolDep(ctx PathContext, path string) toolDepPath {
1184 return toolDepPath{basePath{path, ctx.Config(), ""}}
1185}
1186
Jeff Gaston734e3802017-04-10 15:47:24 -07001187// PathForOutput joins the provided paths and returns an OutputPath that is
1188// validated to not escape the build dir.
1189// On error, it will return a usable, but invalid OutputPath, and report a ModuleError.
1190func PathForOutput(ctx PathContext, pathComponents ...string) OutputPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001191 path, err := validatePath(pathComponents...)
1192 if err != nil {
1193 reportPathError(ctx, err)
1194 }
Colin Crossd63c9a72020-01-29 16:52:50 -08001195 fullPath := filepath.Join(ctx.Config().buildDir, path)
1196 path = fullPath[len(fullPath)-len(path):]
1197 return OutputPath{basePath{path, ctx.Config(), ""}, fullPath}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001198}
1199
Colin Cross40e33732019-02-15 11:08:35 -08001200// PathsForOutput returns Paths rooted from buildDir
1201func PathsForOutput(ctx PathContext, paths []string) WritablePaths {
1202 ret := make(WritablePaths, len(paths))
1203 for i, path := range paths {
1204 ret[i] = PathForOutput(ctx, path)
1205 }
1206 return ret
1207}
1208
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001209func (p OutputPath) writablePath() {}
1210
1211func (p OutputPath) String() string {
Colin Crossd63c9a72020-01-29 16:52:50 -08001212 return p.fullPath
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001213}
1214
1215// Join creates a new OutputPath with paths... joined with the current path. The
1216// provided paths... may not use '..' to escape from the current path.
1217func (p OutputPath) Join(ctx PathContext, paths ...string) OutputPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001218 path, err := validatePath(paths...)
1219 if err != nil {
1220 reportPathError(ctx, err)
1221 }
Colin Cross0db55682017-12-05 15:36:55 -08001222 return p.withRel(path)
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001223}
1224
Colin Cross8854a5a2019-02-11 14:14:16 -08001225// ReplaceExtension creates a new OutputPath with the extension replaced with ext.
1226func (p OutputPath) ReplaceExtension(ctx PathContext, ext string) OutputPath {
1227 if strings.Contains(ext, "/") {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001228 ReportPathErrorf(ctx, "extension %q cannot contain /", ext)
Colin Cross8854a5a2019-02-11 14:14:16 -08001229 }
1230 ret := PathForOutput(ctx, pathtools.ReplaceExtension(p.path, ext))
Colin Cross2cdd5df2019-02-25 10:25:24 -08001231 ret.rel = pathtools.ReplaceExtension(p.rel, ext)
Colin Cross8854a5a2019-02-11 14:14:16 -08001232 return ret
1233}
1234
Colin Cross40e33732019-02-15 11:08:35 -08001235// InSameDir creates a new OutputPath from the directory of the current OutputPath joined with the elements in paths.
1236func (p OutputPath) InSameDir(ctx PathContext, paths ...string) OutputPath {
1237 path, err := validatePath(paths...)
1238 if err != nil {
1239 reportPathError(ctx, err)
1240 }
1241
1242 ret := PathForOutput(ctx, filepath.Dir(p.path), path)
Colin Cross2cdd5df2019-02-25 10:25:24 -08001243 ret.rel = filepath.Join(filepath.Dir(p.rel), path)
Colin Cross40e33732019-02-15 11:08:35 -08001244 return ret
1245}
1246
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001247// PathForIntermediates returns an OutputPath representing the top-level
1248// intermediates directory.
1249func PathForIntermediates(ctx PathContext, paths ...string) OutputPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001250 path, err := validatePath(paths...)
1251 if err != nil {
1252 reportPathError(ctx, err)
1253 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001254 return PathForOutput(ctx, ".intermediates", path)
1255}
1256
Colin Cross07e51612019-03-05 12:46:40 -08001257var _ genPathProvider = SourcePath{}
1258var _ objPathProvider = SourcePath{}
1259var _ resPathProvider = SourcePath{}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001260
Colin Cross07e51612019-03-05 12:46:40 -08001261// PathForModuleSrc returns a Path representing the paths... under the
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001262// module's local source directory.
Liz Kammera830f3a2020-11-10 10:50:34 -08001263func PathForModuleSrc(ctx ModuleMissingDepsPathContext, pathComponents ...string) Path {
Colin Cross8a497952019-03-05 22:25:09 -08001264 p, err := validatePath(pathComponents...)
1265 if err != nil {
1266 reportPathError(ctx, err)
Colin Cross192e97a2018-02-22 14:21:02 -08001267 }
Colin Cross8a497952019-03-05 22:25:09 -08001268 paths, err := expandOneSrcPath(ctx, p, nil)
1269 if err != nil {
1270 if depErr, ok := err.(missingDependencyError); ok {
1271 if ctx.Config().AllowMissingDependencies() {
1272 ctx.AddMissingDependencies(depErr.missingDeps)
1273 } else {
1274 ctx.ModuleErrorf(`%s, is the property annotated with android:"path"?`, depErr.Error())
1275 }
1276 } else {
1277 reportPathError(ctx, err)
1278 }
1279 return nil
1280 } else if len(paths) == 0 {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001281 ReportPathErrorf(ctx, "%q produced no files, expected exactly one", p)
Colin Cross8a497952019-03-05 22:25:09 -08001282 return nil
1283 } else if len(paths) > 1 {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001284 ReportPathErrorf(ctx, "%q produced %d files, expected exactly one", p, len(paths))
Colin Cross8a497952019-03-05 22:25:09 -08001285 }
1286 return paths[0]
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001287}
1288
Liz Kammera830f3a2020-11-10 10:50:34 -08001289func pathForModuleSrc(ctx EarlyModulePathContext, paths ...string) SourcePath {
Colin Cross07e51612019-03-05 12:46:40 -08001290 p, err := validatePath(paths...)
1291 if err != nil {
1292 reportPathError(ctx, err)
1293 }
1294
1295 path, err := pathForSource(ctx, ctx.ModuleDir(), p)
1296 if err != nil {
1297 reportPathError(ctx, err)
1298 }
1299
1300 path.basePath.rel = p
1301
1302 return path
1303}
1304
Colin Cross2fafa3e2019-03-05 12:39:51 -08001305// PathsWithModuleSrcSubDir takes a list of Paths and returns a new list of Paths where Rel() on each path
1306// will return the path relative to subDir in the module's source directory. If any input paths are not located
1307// inside subDir then a path error will be reported.
Liz Kammera830f3a2020-11-10 10:50:34 -08001308func PathsWithModuleSrcSubDir(ctx EarlyModulePathContext, paths Paths, subDir string) Paths {
Colin Cross2fafa3e2019-03-05 12:39:51 -08001309 paths = append(Paths(nil), paths...)
Colin Cross07e51612019-03-05 12:46:40 -08001310 subDirFullPath := pathForModuleSrc(ctx, subDir)
Colin Cross2fafa3e2019-03-05 12:39:51 -08001311 for i, path := range paths {
1312 rel := Rel(ctx, subDirFullPath.String(), path.String())
1313 paths[i] = subDirFullPath.join(ctx, rel)
1314 }
1315 return paths
1316}
1317
1318// PathWithModuleSrcSubDir takes a Path and returns a Path where Rel() will return the path relative to subDir in the
1319// 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 -08001320func PathWithModuleSrcSubDir(ctx EarlyModulePathContext, path Path, subDir string) Path {
Colin Cross07e51612019-03-05 12:46:40 -08001321 subDirFullPath := pathForModuleSrc(ctx, subDir)
Colin Cross2fafa3e2019-03-05 12:39:51 -08001322 rel := Rel(ctx, subDirFullPath.String(), path.String())
1323 return subDirFullPath.Join(ctx, rel)
1324}
1325
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001326// OptionalPathForModuleSrc returns an OptionalPath. The OptionalPath contains a
1327// valid path if p is non-nil.
Liz Kammera830f3a2020-11-10 10:50:34 -08001328func OptionalPathForModuleSrc(ctx ModuleMissingDepsPathContext, p *string) OptionalPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001329 if p == nil {
1330 return OptionalPath{}
1331 }
1332 return OptionalPathForPath(PathForModuleSrc(ctx, *p))
1333}
1334
Liz Kammera830f3a2020-11-10 10:50:34 -08001335func (p SourcePath) genPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleGenPath {
Colin Cross7fc17db2017-02-01 14:07:55 -08001336 return PathForModuleGen(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001337}
1338
Liz Kammera830f3a2020-11-10 10:50:34 -08001339func (p SourcePath) objPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleObjPath {
Colin Cross7fc17db2017-02-01 14:07:55 -08001340 return PathForModuleObj(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001341}
1342
Liz Kammera830f3a2020-11-10 10:50:34 -08001343func (p SourcePath) resPathWithName(ctx ModuleOutPathContext, name string) ModuleResPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001344 // TODO: Use full directory if the new ctx is not the current ctx?
1345 return PathForModuleRes(ctx, p.path, name)
1346}
1347
1348// ModuleOutPath is a Path representing a module's output directory.
1349type ModuleOutPath struct {
1350 OutputPath
1351}
1352
1353var _ Path = ModuleOutPath{}
1354
Liz Kammera830f3a2020-11-10 10:50:34 -08001355func (p ModuleOutPath) objPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleObjPath {
Pete Bentleyfcf55bf2019-08-16 20:14:32 +01001356 return PathForModuleObj(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
1357}
1358
Liz Kammera830f3a2020-11-10 10:50:34 -08001359// ModuleOutPathContext Subset of ModuleContext functions necessary for output path methods.
1360type ModuleOutPathContext interface {
1361 PathContext
1362
1363 ModuleName() string
1364 ModuleDir() string
1365 ModuleSubDir() string
1366}
1367
1368func pathForModuleOut(ctx ModuleOutPathContext) OutputPath {
Colin Cross702e0f82017-10-18 17:27:54 -07001369 return PathForOutput(ctx, ".intermediates", ctx.ModuleDir(), ctx.ModuleName(), ctx.ModuleSubDir())
1370}
1371
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001372type BazelOutPath struct {
1373 OutputPath
1374}
1375
1376var _ Path = BazelOutPath{}
1377var _ objPathProvider = BazelOutPath{}
1378
Liz Kammera830f3a2020-11-10 10:50:34 -08001379func (p BazelOutPath) objPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleObjPath {
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001380 return PathForModuleObj(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
1381}
1382
Logan Chien7eefdc42018-07-11 18:10:41 +08001383// PathForVndkRefAbiDump returns an OptionalPath representing the path of the
1384// reference abi dump for the given module. This is not guaranteed to be valid.
Liz Kammera830f3a2020-11-10 10:50:34 -08001385func PathForVndkRefAbiDump(ctx ModuleInstallPathContext, version, fileName string,
Hsin-Yi Chen53489642019-07-31 17:10:45 +08001386 isNdk, isLlndkOrVndk, isGzip bool) OptionalPath {
Logan Chien7eefdc42018-07-11 18:10:41 +08001387
Jayant Chowdharyac066c62018-02-20 10:53:31 -08001388 arches := ctx.DeviceConfig().Arches()
Logan Chien7eefdc42018-07-11 18:10:41 +08001389 if len(arches) == 0 {
1390 panic("device build with no primary arch")
1391 }
Jayant Chowdharyac066c62018-02-20 10:53:31 -08001392 currentArch := ctx.Arch()
1393 archNameAndVariant := currentArch.ArchType.String()
1394 if currentArch.ArchVariant != "" {
1395 archNameAndVariant += "_" + currentArch.ArchVariant
1396 }
Logan Chien5237bed2018-07-11 17:15:57 +08001397
1398 var dirName string
Hsin-Yi Chen53489642019-07-31 17:10:45 +08001399 if isNdk {
Logan Chien5237bed2018-07-11 17:15:57 +08001400 dirName = "ndk"
Hsin-Yi Chen53489642019-07-31 17:10:45 +08001401 } else if isLlndkOrVndk {
Logan Chien5237bed2018-07-11 17:15:57 +08001402 dirName = "vndk"
Logan Chien41eabe62019-04-10 13:33:58 +08001403 } else {
1404 dirName = "platform" // opt-in libs
Jayant Chowdhary3e231fd2017-02-08 13:45:53 -08001405 }
Logan Chien5237bed2018-07-11 17:15:57 +08001406
Jayant Chowdhary34ce67d2018-03-08 11:00:50 -08001407 binderBitness := ctx.DeviceConfig().BinderBitness()
Logan Chien7eefdc42018-07-11 18:10:41 +08001408
1409 var ext string
1410 if isGzip {
1411 ext = ".lsdump.gz"
1412 } else {
1413 ext = ".lsdump"
1414 }
1415
1416 return ExistentPathForSource(ctx, "prebuilts", "abi-dumps", dirName,
1417 version, binderBitness, archNameAndVariant, "source-based",
1418 fileName+ext)
Jayant Chowdhary3e231fd2017-02-08 13:45:53 -08001419}
1420
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001421// PathForBazelOut returns a Path representing the paths... under an output directory dedicated to
1422// bazel-owned outputs.
1423func PathForBazelOut(ctx PathContext, paths ...string) BazelOutPath {
1424 execRootPathComponents := append([]string{"execroot", "__main__"}, paths...)
1425 execRootPath := filepath.Join(execRootPathComponents...)
1426 validatedExecRootPath, err := validatePath(execRootPath)
1427 if err != nil {
1428 reportPathError(ctx, err)
1429 }
1430
1431 outputPath := OutputPath{basePath{"", ctx.Config(), ""},
1432 ctx.Config().BazelContext.OutputBase()}
1433
1434 return BazelOutPath{
1435 OutputPath: outputPath.withRel(validatedExecRootPath),
1436 }
1437}
1438
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001439// PathForModuleOut returns a Path representing the paths... under the module's
1440// output directory.
Liz Kammera830f3a2020-11-10 10:50:34 -08001441func PathForModuleOut(ctx ModuleOutPathContext, paths ...string) ModuleOutPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001442 p, err := validatePath(paths...)
1443 if err != nil {
1444 reportPathError(ctx, err)
1445 }
Colin Cross702e0f82017-10-18 17:27:54 -07001446 return ModuleOutPath{
Liz Kammera830f3a2020-11-10 10:50:34 -08001447 OutputPath: pathForModuleOut(ctx).withRel(p),
Colin Cross702e0f82017-10-18 17:27:54 -07001448 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001449}
1450
1451// ModuleGenPath is a Path representing the 'gen' directory in a module's output
1452// directory. Mainly used for generated sources.
1453type ModuleGenPath struct {
1454 ModuleOutPath
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001455}
1456
1457var _ Path = ModuleGenPath{}
1458var _ genPathProvider = ModuleGenPath{}
1459var _ objPathProvider = ModuleGenPath{}
1460
1461// PathForModuleGen returns a Path representing the paths... under the module's
1462// `gen' directory.
Liz Kammera830f3a2020-11-10 10:50:34 -08001463func PathForModuleGen(ctx ModuleOutPathContext, paths ...string) ModuleGenPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001464 p, err := validatePath(paths...)
1465 if err != nil {
1466 reportPathError(ctx, err)
1467 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001468 return ModuleGenPath{
Colin Cross702e0f82017-10-18 17:27:54 -07001469 ModuleOutPath: ModuleOutPath{
Liz Kammera830f3a2020-11-10 10:50:34 -08001470 OutputPath: pathForModuleOut(ctx).withRel("gen").withRel(p),
Colin Cross702e0f82017-10-18 17:27:54 -07001471 },
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001472 }
1473}
1474
Liz Kammera830f3a2020-11-10 10:50:34 -08001475func (p ModuleGenPath) genPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleGenPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001476 // TODO: make a different path for local vs remote generated files?
Dan Willemsen21ec4902016-11-02 20:43:13 -07001477 return PathForModuleGen(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001478}
1479
Liz Kammera830f3a2020-11-10 10:50:34 -08001480func (p ModuleGenPath) objPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleObjPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001481 return PathForModuleObj(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
1482}
1483
1484// ModuleObjPath is a Path representing the 'obj' directory in a module's output
1485// directory. Used for compiled objects.
1486type ModuleObjPath struct {
1487 ModuleOutPath
1488}
1489
1490var _ Path = ModuleObjPath{}
1491
1492// PathForModuleObj returns a Path representing the paths... under the module's
1493// 'obj' directory.
Liz Kammera830f3a2020-11-10 10:50:34 -08001494func PathForModuleObj(ctx ModuleOutPathContext, pathComponents ...string) ModuleObjPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001495 p, err := validatePath(pathComponents...)
1496 if err != nil {
1497 reportPathError(ctx, err)
1498 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001499 return ModuleObjPath{PathForModuleOut(ctx, "obj", p)}
1500}
1501
1502// ModuleResPath is a a Path representing the 'res' directory in a module's
1503// output directory.
1504type ModuleResPath struct {
1505 ModuleOutPath
1506}
1507
1508var _ Path = ModuleResPath{}
1509
1510// PathForModuleRes returns a Path representing the paths... under the module's
1511// 'res' directory.
Liz Kammera830f3a2020-11-10 10:50:34 -08001512func PathForModuleRes(ctx ModuleOutPathContext, pathComponents ...string) ModuleResPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001513 p, err := validatePath(pathComponents...)
1514 if err != nil {
1515 reportPathError(ctx, err)
1516 }
1517
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001518 return ModuleResPath{PathForModuleOut(ctx, "res", p)}
1519}
1520
Colin Cross70dda7e2019-10-01 22:05:35 -07001521// InstallPath is a Path representing a installed file path rooted from the build directory
1522type InstallPath struct {
1523 basePath
Colin Crossff6c33d2019-10-02 16:01:35 -07001524
Jiyong Park957bcd92020-10-20 18:23:33 +09001525 // partitionDir is the part of the InstallPath that is automatically determined according to the context.
1526 // For example, it is host/<os>-<arch> for host modules, and target/product/<device>/<partition> for device modules.
1527 partitionDir string
1528
1529 // makePath indicates whether this path is for Soong (false) or Make (true).
1530 makePath bool
Colin Cross70dda7e2019-10-01 22:05:35 -07001531}
1532
Paul Duffin9b478b02019-12-10 13:41:51 +00001533func (p InstallPath) buildDir() string {
1534 return p.config.buildDir
1535}
1536
Hans MÃ¥nssond3f2bd72020-11-27 12:37:28 +01001537func (p InstallPath) ReplaceExtension(ctx PathContext, ext string) OutputPath {
1538 panic("Not implemented")
1539}
1540
Paul Duffin9b478b02019-12-10 13:41:51 +00001541var _ Path = InstallPath{}
1542var _ WritablePath = InstallPath{}
1543
Colin Cross70dda7e2019-10-01 22:05:35 -07001544func (p InstallPath) writablePath() {}
1545
1546func (p InstallPath) String() string {
Jiyong Park957bcd92020-10-20 18:23:33 +09001547 if p.makePath {
1548 // Make path starts with out/ instead of out/soong.
1549 return filepath.Join(p.config.buildDir, "../", p.path)
1550 } else {
1551 return filepath.Join(p.config.buildDir, p.path)
1552 }
1553}
1554
1555// PartitionDir returns the path to the partition where the install path is rooted at. It is
1556// out/soong/target/product/<device>/<partition> for device modules, and out/soong/host/<os>-<arch> for host modules.
1557// The ./soong is dropped if the install path is for Make.
1558func (p InstallPath) PartitionDir() string {
1559 if p.makePath {
1560 return filepath.Join(p.config.buildDir, "../", p.partitionDir)
1561 } else {
1562 return filepath.Join(p.config.buildDir, p.partitionDir)
1563 }
Colin Cross70dda7e2019-10-01 22:05:35 -07001564}
1565
1566// Join creates a new InstallPath with paths... joined with the current path. The
1567// provided paths... may not use '..' to escape from the current path.
1568func (p InstallPath) Join(ctx PathContext, paths ...string) InstallPath {
1569 path, err := validatePath(paths...)
1570 if err != nil {
1571 reportPathError(ctx, err)
1572 }
1573 return p.withRel(path)
1574}
1575
1576func (p InstallPath) withRel(rel string) InstallPath {
1577 p.basePath = p.basePath.withRel(rel)
1578 return p
1579}
1580
Colin Crossff6c33d2019-10-02 16:01:35 -07001581// ToMakePath returns a new InstallPath that points to Make's install directory instead of Soong's,
1582// i.e. out/ instead of out/soong/.
1583func (p InstallPath) ToMakePath() InstallPath {
Jiyong Park957bcd92020-10-20 18:23:33 +09001584 p.makePath = true
Colin Crossff6c33d2019-10-02 16:01:35 -07001585 return p
Colin Cross70dda7e2019-10-01 22:05:35 -07001586}
1587
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001588// PathForModuleInstall returns a Path representing the install path for the
1589// module appended with paths...
Colin Cross70dda7e2019-10-01 22:05:35 -07001590func PathForModuleInstall(ctx ModuleInstallPathContext, pathComponents ...string) InstallPath {
Colin Cross6e359402020-02-10 15:29:54 -08001591 os := ctx.Os()
Jiyong Park87788b52020-09-01 12:37:45 +09001592 arch := ctx.Arch().ArchType
1593 forceOS, forceArch := ctx.InstallForceOS()
1594 if forceOS != nil {
Colin Cross6e359402020-02-10 15:29:54 -08001595 os = *forceOS
1596 }
Jiyong Park87788b52020-09-01 12:37:45 +09001597 if forceArch != nil {
1598 arch = *forceArch
1599 }
Colin Cross6e359402020-02-10 15:29:54 -08001600 partition := modulePartition(ctx, os)
Colin Cross609c49a2020-02-13 13:20:11 -08001601
Jiyong Park87788b52020-09-01 12:37:45 +09001602 ret := pathForInstall(ctx, os, arch, partition, ctx.Debug(), pathComponents...)
Colin Cross609c49a2020-02-13 13:20:11 -08001603
Jingwen Chencda22c92020-11-23 00:22:30 -05001604 if ctx.InstallBypassMake() && ctx.Config().KatiEnabled() {
Colin Cross609c49a2020-02-13 13:20:11 -08001605 ret = ret.ToMakePath()
1606 }
1607
1608 return ret
1609}
1610
Jiyong Park87788b52020-09-01 12:37:45 +09001611func pathForInstall(ctx PathContext, os OsType, arch ArchType, partition string, debug bool,
Colin Cross609c49a2020-02-13 13:20:11 -08001612 pathComponents ...string) InstallPath {
1613
Jiyong Park957bcd92020-10-20 18:23:33 +09001614 var partionPaths []string
Colin Cross609c49a2020-02-13 13:20:11 -08001615
Colin Cross6e359402020-02-10 15:29:54 -08001616 if os.Class == Device {
Jiyong Park957bcd92020-10-20 18:23:33 +09001617 partionPaths = []string{"target", "product", ctx.Config().DeviceName(), partition}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001618 } else {
Jiyong Park87788b52020-09-01 12:37:45 +09001619 osName := os.String()
1620 if os == Linux {
1621 // instead of linux_glibc
1622 osName = "linux"
Dan Willemsen866b5632017-09-22 12:28:24 -07001623 }
Jiyong Park87788b52020-09-01 12:37:45 +09001624 // SOONG_HOST_OUT is set to out/host/$(HOST_OS)-$(HOST_PREBUILT_ARCH)
1625 // and HOST_PREBUILT_ARCH is forcibly set to x86 even on x86_64 hosts. We don't seem
1626 // to have a plan to fix it (see the comment in build/make/core/envsetup.mk).
1627 // Let's keep using x86 for the existing cases until we have a need to support
1628 // other architectures.
1629 archName := arch.String()
1630 if os.Class == Host && (arch == X86_64 || arch == Common) {
1631 archName = "x86"
1632 }
Jiyong Park957bcd92020-10-20 18:23:33 +09001633 partionPaths = []string{"host", osName + "-" + archName, partition}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001634 }
Colin Cross609c49a2020-02-13 13:20:11 -08001635 if debug {
Jiyong Park957bcd92020-10-20 18:23:33 +09001636 partionPaths = append([]string{"debug"}, partionPaths...)
Dan Willemsen782a2d12015-12-21 14:55:28 -08001637 }
Colin Cross70dda7e2019-10-01 22:05:35 -07001638
Jiyong Park957bcd92020-10-20 18:23:33 +09001639 partionPath, err := validatePath(partionPaths...)
Colin Cross70dda7e2019-10-01 22:05:35 -07001640 if err != nil {
1641 reportPathError(ctx, err)
1642 }
Colin Crossff6c33d2019-10-02 16:01:35 -07001643
Jiyong Park957bcd92020-10-20 18:23:33 +09001644 base := InstallPath{
1645 basePath: basePath{partionPath, ctx.Config(), ""},
1646 partitionDir: partionPath,
1647 makePath: false,
1648 }
Colin Crossff6c33d2019-10-02 16:01:35 -07001649
Jiyong Park957bcd92020-10-20 18:23:33 +09001650 return base.Join(ctx, pathComponents...)
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001651}
1652
Nicolas Geoffray1228e9c2020-02-27 13:45:35 +00001653func pathForNdkOrSdkInstall(ctx PathContext, prefix string, paths []string) InstallPath {
Jiyong Park957bcd92020-10-20 18:23:33 +09001654 base := InstallPath{
1655 basePath: basePath{prefix, ctx.Config(), ""},
1656 partitionDir: prefix,
1657 makePath: false,
Colin Cross70dda7e2019-10-01 22:05:35 -07001658 }
Jiyong Park957bcd92020-10-20 18:23:33 +09001659 return base.Join(ctx, paths...)
Colin Cross70dda7e2019-10-01 22:05:35 -07001660}
1661
Nicolas Geoffray1228e9c2020-02-27 13:45:35 +00001662func PathForNdkInstall(ctx PathContext, paths ...string) InstallPath {
1663 return pathForNdkOrSdkInstall(ctx, "ndk", paths)
1664}
1665
1666func PathForMainlineSdksInstall(ctx PathContext, paths ...string) InstallPath {
1667 return pathForNdkOrSdkInstall(ctx, "mainline-sdks", paths)
1668}
1669
Colin Cross70dda7e2019-10-01 22:05:35 -07001670func InstallPathToOnDevicePath(ctx PathContext, path InstallPath) string {
Colin Cross43f08db2018-11-12 10:13:39 -08001671 rel := Rel(ctx, PathForOutput(ctx, "target", "product", ctx.Config().DeviceName()).String(), path.String())
1672
1673 return "/" + rel
1674}
1675
Colin Cross6e359402020-02-10 15:29:54 -08001676func modulePartition(ctx ModuleInstallPathContext, os OsType) string {
Colin Cross43f08db2018-11-12 10:13:39 -08001677 var partition string
Colin Cross6e359402020-02-10 15:29:54 -08001678 if ctx.InstallInTestcases() {
1679 // "testcases" install directory can be used for host or device modules.
Jaewoong Jung0949f312019-09-11 10:25:18 -07001680 partition = "testcases"
Colin Cross6e359402020-02-10 15:29:54 -08001681 } else if os.Class == Device {
1682 if ctx.InstallInData() {
1683 partition = "data"
1684 } else if ctx.InstallInRamdisk() {
1685 if ctx.DeviceConfig().BoardUsesRecoveryAsBoot() {
1686 partition = "recovery/root/first_stage_ramdisk"
1687 } else {
1688 partition = "ramdisk"
1689 }
1690 if !ctx.InstallInRoot() {
1691 partition += "/system"
1692 }
Yifan Hong60e0cfb2020-10-21 15:17:56 -07001693 } else if ctx.InstallInVendorRamdisk() {
Yifan Hong39143a92020-10-26 12:43:12 -07001694 // The module is only available after switching root into
1695 // /first_stage_ramdisk. To expose the module before switching root
1696 // on a device without a dedicated recovery partition, install the
1697 // recovery variant.
Yifan Hongdd8dacc2020-10-21 15:40:17 -07001698 if ctx.DeviceConfig().BoardMoveRecoveryResourcesToVendorBoot() {
Petri Gyntherac229562021-03-02 23:44:02 -08001699 partition = "vendor_ramdisk/first_stage_ramdisk"
Yifan Hongdd8dacc2020-10-21 15:40:17 -07001700 } else {
Petri Gyntherac229562021-03-02 23:44:02 -08001701 partition = "vendor_ramdisk"
Yifan Hongdd8dacc2020-10-21 15:40:17 -07001702 }
1703 if !ctx.InstallInRoot() {
1704 partition += "/system"
1705 }
Colin Cross6e359402020-02-10 15:29:54 -08001706 } else if ctx.InstallInRecovery() {
1707 if ctx.InstallInRoot() {
1708 partition = "recovery/root"
1709 } else {
1710 // the layout of recovery partion is the same as that of system partition
1711 partition = "recovery/root/system"
1712 }
1713 } else if ctx.SocSpecific() {
1714 partition = ctx.DeviceConfig().VendorPath()
1715 } else if ctx.DeviceSpecific() {
1716 partition = ctx.DeviceConfig().OdmPath()
1717 } else if ctx.ProductSpecific() {
1718 partition = ctx.DeviceConfig().ProductPath()
1719 } else if ctx.SystemExtSpecific() {
1720 partition = ctx.DeviceConfig().SystemExtPath()
1721 } else if ctx.InstallInRoot() {
1722 partition = "root"
Yifan Hong82db7352020-01-21 16:12:26 -08001723 } else {
Colin Cross6e359402020-02-10 15:29:54 -08001724 partition = "system"
Yifan Hong82db7352020-01-21 16:12:26 -08001725 }
Colin Cross6e359402020-02-10 15:29:54 -08001726 if ctx.InstallInSanitizerDir() {
1727 partition = "data/asan/" + partition
Yifan Hong82db7352020-01-21 16:12:26 -08001728 }
Colin Cross43f08db2018-11-12 10:13:39 -08001729 }
1730 return partition
1731}
1732
Colin Cross609c49a2020-02-13 13:20:11 -08001733type InstallPaths []InstallPath
1734
1735// Paths returns the InstallPaths as a Paths
1736func (p InstallPaths) Paths() Paths {
1737 if p == nil {
1738 return nil
1739 }
1740 ret := make(Paths, len(p))
1741 for i, path := range p {
1742 ret[i] = path
1743 }
1744 return ret
1745}
1746
1747// Strings returns the string forms of the install paths.
1748func (p InstallPaths) Strings() []string {
1749 if p == nil {
1750 return nil
1751 }
1752 ret := make([]string, len(p))
1753 for i, path := range p {
1754 ret[i] = path.String()
1755 }
1756 return ret
1757}
1758
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001759// validateSafePath validates a path that we trust (may contain ninja variables).
Dan Willemsen80a7c2a2015-12-21 14:57:11 -08001760// Ensures that each path component does not attempt to leave its component.
Colin Cross1ccfcc32018-02-22 13:54:26 -08001761func validateSafePath(pathComponents ...string) (string, error) {
Jeff Gaston734e3802017-04-10 15:47:24 -07001762 for _, path := range pathComponents {
Dan Willemsen80a7c2a2015-12-21 14:57:11 -08001763 path := filepath.Clean(path)
1764 if path == ".." || strings.HasPrefix(path, "../") || strings.HasPrefix(path, "/") {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001765 return "", fmt.Errorf("Path is outside directory: %s", path)
Dan Willemsen80a7c2a2015-12-21 14:57:11 -08001766 }
1767 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001768 // TODO: filepath.Join isn't necessarily correct with embedded ninja
1769 // variables. '..' may remove the entire ninja variable, even if it
1770 // will be expanded to multiple nested directories.
Colin Cross1ccfcc32018-02-22 13:54:26 -08001771 return filepath.Join(pathComponents...), nil
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001772}
1773
Dan Willemsen80a7c2a2015-12-21 14:57:11 -08001774// validatePath validates that a path does not include ninja variables, and that
1775// each path component does not attempt to leave its component. Returns a joined
1776// version of each path component.
Colin Cross1ccfcc32018-02-22 13:54:26 -08001777func validatePath(pathComponents ...string) (string, error) {
Jeff Gaston734e3802017-04-10 15:47:24 -07001778 for _, path := range pathComponents {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001779 if strings.Contains(path, "$") {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001780 return "", fmt.Errorf("Path contains invalid character($): %s", path)
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001781 }
1782 }
Colin Cross1ccfcc32018-02-22 13:54:26 -08001783 return validateSafePath(pathComponents...)
Colin Cross6e18ca42015-07-14 18:55:36 -07001784}
Colin Cross5b529592017-05-09 13:34:34 -07001785
Colin Cross0875c522017-11-28 17:34:01 -08001786func PathForPhony(ctx PathContext, phony string) WritablePath {
1787 if strings.ContainsAny(phony, "$/") {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001788 ReportPathErrorf(ctx, "Phony target contains invalid character ($ or /): %s", phony)
Colin Cross0875c522017-11-28 17:34:01 -08001789 }
Colin Cross74e3fe42017-12-11 15:51:44 -08001790 return PhonyPath{basePath{phony, ctx.Config(), ""}}
Colin Cross0875c522017-11-28 17:34:01 -08001791}
1792
Colin Cross74e3fe42017-12-11 15:51:44 -08001793type PhonyPath struct {
1794 basePath
1795}
1796
1797func (p PhonyPath) writablePath() {}
1798
Paul Duffin9b478b02019-12-10 13:41:51 +00001799func (p PhonyPath) buildDir() string {
1800 return p.config.buildDir
1801}
1802
Hans MÃ¥nssond3f2bd72020-11-27 12:37:28 +01001803func (p PhonyPath) ReplaceExtension(ctx PathContext, ext string) OutputPath {
1804 panic("Not implemented")
1805}
1806
Colin Cross74e3fe42017-12-11 15:51:44 -08001807var _ Path = PhonyPath{}
1808var _ WritablePath = PhonyPath{}
1809
Colin Cross5b529592017-05-09 13:34:34 -07001810type testPath struct {
1811 basePath
1812}
1813
1814func (p testPath) String() string {
1815 return p.path
1816}
1817
Colin Cross40e33732019-02-15 11:08:35 -08001818// PathForTesting returns a Path constructed from joining the elements of paths with '/'. It should only be used from
1819// within tests.
Colin Cross5b529592017-05-09 13:34:34 -07001820func PathForTesting(paths ...string) Path {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001821 p, err := validateSafePath(paths...)
1822 if err != nil {
1823 panic(err)
1824 }
Colin Cross5b529592017-05-09 13:34:34 -07001825 return testPath{basePath{path: p, rel: p}}
1826}
1827
Colin Cross40e33732019-02-15 11:08:35 -08001828// PathsForTesting returns a Path constructed from each element in strs. It should only be used from within tests.
1829func PathsForTesting(strs ...string) Paths {
Colin Cross5b529592017-05-09 13:34:34 -07001830 p := make(Paths, len(strs))
1831 for i, s := range strs {
1832 p[i] = PathForTesting(s)
1833 }
1834
1835 return p
1836}
Colin Cross43f08db2018-11-12 10:13:39 -08001837
Colin Cross40e33732019-02-15 11:08:35 -08001838type testPathContext struct {
1839 config Config
Colin Cross40e33732019-02-15 11:08:35 -08001840}
1841
Colin Cross40e33732019-02-15 11:08:35 -08001842func (x *testPathContext) Config() Config { return x.config }
1843func (x *testPathContext) AddNinjaFileDeps(...string) {}
1844
1845// PathContextForTesting returns a PathContext that can be used in tests, for example to create an OutputPath with
1846// PathForOutput.
Colin Cross98be1bb2019-12-13 20:41:13 -08001847func PathContextForTesting(config Config) PathContext {
Colin Cross40e33732019-02-15 11:08:35 -08001848 return &testPathContext{
1849 config: config,
Colin Cross40e33732019-02-15 11:08:35 -08001850 }
1851}
1852
Ulya Trafimovichccc8c852020-10-14 11:29:07 +01001853type testModuleInstallPathContext struct {
1854 baseModuleContext
1855
1856 inData bool
1857 inTestcases bool
1858 inSanitizerDir bool
1859 inRamdisk bool
1860 inVendorRamdisk bool
1861 inRecovery bool
1862 inRoot bool
1863 forceOS *OsType
1864 forceArch *ArchType
1865}
1866
1867func (m testModuleInstallPathContext) Config() Config {
1868 return m.baseModuleContext.config
1869}
1870
1871func (testModuleInstallPathContext) AddNinjaFileDeps(deps ...string) {}
1872
1873func (m testModuleInstallPathContext) InstallInData() bool {
1874 return m.inData
1875}
1876
1877func (m testModuleInstallPathContext) InstallInTestcases() bool {
1878 return m.inTestcases
1879}
1880
1881func (m testModuleInstallPathContext) InstallInSanitizerDir() bool {
1882 return m.inSanitizerDir
1883}
1884
1885func (m testModuleInstallPathContext) InstallInRamdisk() bool {
1886 return m.inRamdisk
1887}
1888
1889func (m testModuleInstallPathContext) InstallInVendorRamdisk() bool {
1890 return m.inVendorRamdisk
1891}
1892
1893func (m testModuleInstallPathContext) InstallInRecovery() bool {
1894 return m.inRecovery
1895}
1896
1897func (m testModuleInstallPathContext) InstallInRoot() bool {
1898 return m.inRoot
1899}
1900
1901func (m testModuleInstallPathContext) InstallBypassMake() bool {
1902 return false
1903}
1904
1905func (m testModuleInstallPathContext) InstallForceOS() (*OsType, *ArchType) {
1906 return m.forceOS, m.forceArch
1907}
1908
1909// Construct a minimal ModuleInstallPathContext for testing. Note that baseModuleContext is
1910// default-initialized, which leaves blueprint.baseModuleContext set to nil, so methods that are
1911// delegated to it will panic.
1912func ModuleInstallPathContextForTesting(config Config) ModuleInstallPathContext {
1913 ctx := &testModuleInstallPathContext{}
1914 ctx.config = config
1915 ctx.os = Android
1916 return ctx
1917}
1918
Colin Cross43f08db2018-11-12 10:13:39 -08001919// Rel performs the same function as filepath.Rel, but reports errors to a PathContext, and reports an error if
1920// targetPath is not inside basePath.
1921func Rel(ctx PathContext, basePath string, targetPath string) string {
1922 rel, isRel := MaybeRel(ctx, basePath, targetPath)
1923 if !isRel {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001924 ReportPathErrorf(ctx, "path %q is not under path %q", targetPath, basePath)
Colin Cross43f08db2018-11-12 10:13:39 -08001925 return ""
1926 }
1927 return rel
1928}
1929
1930// MaybeRel performs the same function as filepath.Rel, but reports errors to a PathContext, and returns false if
1931// targetPath is not inside basePath.
1932func MaybeRel(ctx PathContext, basePath string, targetPath string) (string, bool) {
Dan Willemsen633c5022019-04-12 11:11:38 -07001933 rel, isRel, err := maybeRelErr(basePath, targetPath)
1934 if err != nil {
1935 reportPathError(ctx, err)
1936 }
1937 return rel, isRel
1938}
1939
1940func maybeRelErr(basePath string, targetPath string) (string, bool, error) {
Colin Cross43f08db2018-11-12 10:13:39 -08001941 // filepath.Rel returns an error if one path is absolute and the other is not, handle that case first.
1942 if filepath.IsAbs(basePath) != filepath.IsAbs(targetPath) {
Dan Willemsen633c5022019-04-12 11:11:38 -07001943 return "", false, nil
Colin Cross43f08db2018-11-12 10:13:39 -08001944 }
1945 rel, err := filepath.Rel(basePath, targetPath)
1946 if err != nil {
Dan Willemsen633c5022019-04-12 11:11:38 -07001947 return "", false, err
Colin Cross43f08db2018-11-12 10:13:39 -08001948 } else if rel == ".." || strings.HasPrefix(rel, "../") || strings.HasPrefix(rel, "/") {
Dan Willemsen633c5022019-04-12 11:11:38 -07001949 return "", false, nil
Colin Cross43f08db2018-11-12 10:13:39 -08001950 }
Dan Willemsen633c5022019-04-12 11:11:38 -07001951 return rel, true, nil
Colin Cross43f08db2018-11-12 10:13:39 -08001952}
Colin Cross988414c2020-01-11 01:11:46 +00001953
1954// Writes a file to the output directory. Attempting to write directly to the output directory
1955// will fail due to the sandbox of the soong_build process.
1956func WriteFileToOutputDir(path WritablePath, data []byte, perm os.FileMode) error {
1957 return ioutil.WriteFile(absolutePath(path.String()), data, perm)
1958}
1959
Liz Kammer2dd9ca42020-11-25 16:06:39 -08001960func RemoveAllOutputDir(path WritablePath) error {
1961 return os.RemoveAll(absolutePath(path.String()))
1962}
1963
1964func CreateOutputDirIfNonexistent(path WritablePath, perm os.FileMode) error {
1965 dir := absolutePath(path.String())
1966 if _, err := os.Stat(dir); os.IsNotExist(err) {
1967 return os.MkdirAll(dir, os.ModePerm)
1968 } else {
1969 return err
1970 }
1971}
1972
Colin Cross988414c2020-01-11 01:11:46 +00001973func absolutePath(path string) string {
1974 if filepath.IsAbs(path) {
1975 return path
1976 }
1977 return filepath.Join(absSrcDir, path)
1978}
Chris Parsons216e10a2020-07-09 17:12:52 -04001979
1980// A DataPath represents the path of a file to be used as data, for example
1981// a test library to be installed alongside a test.
1982// The data file should be installed (copied from `<SrcPath>`) to
1983// `<install_root>/<RelativeInstallPath>/<filename>`, or
1984// `<install_root>/<filename>` if RelativeInstallPath is empty.
1985type DataPath struct {
1986 // The path of the data file that should be copied into the data directory
1987 SrcPath Path
1988 // The install path of the data file, relative to the install root.
1989 RelativeInstallPath string
1990}
Colin Crossdcf71b22021-02-01 13:59:03 -08001991
1992// PathsIfNonNil returns a Paths containing only the non-nil input arguments.
1993func PathsIfNonNil(paths ...Path) Paths {
1994 if len(paths) == 0 {
1995 // Fast path for empty argument list
1996 return nil
1997 } else if len(paths) == 1 {
1998 // Fast path for a single argument
1999 if paths[0] != nil {
2000 return paths
2001 } else {
2002 return nil
2003 }
2004 }
2005 ret := make(Paths, 0, len(paths))
2006 for _, path := range paths {
2007 if path != nil {
2008 ret = append(ret, path)
2009 }
2010 }
2011 if len(ret) == 0 {
2012 return nil
2013 }
2014 return ret
2015}