blob: ef7e1dfa629dc6289325ffeea4c343381a0fdc15 [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
289// String returns the string version of the Path, or "" if it isn't valid.
290func (p OptionalPath) String() string {
291 if p.valid {
292 return p.path.String()
293 } else {
294 return ""
Colin Crossf2298272015-05-12 11:36:53 -0700295 }
296}
Colin Cross6e18ca42015-07-14 18:55:36 -0700297
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700298// Paths is a slice of Path objects, with helpers to operate on the collection.
299type Paths []Path
300
Paul Duffin85d8f0d2021-03-24 10:18:18 +0000301// RelativeToTop creates a new Paths containing the result of calling Path.RelativeToTop on each
302// item in this slice.
303func (p Paths) RelativeToTop() Paths {
304 ensureTestOnly()
305 if p == nil {
306 return p
307 }
308 ret := make(Paths, len(p))
309 for i, path := range p {
310 ret[i] = path.RelativeToTop()
311 }
312 return ret
313}
314
Jingwen Chen40fd90a2020-06-15 05:24:19 +0000315func (paths Paths) containsPath(path Path) bool {
316 for _, p := range paths {
317 if p == path {
318 return true
319 }
320 }
321 return false
322}
323
Liz Kammer7aa52882021-02-11 09:16:14 -0500324// PathsForSource returns Paths rooted from SrcDir, *not* rooted from the module's local source
325// directory
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700326func PathsForSource(ctx PathContext, paths []string) Paths {
327 ret := make(Paths, len(paths))
328 for i, path := range paths {
329 ret[i] = PathForSource(ctx, path)
330 }
331 return ret
332}
333
Liz Kammer7aa52882021-02-11 09:16:14 -0500334// ExistentPathsForSources returns a list of Paths rooted from SrcDir, *not* rooted from the
335// module's local source directory, that are found in the tree. If any are not found, they are
336// 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 -0800337func ExistentPathsForSources(ctx PathContext, paths []string) Paths {
Dan Willemsen7b310ee2015-12-18 15:11:17 -0800338 ret := make(Paths, 0, len(paths))
339 for _, path := range paths {
Colin Cross32f38982018-02-22 11:47:25 -0800340 p := ExistentPathForSource(ctx, path)
Dan Willemsen7b310ee2015-12-18 15:11:17 -0800341 if p.Valid() {
342 ret = append(ret, p.Path())
343 }
344 }
345 return ret
346}
347
Colin Cross41955e82019-05-29 14:40:35 -0700348// PathsForModuleSrc returns Paths rooted from the module's local source directory. It expands globs, references to
349// SourceFileProducer modules using the ":name" syntax, and references to OutputFileProducer modules using the
350// ":name{.tag}" syntax. Properties passed as the paths argument must have been annotated with struct tag
351// `android:"path"` so that dependencies on SourceFileProducer modules will have already been handled by the
352// path_properties mutator. If ctx.Config().AllowMissingDependencies() is true then any missing SourceFileProducer or
353// OutputFileProducer dependencies will cause the module to be marked as having missing dependencies.
Liz Kammera830f3a2020-11-10 10:50:34 -0800354func PathsForModuleSrc(ctx ModuleMissingDepsPathContext, paths []string) Paths {
Colin Cross8a497952019-03-05 22:25:09 -0800355 return PathsForModuleSrcExcludes(ctx, paths, nil)
356}
357
Colin Crossba71a3f2019-03-18 12:12:48 -0700358// PathsForModuleSrcExcludes returns Paths rooted from the module's local source directory, excluding paths listed in
Colin Cross41955e82019-05-29 14:40:35 -0700359// the excludes arguments. It expands globs, references to SourceFileProducer modules using the ":name" syntax, and
360// references to OutputFileProducer modules using the ":name{.tag}" syntax. Properties passed as the paths or excludes
361// argument must have been annotated with struct tag `android:"path"` so that dependencies on SourceFileProducer modules
362// will have already been handled by the path_properties mutator. If ctx.Config().AllowMissingDependencies() is
Paul Duffin036cace2019-07-25 14:44:56 +0100363// true then any missing SourceFileProducer or OutputFileProducer dependencies will cause the module to be marked as
Colin Cross41955e82019-05-29 14:40:35 -0700364// having missing dependencies.
Liz Kammera830f3a2020-11-10 10:50:34 -0800365func PathsForModuleSrcExcludes(ctx ModuleMissingDepsPathContext, paths, excludes []string) Paths {
Colin Crossba71a3f2019-03-18 12:12:48 -0700366 ret, missingDeps := PathsAndMissingDepsForModuleSrcExcludes(ctx, paths, excludes)
367 if ctx.Config().AllowMissingDependencies() {
368 ctx.AddMissingDependencies(missingDeps)
369 } else {
370 for _, m := range missingDeps {
371 ctx.ModuleErrorf(`missing dependency on %q, is the property annotated with android:"path"?`, m)
372 }
373 }
374 return ret
375}
376
Liz Kammer356f7d42021-01-26 09:18:53 -0500377// A subset of the ModuleContext methods which are sufficient to resolve references to paths/deps in
378// order to form a Bazel-compatible label for conversion.
379type BazelConversionPathContext interface {
380 EarlyModulePathContext
381
382 GetDirectDep(name string) (blueprint.Module, blueprint.DependencyTag)
Liz Kammerbdc60992021-02-24 16:55:11 -0500383 Module() Module
Jingwen Chen12b4c272021-03-10 02:05:59 -0500384 ModuleType() string
Liz Kammer356f7d42021-01-26 09:18:53 -0500385 OtherModuleName(m blueprint.Module) string
386 OtherModuleDir(m blueprint.Module) string
387}
388
389// BazelLabelForModuleDeps returns a Bazel-compatible label for the requested modules which
390// correspond to dependencies on the module within the given ctx.
391func BazelLabelForModuleDeps(ctx BazelConversionPathContext, modules []string) bazel.LabelList {
392 var labels bazel.LabelList
393 for _, module := range modules {
394 bpText := module
395 if m := SrcIsModule(module); m == "" {
396 module = ":" + module
397 }
398 if m, t := SrcIsModuleWithTag(module); m != "" {
399 l := getOtherModuleLabel(ctx, m, t)
400 l.Bp_text = bpText
401 labels.Includes = append(labels.Includes, l)
402 } else {
403 ctx.ModuleErrorf("%q, is not a module reference", module)
404 }
405 }
406 return labels
407}
408
409// BazelLabelForModuleSrc returns bazel.LabelList with paths rooted from the module's local source
410// directory. It expands globs, and resolves references to modules using the ":name" syntax to
411// bazel-compatible labels. Properties passed as the paths or excludes argument must have been
412// annotated with struct tag `android:"path"` so that dependencies on other modules will have
413// already been handled by the path_properties mutator.
414func BazelLabelForModuleSrc(ctx BazelConversionPathContext, paths []string) bazel.LabelList {
415 return BazelLabelForModuleSrcExcludes(ctx, paths, []string(nil))
416}
417
418// BazelLabelForModuleSrcExcludes returns bazel.LabelList with paths rooted from the module's local
419// source directory, excluding labels included in the excludes argument. It expands globs, and
420// resolves references to modules using the ":name" syntax to bazel-compatible labels. Properties
421// passed as the paths or excludes argument must have been annotated with struct tag
422// `android:"path"` so that dependencies on other modules will have already been handled by the
423// path_properties mutator.
424func BazelLabelForModuleSrcExcludes(ctx BazelConversionPathContext, paths, excludes []string) bazel.LabelList {
425 excludeLabels := expandSrcsForBazel(ctx, excludes, []string(nil))
426 excluded := make([]string, 0, len(excludeLabels.Includes))
427 for _, e := range excludeLabels.Includes {
428 excluded = append(excluded, e.Label)
429 }
430 labels := expandSrcsForBazel(ctx, paths, excluded)
431 labels.Excludes = excludeLabels.Includes
432 return labels
433}
434
435// expandSrcsForBazel returns bazel.LabelList with paths rooted from the module's local
436// source directory, excluding labels included in the excludes argument. It expands globs, and
437// resolves references to modules using the ":name" syntax to bazel-compatible labels. Properties
438// passed as the paths or excludes argument must have been annotated with struct tag
439// `android:"path"` so that dependencies on other modules will have already been handled by the
440// path_properties mutator.
441func expandSrcsForBazel(ctx BazelConversionPathContext, paths, expandedExcludes []string) bazel.LabelList {
Liz Kammerebfcf672021-02-16 15:00:05 -0500442 if paths == nil {
443 return bazel.LabelList{}
444 }
Liz Kammer356f7d42021-01-26 09:18:53 -0500445 labels := bazel.LabelList{
446 Includes: []bazel.Label{},
447 }
448 for _, p := range paths {
449 if m, tag := SrcIsModuleWithTag(p); m != "" {
450 l := getOtherModuleLabel(ctx, m, tag)
451 if !InList(l.Label, expandedExcludes) {
452 l.Bp_text = fmt.Sprintf(":%s", m)
453 labels.Includes = append(labels.Includes, l)
454 }
455 } else {
456 var expandedPaths []bazel.Label
457 if pathtools.IsGlob(p) {
458 globbedPaths := GlobFiles(ctx, pathForModuleSrc(ctx, p).String(), expandedExcludes)
459 globbedPaths = PathsWithModuleSrcSubDir(ctx, globbedPaths, "")
460 for _, path := range globbedPaths {
461 s := path.Rel()
462 expandedPaths = append(expandedPaths, bazel.Label{Label: s})
463 }
464 } else {
465 if !InList(p, expandedExcludes) {
466 expandedPaths = append(expandedPaths, bazel.Label{Label: p})
467 }
468 }
469 labels.Includes = append(labels.Includes, expandedPaths...)
470 }
471 }
472 return labels
473}
474
475// getOtherModuleLabel returns a bazel.Label for the given dependency/tag combination for the
476// module. The label will be relative to the current directory if appropriate. The dependency must
477// already be resolved by either deps mutator or path deps mutator.
478func getOtherModuleLabel(ctx BazelConversionPathContext, dep, tag string) bazel.Label {
479 m, _ := ctx.GetDirectDep(dep)
Jingwen Chen07027912021-03-15 06:02:43 -0400480 if m == nil {
481 panic(fmt.Errorf("cannot get direct dep %s of %s", dep, ctx.Module().Name()))
482 }
Liz Kammerbdc60992021-02-24 16:55:11 -0500483 otherLabel := bazelModuleLabel(ctx, m, tag)
484 label := bazelModuleLabel(ctx, ctx.Module(), "")
485 if samePackage(label, otherLabel) {
486 otherLabel = bazelShortLabel(otherLabel)
Liz Kammer356f7d42021-01-26 09:18:53 -0500487 }
Liz Kammerbdc60992021-02-24 16:55:11 -0500488
489 return bazel.Label{
490 Label: otherLabel,
491 }
492}
493
494func bazelModuleLabel(ctx BazelConversionPathContext, module blueprint.Module, tag string) string {
495 // TODO(b/165114590): Convert tag (":name{.tag}") to corresponding Bazel implicit output targets.
496 b, ok := module.(Bazelable)
497 // 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 -0500498 if !ok || !b.ConvertedToBazel(ctx) {
Liz Kammerbdc60992021-02-24 16:55:11 -0500499 return bp2buildModuleLabel(ctx, module)
500 }
501 return b.GetBazelLabel(ctx, module)
502}
503
504func bazelShortLabel(label string) string {
505 i := strings.Index(label, ":")
506 return label[i:]
507}
508
509func bazelPackage(label string) string {
510 i := strings.Index(label, ":")
511 return label[0:i]
512}
513
514func samePackage(label1, label2 string) bool {
515 return bazelPackage(label1) == bazelPackage(label2)
516}
517
518func bp2buildModuleLabel(ctx BazelConversionPathContext, module blueprint.Module) string {
519 moduleName := ctx.OtherModuleName(module)
520 moduleDir := ctx.OtherModuleDir(module)
521 return fmt.Sprintf("//%s:%s", moduleDir, moduleName)
Liz Kammer356f7d42021-01-26 09:18:53 -0500522}
523
Ulya Trafimovich4d2eeed2019-11-08 10:54:21 +0000524// OutputPaths is a slice of OutputPath objects, with helpers to operate on the collection.
525type OutputPaths []OutputPath
526
527// Paths returns the OutputPaths as a Paths
528func (p OutputPaths) Paths() Paths {
529 if p == nil {
530 return nil
531 }
532 ret := make(Paths, len(p))
533 for i, path := range p {
534 ret[i] = path
535 }
536 return ret
537}
538
539// Strings returns the string forms of the writable paths.
540func (p OutputPaths) Strings() []string {
541 if p == nil {
542 return nil
543 }
544 ret := make([]string, len(p))
545 for i, path := range p {
546 ret[i] = path.String()
547 }
548 return ret
549}
550
Liz Kammera830f3a2020-11-10 10:50:34 -0800551// Expands Paths to a SourceFileProducer or OutputFileProducer module dependency referenced via ":name" or ":name{.tag}" syntax.
552// If the dependency is not found, a missingErrorDependency is returned.
553// If the module dependency is not a SourceFileProducer or OutputFileProducer, appropriate errors will be returned.
554func getPathsFromModuleDep(ctx ModuleWithDepsPathContext, path, moduleName, tag string) (Paths, error) {
555 module := ctx.GetDirectDepWithTag(moduleName, sourceOrOutputDepTag(tag))
556 if module == nil {
557 return nil, missingDependencyError{[]string{moduleName}}
558 }
Colin Crossfa65cee2021-03-22 17:05:59 -0700559 if aModule, ok := module.(Module); ok && !aModule.Enabled() {
560 return nil, missingDependencyError{[]string{moduleName}}
561 }
Liz Kammera830f3a2020-11-10 10:50:34 -0800562 if outProducer, ok := module.(OutputFileProducer); ok {
563 outputFiles, err := outProducer.OutputFiles(tag)
564 if err != nil {
565 return nil, fmt.Errorf("path dependency %q: %s", path, err)
566 }
567 return outputFiles, nil
568 } else if tag != "" {
569 return nil, fmt.Errorf("path dependency %q is not an output file producing module", path)
570 } else if srcProducer, ok := module.(SourceFileProducer); ok {
571 return srcProducer.Srcs(), nil
572 } else {
573 return nil, fmt.Errorf("path dependency %q is not a source file producing module", path)
574 }
575}
576
Colin Crossba71a3f2019-03-18 12:12:48 -0700577// PathsAndMissingDepsForModuleSrcExcludes returns Paths rooted from the module's local source directory, excluding
Colin Cross41955e82019-05-29 14:40:35 -0700578// paths listed in the excludes arguments, and a list of missing dependencies. It expands globs, references to
579// SourceFileProducer modules using the ":name" syntax, and references to OutputFileProducer modules using the
580// ":name{.tag}" syntax. Properties passed as the paths or excludes argument must have been annotated with struct tag
581// `android:"path"` so that dependencies on SourceFileProducer modules will have already been handled by the
582// path_properties mutator. If ctx.Config().AllowMissingDependencies() is true then any missing SourceFileProducer or
583// OutputFileProducer dependencies will be returned, and they will NOT cause the module to be marked as having missing
584// dependencies.
Liz Kammera830f3a2020-11-10 10:50:34 -0800585func PathsAndMissingDepsForModuleSrcExcludes(ctx ModuleWithDepsPathContext, paths, excludes []string) (Paths, []string) {
Colin Cross8a497952019-03-05 22:25:09 -0800586 prefix := pathForModuleSrc(ctx).String()
587
588 var expandedExcludes []string
589 if excludes != nil {
590 expandedExcludes = make([]string, 0, len(excludes))
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700591 }
Colin Cross8a497952019-03-05 22:25:09 -0800592
Colin Crossba71a3f2019-03-18 12:12:48 -0700593 var missingExcludeDeps []string
594
Colin Cross8a497952019-03-05 22:25:09 -0800595 for _, e := range excludes {
Colin Cross41955e82019-05-29 14:40:35 -0700596 if m, t := SrcIsModuleWithTag(e); m != "" {
Liz Kammera830f3a2020-11-10 10:50:34 -0800597 modulePaths, err := getPathsFromModuleDep(ctx, e, m, t)
598 if m, ok := err.(missingDependencyError); ok {
599 missingExcludeDeps = append(missingExcludeDeps, m.missingDeps...)
600 } else if err != nil {
601 reportPathError(ctx, err)
Colin Cross8a497952019-03-05 22:25:09 -0800602 } else {
Liz Kammera830f3a2020-11-10 10:50:34 -0800603 expandedExcludes = append(expandedExcludes, modulePaths.Strings()...)
Colin Cross8a497952019-03-05 22:25:09 -0800604 }
605 } else {
606 expandedExcludes = append(expandedExcludes, filepath.Join(prefix, e))
607 }
608 }
609
610 if paths == nil {
Colin Crossba71a3f2019-03-18 12:12:48 -0700611 return nil, missingExcludeDeps
Colin Cross8a497952019-03-05 22:25:09 -0800612 }
613
Colin Crossba71a3f2019-03-18 12:12:48 -0700614 var missingDeps []string
615
Colin Cross8a497952019-03-05 22:25:09 -0800616 expandedSrcFiles := make(Paths, 0, len(paths))
617 for _, s := range paths {
618 srcFiles, err := expandOneSrcPath(ctx, s, expandedExcludes)
619 if depErr, ok := err.(missingDependencyError); ok {
Colin Crossba71a3f2019-03-18 12:12:48 -0700620 missingDeps = append(missingDeps, depErr.missingDeps...)
Colin Cross8a497952019-03-05 22:25:09 -0800621 } else if err != nil {
622 reportPathError(ctx, err)
623 }
624 expandedSrcFiles = append(expandedSrcFiles, srcFiles...)
625 }
Colin Crossba71a3f2019-03-18 12:12:48 -0700626
627 return expandedSrcFiles, append(missingDeps, missingExcludeDeps...)
Colin Cross8a497952019-03-05 22:25:09 -0800628}
629
630type missingDependencyError struct {
631 missingDeps []string
632}
633
634func (e missingDependencyError) Error() string {
635 return "missing dependencies: " + strings.Join(e.missingDeps, ", ")
636}
637
Liz Kammera830f3a2020-11-10 10:50:34 -0800638// Expands one path string to Paths rooted from the module's local source
639// directory, excluding those listed in the expandedExcludes.
640// Expands globs, references to SourceFileProducer or OutputFileProducer modules using the ":name" and ":name{.tag}" syntax.
641func expandOneSrcPath(ctx ModuleWithDepsPathContext, sPath string, expandedExcludes []string) (Paths, error) {
Jooyung Han7607dd32020-07-05 10:23:14 +0900642 excludePaths := func(paths Paths) Paths {
643 if len(expandedExcludes) == 0 {
644 return paths
645 }
646 remainder := make(Paths, 0, len(paths))
647 for _, p := range paths {
648 if !InList(p.String(), expandedExcludes) {
649 remainder = append(remainder, p)
650 }
651 }
652 return remainder
653 }
Liz Kammera830f3a2020-11-10 10:50:34 -0800654 if m, t := SrcIsModuleWithTag(sPath); m != "" {
655 modulePaths, err := getPathsFromModuleDep(ctx, sPath, m, t)
656 if err != nil {
657 return nil, err
Colin Cross8a497952019-03-05 22:25:09 -0800658 } else {
Liz Kammera830f3a2020-11-10 10:50:34 -0800659 return excludePaths(modulePaths), nil
Colin Cross8a497952019-03-05 22:25:09 -0800660 }
Liz Kammera830f3a2020-11-10 10:50:34 -0800661 } else if pathtools.IsGlob(sPath) {
662 paths := GlobFiles(ctx, pathForModuleSrc(ctx, sPath).String(), expandedExcludes)
Colin Cross8a497952019-03-05 22:25:09 -0800663 return PathsWithModuleSrcSubDir(ctx, paths, ""), nil
664 } else {
Liz Kammera830f3a2020-11-10 10:50:34 -0800665 p := pathForModuleSrc(ctx, sPath)
Colin Cross988414c2020-01-11 01:11:46 +0000666 if exists, _, err := ctx.Config().fs.Exists(p.String()); err != nil {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +0100667 ReportPathErrorf(ctx, "%s: %s", p, err.Error())
Pedro Loureiro5d190cc2021-02-15 15:41:33 +0000668 } else if !exists && !ctx.Config().TestAllowNonExistentPaths {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +0100669 ReportPathErrorf(ctx, "module source path %q does not exist", p)
Colin Cross8a497952019-03-05 22:25:09 -0800670 }
671
Jooyung Han7607dd32020-07-05 10:23:14 +0900672 if InList(p.String(), expandedExcludes) {
Colin Cross8a497952019-03-05 22:25:09 -0800673 return nil, nil
674 }
675 return Paths{p}, nil
676 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700677}
678
679// pathsForModuleSrcFromFullPath returns Paths rooted from the module's local
680// source directory, but strip the local source directory from the beginning of
Dan Willemsen540a78c2018-02-26 21:50:08 -0800681// each string. If incDirs is false, strip paths with a trailing '/' from the list.
Colin Crossfe4bc362018-09-12 10:02:13 -0700682// It intended for use in globs that only list files that exist, so it allows '$' in
683// filenames.
Liz Kammera830f3a2020-11-10 10:50:34 -0800684func pathsForModuleSrcFromFullPath(ctx EarlyModulePathContext, paths []string, incDirs bool) Paths {
Colin Cross6510f912017-11-29 00:27:14 -0800685 prefix := filepath.Join(ctx.Config().srcDir, ctx.ModuleDir()) + "/"
Colin Cross0f37af02017-09-27 17:42:05 -0700686 if prefix == "./" {
687 prefix = ""
688 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700689 ret := make(Paths, 0, len(paths))
690 for _, p := range paths {
Dan Willemsen540a78c2018-02-26 21:50:08 -0800691 if !incDirs && strings.HasSuffix(p, "/") {
692 continue
693 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700694 path := filepath.Clean(p)
695 if !strings.HasPrefix(path, prefix) {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +0100696 ReportPathErrorf(ctx, "Path %q is not in module source directory %q", p, prefix)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700697 continue
698 }
Colin Crosse3924e12018-08-15 20:18:53 -0700699
Colin Crossfe4bc362018-09-12 10:02:13 -0700700 srcPath, err := safePathForSource(ctx, ctx.ModuleDir(), path[len(prefix):])
Colin Crosse3924e12018-08-15 20:18:53 -0700701 if err != nil {
702 reportPathError(ctx, err)
703 continue
704 }
705
Colin Cross07e51612019-03-05 12:46:40 -0800706 srcPath.basePath.rel = srcPath.path
Colin Crosse3924e12018-08-15 20:18:53 -0700707
Colin Cross07e51612019-03-05 12:46:40 -0800708 ret = append(ret, srcPath)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700709 }
710 return ret
711}
712
Liz Kammera830f3a2020-11-10 10:50:34 -0800713// PathsWithOptionalDefaultForModuleSrc returns Paths rooted from the module's local source
714// directory. If input is nil, use the default if it exists. If input is empty, returns nil.
715func PathsWithOptionalDefaultForModuleSrc(ctx ModuleMissingDepsPathContext, input []string, def string) Paths {
Colin Cross0ddae7f2019-02-07 15:30:01 -0800716 if input != nil {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700717 return PathsForModuleSrc(ctx, input)
718 }
719 // Use Glob so that if the default doesn't exist, a dependency is added so that when it
720 // is created, we're run again.
Colin Cross6510f912017-11-29 00:27:14 -0800721 path := filepath.Join(ctx.Config().srcDir, ctx.ModuleDir(), def)
Liz Kammera830f3a2020-11-10 10:50:34 -0800722 return Glob(ctx, path, nil)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700723}
724
725// Strings returns the Paths in string form
726func (p Paths) Strings() []string {
727 if p == nil {
728 return nil
729 }
730 ret := make([]string, len(p))
731 for i, path := range p {
732 ret[i] = path.String()
733 }
734 return ret
735}
736
Colin Crossc0efd1d2020-07-03 11:56:24 -0700737func CopyOfPaths(paths Paths) Paths {
738 return append(Paths(nil), paths...)
739}
740
Colin Crossb6715442017-10-24 11:13:31 -0700741// FirstUniquePaths returns all unique elements of a Paths, keeping the first copy of each. It
742// modifies the Paths slice contents in place, and returns a subslice of the original slice.
Dan Willemsenfe92c962017-08-29 12:28:37 -0700743func FirstUniquePaths(list Paths) Paths {
Colin Cross27027c72020-02-28 15:34:17 -0800744 // 128 was chosen based on BenchmarkFirstUniquePaths results.
745 if len(list) > 128 {
746 return firstUniquePathsMap(list)
747 }
748 return firstUniquePathsList(list)
749}
750
Colin Crossc0efd1d2020-07-03 11:56:24 -0700751// SortedUniquePaths returns all unique elements of a Paths in sorted order. It modifies the
752// Paths slice contents in place, and returns a subslice of the original slice.
Jiyong Park33c77362020-05-29 22:00:16 +0900753func SortedUniquePaths(list Paths) Paths {
754 unique := FirstUniquePaths(list)
755 sort.Slice(unique, func(i, j int) bool {
756 return unique[i].String() < unique[j].String()
757 })
758 return unique
759}
760
Colin Cross27027c72020-02-28 15:34:17 -0800761func firstUniquePathsList(list Paths) Paths {
Dan Willemsenfe92c962017-08-29 12:28:37 -0700762 k := 0
763outer:
764 for i := 0; i < len(list); i++ {
765 for j := 0; j < k; j++ {
766 if list[i] == list[j] {
767 continue outer
768 }
769 }
770 list[k] = list[i]
771 k++
772 }
773 return list[:k]
774}
775
Colin Cross27027c72020-02-28 15:34:17 -0800776func firstUniquePathsMap(list Paths) Paths {
777 k := 0
778 seen := make(map[Path]bool, len(list))
779 for i := 0; i < len(list); i++ {
780 if seen[list[i]] {
781 continue
782 }
783 seen[list[i]] = true
784 list[k] = list[i]
785 k++
786 }
787 return list[:k]
788}
789
Colin Cross5d583952020-11-24 16:21:24 -0800790// FirstUniqueInstallPaths returns all unique elements of an InstallPaths, keeping the first copy of each. It
791// modifies the InstallPaths slice contents in place, and returns a subslice of the original slice.
792func FirstUniqueInstallPaths(list InstallPaths) InstallPaths {
793 // 128 was chosen based on BenchmarkFirstUniquePaths results.
794 if len(list) > 128 {
795 return firstUniqueInstallPathsMap(list)
796 }
797 return firstUniqueInstallPathsList(list)
798}
799
800func firstUniqueInstallPathsList(list InstallPaths) InstallPaths {
801 k := 0
802outer:
803 for i := 0; i < len(list); i++ {
804 for j := 0; j < k; j++ {
805 if list[i] == list[j] {
806 continue outer
807 }
808 }
809 list[k] = list[i]
810 k++
811 }
812 return list[:k]
813}
814
815func firstUniqueInstallPathsMap(list InstallPaths) InstallPaths {
816 k := 0
817 seen := make(map[InstallPath]bool, len(list))
818 for i := 0; i < len(list); i++ {
819 if seen[list[i]] {
820 continue
821 }
822 seen[list[i]] = true
823 list[k] = list[i]
824 k++
825 }
826 return list[:k]
827}
828
Colin Crossb6715442017-10-24 11:13:31 -0700829// LastUniquePaths returns all unique elements of a Paths, keeping the last copy of each. It
830// modifies the Paths slice contents in place, and returns a subslice of the original slice.
831func LastUniquePaths(list Paths) Paths {
832 totalSkip := 0
833 for i := len(list) - 1; i >= totalSkip; i-- {
834 skip := 0
835 for j := i - 1; j >= totalSkip; j-- {
836 if list[i] == list[j] {
837 skip++
838 } else {
839 list[j+skip] = list[j]
840 }
841 }
842 totalSkip += skip
843 }
844 return list[totalSkip:]
845}
846
Colin Crossa140bb02018-04-17 10:52:26 -0700847// ReversePaths returns a copy of a Paths in reverse order.
848func ReversePaths(list Paths) Paths {
849 if list == nil {
850 return nil
851 }
852 ret := make(Paths, len(list))
853 for i := range list {
854 ret[i] = list[len(list)-1-i]
855 }
856 return ret
857}
858
Jeff Gaston294356f2017-09-27 17:05:30 -0700859func indexPathList(s Path, list []Path) int {
860 for i, l := range list {
861 if l == s {
862 return i
863 }
864 }
865
866 return -1
867}
868
869func inPathList(p Path, list []Path) bool {
870 return indexPathList(p, list) != -1
871}
872
873func FilterPathList(list []Path, filter []Path) (remainder []Path, filtered []Path) {
Paul Duffin57b9e1d2019-12-13 00:03:35 +0000874 return FilterPathListPredicate(list, func(p Path) bool { return inPathList(p, filter) })
875}
876
877func FilterPathListPredicate(list []Path, predicate func(Path) bool) (remainder []Path, filtered []Path) {
Jeff Gaston294356f2017-09-27 17:05:30 -0700878 for _, l := range list {
Paul Duffin57b9e1d2019-12-13 00:03:35 +0000879 if predicate(l) {
Jeff Gaston294356f2017-09-27 17:05:30 -0700880 filtered = append(filtered, l)
881 } else {
882 remainder = append(remainder, l)
883 }
884 }
885
886 return
887}
888
Colin Cross93e85952017-08-15 13:34:18 -0700889// HasExt returns true of any of the paths have extension ext, otherwise false
890func (p Paths) HasExt(ext string) bool {
891 for _, path := range p {
892 if path.Ext() == ext {
893 return true
894 }
895 }
896
897 return false
898}
899
900// FilterByExt returns the subset of the paths that have extension ext
901func (p Paths) FilterByExt(ext string) Paths {
902 ret := make(Paths, 0, len(p))
903 for _, path := range p {
904 if path.Ext() == ext {
905 ret = append(ret, path)
906 }
907 }
908 return ret
909}
910
911// FilterOutByExt returns the subset of the paths that do not have extension ext
912func (p Paths) FilterOutByExt(ext string) Paths {
913 ret := make(Paths, 0, len(p))
914 for _, path := range p {
915 if path.Ext() != ext {
916 ret = append(ret, path)
917 }
918 }
919 return ret
920}
921
Colin Cross5e6cfbe2017-11-03 15:20:35 -0700922// DirectorySortedPaths is a slice of paths that are sorted such that all files in a directory
923// (including subdirectories) are in a contiguous subslice of the list, and can be found in
924// O(log(N)) time using a binary search on the directory prefix.
925type DirectorySortedPaths Paths
926
927func PathsToDirectorySortedPaths(paths Paths) DirectorySortedPaths {
928 ret := append(DirectorySortedPaths(nil), paths...)
929 sort.Slice(ret, func(i, j int) bool {
930 return ret[i].String() < ret[j].String()
931 })
932 return ret
933}
934
935// PathsInDirectory returns a subslice of the DirectorySortedPaths as a Paths that contains all entries
936// that are in the specified directory and its subdirectories.
937func (p DirectorySortedPaths) PathsInDirectory(dir string) Paths {
938 prefix := filepath.Clean(dir) + "/"
939 start := sort.Search(len(p), func(i int) bool {
940 return prefix < p[i].String()
941 })
942
943 ret := p[start:]
944
945 end := sort.Search(len(ret), func(i int) bool {
946 return !strings.HasPrefix(ret[i].String(), prefix)
947 })
948
949 ret = ret[:end]
950
951 return Paths(ret)
952}
953
Alex Humesky29e3bbe2020-11-20 21:30:13 -0500954// WritablePaths is a slice of WritablePath, used for multiple outputs.
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700955type WritablePaths []WritablePath
956
Paul Duffin85d8f0d2021-03-24 10:18:18 +0000957// RelativeToTop creates a new WritablePaths containing the result of calling Path.RelativeToTop on
958// each item in this slice.
959func (p WritablePaths) RelativeToTop() WritablePaths {
960 ensureTestOnly()
961 if p == nil {
962 return p
963 }
964 ret := make(WritablePaths, len(p))
965 for i, path := range p {
966 ret[i] = path.RelativeToTop().(WritablePath)
967 }
968 return ret
969}
970
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700971// Strings returns the string forms of the writable paths.
972func (p WritablePaths) Strings() []string {
973 if p == nil {
974 return nil
975 }
976 ret := make([]string, len(p))
977 for i, path := range p {
978 ret[i] = path.String()
979 }
980 return ret
981}
982
Colin Cross3bc7ffa2017-11-22 16:19:37 -0800983// Paths returns the WritablePaths as a Paths
984func (p WritablePaths) Paths() Paths {
985 if p == nil {
986 return nil
987 }
988 ret := make(Paths, len(p))
989 for i, path := range p {
990 ret[i] = path
991 }
992 return ret
993}
994
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700995type basePath struct {
Paul Duffin74abc5d2021-03-24 09:24:59 +0000996 path string
997 rel string
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700998}
999
1000func (p basePath) Ext() string {
1001 return filepath.Ext(p.path)
1002}
1003
Colin Cross4f6fc9c2016-10-26 10:05:25 -07001004func (p basePath) Base() string {
1005 return filepath.Base(p.path)
1006}
1007
Colin Crossfaeb7aa2017-02-01 14:12:44 -08001008func (p basePath) Rel() string {
1009 if p.rel != "" {
1010 return p.rel
1011 }
1012 return p.path
1013}
1014
Colin Cross0875c522017-11-28 17:34:01 -08001015func (p basePath) String() string {
1016 return p.path
1017}
1018
Colin Cross0db55682017-12-05 15:36:55 -08001019func (p basePath) withRel(rel string) basePath {
1020 p.path = filepath.Join(p.path, rel)
1021 p.rel = rel
1022 return p
1023}
1024
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001025// SourcePath is a Path representing a file path rooted from SrcDir
1026type SourcePath struct {
1027 basePath
Paul Duffin580efc82021-03-24 09:04:03 +00001028
1029 // The sources root, i.e. Config.SrcDir()
1030 srcDir string
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001031}
1032
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001033func (p SourcePath) RelativeToTop() Path {
1034 ensureTestOnly()
1035 return p
1036}
1037
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001038var _ Path = SourcePath{}
1039
Colin Cross0db55682017-12-05 15:36:55 -08001040func (p SourcePath) withRel(rel string) SourcePath {
1041 p.basePath = p.basePath.withRel(rel)
1042 return p
1043}
1044
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001045// safePathForSource is for paths that we expect are safe -- only for use by go
1046// code that is embedding ninja variables in paths
Colin Crossfe4bc362018-09-12 10:02:13 -07001047func safePathForSource(ctx PathContext, pathComponents ...string) (SourcePath, error) {
1048 p, err := validateSafePath(pathComponents...)
Paul Duffin74abc5d2021-03-24 09:24:59 +00001049 ret := SourcePath{basePath{p, ""}, ctx.Config().srcDir}
Colin Crossfe4bc362018-09-12 10:02:13 -07001050 if err != nil {
1051 return ret, err
1052 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001053
Colin Cross7b3dcc32019-01-24 13:14:39 -08001054 // absolute path already checked by validateSafePath
1055 if strings.HasPrefix(ret.String(), ctx.Config().buildDir) {
Mikhail Naganovab1f5182019-02-08 13:17:55 -08001056 return ret, fmt.Errorf("source path %q is in output", ret.String())
Colin Cross6e18ca42015-07-14 18:55:36 -07001057 }
1058
Colin Crossfe4bc362018-09-12 10:02:13 -07001059 return ret, err
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001060}
1061
Colin Cross192e97a2018-02-22 14:21:02 -08001062// pathForSource creates a SourcePath from pathComponents, but does not check that it exists.
1063func pathForSource(ctx PathContext, pathComponents ...string) (SourcePath, error) {
Colin Crossc48c1432018-02-23 07:09:01 +00001064 p, err := validatePath(pathComponents...)
Paul Duffin74abc5d2021-03-24 09:24:59 +00001065 ret := SourcePath{basePath{p, ""}, ctx.Config().srcDir}
Colin Cross94a32102018-02-22 14:21:02 -08001066 if err != nil {
Colin Cross192e97a2018-02-22 14:21:02 -08001067 return ret, err
Colin Cross94a32102018-02-22 14:21:02 -08001068 }
1069
Colin Cross7b3dcc32019-01-24 13:14:39 -08001070 // absolute path already checked by validatePath
1071 if strings.HasPrefix(ret.String(), ctx.Config().buildDir) {
Mikhail Naganovab1f5182019-02-08 13:17:55 -08001072 return ret, fmt.Errorf("source path %q is in output", ret.String())
Colin Crossc48c1432018-02-23 07:09:01 +00001073 }
1074
Colin Cross192e97a2018-02-22 14:21:02 -08001075 return ret, nil
1076}
1077
1078// existsWithDependencies returns true if the path exists, and adds appropriate dependencies to rerun if the
1079// path does not exist.
1080func existsWithDependencies(ctx PathContext, path SourcePath) (exists bool, err error) {
1081 var files []string
1082
1083 if gctx, ok := ctx.(PathGlobContext); ok {
1084 // Use glob to produce proper dependencies, even though we only want
1085 // a single file.
1086 files, err = gctx.GlobWithDeps(path.String(), nil)
1087 } else {
1088 var deps []string
1089 // We cannot add build statements in this context, so we fall back to
1090 // AddNinjaFileDeps
Colin Cross988414c2020-01-11 01:11:46 +00001091 files, deps, err = ctx.Config().fs.Glob(path.String(), nil, pathtools.FollowSymlinks)
Colin Cross192e97a2018-02-22 14:21:02 -08001092 ctx.AddNinjaFileDeps(deps...)
1093 }
1094
1095 if err != nil {
1096 return false, fmt.Errorf("glob: %s", err.Error())
1097 }
1098
1099 return len(files) > 0, nil
1100}
1101
1102// PathForSource joins the provided path components and validates that the result
1103// neither escapes the source dir nor is in the out dir.
1104// On error, it will return a usable, but invalid SourcePath, and report a ModuleError.
1105func PathForSource(ctx PathContext, pathComponents ...string) SourcePath {
1106 path, err := pathForSource(ctx, pathComponents...)
1107 if err != nil {
1108 reportPathError(ctx, err)
1109 }
1110
Colin Crosse3924e12018-08-15 20:18:53 -07001111 if pathtools.IsGlob(path.String()) {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001112 ReportPathErrorf(ctx, "path may not contain a glob: %s", path.String())
Colin Crosse3924e12018-08-15 20:18:53 -07001113 }
1114
Liz Kammera830f3a2020-11-10 10:50:34 -08001115 if modCtx, ok := ctx.(ModuleMissingDepsPathContext); ok && ctx.Config().AllowMissingDependencies() {
Colin Cross192e97a2018-02-22 14:21:02 -08001116 exists, err := existsWithDependencies(ctx, path)
1117 if err != nil {
1118 reportPathError(ctx, err)
1119 }
1120 if !exists {
1121 modCtx.AddMissingDependencies([]string{path.String()})
1122 }
Colin Cross988414c2020-01-11 01:11:46 +00001123 } else if exists, _, err := ctx.Config().fs.Exists(path.String()); err != nil {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001124 ReportPathErrorf(ctx, "%s: %s", path, err.Error())
Pedro Loureiro5d190cc2021-02-15 15:41:33 +00001125 } else if !exists && !ctx.Config().TestAllowNonExistentPaths {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001126 ReportPathErrorf(ctx, "source path %q does not exist", path)
Colin Cross192e97a2018-02-22 14:21:02 -08001127 }
1128 return path
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001129}
1130
Liz Kammer7aa52882021-02-11 09:16:14 -05001131// ExistentPathForSource returns an OptionalPath with the SourcePath, rooted from SrcDir, *not*
1132// rooted from the module's local source directory, if the path exists, or an empty OptionalPath if
1133// it doesn't exist. Dependencies are added so that the ninja file will be regenerated if the state
1134// of the path changes.
Colin Cross32f38982018-02-22 11:47:25 -08001135func ExistentPathForSource(ctx PathContext, pathComponents ...string) OptionalPath {
Colin Cross192e97a2018-02-22 14:21:02 -08001136 path, err := pathForSource(ctx, pathComponents...)
Colin Cross1ccfcc32018-02-22 13:54:26 -08001137 if err != nil {
1138 reportPathError(ctx, err)
1139 return OptionalPath{}
1140 }
Colin Crossc48c1432018-02-23 07:09:01 +00001141
Colin Crosse3924e12018-08-15 20:18:53 -07001142 if pathtools.IsGlob(path.String()) {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001143 ReportPathErrorf(ctx, "path may not contain a glob: %s", path.String())
Colin Crosse3924e12018-08-15 20:18:53 -07001144 return OptionalPath{}
1145 }
1146
Colin Cross192e97a2018-02-22 14:21:02 -08001147 exists, err := existsWithDependencies(ctx, path)
Colin Crossc48c1432018-02-23 07:09:01 +00001148 if err != nil {
1149 reportPathError(ctx, err)
1150 return OptionalPath{}
1151 }
Colin Cross192e97a2018-02-22 14:21:02 -08001152 if !exists {
Colin Crossc48c1432018-02-23 07:09:01 +00001153 return OptionalPath{}
1154 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001155 return OptionalPathForPath(path)
1156}
1157
1158func (p SourcePath) String() string {
Paul Duffin580efc82021-03-24 09:04:03 +00001159 return filepath.Join(p.srcDir, p.path)
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001160}
1161
1162// Join creates a new SourcePath with paths... joined with the current path. The
1163// provided paths... may not use '..' to escape from the current path.
1164func (p SourcePath) Join(ctx PathContext, paths ...string) SourcePath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001165 path, err := validatePath(paths...)
1166 if err != nil {
1167 reportPathError(ctx, err)
1168 }
Colin Cross0db55682017-12-05 15:36:55 -08001169 return p.withRel(path)
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001170}
1171
Colin Cross2fafa3e2019-03-05 12:39:51 -08001172// join is like Join but does less path validation.
1173func (p SourcePath) join(ctx PathContext, paths ...string) SourcePath {
1174 path, err := validateSafePath(paths...)
1175 if err != nil {
1176 reportPathError(ctx, err)
1177 }
1178 return p.withRel(path)
1179}
1180
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001181// OverlayPath returns the overlay for `path' if it exists. This assumes that the
1182// SourcePath is the path to a resource overlay directory.
Liz Kammera830f3a2020-11-10 10:50:34 -08001183func (p SourcePath) OverlayPath(ctx ModuleMissingDepsPathContext, path Path) OptionalPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001184 var relDir string
Colin Cross07e51612019-03-05 12:46:40 -08001185 if srcPath, ok := path.(SourcePath); ok {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001186 relDir = srcPath.path
1187 } else {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001188 ReportPathErrorf(ctx, "Cannot find relative path for %s(%s)", reflect.TypeOf(path).Name(), path)
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001189 return OptionalPath{}
1190 }
Paul Duffin580efc82021-03-24 09:04:03 +00001191 dir := filepath.Join(p.srcDir, p.path, relDir)
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001192 // Use Glob so that we are run again if the directory is added.
Colin Cross7f19f372016-11-01 11:10:25 -07001193 if pathtools.IsGlob(dir) {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001194 ReportPathErrorf(ctx, "Path may not contain a glob: %s", dir)
Dan Willemsen7b310ee2015-12-18 15:11:17 -08001195 }
Colin Cross461b4452018-02-23 09:22:42 -08001196 paths, err := ctx.GlobWithDeps(dir, nil)
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001197 if err != nil {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001198 ReportPathErrorf(ctx, "glob: %s", err.Error())
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001199 return OptionalPath{}
1200 }
1201 if len(paths) == 0 {
1202 return OptionalPath{}
1203 }
Paul Duffin580efc82021-03-24 09:04:03 +00001204 relPath := Rel(ctx, p.srcDir, paths[0])
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001205 return OptionalPathForPath(PathForSource(ctx, relPath))
1206}
1207
Colin Cross70dda7e2019-10-01 22:05:35 -07001208// OutputPath is a Path representing an intermediates file path rooted from the build directory
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001209type OutputPath struct {
1210 basePath
Paul Duffind65c58b2021-03-24 09:22:07 +00001211
1212 // The soong build directory, i.e. Config.BuildDir()
1213 buildDir string
1214
Colin Crossd63c9a72020-01-29 16:52:50 -08001215 fullPath string
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001216}
1217
Colin Cross702e0f82017-10-18 17:27:54 -07001218func (p OutputPath) withRel(rel string) OutputPath {
Colin Cross0db55682017-12-05 15:36:55 -08001219 p.basePath = p.basePath.withRel(rel)
Colin Crossd63c9a72020-01-29 16:52:50 -08001220 p.fullPath = filepath.Join(p.fullPath, rel)
Colin Cross702e0f82017-10-18 17:27:54 -07001221 return p
1222}
1223
Colin Cross3063b782018-08-15 11:19:12 -07001224func (p OutputPath) WithoutRel() OutputPath {
1225 p.basePath.rel = filepath.Base(p.basePath.path)
1226 return p
1227}
1228
Paul Duffind65c58b2021-03-24 09:22:07 +00001229func (p OutputPath) getBuildDir() string {
1230 return p.buildDir
Paul Duffin9b478b02019-12-10 13:41:51 +00001231}
1232
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001233func (p OutputPath) RelativeToTop() Path {
1234 return p.outputPathRelativeToTop()
1235}
1236
1237func (p OutputPath) outputPathRelativeToTop() OutputPath {
1238 p.fullPath = StringPathRelativeToTop(p.buildDir, p.fullPath)
1239 p.buildDir = OutSoongDir
1240 return p
1241}
1242
Paul Duffin0267d492021-02-02 10:05:52 +00001243func (p OutputPath) objPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleObjPath {
1244 return PathForModuleObj(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
1245}
1246
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001247var _ Path = OutputPath{}
Paul Duffin9b478b02019-12-10 13:41:51 +00001248var _ WritablePath = OutputPath{}
Paul Duffin0267d492021-02-02 10:05:52 +00001249var _ objPathProvider = OutputPath{}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001250
Chris Parsons8f232a22020-06-23 17:37:05 -04001251// toolDepPath is a Path representing a dependency of the build tool.
1252type toolDepPath struct {
1253 basePath
1254}
1255
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001256func (t toolDepPath) RelativeToTop() Path {
1257 ensureTestOnly()
1258 return t
1259}
1260
Chris Parsons8f232a22020-06-23 17:37:05 -04001261var _ Path = toolDepPath{}
1262
1263// pathForBuildToolDep returns a toolDepPath representing the given path string.
1264// There is no validation for the path, as it is "trusted": It may fail
1265// normal validation checks. For example, it may be an absolute path.
1266// Only use this function to construct paths for dependencies of the build
1267// tool invocation.
1268func pathForBuildToolDep(ctx PathContext, path string) toolDepPath {
Paul Duffin74abc5d2021-03-24 09:24:59 +00001269 return toolDepPath{basePath{path, ""}}
Chris Parsons8f232a22020-06-23 17:37:05 -04001270}
1271
Jeff Gaston734e3802017-04-10 15:47:24 -07001272// PathForOutput joins the provided paths and returns an OutputPath that is
1273// validated to not escape the build dir.
1274// On error, it will return a usable, but invalid OutputPath, and report a ModuleError.
1275func PathForOutput(ctx PathContext, pathComponents ...string) OutputPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001276 path, err := validatePath(pathComponents...)
1277 if err != nil {
1278 reportPathError(ctx, err)
1279 }
Colin Crossd63c9a72020-01-29 16:52:50 -08001280 fullPath := filepath.Join(ctx.Config().buildDir, path)
1281 path = fullPath[len(fullPath)-len(path):]
Paul Duffin74abc5d2021-03-24 09:24:59 +00001282 return OutputPath{basePath{path, ""}, ctx.Config().buildDir, fullPath}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001283}
1284
Colin Cross40e33732019-02-15 11:08:35 -08001285// PathsForOutput returns Paths rooted from buildDir
1286func PathsForOutput(ctx PathContext, paths []string) WritablePaths {
1287 ret := make(WritablePaths, len(paths))
1288 for i, path := range paths {
1289 ret[i] = PathForOutput(ctx, path)
1290 }
1291 return ret
1292}
1293
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001294func (p OutputPath) writablePath() {}
1295
1296func (p OutputPath) String() string {
Colin Crossd63c9a72020-01-29 16:52:50 -08001297 return p.fullPath
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001298}
1299
1300// Join creates a new OutputPath with paths... joined with the current path. The
1301// provided paths... may not use '..' to escape from the current path.
1302func (p OutputPath) Join(ctx PathContext, paths ...string) OutputPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001303 path, err := validatePath(paths...)
1304 if err != nil {
1305 reportPathError(ctx, err)
1306 }
Colin Cross0db55682017-12-05 15:36:55 -08001307 return p.withRel(path)
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001308}
1309
Colin Cross8854a5a2019-02-11 14:14:16 -08001310// ReplaceExtension creates a new OutputPath with the extension replaced with ext.
1311func (p OutputPath) ReplaceExtension(ctx PathContext, ext string) OutputPath {
1312 if strings.Contains(ext, "/") {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001313 ReportPathErrorf(ctx, "extension %q cannot contain /", ext)
Colin Cross8854a5a2019-02-11 14:14:16 -08001314 }
1315 ret := PathForOutput(ctx, pathtools.ReplaceExtension(p.path, ext))
Colin Cross2cdd5df2019-02-25 10:25:24 -08001316 ret.rel = pathtools.ReplaceExtension(p.rel, ext)
Colin Cross8854a5a2019-02-11 14:14:16 -08001317 return ret
1318}
1319
Colin Cross40e33732019-02-15 11:08:35 -08001320// InSameDir creates a new OutputPath from the directory of the current OutputPath joined with the elements in paths.
1321func (p OutputPath) InSameDir(ctx PathContext, paths ...string) OutputPath {
1322 path, err := validatePath(paths...)
1323 if err != nil {
1324 reportPathError(ctx, err)
1325 }
1326
1327 ret := PathForOutput(ctx, filepath.Dir(p.path), path)
Colin Cross2cdd5df2019-02-25 10:25:24 -08001328 ret.rel = filepath.Join(filepath.Dir(p.rel), path)
Colin Cross40e33732019-02-15 11:08:35 -08001329 return ret
1330}
1331
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001332// PathForIntermediates returns an OutputPath representing the top-level
1333// intermediates directory.
1334func PathForIntermediates(ctx PathContext, paths ...string) OutputPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001335 path, err := validatePath(paths...)
1336 if err != nil {
1337 reportPathError(ctx, err)
1338 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001339 return PathForOutput(ctx, ".intermediates", path)
1340}
1341
Colin Cross07e51612019-03-05 12:46:40 -08001342var _ genPathProvider = SourcePath{}
1343var _ objPathProvider = SourcePath{}
1344var _ resPathProvider = SourcePath{}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001345
Colin Cross07e51612019-03-05 12:46:40 -08001346// PathForModuleSrc returns a Path representing the paths... under the
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001347// module's local source directory.
Liz Kammera830f3a2020-11-10 10:50:34 -08001348func PathForModuleSrc(ctx ModuleMissingDepsPathContext, pathComponents ...string) Path {
Colin Cross8a497952019-03-05 22:25:09 -08001349 p, err := validatePath(pathComponents...)
1350 if err != nil {
1351 reportPathError(ctx, err)
Colin Cross192e97a2018-02-22 14:21:02 -08001352 }
Colin Cross8a497952019-03-05 22:25:09 -08001353 paths, err := expandOneSrcPath(ctx, p, nil)
1354 if err != nil {
1355 if depErr, ok := err.(missingDependencyError); ok {
1356 if ctx.Config().AllowMissingDependencies() {
1357 ctx.AddMissingDependencies(depErr.missingDeps)
1358 } else {
1359 ctx.ModuleErrorf(`%s, is the property annotated with android:"path"?`, depErr.Error())
1360 }
1361 } else {
1362 reportPathError(ctx, err)
1363 }
1364 return nil
1365 } else if len(paths) == 0 {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001366 ReportPathErrorf(ctx, "%q produced no files, expected exactly one", p)
Colin Cross8a497952019-03-05 22:25:09 -08001367 return nil
1368 } else if len(paths) > 1 {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001369 ReportPathErrorf(ctx, "%q produced %d files, expected exactly one", p, len(paths))
Colin Cross8a497952019-03-05 22:25:09 -08001370 }
1371 return paths[0]
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001372}
1373
Liz Kammera830f3a2020-11-10 10:50:34 -08001374func pathForModuleSrc(ctx EarlyModulePathContext, paths ...string) SourcePath {
Colin Cross07e51612019-03-05 12:46:40 -08001375 p, err := validatePath(paths...)
1376 if err != nil {
1377 reportPathError(ctx, err)
1378 }
1379
1380 path, err := pathForSource(ctx, ctx.ModuleDir(), p)
1381 if err != nil {
1382 reportPathError(ctx, err)
1383 }
1384
1385 path.basePath.rel = p
1386
1387 return path
1388}
1389
Colin Cross2fafa3e2019-03-05 12:39:51 -08001390// PathsWithModuleSrcSubDir takes a list of Paths and returns a new list of Paths where Rel() on each path
1391// will return the path relative to subDir in the module's source directory. If any input paths are not located
1392// inside subDir then a path error will be reported.
Liz Kammera830f3a2020-11-10 10:50:34 -08001393func PathsWithModuleSrcSubDir(ctx EarlyModulePathContext, paths Paths, subDir string) Paths {
Colin Cross2fafa3e2019-03-05 12:39:51 -08001394 paths = append(Paths(nil), paths...)
Colin Cross07e51612019-03-05 12:46:40 -08001395 subDirFullPath := pathForModuleSrc(ctx, subDir)
Colin Cross2fafa3e2019-03-05 12:39:51 -08001396 for i, path := range paths {
1397 rel := Rel(ctx, subDirFullPath.String(), path.String())
1398 paths[i] = subDirFullPath.join(ctx, rel)
1399 }
1400 return paths
1401}
1402
1403// PathWithModuleSrcSubDir takes a Path and returns a Path where Rel() will return the path relative to subDir in the
1404// 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 -08001405func PathWithModuleSrcSubDir(ctx EarlyModulePathContext, path Path, subDir string) Path {
Colin Cross07e51612019-03-05 12:46:40 -08001406 subDirFullPath := pathForModuleSrc(ctx, subDir)
Colin Cross2fafa3e2019-03-05 12:39:51 -08001407 rel := Rel(ctx, subDirFullPath.String(), path.String())
1408 return subDirFullPath.Join(ctx, rel)
1409}
1410
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001411// OptionalPathForModuleSrc returns an OptionalPath. The OptionalPath contains a
1412// valid path if p is non-nil.
Liz Kammera830f3a2020-11-10 10:50:34 -08001413func OptionalPathForModuleSrc(ctx ModuleMissingDepsPathContext, p *string) OptionalPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001414 if p == nil {
1415 return OptionalPath{}
1416 }
1417 return OptionalPathForPath(PathForModuleSrc(ctx, *p))
1418}
1419
Liz Kammera830f3a2020-11-10 10:50:34 -08001420func (p SourcePath) genPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleGenPath {
Colin Cross7fc17db2017-02-01 14:07:55 -08001421 return PathForModuleGen(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001422}
1423
Liz Kammera830f3a2020-11-10 10:50:34 -08001424func (p SourcePath) objPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleObjPath {
Colin Cross7fc17db2017-02-01 14:07:55 -08001425 return PathForModuleObj(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001426}
1427
Liz Kammera830f3a2020-11-10 10:50:34 -08001428func (p SourcePath) resPathWithName(ctx ModuleOutPathContext, name string) ModuleResPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001429 // TODO: Use full directory if the new ctx is not the current ctx?
1430 return PathForModuleRes(ctx, p.path, name)
1431}
1432
1433// ModuleOutPath is a Path representing a module's output directory.
1434type ModuleOutPath struct {
1435 OutputPath
1436}
1437
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001438func (p ModuleOutPath) RelativeToTop() Path {
1439 p.OutputPath = p.outputPathRelativeToTop()
1440 return p
1441}
1442
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001443var _ Path = ModuleOutPath{}
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001444var _ WritablePath = ModuleOutPath{}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001445
Liz Kammera830f3a2020-11-10 10:50:34 -08001446func (p ModuleOutPath) objPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleObjPath {
Pete Bentleyfcf55bf2019-08-16 20:14:32 +01001447 return PathForModuleObj(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
1448}
1449
Liz Kammera830f3a2020-11-10 10:50:34 -08001450// ModuleOutPathContext Subset of ModuleContext functions necessary for output path methods.
1451type ModuleOutPathContext interface {
1452 PathContext
1453
1454 ModuleName() string
1455 ModuleDir() string
1456 ModuleSubDir() string
1457}
1458
1459func pathForModuleOut(ctx ModuleOutPathContext) OutputPath {
Colin Cross702e0f82017-10-18 17:27:54 -07001460 return PathForOutput(ctx, ".intermediates", ctx.ModuleDir(), ctx.ModuleName(), ctx.ModuleSubDir())
1461}
1462
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001463type BazelOutPath struct {
1464 OutputPath
1465}
1466
1467var _ Path = BazelOutPath{}
1468var _ objPathProvider = BazelOutPath{}
1469
Liz Kammera830f3a2020-11-10 10:50:34 -08001470func (p BazelOutPath) objPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleObjPath {
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001471 return PathForModuleObj(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
1472}
1473
Logan Chien7eefdc42018-07-11 18:10:41 +08001474// PathForVndkRefAbiDump returns an OptionalPath representing the path of the
1475// reference abi dump for the given module. This is not guaranteed to be valid.
Liz Kammera830f3a2020-11-10 10:50:34 -08001476func PathForVndkRefAbiDump(ctx ModuleInstallPathContext, version, fileName string,
Hsin-Yi Chen53489642019-07-31 17:10:45 +08001477 isNdk, isLlndkOrVndk, isGzip bool) OptionalPath {
Logan Chien7eefdc42018-07-11 18:10:41 +08001478
Jayant Chowdharyac066c62018-02-20 10:53:31 -08001479 arches := ctx.DeviceConfig().Arches()
Logan Chien7eefdc42018-07-11 18:10:41 +08001480 if len(arches) == 0 {
1481 panic("device build with no primary arch")
1482 }
Jayant Chowdharyac066c62018-02-20 10:53:31 -08001483 currentArch := ctx.Arch()
1484 archNameAndVariant := currentArch.ArchType.String()
1485 if currentArch.ArchVariant != "" {
1486 archNameAndVariant += "_" + currentArch.ArchVariant
1487 }
Logan Chien5237bed2018-07-11 17:15:57 +08001488
1489 var dirName string
Hsin-Yi Chen53489642019-07-31 17:10:45 +08001490 if isNdk {
Logan Chien5237bed2018-07-11 17:15:57 +08001491 dirName = "ndk"
Hsin-Yi Chen53489642019-07-31 17:10:45 +08001492 } else if isLlndkOrVndk {
Logan Chien5237bed2018-07-11 17:15:57 +08001493 dirName = "vndk"
Logan Chien41eabe62019-04-10 13:33:58 +08001494 } else {
1495 dirName = "platform" // opt-in libs
Jayant Chowdhary3e231fd2017-02-08 13:45:53 -08001496 }
Logan Chien5237bed2018-07-11 17:15:57 +08001497
Jayant Chowdhary34ce67d2018-03-08 11:00:50 -08001498 binderBitness := ctx.DeviceConfig().BinderBitness()
Logan Chien7eefdc42018-07-11 18:10:41 +08001499
1500 var ext string
1501 if isGzip {
1502 ext = ".lsdump.gz"
1503 } else {
1504 ext = ".lsdump"
1505 }
1506
1507 return ExistentPathForSource(ctx, "prebuilts", "abi-dumps", dirName,
1508 version, binderBitness, archNameAndVariant, "source-based",
1509 fileName+ext)
Jayant Chowdhary3e231fd2017-02-08 13:45:53 -08001510}
1511
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001512// PathForBazelOut returns a Path representing the paths... under an output directory dedicated to
1513// bazel-owned outputs.
1514func PathForBazelOut(ctx PathContext, paths ...string) BazelOutPath {
1515 execRootPathComponents := append([]string{"execroot", "__main__"}, paths...)
1516 execRootPath := filepath.Join(execRootPathComponents...)
1517 validatedExecRootPath, err := validatePath(execRootPath)
1518 if err != nil {
1519 reportPathError(ctx, err)
1520 }
1521
Paul Duffin74abc5d2021-03-24 09:24:59 +00001522 outputPath := OutputPath{basePath{"", ""},
Paul Duffind65c58b2021-03-24 09:22:07 +00001523 ctx.Config().buildDir,
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001524 ctx.Config().BazelContext.OutputBase()}
1525
1526 return BazelOutPath{
1527 OutputPath: outputPath.withRel(validatedExecRootPath),
1528 }
1529}
1530
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001531// PathForModuleOut returns a Path representing the paths... under the module's
1532// output directory.
Liz Kammera830f3a2020-11-10 10:50:34 -08001533func PathForModuleOut(ctx ModuleOutPathContext, paths ...string) ModuleOutPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001534 p, err := validatePath(paths...)
1535 if err != nil {
1536 reportPathError(ctx, err)
1537 }
Colin Cross702e0f82017-10-18 17:27:54 -07001538 return ModuleOutPath{
Liz Kammera830f3a2020-11-10 10:50:34 -08001539 OutputPath: pathForModuleOut(ctx).withRel(p),
Colin Cross702e0f82017-10-18 17:27:54 -07001540 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001541}
1542
1543// ModuleGenPath is a Path representing the 'gen' directory in a module's output
1544// directory. Mainly used for generated sources.
1545type ModuleGenPath struct {
1546 ModuleOutPath
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001547}
1548
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001549func (p ModuleGenPath) RelativeToTop() Path {
1550 p.OutputPath = p.outputPathRelativeToTop()
1551 return p
1552}
1553
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001554var _ Path = ModuleGenPath{}
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001555var _ WritablePath = ModuleGenPath{}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001556var _ genPathProvider = ModuleGenPath{}
1557var _ objPathProvider = ModuleGenPath{}
1558
1559// PathForModuleGen returns a Path representing the paths... under the module's
1560// `gen' directory.
Liz Kammera830f3a2020-11-10 10:50:34 -08001561func PathForModuleGen(ctx ModuleOutPathContext, paths ...string) ModuleGenPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001562 p, err := validatePath(paths...)
1563 if err != nil {
1564 reportPathError(ctx, err)
1565 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001566 return ModuleGenPath{
Colin Cross702e0f82017-10-18 17:27:54 -07001567 ModuleOutPath: ModuleOutPath{
Liz Kammera830f3a2020-11-10 10:50:34 -08001568 OutputPath: pathForModuleOut(ctx).withRel("gen").withRel(p),
Colin Cross702e0f82017-10-18 17:27:54 -07001569 },
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001570 }
1571}
1572
Liz Kammera830f3a2020-11-10 10:50:34 -08001573func (p ModuleGenPath) genPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleGenPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001574 // TODO: make a different path for local vs remote generated files?
Dan Willemsen21ec4902016-11-02 20:43:13 -07001575 return PathForModuleGen(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001576}
1577
Liz Kammera830f3a2020-11-10 10:50:34 -08001578func (p ModuleGenPath) objPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleObjPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001579 return PathForModuleObj(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
1580}
1581
1582// ModuleObjPath is a Path representing the 'obj' directory in a module's output
1583// directory. Used for compiled objects.
1584type ModuleObjPath struct {
1585 ModuleOutPath
1586}
1587
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001588func (p ModuleObjPath) RelativeToTop() Path {
1589 p.OutputPath = p.outputPathRelativeToTop()
1590 return p
1591}
1592
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001593var _ Path = ModuleObjPath{}
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001594var _ WritablePath = ModuleObjPath{}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001595
1596// PathForModuleObj returns a Path representing the paths... under the module's
1597// 'obj' directory.
Liz Kammera830f3a2020-11-10 10:50:34 -08001598func PathForModuleObj(ctx ModuleOutPathContext, pathComponents ...string) ModuleObjPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001599 p, err := validatePath(pathComponents...)
1600 if err != nil {
1601 reportPathError(ctx, err)
1602 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001603 return ModuleObjPath{PathForModuleOut(ctx, "obj", p)}
1604}
1605
1606// ModuleResPath is a a Path representing the 'res' directory in a module's
1607// output directory.
1608type ModuleResPath struct {
1609 ModuleOutPath
1610}
1611
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001612func (p ModuleResPath) RelativeToTop() Path {
1613 p.OutputPath = p.outputPathRelativeToTop()
1614 return p
1615}
1616
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001617var _ Path = ModuleResPath{}
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001618var _ WritablePath = ModuleResPath{}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001619
1620// PathForModuleRes returns a Path representing the paths... under the module's
1621// 'res' directory.
Liz Kammera830f3a2020-11-10 10:50:34 -08001622func PathForModuleRes(ctx ModuleOutPathContext, pathComponents ...string) ModuleResPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001623 p, err := validatePath(pathComponents...)
1624 if err != nil {
1625 reportPathError(ctx, err)
1626 }
1627
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001628 return ModuleResPath{PathForModuleOut(ctx, "res", p)}
1629}
1630
Colin Cross70dda7e2019-10-01 22:05:35 -07001631// InstallPath is a Path representing a installed file path rooted from the build directory
1632type InstallPath struct {
1633 basePath
Colin Crossff6c33d2019-10-02 16:01:35 -07001634
Paul Duffind65c58b2021-03-24 09:22:07 +00001635 // The soong build directory, i.e. Config.BuildDir()
1636 buildDir string
1637
Jiyong Park957bcd92020-10-20 18:23:33 +09001638 // partitionDir is the part of the InstallPath that is automatically determined according to the context.
1639 // For example, it is host/<os>-<arch> for host modules, and target/product/<device>/<partition> for device modules.
1640 partitionDir string
1641
1642 // makePath indicates whether this path is for Soong (false) or Make (true).
1643 makePath bool
Colin Cross70dda7e2019-10-01 22:05:35 -07001644}
1645
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001646// Will panic if called from outside a test environment.
1647func ensureTestOnly() {
Martin Stjernholm32312eb2021-03-27 18:54:49 +00001648 if PrefixInList(os.Args, "-test.") {
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001649 return
1650 }
Martin Stjernholm32312eb2021-03-27 18:54:49 +00001651 panic(fmt.Errorf("Not in test. Command line:\n %s", strings.Join(os.Args, "\n ")))
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001652}
1653
1654func (p InstallPath) RelativeToTop() Path {
1655 ensureTestOnly()
1656 p.buildDir = OutSoongDir
1657 return p
1658}
1659
Paul Duffind65c58b2021-03-24 09:22:07 +00001660func (p InstallPath) getBuildDir() string {
1661 return p.buildDir
Paul Duffin9b478b02019-12-10 13:41:51 +00001662}
1663
Hans MÃ¥nssond3f2bd72020-11-27 12:37:28 +01001664func (p InstallPath) ReplaceExtension(ctx PathContext, ext string) OutputPath {
1665 panic("Not implemented")
1666}
1667
Paul Duffin9b478b02019-12-10 13:41:51 +00001668var _ Path = InstallPath{}
1669var _ WritablePath = InstallPath{}
1670
Colin Cross70dda7e2019-10-01 22:05:35 -07001671func (p InstallPath) writablePath() {}
1672
1673func (p InstallPath) String() string {
Jiyong Park957bcd92020-10-20 18:23:33 +09001674 if p.makePath {
1675 // Make path starts with out/ instead of out/soong.
Paul Duffind65c58b2021-03-24 09:22:07 +00001676 return filepath.Join(p.buildDir, "../", p.path)
Jiyong Park957bcd92020-10-20 18:23:33 +09001677 } else {
Paul Duffind65c58b2021-03-24 09:22:07 +00001678 return filepath.Join(p.buildDir, p.path)
Jiyong Park957bcd92020-10-20 18:23:33 +09001679 }
1680}
1681
1682// PartitionDir returns the path to the partition where the install path is rooted at. It is
1683// out/soong/target/product/<device>/<partition> for device modules, and out/soong/host/<os>-<arch> for host modules.
1684// The ./soong is dropped if the install path is for Make.
1685func (p InstallPath) PartitionDir() string {
1686 if p.makePath {
Paul Duffind65c58b2021-03-24 09:22:07 +00001687 return filepath.Join(p.buildDir, "../", p.partitionDir)
Jiyong Park957bcd92020-10-20 18:23:33 +09001688 } else {
Paul Duffind65c58b2021-03-24 09:22:07 +00001689 return filepath.Join(p.buildDir, p.partitionDir)
Jiyong Park957bcd92020-10-20 18:23:33 +09001690 }
Colin Cross70dda7e2019-10-01 22:05:35 -07001691}
1692
1693// Join creates a new InstallPath with paths... joined with the current path. The
1694// provided paths... may not use '..' to escape from the current path.
1695func (p InstallPath) Join(ctx PathContext, paths ...string) InstallPath {
1696 path, err := validatePath(paths...)
1697 if err != nil {
1698 reportPathError(ctx, err)
1699 }
1700 return p.withRel(path)
1701}
1702
1703func (p InstallPath) withRel(rel string) InstallPath {
1704 p.basePath = p.basePath.withRel(rel)
1705 return p
1706}
1707
Colin Crossff6c33d2019-10-02 16:01:35 -07001708// ToMakePath returns a new InstallPath that points to Make's install directory instead of Soong's,
1709// i.e. out/ instead of out/soong/.
1710func (p InstallPath) ToMakePath() InstallPath {
Jiyong Park957bcd92020-10-20 18:23:33 +09001711 p.makePath = true
Colin Crossff6c33d2019-10-02 16:01:35 -07001712 return p
Colin Cross70dda7e2019-10-01 22:05:35 -07001713}
1714
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001715// PathForModuleInstall returns a Path representing the install path for the
1716// module appended with paths...
Colin Cross70dda7e2019-10-01 22:05:35 -07001717func PathForModuleInstall(ctx ModuleInstallPathContext, pathComponents ...string) InstallPath {
Colin Cross6e359402020-02-10 15:29:54 -08001718 os := ctx.Os()
Jiyong Park87788b52020-09-01 12:37:45 +09001719 arch := ctx.Arch().ArchType
1720 forceOS, forceArch := ctx.InstallForceOS()
1721 if forceOS != nil {
Colin Cross6e359402020-02-10 15:29:54 -08001722 os = *forceOS
1723 }
Jiyong Park87788b52020-09-01 12:37:45 +09001724 if forceArch != nil {
1725 arch = *forceArch
1726 }
Colin Cross6e359402020-02-10 15:29:54 -08001727 partition := modulePartition(ctx, os)
Colin Cross609c49a2020-02-13 13:20:11 -08001728
Jiyong Park87788b52020-09-01 12:37:45 +09001729 ret := pathForInstall(ctx, os, arch, partition, ctx.Debug(), pathComponents...)
Colin Cross609c49a2020-02-13 13:20:11 -08001730
Jingwen Chencda22c92020-11-23 00:22:30 -05001731 if ctx.InstallBypassMake() && ctx.Config().KatiEnabled() {
Colin Cross609c49a2020-02-13 13:20:11 -08001732 ret = ret.ToMakePath()
1733 }
1734
1735 return ret
1736}
1737
Jiyong Park87788b52020-09-01 12:37:45 +09001738func pathForInstall(ctx PathContext, os OsType, arch ArchType, partition string, debug bool,
Colin Cross609c49a2020-02-13 13:20:11 -08001739 pathComponents ...string) InstallPath {
1740
Jiyong Park957bcd92020-10-20 18:23:33 +09001741 var partionPaths []string
Colin Cross609c49a2020-02-13 13:20:11 -08001742
Colin Cross6e359402020-02-10 15:29:54 -08001743 if os.Class == Device {
Jiyong Park957bcd92020-10-20 18:23:33 +09001744 partionPaths = []string{"target", "product", ctx.Config().DeviceName(), partition}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001745 } else {
Jiyong Park87788b52020-09-01 12:37:45 +09001746 osName := os.String()
1747 if os == Linux {
1748 // instead of linux_glibc
1749 osName = "linux"
Dan Willemsen866b5632017-09-22 12:28:24 -07001750 }
Jiyong Park87788b52020-09-01 12:37:45 +09001751 // SOONG_HOST_OUT is set to out/host/$(HOST_OS)-$(HOST_PREBUILT_ARCH)
1752 // and HOST_PREBUILT_ARCH is forcibly set to x86 even on x86_64 hosts. We don't seem
1753 // to have a plan to fix it (see the comment in build/make/core/envsetup.mk).
1754 // Let's keep using x86 for the existing cases until we have a need to support
1755 // other architectures.
1756 archName := arch.String()
1757 if os.Class == Host && (arch == X86_64 || arch == Common) {
1758 archName = "x86"
1759 }
Jiyong Park957bcd92020-10-20 18:23:33 +09001760 partionPaths = []string{"host", osName + "-" + archName, partition}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001761 }
Colin Cross609c49a2020-02-13 13:20:11 -08001762 if debug {
Jiyong Park957bcd92020-10-20 18:23:33 +09001763 partionPaths = append([]string{"debug"}, partionPaths...)
Dan Willemsen782a2d12015-12-21 14:55:28 -08001764 }
Colin Cross70dda7e2019-10-01 22:05:35 -07001765
Jiyong Park957bcd92020-10-20 18:23:33 +09001766 partionPath, err := validatePath(partionPaths...)
Colin Cross70dda7e2019-10-01 22:05:35 -07001767 if err != nil {
1768 reportPathError(ctx, err)
1769 }
Colin Crossff6c33d2019-10-02 16:01:35 -07001770
Jiyong Park957bcd92020-10-20 18:23:33 +09001771 base := InstallPath{
Paul Duffin74abc5d2021-03-24 09:24:59 +00001772 basePath: basePath{partionPath, ""},
Paul Duffind65c58b2021-03-24 09:22:07 +00001773 buildDir: ctx.Config().buildDir,
Jiyong Park957bcd92020-10-20 18:23:33 +09001774 partitionDir: partionPath,
1775 makePath: false,
1776 }
Colin Crossff6c33d2019-10-02 16:01:35 -07001777
Jiyong Park957bcd92020-10-20 18:23:33 +09001778 return base.Join(ctx, pathComponents...)
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001779}
1780
Nicolas Geoffray1228e9c2020-02-27 13:45:35 +00001781func pathForNdkOrSdkInstall(ctx PathContext, prefix string, paths []string) InstallPath {
Jiyong Park957bcd92020-10-20 18:23:33 +09001782 base := InstallPath{
Paul Duffin74abc5d2021-03-24 09:24:59 +00001783 basePath: basePath{prefix, ""},
Paul Duffind65c58b2021-03-24 09:22:07 +00001784 buildDir: ctx.Config().buildDir,
Jiyong Park957bcd92020-10-20 18:23:33 +09001785 partitionDir: prefix,
1786 makePath: false,
Colin Cross70dda7e2019-10-01 22:05:35 -07001787 }
Jiyong Park957bcd92020-10-20 18:23:33 +09001788 return base.Join(ctx, paths...)
Colin Cross70dda7e2019-10-01 22:05:35 -07001789}
1790
Nicolas Geoffray1228e9c2020-02-27 13:45:35 +00001791func PathForNdkInstall(ctx PathContext, paths ...string) InstallPath {
1792 return pathForNdkOrSdkInstall(ctx, "ndk", paths)
1793}
1794
1795func PathForMainlineSdksInstall(ctx PathContext, paths ...string) InstallPath {
1796 return pathForNdkOrSdkInstall(ctx, "mainline-sdks", paths)
1797}
1798
Colin Cross70dda7e2019-10-01 22:05:35 -07001799func InstallPathToOnDevicePath(ctx PathContext, path InstallPath) string {
Colin Cross43f08db2018-11-12 10:13:39 -08001800 rel := Rel(ctx, PathForOutput(ctx, "target", "product", ctx.Config().DeviceName()).String(), path.String())
1801
1802 return "/" + rel
1803}
1804
Colin Cross6e359402020-02-10 15:29:54 -08001805func modulePartition(ctx ModuleInstallPathContext, os OsType) string {
Colin Cross43f08db2018-11-12 10:13:39 -08001806 var partition string
Colin Cross6e359402020-02-10 15:29:54 -08001807 if ctx.InstallInTestcases() {
1808 // "testcases" install directory can be used for host or device modules.
Jaewoong Jung0949f312019-09-11 10:25:18 -07001809 partition = "testcases"
Colin Cross6e359402020-02-10 15:29:54 -08001810 } else if os.Class == Device {
1811 if ctx.InstallInData() {
1812 partition = "data"
1813 } else if ctx.InstallInRamdisk() {
1814 if ctx.DeviceConfig().BoardUsesRecoveryAsBoot() {
1815 partition = "recovery/root/first_stage_ramdisk"
1816 } else {
1817 partition = "ramdisk"
1818 }
1819 if !ctx.InstallInRoot() {
1820 partition += "/system"
1821 }
Yifan Hong60e0cfb2020-10-21 15:17:56 -07001822 } else if ctx.InstallInVendorRamdisk() {
Yifan Hong39143a92020-10-26 12:43:12 -07001823 // The module is only available after switching root into
1824 // /first_stage_ramdisk. To expose the module before switching root
1825 // on a device without a dedicated recovery partition, install the
1826 // recovery variant.
Yifan Hongdd8dacc2020-10-21 15:40:17 -07001827 if ctx.DeviceConfig().BoardMoveRecoveryResourcesToVendorBoot() {
Petri Gyntherac229562021-03-02 23:44:02 -08001828 partition = "vendor_ramdisk/first_stage_ramdisk"
Yifan Hongdd8dacc2020-10-21 15:40:17 -07001829 } else {
Petri Gyntherac229562021-03-02 23:44:02 -08001830 partition = "vendor_ramdisk"
Yifan Hongdd8dacc2020-10-21 15:40:17 -07001831 }
1832 if !ctx.InstallInRoot() {
1833 partition += "/system"
1834 }
Colin Cross6e359402020-02-10 15:29:54 -08001835 } else if ctx.InstallInRecovery() {
1836 if ctx.InstallInRoot() {
1837 partition = "recovery/root"
1838 } else {
1839 // the layout of recovery partion is the same as that of system partition
1840 partition = "recovery/root/system"
1841 }
1842 } else if ctx.SocSpecific() {
1843 partition = ctx.DeviceConfig().VendorPath()
1844 } else if ctx.DeviceSpecific() {
1845 partition = ctx.DeviceConfig().OdmPath()
1846 } else if ctx.ProductSpecific() {
1847 partition = ctx.DeviceConfig().ProductPath()
1848 } else if ctx.SystemExtSpecific() {
1849 partition = ctx.DeviceConfig().SystemExtPath()
1850 } else if ctx.InstallInRoot() {
1851 partition = "root"
Yifan Hong82db7352020-01-21 16:12:26 -08001852 } else {
Colin Cross6e359402020-02-10 15:29:54 -08001853 partition = "system"
Yifan Hong82db7352020-01-21 16:12:26 -08001854 }
Colin Cross6e359402020-02-10 15:29:54 -08001855 if ctx.InstallInSanitizerDir() {
1856 partition = "data/asan/" + partition
Yifan Hong82db7352020-01-21 16:12:26 -08001857 }
Colin Cross43f08db2018-11-12 10:13:39 -08001858 }
1859 return partition
1860}
1861
Colin Cross609c49a2020-02-13 13:20:11 -08001862type InstallPaths []InstallPath
1863
1864// Paths returns the InstallPaths as a Paths
1865func (p InstallPaths) Paths() Paths {
1866 if p == nil {
1867 return nil
1868 }
1869 ret := make(Paths, len(p))
1870 for i, path := range p {
1871 ret[i] = path
1872 }
1873 return ret
1874}
1875
1876// Strings returns the string forms of the install paths.
1877func (p InstallPaths) Strings() []string {
1878 if p == nil {
1879 return nil
1880 }
1881 ret := make([]string, len(p))
1882 for i, path := range p {
1883 ret[i] = path.String()
1884 }
1885 return ret
1886}
1887
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001888// validateSafePath validates a path that we trust (may contain ninja variables).
Dan Willemsen80a7c2a2015-12-21 14:57:11 -08001889// Ensures that each path component does not attempt to leave its component.
Colin Cross1ccfcc32018-02-22 13:54:26 -08001890func validateSafePath(pathComponents ...string) (string, error) {
Jeff Gaston734e3802017-04-10 15:47:24 -07001891 for _, path := range pathComponents {
Dan Willemsen80a7c2a2015-12-21 14:57:11 -08001892 path := filepath.Clean(path)
1893 if path == ".." || strings.HasPrefix(path, "../") || strings.HasPrefix(path, "/") {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001894 return "", fmt.Errorf("Path is outside directory: %s", path)
Dan Willemsen80a7c2a2015-12-21 14:57:11 -08001895 }
1896 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001897 // TODO: filepath.Join isn't necessarily correct with embedded ninja
1898 // variables. '..' may remove the entire ninja variable, even if it
1899 // will be expanded to multiple nested directories.
Colin Cross1ccfcc32018-02-22 13:54:26 -08001900 return filepath.Join(pathComponents...), nil
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001901}
1902
Dan Willemsen80a7c2a2015-12-21 14:57:11 -08001903// validatePath validates that a path does not include ninja variables, and that
1904// each path component does not attempt to leave its component. Returns a joined
1905// version of each path component.
Colin Cross1ccfcc32018-02-22 13:54:26 -08001906func validatePath(pathComponents ...string) (string, error) {
Jeff Gaston734e3802017-04-10 15:47:24 -07001907 for _, path := range pathComponents {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001908 if strings.Contains(path, "$") {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001909 return "", fmt.Errorf("Path contains invalid character($): %s", path)
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001910 }
1911 }
Colin Cross1ccfcc32018-02-22 13:54:26 -08001912 return validateSafePath(pathComponents...)
Colin Cross6e18ca42015-07-14 18:55:36 -07001913}
Colin Cross5b529592017-05-09 13:34:34 -07001914
Colin Cross0875c522017-11-28 17:34:01 -08001915func PathForPhony(ctx PathContext, phony string) WritablePath {
1916 if strings.ContainsAny(phony, "$/") {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001917 ReportPathErrorf(ctx, "Phony target contains invalid character ($ or /): %s", phony)
Colin Cross0875c522017-11-28 17:34:01 -08001918 }
Paul Duffin74abc5d2021-03-24 09:24:59 +00001919 return PhonyPath{basePath{phony, ""}}
Colin Cross0875c522017-11-28 17:34:01 -08001920}
1921
Colin Cross74e3fe42017-12-11 15:51:44 -08001922type PhonyPath struct {
1923 basePath
1924}
1925
1926func (p PhonyPath) writablePath() {}
1927
Paul Duffind65c58b2021-03-24 09:22:07 +00001928func (p PhonyPath) getBuildDir() string {
1929 // A phone path cannot contain any / so cannot be relative to the build directory.
1930 return ""
Paul Duffin9b478b02019-12-10 13:41:51 +00001931}
1932
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001933func (p PhonyPath) RelativeToTop() Path {
1934 ensureTestOnly()
1935 // A phony path cannot contain any / so does not have a build directory so switching to a new
1936 // build directory has no effect so just return this path.
1937 return p
1938}
1939
Hans MÃ¥nssond3f2bd72020-11-27 12:37:28 +01001940func (p PhonyPath) ReplaceExtension(ctx PathContext, ext string) OutputPath {
1941 panic("Not implemented")
1942}
1943
Colin Cross74e3fe42017-12-11 15:51:44 -08001944var _ Path = PhonyPath{}
1945var _ WritablePath = PhonyPath{}
1946
Colin Cross5b529592017-05-09 13:34:34 -07001947type testPath struct {
1948 basePath
1949}
1950
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001951func (p testPath) RelativeToTop() Path {
1952 ensureTestOnly()
1953 return p
1954}
1955
Colin Cross5b529592017-05-09 13:34:34 -07001956func (p testPath) String() string {
1957 return p.path
1958}
1959
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001960var _ Path = testPath{}
1961
Colin Cross40e33732019-02-15 11:08:35 -08001962// PathForTesting returns a Path constructed from joining the elements of paths with '/'. It should only be used from
1963// within tests.
Colin Cross5b529592017-05-09 13:34:34 -07001964func PathForTesting(paths ...string) Path {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001965 p, err := validateSafePath(paths...)
1966 if err != nil {
1967 panic(err)
1968 }
Colin Cross5b529592017-05-09 13:34:34 -07001969 return testPath{basePath{path: p, rel: p}}
1970}
1971
Colin Cross40e33732019-02-15 11:08:35 -08001972// PathsForTesting returns a Path constructed from each element in strs. It should only be used from within tests.
1973func PathsForTesting(strs ...string) Paths {
Colin Cross5b529592017-05-09 13:34:34 -07001974 p := make(Paths, len(strs))
1975 for i, s := range strs {
1976 p[i] = PathForTesting(s)
1977 }
1978
1979 return p
1980}
Colin Cross43f08db2018-11-12 10:13:39 -08001981
Colin Cross40e33732019-02-15 11:08:35 -08001982type testPathContext struct {
1983 config Config
Colin Cross40e33732019-02-15 11:08:35 -08001984}
1985
Colin Cross40e33732019-02-15 11:08:35 -08001986func (x *testPathContext) Config() Config { return x.config }
1987func (x *testPathContext) AddNinjaFileDeps(...string) {}
1988
1989// PathContextForTesting returns a PathContext that can be used in tests, for example to create an OutputPath with
1990// PathForOutput.
Colin Cross98be1bb2019-12-13 20:41:13 -08001991func PathContextForTesting(config Config) PathContext {
Colin Cross40e33732019-02-15 11:08:35 -08001992 return &testPathContext{
1993 config: config,
Colin Cross40e33732019-02-15 11:08:35 -08001994 }
1995}
1996
Ulya Trafimovichccc8c852020-10-14 11:29:07 +01001997type testModuleInstallPathContext struct {
1998 baseModuleContext
1999
2000 inData bool
2001 inTestcases bool
2002 inSanitizerDir bool
2003 inRamdisk bool
2004 inVendorRamdisk bool
2005 inRecovery bool
2006 inRoot bool
2007 forceOS *OsType
2008 forceArch *ArchType
2009}
2010
2011func (m testModuleInstallPathContext) Config() Config {
2012 return m.baseModuleContext.config
2013}
2014
2015func (testModuleInstallPathContext) AddNinjaFileDeps(deps ...string) {}
2016
2017func (m testModuleInstallPathContext) InstallInData() bool {
2018 return m.inData
2019}
2020
2021func (m testModuleInstallPathContext) InstallInTestcases() bool {
2022 return m.inTestcases
2023}
2024
2025func (m testModuleInstallPathContext) InstallInSanitizerDir() bool {
2026 return m.inSanitizerDir
2027}
2028
2029func (m testModuleInstallPathContext) InstallInRamdisk() bool {
2030 return m.inRamdisk
2031}
2032
2033func (m testModuleInstallPathContext) InstallInVendorRamdisk() bool {
2034 return m.inVendorRamdisk
2035}
2036
2037func (m testModuleInstallPathContext) InstallInRecovery() bool {
2038 return m.inRecovery
2039}
2040
2041func (m testModuleInstallPathContext) InstallInRoot() bool {
2042 return m.inRoot
2043}
2044
2045func (m testModuleInstallPathContext) InstallBypassMake() bool {
2046 return false
2047}
2048
2049func (m testModuleInstallPathContext) InstallForceOS() (*OsType, *ArchType) {
2050 return m.forceOS, m.forceArch
2051}
2052
2053// Construct a minimal ModuleInstallPathContext for testing. Note that baseModuleContext is
2054// default-initialized, which leaves blueprint.baseModuleContext set to nil, so methods that are
2055// delegated to it will panic.
2056func ModuleInstallPathContextForTesting(config Config) ModuleInstallPathContext {
2057 ctx := &testModuleInstallPathContext{}
2058 ctx.config = config
2059 ctx.os = Android
2060 return ctx
2061}
2062
Colin Cross43f08db2018-11-12 10:13:39 -08002063// Rel performs the same function as filepath.Rel, but reports errors to a PathContext, and reports an error if
2064// targetPath is not inside basePath.
2065func Rel(ctx PathContext, basePath string, targetPath string) string {
2066 rel, isRel := MaybeRel(ctx, basePath, targetPath)
2067 if !isRel {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01002068 ReportPathErrorf(ctx, "path %q is not under path %q", targetPath, basePath)
Colin Cross43f08db2018-11-12 10:13:39 -08002069 return ""
2070 }
2071 return rel
2072}
2073
2074// MaybeRel performs the same function as filepath.Rel, but reports errors to a PathContext, and returns false if
2075// targetPath is not inside basePath.
2076func MaybeRel(ctx PathContext, basePath string, targetPath string) (string, bool) {
Dan Willemsen633c5022019-04-12 11:11:38 -07002077 rel, isRel, err := maybeRelErr(basePath, targetPath)
2078 if err != nil {
2079 reportPathError(ctx, err)
2080 }
2081 return rel, isRel
2082}
2083
2084func maybeRelErr(basePath string, targetPath string) (string, bool, error) {
Colin Cross43f08db2018-11-12 10:13:39 -08002085 // filepath.Rel returns an error if one path is absolute and the other is not, handle that case first.
2086 if filepath.IsAbs(basePath) != filepath.IsAbs(targetPath) {
Dan Willemsen633c5022019-04-12 11:11:38 -07002087 return "", false, nil
Colin Cross43f08db2018-11-12 10:13:39 -08002088 }
2089 rel, err := filepath.Rel(basePath, targetPath)
2090 if err != nil {
Dan Willemsen633c5022019-04-12 11:11:38 -07002091 return "", false, err
Colin Cross43f08db2018-11-12 10:13:39 -08002092 } else if rel == ".." || strings.HasPrefix(rel, "../") || strings.HasPrefix(rel, "/") {
Dan Willemsen633c5022019-04-12 11:11:38 -07002093 return "", false, nil
Colin Cross43f08db2018-11-12 10:13:39 -08002094 }
Dan Willemsen633c5022019-04-12 11:11:38 -07002095 return rel, true, nil
Colin Cross43f08db2018-11-12 10:13:39 -08002096}
Colin Cross988414c2020-01-11 01:11:46 +00002097
2098// Writes a file to the output directory. Attempting to write directly to the output directory
2099// will fail due to the sandbox of the soong_build process.
2100func WriteFileToOutputDir(path WritablePath, data []byte, perm os.FileMode) error {
2101 return ioutil.WriteFile(absolutePath(path.String()), data, perm)
2102}
2103
Liz Kammer2dd9ca42020-11-25 16:06:39 -08002104func RemoveAllOutputDir(path WritablePath) error {
2105 return os.RemoveAll(absolutePath(path.String()))
2106}
2107
2108func CreateOutputDirIfNonexistent(path WritablePath, perm os.FileMode) error {
2109 dir := absolutePath(path.String())
2110 if _, err := os.Stat(dir); os.IsNotExist(err) {
2111 return os.MkdirAll(dir, os.ModePerm)
2112 } else {
2113 return err
2114 }
2115}
2116
Colin Cross988414c2020-01-11 01:11:46 +00002117func absolutePath(path string) string {
2118 if filepath.IsAbs(path) {
2119 return path
2120 }
2121 return filepath.Join(absSrcDir, path)
2122}
Chris Parsons216e10a2020-07-09 17:12:52 -04002123
2124// A DataPath represents the path of a file to be used as data, for example
2125// a test library to be installed alongside a test.
2126// The data file should be installed (copied from `<SrcPath>`) to
2127// `<install_root>/<RelativeInstallPath>/<filename>`, or
2128// `<install_root>/<filename>` if RelativeInstallPath is empty.
2129type DataPath struct {
2130 // The path of the data file that should be copied into the data directory
2131 SrcPath Path
2132 // The install path of the data file, relative to the install root.
2133 RelativeInstallPath string
2134}
Colin Crossdcf71b22021-02-01 13:59:03 -08002135
2136// PathsIfNonNil returns a Paths containing only the non-nil input arguments.
2137func PathsIfNonNil(paths ...Path) Paths {
2138 if len(paths) == 0 {
2139 // Fast path for empty argument list
2140 return nil
2141 } else if len(paths) == 1 {
2142 // Fast path for a single argument
2143 if paths[0] != nil {
2144 return paths
2145 } else {
2146 return nil
2147 }
2148 }
2149 ret := make(Paths, 0, len(paths))
2150 for _, path := range paths {
2151 if path != nil {
2152 ret = append(ret, path)
2153 }
2154 }
2155 if len(ret) == 0 {
2156 return nil
2157 }
2158 return ret
2159}