blob: b245fc0e92288f643670a780a39205cef7e0ffdb [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.
Paul Duffind65c58b2021-03-24 09:22:07 +0000184 getBuildDir() string
Paul Duffin9b478b02019-12-10 13:41:51 +0000185
Jeff Gaston734e3802017-04-10 15:47:24 -0700186 // the writablePath method doesn't directly do anything,
187 // but it allows a struct to distinguish between whether or not it implements the WritablePath interface
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700188 writablePath()
Hans MÃ¥nssond3f2bd72020-11-27 12:37:28 +0100189
190 ReplaceExtension(ctx PathContext, ext string) OutputPath
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700191}
192
193type genPathProvider interface {
Liz Kammera830f3a2020-11-10 10:50:34 -0800194 genPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleGenPath
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700195}
196type objPathProvider interface {
Liz Kammera830f3a2020-11-10 10:50:34 -0800197 objPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleObjPath
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700198}
199type resPathProvider interface {
Liz Kammera830f3a2020-11-10 10:50:34 -0800200 resPathWithName(ctx ModuleOutPathContext, name string) ModuleResPath
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700201}
202
203// GenPathWithExt derives a new file path in ctx's generated sources directory
204// from the current path, but with the new extension.
Liz Kammera830f3a2020-11-10 10:50:34 -0800205func GenPathWithExt(ctx ModuleOutPathContext, subdir string, p Path, ext string) ModuleGenPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700206 if path, ok := p.(genPathProvider); ok {
Dan Willemsen21ec4902016-11-02 20:43:13 -0700207 return path.genPathWithExt(ctx, subdir, ext)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700208 }
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +0100209 ReportPathErrorf(ctx, "Tried to create generated file from unsupported path: %s(%s)", reflect.TypeOf(p).Name(), p)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700210 return PathForModuleGen(ctx)
211}
212
213// ObjPathWithExt derives a new file path in ctx's object directory from the
214// current path, but with the new extension.
Liz Kammera830f3a2020-11-10 10:50:34 -0800215func ObjPathWithExt(ctx ModuleOutPathContext, subdir string, p Path, ext string) ModuleObjPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700216 if path, ok := p.(objPathProvider); ok {
217 return path.objPathWithExt(ctx, subdir, ext)
218 }
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +0100219 ReportPathErrorf(ctx, "Tried to create object file from unsupported path: %s (%s)", reflect.TypeOf(p).Name(), p)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700220 return PathForModuleObj(ctx)
221}
222
223// ResPathWithName derives a new path in ctx's output resource directory, using
224// the current path to create the directory name, and the `name` argument for
225// the filename.
Liz Kammera830f3a2020-11-10 10:50:34 -0800226func ResPathWithName(ctx ModuleOutPathContext, p Path, name string) ModuleResPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700227 if path, ok := p.(resPathProvider); ok {
228 return path.resPathWithName(ctx, name)
229 }
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +0100230 ReportPathErrorf(ctx, "Tried to create res file from unsupported path: %s (%s)", reflect.TypeOf(p).Name(), p)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700231 return PathForModuleRes(ctx)
232}
233
234// OptionalPath is a container that may or may not contain a valid Path.
235type OptionalPath struct {
236 valid bool
237 path Path
238}
239
240// OptionalPathForPath returns an OptionalPath containing the path.
241func OptionalPathForPath(path Path) OptionalPath {
242 if path == nil {
243 return OptionalPath{}
244 }
245 return OptionalPath{valid: true, path: path}
246}
247
248// Valid returns whether there is a valid path
249func (p OptionalPath) Valid() bool {
250 return p.valid
251}
252
253// Path returns the Path embedded in this OptionalPath. You must be sure that
254// there is a valid path, since this method will panic if there is not.
255func (p OptionalPath) Path() Path {
256 if !p.valid {
257 panic("Requesting an invalid path")
258 }
259 return p.path
260}
261
262// String returns the string version of the Path, or "" if it isn't valid.
263func (p OptionalPath) String() string {
264 if p.valid {
265 return p.path.String()
266 } else {
267 return ""
Colin Crossf2298272015-05-12 11:36:53 -0700268 }
269}
Colin Cross6e18ca42015-07-14 18:55:36 -0700270
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700271// Paths is a slice of Path objects, with helpers to operate on the collection.
272type Paths []Path
273
Jingwen Chen40fd90a2020-06-15 05:24:19 +0000274func (paths Paths) containsPath(path Path) bool {
275 for _, p := range paths {
276 if p == path {
277 return true
278 }
279 }
280 return false
281}
282
Liz Kammer7aa52882021-02-11 09:16:14 -0500283// PathsForSource returns Paths rooted from SrcDir, *not* rooted from the module's local source
284// directory
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700285func PathsForSource(ctx PathContext, paths []string) Paths {
286 ret := make(Paths, len(paths))
287 for i, path := range paths {
288 ret[i] = PathForSource(ctx, path)
289 }
290 return ret
291}
292
Liz Kammer7aa52882021-02-11 09:16:14 -0500293// ExistentPathsForSources returns a list of Paths rooted from SrcDir, *not* rooted from the
294// module's local source directory, that are found in the tree. If any are not found, they are
295// omitted from the list, and dependencies are added so that we're re-run when they are added.
Colin Cross32f38982018-02-22 11:47:25 -0800296func ExistentPathsForSources(ctx PathContext, paths []string) Paths {
Dan Willemsen7b310ee2015-12-18 15:11:17 -0800297 ret := make(Paths, 0, len(paths))
298 for _, path := range paths {
Colin Cross32f38982018-02-22 11:47:25 -0800299 p := ExistentPathForSource(ctx, path)
Dan Willemsen7b310ee2015-12-18 15:11:17 -0800300 if p.Valid() {
301 ret = append(ret, p.Path())
302 }
303 }
304 return ret
305}
306
Colin Cross41955e82019-05-29 14:40:35 -0700307// PathsForModuleSrc returns Paths rooted from the module's local source directory. It expands globs, references to
308// SourceFileProducer modules using the ":name" syntax, and references to OutputFileProducer modules using the
309// ":name{.tag}" syntax. Properties passed as the paths argument must have been annotated with struct tag
310// `android:"path"` so that dependencies on SourceFileProducer modules will have already been handled by the
311// path_properties mutator. If ctx.Config().AllowMissingDependencies() is true then any missing SourceFileProducer or
312// OutputFileProducer dependencies will cause the module to be marked as having missing dependencies.
Liz Kammera830f3a2020-11-10 10:50:34 -0800313func PathsForModuleSrc(ctx ModuleMissingDepsPathContext, paths []string) Paths {
Colin Cross8a497952019-03-05 22:25:09 -0800314 return PathsForModuleSrcExcludes(ctx, paths, nil)
315}
316
Colin Crossba71a3f2019-03-18 12:12:48 -0700317// PathsForModuleSrcExcludes returns Paths rooted from the module's local source directory, excluding paths listed in
Colin Cross41955e82019-05-29 14:40:35 -0700318// the excludes arguments. It expands globs, references to SourceFileProducer modules using the ":name" syntax, and
319// references to OutputFileProducer modules using the ":name{.tag}" syntax. Properties passed as the paths or excludes
320// argument must have been annotated with struct tag `android:"path"` so that dependencies on SourceFileProducer modules
321// will have already been handled by the path_properties mutator. If ctx.Config().AllowMissingDependencies() is
Paul Duffin036cace2019-07-25 14:44:56 +0100322// true then any missing SourceFileProducer or OutputFileProducer dependencies will cause the module to be marked as
Colin Cross41955e82019-05-29 14:40:35 -0700323// having missing dependencies.
Liz Kammera830f3a2020-11-10 10:50:34 -0800324func PathsForModuleSrcExcludes(ctx ModuleMissingDepsPathContext, paths, excludes []string) Paths {
Colin Crossba71a3f2019-03-18 12:12:48 -0700325 ret, missingDeps := PathsAndMissingDepsForModuleSrcExcludes(ctx, paths, excludes)
326 if ctx.Config().AllowMissingDependencies() {
327 ctx.AddMissingDependencies(missingDeps)
328 } else {
329 for _, m := range missingDeps {
330 ctx.ModuleErrorf(`missing dependency on %q, is the property annotated with android:"path"?`, m)
331 }
332 }
333 return ret
334}
335
Liz Kammer356f7d42021-01-26 09:18:53 -0500336// A subset of the ModuleContext methods which are sufficient to resolve references to paths/deps in
337// order to form a Bazel-compatible label for conversion.
338type BazelConversionPathContext interface {
339 EarlyModulePathContext
340
341 GetDirectDep(name string) (blueprint.Module, blueprint.DependencyTag)
Liz Kammerbdc60992021-02-24 16:55:11 -0500342 Module() Module
Jingwen Chen12b4c272021-03-10 02:05:59 -0500343 ModuleType() string
Liz Kammer356f7d42021-01-26 09:18:53 -0500344 OtherModuleName(m blueprint.Module) string
345 OtherModuleDir(m blueprint.Module) string
346}
347
348// BazelLabelForModuleDeps returns a Bazel-compatible label for the requested modules which
349// correspond to dependencies on the module within the given ctx.
350func BazelLabelForModuleDeps(ctx BazelConversionPathContext, modules []string) bazel.LabelList {
351 var labels bazel.LabelList
352 for _, module := range modules {
353 bpText := module
354 if m := SrcIsModule(module); m == "" {
355 module = ":" + module
356 }
357 if m, t := SrcIsModuleWithTag(module); m != "" {
358 l := getOtherModuleLabel(ctx, m, t)
359 l.Bp_text = bpText
360 labels.Includes = append(labels.Includes, l)
361 } else {
362 ctx.ModuleErrorf("%q, is not a module reference", module)
363 }
364 }
365 return labels
366}
367
368// BazelLabelForModuleSrc returns bazel.LabelList with paths rooted from the module's local source
369// directory. It expands globs, and resolves references to modules using the ":name" syntax to
370// bazel-compatible labels. Properties passed as the paths or excludes argument must have been
371// annotated with struct tag `android:"path"` so that dependencies on other modules will have
372// already been handled by the path_properties mutator.
373func BazelLabelForModuleSrc(ctx BazelConversionPathContext, paths []string) bazel.LabelList {
374 return BazelLabelForModuleSrcExcludes(ctx, paths, []string(nil))
375}
376
377// BazelLabelForModuleSrcExcludes returns bazel.LabelList with paths rooted from the module's local
378// source directory, excluding labels included in the excludes argument. It expands globs, and
379// resolves references to modules using the ":name" syntax to bazel-compatible labels. Properties
380// passed as the paths or excludes argument must have been annotated with struct tag
381// `android:"path"` so that dependencies on other modules will have already been handled by the
382// path_properties mutator.
383func BazelLabelForModuleSrcExcludes(ctx BazelConversionPathContext, paths, excludes []string) bazel.LabelList {
384 excludeLabels := expandSrcsForBazel(ctx, excludes, []string(nil))
385 excluded := make([]string, 0, len(excludeLabels.Includes))
386 for _, e := range excludeLabels.Includes {
387 excluded = append(excluded, e.Label)
388 }
389 labels := expandSrcsForBazel(ctx, paths, excluded)
390 labels.Excludes = excludeLabels.Includes
391 return labels
392}
393
394// expandSrcsForBazel returns bazel.LabelList with paths rooted from the module's local
395// source directory, excluding labels included in the excludes argument. It expands globs, and
396// resolves references to modules using the ":name" syntax to bazel-compatible labels. Properties
397// passed as the paths or excludes argument must have been annotated with struct tag
398// `android:"path"` so that dependencies on other modules will have already been handled by the
399// path_properties mutator.
400func expandSrcsForBazel(ctx BazelConversionPathContext, paths, expandedExcludes []string) bazel.LabelList {
Liz Kammerebfcf672021-02-16 15:00:05 -0500401 if paths == nil {
402 return bazel.LabelList{}
403 }
Liz Kammer356f7d42021-01-26 09:18:53 -0500404 labels := bazel.LabelList{
405 Includes: []bazel.Label{},
406 }
407 for _, p := range paths {
408 if m, tag := SrcIsModuleWithTag(p); m != "" {
409 l := getOtherModuleLabel(ctx, m, tag)
410 if !InList(l.Label, expandedExcludes) {
411 l.Bp_text = fmt.Sprintf(":%s", m)
412 labels.Includes = append(labels.Includes, l)
413 }
414 } else {
415 var expandedPaths []bazel.Label
416 if pathtools.IsGlob(p) {
417 globbedPaths := GlobFiles(ctx, pathForModuleSrc(ctx, p).String(), expandedExcludes)
418 globbedPaths = PathsWithModuleSrcSubDir(ctx, globbedPaths, "")
419 for _, path := range globbedPaths {
420 s := path.Rel()
421 expandedPaths = append(expandedPaths, bazel.Label{Label: s})
422 }
423 } else {
424 if !InList(p, expandedExcludes) {
425 expandedPaths = append(expandedPaths, bazel.Label{Label: p})
426 }
427 }
428 labels.Includes = append(labels.Includes, expandedPaths...)
429 }
430 }
431 return labels
432}
433
434// getOtherModuleLabel returns a bazel.Label for the given dependency/tag combination for the
435// module. The label will be relative to the current directory if appropriate. The dependency must
436// already be resolved by either deps mutator or path deps mutator.
437func getOtherModuleLabel(ctx BazelConversionPathContext, dep, tag string) bazel.Label {
438 m, _ := ctx.GetDirectDep(dep)
Liz Kammerbdc60992021-02-24 16:55:11 -0500439 otherLabel := bazelModuleLabel(ctx, m, tag)
440 label := bazelModuleLabel(ctx, ctx.Module(), "")
441 if samePackage(label, otherLabel) {
442 otherLabel = bazelShortLabel(otherLabel)
Liz Kammer356f7d42021-01-26 09:18:53 -0500443 }
Liz Kammerbdc60992021-02-24 16:55:11 -0500444
445 return bazel.Label{
446 Label: otherLabel,
447 }
448}
449
450func bazelModuleLabel(ctx BazelConversionPathContext, module blueprint.Module, tag string) string {
451 // TODO(b/165114590): Convert tag (":name{.tag}") to corresponding Bazel implicit output targets.
452 b, ok := module.(Bazelable)
453 // TODO(b/181155349): perhaps return an error here if the module can't be/isn't being converted
Jingwen Chen12b4c272021-03-10 02:05:59 -0500454 if !ok || !b.ConvertedToBazel(ctx) {
Liz Kammerbdc60992021-02-24 16:55:11 -0500455 return bp2buildModuleLabel(ctx, module)
456 }
457 return b.GetBazelLabel(ctx, module)
458}
459
460func bazelShortLabel(label string) string {
461 i := strings.Index(label, ":")
462 return label[i:]
463}
464
465func bazelPackage(label string) string {
466 i := strings.Index(label, ":")
467 return label[0:i]
468}
469
470func samePackage(label1, label2 string) bool {
471 return bazelPackage(label1) == bazelPackage(label2)
472}
473
474func bp2buildModuleLabel(ctx BazelConversionPathContext, module blueprint.Module) string {
475 moduleName := ctx.OtherModuleName(module)
476 moduleDir := ctx.OtherModuleDir(module)
477 return fmt.Sprintf("//%s:%s", moduleDir, moduleName)
Liz Kammer356f7d42021-01-26 09:18:53 -0500478}
479
Ulya Trafimovich4d2eeed2019-11-08 10:54:21 +0000480// OutputPaths is a slice of OutputPath objects, with helpers to operate on the collection.
481type OutputPaths []OutputPath
482
483// Paths returns the OutputPaths as a Paths
484func (p OutputPaths) Paths() Paths {
485 if p == nil {
486 return nil
487 }
488 ret := make(Paths, len(p))
489 for i, path := range p {
490 ret[i] = path
491 }
492 return ret
493}
494
495// Strings returns the string forms of the writable paths.
496func (p OutputPaths) Strings() []string {
497 if p == nil {
498 return nil
499 }
500 ret := make([]string, len(p))
501 for i, path := range p {
502 ret[i] = path.String()
503 }
504 return ret
505}
506
Liz Kammera830f3a2020-11-10 10:50:34 -0800507// Expands Paths to a SourceFileProducer or OutputFileProducer module dependency referenced via ":name" or ":name{.tag}" syntax.
508// If the dependency is not found, a missingErrorDependency is returned.
509// If the module dependency is not a SourceFileProducer or OutputFileProducer, appropriate errors will be returned.
510func getPathsFromModuleDep(ctx ModuleWithDepsPathContext, path, moduleName, tag string) (Paths, error) {
511 module := ctx.GetDirectDepWithTag(moduleName, sourceOrOutputDepTag(tag))
512 if module == nil {
513 return nil, missingDependencyError{[]string{moduleName}}
514 }
Colin Crossfa65cee2021-03-22 17:05:59 -0700515 if aModule, ok := module.(Module); ok && !aModule.Enabled() {
516 return nil, missingDependencyError{[]string{moduleName}}
517 }
Liz Kammera830f3a2020-11-10 10:50:34 -0800518 if outProducer, ok := module.(OutputFileProducer); ok {
519 outputFiles, err := outProducer.OutputFiles(tag)
520 if err != nil {
521 return nil, fmt.Errorf("path dependency %q: %s", path, err)
522 }
523 return outputFiles, nil
524 } else if tag != "" {
525 return nil, fmt.Errorf("path dependency %q is not an output file producing module", path)
526 } else if srcProducer, ok := module.(SourceFileProducer); ok {
527 return srcProducer.Srcs(), nil
528 } else {
529 return nil, fmt.Errorf("path dependency %q is not a source file producing module", path)
530 }
531}
532
Colin Crossba71a3f2019-03-18 12:12:48 -0700533// PathsAndMissingDepsForModuleSrcExcludes returns Paths rooted from the module's local source directory, excluding
Colin Cross41955e82019-05-29 14:40:35 -0700534// paths listed in the excludes arguments, and a list of missing dependencies. It expands globs, references to
535// SourceFileProducer modules using the ":name" syntax, and references to OutputFileProducer modules using the
536// ":name{.tag}" syntax. Properties passed as the paths or excludes argument must have been annotated with struct tag
537// `android:"path"` so that dependencies on SourceFileProducer modules will have already been handled by the
538// path_properties mutator. If ctx.Config().AllowMissingDependencies() is true then any missing SourceFileProducer or
539// OutputFileProducer dependencies will be returned, and they will NOT cause the module to be marked as having missing
540// dependencies.
Liz Kammera830f3a2020-11-10 10:50:34 -0800541func PathsAndMissingDepsForModuleSrcExcludes(ctx ModuleWithDepsPathContext, paths, excludes []string) (Paths, []string) {
Colin Cross8a497952019-03-05 22:25:09 -0800542 prefix := pathForModuleSrc(ctx).String()
543
544 var expandedExcludes []string
545 if excludes != nil {
546 expandedExcludes = make([]string, 0, len(excludes))
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700547 }
Colin Cross8a497952019-03-05 22:25:09 -0800548
Colin Crossba71a3f2019-03-18 12:12:48 -0700549 var missingExcludeDeps []string
550
Colin Cross8a497952019-03-05 22:25:09 -0800551 for _, e := range excludes {
Colin Cross41955e82019-05-29 14:40:35 -0700552 if m, t := SrcIsModuleWithTag(e); m != "" {
Liz Kammera830f3a2020-11-10 10:50:34 -0800553 modulePaths, err := getPathsFromModuleDep(ctx, e, m, t)
554 if m, ok := err.(missingDependencyError); ok {
555 missingExcludeDeps = append(missingExcludeDeps, m.missingDeps...)
556 } else if err != nil {
557 reportPathError(ctx, err)
Colin Cross8a497952019-03-05 22:25:09 -0800558 } else {
Liz Kammera830f3a2020-11-10 10:50:34 -0800559 expandedExcludes = append(expandedExcludes, modulePaths.Strings()...)
Colin Cross8a497952019-03-05 22:25:09 -0800560 }
561 } else {
562 expandedExcludes = append(expandedExcludes, filepath.Join(prefix, e))
563 }
564 }
565
566 if paths == nil {
Colin Crossba71a3f2019-03-18 12:12:48 -0700567 return nil, missingExcludeDeps
Colin Cross8a497952019-03-05 22:25:09 -0800568 }
569
Colin Crossba71a3f2019-03-18 12:12:48 -0700570 var missingDeps []string
571
Colin Cross8a497952019-03-05 22:25:09 -0800572 expandedSrcFiles := make(Paths, 0, len(paths))
573 for _, s := range paths {
574 srcFiles, err := expandOneSrcPath(ctx, s, expandedExcludes)
575 if depErr, ok := err.(missingDependencyError); ok {
Colin Crossba71a3f2019-03-18 12:12:48 -0700576 missingDeps = append(missingDeps, depErr.missingDeps...)
Colin Cross8a497952019-03-05 22:25:09 -0800577 } else if err != nil {
578 reportPathError(ctx, err)
579 }
580 expandedSrcFiles = append(expandedSrcFiles, srcFiles...)
581 }
Colin Crossba71a3f2019-03-18 12:12:48 -0700582
583 return expandedSrcFiles, append(missingDeps, missingExcludeDeps...)
Colin Cross8a497952019-03-05 22:25:09 -0800584}
585
586type missingDependencyError struct {
587 missingDeps []string
588}
589
590func (e missingDependencyError) Error() string {
591 return "missing dependencies: " + strings.Join(e.missingDeps, ", ")
592}
593
Liz Kammera830f3a2020-11-10 10:50:34 -0800594// Expands one path string to Paths rooted from the module's local source
595// directory, excluding those listed in the expandedExcludes.
596// Expands globs, references to SourceFileProducer or OutputFileProducer modules using the ":name" and ":name{.tag}" syntax.
597func expandOneSrcPath(ctx ModuleWithDepsPathContext, sPath string, expandedExcludes []string) (Paths, error) {
Jooyung Han7607dd32020-07-05 10:23:14 +0900598 excludePaths := func(paths Paths) Paths {
599 if len(expandedExcludes) == 0 {
600 return paths
601 }
602 remainder := make(Paths, 0, len(paths))
603 for _, p := range paths {
604 if !InList(p.String(), expandedExcludes) {
605 remainder = append(remainder, p)
606 }
607 }
608 return remainder
609 }
Liz Kammera830f3a2020-11-10 10:50:34 -0800610 if m, t := SrcIsModuleWithTag(sPath); m != "" {
611 modulePaths, err := getPathsFromModuleDep(ctx, sPath, m, t)
612 if err != nil {
613 return nil, err
Colin Cross8a497952019-03-05 22:25:09 -0800614 } else {
Liz Kammera830f3a2020-11-10 10:50:34 -0800615 return excludePaths(modulePaths), nil
Colin Cross8a497952019-03-05 22:25:09 -0800616 }
Liz Kammera830f3a2020-11-10 10:50:34 -0800617 } else if pathtools.IsGlob(sPath) {
618 paths := GlobFiles(ctx, pathForModuleSrc(ctx, sPath).String(), expandedExcludes)
Colin Cross8a497952019-03-05 22:25:09 -0800619 return PathsWithModuleSrcSubDir(ctx, paths, ""), nil
620 } else {
Liz Kammera830f3a2020-11-10 10:50:34 -0800621 p := pathForModuleSrc(ctx, sPath)
Colin Cross988414c2020-01-11 01:11:46 +0000622 if exists, _, err := ctx.Config().fs.Exists(p.String()); err != nil {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +0100623 ReportPathErrorf(ctx, "%s: %s", p, err.Error())
Pedro Loureiro5d190cc2021-02-15 15:41:33 +0000624 } else if !exists && !ctx.Config().TestAllowNonExistentPaths {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +0100625 ReportPathErrorf(ctx, "module source path %q does not exist", p)
Colin Cross8a497952019-03-05 22:25:09 -0800626 }
627
Jooyung Han7607dd32020-07-05 10:23:14 +0900628 if InList(p.String(), expandedExcludes) {
Colin Cross8a497952019-03-05 22:25:09 -0800629 return nil, nil
630 }
631 return Paths{p}, nil
632 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700633}
634
635// pathsForModuleSrcFromFullPath returns Paths rooted from the module's local
636// source directory, but strip the local source directory from the beginning of
Dan Willemsen540a78c2018-02-26 21:50:08 -0800637// each string. If incDirs is false, strip paths with a trailing '/' from the list.
Colin Crossfe4bc362018-09-12 10:02:13 -0700638// It intended for use in globs that only list files that exist, so it allows '$' in
639// filenames.
Liz Kammera830f3a2020-11-10 10:50:34 -0800640func pathsForModuleSrcFromFullPath(ctx EarlyModulePathContext, paths []string, incDirs bool) Paths {
Colin Cross6510f912017-11-29 00:27:14 -0800641 prefix := filepath.Join(ctx.Config().srcDir, ctx.ModuleDir()) + "/"
Colin Cross0f37af02017-09-27 17:42:05 -0700642 if prefix == "./" {
643 prefix = ""
644 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700645 ret := make(Paths, 0, len(paths))
646 for _, p := range paths {
Dan Willemsen540a78c2018-02-26 21:50:08 -0800647 if !incDirs && strings.HasSuffix(p, "/") {
648 continue
649 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700650 path := filepath.Clean(p)
651 if !strings.HasPrefix(path, prefix) {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +0100652 ReportPathErrorf(ctx, "Path %q is not in module source directory %q", p, prefix)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700653 continue
654 }
Colin Crosse3924e12018-08-15 20:18:53 -0700655
Colin Crossfe4bc362018-09-12 10:02:13 -0700656 srcPath, err := safePathForSource(ctx, ctx.ModuleDir(), path[len(prefix):])
Colin Crosse3924e12018-08-15 20:18:53 -0700657 if err != nil {
658 reportPathError(ctx, err)
659 continue
660 }
661
Colin Cross07e51612019-03-05 12:46:40 -0800662 srcPath.basePath.rel = srcPath.path
Colin Crosse3924e12018-08-15 20:18:53 -0700663
Colin Cross07e51612019-03-05 12:46:40 -0800664 ret = append(ret, srcPath)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700665 }
666 return ret
667}
668
Liz Kammera830f3a2020-11-10 10:50:34 -0800669// PathsWithOptionalDefaultForModuleSrc returns Paths rooted from the module's local source
670// directory. If input is nil, use the default if it exists. If input is empty, returns nil.
671func PathsWithOptionalDefaultForModuleSrc(ctx ModuleMissingDepsPathContext, input []string, def string) Paths {
Colin Cross0ddae7f2019-02-07 15:30:01 -0800672 if input != nil {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700673 return PathsForModuleSrc(ctx, input)
674 }
675 // Use Glob so that if the default doesn't exist, a dependency is added so that when it
676 // is created, we're run again.
Colin Cross6510f912017-11-29 00:27:14 -0800677 path := filepath.Join(ctx.Config().srcDir, ctx.ModuleDir(), def)
Liz Kammera830f3a2020-11-10 10:50:34 -0800678 return Glob(ctx, path, nil)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700679}
680
681// Strings returns the Paths in string form
682func (p Paths) Strings() []string {
683 if p == nil {
684 return nil
685 }
686 ret := make([]string, len(p))
687 for i, path := range p {
688 ret[i] = path.String()
689 }
690 return ret
691}
692
Colin Crossc0efd1d2020-07-03 11:56:24 -0700693func CopyOfPaths(paths Paths) Paths {
694 return append(Paths(nil), paths...)
695}
696
Colin Crossb6715442017-10-24 11:13:31 -0700697// FirstUniquePaths returns all unique elements of a Paths, keeping the first copy of each. It
698// modifies the Paths slice contents in place, and returns a subslice of the original slice.
Dan Willemsenfe92c962017-08-29 12:28:37 -0700699func FirstUniquePaths(list Paths) Paths {
Colin Cross27027c72020-02-28 15:34:17 -0800700 // 128 was chosen based on BenchmarkFirstUniquePaths results.
701 if len(list) > 128 {
702 return firstUniquePathsMap(list)
703 }
704 return firstUniquePathsList(list)
705}
706
Colin Crossc0efd1d2020-07-03 11:56:24 -0700707// SortedUniquePaths returns all unique elements of a Paths in sorted order. It modifies the
708// Paths slice contents in place, and returns a subslice of the original slice.
Jiyong Park33c77362020-05-29 22:00:16 +0900709func SortedUniquePaths(list Paths) Paths {
710 unique := FirstUniquePaths(list)
711 sort.Slice(unique, func(i, j int) bool {
712 return unique[i].String() < unique[j].String()
713 })
714 return unique
715}
716
Colin Cross27027c72020-02-28 15:34:17 -0800717func firstUniquePathsList(list Paths) Paths {
Dan Willemsenfe92c962017-08-29 12:28:37 -0700718 k := 0
719outer:
720 for i := 0; i < len(list); i++ {
721 for j := 0; j < k; j++ {
722 if list[i] == list[j] {
723 continue outer
724 }
725 }
726 list[k] = list[i]
727 k++
728 }
729 return list[:k]
730}
731
Colin Cross27027c72020-02-28 15:34:17 -0800732func firstUniquePathsMap(list Paths) Paths {
733 k := 0
734 seen := make(map[Path]bool, len(list))
735 for i := 0; i < len(list); i++ {
736 if seen[list[i]] {
737 continue
738 }
739 seen[list[i]] = true
740 list[k] = list[i]
741 k++
742 }
743 return list[:k]
744}
745
Colin Cross5d583952020-11-24 16:21:24 -0800746// FirstUniqueInstallPaths returns all unique elements of an InstallPaths, keeping the first copy of each. It
747// modifies the InstallPaths slice contents in place, and returns a subslice of the original slice.
748func FirstUniqueInstallPaths(list InstallPaths) InstallPaths {
749 // 128 was chosen based on BenchmarkFirstUniquePaths results.
750 if len(list) > 128 {
751 return firstUniqueInstallPathsMap(list)
752 }
753 return firstUniqueInstallPathsList(list)
754}
755
756func firstUniqueInstallPathsList(list InstallPaths) InstallPaths {
757 k := 0
758outer:
759 for i := 0; i < len(list); i++ {
760 for j := 0; j < k; j++ {
761 if list[i] == list[j] {
762 continue outer
763 }
764 }
765 list[k] = list[i]
766 k++
767 }
768 return list[:k]
769}
770
771func firstUniqueInstallPathsMap(list InstallPaths) InstallPaths {
772 k := 0
773 seen := make(map[InstallPath]bool, len(list))
774 for i := 0; i < len(list); i++ {
775 if seen[list[i]] {
776 continue
777 }
778 seen[list[i]] = true
779 list[k] = list[i]
780 k++
781 }
782 return list[:k]
783}
784
Colin Crossb6715442017-10-24 11:13:31 -0700785// LastUniquePaths returns all unique elements of a Paths, keeping the last copy of each. It
786// modifies the Paths slice contents in place, and returns a subslice of the original slice.
787func LastUniquePaths(list Paths) Paths {
788 totalSkip := 0
789 for i := len(list) - 1; i >= totalSkip; i-- {
790 skip := 0
791 for j := i - 1; j >= totalSkip; j-- {
792 if list[i] == list[j] {
793 skip++
794 } else {
795 list[j+skip] = list[j]
796 }
797 }
798 totalSkip += skip
799 }
800 return list[totalSkip:]
801}
802
Colin Crossa140bb02018-04-17 10:52:26 -0700803// ReversePaths returns a copy of a Paths in reverse order.
804func ReversePaths(list Paths) Paths {
805 if list == nil {
806 return nil
807 }
808 ret := make(Paths, len(list))
809 for i := range list {
810 ret[i] = list[len(list)-1-i]
811 }
812 return ret
813}
814
Jeff Gaston294356f2017-09-27 17:05:30 -0700815func indexPathList(s Path, list []Path) int {
816 for i, l := range list {
817 if l == s {
818 return i
819 }
820 }
821
822 return -1
823}
824
825func inPathList(p Path, list []Path) bool {
826 return indexPathList(p, list) != -1
827}
828
829func FilterPathList(list []Path, filter []Path) (remainder []Path, filtered []Path) {
Paul Duffin57b9e1d2019-12-13 00:03:35 +0000830 return FilterPathListPredicate(list, func(p Path) bool { return inPathList(p, filter) })
831}
832
833func FilterPathListPredicate(list []Path, predicate func(Path) bool) (remainder []Path, filtered []Path) {
Jeff Gaston294356f2017-09-27 17:05:30 -0700834 for _, l := range list {
Paul Duffin57b9e1d2019-12-13 00:03:35 +0000835 if predicate(l) {
Jeff Gaston294356f2017-09-27 17:05:30 -0700836 filtered = append(filtered, l)
837 } else {
838 remainder = append(remainder, l)
839 }
840 }
841
842 return
843}
844
Colin Cross93e85952017-08-15 13:34:18 -0700845// HasExt returns true of any of the paths have extension ext, otherwise false
846func (p Paths) HasExt(ext string) bool {
847 for _, path := range p {
848 if path.Ext() == ext {
849 return true
850 }
851 }
852
853 return false
854}
855
856// FilterByExt returns the subset of the paths that have extension ext
857func (p Paths) FilterByExt(ext string) Paths {
858 ret := make(Paths, 0, len(p))
859 for _, path := range p {
860 if path.Ext() == ext {
861 ret = append(ret, path)
862 }
863 }
864 return ret
865}
866
867// FilterOutByExt returns the subset of the paths that do not have extension ext
868func (p Paths) FilterOutByExt(ext string) Paths {
869 ret := make(Paths, 0, len(p))
870 for _, path := range p {
871 if path.Ext() != ext {
872 ret = append(ret, path)
873 }
874 }
875 return ret
876}
877
Colin Cross5e6cfbe2017-11-03 15:20:35 -0700878// DirectorySortedPaths is a slice of paths that are sorted such that all files in a directory
879// (including subdirectories) are in a contiguous subslice of the list, and can be found in
880// O(log(N)) time using a binary search on the directory prefix.
881type DirectorySortedPaths Paths
882
883func PathsToDirectorySortedPaths(paths Paths) DirectorySortedPaths {
884 ret := append(DirectorySortedPaths(nil), paths...)
885 sort.Slice(ret, func(i, j int) bool {
886 return ret[i].String() < ret[j].String()
887 })
888 return ret
889}
890
891// PathsInDirectory returns a subslice of the DirectorySortedPaths as a Paths that contains all entries
892// that are in the specified directory and its subdirectories.
893func (p DirectorySortedPaths) PathsInDirectory(dir string) Paths {
894 prefix := filepath.Clean(dir) + "/"
895 start := sort.Search(len(p), func(i int) bool {
896 return prefix < p[i].String()
897 })
898
899 ret := p[start:]
900
901 end := sort.Search(len(ret), func(i int) bool {
902 return !strings.HasPrefix(ret[i].String(), prefix)
903 })
904
905 ret = ret[:end]
906
907 return Paths(ret)
908}
909
Alex Humesky29e3bbe2020-11-20 21:30:13 -0500910// WritablePaths is a slice of WritablePath, used for multiple outputs.
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700911type WritablePaths []WritablePath
912
913// Strings returns the string forms of the writable paths.
914func (p WritablePaths) Strings() []string {
915 if p == nil {
916 return nil
917 }
918 ret := make([]string, len(p))
919 for i, path := range p {
920 ret[i] = path.String()
921 }
922 return ret
923}
924
Colin Cross3bc7ffa2017-11-22 16:19:37 -0800925// Paths returns the WritablePaths as a Paths
926func (p WritablePaths) Paths() Paths {
927 if p == nil {
928 return nil
929 }
930 ret := make(Paths, len(p))
931 for i, path := range p {
932 ret[i] = path
933 }
934 return ret
935}
936
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700937type basePath struct {
938 path string
939 config Config
Colin Crossfaeb7aa2017-02-01 14:12:44 -0800940 rel string
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700941}
942
943func (p basePath) Ext() string {
944 return filepath.Ext(p.path)
945}
946
Colin Cross4f6fc9c2016-10-26 10:05:25 -0700947func (p basePath) Base() string {
948 return filepath.Base(p.path)
949}
950
Colin Crossfaeb7aa2017-02-01 14:12:44 -0800951func (p basePath) Rel() string {
952 if p.rel != "" {
953 return p.rel
954 }
955 return p.path
956}
957
Colin Cross0875c522017-11-28 17:34:01 -0800958func (p basePath) String() string {
959 return p.path
960}
961
Colin Cross0db55682017-12-05 15:36:55 -0800962func (p basePath) withRel(rel string) basePath {
963 p.path = filepath.Join(p.path, rel)
964 p.rel = rel
965 return p
966}
967
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700968// SourcePath is a Path representing a file path rooted from SrcDir
969type SourcePath struct {
970 basePath
Paul Duffin580efc82021-03-24 09:04:03 +0000971
972 // The sources root, i.e. Config.SrcDir()
973 srcDir string
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700974}
975
976var _ Path = SourcePath{}
977
Colin Cross0db55682017-12-05 15:36:55 -0800978func (p SourcePath) withRel(rel string) SourcePath {
979 p.basePath = p.basePath.withRel(rel)
980 return p
981}
982
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700983// safePathForSource is for paths that we expect are safe -- only for use by go
984// code that is embedding ninja variables in paths
Colin Crossfe4bc362018-09-12 10:02:13 -0700985func safePathForSource(ctx PathContext, pathComponents ...string) (SourcePath, error) {
986 p, err := validateSafePath(pathComponents...)
Paul Duffin580efc82021-03-24 09:04:03 +0000987 ret := SourcePath{basePath{p, ctx.Config(), ""}, ctx.Config().srcDir}
Colin Crossfe4bc362018-09-12 10:02:13 -0700988 if err != nil {
989 return ret, err
990 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700991
Colin Cross7b3dcc32019-01-24 13:14:39 -0800992 // absolute path already checked by validateSafePath
993 if strings.HasPrefix(ret.String(), ctx.Config().buildDir) {
Mikhail Naganovab1f5182019-02-08 13:17:55 -0800994 return ret, fmt.Errorf("source path %q is in output", ret.String())
Colin Cross6e18ca42015-07-14 18:55:36 -0700995 }
996
Colin Crossfe4bc362018-09-12 10:02:13 -0700997 return ret, err
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700998}
999
Colin Cross192e97a2018-02-22 14:21:02 -08001000// pathForSource creates a SourcePath from pathComponents, but does not check that it exists.
1001func pathForSource(ctx PathContext, pathComponents ...string) (SourcePath, error) {
Colin Crossc48c1432018-02-23 07:09:01 +00001002 p, err := validatePath(pathComponents...)
Paul Duffin580efc82021-03-24 09:04:03 +00001003 ret := SourcePath{basePath{p, ctx.Config(), ""}, ctx.Config().srcDir}
Colin Cross94a32102018-02-22 14:21:02 -08001004 if err != nil {
Colin Cross192e97a2018-02-22 14:21:02 -08001005 return ret, err
Colin Cross94a32102018-02-22 14:21:02 -08001006 }
1007
Colin Cross7b3dcc32019-01-24 13:14:39 -08001008 // absolute path already checked by validatePath
1009 if strings.HasPrefix(ret.String(), ctx.Config().buildDir) {
Mikhail Naganovab1f5182019-02-08 13:17:55 -08001010 return ret, fmt.Errorf("source path %q is in output", ret.String())
Colin Crossc48c1432018-02-23 07:09:01 +00001011 }
1012
Colin Cross192e97a2018-02-22 14:21:02 -08001013 return ret, nil
1014}
1015
1016// existsWithDependencies returns true if the path exists, and adds appropriate dependencies to rerun if the
1017// path does not exist.
1018func existsWithDependencies(ctx PathContext, path SourcePath) (exists bool, err error) {
1019 var files []string
1020
1021 if gctx, ok := ctx.(PathGlobContext); ok {
1022 // Use glob to produce proper dependencies, even though we only want
1023 // a single file.
1024 files, err = gctx.GlobWithDeps(path.String(), nil)
1025 } else {
1026 var deps []string
1027 // We cannot add build statements in this context, so we fall back to
1028 // AddNinjaFileDeps
Colin Cross988414c2020-01-11 01:11:46 +00001029 files, deps, err = ctx.Config().fs.Glob(path.String(), nil, pathtools.FollowSymlinks)
Colin Cross192e97a2018-02-22 14:21:02 -08001030 ctx.AddNinjaFileDeps(deps...)
1031 }
1032
1033 if err != nil {
1034 return false, fmt.Errorf("glob: %s", err.Error())
1035 }
1036
1037 return len(files) > 0, nil
1038}
1039
1040// PathForSource joins the provided path components and validates that the result
1041// neither escapes the source dir nor is in the out dir.
1042// On error, it will return a usable, but invalid SourcePath, and report a ModuleError.
1043func PathForSource(ctx PathContext, pathComponents ...string) SourcePath {
1044 path, err := pathForSource(ctx, pathComponents...)
1045 if err != nil {
1046 reportPathError(ctx, err)
1047 }
1048
Colin Crosse3924e12018-08-15 20:18:53 -07001049 if pathtools.IsGlob(path.String()) {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001050 ReportPathErrorf(ctx, "path may not contain a glob: %s", path.String())
Colin Crosse3924e12018-08-15 20:18:53 -07001051 }
1052
Liz Kammera830f3a2020-11-10 10:50:34 -08001053 if modCtx, ok := ctx.(ModuleMissingDepsPathContext); ok && ctx.Config().AllowMissingDependencies() {
Colin Cross192e97a2018-02-22 14:21:02 -08001054 exists, err := existsWithDependencies(ctx, path)
1055 if err != nil {
1056 reportPathError(ctx, err)
1057 }
1058 if !exists {
1059 modCtx.AddMissingDependencies([]string{path.String()})
1060 }
Colin Cross988414c2020-01-11 01:11:46 +00001061 } else if exists, _, err := ctx.Config().fs.Exists(path.String()); err != nil {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001062 ReportPathErrorf(ctx, "%s: %s", path, err.Error())
Pedro Loureiro5d190cc2021-02-15 15:41:33 +00001063 } else if !exists && !ctx.Config().TestAllowNonExistentPaths {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001064 ReportPathErrorf(ctx, "source path %q does not exist", path)
Colin Cross192e97a2018-02-22 14:21:02 -08001065 }
1066 return path
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001067}
1068
Liz Kammer7aa52882021-02-11 09:16:14 -05001069// ExistentPathForSource returns an OptionalPath with the SourcePath, rooted from SrcDir, *not*
1070// rooted from the module's local source directory, if the path exists, or an empty OptionalPath if
1071// it doesn't exist. Dependencies are added so that the ninja file will be regenerated if the state
1072// of the path changes.
Colin Cross32f38982018-02-22 11:47:25 -08001073func ExistentPathForSource(ctx PathContext, pathComponents ...string) OptionalPath {
Colin Cross192e97a2018-02-22 14:21:02 -08001074 path, err := pathForSource(ctx, pathComponents...)
Colin Cross1ccfcc32018-02-22 13:54:26 -08001075 if err != nil {
1076 reportPathError(ctx, err)
1077 return OptionalPath{}
1078 }
Colin Crossc48c1432018-02-23 07:09:01 +00001079
Colin Crosse3924e12018-08-15 20:18:53 -07001080 if pathtools.IsGlob(path.String()) {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001081 ReportPathErrorf(ctx, "path may not contain a glob: %s", path.String())
Colin Crosse3924e12018-08-15 20:18:53 -07001082 return OptionalPath{}
1083 }
1084
Colin Cross192e97a2018-02-22 14:21:02 -08001085 exists, err := existsWithDependencies(ctx, path)
Colin Crossc48c1432018-02-23 07:09:01 +00001086 if err != nil {
1087 reportPathError(ctx, err)
1088 return OptionalPath{}
1089 }
Colin Cross192e97a2018-02-22 14:21:02 -08001090 if !exists {
Colin Crossc48c1432018-02-23 07:09:01 +00001091 return OptionalPath{}
1092 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001093 return OptionalPathForPath(path)
1094}
1095
1096func (p SourcePath) String() string {
Paul Duffin580efc82021-03-24 09:04:03 +00001097 return filepath.Join(p.srcDir, p.path)
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001098}
1099
1100// Join creates a new SourcePath with paths... joined with the current path. The
1101// provided paths... may not use '..' to escape from the current path.
1102func (p SourcePath) Join(ctx PathContext, paths ...string) SourcePath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001103 path, err := validatePath(paths...)
1104 if err != nil {
1105 reportPathError(ctx, err)
1106 }
Colin Cross0db55682017-12-05 15:36:55 -08001107 return p.withRel(path)
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001108}
1109
Colin Cross2fafa3e2019-03-05 12:39:51 -08001110// join is like Join but does less path validation.
1111func (p SourcePath) join(ctx PathContext, paths ...string) SourcePath {
1112 path, err := validateSafePath(paths...)
1113 if err != nil {
1114 reportPathError(ctx, err)
1115 }
1116 return p.withRel(path)
1117}
1118
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001119// OverlayPath returns the overlay for `path' if it exists. This assumes that the
1120// SourcePath is the path to a resource overlay directory.
Liz Kammera830f3a2020-11-10 10:50:34 -08001121func (p SourcePath) OverlayPath(ctx ModuleMissingDepsPathContext, path Path) OptionalPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001122 var relDir string
Colin Cross07e51612019-03-05 12:46:40 -08001123 if srcPath, ok := path.(SourcePath); ok {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001124 relDir = srcPath.path
1125 } else {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001126 ReportPathErrorf(ctx, "Cannot find relative path for %s(%s)", reflect.TypeOf(path).Name(), path)
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001127 return OptionalPath{}
1128 }
Paul Duffin580efc82021-03-24 09:04:03 +00001129 dir := filepath.Join(p.srcDir, p.path, relDir)
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001130 // Use Glob so that we are run again if the directory is added.
Colin Cross7f19f372016-11-01 11:10:25 -07001131 if pathtools.IsGlob(dir) {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001132 ReportPathErrorf(ctx, "Path may not contain a glob: %s", dir)
Dan Willemsen7b310ee2015-12-18 15:11:17 -08001133 }
Colin Cross461b4452018-02-23 09:22:42 -08001134 paths, err := ctx.GlobWithDeps(dir, nil)
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001135 if err != nil {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001136 ReportPathErrorf(ctx, "glob: %s", err.Error())
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001137 return OptionalPath{}
1138 }
1139 if len(paths) == 0 {
1140 return OptionalPath{}
1141 }
Paul Duffin580efc82021-03-24 09:04:03 +00001142 relPath := Rel(ctx, p.srcDir, paths[0])
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001143 return OptionalPathForPath(PathForSource(ctx, relPath))
1144}
1145
Colin Cross70dda7e2019-10-01 22:05:35 -07001146// OutputPath is a Path representing an intermediates file path rooted from the build directory
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001147type OutputPath struct {
1148 basePath
Paul Duffind65c58b2021-03-24 09:22:07 +00001149
1150 // The soong build directory, i.e. Config.BuildDir()
1151 buildDir string
1152
Colin Crossd63c9a72020-01-29 16:52:50 -08001153 fullPath string
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001154}
1155
Colin Cross702e0f82017-10-18 17:27:54 -07001156func (p OutputPath) withRel(rel string) OutputPath {
Colin Cross0db55682017-12-05 15:36:55 -08001157 p.basePath = p.basePath.withRel(rel)
Colin Crossd63c9a72020-01-29 16:52:50 -08001158 p.fullPath = filepath.Join(p.fullPath, rel)
Colin Cross702e0f82017-10-18 17:27:54 -07001159 return p
1160}
1161
Colin Cross3063b782018-08-15 11:19:12 -07001162func (p OutputPath) WithoutRel() OutputPath {
1163 p.basePath.rel = filepath.Base(p.basePath.path)
1164 return p
1165}
1166
Paul Duffind65c58b2021-03-24 09:22:07 +00001167func (p OutputPath) getBuildDir() string {
1168 return p.buildDir
Paul Duffin9b478b02019-12-10 13:41:51 +00001169}
1170
Paul Duffin0267d492021-02-02 10:05:52 +00001171func (p OutputPath) objPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleObjPath {
1172 return PathForModuleObj(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
1173}
1174
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001175var _ Path = OutputPath{}
Paul Duffin9b478b02019-12-10 13:41:51 +00001176var _ WritablePath = OutputPath{}
Paul Duffin0267d492021-02-02 10:05:52 +00001177var _ objPathProvider = OutputPath{}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001178
Chris Parsons8f232a22020-06-23 17:37:05 -04001179// toolDepPath is a Path representing a dependency of the build tool.
1180type toolDepPath struct {
1181 basePath
1182}
1183
1184var _ Path = toolDepPath{}
1185
1186// pathForBuildToolDep returns a toolDepPath representing the given path string.
1187// There is no validation for the path, as it is "trusted": It may fail
1188// normal validation checks. For example, it may be an absolute path.
1189// Only use this function to construct paths for dependencies of the build
1190// tool invocation.
1191func pathForBuildToolDep(ctx PathContext, path string) toolDepPath {
1192 return toolDepPath{basePath{path, ctx.Config(), ""}}
1193}
1194
Jeff Gaston734e3802017-04-10 15:47:24 -07001195// PathForOutput joins the provided paths and returns an OutputPath that is
1196// validated to not escape the build dir.
1197// On error, it will return a usable, but invalid OutputPath, and report a ModuleError.
1198func PathForOutput(ctx PathContext, pathComponents ...string) OutputPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001199 path, err := validatePath(pathComponents...)
1200 if err != nil {
1201 reportPathError(ctx, err)
1202 }
Colin Crossd63c9a72020-01-29 16:52:50 -08001203 fullPath := filepath.Join(ctx.Config().buildDir, path)
1204 path = fullPath[len(fullPath)-len(path):]
Paul Duffind65c58b2021-03-24 09:22:07 +00001205 return OutputPath{basePath{path, ctx.Config(), ""}, ctx.Config().buildDir, fullPath}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001206}
1207
Colin Cross40e33732019-02-15 11:08:35 -08001208// PathsForOutput returns Paths rooted from buildDir
1209func PathsForOutput(ctx PathContext, paths []string) WritablePaths {
1210 ret := make(WritablePaths, len(paths))
1211 for i, path := range paths {
1212 ret[i] = PathForOutput(ctx, path)
1213 }
1214 return ret
1215}
1216
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001217func (p OutputPath) writablePath() {}
1218
1219func (p OutputPath) String() string {
Colin Crossd63c9a72020-01-29 16:52:50 -08001220 return p.fullPath
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001221}
1222
1223// Join creates a new OutputPath with paths... joined with the current path. The
1224// provided paths... may not use '..' to escape from the current path.
1225func (p OutputPath) Join(ctx PathContext, paths ...string) OutputPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001226 path, err := validatePath(paths...)
1227 if err != nil {
1228 reportPathError(ctx, err)
1229 }
Colin Cross0db55682017-12-05 15:36:55 -08001230 return p.withRel(path)
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001231}
1232
Colin Cross8854a5a2019-02-11 14:14:16 -08001233// ReplaceExtension creates a new OutputPath with the extension replaced with ext.
1234func (p OutputPath) ReplaceExtension(ctx PathContext, ext string) OutputPath {
1235 if strings.Contains(ext, "/") {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001236 ReportPathErrorf(ctx, "extension %q cannot contain /", ext)
Colin Cross8854a5a2019-02-11 14:14:16 -08001237 }
1238 ret := PathForOutput(ctx, pathtools.ReplaceExtension(p.path, ext))
Colin Cross2cdd5df2019-02-25 10:25:24 -08001239 ret.rel = pathtools.ReplaceExtension(p.rel, ext)
Colin Cross8854a5a2019-02-11 14:14:16 -08001240 return ret
1241}
1242
Colin Cross40e33732019-02-15 11:08:35 -08001243// InSameDir creates a new OutputPath from the directory of the current OutputPath joined with the elements in paths.
1244func (p OutputPath) InSameDir(ctx PathContext, paths ...string) OutputPath {
1245 path, err := validatePath(paths...)
1246 if err != nil {
1247 reportPathError(ctx, err)
1248 }
1249
1250 ret := PathForOutput(ctx, filepath.Dir(p.path), path)
Colin Cross2cdd5df2019-02-25 10:25:24 -08001251 ret.rel = filepath.Join(filepath.Dir(p.rel), path)
Colin Cross40e33732019-02-15 11:08:35 -08001252 return ret
1253}
1254
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001255// PathForIntermediates returns an OutputPath representing the top-level
1256// intermediates directory.
1257func PathForIntermediates(ctx PathContext, paths ...string) OutputPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001258 path, err := validatePath(paths...)
1259 if err != nil {
1260 reportPathError(ctx, err)
1261 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001262 return PathForOutput(ctx, ".intermediates", path)
1263}
1264
Colin Cross07e51612019-03-05 12:46:40 -08001265var _ genPathProvider = SourcePath{}
1266var _ objPathProvider = SourcePath{}
1267var _ resPathProvider = SourcePath{}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001268
Colin Cross07e51612019-03-05 12:46:40 -08001269// PathForModuleSrc returns a Path representing the paths... under the
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001270// module's local source directory.
Liz Kammera830f3a2020-11-10 10:50:34 -08001271func PathForModuleSrc(ctx ModuleMissingDepsPathContext, pathComponents ...string) Path {
Colin Cross8a497952019-03-05 22:25:09 -08001272 p, err := validatePath(pathComponents...)
1273 if err != nil {
1274 reportPathError(ctx, err)
Colin Cross192e97a2018-02-22 14:21:02 -08001275 }
Colin Cross8a497952019-03-05 22:25:09 -08001276 paths, err := expandOneSrcPath(ctx, p, nil)
1277 if err != nil {
1278 if depErr, ok := err.(missingDependencyError); ok {
1279 if ctx.Config().AllowMissingDependencies() {
1280 ctx.AddMissingDependencies(depErr.missingDeps)
1281 } else {
1282 ctx.ModuleErrorf(`%s, is the property annotated with android:"path"?`, depErr.Error())
1283 }
1284 } else {
1285 reportPathError(ctx, err)
1286 }
1287 return nil
1288 } else if len(paths) == 0 {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001289 ReportPathErrorf(ctx, "%q produced no files, expected exactly one", p)
Colin Cross8a497952019-03-05 22:25:09 -08001290 return nil
1291 } else if len(paths) > 1 {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001292 ReportPathErrorf(ctx, "%q produced %d files, expected exactly one", p, len(paths))
Colin Cross8a497952019-03-05 22:25:09 -08001293 }
1294 return paths[0]
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001295}
1296
Liz Kammera830f3a2020-11-10 10:50:34 -08001297func pathForModuleSrc(ctx EarlyModulePathContext, paths ...string) SourcePath {
Colin Cross07e51612019-03-05 12:46:40 -08001298 p, err := validatePath(paths...)
1299 if err != nil {
1300 reportPathError(ctx, err)
1301 }
1302
1303 path, err := pathForSource(ctx, ctx.ModuleDir(), p)
1304 if err != nil {
1305 reportPathError(ctx, err)
1306 }
1307
1308 path.basePath.rel = p
1309
1310 return path
1311}
1312
Colin Cross2fafa3e2019-03-05 12:39:51 -08001313// PathsWithModuleSrcSubDir takes a list of Paths and returns a new list of Paths where Rel() on each path
1314// will return the path relative to subDir in the module's source directory. If any input paths are not located
1315// inside subDir then a path error will be reported.
Liz Kammera830f3a2020-11-10 10:50:34 -08001316func PathsWithModuleSrcSubDir(ctx EarlyModulePathContext, paths Paths, subDir string) Paths {
Colin Cross2fafa3e2019-03-05 12:39:51 -08001317 paths = append(Paths(nil), paths...)
Colin Cross07e51612019-03-05 12:46:40 -08001318 subDirFullPath := pathForModuleSrc(ctx, subDir)
Colin Cross2fafa3e2019-03-05 12:39:51 -08001319 for i, path := range paths {
1320 rel := Rel(ctx, subDirFullPath.String(), path.String())
1321 paths[i] = subDirFullPath.join(ctx, rel)
1322 }
1323 return paths
1324}
1325
1326// PathWithModuleSrcSubDir takes a Path and returns a Path where Rel() will return the path relative to subDir in the
1327// 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 -08001328func PathWithModuleSrcSubDir(ctx EarlyModulePathContext, path Path, subDir string) Path {
Colin Cross07e51612019-03-05 12:46:40 -08001329 subDirFullPath := pathForModuleSrc(ctx, subDir)
Colin Cross2fafa3e2019-03-05 12:39:51 -08001330 rel := Rel(ctx, subDirFullPath.String(), path.String())
1331 return subDirFullPath.Join(ctx, rel)
1332}
1333
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001334// OptionalPathForModuleSrc returns an OptionalPath. The OptionalPath contains a
1335// valid path if p is non-nil.
Liz Kammera830f3a2020-11-10 10:50:34 -08001336func OptionalPathForModuleSrc(ctx ModuleMissingDepsPathContext, p *string) OptionalPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001337 if p == nil {
1338 return OptionalPath{}
1339 }
1340 return OptionalPathForPath(PathForModuleSrc(ctx, *p))
1341}
1342
Liz Kammera830f3a2020-11-10 10:50:34 -08001343func (p SourcePath) genPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleGenPath {
Colin Cross7fc17db2017-02-01 14:07:55 -08001344 return PathForModuleGen(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001345}
1346
Liz Kammera830f3a2020-11-10 10:50:34 -08001347func (p SourcePath) objPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleObjPath {
Colin Cross7fc17db2017-02-01 14:07:55 -08001348 return PathForModuleObj(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001349}
1350
Liz Kammera830f3a2020-11-10 10:50:34 -08001351func (p SourcePath) resPathWithName(ctx ModuleOutPathContext, name string) ModuleResPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001352 // TODO: Use full directory if the new ctx is not the current ctx?
1353 return PathForModuleRes(ctx, p.path, name)
1354}
1355
1356// ModuleOutPath is a Path representing a module's output directory.
1357type ModuleOutPath struct {
1358 OutputPath
1359}
1360
1361var _ Path = ModuleOutPath{}
1362
Liz Kammera830f3a2020-11-10 10:50:34 -08001363func (p ModuleOutPath) objPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleObjPath {
Pete Bentleyfcf55bf2019-08-16 20:14:32 +01001364 return PathForModuleObj(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
1365}
1366
Liz Kammera830f3a2020-11-10 10:50:34 -08001367// ModuleOutPathContext Subset of ModuleContext functions necessary for output path methods.
1368type ModuleOutPathContext interface {
1369 PathContext
1370
1371 ModuleName() string
1372 ModuleDir() string
1373 ModuleSubDir() string
1374}
1375
1376func pathForModuleOut(ctx ModuleOutPathContext) OutputPath {
Colin Cross702e0f82017-10-18 17:27:54 -07001377 return PathForOutput(ctx, ".intermediates", ctx.ModuleDir(), ctx.ModuleName(), ctx.ModuleSubDir())
1378}
1379
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001380type BazelOutPath struct {
1381 OutputPath
1382}
1383
1384var _ Path = BazelOutPath{}
1385var _ objPathProvider = BazelOutPath{}
1386
Liz Kammera830f3a2020-11-10 10:50:34 -08001387func (p BazelOutPath) objPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleObjPath {
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001388 return PathForModuleObj(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
1389}
1390
Logan Chien7eefdc42018-07-11 18:10:41 +08001391// PathForVndkRefAbiDump returns an OptionalPath representing the path of the
1392// reference abi dump for the given module. This is not guaranteed to be valid.
Liz Kammera830f3a2020-11-10 10:50:34 -08001393func PathForVndkRefAbiDump(ctx ModuleInstallPathContext, version, fileName string,
Hsin-Yi Chen53489642019-07-31 17:10:45 +08001394 isNdk, isLlndkOrVndk, isGzip bool) OptionalPath {
Logan Chien7eefdc42018-07-11 18:10:41 +08001395
Jayant Chowdharyac066c62018-02-20 10:53:31 -08001396 arches := ctx.DeviceConfig().Arches()
Logan Chien7eefdc42018-07-11 18:10:41 +08001397 if len(arches) == 0 {
1398 panic("device build with no primary arch")
1399 }
Jayant Chowdharyac066c62018-02-20 10:53:31 -08001400 currentArch := ctx.Arch()
1401 archNameAndVariant := currentArch.ArchType.String()
1402 if currentArch.ArchVariant != "" {
1403 archNameAndVariant += "_" + currentArch.ArchVariant
1404 }
Logan Chien5237bed2018-07-11 17:15:57 +08001405
1406 var dirName string
Hsin-Yi Chen53489642019-07-31 17:10:45 +08001407 if isNdk {
Logan Chien5237bed2018-07-11 17:15:57 +08001408 dirName = "ndk"
Hsin-Yi Chen53489642019-07-31 17:10:45 +08001409 } else if isLlndkOrVndk {
Logan Chien5237bed2018-07-11 17:15:57 +08001410 dirName = "vndk"
Logan Chien41eabe62019-04-10 13:33:58 +08001411 } else {
1412 dirName = "platform" // opt-in libs
Jayant Chowdhary3e231fd2017-02-08 13:45:53 -08001413 }
Logan Chien5237bed2018-07-11 17:15:57 +08001414
Jayant Chowdhary34ce67d2018-03-08 11:00:50 -08001415 binderBitness := ctx.DeviceConfig().BinderBitness()
Logan Chien7eefdc42018-07-11 18:10:41 +08001416
1417 var ext string
1418 if isGzip {
1419 ext = ".lsdump.gz"
1420 } else {
1421 ext = ".lsdump"
1422 }
1423
1424 return ExistentPathForSource(ctx, "prebuilts", "abi-dumps", dirName,
1425 version, binderBitness, archNameAndVariant, "source-based",
1426 fileName+ext)
Jayant Chowdhary3e231fd2017-02-08 13:45:53 -08001427}
1428
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001429// PathForBazelOut returns a Path representing the paths... under an output directory dedicated to
1430// bazel-owned outputs.
1431func PathForBazelOut(ctx PathContext, paths ...string) BazelOutPath {
1432 execRootPathComponents := append([]string{"execroot", "__main__"}, paths...)
1433 execRootPath := filepath.Join(execRootPathComponents...)
1434 validatedExecRootPath, err := validatePath(execRootPath)
1435 if err != nil {
1436 reportPathError(ctx, err)
1437 }
1438
1439 outputPath := OutputPath{basePath{"", ctx.Config(), ""},
Paul Duffind65c58b2021-03-24 09:22:07 +00001440 ctx.Config().buildDir,
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001441 ctx.Config().BazelContext.OutputBase()}
1442
1443 return BazelOutPath{
1444 OutputPath: outputPath.withRel(validatedExecRootPath),
1445 }
1446}
1447
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001448// PathForModuleOut returns a Path representing the paths... under the module's
1449// output directory.
Liz Kammera830f3a2020-11-10 10:50:34 -08001450func PathForModuleOut(ctx ModuleOutPathContext, paths ...string) ModuleOutPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001451 p, err := validatePath(paths...)
1452 if err != nil {
1453 reportPathError(ctx, err)
1454 }
Colin Cross702e0f82017-10-18 17:27:54 -07001455 return ModuleOutPath{
Liz Kammera830f3a2020-11-10 10:50:34 -08001456 OutputPath: pathForModuleOut(ctx).withRel(p),
Colin Cross702e0f82017-10-18 17:27:54 -07001457 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001458}
1459
1460// ModuleGenPath is a Path representing the 'gen' directory in a module's output
1461// directory. Mainly used for generated sources.
1462type ModuleGenPath struct {
1463 ModuleOutPath
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001464}
1465
1466var _ Path = ModuleGenPath{}
1467var _ genPathProvider = ModuleGenPath{}
1468var _ objPathProvider = ModuleGenPath{}
1469
1470// PathForModuleGen returns a Path representing the paths... under the module's
1471// `gen' directory.
Liz Kammera830f3a2020-11-10 10:50:34 -08001472func PathForModuleGen(ctx ModuleOutPathContext, paths ...string) ModuleGenPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001473 p, err := validatePath(paths...)
1474 if err != nil {
1475 reportPathError(ctx, err)
1476 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001477 return ModuleGenPath{
Colin Cross702e0f82017-10-18 17:27:54 -07001478 ModuleOutPath: ModuleOutPath{
Liz Kammera830f3a2020-11-10 10:50:34 -08001479 OutputPath: pathForModuleOut(ctx).withRel("gen").withRel(p),
Colin Cross702e0f82017-10-18 17:27:54 -07001480 },
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001481 }
1482}
1483
Liz Kammera830f3a2020-11-10 10:50:34 -08001484func (p ModuleGenPath) genPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleGenPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001485 // TODO: make a different path for local vs remote generated files?
Dan Willemsen21ec4902016-11-02 20:43:13 -07001486 return PathForModuleGen(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001487}
1488
Liz Kammera830f3a2020-11-10 10:50:34 -08001489func (p ModuleGenPath) objPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleObjPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001490 return PathForModuleObj(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
1491}
1492
1493// ModuleObjPath is a Path representing the 'obj' directory in a module's output
1494// directory. Used for compiled objects.
1495type ModuleObjPath struct {
1496 ModuleOutPath
1497}
1498
1499var _ Path = ModuleObjPath{}
1500
1501// PathForModuleObj returns a Path representing the paths... under the module's
1502// 'obj' directory.
Liz Kammera830f3a2020-11-10 10:50:34 -08001503func PathForModuleObj(ctx ModuleOutPathContext, pathComponents ...string) ModuleObjPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001504 p, err := validatePath(pathComponents...)
1505 if err != nil {
1506 reportPathError(ctx, err)
1507 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001508 return ModuleObjPath{PathForModuleOut(ctx, "obj", p)}
1509}
1510
1511// ModuleResPath is a a Path representing the 'res' directory in a module's
1512// output directory.
1513type ModuleResPath struct {
1514 ModuleOutPath
1515}
1516
1517var _ Path = ModuleResPath{}
1518
1519// PathForModuleRes returns a Path representing the paths... under the module's
1520// 'res' directory.
Liz Kammera830f3a2020-11-10 10:50:34 -08001521func PathForModuleRes(ctx ModuleOutPathContext, pathComponents ...string) ModuleResPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001522 p, err := validatePath(pathComponents...)
1523 if err != nil {
1524 reportPathError(ctx, err)
1525 }
1526
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001527 return ModuleResPath{PathForModuleOut(ctx, "res", p)}
1528}
1529
Colin Cross70dda7e2019-10-01 22:05:35 -07001530// InstallPath is a Path representing a installed file path rooted from the build directory
1531type InstallPath struct {
1532 basePath
Colin Crossff6c33d2019-10-02 16:01:35 -07001533
Paul Duffind65c58b2021-03-24 09:22:07 +00001534 // The soong build directory, i.e. Config.BuildDir()
1535 buildDir string
1536
Jiyong Park957bcd92020-10-20 18:23:33 +09001537 // partitionDir is the part of the InstallPath that is automatically determined according to the context.
1538 // For example, it is host/<os>-<arch> for host modules, and target/product/<device>/<partition> for device modules.
1539 partitionDir string
1540
1541 // makePath indicates whether this path is for Soong (false) or Make (true).
1542 makePath bool
Colin Cross70dda7e2019-10-01 22:05:35 -07001543}
1544
Paul Duffind65c58b2021-03-24 09:22:07 +00001545func (p InstallPath) getBuildDir() string {
1546 return p.buildDir
Paul Duffin9b478b02019-12-10 13:41:51 +00001547}
1548
Hans MÃ¥nssond3f2bd72020-11-27 12:37:28 +01001549func (p InstallPath) ReplaceExtension(ctx PathContext, ext string) OutputPath {
1550 panic("Not implemented")
1551}
1552
Paul Duffin9b478b02019-12-10 13:41:51 +00001553var _ Path = InstallPath{}
1554var _ WritablePath = InstallPath{}
1555
Colin Cross70dda7e2019-10-01 22:05:35 -07001556func (p InstallPath) writablePath() {}
1557
1558func (p InstallPath) String() string {
Jiyong Park957bcd92020-10-20 18:23:33 +09001559 if p.makePath {
1560 // Make path starts with out/ instead of out/soong.
Paul Duffind65c58b2021-03-24 09:22:07 +00001561 return filepath.Join(p.buildDir, "../", p.path)
Jiyong Park957bcd92020-10-20 18:23:33 +09001562 } else {
Paul Duffind65c58b2021-03-24 09:22:07 +00001563 return filepath.Join(p.buildDir, p.path)
Jiyong Park957bcd92020-10-20 18:23:33 +09001564 }
1565}
1566
1567// PartitionDir returns the path to the partition where the install path is rooted at. It is
1568// out/soong/target/product/<device>/<partition> for device modules, and out/soong/host/<os>-<arch> for host modules.
1569// The ./soong is dropped if the install path is for Make.
1570func (p InstallPath) PartitionDir() string {
1571 if p.makePath {
Paul Duffind65c58b2021-03-24 09:22:07 +00001572 return filepath.Join(p.buildDir, "../", p.partitionDir)
Jiyong Park957bcd92020-10-20 18:23:33 +09001573 } else {
Paul Duffind65c58b2021-03-24 09:22:07 +00001574 return filepath.Join(p.buildDir, p.partitionDir)
Jiyong Park957bcd92020-10-20 18:23:33 +09001575 }
Colin Cross70dda7e2019-10-01 22:05:35 -07001576}
1577
1578// Join creates a new InstallPath with paths... joined with the current path. The
1579// provided paths... may not use '..' to escape from the current path.
1580func (p InstallPath) Join(ctx PathContext, paths ...string) InstallPath {
1581 path, err := validatePath(paths...)
1582 if err != nil {
1583 reportPathError(ctx, err)
1584 }
1585 return p.withRel(path)
1586}
1587
1588func (p InstallPath) withRel(rel string) InstallPath {
1589 p.basePath = p.basePath.withRel(rel)
1590 return p
1591}
1592
Colin Crossff6c33d2019-10-02 16:01:35 -07001593// ToMakePath returns a new InstallPath that points to Make's install directory instead of Soong's,
1594// i.e. out/ instead of out/soong/.
1595func (p InstallPath) ToMakePath() InstallPath {
Jiyong Park957bcd92020-10-20 18:23:33 +09001596 p.makePath = true
Colin Crossff6c33d2019-10-02 16:01:35 -07001597 return p
Colin Cross70dda7e2019-10-01 22:05:35 -07001598}
1599
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001600// PathForModuleInstall returns a Path representing the install path for the
1601// module appended with paths...
Colin Cross70dda7e2019-10-01 22:05:35 -07001602func PathForModuleInstall(ctx ModuleInstallPathContext, pathComponents ...string) InstallPath {
Colin Cross6e359402020-02-10 15:29:54 -08001603 os := ctx.Os()
Jiyong Park87788b52020-09-01 12:37:45 +09001604 arch := ctx.Arch().ArchType
1605 forceOS, forceArch := ctx.InstallForceOS()
1606 if forceOS != nil {
Colin Cross6e359402020-02-10 15:29:54 -08001607 os = *forceOS
1608 }
Jiyong Park87788b52020-09-01 12:37:45 +09001609 if forceArch != nil {
1610 arch = *forceArch
1611 }
Colin Cross6e359402020-02-10 15:29:54 -08001612 partition := modulePartition(ctx, os)
Colin Cross609c49a2020-02-13 13:20:11 -08001613
Jiyong Park87788b52020-09-01 12:37:45 +09001614 ret := pathForInstall(ctx, os, arch, partition, ctx.Debug(), pathComponents...)
Colin Cross609c49a2020-02-13 13:20:11 -08001615
Jingwen Chencda22c92020-11-23 00:22:30 -05001616 if ctx.InstallBypassMake() && ctx.Config().KatiEnabled() {
Colin Cross609c49a2020-02-13 13:20:11 -08001617 ret = ret.ToMakePath()
1618 }
1619
1620 return ret
1621}
1622
Jiyong Park87788b52020-09-01 12:37:45 +09001623func pathForInstall(ctx PathContext, os OsType, arch ArchType, partition string, debug bool,
Colin Cross609c49a2020-02-13 13:20:11 -08001624 pathComponents ...string) InstallPath {
1625
Jiyong Park957bcd92020-10-20 18:23:33 +09001626 var partionPaths []string
Colin Cross609c49a2020-02-13 13:20:11 -08001627
Colin Cross6e359402020-02-10 15:29:54 -08001628 if os.Class == Device {
Jiyong Park957bcd92020-10-20 18:23:33 +09001629 partionPaths = []string{"target", "product", ctx.Config().DeviceName(), partition}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001630 } else {
Jiyong Park87788b52020-09-01 12:37:45 +09001631 osName := os.String()
1632 if os == Linux {
1633 // instead of linux_glibc
1634 osName = "linux"
Dan Willemsen866b5632017-09-22 12:28:24 -07001635 }
Jiyong Park87788b52020-09-01 12:37:45 +09001636 // SOONG_HOST_OUT is set to out/host/$(HOST_OS)-$(HOST_PREBUILT_ARCH)
1637 // and HOST_PREBUILT_ARCH is forcibly set to x86 even on x86_64 hosts. We don't seem
1638 // to have a plan to fix it (see the comment in build/make/core/envsetup.mk).
1639 // Let's keep using x86 for the existing cases until we have a need to support
1640 // other architectures.
1641 archName := arch.String()
1642 if os.Class == Host && (arch == X86_64 || arch == Common) {
1643 archName = "x86"
1644 }
Jiyong Park957bcd92020-10-20 18:23:33 +09001645 partionPaths = []string{"host", osName + "-" + archName, partition}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001646 }
Colin Cross609c49a2020-02-13 13:20:11 -08001647 if debug {
Jiyong Park957bcd92020-10-20 18:23:33 +09001648 partionPaths = append([]string{"debug"}, partionPaths...)
Dan Willemsen782a2d12015-12-21 14:55:28 -08001649 }
Colin Cross70dda7e2019-10-01 22:05:35 -07001650
Jiyong Park957bcd92020-10-20 18:23:33 +09001651 partionPath, err := validatePath(partionPaths...)
Colin Cross70dda7e2019-10-01 22:05:35 -07001652 if err != nil {
1653 reportPathError(ctx, err)
1654 }
Colin Crossff6c33d2019-10-02 16:01:35 -07001655
Jiyong Park957bcd92020-10-20 18:23:33 +09001656 base := InstallPath{
1657 basePath: basePath{partionPath, ctx.Config(), ""},
Paul Duffind65c58b2021-03-24 09:22:07 +00001658 buildDir: ctx.Config().buildDir,
Jiyong Park957bcd92020-10-20 18:23:33 +09001659 partitionDir: partionPath,
1660 makePath: false,
1661 }
Colin Crossff6c33d2019-10-02 16:01:35 -07001662
Jiyong Park957bcd92020-10-20 18:23:33 +09001663 return base.Join(ctx, pathComponents...)
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001664}
1665
Nicolas Geoffray1228e9c2020-02-27 13:45:35 +00001666func pathForNdkOrSdkInstall(ctx PathContext, prefix string, paths []string) InstallPath {
Jiyong Park957bcd92020-10-20 18:23:33 +09001667 base := InstallPath{
1668 basePath: basePath{prefix, ctx.Config(), ""},
Paul Duffind65c58b2021-03-24 09:22:07 +00001669 buildDir: ctx.Config().buildDir,
Jiyong Park957bcd92020-10-20 18:23:33 +09001670 partitionDir: prefix,
1671 makePath: false,
Colin Cross70dda7e2019-10-01 22:05:35 -07001672 }
Jiyong Park957bcd92020-10-20 18:23:33 +09001673 return base.Join(ctx, paths...)
Colin Cross70dda7e2019-10-01 22:05:35 -07001674}
1675
Nicolas Geoffray1228e9c2020-02-27 13:45:35 +00001676func PathForNdkInstall(ctx PathContext, paths ...string) InstallPath {
1677 return pathForNdkOrSdkInstall(ctx, "ndk", paths)
1678}
1679
1680func PathForMainlineSdksInstall(ctx PathContext, paths ...string) InstallPath {
1681 return pathForNdkOrSdkInstall(ctx, "mainline-sdks", paths)
1682}
1683
Colin Cross70dda7e2019-10-01 22:05:35 -07001684func InstallPathToOnDevicePath(ctx PathContext, path InstallPath) string {
Colin Cross43f08db2018-11-12 10:13:39 -08001685 rel := Rel(ctx, PathForOutput(ctx, "target", "product", ctx.Config().DeviceName()).String(), path.String())
1686
1687 return "/" + rel
1688}
1689
Colin Cross6e359402020-02-10 15:29:54 -08001690func modulePartition(ctx ModuleInstallPathContext, os OsType) string {
Colin Cross43f08db2018-11-12 10:13:39 -08001691 var partition string
Colin Cross6e359402020-02-10 15:29:54 -08001692 if ctx.InstallInTestcases() {
1693 // "testcases" install directory can be used for host or device modules.
Jaewoong Jung0949f312019-09-11 10:25:18 -07001694 partition = "testcases"
Colin Cross6e359402020-02-10 15:29:54 -08001695 } else if os.Class == Device {
1696 if ctx.InstallInData() {
1697 partition = "data"
1698 } else if ctx.InstallInRamdisk() {
1699 if ctx.DeviceConfig().BoardUsesRecoveryAsBoot() {
1700 partition = "recovery/root/first_stage_ramdisk"
1701 } else {
1702 partition = "ramdisk"
1703 }
1704 if !ctx.InstallInRoot() {
1705 partition += "/system"
1706 }
Yifan Hong60e0cfb2020-10-21 15:17:56 -07001707 } else if ctx.InstallInVendorRamdisk() {
Yifan Hong39143a92020-10-26 12:43:12 -07001708 // The module is only available after switching root into
1709 // /first_stage_ramdisk. To expose the module before switching root
1710 // on a device without a dedicated recovery partition, install the
1711 // recovery variant.
Yifan Hongdd8dacc2020-10-21 15:40:17 -07001712 if ctx.DeviceConfig().BoardMoveRecoveryResourcesToVendorBoot() {
Petri Gyntherac229562021-03-02 23:44:02 -08001713 partition = "vendor_ramdisk/first_stage_ramdisk"
Yifan Hongdd8dacc2020-10-21 15:40:17 -07001714 } else {
Petri Gyntherac229562021-03-02 23:44:02 -08001715 partition = "vendor_ramdisk"
Yifan Hongdd8dacc2020-10-21 15:40:17 -07001716 }
1717 if !ctx.InstallInRoot() {
1718 partition += "/system"
1719 }
Colin Cross6e359402020-02-10 15:29:54 -08001720 } else if ctx.InstallInRecovery() {
1721 if ctx.InstallInRoot() {
1722 partition = "recovery/root"
1723 } else {
1724 // the layout of recovery partion is the same as that of system partition
1725 partition = "recovery/root/system"
1726 }
1727 } else if ctx.SocSpecific() {
1728 partition = ctx.DeviceConfig().VendorPath()
1729 } else if ctx.DeviceSpecific() {
1730 partition = ctx.DeviceConfig().OdmPath()
1731 } else if ctx.ProductSpecific() {
1732 partition = ctx.DeviceConfig().ProductPath()
1733 } else if ctx.SystemExtSpecific() {
1734 partition = ctx.DeviceConfig().SystemExtPath()
1735 } else if ctx.InstallInRoot() {
1736 partition = "root"
Yifan Hong82db7352020-01-21 16:12:26 -08001737 } else {
Colin Cross6e359402020-02-10 15:29:54 -08001738 partition = "system"
Yifan Hong82db7352020-01-21 16:12:26 -08001739 }
Colin Cross6e359402020-02-10 15:29:54 -08001740 if ctx.InstallInSanitizerDir() {
1741 partition = "data/asan/" + partition
Yifan Hong82db7352020-01-21 16:12:26 -08001742 }
Colin Cross43f08db2018-11-12 10:13:39 -08001743 }
1744 return partition
1745}
1746
Colin Cross609c49a2020-02-13 13:20:11 -08001747type InstallPaths []InstallPath
1748
1749// Paths returns the InstallPaths as a Paths
1750func (p InstallPaths) Paths() Paths {
1751 if p == nil {
1752 return nil
1753 }
1754 ret := make(Paths, len(p))
1755 for i, path := range p {
1756 ret[i] = path
1757 }
1758 return ret
1759}
1760
1761// Strings returns the string forms of the install paths.
1762func (p InstallPaths) Strings() []string {
1763 if p == nil {
1764 return nil
1765 }
1766 ret := make([]string, len(p))
1767 for i, path := range p {
1768 ret[i] = path.String()
1769 }
1770 return ret
1771}
1772
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001773// validateSafePath validates a path that we trust (may contain ninja variables).
Dan Willemsen80a7c2a2015-12-21 14:57:11 -08001774// Ensures that each path component does not attempt to leave its component.
Colin Cross1ccfcc32018-02-22 13:54:26 -08001775func validateSafePath(pathComponents ...string) (string, error) {
Jeff Gaston734e3802017-04-10 15:47:24 -07001776 for _, path := range pathComponents {
Dan Willemsen80a7c2a2015-12-21 14:57:11 -08001777 path := filepath.Clean(path)
1778 if path == ".." || strings.HasPrefix(path, "../") || strings.HasPrefix(path, "/") {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001779 return "", fmt.Errorf("Path is outside directory: %s", path)
Dan Willemsen80a7c2a2015-12-21 14:57:11 -08001780 }
1781 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001782 // TODO: filepath.Join isn't necessarily correct with embedded ninja
1783 // variables. '..' may remove the entire ninja variable, even if it
1784 // will be expanded to multiple nested directories.
Colin Cross1ccfcc32018-02-22 13:54:26 -08001785 return filepath.Join(pathComponents...), nil
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001786}
1787
Dan Willemsen80a7c2a2015-12-21 14:57:11 -08001788// validatePath validates that a path does not include ninja variables, and that
1789// each path component does not attempt to leave its component. Returns a joined
1790// version of each path component.
Colin Cross1ccfcc32018-02-22 13:54:26 -08001791func validatePath(pathComponents ...string) (string, error) {
Jeff Gaston734e3802017-04-10 15:47:24 -07001792 for _, path := range pathComponents {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001793 if strings.Contains(path, "$") {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001794 return "", fmt.Errorf("Path contains invalid character($): %s", path)
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001795 }
1796 }
Colin Cross1ccfcc32018-02-22 13:54:26 -08001797 return validateSafePath(pathComponents...)
Colin Cross6e18ca42015-07-14 18:55:36 -07001798}
Colin Cross5b529592017-05-09 13:34:34 -07001799
Colin Cross0875c522017-11-28 17:34:01 -08001800func PathForPhony(ctx PathContext, phony string) WritablePath {
1801 if strings.ContainsAny(phony, "$/") {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001802 ReportPathErrorf(ctx, "Phony target contains invalid character ($ or /): %s", phony)
Colin Cross0875c522017-11-28 17:34:01 -08001803 }
Colin Cross74e3fe42017-12-11 15:51:44 -08001804 return PhonyPath{basePath{phony, ctx.Config(), ""}}
Colin Cross0875c522017-11-28 17:34:01 -08001805}
1806
Colin Cross74e3fe42017-12-11 15:51:44 -08001807type PhonyPath struct {
1808 basePath
1809}
1810
1811func (p PhonyPath) writablePath() {}
1812
Paul Duffind65c58b2021-03-24 09:22:07 +00001813func (p PhonyPath) getBuildDir() string {
1814 // A phone path cannot contain any / so cannot be relative to the build directory.
1815 return ""
Paul Duffin9b478b02019-12-10 13:41:51 +00001816}
1817
Hans MÃ¥nssond3f2bd72020-11-27 12:37:28 +01001818func (p PhonyPath) ReplaceExtension(ctx PathContext, ext string) OutputPath {
1819 panic("Not implemented")
1820}
1821
Colin Cross74e3fe42017-12-11 15:51:44 -08001822var _ Path = PhonyPath{}
1823var _ WritablePath = PhonyPath{}
1824
Colin Cross5b529592017-05-09 13:34:34 -07001825type testPath struct {
1826 basePath
1827}
1828
1829func (p testPath) String() string {
1830 return p.path
1831}
1832
Colin Cross40e33732019-02-15 11:08:35 -08001833// PathForTesting returns a Path constructed from joining the elements of paths with '/'. It should only be used from
1834// within tests.
Colin Cross5b529592017-05-09 13:34:34 -07001835func PathForTesting(paths ...string) Path {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001836 p, err := validateSafePath(paths...)
1837 if err != nil {
1838 panic(err)
1839 }
Colin Cross5b529592017-05-09 13:34:34 -07001840 return testPath{basePath{path: p, rel: p}}
1841}
1842
Colin Cross40e33732019-02-15 11:08:35 -08001843// PathsForTesting returns a Path constructed from each element in strs. It should only be used from within tests.
1844func PathsForTesting(strs ...string) Paths {
Colin Cross5b529592017-05-09 13:34:34 -07001845 p := make(Paths, len(strs))
1846 for i, s := range strs {
1847 p[i] = PathForTesting(s)
1848 }
1849
1850 return p
1851}
Colin Cross43f08db2018-11-12 10:13:39 -08001852
Colin Cross40e33732019-02-15 11:08:35 -08001853type testPathContext struct {
1854 config Config
Colin Cross40e33732019-02-15 11:08:35 -08001855}
1856
Colin Cross40e33732019-02-15 11:08:35 -08001857func (x *testPathContext) Config() Config { return x.config }
1858func (x *testPathContext) AddNinjaFileDeps(...string) {}
1859
1860// PathContextForTesting returns a PathContext that can be used in tests, for example to create an OutputPath with
1861// PathForOutput.
Colin Cross98be1bb2019-12-13 20:41:13 -08001862func PathContextForTesting(config Config) PathContext {
Colin Cross40e33732019-02-15 11:08:35 -08001863 return &testPathContext{
1864 config: config,
Colin Cross40e33732019-02-15 11:08:35 -08001865 }
1866}
1867
Ulya Trafimovichccc8c852020-10-14 11:29:07 +01001868type testModuleInstallPathContext struct {
1869 baseModuleContext
1870
1871 inData bool
1872 inTestcases bool
1873 inSanitizerDir bool
1874 inRamdisk bool
1875 inVendorRamdisk bool
1876 inRecovery bool
1877 inRoot bool
1878 forceOS *OsType
1879 forceArch *ArchType
1880}
1881
1882func (m testModuleInstallPathContext) Config() Config {
1883 return m.baseModuleContext.config
1884}
1885
1886func (testModuleInstallPathContext) AddNinjaFileDeps(deps ...string) {}
1887
1888func (m testModuleInstallPathContext) InstallInData() bool {
1889 return m.inData
1890}
1891
1892func (m testModuleInstallPathContext) InstallInTestcases() bool {
1893 return m.inTestcases
1894}
1895
1896func (m testModuleInstallPathContext) InstallInSanitizerDir() bool {
1897 return m.inSanitizerDir
1898}
1899
1900func (m testModuleInstallPathContext) InstallInRamdisk() bool {
1901 return m.inRamdisk
1902}
1903
1904func (m testModuleInstallPathContext) InstallInVendorRamdisk() bool {
1905 return m.inVendorRamdisk
1906}
1907
1908func (m testModuleInstallPathContext) InstallInRecovery() bool {
1909 return m.inRecovery
1910}
1911
1912func (m testModuleInstallPathContext) InstallInRoot() bool {
1913 return m.inRoot
1914}
1915
1916func (m testModuleInstallPathContext) InstallBypassMake() bool {
1917 return false
1918}
1919
1920func (m testModuleInstallPathContext) InstallForceOS() (*OsType, *ArchType) {
1921 return m.forceOS, m.forceArch
1922}
1923
1924// Construct a minimal ModuleInstallPathContext for testing. Note that baseModuleContext is
1925// default-initialized, which leaves blueprint.baseModuleContext set to nil, so methods that are
1926// delegated to it will panic.
1927func ModuleInstallPathContextForTesting(config Config) ModuleInstallPathContext {
1928 ctx := &testModuleInstallPathContext{}
1929 ctx.config = config
1930 ctx.os = Android
1931 return ctx
1932}
1933
Colin Cross43f08db2018-11-12 10:13:39 -08001934// Rel performs the same function as filepath.Rel, but reports errors to a PathContext, and reports an error if
1935// targetPath is not inside basePath.
1936func Rel(ctx PathContext, basePath string, targetPath string) string {
1937 rel, isRel := MaybeRel(ctx, basePath, targetPath)
1938 if !isRel {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001939 ReportPathErrorf(ctx, "path %q is not under path %q", targetPath, basePath)
Colin Cross43f08db2018-11-12 10:13:39 -08001940 return ""
1941 }
1942 return rel
1943}
1944
1945// MaybeRel performs the same function as filepath.Rel, but reports errors to a PathContext, and returns false if
1946// targetPath is not inside basePath.
1947func MaybeRel(ctx PathContext, basePath string, targetPath string) (string, bool) {
Dan Willemsen633c5022019-04-12 11:11:38 -07001948 rel, isRel, err := maybeRelErr(basePath, targetPath)
1949 if err != nil {
1950 reportPathError(ctx, err)
1951 }
1952 return rel, isRel
1953}
1954
1955func maybeRelErr(basePath string, targetPath string) (string, bool, error) {
Colin Cross43f08db2018-11-12 10:13:39 -08001956 // filepath.Rel returns an error if one path is absolute and the other is not, handle that case first.
1957 if filepath.IsAbs(basePath) != filepath.IsAbs(targetPath) {
Dan Willemsen633c5022019-04-12 11:11:38 -07001958 return "", false, nil
Colin Cross43f08db2018-11-12 10:13:39 -08001959 }
1960 rel, err := filepath.Rel(basePath, targetPath)
1961 if err != nil {
Dan Willemsen633c5022019-04-12 11:11:38 -07001962 return "", false, err
Colin Cross43f08db2018-11-12 10:13:39 -08001963 } else if rel == ".." || strings.HasPrefix(rel, "../") || strings.HasPrefix(rel, "/") {
Dan Willemsen633c5022019-04-12 11:11:38 -07001964 return "", false, nil
Colin Cross43f08db2018-11-12 10:13:39 -08001965 }
Dan Willemsen633c5022019-04-12 11:11:38 -07001966 return rel, true, nil
Colin Cross43f08db2018-11-12 10:13:39 -08001967}
Colin Cross988414c2020-01-11 01:11:46 +00001968
1969// Writes a file to the output directory. Attempting to write directly to the output directory
1970// will fail due to the sandbox of the soong_build process.
1971func WriteFileToOutputDir(path WritablePath, data []byte, perm os.FileMode) error {
1972 return ioutil.WriteFile(absolutePath(path.String()), data, perm)
1973}
1974
Liz Kammer2dd9ca42020-11-25 16:06:39 -08001975func RemoveAllOutputDir(path WritablePath) error {
1976 return os.RemoveAll(absolutePath(path.String()))
1977}
1978
1979func CreateOutputDirIfNonexistent(path WritablePath, perm os.FileMode) error {
1980 dir := absolutePath(path.String())
1981 if _, err := os.Stat(dir); os.IsNotExist(err) {
1982 return os.MkdirAll(dir, os.ModePerm)
1983 } else {
1984 return err
1985 }
1986}
1987
Colin Cross988414c2020-01-11 01:11:46 +00001988func absolutePath(path string) string {
1989 if filepath.IsAbs(path) {
1990 return path
1991 }
1992 return filepath.Join(absSrcDir, path)
1993}
Chris Parsons216e10a2020-07-09 17:12:52 -04001994
1995// A DataPath represents the path of a file to be used as data, for example
1996// a test library to be installed alongside a test.
1997// The data file should be installed (copied from `<SrcPath>`) to
1998// `<install_root>/<RelativeInstallPath>/<filename>`, or
1999// `<install_root>/<filename>` if RelativeInstallPath is empty.
2000type DataPath struct {
2001 // The path of the data file that should be copied into the data directory
2002 SrcPath Path
2003 // The install path of the data file, relative to the install root.
2004 RelativeInstallPath string
2005}
Colin Crossdcf71b22021-02-01 13:59:03 -08002006
2007// PathsIfNonNil returns a Paths containing only the non-nil input arguments.
2008func PathsIfNonNil(paths ...Path) Paths {
2009 if len(paths) == 0 {
2010 // Fast path for empty argument list
2011 return nil
2012 } else if len(paths) == 1 {
2013 // Fast path for a single argument
2014 if paths[0] != nil {
2015 return paths
2016 } else {
2017 return nil
2018 }
2019 }
2020 ret := make(Paths, 0, len(paths))
2021 for _, path := range paths {
2022 if path != nil {
2023 ret = append(ret, path)
2024 }
2025 }
2026 if len(ret) == 0 {
2027 return nil
2028 }
2029 return ret
2030}