blob: 1ad548bea1161acd77562176d574361ef4be917a [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
Paul Duffin85d8f0d2021-03-24 10:18:18 +0000177
178 // RelativeToTop returns a new path relative to the top, it is provided solely for use in tests.
179 //
180 // It is guaranteed to always return the same type as it is called on, e.g. if called on an
181 // InstallPath then the returned value can be converted to an InstallPath.
182 //
183 // A standard build has the following structure:
184 // ../top/
185 // out/ - make install files go here.
186 // out/soong - this is the buildDir passed to NewTestConfig()
187 // ... - the source files
188 //
189 // This function converts a path so that it appears relative to the ../top/ directory, i.e.
190 // * Make install paths, which have the pattern "buildDir/../<path>" are converted into the top
191 // relative path "out/<path>"
192 // * Soong install paths and other writable paths, which have the pattern "buildDir/<path>" are
193 // converted into the top relative path "out/soong/<path>".
194 // * Source paths are already relative to the top.
195 // * Phony paths are not relative to anything.
196 // * toolDepPath have an absolute but known value in so don't need making relative to anything in
197 // order to test.
198 RelativeToTop() Path
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700199}
200
Paul Duffin85d8f0d2021-03-24 10:18:18 +0000201const (
202 OutDir = "out"
203 OutSoongDir = OutDir + "/soong"
204)
205
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700206// WritablePath is a type of path that can be used as an output for build rules.
207type WritablePath interface {
208 Path
209
Paul Duffin9b478b02019-12-10 13:41:51 +0000210 // return the path to the build directory.
Paul Duffind65c58b2021-03-24 09:22:07 +0000211 getBuildDir() string
Paul Duffin9b478b02019-12-10 13:41:51 +0000212
Jeff Gaston734e3802017-04-10 15:47:24 -0700213 // the writablePath method doesn't directly do anything,
214 // but it allows a struct to distinguish between whether or not it implements the WritablePath interface
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700215 writablePath()
Hans MÃ¥nssond3f2bd72020-11-27 12:37:28 +0100216
217 ReplaceExtension(ctx PathContext, ext string) OutputPath
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700218}
219
220type genPathProvider interface {
Liz Kammera830f3a2020-11-10 10:50:34 -0800221 genPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleGenPath
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700222}
223type objPathProvider interface {
Liz Kammera830f3a2020-11-10 10:50:34 -0800224 objPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleObjPath
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700225}
226type resPathProvider interface {
Liz Kammera830f3a2020-11-10 10:50:34 -0800227 resPathWithName(ctx ModuleOutPathContext, name string) ModuleResPath
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700228}
229
230// GenPathWithExt derives a new file path in ctx's generated sources directory
231// from the current path, but with the new extension.
Liz Kammera830f3a2020-11-10 10:50:34 -0800232func GenPathWithExt(ctx ModuleOutPathContext, subdir string, p Path, ext string) ModuleGenPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700233 if path, ok := p.(genPathProvider); ok {
Dan Willemsen21ec4902016-11-02 20:43:13 -0700234 return path.genPathWithExt(ctx, subdir, ext)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700235 }
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +0100236 ReportPathErrorf(ctx, "Tried to create generated file from unsupported path: %s(%s)", reflect.TypeOf(p).Name(), p)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700237 return PathForModuleGen(ctx)
238}
239
240// ObjPathWithExt derives a new file path in ctx's object directory from the
241// current path, but with the new extension.
Liz Kammera830f3a2020-11-10 10:50:34 -0800242func ObjPathWithExt(ctx ModuleOutPathContext, subdir string, p Path, ext string) ModuleObjPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700243 if path, ok := p.(objPathProvider); ok {
244 return path.objPathWithExt(ctx, subdir, ext)
245 }
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +0100246 ReportPathErrorf(ctx, "Tried to create object file from unsupported path: %s (%s)", reflect.TypeOf(p).Name(), p)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700247 return PathForModuleObj(ctx)
248}
249
250// ResPathWithName derives a new path in ctx's output resource directory, using
251// the current path to create the directory name, and the `name` argument for
252// the filename.
Liz Kammera830f3a2020-11-10 10:50:34 -0800253func ResPathWithName(ctx ModuleOutPathContext, p Path, name string) ModuleResPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700254 if path, ok := p.(resPathProvider); ok {
255 return path.resPathWithName(ctx, name)
256 }
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +0100257 ReportPathErrorf(ctx, "Tried to create res file from unsupported path: %s (%s)", reflect.TypeOf(p).Name(), p)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700258 return PathForModuleRes(ctx)
259}
260
261// OptionalPath is a container that may or may not contain a valid Path.
262type OptionalPath struct {
263 valid bool
264 path Path
265}
266
267// OptionalPathForPath returns an OptionalPath containing the path.
268func OptionalPathForPath(path Path) OptionalPath {
269 if path == nil {
270 return OptionalPath{}
271 }
272 return OptionalPath{valid: true, path: path}
273}
274
275// Valid returns whether there is a valid path
276func (p OptionalPath) Valid() bool {
277 return p.valid
278}
279
280// Path returns the Path embedded in this OptionalPath. You must be sure that
281// there is a valid path, since this method will panic if there is not.
282func (p OptionalPath) Path() Path {
283 if !p.valid {
284 panic("Requesting an invalid path")
285 }
286 return p.path
287}
288
Paul Duffinafdd4062021-03-30 19:44:07 +0100289// RelativeToTop returns an OptionalPath with the path that was embedded having been replaced by the
290// result of calling Path.RelativeToTop on it.
291func (p OptionalPath) RelativeToTop() OptionalPath {
Paul Duffina5b81352021-03-28 23:57:19 +0100292 if !p.valid {
293 return p
294 }
295 p.path = p.path.RelativeToTop()
296 return p
297}
298
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700299// String returns the string version of the Path, or "" if it isn't valid.
300func (p OptionalPath) String() string {
301 if p.valid {
302 return p.path.String()
303 } else {
304 return ""
Colin Crossf2298272015-05-12 11:36:53 -0700305 }
306}
Colin Cross6e18ca42015-07-14 18:55:36 -0700307
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700308// Paths is a slice of Path objects, with helpers to operate on the collection.
309type Paths []Path
310
Paul Duffin85d8f0d2021-03-24 10:18:18 +0000311// RelativeToTop creates a new Paths containing the result of calling Path.RelativeToTop on each
312// item in this slice.
313func (p Paths) RelativeToTop() Paths {
314 ensureTestOnly()
315 if p == nil {
316 return p
317 }
318 ret := make(Paths, len(p))
319 for i, path := range p {
320 ret[i] = path.RelativeToTop()
321 }
322 return ret
323}
324
Jingwen Chen40fd90a2020-06-15 05:24:19 +0000325func (paths Paths) containsPath(path Path) bool {
326 for _, p := range paths {
327 if p == path {
328 return true
329 }
330 }
331 return false
332}
333
Liz Kammer7aa52882021-02-11 09:16:14 -0500334// PathsForSource returns Paths rooted from SrcDir, *not* rooted from the module's local source
335// directory
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700336func PathsForSource(ctx PathContext, paths []string) Paths {
337 ret := make(Paths, len(paths))
338 for i, path := range paths {
339 ret[i] = PathForSource(ctx, path)
340 }
341 return ret
342}
343
Liz Kammer7aa52882021-02-11 09:16:14 -0500344// ExistentPathsForSources returns a list of Paths rooted from SrcDir, *not* rooted from the
345// module's local source directory, that are found in the tree. If any are not found, they are
346// 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 -0800347func ExistentPathsForSources(ctx PathContext, paths []string) Paths {
Dan Willemsen7b310ee2015-12-18 15:11:17 -0800348 ret := make(Paths, 0, len(paths))
349 for _, path := range paths {
Colin Cross32f38982018-02-22 11:47:25 -0800350 p := ExistentPathForSource(ctx, path)
Dan Willemsen7b310ee2015-12-18 15:11:17 -0800351 if p.Valid() {
352 ret = append(ret, p.Path())
353 }
354 }
355 return ret
356}
357
Colin Cross41955e82019-05-29 14:40:35 -0700358// PathsForModuleSrc returns Paths rooted from the module's local source directory. It expands globs, references to
359// SourceFileProducer modules using the ":name" syntax, and references to OutputFileProducer modules using the
360// ":name{.tag}" syntax. Properties passed as the paths argument must have been annotated with struct tag
361// `android:"path"` so that dependencies on SourceFileProducer modules will have already been handled by the
362// path_properties mutator. If ctx.Config().AllowMissingDependencies() is true then any missing SourceFileProducer or
363// OutputFileProducer dependencies will cause the module to be marked as having missing dependencies.
Liz Kammera830f3a2020-11-10 10:50:34 -0800364func PathsForModuleSrc(ctx ModuleMissingDepsPathContext, paths []string) Paths {
Colin Cross8a497952019-03-05 22:25:09 -0800365 return PathsForModuleSrcExcludes(ctx, paths, nil)
366}
367
Colin Crossba71a3f2019-03-18 12:12:48 -0700368// PathsForModuleSrcExcludes returns Paths rooted from the module's local source directory, excluding paths listed in
Colin Cross41955e82019-05-29 14:40:35 -0700369// the excludes arguments. It expands globs, references to SourceFileProducer modules using the ":name" syntax, and
370// references to OutputFileProducer modules using the ":name{.tag}" syntax. Properties passed as the paths or excludes
371// argument must have been annotated with struct tag `android:"path"` so that dependencies on SourceFileProducer modules
372// will have already been handled by the path_properties mutator. If ctx.Config().AllowMissingDependencies() is
Paul Duffin036cace2019-07-25 14:44:56 +0100373// true then any missing SourceFileProducer or OutputFileProducer dependencies will cause the module to be marked as
Colin Cross41955e82019-05-29 14:40:35 -0700374// having missing dependencies.
Liz Kammera830f3a2020-11-10 10:50:34 -0800375func PathsForModuleSrcExcludes(ctx ModuleMissingDepsPathContext, paths, excludes []string) Paths {
Colin Crossba71a3f2019-03-18 12:12:48 -0700376 ret, missingDeps := PathsAndMissingDepsForModuleSrcExcludes(ctx, paths, excludes)
377 if ctx.Config().AllowMissingDependencies() {
378 ctx.AddMissingDependencies(missingDeps)
379 } else {
380 for _, m := range missingDeps {
381 ctx.ModuleErrorf(`missing dependency on %q, is the property annotated with android:"path"?`, m)
382 }
383 }
384 return ret
385}
386
Liz Kammer356f7d42021-01-26 09:18:53 -0500387// A subset of the ModuleContext methods which are sufficient to resolve references to paths/deps in
388// order to form a Bazel-compatible label for conversion.
389type BazelConversionPathContext interface {
390 EarlyModulePathContext
391
392 GetDirectDep(name string) (blueprint.Module, blueprint.DependencyTag)
Liz Kammerbdc60992021-02-24 16:55:11 -0500393 Module() Module
Jingwen Chen12b4c272021-03-10 02:05:59 -0500394 ModuleType() string
Liz Kammer356f7d42021-01-26 09:18:53 -0500395 OtherModuleName(m blueprint.Module) string
396 OtherModuleDir(m blueprint.Module) string
397}
398
399// BazelLabelForModuleDeps returns a Bazel-compatible label for the requested modules which
400// correspond to dependencies on the module within the given ctx.
401func BazelLabelForModuleDeps(ctx BazelConversionPathContext, modules []string) bazel.LabelList {
402 var labels bazel.LabelList
403 for _, module := range modules {
404 bpText := module
405 if m := SrcIsModule(module); m == "" {
406 module = ":" + module
407 }
408 if m, t := SrcIsModuleWithTag(module); m != "" {
409 l := getOtherModuleLabel(ctx, m, t)
410 l.Bp_text = bpText
411 labels.Includes = append(labels.Includes, l)
412 } else {
413 ctx.ModuleErrorf("%q, is not a module reference", module)
414 }
415 }
416 return labels
417}
418
419// BazelLabelForModuleSrc returns bazel.LabelList with paths rooted from the module's local source
420// directory. It expands globs, and resolves references to modules using the ":name" syntax to
421// bazel-compatible labels. Properties passed as the paths or excludes argument must have been
422// annotated with struct tag `android:"path"` so that dependencies on other modules will have
423// already been handled by the path_properties mutator.
424func BazelLabelForModuleSrc(ctx BazelConversionPathContext, paths []string) bazel.LabelList {
425 return BazelLabelForModuleSrcExcludes(ctx, paths, []string(nil))
426}
427
428// BazelLabelForModuleSrcExcludes returns bazel.LabelList with paths rooted from the module's local
429// source directory, excluding labels included in the excludes argument. It expands globs, and
430// resolves references to modules using the ":name" syntax to bazel-compatible labels. Properties
431// passed as the paths or excludes argument must have been annotated with struct tag
432// `android:"path"` so that dependencies on other modules will have already been handled by the
433// path_properties mutator.
434func BazelLabelForModuleSrcExcludes(ctx BazelConversionPathContext, paths, excludes []string) bazel.LabelList {
435 excludeLabels := expandSrcsForBazel(ctx, excludes, []string(nil))
436 excluded := make([]string, 0, len(excludeLabels.Includes))
437 for _, e := range excludeLabels.Includes {
438 excluded = append(excluded, e.Label)
439 }
440 labels := expandSrcsForBazel(ctx, paths, excluded)
441 labels.Excludes = excludeLabels.Includes
442 return labels
443}
444
445// expandSrcsForBazel returns bazel.LabelList with paths rooted from the module's local
446// source directory, excluding labels included in the excludes argument. It expands globs, and
447// resolves references to modules using the ":name" syntax to bazel-compatible labels. Properties
448// passed as the paths or excludes argument must have been annotated with struct tag
449// `android:"path"` so that dependencies on other modules will have already been handled by the
450// path_properties mutator.
451func expandSrcsForBazel(ctx BazelConversionPathContext, paths, expandedExcludes []string) bazel.LabelList {
Liz Kammerebfcf672021-02-16 15:00:05 -0500452 if paths == nil {
453 return bazel.LabelList{}
454 }
Liz Kammer356f7d42021-01-26 09:18:53 -0500455 labels := bazel.LabelList{
456 Includes: []bazel.Label{},
457 }
458 for _, p := range paths {
459 if m, tag := SrcIsModuleWithTag(p); m != "" {
460 l := getOtherModuleLabel(ctx, m, tag)
461 if !InList(l.Label, expandedExcludes) {
462 l.Bp_text = fmt.Sprintf(":%s", m)
463 labels.Includes = append(labels.Includes, l)
464 }
465 } else {
466 var expandedPaths []bazel.Label
467 if pathtools.IsGlob(p) {
468 globbedPaths := GlobFiles(ctx, pathForModuleSrc(ctx, p).String(), expandedExcludes)
469 globbedPaths = PathsWithModuleSrcSubDir(ctx, globbedPaths, "")
470 for _, path := range globbedPaths {
471 s := path.Rel()
472 expandedPaths = append(expandedPaths, bazel.Label{Label: s})
473 }
474 } else {
475 if !InList(p, expandedExcludes) {
476 expandedPaths = append(expandedPaths, bazel.Label{Label: p})
477 }
478 }
479 labels.Includes = append(labels.Includes, expandedPaths...)
480 }
481 }
482 return labels
483}
484
485// getOtherModuleLabel returns a bazel.Label for the given dependency/tag combination for the
486// module. The label will be relative to the current directory if appropriate. The dependency must
487// already be resolved by either deps mutator or path deps mutator.
488func getOtherModuleLabel(ctx BazelConversionPathContext, dep, tag string) bazel.Label {
489 m, _ := ctx.GetDirectDep(dep)
Jingwen Chen07027912021-03-15 06:02:43 -0400490 if m == nil {
491 panic(fmt.Errorf("cannot get direct dep %s of %s", dep, ctx.Module().Name()))
492 }
Liz Kammerbdc60992021-02-24 16:55:11 -0500493 otherLabel := bazelModuleLabel(ctx, m, tag)
494 label := bazelModuleLabel(ctx, ctx.Module(), "")
495 if samePackage(label, otherLabel) {
496 otherLabel = bazelShortLabel(otherLabel)
Liz Kammer356f7d42021-01-26 09:18:53 -0500497 }
Liz Kammerbdc60992021-02-24 16:55:11 -0500498
499 return bazel.Label{
500 Label: otherLabel,
501 }
502}
503
504func bazelModuleLabel(ctx BazelConversionPathContext, module blueprint.Module, tag string) string {
505 // TODO(b/165114590): Convert tag (":name{.tag}") to corresponding Bazel implicit output targets.
506 b, ok := module.(Bazelable)
507 // 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 -0500508 if !ok || !b.ConvertedToBazel(ctx) {
Liz Kammerbdc60992021-02-24 16:55:11 -0500509 return bp2buildModuleLabel(ctx, module)
510 }
511 return b.GetBazelLabel(ctx, module)
512}
513
514func bazelShortLabel(label string) string {
515 i := strings.Index(label, ":")
516 return label[i:]
517}
518
519func bazelPackage(label string) string {
520 i := strings.Index(label, ":")
521 return label[0:i]
522}
523
524func samePackage(label1, label2 string) bool {
525 return bazelPackage(label1) == bazelPackage(label2)
526}
527
528func bp2buildModuleLabel(ctx BazelConversionPathContext, module blueprint.Module) string {
529 moduleName := ctx.OtherModuleName(module)
530 moduleDir := ctx.OtherModuleDir(module)
531 return fmt.Sprintf("//%s:%s", moduleDir, moduleName)
Liz Kammer356f7d42021-01-26 09:18:53 -0500532}
533
Ulya Trafimovich4d2eeed2019-11-08 10:54:21 +0000534// OutputPaths is a slice of OutputPath objects, with helpers to operate on the collection.
535type OutputPaths []OutputPath
536
537// Paths returns the OutputPaths as a Paths
538func (p OutputPaths) Paths() Paths {
539 if p == nil {
540 return nil
541 }
542 ret := make(Paths, len(p))
543 for i, path := range p {
544 ret[i] = path
545 }
546 return ret
547}
548
549// Strings returns the string forms of the writable paths.
550func (p OutputPaths) Strings() []string {
551 if p == nil {
552 return nil
553 }
554 ret := make([]string, len(p))
555 for i, path := range p {
556 ret[i] = path.String()
557 }
558 return ret
559}
560
Liz Kammera830f3a2020-11-10 10:50:34 -0800561// Expands Paths to a SourceFileProducer or OutputFileProducer module dependency referenced via ":name" or ":name{.tag}" syntax.
562// If the dependency is not found, a missingErrorDependency is returned.
563// If the module dependency is not a SourceFileProducer or OutputFileProducer, appropriate errors will be returned.
564func getPathsFromModuleDep(ctx ModuleWithDepsPathContext, path, moduleName, tag string) (Paths, error) {
565 module := ctx.GetDirectDepWithTag(moduleName, sourceOrOutputDepTag(tag))
566 if module == nil {
567 return nil, missingDependencyError{[]string{moduleName}}
568 }
Colin Crossfa65cee2021-03-22 17:05:59 -0700569 if aModule, ok := module.(Module); ok && !aModule.Enabled() {
570 return nil, missingDependencyError{[]string{moduleName}}
571 }
Liz Kammera830f3a2020-11-10 10:50:34 -0800572 if outProducer, ok := module.(OutputFileProducer); ok {
573 outputFiles, err := outProducer.OutputFiles(tag)
574 if err != nil {
575 return nil, fmt.Errorf("path dependency %q: %s", path, err)
576 }
577 return outputFiles, nil
578 } else if tag != "" {
579 return nil, fmt.Errorf("path dependency %q is not an output file producing module", path)
580 } else if srcProducer, ok := module.(SourceFileProducer); ok {
581 return srcProducer.Srcs(), nil
582 } else {
583 return nil, fmt.Errorf("path dependency %q is not a source file producing module", path)
584 }
585}
586
Colin Crossba71a3f2019-03-18 12:12:48 -0700587// PathsAndMissingDepsForModuleSrcExcludes returns Paths rooted from the module's local source directory, excluding
Colin Cross41955e82019-05-29 14:40:35 -0700588// paths listed in the excludes arguments, and a list of missing dependencies. It expands globs, references to
589// SourceFileProducer modules using the ":name" syntax, and references to OutputFileProducer modules using the
590// ":name{.tag}" syntax. Properties passed as the paths or excludes argument must have been annotated with struct tag
591// `android:"path"` so that dependencies on SourceFileProducer modules will have already been handled by the
592// path_properties mutator. If ctx.Config().AllowMissingDependencies() is true then any missing SourceFileProducer or
593// OutputFileProducer dependencies will be returned, and they will NOT cause the module to be marked as having missing
594// dependencies.
Liz Kammera830f3a2020-11-10 10:50:34 -0800595func PathsAndMissingDepsForModuleSrcExcludes(ctx ModuleWithDepsPathContext, paths, excludes []string) (Paths, []string) {
Colin Cross8a497952019-03-05 22:25:09 -0800596 prefix := pathForModuleSrc(ctx).String()
597
598 var expandedExcludes []string
599 if excludes != nil {
600 expandedExcludes = make([]string, 0, len(excludes))
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700601 }
Colin Cross8a497952019-03-05 22:25:09 -0800602
Colin Crossba71a3f2019-03-18 12:12:48 -0700603 var missingExcludeDeps []string
604
Colin Cross8a497952019-03-05 22:25:09 -0800605 for _, e := range excludes {
Colin Cross41955e82019-05-29 14:40:35 -0700606 if m, t := SrcIsModuleWithTag(e); m != "" {
Liz Kammera830f3a2020-11-10 10:50:34 -0800607 modulePaths, err := getPathsFromModuleDep(ctx, e, m, t)
608 if m, ok := err.(missingDependencyError); ok {
609 missingExcludeDeps = append(missingExcludeDeps, m.missingDeps...)
610 } else if err != nil {
611 reportPathError(ctx, err)
Colin Cross8a497952019-03-05 22:25:09 -0800612 } else {
Liz Kammera830f3a2020-11-10 10:50:34 -0800613 expandedExcludes = append(expandedExcludes, modulePaths.Strings()...)
Colin Cross8a497952019-03-05 22:25:09 -0800614 }
615 } else {
616 expandedExcludes = append(expandedExcludes, filepath.Join(prefix, e))
617 }
618 }
619
620 if paths == nil {
Colin Crossba71a3f2019-03-18 12:12:48 -0700621 return nil, missingExcludeDeps
Colin Cross8a497952019-03-05 22:25:09 -0800622 }
623
Colin Crossba71a3f2019-03-18 12:12:48 -0700624 var missingDeps []string
625
Colin Cross8a497952019-03-05 22:25:09 -0800626 expandedSrcFiles := make(Paths, 0, len(paths))
627 for _, s := range paths {
628 srcFiles, err := expandOneSrcPath(ctx, s, expandedExcludes)
629 if depErr, ok := err.(missingDependencyError); ok {
Colin Crossba71a3f2019-03-18 12:12:48 -0700630 missingDeps = append(missingDeps, depErr.missingDeps...)
Colin Cross8a497952019-03-05 22:25:09 -0800631 } else if err != nil {
632 reportPathError(ctx, err)
633 }
634 expandedSrcFiles = append(expandedSrcFiles, srcFiles...)
635 }
Colin Crossba71a3f2019-03-18 12:12:48 -0700636
637 return expandedSrcFiles, append(missingDeps, missingExcludeDeps...)
Colin Cross8a497952019-03-05 22:25:09 -0800638}
639
640type missingDependencyError struct {
641 missingDeps []string
642}
643
644func (e missingDependencyError) Error() string {
645 return "missing dependencies: " + strings.Join(e.missingDeps, ", ")
646}
647
Liz Kammera830f3a2020-11-10 10:50:34 -0800648// Expands one path string to Paths rooted from the module's local source
649// directory, excluding those listed in the expandedExcludes.
650// Expands globs, references to SourceFileProducer or OutputFileProducer modules using the ":name" and ":name{.tag}" syntax.
651func expandOneSrcPath(ctx ModuleWithDepsPathContext, sPath string, expandedExcludes []string) (Paths, error) {
Jooyung Han7607dd32020-07-05 10:23:14 +0900652 excludePaths := func(paths Paths) Paths {
653 if len(expandedExcludes) == 0 {
654 return paths
655 }
656 remainder := make(Paths, 0, len(paths))
657 for _, p := range paths {
658 if !InList(p.String(), expandedExcludes) {
659 remainder = append(remainder, p)
660 }
661 }
662 return remainder
663 }
Liz Kammera830f3a2020-11-10 10:50:34 -0800664 if m, t := SrcIsModuleWithTag(sPath); m != "" {
665 modulePaths, err := getPathsFromModuleDep(ctx, sPath, m, t)
666 if err != nil {
667 return nil, err
Colin Cross8a497952019-03-05 22:25:09 -0800668 } else {
Liz Kammera830f3a2020-11-10 10:50:34 -0800669 return excludePaths(modulePaths), nil
Colin Cross8a497952019-03-05 22:25:09 -0800670 }
Liz Kammera830f3a2020-11-10 10:50:34 -0800671 } else if pathtools.IsGlob(sPath) {
672 paths := GlobFiles(ctx, pathForModuleSrc(ctx, sPath).String(), expandedExcludes)
Colin Cross8a497952019-03-05 22:25:09 -0800673 return PathsWithModuleSrcSubDir(ctx, paths, ""), nil
674 } else {
Liz Kammera830f3a2020-11-10 10:50:34 -0800675 p := pathForModuleSrc(ctx, sPath)
Colin Cross988414c2020-01-11 01:11:46 +0000676 if exists, _, err := ctx.Config().fs.Exists(p.String()); err != nil {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +0100677 ReportPathErrorf(ctx, "%s: %s", p, err.Error())
Pedro Loureiro5d190cc2021-02-15 15:41:33 +0000678 } else if !exists && !ctx.Config().TestAllowNonExistentPaths {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +0100679 ReportPathErrorf(ctx, "module source path %q does not exist", p)
Colin Cross8a497952019-03-05 22:25:09 -0800680 }
681
Jooyung Han7607dd32020-07-05 10:23:14 +0900682 if InList(p.String(), expandedExcludes) {
Colin Cross8a497952019-03-05 22:25:09 -0800683 return nil, nil
684 }
685 return Paths{p}, nil
686 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700687}
688
689// pathsForModuleSrcFromFullPath returns Paths rooted from the module's local
690// source directory, but strip the local source directory from the beginning of
Dan Willemsen540a78c2018-02-26 21:50:08 -0800691// each string. If incDirs is false, strip paths with a trailing '/' from the list.
Colin Crossfe4bc362018-09-12 10:02:13 -0700692// It intended for use in globs that only list files that exist, so it allows '$' in
693// filenames.
Liz Kammera830f3a2020-11-10 10:50:34 -0800694func pathsForModuleSrcFromFullPath(ctx EarlyModulePathContext, paths []string, incDirs bool) Paths {
Colin Cross6510f912017-11-29 00:27:14 -0800695 prefix := filepath.Join(ctx.Config().srcDir, ctx.ModuleDir()) + "/"
Colin Cross0f37af02017-09-27 17:42:05 -0700696 if prefix == "./" {
697 prefix = ""
698 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700699 ret := make(Paths, 0, len(paths))
700 for _, p := range paths {
Dan Willemsen540a78c2018-02-26 21:50:08 -0800701 if !incDirs && strings.HasSuffix(p, "/") {
702 continue
703 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700704 path := filepath.Clean(p)
705 if !strings.HasPrefix(path, prefix) {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +0100706 ReportPathErrorf(ctx, "Path %q is not in module source directory %q", p, prefix)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700707 continue
708 }
Colin Crosse3924e12018-08-15 20:18:53 -0700709
Colin Crossfe4bc362018-09-12 10:02:13 -0700710 srcPath, err := safePathForSource(ctx, ctx.ModuleDir(), path[len(prefix):])
Colin Crosse3924e12018-08-15 20:18:53 -0700711 if err != nil {
712 reportPathError(ctx, err)
713 continue
714 }
715
Colin Cross07e51612019-03-05 12:46:40 -0800716 srcPath.basePath.rel = srcPath.path
Colin Crosse3924e12018-08-15 20:18:53 -0700717
Colin Cross07e51612019-03-05 12:46:40 -0800718 ret = append(ret, srcPath)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700719 }
720 return ret
721}
722
Liz Kammera830f3a2020-11-10 10:50:34 -0800723// PathsWithOptionalDefaultForModuleSrc returns Paths rooted from the module's local source
724// directory. If input is nil, use the default if it exists. If input is empty, returns nil.
725func PathsWithOptionalDefaultForModuleSrc(ctx ModuleMissingDepsPathContext, input []string, def string) Paths {
Colin Cross0ddae7f2019-02-07 15:30:01 -0800726 if input != nil {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700727 return PathsForModuleSrc(ctx, input)
728 }
729 // Use Glob so that if the default doesn't exist, a dependency is added so that when it
730 // is created, we're run again.
Colin Cross6510f912017-11-29 00:27:14 -0800731 path := filepath.Join(ctx.Config().srcDir, ctx.ModuleDir(), def)
Liz Kammera830f3a2020-11-10 10:50:34 -0800732 return Glob(ctx, path, nil)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700733}
734
735// Strings returns the Paths in string form
736func (p Paths) Strings() []string {
737 if p == nil {
738 return nil
739 }
740 ret := make([]string, len(p))
741 for i, path := range p {
742 ret[i] = path.String()
743 }
744 return ret
745}
746
Colin Crossc0efd1d2020-07-03 11:56:24 -0700747func CopyOfPaths(paths Paths) Paths {
748 return append(Paths(nil), paths...)
749}
750
Colin Crossb6715442017-10-24 11:13:31 -0700751// FirstUniquePaths returns all unique elements of a Paths, keeping the first copy of each. It
752// modifies the Paths slice contents in place, and returns a subslice of the original slice.
Dan Willemsenfe92c962017-08-29 12:28:37 -0700753func FirstUniquePaths(list Paths) Paths {
Colin Cross27027c72020-02-28 15:34:17 -0800754 // 128 was chosen based on BenchmarkFirstUniquePaths results.
755 if len(list) > 128 {
756 return firstUniquePathsMap(list)
757 }
758 return firstUniquePathsList(list)
759}
760
Colin Crossc0efd1d2020-07-03 11:56:24 -0700761// SortedUniquePaths returns all unique elements of a Paths in sorted order. It modifies the
762// Paths slice contents in place, and returns a subslice of the original slice.
Jiyong Park33c77362020-05-29 22:00:16 +0900763func SortedUniquePaths(list Paths) Paths {
764 unique := FirstUniquePaths(list)
765 sort.Slice(unique, func(i, j int) bool {
766 return unique[i].String() < unique[j].String()
767 })
768 return unique
769}
770
Colin Cross27027c72020-02-28 15:34:17 -0800771func firstUniquePathsList(list Paths) Paths {
Dan Willemsenfe92c962017-08-29 12:28:37 -0700772 k := 0
773outer:
774 for i := 0; i < len(list); i++ {
775 for j := 0; j < k; j++ {
776 if list[i] == list[j] {
777 continue outer
778 }
779 }
780 list[k] = list[i]
781 k++
782 }
783 return list[:k]
784}
785
Colin Cross27027c72020-02-28 15:34:17 -0800786func firstUniquePathsMap(list Paths) Paths {
787 k := 0
788 seen := make(map[Path]bool, len(list))
789 for i := 0; i < len(list); i++ {
790 if seen[list[i]] {
791 continue
792 }
793 seen[list[i]] = true
794 list[k] = list[i]
795 k++
796 }
797 return list[:k]
798}
799
Colin Cross5d583952020-11-24 16:21:24 -0800800// FirstUniqueInstallPaths returns all unique elements of an InstallPaths, keeping the first copy of each. It
801// modifies the InstallPaths slice contents in place, and returns a subslice of the original slice.
802func FirstUniqueInstallPaths(list InstallPaths) InstallPaths {
803 // 128 was chosen based on BenchmarkFirstUniquePaths results.
804 if len(list) > 128 {
805 return firstUniqueInstallPathsMap(list)
806 }
807 return firstUniqueInstallPathsList(list)
808}
809
810func firstUniqueInstallPathsList(list InstallPaths) InstallPaths {
811 k := 0
812outer:
813 for i := 0; i < len(list); i++ {
814 for j := 0; j < k; j++ {
815 if list[i] == list[j] {
816 continue outer
817 }
818 }
819 list[k] = list[i]
820 k++
821 }
822 return list[:k]
823}
824
825func firstUniqueInstallPathsMap(list InstallPaths) InstallPaths {
826 k := 0
827 seen := make(map[InstallPath]bool, len(list))
828 for i := 0; i < len(list); i++ {
829 if seen[list[i]] {
830 continue
831 }
832 seen[list[i]] = true
833 list[k] = list[i]
834 k++
835 }
836 return list[:k]
837}
838
Colin Crossb6715442017-10-24 11:13:31 -0700839// LastUniquePaths returns all unique elements of a Paths, keeping the last copy of each. It
840// modifies the Paths slice contents in place, and returns a subslice of the original slice.
841func LastUniquePaths(list Paths) Paths {
842 totalSkip := 0
843 for i := len(list) - 1; i >= totalSkip; i-- {
844 skip := 0
845 for j := i - 1; j >= totalSkip; j-- {
846 if list[i] == list[j] {
847 skip++
848 } else {
849 list[j+skip] = list[j]
850 }
851 }
852 totalSkip += skip
853 }
854 return list[totalSkip:]
855}
856
Colin Crossa140bb02018-04-17 10:52:26 -0700857// ReversePaths returns a copy of a Paths in reverse order.
858func ReversePaths(list Paths) Paths {
859 if list == nil {
860 return nil
861 }
862 ret := make(Paths, len(list))
863 for i := range list {
864 ret[i] = list[len(list)-1-i]
865 }
866 return ret
867}
868
Jeff Gaston294356f2017-09-27 17:05:30 -0700869func indexPathList(s Path, list []Path) int {
870 for i, l := range list {
871 if l == s {
872 return i
873 }
874 }
875
876 return -1
877}
878
879func inPathList(p Path, list []Path) bool {
880 return indexPathList(p, list) != -1
881}
882
883func FilterPathList(list []Path, filter []Path) (remainder []Path, filtered []Path) {
Paul Duffin57b9e1d2019-12-13 00:03:35 +0000884 return FilterPathListPredicate(list, func(p Path) bool { return inPathList(p, filter) })
885}
886
887func FilterPathListPredicate(list []Path, predicate func(Path) bool) (remainder []Path, filtered []Path) {
Jeff Gaston294356f2017-09-27 17:05:30 -0700888 for _, l := range list {
Paul Duffin57b9e1d2019-12-13 00:03:35 +0000889 if predicate(l) {
Jeff Gaston294356f2017-09-27 17:05:30 -0700890 filtered = append(filtered, l)
891 } else {
892 remainder = append(remainder, l)
893 }
894 }
895
896 return
897}
898
Colin Cross93e85952017-08-15 13:34:18 -0700899// HasExt returns true of any of the paths have extension ext, otherwise false
900func (p Paths) HasExt(ext string) bool {
901 for _, path := range p {
902 if path.Ext() == ext {
903 return true
904 }
905 }
906
907 return false
908}
909
910// FilterByExt returns the subset of the paths that have extension ext
911func (p Paths) FilterByExt(ext string) Paths {
912 ret := make(Paths, 0, len(p))
913 for _, path := range p {
914 if path.Ext() == ext {
915 ret = append(ret, path)
916 }
917 }
918 return ret
919}
920
921// FilterOutByExt returns the subset of the paths that do not have extension ext
922func (p Paths) FilterOutByExt(ext string) Paths {
923 ret := make(Paths, 0, len(p))
924 for _, path := range p {
925 if path.Ext() != ext {
926 ret = append(ret, path)
927 }
928 }
929 return ret
930}
931
Colin Cross5e6cfbe2017-11-03 15:20:35 -0700932// DirectorySortedPaths is a slice of paths that are sorted such that all files in a directory
933// (including subdirectories) are in a contiguous subslice of the list, and can be found in
934// O(log(N)) time using a binary search on the directory prefix.
935type DirectorySortedPaths Paths
936
937func PathsToDirectorySortedPaths(paths Paths) DirectorySortedPaths {
938 ret := append(DirectorySortedPaths(nil), paths...)
939 sort.Slice(ret, func(i, j int) bool {
940 return ret[i].String() < ret[j].String()
941 })
942 return ret
943}
944
945// PathsInDirectory returns a subslice of the DirectorySortedPaths as a Paths that contains all entries
946// that are in the specified directory and its subdirectories.
947func (p DirectorySortedPaths) PathsInDirectory(dir string) Paths {
948 prefix := filepath.Clean(dir) + "/"
949 start := sort.Search(len(p), func(i int) bool {
950 return prefix < p[i].String()
951 })
952
953 ret := p[start:]
954
955 end := sort.Search(len(ret), func(i int) bool {
956 return !strings.HasPrefix(ret[i].String(), prefix)
957 })
958
959 ret = ret[:end]
960
961 return Paths(ret)
962}
963
Alex Humesky29e3bbe2020-11-20 21:30:13 -0500964// WritablePaths is a slice of WritablePath, used for multiple outputs.
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700965type WritablePaths []WritablePath
966
Paul Duffin85d8f0d2021-03-24 10:18:18 +0000967// RelativeToTop creates a new WritablePaths containing the result of calling Path.RelativeToTop on
968// each item in this slice.
969func (p WritablePaths) RelativeToTop() WritablePaths {
970 ensureTestOnly()
971 if p == nil {
972 return p
973 }
974 ret := make(WritablePaths, len(p))
975 for i, path := range p {
976 ret[i] = path.RelativeToTop().(WritablePath)
977 }
978 return ret
979}
980
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700981// Strings returns the string forms of the writable paths.
982func (p WritablePaths) Strings() []string {
983 if p == nil {
984 return nil
985 }
986 ret := make([]string, len(p))
987 for i, path := range p {
988 ret[i] = path.String()
989 }
990 return ret
991}
992
Colin Cross3bc7ffa2017-11-22 16:19:37 -0800993// Paths returns the WritablePaths as a Paths
994func (p WritablePaths) Paths() Paths {
995 if p == nil {
996 return nil
997 }
998 ret := make(Paths, len(p))
999 for i, path := range p {
1000 ret[i] = path
1001 }
1002 return ret
1003}
1004
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001005type basePath struct {
Paul Duffin74abc5d2021-03-24 09:24:59 +00001006 path string
1007 rel string
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001008}
1009
1010func (p basePath) Ext() string {
1011 return filepath.Ext(p.path)
1012}
1013
Colin Cross4f6fc9c2016-10-26 10:05:25 -07001014func (p basePath) Base() string {
1015 return filepath.Base(p.path)
1016}
1017
Colin Crossfaeb7aa2017-02-01 14:12:44 -08001018func (p basePath) Rel() string {
1019 if p.rel != "" {
1020 return p.rel
1021 }
1022 return p.path
1023}
1024
Colin Cross0875c522017-11-28 17:34:01 -08001025func (p basePath) String() string {
1026 return p.path
1027}
1028
Colin Cross0db55682017-12-05 15:36:55 -08001029func (p basePath) withRel(rel string) basePath {
1030 p.path = filepath.Join(p.path, rel)
1031 p.rel = rel
1032 return p
1033}
1034
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001035// SourcePath is a Path representing a file path rooted from SrcDir
1036type SourcePath struct {
1037 basePath
Paul Duffin580efc82021-03-24 09:04:03 +00001038
1039 // The sources root, i.e. Config.SrcDir()
1040 srcDir string
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001041}
1042
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001043func (p SourcePath) RelativeToTop() Path {
1044 ensureTestOnly()
1045 return p
1046}
1047
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001048var _ Path = SourcePath{}
1049
Colin Cross0db55682017-12-05 15:36:55 -08001050func (p SourcePath) withRel(rel string) SourcePath {
1051 p.basePath = p.basePath.withRel(rel)
1052 return p
1053}
1054
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001055// safePathForSource is for paths that we expect are safe -- only for use by go
1056// code that is embedding ninja variables in paths
Colin Crossfe4bc362018-09-12 10:02:13 -07001057func safePathForSource(ctx PathContext, pathComponents ...string) (SourcePath, error) {
1058 p, err := validateSafePath(pathComponents...)
Paul Duffin74abc5d2021-03-24 09:24:59 +00001059 ret := SourcePath{basePath{p, ""}, ctx.Config().srcDir}
Colin Crossfe4bc362018-09-12 10:02:13 -07001060 if err != nil {
1061 return ret, err
1062 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001063
Colin Cross7b3dcc32019-01-24 13:14:39 -08001064 // absolute path already checked by validateSafePath
1065 if strings.HasPrefix(ret.String(), ctx.Config().buildDir) {
Mikhail Naganovab1f5182019-02-08 13:17:55 -08001066 return ret, fmt.Errorf("source path %q is in output", ret.String())
Colin Cross6e18ca42015-07-14 18:55:36 -07001067 }
1068
Colin Crossfe4bc362018-09-12 10:02:13 -07001069 return ret, err
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001070}
1071
Colin Cross192e97a2018-02-22 14:21:02 -08001072// pathForSource creates a SourcePath from pathComponents, but does not check that it exists.
1073func pathForSource(ctx PathContext, pathComponents ...string) (SourcePath, error) {
Colin Crossc48c1432018-02-23 07:09:01 +00001074 p, err := validatePath(pathComponents...)
Paul Duffin74abc5d2021-03-24 09:24:59 +00001075 ret := SourcePath{basePath{p, ""}, ctx.Config().srcDir}
Colin Cross94a32102018-02-22 14:21:02 -08001076 if err != nil {
Colin Cross192e97a2018-02-22 14:21:02 -08001077 return ret, err
Colin Cross94a32102018-02-22 14:21:02 -08001078 }
1079
Colin Cross7b3dcc32019-01-24 13:14:39 -08001080 // absolute path already checked by validatePath
1081 if strings.HasPrefix(ret.String(), ctx.Config().buildDir) {
Mikhail Naganovab1f5182019-02-08 13:17:55 -08001082 return ret, fmt.Errorf("source path %q is in output", ret.String())
Colin Crossc48c1432018-02-23 07:09:01 +00001083 }
1084
Colin Cross192e97a2018-02-22 14:21:02 -08001085 return ret, nil
1086}
1087
1088// existsWithDependencies returns true if the path exists, and adds appropriate dependencies to rerun if the
1089// path does not exist.
1090func existsWithDependencies(ctx PathContext, path SourcePath) (exists bool, err error) {
1091 var files []string
1092
1093 if gctx, ok := ctx.(PathGlobContext); ok {
1094 // Use glob to produce proper dependencies, even though we only want
1095 // a single file.
1096 files, err = gctx.GlobWithDeps(path.String(), nil)
1097 } else {
Colin Cross82ea3fb2021-04-05 17:48:26 -07001098 var result pathtools.GlobResult
Colin Cross192e97a2018-02-22 14:21:02 -08001099 // We cannot add build statements in this context, so we fall back to
1100 // AddNinjaFileDeps
Colin Cross82ea3fb2021-04-05 17:48:26 -07001101 result, err = ctx.Config().fs.Glob(path.String(), nil, pathtools.FollowSymlinks)
1102 ctx.AddNinjaFileDeps(result.Deps...)
1103 files = result.Matches
Colin Cross192e97a2018-02-22 14:21:02 -08001104 }
1105
1106 if err != nil {
1107 return false, fmt.Errorf("glob: %s", err.Error())
1108 }
1109
1110 return len(files) > 0, nil
1111}
1112
1113// PathForSource joins the provided path components and validates that the result
1114// neither escapes the source dir nor is in the out dir.
1115// On error, it will return a usable, but invalid SourcePath, and report a ModuleError.
1116func PathForSource(ctx PathContext, pathComponents ...string) SourcePath {
1117 path, err := pathForSource(ctx, pathComponents...)
1118 if err != nil {
1119 reportPathError(ctx, err)
1120 }
1121
Colin Crosse3924e12018-08-15 20:18:53 -07001122 if pathtools.IsGlob(path.String()) {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001123 ReportPathErrorf(ctx, "path may not contain a glob: %s", path.String())
Colin Crosse3924e12018-08-15 20:18:53 -07001124 }
1125
Liz Kammera830f3a2020-11-10 10:50:34 -08001126 if modCtx, ok := ctx.(ModuleMissingDepsPathContext); ok && ctx.Config().AllowMissingDependencies() {
Colin Cross192e97a2018-02-22 14:21:02 -08001127 exists, err := existsWithDependencies(ctx, path)
1128 if err != nil {
1129 reportPathError(ctx, err)
1130 }
1131 if !exists {
1132 modCtx.AddMissingDependencies([]string{path.String()})
1133 }
Colin Cross988414c2020-01-11 01:11:46 +00001134 } else if exists, _, err := ctx.Config().fs.Exists(path.String()); err != nil {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001135 ReportPathErrorf(ctx, "%s: %s", path, err.Error())
Pedro Loureiro5d190cc2021-02-15 15:41:33 +00001136 } else if !exists && !ctx.Config().TestAllowNonExistentPaths {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001137 ReportPathErrorf(ctx, "source path %q does not exist", path)
Colin Cross192e97a2018-02-22 14:21:02 -08001138 }
1139 return path
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001140}
1141
Liz Kammer7aa52882021-02-11 09:16:14 -05001142// ExistentPathForSource returns an OptionalPath with the SourcePath, rooted from SrcDir, *not*
1143// rooted from the module's local source directory, if the path exists, or an empty OptionalPath if
1144// it doesn't exist. Dependencies are added so that the ninja file will be regenerated if the state
1145// of the path changes.
Colin Cross32f38982018-02-22 11:47:25 -08001146func ExistentPathForSource(ctx PathContext, pathComponents ...string) OptionalPath {
Colin Cross192e97a2018-02-22 14:21:02 -08001147 path, err := pathForSource(ctx, pathComponents...)
Colin Cross1ccfcc32018-02-22 13:54:26 -08001148 if err != nil {
1149 reportPathError(ctx, err)
1150 return OptionalPath{}
1151 }
Colin Crossc48c1432018-02-23 07:09:01 +00001152
Colin Crosse3924e12018-08-15 20:18:53 -07001153 if pathtools.IsGlob(path.String()) {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001154 ReportPathErrorf(ctx, "path may not contain a glob: %s", path.String())
Colin Crosse3924e12018-08-15 20:18:53 -07001155 return OptionalPath{}
1156 }
1157
Colin Cross192e97a2018-02-22 14:21:02 -08001158 exists, err := existsWithDependencies(ctx, path)
Colin Crossc48c1432018-02-23 07:09:01 +00001159 if err != nil {
1160 reportPathError(ctx, err)
1161 return OptionalPath{}
1162 }
Colin Cross192e97a2018-02-22 14:21:02 -08001163 if !exists {
Colin Crossc48c1432018-02-23 07:09:01 +00001164 return OptionalPath{}
1165 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001166 return OptionalPathForPath(path)
1167}
1168
1169func (p SourcePath) String() string {
Paul Duffin580efc82021-03-24 09:04:03 +00001170 return filepath.Join(p.srcDir, p.path)
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001171}
1172
1173// Join creates a new SourcePath with paths... joined with the current path. The
1174// provided paths... may not use '..' to escape from the current path.
1175func (p SourcePath) Join(ctx PathContext, paths ...string) SourcePath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001176 path, err := validatePath(paths...)
1177 if err != nil {
1178 reportPathError(ctx, err)
1179 }
Colin Cross0db55682017-12-05 15:36:55 -08001180 return p.withRel(path)
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001181}
1182
Colin Cross2fafa3e2019-03-05 12:39:51 -08001183// join is like Join but does less path validation.
1184func (p SourcePath) join(ctx PathContext, paths ...string) SourcePath {
1185 path, err := validateSafePath(paths...)
1186 if err != nil {
1187 reportPathError(ctx, err)
1188 }
1189 return p.withRel(path)
1190}
1191
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001192// OverlayPath returns the overlay for `path' if it exists. This assumes that the
1193// SourcePath is the path to a resource overlay directory.
Liz Kammera830f3a2020-11-10 10:50:34 -08001194func (p SourcePath) OverlayPath(ctx ModuleMissingDepsPathContext, path Path) OptionalPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001195 var relDir string
Colin Cross07e51612019-03-05 12:46:40 -08001196 if srcPath, ok := path.(SourcePath); ok {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001197 relDir = srcPath.path
1198 } else {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001199 ReportPathErrorf(ctx, "Cannot find relative path for %s(%s)", reflect.TypeOf(path).Name(), path)
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001200 return OptionalPath{}
1201 }
Paul Duffin580efc82021-03-24 09:04:03 +00001202 dir := filepath.Join(p.srcDir, p.path, relDir)
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001203 // Use Glob so that we are run again if the directory is added.
Colin Cross7f19f372016-11-01 11:10:25 -07001204 if pathtools.IsGlob(dir) {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001205 ReportPathErrorf(ctx, "Path may not contain a glob: %s", dir)
Dan Willemsen7b310ee2015-12-18 15:11:17 -08001206 }
Colin Cross461b4452018-02-23 09:22:42 -08001207 paths, err := ctx.GlobWithDeps(dir, nil)
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001208 if err != nil {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001209 ReportPathErrorf(ctx, "glob: %s", err.Error())
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001210 return OptionalPath{}
1211 }
1212 if len(paths) == 0 {
1213 return OptionalPath{}
1214 }
Paul Duffin580efc82021-03-24 09:04:03 +00001215 relPath := Rel(ctx, p.srcDir, paths[0])
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001216 return OptionalPathForPath(PathForSource(ctx, relPath))
1217}
1218
Colin Cross70dda7e2019-10-01 22:05:35 -07001219// OutputPath is a Path representing an intermediates file path rooted from the build directory
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001220type OutputPath struct {
1221 basePath
Paul Duffind65c58b2021-03-24 09:22:07 +00001222
1223 // The soong build directory, i.e. Config.BuildDir()
1224 buildDir string
1225
Colin Crossd63c9a72020-01-29 16:52:50 -08001226 fullPath string
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001227}
1228
Colin Cross702e0f82017-10-18 17:27:54 -07001229func (p OutputPath) withRel(rel string) OutputPath {
Colin Cross0db55682017-12-05 15:36:55 -08001230 p.basePath = p.basePath.withRel(rel)
Colin Crossd63c9a72020-01-29 16:52:50 -08001231 p.fullPath = filepath.Join(p.fullPath, rel)
Colin Cross702e0f82017-10-18 17:27:54 -07001232 return p
1233}
1234
Colin Cross3063b782018-08-15 11:19:12 -07001235func (p OutputPath) WithoutRel() OutputPath {
1236 p.basePath.rel = filepath.Base(p.basePath.path)
1237 return p
1238}
1239
Paul Duffind65c58b2021-03-24 09:22:07 +00001240func (p OutputPath) getBuildDir() string {
1241 return p.buildDir
Paul Duffin9b478b02019-12-10 13:41:51 +00001242}
1243
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001244func (p OutputPath) RelativeToTop() Path {
1245 return p.outputPathRelativeToTop()
1246}
1247
1248func (p OutputPath) outputPathRelativeToTop() OutputPath {
1249 p.fullPath = StringPathRelativeToTop(p.buildDir, p.fullPath)
1250 p.buildDir = OutSoongDir
1251 return p
1252}
1253
Paul Duffin0267d492021-02-02 10:05:52 +00001254func (p OutputPath) objPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleObjPath {
1255 return PathForModuleObj(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
1256}
1257
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001258var _ Path = OutputPath{}
Paul Duffin9b478b02019-12-10 13:41:51 +00001259var _ WritablePath = OutputPath{}
Paul Duffin0267d492021-02-02 10:05:52 +00001260var _ objPathProvider = OutputPath{}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001261
Chris Parsons8f232a22020-06-23 17:37:05 -04001262// toolDepPath is a Path representing a dependency of the build tool.
1263type toolDepPath struct {
1264 basePath
1265}
1266
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001267func (t toolDepPath) RelativeToTop() Path {
1268 ensureTestOnly()
1269 return t
1270}
1271
Chris Parsons8f232a22020-06-23 17:37:05 -04001272var _ Path = toolDepPath{}
1273
1274// pathForBuildToolDep returns a toolDepPath representing the given path string.
1275// There is no validation for the path, as it is "trusted": It may fail
1276// normal validation checks. For example, it may be an absolute path.
1277// Only use this function to construct paths for dependencies of the build
1278// tool invocation.
1279func pathForBuildToolDep(ctx PathContext, path string) toolDepPath {
Paul Duffin74abc5d2021-03-24 09:24:59 +00001280 return toolDepPath{basePath{path, ""}}
Chris Parsons8f232a22020-06-23 17:37:05 -04001281}
1282
Jeff Gaston734e3802017-04-10 15:47:24 -07001283// PathForOutput joins the provided paths and returns an OutputPath that is
1284// validated to not escape the build dir.
1285// On error, it will return a usable, but invalid OutputPath, and report a ModuleError.
1286func PathForOutput(ctx PathContext, pathComponents ...string) OutputPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001287 path, err := validatePath(pathComponents...)
1288 if err != nil {
1289 reportPathError(ctx, err)
1290 }
Colin Crossd63c9a72020-01-29 16:52:50 -08001291 fullPath := filepath.Join(ctx.Config().buildDir, path)
1292 path = fullPath[len(fullPath)-len(path):]
Paul Duffin74abc5d2021-03-24 09:24:59 +00001293 return OutputPath{basePath{path, ""}, ctx.Config().buildDir, fullPath}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001294}
1295
Colin Cross40e33732019-02-15 11:08:35 -08001296// PathsForOutput returns Paths rooted from buildDir
1297func PathsForOutput(ctx PathContext, paths []string) WritablePaths {
1298 ret := make(WritablePaths, len(paths))
1299 for i, path := range paths {
1300 ret[i] = PathForOutput(ctx, path)
1301 }
1302 return ret
1303}
1304
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001305func (p OutputPath) writablePath() {}
1306
1307func (p OutputPath) String() string {
Colin Crossd63c9a72020-01-29 16:52:50 -08001308 return p.fullPath
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001309}
1310
1311// Join creates a new OutputPath with paths... joined with the current path. The
1312// provided paths... may not use '..' to escape from the current path.
1313func (p OutputPath) Join(ctx PathContext, paths ...string) OutputPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001314 path, err := validatePath(paths...)
1315 if err != nil {
1316 reportPathError(ctx, err)
1317 }
Colin Cross0db55682017-12-05 15:36:55 -08001318 return p.withRel(path)
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001319}
1320
Colin Cross8854a5a2019-02-11 14:14:16 -08001321// ReplaceExtension creates a new OutputPath with the extension replaced with ext.
1322func (p OutputPath) ReplaceExtension(ctx PathContext, ext string) OutputPath {
1323 if strings.Contains(ext, "/") {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001324 ReportPathErrorf(ctx, "extension %q cannot contain /", ext)
Colin Cross8854a5a2019-02-11 14:14:16 -08001325 }
1326 ret := PathForOutput(ctx, pathtools.ReplaceExtension(p.path, ext))
Colin Cross2cdd5df2019-02-25 10:25:24 -08001327 ret.rel = pathtools.ReplaceExtension(p.rel, ext)
Colin Cross8854a5a2019-02-11 14:14:16 -08001328 return ret
1329}
1330
Colin Cross40e33732019-02-15 11:08:35 -08001331// InSameDir creates a new OutputPath from the directory of the current OutputPath joined with the elements in paths.
1332func (p OutputPath) InSameDir(ctx PathContext, paths ...string) OutputPath {
1333 path, err := validatePath(paths...)
1334 if err != nil {
1335 reportPathError(ctx, err)
1336 }
1337
1338 ret := PathForOutput(ctx, filepath.Dir(p.path), path)
Colin Cross2cdd5df2019-02-25 10:25:24 -08001339 ret.rel = filepath.Join(filepath.Dir(p.rel), path)
Colin Cross40e33732019-02-15 11:08:35 -08001340 return ret
1341}
1342
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001343// PathForIntermediates returns an OutputPath representing the top-level
1344// intermediates directory.
1345func PathForIntermediates(ctx PathContext, paths ...string) OutputPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001346 path, err := validatePath(paths...)
1347 if err != nil {
1348 reportPathError(ctx, err)
1349 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001350 return PathForOutput(ctx, ".intermediates", path)
1351}
1352
Colin Cross07e51612019-03-05 12:46:40 -08001353var _ genPathProvider = SourcePath{}
1354var _ objPathProvider = SourcePath{}
1355var _ resPathProvider = SourcePath{}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001356
Colin Cross07e51612019-03-05 12:46:40 -08001357// PathForModuleSrc returns a Path representing the paths... under the
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001358// module's local source directory.
Liz Kammera830f3a2020-11-10 10:50:34 -08001359func PathForModuleSrc(ctx ModuleMissingDepsPathContext, pathComponents ...string) Path {
Colin Cross8a497952019-03-05 22:25:09 -08001360 p, err := validatePath(pathComponents...)
1361 if err != nil {
1362 reportPathError(ctx, err)
Colin Cross192e97a2018-02-22 14:21:02 -08001363 }
Colin Cross8a497952019-03-05 22:25:09 -08001364 paths, err := expandOneSrcPath(ctx, p, nil)
1365 if err != nil {
1366 if depErr, ok := err.(missingDependencyError); ok {
1367 if ctx.Config().AllowMissingDependencies() {
1368 ctx.AddMissingDependencies(depErr.missingDeps)
1369 } else {
1370 ctx.ModuleErrorf(`%s, is the property annotated with android:"path"?`, depErr.Error())
1371 }
1372 } else {
1373 reportPathError(ctx, err)
1374 }
1375 return nil
1376 } else if len(paths) == 0 {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001377 ReportPathErrorf(ctx, "%q produced no files, expected exactly one", p)
Colin Cross8a497952019-03-05 22:25:09 -08001378 return nil
1379 } else if len(paths) > 1 {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001380 ReportPathErrorf(ctx, "%q produced %d files, expected exactly one", p, len(paths))
Colin Cross8a497952019-03-05 22:25:09 -08001381 }
1382 return paths[0]
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001383}
1384
Liz Kammera830f3a2020-11-10 10:50:34 -08001385func pathForModuleSrc(ctx EarlyModulePathContext, paths ...string) SourcePath {
Colin Cross07e51612019-03-05 12:46:40 -08001386 p, err := validatePath(paths...)
1387 if err != nil {
1388 reportPathError(ctx, err)
1389 }
1390
1391 path, err := pathForSource(ctx, ctx.ModuleDir(), p)
1392 if err != nil {
1393 reportPathError(ctx, err)
1394 }
1395
1396 path.basePath.rel = p
1397
1398 return path
1399}
1400
Colin Cross2fafa3e2019-03-05 12:39:51 -08001401// PathsWithModuleSrcSubDir takes a list of Paths and returns a new list of Paths where Rel() on each path
1402// will return the path relative to subDir in the module's source directory. If any input paths are not located
1403// inside subDir then a path error will be reported.
Liz Kammera830f3a2020-11-10 10:50:34 -08001404func PathsWithModuleSrcSubDir(ctx EarlyModulePathContext, paths Paths, subDir string) Paths {
Colin Cross2fafa3e2019-03-05 12:39:51 -08001405 paths = append(Paths(nil), paths...)
Colin Cross07e51612019-03-05 12:46:40 -08001406 subDirFullPath := pathForModuleSrc(ctx, subDir)
Colin Cross2fafa3e2019-03-05 12:39:51 -08001407 for i, path := range paths {
1408 rel := Rel(ctx, subDirFullPath.String(), path.String())
1409 paths[i] = subDirFullPath.join(ctx, rel)
1410 }
1411 return paths
1412}
1413
1414// PathWithModuleSrcSubDir takes a Path and returns a Path where Rel() will return the path relative to subDir in the
1415// 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 -08001416func PathWithModuleSrcSubDir(ctx EarlyModulePathContext, path Path, subDir string) Path {
Colin Cross07e51612019-03-05 12:46:40 -08001417 subDirFullPath := pathForModuleSrc(ctx, subDir)
Colin Cross2fafa3e2019-03-05 12:39:51 -08001418 rel := Rel(ctx, subDirFullPath.String(), path.String())
1419 return subDirFullPath.Join(ctx, rel)
1420}
1421
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001422// OptionalPathForModuleSrc returns an OptionalPath. The OptionalPath contains a
1423// valid path if p is non-nil.
Liz Kammera830f3a2020-11-10 10:50:34 -08001424func OptionalPathForModuleSrc(ctx ModuleMissingDepsPathContext, p *string) OptionalPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001425 if p == nil {
1426 return OptionalPath{}
1427 }
1428 return OptionalPathForPath(PathForModuleSrc(ctx, *p))
1429}
1430
Liz Kammera830f3a2020-11-10 10:50:34 -08001431func (p SourcePath) genPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleGenPath {
Colin Cross7fc17db2017-02-01 14:07:55 -08001432 return PathForModuleGen(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001433}
1434
Liz Kammera830f3a2020-11-10 10:50:34 -08001435func (p SourcePath) objPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleObjPath {
Colin Cross7fc17db2017-02-01 14:07:55 -08001436 return PathForModuleObj(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001437}
1438
Liz Kammera830f3a2020-11-10 10:50:34 -08001439func (p SourcePath) resPathWithName(ctx ModuleOutPathContext, name string) ModuleResPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001440 // TODO: Use full directory if the new ctx is not the current ctx?
1441 return PathForModuleRes(ctx, p.path, name)
1442}
1443
1444// ModuleOutPath is a Path representing a module's output directory.
1445type ModuleOutPath struct {
1446 OutputPath
1447}
1448
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001449func (p ModuleOutPath) RelativeToTop() Path {
1450 p.OutputPath = p.outputPathRelativeToTop()
1451 return p
1452}
1453
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001454var _ Path = ModuleOutPath{}
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001455var _ WritablePath = ModuleOutPath{}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001456
Liz Kammera830f3a2020-11-10 10:50:34 -08001457func (p ModuleOutPath) objPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleObjPath {
Pete Bentleyfcf55bf2019-08-16 20:14:32 +01001458 return PathForModuleObj(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
1459}
1460
Liz Kammera830f3a2020-11-10 10:50:34 -08001461// ModuleOutPathContext Subset of ModuleContext functions necessary for output path methods.
1462type ModuleOutPathContext interface {
1463 PathContext
1464
1465 ModuleName() string
1466 ModuleDir() string
1467 ModuleSubDir() string
1468}
1469
1470func pathForModuleOut(ctx ModuleOutPathContext) OutputPath {
Colin Cross702e0f82017-10-18 17:27:54 -07001471 return PathForOutput(ctx, ".intermediates", ctx.ModuleDir(), ctx.ModuleName(), ctx.ModuleSubDir())
1472}
1473
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001474type BazelOutPath struct {
1475 OutputPath
1476}
1477
1478var _ Path = BazelOutPath{}
1479var _ objPathProvider = BazelOutPath{}
1480
Liz Kammera830f3a2020-11-10 10:50:34 -08001481func (p BazelOutPath) objPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleObjPath {
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001482 return PathForModuleObj(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
1483}
1484
Logan Chien7eefdc42018-07-11 18:10:41 +08001485// PathForVndkRefAbiDump returns an OptionalPath representing the path of the
1486// reference abi dump for the given module. This is not guaranteed to be valid.
Liz Kammera830f3a2020-11-10 10:50:34 -08001487func PathForVndkRefAbiDump(ctx ModuleInstallPathContext, version, fileName string,
Hsin-Yi Chen53489642019-07-31 17:10:45 +08001488 isNdk, isLlndkOrVndk, isGzip bool) OptionalPath {
Logan Chien7eefdc42018-07-11 18:10:41 +08001489
Jayant Chowdharyac066c62018-02-20 10:53:31 -08001490 arches := ctx.DeviceConfig().Arches()
Logan Chien7eefdc42018-07-11 18:10:41 +08001491 if len(arches) == 0 {
1492 panic("device build with no primary arch")
1493 }
Jayant Chowdharyac066c62018-02-20 10:53:31 -08001494 currentArch := ctx.Arch()
1495 archNameAndVariant := currentArch.ArchType.String()
1496 if currentArch.ArchVariant != "" {
1497 archNameAndVariant += "_" + currentArch.ArchVariant
1498 }
Logan Chien5237bed2018-07-11 17:15:57 +08001499
1500 var dirName string
Hsin-Yi Chen53489642019-07-31 17:10:45 +08001501 if isNdk {
Logan Chien5237bed2018-07-11 17:15:57 +08001502 dirName = "ndk"
Hsin-Yi Chen53489642019-07-31 17:10:45 +08001503 } else if isLlndkOrVndk {
Logan Chien5237bed2018-07-11 17:15:57 +08001504 dirName = "vndk"
Logan Chien41eabe62019-04-10 13:33:58 +08001505 } else {
1506 dirName = "platform" // opt-in libs
Jayant Chowdhary3e231fd2017-02-08 13:45:53 -08001507 }
Logan Chien5237bed2018-07-11 17:15:57 +08001508
Jayant Chowdhary34ce67d2018-03-08 11:00:50 -08001509 binderBitness := ctx.DeviceConfig().BinderBitness()
Logan Chien7eefdc42018-07-11 18:10:41 +08001510
1511 var ext string
1512 if isGzip {
1513 ext = ".lsdump.gz"
1514 } else {
1515 ext = ".lsdump"
1516 }
1517
1518 return ExistentPathForSource(ctx, "prebuilts", "abi-dumps", dirName,
1519 version, binderBitness, archNameAndVariant, "source-based",
1520 fileName+ext)
Jayant Chowdhary3e231fd2017-02-08 13:45:53 -08001521}
1522
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001523// PathForBazelOut returns a Path representing the paths... under an output directory dedicated to
1524// bazel-owned outputs.
1525func PathForBazelOut(ctx PathContext, paths ...string) BazelOutPath {
1526 execRootPathComponents := append([]string{"execroot", "__main__"}, paths...)
1527 execRootPath := filepath.Join(execRootPathComponents...)
1528 validatedExecRootPath, err := validatePath(execRootPath)
1529 if err != nil {
1530 reportPathError(ctx, err)
1531 }
1532
Paul Duffin74abc5d2021-03-24 09:24:59 +00001533 outputPath := OutputPath{basePath{"", ""},
Paul Duffind65c58b2021-03-24 09:22:07 +00001534 ctx.Config().buildDir,
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001535 ctx.Config().BazelContext.OutputBase()}
1536
1537 return BazelOutPath{
1538 OutputPath: outputPath.withRel(validatedExecRootPath),
1539 }
1540}
1541
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001542// PathForModuleOut returns a Path representing the paths... under the module's
1543// output directory.
Liz Kammera830f3a2020-11-10 10:50:34 -08001544func PathForModuleOut(ctx ModuleOutPathContext, paths ...string) ModuleOutPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001545 p, err := validatePath(paths...)
1546 if err != nil {
1547 reportPathError(ctx, err)
1548 }
Colin Cross702e0f82017-10-18 17:27:54 -07001549 return ModuleOutPath{
Liz Kammera830f3a2020-11-10 10:50:34 -08001550 OutputPath: pathForModuleOut(ctx).withRel(p),
Colin Cross702e0f82017-10-18 17:27:54 -07001551 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001552}
1553
1554// ModuleGenPath is a Path representing the 'gen' directory in a module's output
1555// directory. Mainly used for generated sources.
1556type ModuleGenPath struct {
1557 ModuleOutPath
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001558}
1559
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001560func (p ModuleGenPath) RelativeToTop() Path {
1561 p.OutputPath = p.outputPathRelativeToTop()
1562 return p
1563}
1564
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001565var _ Path = ModuleGenPath{}
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001566var _ WritablePath = ModuleGenPath{}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001567var _ genPathProvider = ModuleGenPath{}
1568var _ objPathProvider = ModuleGenPath{}
1569
1570// PathForModuleGen returns a Path representing the paths... under the module's
1571// `gen' directory.
Liz Kammera830f3a2020-11-10 10:50:34 -08001572func PathForModuleGen(ctx ModuleOutPathContext, paths ...string) ModuleGenPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001573 p, err := validatePath(paths...)
1574 if err != nil {
1575 reportPathError(ctx, err)
1576 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001577 return ModuleGenPath{
Colin Cross702e0f82017-10-18 17:27:54 -07001578 ModuleOutPath: ModuleOutPath{
Liz Kammera830f3a2020-11-10 10:50:34 -08001579 OutputPath: pathForModuleOut(ctx).withRel("gen").withRel(p),
Colin Cross702e0f82017-10-18 17:27:54 -07001580 },
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001581 }
1582}
1583
Liz Kammera830f3a2020-11-10 10:50:34 -08001584func (p ModuleGenPath) genPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleGenPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001585 // TODO: make a different path for local vs remote generated files?
Dan Willemsen21ec4902016-11-02 20:43:13 -07001586 return PathForModuleGen(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001587}
1588
Liz Kammera830f3a2020-11-10 10:50:34 -08001589func (p ModuleGenPath) objPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleObjPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001590 return PathForModuleObj(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
1591}
1592
1593// ModuleObjPath is a Path representing the 'obj' directory in a module's output
1594// directory. Used for compiled objects.
1595type ModuleObjPath struct {
1596 ModuleOutPath
1597}
1598
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001599func (p ModuleObjPath) RelativeToTop() Path {
1600 p.OutputPath = p.outputPathRelativeToTop()
1601 return p
1602}
1603
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001604var _ Path = ModuleObjPath{}
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001605var _ WritablePath = ModuleObjPath{}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001606
1607// PathForModuleObj returns a Path representing the paths... under the module's
1608// 'obj' directory.
Liz Kammera830f3a2020-11-10 10:50:34 -08001609func PathForModuleObj(ctx ModuleOutPathContext, pathComponents ...string) ModuleObjPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001610 p, err := validatePath(pathComponents...)
1611 if err != nil {
1612 reportPathError(ctx, err)
1613 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001614 return ModuleObjPath{PathForModuleOut(ctx, "obj", p)}
1615}
1616
1617// ModuleResPath is a a Path representing the 'res' directory in a module's
1618// output directory.
1619type ModuleResPath struct {
1620 ModuleOutPath
1621}
1622
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001623func (p ModuleResPath) RelativeToTop() Path {
1624 p.OutputPath = p.outputPathRelativeToTop()
1625 return p
1626}
1627
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001628var _ Path = ModuleResPath{}
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001629var _ WritablePath = ModuleResPath{}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001630
1631// PathForModuleRes returns a Path representing the paths... under the module's
1632// 'res' directory.
Liz Kammera830f3a2020-11-10 10:50:34 -08001633func PathForModuleRes(ctx ModuleOutPathContext, pathComponents ...string) ModuleResPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001634 p, err := validatePath(pathComponents...)
1635 if err != nil {
1636 reportPathError(ctx, err)
1637 }
1638
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001639 return ModuleResPath{PathForModuleOut(ctx, "res", p)}
1640}
1641
Colin Cross70dda7e2019-10-01 22:05:35 -07001642// InstallPath is a Path representing a installed file path rooted from the build directory
1643type InstallPath struct {
1644 basePath
Colin Crossff6c33d2019-10-02 16:01:35 -07001645
Paul Duffind65c58b2021-03-24 09:22:07 +00001646 // The soong build directory, i.e. Config.BuildDir()
1647 buildDir string
1648
Jiyong Park957bcd92020-10-20 18:23:33 +09001649 // partitionDir is the part of the InstallPath that is automatically determined according to the context.
1650 // For example, it is host/<os>-<arch> for host modules, and target/product/<device>/<partition> for device modules.
1651 partitionDir string
1652
1653 // makePath indicates whether this path is for Soong (false) or Make (true).
1654 makePath bool
Colin Cross70dda7e2019-10-01 22:05:35 -07001655}
1656
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001657// Will panic if called from outside a test environment.
1658func ensureTestOnly() {
Martin Stjernholm32312eb2021-03-27 18:54:49 +00001659 if PrefixInList(os.Args, "-test.") {
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001660 return
1661 }
Martin Stjernholm32312eb2021-03-27 18:54:49 +00001662 panic(fmt.Errorf("Not in test. Command line:\n %s", strings.Join(os.Args, "\n ")))
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001663}
1664
1665func (p InstallPath) RelativeToTop() Path {
1666 ensureTestOnly()
1667 p.buildDir = OutSoongDir
1668 return p
1669}
1670
Paul Duffind65c58b2021-03-24 09:22:07 +00001671func (p InstallPath) getBuildDir() string {
1672 return p.buildDir
Paul Duffin9b478b02019-12-10 13:41:51 +00001673}
1674
Hans MÃ¥nssond3f2bd72020-11-27 12:37:28 +01001675func (p InstallPath) ReplaceExtension(ctx PathContext, ext string) OutputPath {
1676 panic("Not implemented")
1677}
1678
Paul Duffin9b478b02019-12-10 13:41:51 +00001679var _ Path = InstallPath{}
1680var _ WritablePath = InstallPath{}
1681
Colin Cross70dda7e2019-10-01 22:05:35 -07001682func (p InstallPath) writablePath() {}
1683
1684func (p InstallPath) String() string {
Jiyong Park957bcd92020-10-20 18:23:33 +09001685 if p.makePath {
1686 // Make path starts with out/ instead of out/soong.
Paul Duffind65c58b2021-03-24 09:22:07 +00001687 return filepath.Join(p.buildDir, "../", p.path)
Jiyong Park957bcd92020-10-20 18:23:33 +09001688 } else {
Paul Duffind65c58b2021-03-24 09:22:07 +00001689 return filepath.Join(p.buildDir, p.path)
Jiyong Park957bcd92020-10-20 18:23:33 +09001690 }
1691}
1692
1693// PartitionDir returns the path to the partition where the install path is rooted at. It is
1694// out/soong/target/product/<device>/<partition> for device modules, and out/soong/host/<os>-<arch> for host modules.
1695// The ./soong is dropped if the install path is for Make.
1696func (p InstallPath) PartitionDir() string {
1697 if p.makePath {
Paul Duffind65c58b2021-03-24 09:22:07 +00001698 return filepath.Join(p.buildDir, "../", p.partitionDir)
Jiyong Park957bcd92020-10-20 18:23:33 +09001699 } else {
Paul Duffind65c58b2021-03-24 09:22:07 +00001700 return filepath.Join(p.buildDir, p.partitionDir)
Jiyong Park957bcd92020-10-20 18:23:33 +09001701 }
Colin Cross70dda7e2019-10-01 22:05:35 -07001702}
1703
1704// Join creates a new InstallPath with paths... joined with the current path. The
1705// provided paths... may not use '..' to escape from the current path.
1706func (p InstallPath) Join(ctx PathContext, paths ...string) InstallPath {
1707 path, err := validatePath(paths...)
1708 if err != nil {
1709 reportPathError(ctx, err)
1710 }
1711 return p.withRel(path)
1712}
1713
1714func (p InstallPath) withRel(rel string) InstallPath {
1715 p.basePath = p.basePath.withRel(rel)
1716 return p
1717}
1718
Colin Crossff6c33d2019-10-02 16:01:35 -07001719// ToMakePath returns a new InstallPath that points to Make's install directory instead of Soong's,
1720// i.e. out/ instead of out/soong/.
1721func (p InstallPath) ToMakePath() InstallPath {
Jiyong Park957bcd92020-10-20 18:23:33 +09001722 p.makePath = true
Colin Crossff6c33d2019-10-02 16:01:35 -07001723 return p
Colin Cross70dda7e2019-10-01 22:05:35 -07001724}
1725
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001726// PathForModuleInstall returns a Path representing the install path for the
1727// module appended with paths...
Colin Cross70dda7e2019-10-01 22:05:35 -07001728func PathForModuleInstall(ctx ModuleInstallPathContext, pathComponents ...string) InstallPath {
Colin Cross6e359402020-02-10 15:29:54 -08001729 os := ctx.Os()
Jiyong Park87788b52020-09-01 12:37:45 +09001730 arch := ctx.Arch().ArchType
1731 forceOS, forceArch := ctx.InstallForceOS()
1732 if forceOS != nil {
Colin Cross6e359402020-02-10 15:29:54 -08001733 os = *forceOS
1734 }
Jiyong Park87788b52020-09-01 12:37:45 +09001735 if forceArch != nil {
1736 arch = *forceArch
1737 }
Colin Cross6e359402020-02-10 15:29:54 -08001738 partition := modulePartition(ctx, os)
Colin Cross609c49a2020-02-13 13:20:11 -08001739
Jiyong Park87788b52020-09-01 12:37:45 +09001740 ret := pathForInstall(ctx, os, arch, partition, ctx.Debug(), pathComponents...)
Colin Cross609c49a2020-02-13 13:20:11 -08001741
Jingwen Chencda22c92020-11-23 00:22:30 -05001742 if ctx.InstallBypassMake() && ctx.Config().KatiEnabled() {
Colin Cross609c49a2020-02-13 13:20:11 -08001743 ret = ret.ToMakePath()
1744 }
1745
1746 return ret
1747}
1748
Jiyong Park87788b52020-09-01 12:37:45 +09001749func pathForInstall(ctx PathContext, os OsType, arch ArchType, partition string, debug bool,
Colin Cross609c49a2020-02-13 13:20:11 -08001750 pathComponents ...string) InstallPath {
1751
Jiyong Park957bcd92020-10-20 18:23:33 +09001752 var partionPaths []string
Colin Cross609c49a2020-02-13 13:20:11 -08001753
Colin Cross6e359402020-02-10 15:29:54 -08001754 if os.Class == Device {
Jiyong Park957bcd92020-10-20 18:23:33 +09001755 partionPaths = []string{"target", "product", ctx.Config().DeviceName(), partition}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001756 } else {
Jiyong Park87788b52020-09-01 12:37:45 +09001757 osName := os.String()
1758 if os == Linux {
1759 // instead of linux_glibc
1760 osName = "linux"
Dan Willemsen866b5632017-09-22 12:28:24 -07001761 }
Jiyong Park87788b52020-09-01 12:37:45 +09001762 // SOONG_HOST_OUT is set to out/host/$(HOST_OS)-$(HOST_PREBUILT_ARCH)
1763 // and HOST_PREBUILT_ARCH is forcibly set to x86 even on x86_64 hosts. We don't seem
1764 // to have a plan to fix it (see the comment in build/make/core/envsetup.mk).
1765 // Let's keep using x86 for the existing cases until we have a need to support
1766 // other architectures.
1767 archName := arch.String()
1768 if os.Class == Host && (arch == X86_64 || arch == Common) {
1769 archName = "x86"
1770 }
Jiyong Park957bcd92020-10-20 18:23:33 +09001771 partionPaths = []string{"host", osName + "-" + archName, partition}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001772 }
Colin Cross609c49a2020-02-13 13:20:11 -08001773 if debug {
Jiyong Park957bcd92020-10-20 18:23:33 +09001774 partionPaths = append([]string{"debug"}, partionPaths...)
Dan Willemsen782a2d12015-12-21 14:55:28 -08001775 }
Colin Cross70dda7e2019-10-01 22:05:35 -07001776
Jiyong Park957bcd92020-10-20 18:23:33 +09001777 partionPath, err := validatePath(partionPaths...)
Colin Cross70dda7e2019-10-01 22:05:35 -07001778 if err != nil {
1779 reportPathError(ctx, err)
1780 }
Colin Crossff6c33d2019-10-02 16:01:35 -07001781
Jiyong Park957bcd92020-10-20 18:23:33 +09001782 base := InstallPath{
Paul Duffin74abc5d2021-03-24 09:24:59 +00001783 basePath: basePath{partionPath, ""},
Paul Duffind65c58b2021-03-24 09:22:07 +00001784 buildDir: ctx.Config().buildDir,
Jiyong Park957bcd92020-10-20 18:23:33 +09001785 partitionDir: partionPath,
1786 makePath: false,
1787 }
Colin Crossff6c33d2019-10-02 16:01:35 -07001788
Jiyong Park957bcd92020-10-20 18:23:33 +09001789 return base.Join(ctx, pathComponents...)
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001790}
1791
Nicolas Geoffray1228e9c2020-02-27 13:45:35 +00001792func pathForNdkOrSdkInstall(ctx PathContext, prefix string, paths []string) InstallPath {
Jiyong Park957bcd92020-10-20 18:23:33 +09001793 base := InstallPath{
Paul Duffin74abc5d2021-03-24 09:24:59 +00001794 basePath: basePath{prefix, ""},
Paul Duffind65c58b2021-03-24 09:22:07 +00001795 buildDir: ctx.Config().buildDir,
Jiyong Park957bcd92020-10-20 18:23:33 +09001796 partitionDir: prefix,
1797 makePath: false,
Colin Cross70dda7e2019-10-01 22:05:35 -07001798 }
Jiyong Park957bcd92020-10-20 18:23:33 +09001799 return base.Join(ctx, paths...)
Colin Cross70dda7e2019-10-01 22:05:35 -07001800}
1801
Nicolas Geoffray1228e9c2020-02-27 13:45:35 +00001802func PathForNdkInstall(ctx PathContext, paths ...string) InstallPath {
1803 return pathForNdkOrSdkInstall(ctx, "ndk", paths)
1804}
1805
1806func PathForMainlineSdksInstall(ctx PathContext, paths ...string) InstallPath {
1807 return pathForNdkOrSdkInstall(ctx, "mainline-sdks", paths)
1808}
1809
Colin Cross70dda7e2019-10-01 22:05:35 -07001810func InstallPathToOnDevicePath(ctx PathContext, path InstallPath) string {
Colin Cross43f08db2018-11-12 10:13:39 -08001811 rel := Rel(ctx, PathForOutput(ctx, "target", "product", ctx.Config().DeviceName()).String(), path.String())
1812
1813 return "/" + rel
1814}
1815
Colin Cross6e359402020-02-10 15:29:54 -08001816func modulePartition(ctx ModuleInstallPathContext, os OsType) string {
Colin Cross43f08db2018-11-12 10:13:39 -08001817 var partition string
Colin Cross6e359402020-02-10 15:29:54 -08001818 if ctx.InstallInTestcases() {
1819 // "testcases" install directory can be used for host or device modules.
Jaewoong Jung0949f312019-09-11 10:25:18 -07001820 partition = "testcases"
Colin Cross6e359402020-02-10 15:29:54 -08001821 } else if os.Class == Device {
1822 if ctx.InstallInData() {
1823 partition = "data"
1824 } else if ctx.InstallInRamdisk() {
1825 if ctx.DeviceConfig().BoardUsesRecoveryAsBoot() {
1826 partition = "recovery/root/first_stage_ramdisk"
1827 } else {
1828 partition = "ramdisk"
1829 }
1830 if !ctx.InstallInRoot() {
1831 partition += "/system"
1832 }
Yifan Hong60e0cfb2020-10-21 15:17:56 -07001833 } else if ctx.InstallInVendorRamdisk() {
Yifan Hong39143a92020-10-26 12:43:12 -07001834 // The module is only available after switching root into
1835 // /first_stage_ramdisk. To expose the module before switching root
1836 // on a device without a dedicated recovery partition, install the
1837 // recovery variant.
Yifan Hongdd8dacc2020-10-21 15:40:17 -07001838 if ctx.DeviceConfig().BoardMoveRecoveryResourcesToVendorBoot() {
Petri Gyntherac229562021-03-02 23:44:02 -08001839 partition = "vendor_ramdisk/first_stage_ramdisk"
Yifan Hongdd8dacc2020-10-21 15:40:17 -07001840 } else {
Petri Gyntherac229562021-03-02 23:44:02 -08001841 partition = "vendor_ramdisk"
Yifan Hongdd8dacc2020-10-21 15:40:17 -07001842 }
1843 if !ctx.InstallInRoot() {
1844 partition += "/system"
1845 }
Colin Cross6e359402020-02-10 15:29:54 -08001846 } else if ctx.InstallInRecovery() {
1847 if ctx.InstallInRoot() {
1848 partition = "recovery/root"
1849 } else {
1850 // the layout of recovery partion is the same as that of system partition
1851 partition = "recovery/root/system"
1852 }
1853 } else if ctx.SocSpecific() {
1854 partition = ctx.DeviceConfig().VendorPath()
1855 } else if ctx.DeviceSpecific() {
1856 partition = ctx.DeviceConfig().OdmPath()
1857 } else if ctx.ProductSpecific() {
1858 partition = ctx.DeviceConfig().ProductPath()
1859 } else if ctx.SystemExtSpecific() {
1860 partition = ctx.DeviceConfig().SystemExtPath()
1861 } else if ctx.InstallInRoot() {
1862 partition = "root"
Yifan Hong82db7352020-01-21 16:12:26 -08001863 } else {
Colin Cross6e359402020-02-10 15:29:54 -08001864 partition = "system"
Yifan Hong82db7352020-01-21 16:12:26 -08001865 }
Colin Cross6e359402020-02-10 15:29:54 -08001866 if ctx.InstallInSanitizerDir() {
1867 partition = "data/asan/" + partition
Yifan Hong82db7352020-01-21 16:12:26 -08001868 }
Colin Cross43f08db2018-11-12 10:13:39 -08001869 }
1870 return partition
1871}
1872
Colin Cross609c49a2020-02-13 13:20:11 -08001873type InstallPaths []InstallPath
1874
1875// Paths returns the InstallPaths as a Paths
1876func (p InstallPaths) Paths() Paths {
1877 if p == nil {
1878 return nil
1879 }
1880 ret := make(Paths, len(p))
1881 for i, path := range p {
1882 ret[i] = path
1883 }
1884 return ret
1885}
1886
1887// Strings returns the string forms of the install paths.
1888func (p InstallPaths) Strings() []string {
1889 if p == nil {
1890 return nil
1891 }
1892 ret := make([]string, len(p))
1893 for i, path := range p {
1894 ret[i] = path.String()
1895 }
1896 return ret
1897}
1898
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001899// validateSafePath validates a path that we trust (may contain ninja variables).
Dan Willemsen80a7c2a2015-12-21 14:57:11 -08001900// Ensures that each path component does not attempt to leave its component.
Colin Cross1ccfcc32018-02-22 13:54:26 -08001901func validateSafePath(pathComponents ...string) (string, error) {
Jeff Gaston734e3802017-04-10 15:47:24 -07001902 for _, path := range pathComponents {
Dan Willemsen80a7c2a2015-12-21 14:57:11 -08001903 path := filepath.Clean(path)
1904 if path == ".." || strings.HasPrefix(path, "../") || strings.HasPrefix(path, "/") {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001905 return "", fmt.Errorf("Path is outside directory: %s", path)
Dan Willemsen80a7c2a2015-12-21 14:57:11 -08001906 }
1907 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001908 // TODO: filepath.Join isn't necessarily correct with embedded ninja
1909 // variables. '..' may remove the entire ninja variable, even if it
1910 // will be expanded to multiple nested directories.
Colin Cross1ccfcc32018-02-22 13:54:26 -08001911 return filepath.Join(pathComponents...), nil
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001912}
1913
Dan Willemsen80a7c2a2015-12-21 14:57:11 -08001914// validatePath validates that a path does not include ninja variables, and that
1915// each path component does not attempt to leave its component. Returns a joined
1916// version of each path component.
Colin Cross1ccfcc32018-02-22 13:54:26 -08001917func validatePath(pathComponents ...string) (string, error) {
Jeff Gaston734e3802017-04-10 15:47:24 -07001918 for _, path := range pathComponents {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001919 if strings.Contains(path, "$") {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001920 return "", fmt.Errorf("Path contains invalid character($): %s", path)
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001921 }
1922 }
Colin Cross1ccfcc32018-02-22 13:54:26 -08001923 return validateSafePath(pathComponents...)
Colin Cross6e18ca42015-07-14 18:55:36 -07001924}
Colin Cross5b529592017-05-09 13:34:34 -07001925
Colin Cross0875c522017-11-28 17:34:01 -08001926func PathForPhony(ctx PathContext, phony string) WritablePath {
1927 if strings.ContainsAny(phony, "$/") {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001928 ReportPathErrorf(ctx, "Phony target contains invalid character ($ or /): %s", phony)
Colin Cross0875c522017-11-28 17:34:01 -08001929 }
Paul Duffin74abc5d2021-03-24 09:24:59 +00001930 return PhonyPath{basePath{phony, ""}}
Colin Cross0875c522017-11-28 17:34:01 -08001931}
1932
Colin Cross74e3fe42017-12-11 15:51:44 -08001933type PhonyPath struct {
1934 basePath
1935}
1936
1937func (p PhonyPath) writablePath() {}
1938
Paul Duffind65c58b2021-03-24 09:22:07 +00001939func (p PhonyPath) getBuildDir() string {
1940 // A phone path cannot contain any / so cannot be relative to the build directory.
1941 return ""
Paul Duffin9b478b02019-12-10 13:41:51 +00001942}
1943
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001944func (p PhonyPath) RelativeToTop() Path {
1945 ensureTestOnly()
1946 // A phony path cannot contain any / so does not have a build directory so switching to a new
1947 // build directory has no effect so just return this path.
1948 return p
1949}
1950
Hans MÃ¥nssond3f2bd72020-11-27 12:37:28 +01001951func (p PhonyPath) ReplaceExtension(ctx PathContext, ext string) OutputPath {
1952 panic("Not implemented")
1953}
1954
Colin Cross74e3fe42017-12-11 15:51:44 -08001955var _ Path = PhonyPath{}
1956var _ WritablePath = PhonyPath{}
1957
Colin Cross5b529592017-05-09 13:34:34 -07001958type testPath struct {
1959 basePath
1960}
1961
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001962func (p testPath) RelativeToTop() Path {
1963 ensureTestOnly()
1964 return p
1965}
1966
Colin Cross5b529592017-05-09 13:34:34 -07001967func (p testPath) String() string {
1968 return p.path
1969}
1970
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001971var _ Path = testPath{}
1972
Colin Cross40e33732019-02-15 11:08:35 -08001973// PathForTesting returns a Path constructed from joining the elements of paths with '/'. It should only be used from
1974// within tests.
Colin Cross5b529592017-05-09 13:34:34 -07001975func PathForTesting(paths ...string) Path {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001976 p, err := validateSafePath(paths...)
1977 if err != nil {
1978 panic(err)
1979 }
Colin Cross5b529592017-05-09 13:34:34 -07001980 return testPath{basePath{path: p, rel: p}}
1981}
1982
Colin Cross40e33732019-02-15 11:08:35 -08001983// PathsForTesting returns a Path constructed from each element in strs. It should only be used from within tests.
1984func PathsForTesting(strs ...string) Paths {
Colin Cross5b529592017-05-09 13:34:34 -07001985 p := make(Paths, len(strs))
1986 for i, s := range strs {
1987 p[i] = PathForTesting(s)
1988 }
1989
1990 return p
1991}
Colin Cross43f08db2018-11-12 10:13:39 -08001992
Colin Cross40e33732019-02-15 11:08:35 -08001993type testPathContext struct {
1994 config Config
Colin Cross40e33732019-02-15 11:08:35 -08001995}
1996
Colin Cross40e33732019-02-15 11:08:35 -08001997func (x *testPathContext) Config() Config { return x.config }
1998func (x *testPathContext) AddNinjaFileDeps(...string) {}
1999
2000// PathContextForTesting returns a PathContext that can be used in tests, for example to create an OutputPath with
2001// PathForOutput.
Colin Cross98be1bb2019-12-13 20:41:13 -08002002func PathContextForTesting(config Config) PathContext {
Colin Cross40e33732019-02-15 11:08:35 -08002003 return &testPathContext{
2004 config: config,
Colin Cross40e33732019-02-15 11:08:35 -08002005 }
2006}
2007
Ulya Trafimovichccc8c852020-10-14 11:29:07 +01002008type testModuleInstallPathContext struct {
2009 baseModuleContext
2010
2011 inData bool
2012 inTestcases bool
2013 inSanitizerDir bool
2014 inRamdisk bool
2015 inVendorRamdisk bool
2016 inRecovery bool
2017 inRoot bool
2018 forceOS *OsType
2019 forceArch *ArchType
2020}
2021
2022func (m testModuleInstallPathContext) Config() Config {
2023 return m.baseModuleContext.config
2024}
2025
2026func (testModuleInstallPathContext) AddNinjaFileDeps(deps ...string) {}
2027
2028func (m testModuleInstallPathContext) InstallInData() bool {
2029 return m.inData
2030}
2031
2032func (m testModuleInstallPathContext) InstallInTestcases() bool {
2033 return m.inTestcases
2034}
2035
2036func (m testModuleInstallPathContext) InstallInSanitizerDir() bool {
2037 return m.inSanitizerDir
2038}
2039
2040func (m testModuleInstallPathContext) InstallInRamdisk() bool {
2041 return m.inRamdisk
2042}
2043
2044func (m testModuleInstallPathContext) InstallInVendorRamdisk() bool {
2045 return m.inVendorRamdisk
2046}
2047
2048func (m testModuleInstallPathContext) InstallInRecovery() bool {
2049 return m.inRecovery
2050}
2051
2052func (m testModuleInstallPathContext) InstallInRoot() bool {
2053 return m.inRoot
2054}
2055
2056func (m testModuleInstallPathContext) InstallBypassMake() bool {
2057 return false
2058}
2059
2060func (m testModuleInstallPathContext) InstallForceOS() (*OsType, *ArchType) {
2061 return m.forceOS, m.forceArch
2062}
2063
2064// Construct a minimal ModuleInstallPathContext for testing. Note that baseModuleContext is
2065// default-initialized, which leaves blueprint.baseModuleContext set to nil, so methods that are
2066// delegated to it will panic.
2067func ModuleInstallPathContextForTesting(config Config) ModuleInstallPathContext {
2068 ctx := &testModuleInstallPathContext{}
2069 ctx.config = config
2070 ctx.os = Android
2071 return ctx
2072}
2073
Colin Cross43f08db2018-11-12 10:13:39 -08002074// Rel performs the same function as filepath.Rel, but reports errors to a PathContext, and reports an error if
2075// targetPath is not inside basePath.
2076func Rel(ctx PathContext, basePath string, targetPath string) string {
2077 rel, isRel := MaybeRel(ctx, basePath, targetPath)
2078 if !isRel {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01002079 ReportPathErrorf(ctx, "path %q is not under path %q", targetPath, basePath)
Colin Cross43f08db2018-11-12 10:13:39 -08002080 return ""
2081 }
2082 return rel
2083}
2084
2085// MaybeRel performs the same function as filepath.Rel, but reports errors to a PathContext, and returns false if
2086// targetPath is not inside basePath.
2087func MaybeRel(ctx PathContext, basePath string, targetPath string) (string, bool) {
Dan Willemsen633c5022019-04-12 11:11:38 -07002088 rel, isRel, err := maybeRelErr(basePath, targetPath)
2089 if err != nil {
2090 reportPathError(ctx, err)
2091 }
2092 return rel, isRel
2093}
2094
2095func maybeRelErr(basePath string, targetPath string) (string, bool, error) {
Colin Cross43f08db2018-11-12 10:13:39 -08002096 // filepath.Rel returns an error if one path is absolute and the other is not, handle that case first.
2097 if filepath.IsAbs(basePath) != filepath.IsAbs(targetPath) {
Dan Willemsen633c5022019-04-12 11:11:38 -07002098 return "", false, nil
Colin Cross43f08db2018-11-12 10:13:39 -08002099 }
2100 rel, err := filepath.Rel(basePath, targetPath)
2101 if err != nil {
Dan Willemsen633c5022019-04-12 11:11:38 -07002102 return "", false, err
Colin Cross43f08db2018-11-12 10:13:39 -08002103 } else if rel == ".." || strings.HasPrefix(rel, "../") || strings.HasPrefix(rel, "/") {
Dan Willemsen633c5022019-04-12 11:11:38 -07002104 return "", false, nil
Colin Cross43f08db2018-11-12 10:13:39 -08002105 }
Dan Willemsen633c5022019-04-12 11:11:38 -07002106 return rel, true, nil
Colin Cross43f08db2018-11-12 10:13:39 -08002107}
Colin Cross988414c2020-01-11 01:11:46 +00002108
2109// Writes a file to the output directory. Attempting to write directly to the output directory
2110// will fail due to the sandbox of the soong_build process.
2111func WriteFileToOutputDir(path WritablePath, data []byte, perm os.FileMode) error {
2112 return ioutil.WriteFile(absolutePath(path.String()), data, perm)
2113}
2114
Liz Kammer2dd9ca42020-11-25 16:06:39 -08002115func RemoveAllOutputDir(path WritablePath) error {
2116 return os.RemoveAll(absolutePath(path.String()))
2117}
2118
2119func CreateOutputDirIfNonexistent(path WritablePath, perm os.FileMode) error {
2120 dir := absolutePath(path.String())
2121 if _, err := os.Stat(dir); os.IsNotExist(err) {
2122 return os.MkdirAll(dir, os.ModePerm)
2123 } else {
2124 return err
2125 }
2126}
2127
Colin Cross988414c2020-01-11 01:11:46 +00002128func absolutePath(path string) string {
2129 if filepath.IsAbs(path) {
2130 return path
2131 }
2132 return filepath.Join(absSrcDir, path)
2133}
Chris Parsons216e10a2020-07-09 17:12:52 -04002134
2135// A DataPath represents the path of a file to be used as data, for example
2136// a test library to be installed alongside a test.
2137// The data file should be installed (copied from `<SrcPath>`) to
2138// `<install_root>/<RelativeInstallPath>/<filename>`, or
2139// `<install_root>/<filename>` if RelativeInstallPath is empty.
2140type DataPath struct {
2141 // The path of the data file that should be copied into the data directory
2142 SrcPath Path
2143 // The install path of the data file, relative to the install root.
2144 RelativeInstallPath string
2145}
Colin Crossdcf71b22021-02-01 13:59:03 -08002146
2147// PathsIfNonNil returns a Paths containing only the non-nil input arguments.
2148func PathsIfNonNil(paths ...Path) Paths {
2149 if len(paths) == 0 {
2150 // Fast path for empty argument list
2151 return nil
2152 } else if len(paths) == 1 {
2153 // Fast path for a single argument
2154 if paths[0] != nil {
2155 return paths
2156 } else {
2157 return nil
2158 }
2159 }
2160 ret := make(Paths, 0, len(paths))
2161 for _, path := range paths {
2162 if path != nil {
2163 ret = append(ret, path)
2164 }
2165 }
2166 if len(ret) == 0 {
2167 return nil
2168 }
2169 return ret
2170}