blob: d770823900aa603c16cd64a261830b5bc8f03608 [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
Rupert Shuttleworthc143cc52021-04-13 13:08:04 -0400419// Returns true if a prefix + components[:i] + /Android.bp exists
420// TODO(b/185358476) Could check for BUILD file instead of checking for Android.bp file, or ensure BUILD is always generated?
421func directoryHasBlueprint(fs pathtools.FileSystem, prefix string, components []string, componentIndex int) bool {
422 blueprintPath := prefix
423 if blueprintPath != "" {
424 blueprintPath = blueprintPath + "/"
425 }
426 blueprintPath = blueprintPath + strings.Join(components[:componentIndex+1], "/")
427 blueprintPath = blueprintPath + "/Android.bp"
428 if exists, _, _ := fs.Exists(blueprintPath); exists {
429 return true
430 } else {
431 return false
432 }
433}
434
435// Transform a path (if necessary) to acknowledge package boundaries
436//
437// e.g. something like
438// async_safe/include/async_safe/CHECK.h
439// might become
440// //bionic/libc/async_safe:include/async_safe/CHECK.h
441// if the "async_safe" directory is actually a package and not just a directory.
442//
443// In particular, paths that extend into packages are transformed into absolute labels beginning with //.
444func transformSubpackagePath(ctx BazelConversionPathContext, path bazel.Label) bazel.Label {
445 var newPath bazel.Label
446
447 // Don't transform Bp_text
448 newPath.Bp_text = path.Bp_text
449
450 if strings.HasPrefix(path.Label, "//") {
451 // Assume absolute labels are already correct (e.g. //path/to/some/package:foo.h)
452 newPath.Label = path.Label
453 return newPath
454 }
455
456 newLabel := ""
457 pathComponents := strings.Split(path.Label, "/")
458 foundBlueprint := false
459 // Check the deepest subdirectory first and work upwards
460 for i := len(pathComponents) - 1; i >= 0; i-- {
461 pathComponent := pathComponents[i]
462 var sep string
463 if !foundBlueprint && directoryHasBlueprint(ctx.Config().fs, ctx.ModuleDir(), pathComponents, i) {
464 sep = ":"
465 foundBlueprint = true
466 } else {
467 sep = "/"
468 }
469 if newLabel == "" {
470 newLabel = pathComponent
471 } else {
472 newLabel = pathComponent + sep + newLabel
473 }
474 }
475 if foundBlueprint {
476 // Ensure paths end up looking like //bionic/... instead of //./bionic/...
477 moduleDir := ctx.ModuleDir()
478 if strings.HasPrefix(moduleDir, ".") {
479 moduleDir = moduleDir[1:]
480 }
481 // Make the path into an absolute label (e.g. //bionic/libc/foo:bar.h instead of just foo:bar.h)
482 if moduleDir == "" {
483 newLabel = "//" + newLabel
484 } else {
485 newLabel = "//" + moduleDir + "/" + newLabel
486 }
487 }
488 newPath.Label = newLabel
489
490 return newPath
491}
492
493// Transform paths to acknowledge package boundaries
494// See transformSubpackagePath() for more information
495func transformSubpackagePaths(ctx BazelConversionPathContext, paths bazel.LabelList) bazel.LabelList {
496 var newPaths bazel.LabelList
497 for _, include := range paths.Includes {
498 newPaths.Includes = append(newPaths.Includes, transformSubpackagePath(ctx, include))
499 }
500 for _, exclude := range paths.Excludes {
501 newPaths.Excludes = append(newPaths.Excludes, transformSubpackagePath(ctx, exclude))
502 }
503 return newPaths
504}
505
Liz Kammer356f7d42021-01-26 09:18:53 -0500506// BazelLabelForModuleSrc returns bazel.LabelList with paths rooted from the module's local source
507// directory. It expands globs, and resolves references to modules using the ":name" syntax to
508// bazel-compatible labels. Properties passed as the paths or excludes argument must have been
509// annotated with struct tag `android:"path"` so that dependencies on other modules will have
510// already been handled by the path_properties mutator.
Jingwen Chen63930982021-03-24 10:04:33 -0400511//
512// With expanded globs, we can catch package boundaries problem instead of
513// silently failing to potentially missing files from Bazel's globs.
Liz Kammer356f7d42021-01-26 09:18:53 -0500514func BazelLabelForModuleSrc(ctx BazelConversionPathContext, paths []string) bazel.LabelList {
515 return BazelLabelForModuleSrcExcludes(ctx, paths, []string(nil))
516}
517
518// BazelLabelForModuleSrcExcludes returns bazel.LabelList with paths rooted from the module's local
519// source directory, excluding labels included in the excludes argument. It expands globs, and
520// resolves references to modules using the ":name" syntax to bazel-compatible labels. Properties
521// passed as the paths or excludes argument must have been annotated with struct tag
522// `android:"path"` so that dependencies on other modules will have already been handled by the
523// path_properties mutator.
Jingwen Chen63930982021-03-24 10:04:33 -0400524//
525// With expanded globs, we can catch package boundaries problem instead of
526// silently failing to potentially missing files from Bazel's globs.
Liz Kammer356f7d42021-01-26 09:18:53 -0500527func BazelLabelForModuleSrcExcludes(ctx BazelConversionPathContext, paths, excludes []string) bazel.LabelList {
528 excludeLabels := expandSrcsForBazel(ctx, excludes, []string(nil))
529 excluded := make([]string, 0, len(excludeLabels.Includes))
530 for _, e := range excludeLabels.Includes {
531 excluded = append(excluded, e.Label)
532 }
533 labels := expandSrcsForBazel(ctx, paths, excluded)
534 labels.Excludes = excludeLabels.Includes
Rupert Shuttleworthc143cc52021-04-13 13:08:04 -0400535 labels = transformSubpackagePaths(ctx, labels)
Liz Kammer356f7d42021-01-26 09:18:53 -0500536 return labels
537}
538
539// expandSrcsForBazel returns bazel.LabelList with paths rooted from the module's local
540// source directory, excluding labels included in the excludes argument. It expands globs, and
541// resolves references to modules using the ":name" syntax to bazel-compatible labels. Properties
542// passed as the paths or excludes argument must have been annotated with struct tag
543// `android:"path"` so that dependencies on other modules will have already been handled by the
544// path_properties mutator.
545func expandSrcsForBazel(ctx BazelConversionPathContext, paths, expandedExcludes []string) bazel.LabelList {
Liz Kammerebfcf672021-02-16 15:00:05 -0500546 if paths == nil {
547 return bazel.LabelList{}
548 }
Liz Kammer356f7d42021-01-26 09:18:53 -0500549 labels := bazel.LabelList{
550 Includes: []bazel.Label{},
551 }
552 for _, p := range paths {
553 if m, tag := SrcIsModuleWithTag(p); m != "" {
554 l := getOtherModuleLabel(ctx, m, tag)
555 if !InList(l.Label, expandedExcludes) {
556 l.Bp_text = fmt.Sprintf(":%s", m)
557 labels.Includes = append(labels.Includes, l)
558 }
559 } else {
560 var expandedPaths []bazel.Label
561 if pathtools.IsGlob(p) {
562 globbedPaths := GlobFiles(ctx, pathForModuleSrc(ctx, p).String(), expandedExcludes)
563 globbedPaths = PathsWithModuleSrcSubDir(ctx, globbedPaths, "")
564 for _, path := range globbedPaths {
565 s := path.Rel()
566 expandedPaths = append(expandedPaths, bazel.Label{Label: s})
567 }
568 } else {
569 if !InList(p, expandedExcludes) {
570 expandedPaths = append(expandedPaths, bazel.Label{Label: p})
571 }
572 }
573 labels.Includes = append(labels.Includes, expandedPaths...)
574 }
575 }
576 return labels
577}
578
579// getOtherModuleLabel returns a bazel.Label for the given dependency/tag combination for the
580// module. The label will be relative to the current directory if appropriate. The dependency must
581// already be resolved by either deps mutator or path deps mutator.
582func getOtherModuleLabel(ctx BazelConversionPathContext, dep, tag string) bazel.Label {
583 m, _ := ctx.GetDirectDep(dep)
Jingwen Chen07027912021-03-15 06:02:43 -0400584 if m == nil {
585 panic(fmt.Errorf("cannot get direct dep %s of %s", dep, ctx.Module().Name()))
586 }
Liz Kammerbdc60992021-02-24 16:55:11 -0500587 otherLabel := bazelModuleLabel(ctx, m, tag)
588 label := bazelModuleLabel(ctx, ctx.Module(), "")
589 if samePackage(label, otherLabel) {
590 otherLabel = bazelShortLabel(otherLabel)
Liz Kammer356f7d42021-01-26 09:18:53 -0500591 }
Liz Kammerbdc60992021-02-24 16:55:11 -0500592
593 return bazel.Label{
594 Label: otherLabel,
595 }
596}
597
598func bazelModuleLabel(ctx BazelConversionPathContext, module blueprint.Module, tag string) string {
599 // TODO(b/165114590): Convert tag (":name{.tag}") to corresponding Bazel implicit output targets.
600 b, ok := module.(Bazelable)
601 // 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 -0500602 if !ok || !b.ConvertedToBazel(ctx) {
Liz Kammerbdc60992021-02-24 16:55:11 -0500603 return bp2buildModuleLabel(ctx, module)
604 }
605 return b.GetBazelLabel(ctx, module)
606}
607
608func bazelShortLabel(label string) string {
609 i := strings.Index(label, ":")
610 return label[i:]
611}
612
613func bazelPackage(label string) string {
614 i := strings.Index(label, ":")
615 return label[0:i]
616}
617
618func samePackage(label1, label2 string) bool {
619 return bazelPackage(label1) == bazelPackage(label2)
620}
621
622func bp2buildModuleLabel(ctx BazelConversionPathContext, module blueprint.Module) string {
623 moduleName := ctx.OtherModuleName(module)
624 moduleDir := ctx.OtherModuleDir(module)
625 return fmt.Sprintf("//%s:%s", moduleDir, moduleName)
Liz Kammer356f7d42021-01-26 09:18:53 -0500626}
627
Ulya Trafimovich4d2eeed2019-11-08 10:54:21 +0000628// OutputPaths is a slice of OutputPath objects, with helpers to operate on the collection.
629type OutputPaths []OutputPath
630
631// Paths returns the OutputPaths as a Paths
632func (p OutputPaths) Paths() Paths {
633 if p == nil {
634 return nil
635 }
636 ret := make(Paths, len(p))
637 for i, path := range p {
638 ret[i] = path
639 }
640 return ret
641}
642
643// Strings returns the string forms of the writable paths.
644func (p OutputPaths) Strings() []string {
645 if p == nil {
646 return nil
647 }
648 ret := make([]string, len(p))
649 for i, path := range p {
650 ret[i] = path.String()
651 }
652 return ret
653}
654
Liz Kammera830f3a2020-11-10 10:50:34 -0800655// Expands Paths to a SourceFileProducer or OutputFileProducer module dependency referenced via ":name" or ":name{.tag}" syntax.
656// If the dependency is not found, a missingErrorDependency is returned.
657// If the module dependency is not a SourceFileProducer or OutputFileProducer, appropriate errors will be returned.
658func getPathsFromModuleDep(ctx ModuleWithDepsPathContext, path, moduleName, tag string) (Paths, error) {
659 module := ctx.GetDirectDepWithTag(moduleName, sourceOrOutputDepTag(tag))
660 if module == nil {
661 return nil, missingDependencyError{[]string{moduleName}}
662 }
Colin Crossfa65cee2021-03-22 17:05:59 -0700663 if aModule, ok := module.(Module); ok && !aModule.Enabled() {
664 return nil, missingDependencyError{[]string{moduleName}}
665 }
Liz Kammera830f3a2020-11-10 10:50:34 -0800666 if outProducer, ok := module.(OutputFileProducer); ok {
667 outputFiles, err := outProducer.OutputFiles(tag)
668 if err != nil {
669 return nil, fmt.Errorf("path dependency %q: %s", path, err)
670 }
671 return outputFiles, nil
672 } else if tag != "" {
673 return nil, fmt.Errorf("path dependency %q is not an output file producing module", path)
674 } else if srcProducer, ok := module.(SourceFileProducer); ok {
675 return srcProducer.Srcs(), nil
676 } else {
677 return nil, fmt.Errorf("path dependency %q is not a source file producing module", path)
678 }
679}
680
Colin Crossba71a3f2019-03-18 12:12:48 -0700681// PathsAndMissingDepsForModuleSrcExcludes returns Paths rooted from the module's local source directory, excluding
Colin Cross41955e82019-05-29 14:40:35 -0700682// paths listed in the excludes arguments, and a list of missing dependencies. It expands globs, references to
683// SourceFileProducer modules using the ":name" syntax, and references to OutputFileProducer modules using the
684// ":name{.tag}" syntax. Properties passed as the paths or excludes argument must have been annotated with struct tag
685// `android:"path"` so that dependencies on SourceFileProducer modules will have already been handled by the
686// path_properties mutator. If ctx.Config().AllowMissingDependencies() is true then any missing SourceFileProducer or
687// OutputFileProducer dependencies will be returned, and they will NOT cause the module to be marked as having missing
688// dependencies.
Liz Kammera830f3a2020-11-10 10:50:34 -0800689func PathsAndMissingDepsForModuleSrcExcludes(ctx ModuleWithDepsPathContext, paths, excludes []string) (Paths, []string) {
Colin Cross8a497952019-03-05 22:25:09 -0800690 prefix := pathForModuleSrc(ctx).String()
691
692 var expandedExcludes []string
693 if excludes != nil {
694 expandedExcludes = make([]string, 0, len(excludes))
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700695 }
Colin Cross8a497952019-03-05 22:25:09 -0800696
Colin Crossba71a3f2019-03-18 12:12:48 -0700697 var missingExcludeDeps []string
698
Colin Cross8a497952019-03-05 22:25:09 -0800699 for _, e := range excludes {
Colin Cross41955e82019-05-29 14:40:35 -0700700 if m, t := SrcIsModuleWithTag(e); m != "" {
Liz Kammera830f3a2020-11-10 10:50:34 -0800701 modulePaths, err := getPathsFromModuleDep(ctx, e, m, t)
702 if m, ok := err.(missingDependencyError); ok {
703 missingExcludeDeps = append(missingExcludeDeps, m.missingDeps...)
704 } else if err != nil {
705 reportPathError(ctx, err)
Colin Cross8a497952019-03-05 22:25:09 -0800706 } else {
Liz Kammera830f3a2020-11-10 10:50:34 -0800707 expandedExcludes = append(expandedExcludes, modulePaths.Strings()...)
Colin Cross8a497952019-03-05 22:25:09 -0800708 }
709 } else {
710 expandedExcludes = append(expandedExcludes, filepath.Join(prefix, e))
711 }
712 }
713
714 if paths == nil {
Colin Crossba71a3f2019-03-18 12:12:48 -0700715 return nil, missingExcludeDeps
Colin Cross8a497952019-03-05 22:25:09 -0800716 }
717
Colin Crossba71a3f2019-03-18 12:12:48 -0700718 var missingDeps []string
719
Colin Cross8a497952019-03-05 22:25:09 -0800720 expandedSrcFiles := make(Paths, 0, len(paths))
721 for _, s := range paths {
722 srcFiles, err := expandOneSrcPath(ctx, s, expandedExcludes)
723 if depErr, ok := err.(missingDependencyError); ok {
Colin Crossba71a3f2019-03-18 12:12:48 -0700724 missingDeps = append(missingDeps, depErr.missingDeps...)
Colin Cross8a497952019-03-05 22:25:09 -0800725 } else if err != nil {
726 reportPathError(ctx, err)
727 }
728 expandedSrcFiles = append(expandedSrcFiles, srcFiles...)
729 }
Colin Crossba71a3f2019-03-18 12:12:48 -0700730
731 return expandedSrcFiles, append(missingDeps, missingExcludeDeps...)
Colin Cross8a497952019-03-05 22:25:09 -0800732}
733
734type missingDependencyError struct {
735 missingDeps []string
736}
737
738func (e missingDependencyError) Error() string {
739 return "missing dependencies: " + strings.Join(e.missingDeps, ", ")
740}
741
Liz Kammera830f3a2020-11-10 10:50:34 -0800742// Expands one path string to Paths rooted from the module's local source
743// directory, excluding those listed in the expandedExcludes.
744// Expands globs, references to SourceFileProducer or OutputFileProducer modules using the ":name" and ":name{.tag}" syntax.
745func expandOneSrcPath(ctx ModuleWithDepsPathContext, sPath string, expandedExcludes []string) (Paths, error) {
Jooyung Han7607dd32020-07-05 10:23:14 +0900746 excludePaths := func(paths Paths) Paths {
747 if len(expandedExcludes) == 0 {
748 return paths
749 }
750 remainder := make(Paths, 0, len(paths))
751 for _, p := range paths {
752 if !InList(p.String(), expandedExcludes) {
753 remainder = append(remainder, p)
754 }
755 }
756 return remainder
757 }
Liz Kammera830f3a2020-11-10 10:50:34 -0800758 if m, t := SrcIsModuleWithTag(sPath); m != "" {
759 modulePaths, err := getPathsFromModuleDep(ctx, sPath, m, t)
760 if err != nil {
761 return nil, err
Colin Cross8a497952019-03-05 22:25:09 -0800762 } else {
Liz Kammera830f3a2020-11-10 10:50:34 -0800763 return excludePaths(modulePaths), nil
Colin Cross8a497952019-03-05 22:25:09 -0800764 }
Liz Kammera830f3a2020-11-10 10:50:34 -0800765 } else if pathtools.IsGlob(sPath) {
766 paths := GlobFiles(ctx, pathForModuleSrc(ctx, sPath).String(), expandedExcludes)
Colin Cross8a497952019-03-05 22:25:09 -0800767 return PathsWithModuleSrcSubDir(ctx, paths, ""), nil
768 } else {
Liz Kammera830f3a2020-11-10 10:50:34 -0800769 p := pathForModuleSrc(ctx, sPath)
Colin Cross988414c2020-01-11 01:11:46 +0000770 if exists, _, err := ctx.Config().fs.Exists(p.String()); err != nil {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +0100771 ReportPathErrorf(ctx, "%s: %s", p, err.Error())
Pedro Loureiro5d190cc2021-02-15 15:41:33 +0000772 } else if !exists && !ctx.Config().TestAllowNonExistentPaths {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +0100773 ReportPathErrorf(ctx, "module source path %q does not exist", p)
Colin Cross8a497952019-03-05 22:25:09 -0800774 }
775
Jooyung Han7607dd32020-07-05 10:23:14 +0900776 if InList(p.String(), expandedExcludes) {
Colin Cross8a497952019-03-05 22:25:09 -0800777 return nil, nil
778 }
779 return Paths{p}, nil
780 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700781}
782
783// pathsForModuleSrcFromFullPath returns Paths rooted from the module's local
784// source directory, but strip the local source directory from the beginning of
Dan Willemsen540a78c2018-02-26 21:50:08 -0800785// each string. If incDirs is false, strip paths with a trailing '/' from the list.
Colin Crossfe4bc362018-09-12 10:02:13 -0700786// It intended for use in globs that only list files that exist, so it allows '$' in
787// filenames.
Liz Kammera830f3a2020-11-10 10:50:34 -0800788func pathsForModuleSrcFromFullPath(ctx EarlyModulePathContext, paths []string, incDirs bool) Paths {
Colin Cross6510f912017-11-29 00:27:14 -0800789 prefix := filepath.Join(ctx.Config().srcDir, ctx.ModuleDir()) + "/"
Colin Cross0f37af02017-09-27 17:42:05 -0700790 if prefix == "./" {
791 prefix = ""
792 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700793 ret := make(Paths, 0, len(paths))
794 for _, p := range paths {
Dan Willemsen540a78c2018-02-26 21:50:08 -0800795 if !incDirs && strings.HasSuffix(p, "/") {
796 continue
797 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700798 path := filepath.Clean(p)
799 if !strings.HasPrefix(path, prefix) {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +0100800 ReportPathErrorf(ctx, "Path %q is not in module source directory %q", p, prefix)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700801 continue
802 }
Colin Crosse3924e12018-08-15 20:18:53 -0700803
Colin Crossfe4bc362018-09-12 10:02:13 -0700804 srcPath, err := safePathForSource(ctx, ctx.ModuleDir(), path[len(prefix):])
Colin Crosse3924e12018-08-15 20:18:53 -0700805 if err != nil {
806 reportPathError(ctx, err)
807 continue
808 }
809
Colin Cross07e51612019-03-05 12:46:40 -0800810 srcPath.basePath.rel = srcPath.path
Colin Crosse3924e12018-08-15 20:18:53 -0700811
Colin Cross07e51612019-03-05 12:46:40 -0800812 ret = append(ret, srcPath)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700813 }
814 return ret
815}
816
Liz Kammera830f3a2020-11-10 10:50:34 -0800817// PathsWithOptionalDefaultForModuleSrc returns Paths rooted from the module's local source
818// directory. If input is nil, use the default if it exists. If input is empty, returns nil.
819func PathsWithOptionalDefaultForModuleSrc(ctx ModuleMissingDepsPathContext, input []string, def string) Paths {
Colin Cross0ddae7f2019-02-07 15:30:01 -0800820 if input != nil {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700821 return PathsForModuleSrc(ctx, input)
822 }
823 // Use Glob so that if the default doesn't exist, a dependency is added so that when it
824 // is created, we're run again.
Colin Cross6510f912017-11-29 00:27:14 -0800825 path := filepath.Join(ctx.Config().srcDir, ctx.ModuleDir(), def)
Liz Kammera830f3a2020-11-10 10:50:34 -0800826 return Glob(ctx, path, nil)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700827}
828
829// Strings returns the Paths in string form
830func (p Paths) Strings() []string {
831 if p == nil {
832 return nil
833 }
834 ret := make([]string, len(p))
835 for i, path := range p {
836 ret[i] = path.String()
837 }
838 return ret
839}
840
Colin Crossc0efd1d2020-07-03 11:56:24 -0700841func CopyOfPaths(paths Paths) Paths {
842 return append(Paths(nil), paths...)
843}
844
Colin Crossb6715442017-10-24 11:13:31 -0700845// FirstUniquePaths returns all unique elements of a Paths, keeping the first copy of each. It
846// modifies the Paths slice contents in place, and returns a subslice of the original slice.
Dan Willemsenfe92c962017-08-29 12:28:37 -0700847func FirstUniquePaths(list Paths) Paths {
Colin Cross27027c72020-02-28 15:34:17 -0800848 // 128 was chosen based on BenchmarkFirstUniquePaths results.
849 if len(list) > 128 {
850 return firstUniquePathsMap(list)
851 }
852 return firstUniquePathsList(list)
853}
854
Colin Crossc0efd1d2020-07-03 11:56:24 -0700855// SortedUniquePaths returns all unique elements of a Paths in sorted order. It modifies the
856// Paths slice contents in place, and returns a subslice of the original slice.
Jiyong Park33c77362020-05-29 22:00:16 +0900857func SortedUniquePaths(list Paths) Paths {
858 unique := FirstUniquePaths(list)
859 sort.Slice(unique, func(i, j int) bool {
860 return unique[i].String() < unique[j].String()
861 })
862 return unique
863}
864
Colin Cross27027c72020-02-28 15:34:17 -0800865func firstUniquePathsList(list Paths) Paths {
Dan Willemsenfe92c962017-08-29 12:28:37 -0700866 k := 0
867outer:
868 for i := 0; i < len(list); i++ {
869 for j := 0; j < k; j++ {
870 if list[i] == list[j] {
871 continue outer
872 }
873 }
874 list[k] = list[i]
875 k++
876 }
877 return list[:k]
878}
879
Colin Cross27027c72020-02-28 15:34:17 -0800880func firstUniquePathsMap(list Paths) Paths {
881 k := 0
882 seen := make(map[Path]bool, len(list))
883 for i := 0; i < len(list); i++ {
884 if seen[list[i]] {
885 continue
886 }
887 seen[list[i]] = true
888 list[k] = list[i]
889 k++
890 }
891 return list[:k]
892}
893
Colin Cross5d583952020-11-24 16:21:24 -0800894// FirstUniqueInstallPaths returns all unique elements of an InstallPaths, keeping the first copy of each. It
895// modifies the InstallPaths slice contents in place, and returns a subslice of the original slice.
896func FirstUniqueInstallPaths(list InstallPaths) InstallPaths {
897 // 128 was chosen based on BenchmarkFirstUniquePaths results.
898 if len(list) > 128 {
899 return firstUniqueInstallPathsMap(list)
900 }
901 return firstUniqueInstallPathsList(list)
902}
903
904func firstUniqueInstallPathsList(list InstallPaths) InstallPaths {
905 k := 0
906outer:
907 for i := 0; i < len(list); i++ {
908 for j := 0; j < k; j++ {
909 if list[i] == list[j] {
910 continue outer
911 }
912 }
913 list[k] = list[i]
914 k++
915 }
916 return list[:k]
917}
918
919func firstUniqueInstallPathsMap(list InstallPaths) InstallPaths {
920 k := 0
921 seen := make(map[InstallPath]bool, len(list))
922 for i := 0; i < len(list); i++ {
923 if seen[list[i]] {
924 continue
925 }
926 seen[list[i]] = true
927 list[k] = list[i]
928 k++
929 }
930 return list[:k]
931}
932
Colin Crossb6715442017-10-24 11:13:31 -0700933// LastUniquePaths returns all unique elements of a Paths, keeping the last copy of each. It
934// modifies the Paths slice contents in place, and returns a subslice of the original slice.
935func LastUniquePaths(list Paths) Paths {
936 totalSkip := 0
937 for i := len(list) - 1; i >= totalSkip; i-- {
938 skip := 0
939 for j := i - 1; j >= totalSkip; j-- {
940 if list[i] == list[j] {
941 skip++
942 } else {
943 list[j+skip] = list[j]
944 }
945 }
946 totalSkip += skip
947 }
948 return list[totalSkip:]
949}
950
Colin Crossa140bb02018-04-17 10:52:26 -0700951// ReversePaths returns a copy of a Paths in reverse order.
952func ReversePaths(list Paths) Paths {
953 if list == nil {
954 return nil
955 }
956 ret := make(Paths, len(list))
957 for i := range list {
958 ret[i] = list[len(list)-1-i]
959 }
960 return ret
961}
962
Jeff Gaston294356f2017-09-27 17:05:30 -0700963func indexPathList(s Path, list []Path) int {
964 for i, l := range list {
965 if l == s {
966 return i
967 }
968 }
969
970 return -1
971}
972
973func inPathList(p Path, list []Path) bool {
974 return indexPathList(p, list) != -1
975}
976
977func FilterPathList(list []Path, filter []Path) (remainder []Path, filtered []Path) {
Paul Duffin57b9e1d2019-12-13 00:03:35 +0000978 return FilterPathListPredicate(list, func(p Path) bool { return inPathList(p, filter) })
979}
980
981func FilterPathListPredicate(list []Path, predicate func(Path) bool) (remainder []Path, filtered []Path) {
Jeff Gaston294356f2017-09-27 17:05:30 -0700982 for _, l := range list {
Paul Duffin57b9e1d2019-12-13 00:03:35 +0000983 if predicate(l) {
Jeff Gaston294356f2017-09-27 17:05:30 -0700984 filtered = append(filtered, l)
985 } else {
986 remainder = append(remainder, l)
987 }
988 }
989
990 return
991}
992
Colin Cross93e85952017-08-15 13:34:18 -0700993// HasExt returns true of any of the paths have extension ext, otherwise false
994func (p Paths) HasExt(ext string) bool {
995 for _, path := range p {
996 if path.Ext() == ext {
997 return true
998 }
999 }
1000
1001 return false
1002}
1003
1004// FilterByExt returns the subset of the paths that have extension ext
1005func (p Paths) FilterByExt(ext string) Paths {
1006 ret := make(Paths, 0, len(p))
1007 for _, path := range p {
1008 if path.Ext() == ext {
1009 ret = append(ret, path)
1010 }
1011 }
1012 return ret
1013}
1014
1015// FilterOutByExt returns the subset of the paths that do not have extension ext
1016func (p Paths) FilterOutByExt(ext string) Paths {
1017 ret := make(Paths, 0, len(p))
1018 for _, path := range p {
1019 if path.Ext() != ext {
1020 ret = append(ret, path)
1021 }
1022 }
1023 return ret
1024}
1025
Colin Cross5e6cfbe2017-11-03 15:20:35 -07001026// DirectorySortedPaths is a slice of paths that are sorted such that all files in a directory
1027// (including subdirectories) are in a contiguous subslice of the list, and can be found in
1028// O(log(N)) time using a binary search on the directory prefix.
1029type DirectorySortedPaths Paths
1030
1031func PathsToDirectorySortedPaths(paths Paths) DirectorySortedPaths {
1032 ret := append(DirectorySortedPaths(nil), paths...)
1033 sort.Slice(ret, func(i, j int) bool {
1034 return ret[i].String() < ret[j].String()
1035 })
1036 return ret
1037}
1038
1039// PathsInDirectory returns a subslice of the DirectorySortedPaths as a Paths that contains all entries
1040// that are in the specified directory and its subdirectories.
1041func (p DirectorySortedPaths) PathsInDirectory(dir string) Paths {
1042 prefix := filepath.Clean(dir) + "/"
1043 start := sort.Search(len(p), func(i int) bool {
1044 return prefix < p[i].String()
1045 })
1046
1047 ret := p[start:]
1048
1049 end := sort.Search(len(ret), func(i int) bool {
1050 return !strings.HasPrefix(ret[i].String(), prefix)
1051 })
1052
1053 ret = ret[:end]
1054
1055 return Paths(ret)
1056}
1057
Alex Humesky29e3bbe2020-11-20 21:30:13 -05001058// WritablePaths is a slice of WritablePath, used for multiple outputs.
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001059type WritablePaths []WritablePath
1060
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001061// RelativeToTop creates a new WritablePaths containing the result of calling Path.RelativeToTop on
1062// each item in this slice.
1063func (p WritablePaths) RelativeToTop() WritablePaths {
1064 ensureTestOnly()
1065 if p == nil {
1066 return p
1067 }
1068 ret := make(WritablePaths, len(p))
1069 for i, path := range p {
1070 ret[i] = path.RelativeToTop().(WritablePath)
1071 }
1072 return ret
1073}
1074
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001075// Strings returns the string forms of the writable paths.
1076func (p WritablePaths) Strings() []string {
1077 if p == nil {
1078 return nil
1079 }
1080 ret := make([]string, len(p))
1081 for i, path := range p {
1082 ret[i] = path.String()
1083 }
1084 return ret
1085}
1086
Colin Cross3bc7ffa2017-11-22 16:19:37 -08001087// Paths returns the WritablePaths as a Paths
1088func (p WritablePaths) Paths() Paths {
1089 if p == nil {
1090 return nil
1091 }
1092 ret := make(Paths, len(p))
1093 for i, path := range p {
1094 ret[i] = path
1095 }
1096 return ret
1097}
1098
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001099type basePath struct {
Paul Duffin74abc5d2021-03-24 09:24:59 +00001100 path string
1101 rel string
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001102}
1103
1104func (p basePath) Ext() string {
1105 return filepath.Ext(p.path)
1106}
1107
Colin Cross4f6fc9c2016-10-26 10:05:25 -07001108func (p basePath) Base() string {
1109 return filepath.Base(p.path)
1110}
1111
Colin Crossfaeb7aa2017-02-01 14:12:44 -08001112func (p basePath) Rel() string {
1113 if p.rel != "" {
1114 return p.rel
1115 }
1116 return p.path
1117}
1118
Colin Cross0875c522017-11-28 17:34:01 -08001119func (p basePath) String() string {
1120 return p.path
1121}
1122
Colin Cross0db55682017-12-05 15:36:55 -08001123func (p basePath) withRel(rel string) basePath {
1124 p.path = filepath.Join(p.path, rel)
1125 p.rel = rel
1126 return p
1127}
1128
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001129// SourcePath is a Path representing a file path rooted from SrcDir
1130type SourcePath struct {
1131 basePath
Paul Duffin580efc82021-03-24 09:04:03 +00001132
1133 // The sources root, i.e. Config.SrcDir()
1134 srcDir string
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001135}
1136
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001137func (p SourcePath) RelativeToTop() Path {
1138 ensureTestOnly()
1139 return p
1140}
1141
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001142var _ Path = SourcePath{}
1143
Colin Cross0db55682017-12-05 15:36:55 -08001144func (p SourcePath) withRel(rel string) SourcePath {
1145 p.basePath = p.basePath.withRel(rel)
1146 return p
1147}
1148
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001149// safePathForSource is for paths that we expect are safe -- only for use by go
1150// code that is embedding ninja variables in paths
Colin Crossfe4bc362018-09-12 10:02:13 -07001151func safePathForSource(ctx PathContext, pathComponents ...string) (SourcePath, error) {
1152 p, err := validateSafePath(pathComponents...)
Paul Duffin74abc5d2021-03-24 09:24:59 +00001153 ret := SourcePath{basePath{p, ""}, ctx.Config().srcDir}
Colin Crossfe4bc362018-09-12 10:02:13 -07001154 if err != nil {
1155 return ret, err
1156 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001157
Colin Cross7b3dcc32019-01-24 13:14:39 -08001158 // absolute path already checked by validateSafePath
1159 if strings.HasPrefix(ret.String(), ctx.Config().buildDir) {
Mikhail Naganovab1f5182019-02-08 13:17:55 -08001160 return ret, fmt.Errorf("source path %q is in output", ret.String())
Colin Cross6e18ca42015-07-14 18:55:36 -07001161 }
1162
Colin Crossfe4bc362018-09-12 10:02:13 -07001163 return ret, err
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001164}
1165
Colin Cross192e97a2018-02-22 14:21:02 -08001166// pathForSource creates a SourcePath from pathComponents, but does not check that it exists.
1167func pathForSource(ctx PathContext, pathComponents ...string) (SourcePath, error) {
Colin Crossc48c1432018-02-23 07:09:01 +00001168 p, err := validatePath(pathComponents...)
Paul Duffin74abc5d2021-03-24 09:24:59 +00001169 ret := SourcePath{basePath{p, ""}, ctx.Config().srcDir}
Colin Cross94a32102018-02-22 14:21:02 -08001170 if err != nil {
Colin Cross192e97a2018-02-22 14:21:02 -08001171 return ret, err
Colin Cross94a32102018-02-22 14:21:02 -08001172 }
1173
Colin Cross7b3dcc32019-01-24 13:14:39 -08001174 // absolute path already checked by validatePath
1175 if strings.HasPrefix(ret.String(), ctx.Config().buildDir) {
Mikhail Naganovab1f5182019-02-08 13:17:55 -08001176 return ret, fmt.Errorf("source path %q is in output", ret.String())
Colin Crossc48c1432018-02-23 07:09:01 +00001177 }
1178
Colin Cross192e97a2018-02-22 14:21:02 -08001179 return ret, nil
1180}
1181
1182// existsWithDependencies returns true if the path exists, and adds appropriate dependencies to rerun if the
1183// path does not exist.
1184func existsWithDependencies(ctx PathContext, path SourcePath) (exists bool, err error) {
1185 var files []string
1186
1187 if gctx, ok := ctx.(PathGlobContext); ok {
1188 // Use glob to produce proper dependencies, even though we only want
1189 // a single file.
1190 files, err = gctx.GlobWithDeps(path.String(), nil)
1191 } else {
Colin Cross82ea3fb2021-04-05 17:48:26 -07001192 var result pathtools.GlobResult
Colin Cross192e97a2018-02-22 14:21:02 -08001193 // We cannot add build statements in this context, so we fall back to
1194 // AddNinjaFileDeps
Colin Cross82ea3fb2021-04-05 17:48:26 -07001195 result, err = ctx.Config().fs.Glob(path.String(), nil, pathtools.FollowSymlinks)
1196 ctx.AddNinjaFileDeps(result.Deps...)
1197 files = result.Matches
Colin Cross192e97a2018-02-22 14:21:02 -08001198 }
1199
1200 if err != nil {
1201 return false, fmt.Errorf("glob: %s", err.Error())
1202 }
1203
1204 return len(files) > 0, nil
1205}
1206
1207// PathForSource joins the provided path components and validates that the result
1208// neither escapes the source dir nor is in the out dir.
1209// On error, it will return a usable, but invalid SourcePath, and report a ModuleError.
1210func PathForSource(ctx PathContext, pathComponents ...string) SourcePath {
1211 path, err := pathForSource(ctx, pathComponents...)
1212 if err != nil {
1213 reportPathError(ctx, err)
1214 }
1215
Colin Crosse3924e12018-08-15 20:18:53 -07001216 if pathtools.IsGlob(path.String()) {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001217 ReportPathErrorf(ctx, "path may not contain a glob: %s", path.String())
Colin Crosse3924e12018-08-15 20:18:53 -07001218 }
1219
Liz Kammera830f3a2020-11-10 10:50:34 -08001220 if modCtx, ok := ctx.(ModuleMissingDepsPathContext); ok && ctx.Config().AllowMissingDependencies() {
Colin Cross192e97a2018-02-22 14:21:02 -08001221 exists, err := existsWithDependencies(ctx, path)
1222 if err != nil {
1223 reportPathError(ctx, err)
1224 }
1225 if !exists {
1226 modCtx.AddMissingDependencies([]string{path.String()})
1227 }
Colin Cross988414c2020-01-11 01:11:46 +00001228 } else if exists, _, err := ctx.Config().fs.Exists(path.String()); err != nil {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001229 ReportPathErrorf(ctx, "%s: %s", path, err.Error())
Pedro Loureiro5d190cc2021-02-15 15:41:33 +00001230 } else if !exists && !ctx.Config().TestAllowNonExistentPaths {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001231 ReportPathErrorf(ctx, "source path %q does not exist", path)
Colin Cross192e97a2018-02-22 14:21:02 -08001232 }
1233 return path
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001234}
1235
Liz Kammer7aa52882021-02-11 09:16:14 -05001236// ExistentPathForSource returns an OptionalPath with the SourcePath, rooted from SrcDir, *not*
1237// rooted from the module's local source directory, if the path exists, or an empty OptionalPath if
1238// it doesn't exist. Dependencies are added so that the ninja file will be regenerated if the state
1239// of the path changes.
Colin Cross32f38982018-02-22 11:47:25 -08001240func ExistentPathForSource(ctx PathContext, pathComponents ...string) OptionalPath {
Colin Cross192e97a2018-02-22 14:21:02 -08001241 path, err := pathForSource(ctx, pathComponents...)
Colin Cross1ccfcc32018-02-22 13:54:26 -08001242 if err != nil {
1243 reportPathError(ctx, err)
1244 return OptionalPath{}
1245 }
Colin Crossc48c1432018-02-23 07:09:01 +00001246
Colin Crosse3924e12018-08-15 20:18:53 -07001247 if pathtools.IsGlob(path.String()) {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001248 ReportPathErrorf(ctx, "path may not contain a glob: %s", path.String())
Colin Crosse3924e12018-08-15 20:18:53 -07001249 return OptionalPath{}
1250 }
1251
Colin Cross192e97a2018-02-22 14:21:02 -08001252 exists, err := existsWithDependencies(ctx, path)
Colin Crossc48c1432018-02-23 07:09:01 +00001253 if err != nil {
1254 reportPathError(ctx, err)
1255 return OptionalPath{}
1256 }
Colin Cross192e97a2018-02-22 14:21:02 -08001257 if !exists {
Colin Crossc48c1432018-02-23 07:09:01 +00001258 return OptionalPath{}
1259 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001260 return OptionalPathForPath(path)
1261}
1262
1263func (p SourcePath) String() string {
Paul Duffin580efc82021-03-24 09:04:03 +00001264 return filepath.Join(p.srcDir, p.path)
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001265}
1266
1267// Join creates a new SourcePath with paths... joined with the current path. The
1268// provided paths... may not use '..' to escape from the current path.
1269func (p SourcePath) Join(ctx PathContext, paths ...string) SourcePath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001270 path, err := validatePath(paths...)
1271 if err != nil {
1272 reportPathError(ctx, err)
1273 }
Colin Cross0db55682017-12-05 15:36:55 -08001274 return p.withRel(path)
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001275}
1276
Colin Cross2fafa3e2019-03-05 12:39:51 -08001277// join is like Join but does less path validation.
1278func (p SourcePath) join(ctx PathContext, paths ...string) SourcePath {
1279 path, err := validateSafePath(paths...)
1280 if err != nil {
1281 reportPathError(ctx, err)
1282 }
1283 return p.withRel(path)
1284}
1285
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001286// OverlayPath returns the overlay for `path' if it exists. This assumes that the
1287// SourcePath is the path to a resource overlay directory.
Liz Kammera830f3a2020-11-10 10:50:34 -08001288func (p SourcePath) OverlayPath(ctx ModuleMissingDepsPathContext, path Path) OptionalPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001289 var relDir string
Colin Cross07e51612019-03-05 12:46:40 -08001290 if srcPath, ok := path.(SourcePath); ok {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001291 relDir = srcPath.path
1292 } else {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001293 ReportPathErrorf(ctx, "Cannot find relative path for %s(%s)", reflect.TypeOf(path).Name(), path)
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001294 return OptionalPath{}
1295 }
Paul Duffin580efc82021-03-24 09:04:03 +00001296 dir := filepath.Join(p.srcDir, p.path, relDir)
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001297 // Use Glob so that we are run again if the directory is added.
Colin Cross7f19f372016-11-01 11:10:25 -07001298 if pathtools.IsGlob(dir) {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001299 ReportPathErrorf(ctx, "Path may not contain a glob: %s", dir)
Dan Willemsen7b310ee2015-12-18 15:11:17 -08001300 }
Colin Cross461b4452018-02-23 09:22:42 -08001301 paths, err := ctx.GlobWithDeps(dir, nil)
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001302 if err != nil {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001303 ReportPathErrorf(ctx, "glob: %s", err.Error())
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001304 return OptionalPath{}
1305 }
1306 if len(paths) == 0 {
1307 return OptionalPath{}
1308 }
Paul Duffin580efc82021-03-24 09:04:03 +00001309 relPath := Rel(ctx, p.srcDir, paths[0])
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001310 return OptionalPathForPath(PathForSource(ctx, relPath))
1311}
1312
Colin Cross70dda7e2019-10-01 22:05:35 -07001313// OutputPath is a Path representing an intermediates file path rooted from the build directory
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001314type OutputPath struct {
1315 basePath
Paul Duffind65c58b2021-03-24 09:22:07 +00001316
1317 // The soong build directory, i.e. Config.BuildDir()
1318 buildDir string
1319
Colin Crossd63c9a72020-01-29 16:52:50 -08001320 fullPath string
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001321}
1322
Colin Cross702e0f82017-10-18 17:27:54 -07001323func (p OutputPath) withRel(rel string) OutputPath {
Colin Cross0db55682017-12-05 15:36:55 -08001324 p.basePath = p.basePath.withRel(rel)
Colin Crossd63c9a72020-01-29 16:52:50 -08001325 p.fullPath = filepath.Join(p.fullPath, rel)
Colin Cross702e0f82017-10-18 17:27:54 -07001326 return p
1327}
1328
Colin Cross3063b782018-08-15 11:19:12 -07001329func (p OutputPath) WithoutRel() OutputPath {
1330 p.basePath.rel = filepath.Base(p.basePath.path)
1331 return p
1332}
1333
Paul Duffind65c58b2021-03-24 09:22:07 +00001334func (p OutputPath) getBuildDir() string {
1335 return p.buildDir
Paul Duffin9b478b02019-12-10 13:41:51 +00001336}
1337
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001338func (p OutputPath) RelativeToTop() Path {
1339 return p.outputPathRelativeToTop()
1340}
1341
1342func (p OutputPath) outputPathRelativeToTop() OutputPath {
1343 p.fullPath = StringPathRelativeToTop(p.buildDir, p.fullPath)
1344 p.buildDir = OutSoongDir
1345 return p
1346}
1347
Paul Duffin0267d492021-02-02 10:05:52 +00001348func (p OutputPath) objPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleObjPath {
1349 return PathForModuleObj(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
1350}
1351
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001352var _ Path = OutputPath{}
Paul Duffin9b478b02019-12-10 13:41:51 +00001353var _ WritablePath = OutputPath{}
Paul Duffin0267d492021-02-02 10:05:52 +00001354var _ objPathProvider = OutputPath{}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001355
Chris Parsons8f232a22020-06-23 17:37:05 -04001356// toolDepPath is a Path representing a dependency of the build tool.
1357type toolDepPath struct {
1358 basePath
1359}
1360
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001361func (t toolDepPath) RelativeToTop() Path {
1362 ensureTestOnly()
1363 return t
1364}
1365
Chris Parsons8f232a22020-06-23 17:37:05 -04001366var _ Path = toolDepPath{}
1367
1368// pathForBuildToolDep returns a toolDepPath representing the given path string.
1369// There is no validation for the path, as it is "trusted": It may fail
1370// normal validation checks. For example, it may be an absolute path.
1371// Only use this function to construct paths for dependencies of the build
1372// tool invocation.
1373func pathForBuildToolDep(ctx PathContext, path string) toolDepPath {
Paul Duffin74abc5d2021-03-24 09:24:59 +00001374 return toolDepPath{basePath{path, ""}}
Chris Parsons8f232a22020-06-23 17:37:05 -04001375}
1376
Jeff Gaston734e3802017-04-10 15:47:24 -07001377// PathForOutput joins the provided paths and returns an OutputPath that is
1378// validated to not escape the build dir.
1379// On error, it will return a usable, but invalid OutputPath, and report a ModuleError.
1380func PathForOutput(ctx PathContext, pathComponents ...string) OutputPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001381 path, err := validatePath(pathComponents...)
1382 if err != nil {
1383 reportPathError(ctx, err)
1384 }
Colin Crossd63c9a72020-01-29 16:52:50 -08001385 fullPath := filepath.Join(ctx.Config().buildDir, path)
1386 path = fullPath[len(fullPath)-len(path):]
Paul Duffin74abc5d2021-03-24 09:24:59 +00001387 return OutputPath{basePath{path, ""}, ctx.Config().buildDir, fullPath}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001388}
1389
Colin Cross40e33732019-02-15 11:08:35 -08001390// PathsForOutput returns Paths rooted from buildDir
1391func PathsForOutput(ctx PathContext, paths []string) WritablePaths {
1392 ret := make(WritablePaths, len(paths))
1393 for i, path := range paths {
1394 ret[i] = PathForOutput(ctx, path)
1395 }
1396 return ret
1397}
1398
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001399func (p OutputPath) writablePath() {}
1400
1401func (p OutputPath) String() string {
Colin Crossd63c9a72020-01-29 16:52:50 -08001402 return p.fullPath
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001403}
1404
1405// Join creates a new OutputPath with paths... joined with the current path. The
1406// provided paths... may not use '..' to escape from the current path.
1407func (p OutputPath) Join(ctx PathContext, paths ...string) OutputPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001408 path, err := validatePath(paths...)
1409 if err != nil {
1410 reportPathError(ctx, err)
1411 }
Colin Cross0db55682017-12-05 15:36:55 -08001412 return p.withRel(path)
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001413}
1414
Colin Cross8854a5a2019-02-11 14:14:16 -08001415// ReplaceExtension creates a new OutputPath with the extension replaced with ext.
1416func (p OutputPath) ReplaceExtension(ctx PathContext, ext string) OutputPath {
1417 if strings.Contains(ext, "/") {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001418 ReportPathErrorf(ctx, "extension %q cannot contain /", ext)
Colin Cross8854a5a2019-02-11 14:14:16 -08001419 }
1420 ret := PathForOutput(ctx, pathtools.ReplaceExtension(p.path, ext))
Colin Cross2cdd5df2019-02-25 10:25:24 -08001421 ret.rel = pathtools.ReplaceExtension(p.rel, ext)
Colin Cross8854a5a2019-02-11 14:14:16 -08001422 return ret
1423}
1424
Colin Cross40e33732019-02-15 11:08:35 -08001425// InSameDir creates a new OutputPath from the directory of the current OutputPath joined with the elements in paths.
1426func (p OutputPath) InSameDir(ctx PathContext, paths ...string) OutputPath {
1427 path, err := validatePath(paths...)
1428 if err != nil {
1429 reportPathError(ctx, err)
1430 }
1431
1432 ret := PathForOutput(ctx, filepath.Dir(p.path), path)
Colin Cross2cdd5df2019-02-25 10:25:24 -08001433 ret.rel = filepath.Join(filepath.Dir(p.rel), path)
Colin Cross40e33732019-02-15 11:08:35 -08001434 return ret
1435}
1436
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001437// PathForIntermediates returns an OutputPath representing the top-level
1438// intermediates directory.
1439func PathForIntermediates(ctx PathContext, paths ...string) OutputPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001440 path, err := validatePath(paths...)
1441 if err != nil {
1442 reportPathError(ctx, err)
1443 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001444 return PathForOutput(ctx, ".intermediates", path)
1445}
1446
Colin Cross07e51612019-03-05 12:46:40 -08001447var _ genPathProvider = SourcePath{}
1448var _ objPathProvider = SourcePath{}
1449var _ resPathProvider = SourcePath{}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001450
Colin Cross07e51612019-03-05 12:46:40 -08001451// PathForModuleSrc returns a Path representing the paths... under the
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001452// module's local source directory.
Liz Kammera830f3a2020-11-10 10:50:34 -08001453func PathForModuleSrc(ctx ModuleMissingDepsPathContext, pathComponents ...string) Path {
Colin Cross8a497952019-03-05 22:25:09 -08001454 p, err := validatePath(pathComponents...)
1455 if err != nil {
1456 reportPathError(ctx, err)
Colin Cross192e97a2018-02-22 14:21:02 -08001457 }
Colin Cross8a497952019-03-05 22:25:09 -08001458 paths, err := expandOneSrcPath(ctx, p, nil)
1459 if err != nil {
1460 if depErr, ok := err.(missingDependencyError); ok {
1461 if ctx.Config().AllowMissingDependencies() {
1462 ctx.AddMissingDependencies(depErr.missingDeps)
1463 } else {
1464 ctx.ModuleErrorf(`%s, is the property annotated with android:"path"?`, depErr.Error())
1465 }
1466 } else {
1467 reportPathError(ctx, err)
1468 }
1469 return nil
1470 } else if len(paths) == 0 {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001471 ReportPathErrorf(ctx, "%q produced no files, expected exactly one", p)
Colin Cross8a497952019-03-05 22:25:09 -08001472 return nil
1473 } else if len(paths) > 1 {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001474 ReportPathErrorf(ctx, "%q produced %d files, expected exactly one", p, len(paths))
Colin Cross8a497952019-03-05 22:25:09 -08001475 }
1476 return paths[0]
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001477}
1478
Liz Kammera830f3a2020-11-10 10:50:34 -08001479func pathForModuleSrc(ctx EarlyModulePathContext, paths ...string) SourcePath {
Colin Cross07e51612019-03-05 12:46:40 -08001480 p, err := validatePath(paths...)
1481 if err != nil {
1482 reportPathError(ctx, err)
1483 }
1484
1485 path, err := pathForSource(ctx, ctx.ModuleDir(), p)
1486 if err != nil {
1487 reportPathError(ctx, err)
1488 }
1489
1490 path.basePath.rel = p
1491
1492 return path
1493}
1494
Colin Cross2fafa3e2019-03-05 12:39:51 -08001495// PathsWithModuleSrcSubDir takes a list of Paths and returns a new list of Paths where Rel() on each path
1496// will return the path relative to subDir in the module's source directory. If any input paths are not located
1497// inside subDir then a path error will be reported.
Liz Kammera830f3a2020-11-10 10:50:34 -08001498func PathsWithModuleSrcSubDir(ctx EarlyModulePathContext, paths Paths, subDir string) Paths {
Colin Cross2fafa3e2019-03-05 12:39:51 -08001499 paths = append(Paths(nil), paths...)
Colin Cross07e51612019-03-05 12:46:40 -08001500 subDirFullPath := pathForModuleSrc(ctx, subDir)
Colin Cross2fafa3e2019-03-05 12:39:51 -08001501 for i, path := range paths {
1502 rel := Rel(ctx, subDirFullPath.String(), path.String())
1503 paths[i] = subDirFullPath.join(ctx, rel)
1504 }
1505 return paths
1506}
1507
1508// PathWithModuleSrcSubDir takes a Path and returns a Path where Rel() will return the path relative to subDir in the
1509// 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 -08001510func PathWithModuleSrcSubDir(ctx EarlyModulePathContext, path Path, subDir string) Path {
Colin Cross07e51612019-03-05 12:46:40 -08001511 subDirFullPath := pathForModuleSrc(ctx, subDir)
Colin Cross2fafa3e2019-03-05 12:39:51 -08001512 rel := Rel(ctx, subDirFullPath.String(), path.String())
1513 return subDirFullPath.Join(ctx, rel)
1514}
1515
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001516// OptionalPathForModuleSrc returns an OptionalPath. The OptionalPath contains a
1517// valid path if p is non-nil.
Liz Kammera830f3a2020-11-10 10:50:34 -08001518func OptionalPathForModuleSrc(ctx ModuleMissingDepsPathContext, p *string) OptionalPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001519 if p == nil {
1520 return OptionalPath{}
1521 }
1522 return OptionalPathForPath(PathForModuleSrc(ctx, *p))
1523}
1524
Liz Kammera830f3a2020-11-10 10:50:34 -08001525func (p SourcePath) genPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleGenPath {
Colin Cross7fc17db2017-02-01 14:07:55 -08001526 return PathForModuleGen(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001527}
1528
Liz Kammera830f3a2020-11-10 10:50:34 -08001529func (p SourcePath) objPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleObjPath {
Colin Cross7fc17db2017-02-01 14:07:55 -08001530 return PathForModuleObj(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001531}
1532
Liz Kammera830f3a2020-11-10 10:50:34 -08001533func (p SourcePath) resPathWithName(ctx ModuleOutPathContext, name string) ModuleResPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001534 // TODO: Use full directory if the new ctx is not the current ctx?
1535 return PathForModuleRes(ctx, p.path, name)
1536}
1537
1538// ModuleOutPath is a Path representing a module's output directory.
1539type ModuleOutPath struct {
1540 OutputPath
1541}
1542
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001543func (p ModuleOutPath) RelativeToTop() Path {
1544 p.OutputPath = p.outputPathRelativeToTop()
1545 return p
1546}
1547
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001548var _ Path = ModuleOutPath{}
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001549var _ WritablePath = ModuleOutPath{}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001550
Liz Kammera830f3a2020-11-10 10:50:34 -08001551func (p ModuleOutPath) objPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleObjPath {
Pete Bentleyfcf55bf2019-08-16 20:14:32 +01001552 return PathForModuleObj(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
1553}
1554
Liz Kammera830f3a2020-11-10 10:50:34 -08001555// ModuleOutPathContext Subset of ModuleContext functions necessary for output path methods.
1556type ModuleOutPathContext interface {
1557 PathContext
1558
1559 ModuleName() string
1560 ModuleDir() string
1561 ModuleSubDir() string
1562}
1563
1564func pathForModuleOut(ctx ModuleOutPathContext) OutputPath {
Colin Cross702e0f82017-10-18 17:27:54 -07001565 return PathForOutput(ctx, ".intermediates", ctx.ModuleDir(), ctx.ModuleName(), ctx.ModuleSubDir())
1566}
1567
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001568type BazelOutPath struct {
1569 OutputPath
1570}
1571
1572var _ Path = BazelOutPath{}
1573var _ objPathProvider = BazelOutPath{}
1574
Liz Kammera830f3a2020-11-10 10:50:34 -08001575func (p BazelOutPath) objPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleObjPath {
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001576 return PathForModuleObj(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
1577}
1578
Logan Chien7eefdc42018-07-11 18:10:41 +08001579// PathForVndkRefAbiDump returns an OptionalPath representing the path of the
1580// reference abi dump for the given module. This is not guaranteed to be valid.
Liz Kammera830f3a2020-11-10 10:50:34 -08001581func PathForVndkRefAbiDump(ctx ModuleInstallPathContext, version, fileName string,
Hsin-Yi Chen53489642019-07-31 17:10:45 +08001582 isNdk, isLlndkOrVndk, isGzip bool) OptionalPath {
Logan Chien7eefdc42018-07-11 18:10:41 +08001583
Jayant Chowdharyac066c62018-02-20 10:53:31 -08001584 arches := ctx.DeviceConfig().Arches()
Logan Chien7eefdc42018-07-11 18:10:41 +08001585 if len(arches) == 0 {
1586 panic("device build with no primary arch")
1587 }
Jayant Chowdharyac066c62018-02-20 10:53:31 -08001588 currentArch := ctx.Arch()
1589 archNameAndVariant := currentArch.ArchType.String()
1590 if currentArch.ArchVariant != "" {
1591 archNameAndVariant += "_" + currentArch.ArchVariant
1592 }
Logan Chien5237bed2018-07-11 17:15:57 +08001593
1594 var dirName string
Hsin-Yi Chen53489642019-07-31 17:10:45 +08001595 if isNdk {
Logan Chien5237bed2018-07-11 17:15:57 +08001596 dirName = "ndk"
Hsin-Yi Chen53489642019-07-31 17:10:45 +08001597 } else if isLlndkOrVndk {
Logan Chien5237bed2018-07-11 17:15:57 +08001598 dirName = "vndk"
Logan Chien41eabe62019-04-10 13:33:58 +08001599 } else {
1600 dirName = "platform" // opt-in libs
Jayant Chowdhary3e231fd2017-02-08 13:45:53 -08001601 }
Logan Chien5237bed2018-07-11 17:15:57 +08001602
Jayant Chowdhary34ce67d2018-03-08 11:00:50 -08001603 binderBitness := ctx.DeviceConfig().BinderBitness()
Logan Chien7eefdc42018-07-11 18:10:41 +08001604
1605 var ext string
1606 if isGzip {
1607 ext = ".lsdump.gz"
1608 } else {
1609 ext = ".lsdump"
1610 }
1611
1612 return ExistentPathForSource(ctx, "prebuilts", "abi-dumps", dirName,
1613 version, binderBitness, archNameAndVariant, "source-based",
1614 fileName+ext)
Jayant Chowdhary3e231fd2017-02-08 13:45:53 -08001615}
1616
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001617// PathForBazelOut returns a Path representing the paths... under an output directory dedicated to
1618// bazel-owned outputs.
1619func PathForBazelOut(ctx PathContext, paths ...string) BazelOutPath {
1620 execRootPathComponents := append([]string{"execroot", "__main__"}, paths...)
1621 execRootPath := filepath.Join(execRootPathComponents...)
1622 validatedExecRootPath, err := validatePath(execRootPath)
1623 if err != nil {
1624 reportPathError(ctx, err)
1625 }
1626
Paul Duffin74abc5d2021-03-24 09:24:59 +00001627 outputPath := OutputPath{basePath{"", ""},
Paul Duffind65c58b2021-03-24 09:22:07 +00001628 ctx.Config().buildDir,
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001629 ctx.Config().BazelContext.OutputBase()}
1630
1631 return BazelOutPath{
1632 OutputPath: outputPath.withRel(validatedExecRootPath),
1633 }
1634}
1635
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001636// PathForModuleOut returns a Path representing the paths... under the module's
1637// output directory.
Liz Kammera830f3a2020-11-10 10:50:34 -08001638func PathForModuleOut(ctx ModuleOutPathContext, paths ...string) ModuleOutPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001639 p, err := validatePath(paths...)
1640 if err != nil {
1641 reportPathError(ctx, err)
1642 }
Colin Cross702e0f82017-10-18 17:27:54 -07001643 return ModuleOutPath{
Liz Kammera830f3a2020-11-10 10:50:34 -08001644 OutputPath: pathForModuleOut(ctx).withRel(p),
Colin Cross702e0f82017-10-18 17:27:54 -07001645 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001646}
1647
1648// ModuleGenPath is a Path representing the 'gen' directory in a module's output
1649// directory. Mainly used for generated sources.
1650type ModuleGenPath struct {
1651 ModuleOutPath
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001652}
1653
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001654func (p ModuleGenPath) RelativeToTop() Path {
1655 p.OutputPath = p.outputPathRelativeToTop()
1656 return p
1657}
1658
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001659var _ Path = ModuleGenPath{}
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001660var _ WritablePath = ModuleGenPath{}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001661var _ genPathProvider = ModuleGenPath{}
1662var _ objPathProvider = ModuleGenPath{}
1663
1664// PathForModuleGen returns a Path representing the paths... under the module's
1665// `gen' directory.
Liz Kammera830f3a2020-11-10 10:50:34 -08001666func PathForModuleGen(ctx ModuleOutPathContext, paths ...string) ModuleGenPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001667 p, err := validatePath(paths...)
1668 if err != nil {
1669 reportPathError(ctx, err)
1670 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001671 return ModuleGenPath{
Colin Cross702e0f82017-10-18 17:27:54 -07001672 ModuleOutPath: ModuleOutPath{
Liz Kammera830f3a2020-11-10 10:50:34 -08001673 OutputPath: pathForModuleOut(ctx).withRel("gen").withRel(p),
Colin Cross702e0f82017-10-18 17:27:54 -07001674 },
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001675 }
1676}
1677
Liz Kammera830f3a2020-11-10 10:50:34 -08001678func (p ModuleGenPath) genPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleGenPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001679 // TODO: make a different path for local vs remote generated files?
Dan Willemsen21ec4902016-11-02 20:43:13 -07001680 return PathForModuleGen(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001681}
1682
Liz Kammera830f3a2020-11-10 10:50:34 -08001683func (p ModuleGenPath) objPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleObjPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001684 return PathForModuleObj(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
1685}
1686
1687// ModuleObjPath is a Path representing the 'obj' directory in a module's output
1688// directory. Used for compiled objects.
1689type ModuleObjPath struct {
1690 ModuleOutPath
1691}
1692
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001693func (p ModuleObjPath) RelativeToTop() Path {
1694 p.OutputPath = p.outputPathRelativeToTop()
1695 return p
1696}
1697
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001698var _ Path = ModuleObjPath{}
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001699var _ WritablePath = ModuleObjPath{}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001700
1701// PathForModuleObj returns a Path representing the paths... under the module's
1702// 'obj' directory.
Liz Kammera830f3a2020-11-10 10:50:34 -08001703func PathForModuleObj(ctx ModuleOutPathContext, pathComponents ...string) ModuleObjPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001704 p, err := validatePath(pathComponents...)
1705 if err != nil {
1706 reportPathError(ctx, err)
1707 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001708 return ModuleObjPath{PathForModuleOut(ctx, "obj", p)}
1709}
1710
1711// ModuleResPath is a a Path representing the 'res' directory in a module's
1712// output directory.
1713type ModuleResPath struct {
1714 ModuleOutPath
1715}
1716
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001717func (p ModuleResPath) RelativeToTop() Path {
1718 p.OutputPath = p.outputPathRelativeToTop()
1719 return p
1720}
1721
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001722var _ Path = ModuleResPath{}
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001723var _ WritablePath = ModuleResPath{}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001724
1725// PathForModuleRes returns a Path representing the paths... under the module's
1726// 'res' directory.
Liz Kammera830f3a2020-11-10 10:50:34 -08001727func PathForModuleRes(ctx ModuleOutPathContext, pathComponents ...string) ModuleResPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001728 p, err := validatePath(pathComponents...)
1729 if err != nil {
1730 reportPathError(ctx, err)
1731 }
1732
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001733 return ModuleResPath{PathForModuleOut(ctx, "res", p)}
1734}
1735
Colin Cross70dda7e2019-10-01 22:05:35 -07001736// InstallPath is a Path representing a installed file path rooted from the build directory
1737type InstallPath struct {
1738 basePath
Colin Crossff6c33d2019-10-02 16:01:35 -07001739
Paul Duffind65c58b2021-03-24 09:22:07 +00001740 // The soong build directory, i.e. Config.BuildDir()
1741 buildDir string
1742
Jiyong Park957bcd92020-10-20 18:23:33 +09001743 // partitionDir is the part of the InstallPath that is automatically determined according to the context.
1744 // For example, it is host/<os>-<arch> for host modules, and target/product/<device>/<partition> for device modules.
1745 partitionDir string
1746
1747 // makePath indicates whether this path is for Soong (false) or Make (true).
1748 makePath bool
Colin Cross70dda7e2019-10-01 22:05:35 -07001749}
1750
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001751// Will panic if called from outside a test environment.
1752func ensureTestOnly() {
Martin Stjernholm32312eb2021-03-27 18:54:49 +00001753 if PrefixInList(os.Args, "-test.") {
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001754 return
1755 }
Martin Stjernholm32312eb2021-03-27 18:54:49 +00001756 panic(fmt.Errorf("Not in test. Command line:\n %s", strings.Join(os.Args, "\n ")))
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001757}
1758
1759func (p InstallPath) RelativeToTop() Path {
1760 ensureTestOnly()
1761 p.buildDir = OutSoongDir
1762 return p
1763}
1764
Paul Duffind65c58b2021-03-24 09:22:07 +00001765func (p InstallPath) getBuildDir() string {
1766 return p.buildDir
Paul Duffin9b478b02019-12-10 13:41:51 +00001767}
1768
Hans MÃ¥nssond3f2bd72020-11-27 12:37:28 +01001769func (p InstallPath) ReplaceExtension(ctx PathContext, ext string) OutputPath {
1770 panic("Not implemented")
1771}
1772
Paul Duffin9b478b02019-12-10 13:41:51 +00001773var _ Path = InstallPath{}
1774var _ WritablePath = InstallPath{}
1775
Colin Cross70dda7e2019-10-01 22:05:35 -07001776func (p InstallPath) writablePath() {}
1777
1778func (p InstallPath) String() string {
Jiyong Park957bcd92020-10-20 18:23:33 +09001779 if p.makePath {
1780 // Make path starts with out/ instead of out/soong.
Paul Duffind65c58b2021-03-24 09:22:07 +00001781 return filepath.Join(p.buildDir, "../", p.path)
Jiyong Park957bcd92020-10-20 18:23:33 +09001782 } else {
Paul Duffind65c58b2021-03-24 09:22:07 +00001783 return filepath.Join(p.buildDir, p.path)
Jiyong Park957bcd92020-10-20 18:23:33 +09001784 }
1785}
1786
1787// PartitionDir returns the path to the partition where the install path is rooted at. It is
1788// out/soong/target/product/<device>/<partition> for device modules, and out/soong/host/<os>-<arch> for host modules.
1789// The ./soong is dropped if the install path is for Make.
1790func (p InstallPath) PartitionDir() string {
1791 if p.makePath {
Paul Duffind65c58b2021-03-24 09:22:07 +00001792 return filepath.Join(p.buildDir, "../", p.partitionDir)
Jiyong Park957bcd92020-10-20 18:23:33 +09001793 } else {
Paul Duffind65c58b2021-03-24 09:22:07 +00001794 return filepath.Join(p.buildDir, p.partitionDir)
Jiyong Park957bcd92020-10-20 18:23:33 +09001795 }
Colin Cross70dda7e2019-10-01 22:05:35 -07001796}
1797
1798// Join creates a new InstallPath with paths... joined with the current path. The
1799// provided paths... may not use '..' to escape from the current path.
1800func (p InstallPath) Join(ctx PathContext, paths ...string) InstallPath {
1801 path, err := validatePath(paths...)
1802 if err != nil {
1803 reportPathError(ctx, err)
1804 }
1805 return p.withRel(path)
1806}
1807
1808func (p InstallPath) withRel(rel string) InstallPath {
1809 p.basePath = p.basePath.withRel(rel)
1810 return p
1811}
1812
Colin Crossff6c33d2019-10-02 16:01:35 -07001813// ToMakePath returns a new InstallPath that points to Make's install directory instead of Soong's,
1814// i.e. out/ instead of out/soong/.
1815func (p InstallPath) ToMakePath() InstallPath {
Jiyong Park957bcd92020-10-20 18:23:33 +09001816 p.makePath = true
Colin Crossff6c33d2019-10-02 16:01:35 -07001817 return p
Colin Cross70dda7e2019-10-01 22:05:35 -07001818}
1819
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001820// PathForModuleInstall returns a Path representing the install path for the
1821// module appended with paths...
Colin Cross70dda7e2019-10-01 22:05:35 -07001822func PathForModuleInstall(ctx ModuleInstallPathContext, pathComponents ...string) InstallPath {
Colin Cross6e359402020-02-10 15:29:54 -08001823 os := ctx.Os()
Jiyong Park87788b52020-09-01 12:37:45 +09001824 arch := ctx.Arch().ArchType
1825 forceOS, forceArch := ctx.InstallForceOS()
1826 if forceOS != nil {
Colin Cross6e359402020-02-10 15:29:54 -08001827 os = *forceOS
1828 }
Jiyong Park87788b52020-09-01 12:37:45 +09001829 if forceArch != nil {
1830 arch = *forceArch
1831 }
Colin Cross6e359402020-02-10 15:29:54 -08001832 partition := modulePartition(ctx, os)
Colin Cross609c49a2020-02-13 13:20:11 -08001833
Jiyong Park87788b52020-09-01 12:37:45 +09001834 ret := pathForInstall(ctx, os, arch, partition, ctx.Debug(), pathComponents...)
Colin Cross609c49a2020-02-13 13:20:11 -08001835
Jingwen Chencda22c92020-11-23 00:22:30 -05001836 if ctx.InstallBypassMake() && ctx.Config().KatiEnabled() {
Colin Cross609c49a2020-02-13 13:20:11 -08001837 ret = ret.ToMakePath()
1838 }
1839
1840 return ret
1841}
1842
Jiyong Park87788b52020-09-01 12:37:45 +09001843func pathForInstall(ctx PathContext, os OsType, arch ArchType, partition string, debug bool,
Colin Cross609c49a2020-02-13 13:20:11 -08001844 pathComponents ...string) InstallPath {
1845
Jiyong Park957bcd92020-10-20 18:23:33 +09001846 var partionPaths []string
Colin Cross609c49a2020-02-13 13:20:11 -08001847
Colin Cross6e359402020-02-10 15:29:54 -08001848 if os.Class == Device {
Jiyong Park957bcd92020-10-20 18:23:33 +09001849 partionPaths = []string{"target", "product", ctx.Config().DeviceName(), partition}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001850 } else {
Jiyong Park87788b52020-09-01 12:37:45 +09001851 osName := os.String()
1852 if os == Linux {
1853 // instead of linux_glibc
1854 osName = "linux"
Dan Willemsen866b5632017-09-22 12:28:24 -07001855 }
Jiyong Park87788b52020-09-01 12:37:45 +09001856 // SOONG_HOST_OUT is set to out/host/$(HOST_OS)-$(HOST_PREBUILT_ARCH)
1857 // and HOST_PREBUILT_ARCH is forcibly set to x86 even on x86_64 hosts. We don't seem
1858 // to have a plan to fix it (see the comment in build/make/core/envsetup.mk).
1859 // Let's keep using x86 for the existing cases until we have a need to support
1860 // other architectures.
1861 archName := arch.String()
1862 if os.Class == Host && (arch == X86_64 || arch == Common) {
1863 archName = "x86"
1864 }
Jiyong Park957bcd92020-10-20 18:23:33 +09001865 partionPaths = []string{"host", osName + "-" + archName, partition}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001866 }
Colin Cross609c49a2020-02-13 13:20:11 -08001867 if debug {
Jiyong Park957bcd92020-10-20 18:23:33 +09001868 partionPaths = append([]string{"debug"}, partionPaths...)
Dan Willemsen782a2d12015-12-21 14:55:28 -08001869 }
Colin Cross70dda7e2019-10-01 22:05:35 -07001870
Jiyong Park957bcd92020-10-20 18:23:33 +09001871 partionPath, err := validatePath(partionPaths...)
Colin Cross70dda7e2019-10-01 22:05:35 -07001872 if err != nil {
1873 reportPathError(ctx, err)
1874 }
Colin Crossff6c33d2019-10-02 16:01:35 -07001875
Jiyong Park957bcd92020-10-20 18:23:33 +09001876 base := InstallPath{
Paul Duffin74abc5d2021-03-24 09:24:59 +00001877 basePath: basePath{partionPath, ""},
Paul Duffind65c58b2021-03-24 09:22:07 +00001878 buildDir: ctx.Config().buildDir,
Jiyong Park957bcd92020-10-20 18:23:33 +09001879 partitionDir: partionPath,
1880 makePath: false,
1881 }
Colin Crossff6c33d2019-10-02 16:01:35 -07001882
Jiyong Park957bcd92020-10-20 18:23:33 +09001883 return base.Join(ctx, pathComponents...)
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001884}
1885
Nicolas Geoffray1228e9c2020-02-27 13:45:35 +00001886func pathForNdkOrSdkInstall(ctx PathContext, prefix string, paths []string) InstallPath {
Jiyong Park957bcd92020-10-20 18:23:33 +09001887 base := InstallPath{
Paul Duffin74abc5d2021-03-24 09:24:59 +00001888 basePath: basePath{prefix, ""},
Paul Duffind65c58b2021-03-24 09:22:07 +00001889 buildDir: ctx.Config().buildDir,
Jiyong Park957bcd92020-10-20 18:23:33 +09001890 partitionDir: prefix,
1891 makePath: false,
Colin Cross70dda7e2019-10-01 22:05:35 -07001892 }
Jiyong Park957bcd92020-10-20 18:23:33 +09001893 return base.Join(ctx, paths...)
Colin Cross70dda7e2019-10-01 22:05:35 -07001894}
1895
Nicolas Geoffray1228e9c2020-02-27 13:45:35 +00001896func PathForNdkInstall(ctx PathContext, paths ...string) InstallPath {
1897 return pathForNdkOrSdkInstall(ctx, "ndk", paths)
1898}
1899
1900func PathForMainlineSdksInstall(ctx PathContext, paths ...string) InstallPath {
1901 return pathForNdkOrSdkInstall(ctx, "mainline-sdks", paths)
1902}
1903
Colin Cross70dda7e2019-10-01 22:05:35 -07001904func InstallPathToOnDevicePath(ctx PathContext, path InstallPath) string {
Colin Cross43f08db2018-11-12 10:13:39 -08001905 rel := Rel(ctx, PathForOutput(ctx, "target", "product", ctx.Config().DeviceName()).String(), path.String())
1906
1907 return "/" + rel
1908}
1909
Colin Cross6e359402020-02-10 15:29:54 -08001910func modulePartition(ctx ModuleInstallPathContext, os OsType) string {
Colin Cross43f08db2018-11-12 10:13:39 -08001911 var partition string
Colin Cross6e359402020-02-10 15:29:54 -08001912 if ctx.InstallInTestcases() {
1913 // "testcases" install directory can be used for host or device modules.
Jaewoong Jung0949f312019-09-11 10:25:18 -07001914 partition = "testcases"
Colin Cross6e359402020-02-10 15:29:54 -08001915 } else if os.Class == Device {
1916 if ctx.InstallInData() {
1917 partition = "data"
1918 } else if ctx.InstallInRamdisk() {
1919 if ctx.DeviceConfig().BoardUsesRecoveryAsBoot() {
1920 partition = "recovery/root/first_stage_ramdisk"
1921 } else {
1922 partition = "ramdisk"
1923 }
1924 if !ctx.InstallInRoot() {
1925 partition += "/system"
1926 }
Yifan Hong60e0cfb2020-10-21 15:17:56 -07001927 } else if ctx.InstallInVendorRamdisk() {
Yifan Hong39143a92020-10-26 12:43:12 -07001928 // The module is only available after switching root into
1929 // /first_stage_ramdisk. To expose the module before switching root
1930 // on a device without a dedicated recovery partition, install the
1931 // recovery variant.
Yifan Hongdd8dacc2020-10-21 15:40:17 -07001932 if ctx.DeviceConfig().BoardMoveRecoveryResourcesToVendorBoot() {
Petri Gyntherac229562021-03-02 23:44:02 -08001933 partition = "vendor_ramdisk/first_stage_ramdisk"
Yifan Hongdd8dacc2020-10-21 15:40:17 -07001934 } else {
Petri Gyntherac229562021-03-02 23:44:02 -08001935 partition = "vendor_ramdisk"
Yifan Hongdd8dacc2020-10-21 15:40:17 -07001936 }
1937 if !ctx.InstallInRoot() {
1938 partition += "/system"
1939 }
Colin Cross6e359402020-02-10 15:29:54 -08001940 } else if ctx.InstallInRecovery() {
1941 if ctx.InstallInRoot() {
1942 partition = "recovery/root"
1943 } else {
1944 // the layout of recovery partion is the same as that of system partition
1945 partition = "recovery/root/system"
1946 }
1947 } else if ctx.SocSpecific() {
1948 partition = ctx.DeviceConfig().VendorPath()
1949 } else if ctx.DeviceSpecific() {
1950 partition = ctx.DeviceConfig().OdmPath()
1951 } else if ctx.ProductSpecific() {
1952 partition = ctx.DeviceConfig().ProductPath()
1953 } else if ctx.SystemExtSpecific() {
1954 partition = ctx.DeviceConfig().SystemExtPath()
1955 } else if ctx.InstallInRoot() {
1956 partition = "root"
Yifan Hong82db7352020-01-21 16:12:26 -08001957 } else {
Colin Cross6e359402020-02-10 15:29:54 -08001958 partition = "system"
Yifan Hong82db7352020-01-21 16:12:26 -08001959 }
Colin Cross6e359402020-02-10 15:29:54 -08001960 if ctx.InstallInSanitizerDir() {
1961 partition = "data/asan/" + partition
Yifan Hong82db7352020-01-21 16:12:26 -08001962 }
Colin Cross43f08db2018-11-12 10:13:39 -08001963 }
1964 return partition
1965}
1966
Colin Cross609c49a2020-02-13 13:20:11 -08001967type InstallPaths []InstallPath
1968
1969// Paths returns the InstallPaths as a Paths
1970func (p InstallPaths) Paths() Paths {
1971 if p == nil {
1972 return nil
1973 }
1974 ret := make(Paths, len(p))
1975 for i, path := range p {
1976 ret[i] = path
1977 }
1978 return ret
1979}
1980
1981// Strings returns the string forms of the install paths.
1982func (p InstallPaths) Strings() []string {
1983 if p == nil {
1984 return nil
1985 }
1986 ret := make([]string, len(p))
1987 for i, path := range p {
1988 ret[i] = path.String()
1989 }
1990 return ret
1991}
1992
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001993// validateSafePath validates a path that we trust (may contain ninja variables).
Dan Willemsen80a7c2a2015-12-21 14:57:11 -08001994// Ensures that each path component does not attempt to leave its component.
Colin Cross1ccfcc32018-02-22 13:54:26 -08001995func validateSafePath(pathComponents ...string) (string, error) {
Jeff Gaston734e3802017-04-10 15:47:24 -07001996 for _, path := range pathComponents {
Dan Willemsen80a7c2a2015-12-21 14:57:11 -08001997 path := filepath.Clean(path)
1998 if path == ".." || strings.HasPrefix(path, "../") || strings.HasPrefix(path, "/") {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001999 return "", fmt.Errorf("Path is outside directory: %s", path)
Dan Willemsen80a7c2a2015-12-21 14:57:11 -08002000 }
2001 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07002002 // TODO: filepath.Join isn't necessarily correct with embedded ninja
2003 // variables. '..' may remove the entire ninja variable, even if it
2004 // will be expanded to multiple nested directories.
Colin Cross1ccfcc32018-02-22 13:54:26 -08002005 return filepath.Join(pathComponents...), nil
Dan Willemsen34cc69e2015-09-23 15:26:20 -07002006}
2007
Dan Willemsen80a7c2a2015-12-21 14:57:11 -08002008// validatePath validates that a path does not include ninja variables, and that
2009// each path component does not attempt to leave its component. Returns a joined
2010// version of each path component.
Colin Cross1ccfcc32018-02-22 13:54:26 -08002011func validatePath(pathComponents ...string) (string, error) {
Jeff Gaston734e3802017-04-10 15:47:24 -07002012 for _, path := range pathComponents {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07002013 if strings.Contains(path, "$") {
Colin Cross1ccfcc32018-02-22 13:54:26 -08002014 return "", fmt.Errorf("Path contains invalid character($): %s", path)
Dan Willemsen34cc69e2015-09-23 15:26:20 -07002015 }
2016 }
Colin Cross1ccfcc32018-02-22 13:54:26 -08002017 return validateSafePath(pathComponents...)
Colin Cross6e18ca42015-07-14 18:55:36 -07002018}
Colin Cross5b529592017-05-09 13:34:34 -07002019
Colin Cross0875c522017-11-28 17:34:01 -08002020func PathForPhony(ctx PathContext, phony string) WritablePath {
2021 if strings.ContainsAny(phony, "$/") {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01002022 ReportPathErrorf(ctx, "Phony target contains invalid character ($ or /): %s", phony)
Colin Cross0875c522017-11-28 17:34:01 -08002023 }
Paul Duffin74abc5d2021-03-24 09:24:59 +00002024 return PhonyPath{basePath{phony, ""}}
Colin Cross0875c522017-11-28 17:34:01 -08002025}
2026
Colin Cross74e3fe42017-12-11 15:51:44 -08002027type PhonyPath struct {
2028 basePath
2029}
2030
2031func (p PhonyPath) writablePath() {}
2032
Paul Duffind65c58b2021-03-24 09:22:07 +00002033func (p PhonyPath) getBuildDir() string {
2034 // A phone path cannot contain any / so cannot be relative to the build directory.
2035 return ""
Paul Duffin9b478b02019-12-10 13:41:51 +00002036}
2037
Paul Duffin85d8f0d2021-03-24 10:18:18 +00002038func (p PhonyPath) RelativeToTop() Path {
2039 ensureTestOnly()
2040 // A phony path cannot contain any / so does not have a build directory so switching to a new
2041 // build directory has no effect so just return this path.
2042 return p
2043}
2044
Hans MÃ¥nssond3f2bd72020-11-27 12:37:28 +01002045func (p PhonyPath) ReplaceExtension(ctx PathContext, ext string) OutputPath {
2046 panic("Not implemented")
2047}
2048
Colin Cross74e3fe42017-12-11 15:51:44 -08002049var _ Path = PhonyPath{}
2050var _ WritablePath = PhonyPath{}
2051
Colin Cross5b529592017-05-09 13:34:34 -07002052type testPath struct {
2053 basePath
2054}
2055
Paul Duffin85d8f0d2021-03-24 10:18:18 +00002056func (p testPath) RelativeToTop() Path {
2057 ensureTestOnly()
2058 return p
2059}
2060
Colin Cross5b529592017-05-09 13:34:34 -07002061func (p testPath) String() string {
2062 return p.path
2063}
2064
Paul Duffin85d8f0d2021-03-24 10:18:18 +00002065var _ Path = testPath{}
2066
Colin Cross40e33732019-02-15 11:08:35 -08002067// PathForTesting returns a Path constructed from joining the elements of paths with '/'. It should only be used from
2068// within tests.
Colin Cross5b529592017-05-09 13:34:34 -07002069func PathForTesting(paths ...string) Path {
Colin Cross1ccfcc32018-02-22 13:54:26 -08002070 p, err := validateSafePath(paths...)
2071 if err != nil {
2072 panic(err)
2073 }
Colin Cross5b529592017-05-09 13:34:34 -07002074 return testPath{basePath{path: p, rel: p}}
2075}
2076
Colin Cross40e33732019-02-15 11:08:35 -08002077// PathsForTesting returns a Path constructed from each element in strs. It should only be used from within tests.
2078func PathsForTesting(strs ...string) Paths {
Colin Cross5b529592017-05-09 13:34:34 -07002079 p := make(Paths, len(strs))
2080 for i, s := range strs {
2081 p[i] = PathForTesting(s)
2082 }
2083
2084 return p
2085}
Colin Cross43f08db2018-11-12 10:13:39 -08002086
Colin Cross40e33732019-02-15 11:08:35 -08002087type testPathContext struct {
2088 config Config
Colin Cross40e33732019-02-15 11:08:35 -08002089}
2090
Colin Cross40e33732019-02-15 11:08:35 -08002091func (x *testPathContext) Config() Config { return x.config }
2092func (x *testPathContext) AddNinjaFileDeps(...string) {}
2093
2094// PathContextForTesting returns a PathContext that can be used in tests, for example to create an OutputPath with
2095// PathForOutput.
Colin Cross98be1bb2019-12-13 20:41:13 -08002096func PathContextForTesting(config Config) PathContext {
Colin Cross40e33732019-02-15 11:08:35 -08002097 return &testPathContext{
2098 config: config,
Colin Cross40e33732019-02-15 11:08:35 -08002099 }
2100}
2101
Ulya Trafimovichccc8c852020-10-14 11:29:07 +01002102type testModuleInstallPathContext struct {
2103 baseModuleContext
2104
2105 inData bool
2106 inTestcases bool
2107 inSanitizerDir bool
2108 inRamdisk bool
2109 inVendorRamdisk bool
2110 inRecovery bool
2111 inRoot bool
2112 forceOS *OsType
2113 forceArch *ArchType
2114}
2115
2116func (m testModuleInstallPathContext) Config() Config {
2117 return m.baseModuleContext.config
2118}
2119
2120func (testModuleInstallPathContext) AddNinjaFileDeps(deps ...string) {}
2121
2122func (m testModuleInstallPathContext) InstallInData() bool {
2123 return m.inData
2124}
2125
2126func (m testModuleInstallPathContext) InstallInTestcases() bool {
2127 return m.inTestcases
2128}
2129
2130func (m testModuleInstallPathContext) InstallInSanitizerDir() bool {
2131 return m.inSanitizerDir
2132}
2133
2134func (m testModuleInstallPathContext) InstallInRamdisk() bool {
2135 return m.inRamdisk
2136}
2137
2138func (m testModuleInstallPathContext) InstallInVendorRamdisk() bool {
2139 return m.inVendorRamdisk
2140}
2141
2142func (m testModuleInstallPathContext) InstallInRecovery() bool {
2143 return m.inRecovery
2144}
2145
2146func (m testModuleInstallPathContext) InstallInRoot() bool {
2147 return m.inRoot
2148}
2149
2150func (m testModuleInstallPathContext) InstallBypassMake() bool {
2151 return false
2152}
2153
2154func (m testModuleInstallPathContext) InstallForceOS() (*OsType, *ArchType) {
2155 return m.forceOS, m.forceArch
2156}
2157
2158// Construct a minimal ModuleInstallPathContext for testing. Note that baseModuleContext is
2159// default-initialized, which leaves blueprint.baseModuleContext set to nil, so methods that are
2160// delegated to it will panic.
2161func ModuleInstallPathContextForTesting(config Config) ModuleInstallPathContext {
2162 ctx := &testModuleInstallPathContext{}
2163 ctx.config = config
2164 ctx.os = Android
2165 return ctx
2166}
2167
Colin Cross43f08db2018-11-12 10:13:39 -08002168// Rel performs the same function as filepath.Rel, but reports errors to a PathContext, and reports an error if
2169// targetPath is not inside basePath.
2170func Rel(ctx PathContext, basePath string, targetPath string) string {
2171 rel, isRel := MaybeRel(ctx, basePath, targetPath)
2172 if !isRel {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01002173 ReportPathErrorf(ctx, "path %q is not under path %q", targetPath, basePath)
Colin Cross43f08db2018-11-12 10:13:39 -08002174 return ""
2175 }
2176 return rel
2177}
2178
2179// MaybeRel performs the same function as filepath.Rel, but reports errors to a PathContext, and returns false if
2180// targetPath is not inside basePath.
2181func MaybeRel(ctx PathContext, basePath string, targetPath string) (string, bool) {
Dan Willemsen633c5022019-04-12 11:11:38 -07002182 rel, isRel, err := maybeRelErr(basePath, targetPath)
2183 if err != nil {
2184 reportPathError(ctx, err)
2185 }
2186 return rel, isRel
2187}
2188
2189func maybeRelErr(basePath string, targetPath string) (string, bool, error) {
Colin Cross43f08db2018-11-12 10:13:39 -08002190 // filepath.Rel returns an error if one path is absolute and the other is not, handle that case first.
2191 if filepath.IsAbs(basePath) != filepath.IsAbs(targetPath) {
Dan Willemsen633c5022019-04-12 11:11:38 -07002192 return "", false, nil
Colin Cross43f08db2018-11-12 10:13:39 -08002193 }
2194 rel, err := filepath.Rel(basePath, targetPath)
2195 if err != nil {
Dan Willemsen633c5022019-04-12 11:11:38 -07002196 return "", false, err
Colin Cross43f08db2018-11-12 10:13:39 -08002197 } else if rel == ".." || strings.HasPrefix(rel, "../") || strings.HasPrefix(rel, "/") {
Dan Willemsen633c5022019-04-12 11:11:38 -07002198 return "", false, nil
Colin Cross43f08db2018-11-12 10:13:39 -08002199 }
Dan Willemsen633c5022019-04-12 11:11:38 -07002200 return rel, true, nil
Colin Cross43f08db2018-11-12 10:13:39 -08002201}
Colin Cross988414c2020-01-11 01:11:46 +00002202
2203// Writes a file to the output directory. Attempting to write directly to the output directory
2204// will fail due to the sandbox of the soong_build process.
2205func WriteFileToOutputDir(path WritablePath, data []byte, perm os.FileMode) error {
2206 return ioutil.WriteFile(absolutePath(path.String()), data, perm)
2207}
2208
Liz Kammer2dd9ca42020-11-25 16:06:39 -08002209func RemoveAllOutputDir(path WritablePath) error {
2210 return os.RemoveAll(absolutePath(path.String()))
2211}
2212
2213func CreateOutputDirIfNonexistent(path WritablePath, perm os.FileMode) error {
2214 dir := absolutePath(path.String())
2215 if _, err := os.Stat(dir); os.IsNotExist(err) {
2216 return os.MkdirAll(dir, os.ModePerm)
2217 } else {
2218 return err
2219 }
2220}
2221
Colin Cross988414c2020-01-11 01:11:46 +00002222func absolutePath(path string) string {
2223 if filepath.IsAbs(path) {
2224 return path
2225 }
2226 return filepath.Join(absSrcDir, path)
2227}
Chris Parsons216e10a2020-07-09 17:12:52 -04002228
2229// A DataPath represents the path of a file to be used as data, for example
2230// a test library to be installed alongside a test.
2231// The data file should be installed (copied from `<SrcPath>`) to
2232// `<install_root>/<RelativeInstallPath>/<filename>`, or
2233// `<install_root>/<filename>` if RelativeInstallPath is empty.
2234type DataPath struct {
2235 // The path of the data file that should be copied into the data directory
2236 SrcPath Path
2237 // The install path of the data file, relative to the install root.
2238 RelativeInstallPath string
2239}
Colin Crossdcf71b22021-02-01 13:59:03 -08002240
2241// PathsIfNonNil returns a Paths containing only the non-nil input arguments.
2242func PathsIfNonNil(paths ...Path) Paths {
2243 if len(paths) == 0 {
2244 // Fast path for empty argument list
2245 return nil
2246 } else if len(paths) == 1 {
2247 // Fast path for a single argument
2248 if paths[0] != nil {
2249 return paths
2250 } else {
2251 return nil
2252 }
2253 }
2254 ret := make(Paths, 0, len(paths))
2255 for _, path := range paths {
2256 if path != nil {
2257 ret = append(ret, path)
2258 }
2259 }
2260 if len(ret) == 0 {
2261 return nil
2262 }
2263 return ret
2264}