blob: 93c5684f361579d0682c6d3dc103d99d28ae38d2 [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 (
Colin Cross6e18ca42015-07-14 18:55:36 -070018 "fmt"
Colin Cross988414c2020-01-11 01:11:46 +000019 "io/ioutil"
20 "os"
Colin Cross6a745c62015-06-16 16:38:10 -070021 "path/filepath"
Dan Willemsen34cc69e2015-09-23 15:26:20 -070022 "reflect"
Colin Cross5e6cfbe2017-11-03 15:20:35 -070023 "sort"
Dan Willemsen34cc69e2015-09-23 15:26:20 -070024 "strings"
25
26 "github.com/google/blueprint"
27 "github.com/google/blueprint/pathtools"
Colin Cross3f40fa42015-01-30 17:27:36 -080028)
29
Colin Cross988414c2020-01-11 01:11:46 +000030var absSrcDir string
31
Dan Willemsen34cc69e2015-09-23 15:26:20 -070032// PathContext is the subset of a (Module|Singleton)Context required by the
33// Path methods.
34type PathContext interface {
Colin Crossaabf6792017-11-29 00:27:14 -080035 Config() Config
Dan Willemsen7b310ee2015-12-18 15:11:17 -080036 AddNinjaFileDeps(deps ...string)
Colin Cross3f40fa42015-01-30 17:27:36 -080037}
38
Colin Cross7f19f372016-11-01 11:10:25 -070039type PathGlobContext interface {
40 GlobWithDeps(globPattern string, excludes []string) ([]string, error)
41}
42
Colin Crossaabf6792017-11-29 00:27:14 -080043var _ PathContext = SingletonContext(nil)
44var _ PathContext = ModuleContext(nil)
Dan Willemsen34cc69e2015-09-23 15:26:20 -070045
Ulya Trafimovich8640ab92020-05-11 18:06:15 +010046// "Null" path context is a minimal path context for a given config.
47type NullPathContext struct {
48 config Config
49}
50
51func (NullPathContext) AddNinjaFileDeps(...string) {}
52func (ctx NullPathContext) Config() Config { return ctx.config }
53
Liz Kammera830f3a2020-11-10 10:50:34 -080054// EarlyModulePathContext is a subset of EarlyModuleContext methods required by the
55// Path methods. These path methods can be called before any mutators have run.
56type EarlyModulePathContext interface {
57 PathContext
58 PathGlobContext
59
60 ModuleDir() string
61 ModuleErrorf(fmt string, args ...interface{})
62}
63
64var _ EarlyModulePathContext = ModuleContext(nil)
65
66// Glob globs files and directories matching globPattern relative to ModuleDir(),
67// paths in the excludes parameter will be omitted.
68func Glob(ctx EarlyModulePathContext, globPattern string, excludes []string) Paths {
69 ret, err := ctx.GlobWithDeps(globPattern, excludes)
70 if err != nil {
71 ctx.ModuleErrorf("glob: %s", err.Error())
72 }
73 return pathsForModuleSrcFromFullPath(ctx, ret, true)
74}
75
76// GlobFiles globs *only* files (not directories) matching globPattern relative to ModuleDir().
77// Paths in the excludes parameter will be omitted.
78func GlobFiles(ctx EarlyModulePathContext, globPattern string, excludes []string) Paths {
79 ret, err := ctx.GlobWithDeps(globPattern, excludes)
80 if err != nil {
81 ctx.ModuleErrorf("glob: %s", err.Error())
82 }
83 return pathsForModuleSrcFromFullPath(ctx, ret, false)
84}
85
86// ModuleWithDepsPathContext is a subset of *ModuleContext methods required by
87// the Path methods that rely on module dependencies having been resolved.
88type ModuleWithDepsPathContext interface {
89 EarlyModulePathContext
90 GetDirectDepWithTag(name string, tag blueprint.DependencyTag) blueprint.Module
91}
92
93// ModuleMissingDepsPathContext is a subset of *ModuleContext methods required by
94// the Path methods that rely on module dependencies having been resolved and ability to report
95// missing dependency errors.
96type ModuleMissingDepsPathContext interface {
97 ModuleWithDepsPathContext
98 AddMissingDependencies(missingDeps []string)
99}
100
Dan Willemsen00269f22017-07-06 16:59:48 -0700101type ModuleInstallPathContext interface {
Colin Cross0ea8ba82019-06-06 14:33:29 -0700102 BaseModuleContext
Dan Willemsen00269f22017-07-06 16:59:48 -0700103
104 InstallInData() bool
Jaewoong Jung0949f312019-09-11 10:25:18 -0700105 InstallInTestcases() bool
Dan Willemsen00269f22017-07-06 16:59:48 -0700106 InstallInSanitizerDir() bool
Yifan Hong1b3348d2020-01-21 15:53:22 -0800107 InstallInRamdisk() bool
Yifan Hong60e0cfb2020-10-21 15:17:56 -0700108 InstallInVendorRamdisk() bool
Jiyong Parkf9332f12018-02-01 00:54:12 +0900109 InstallInRecovery() bool
Colin Cross90ba5f42019-10-02 11:10:58 -0700110 InstallInRoot() bool
Colin Cross607d8582019-07-29 16:44:46 -0700111 InstallBypassMake() bool
Jiyong Park87788b52020-09-01 12:37:45 +0900112 InstallForceOS() (*OsType, *ArchType)
Dan Willemsen00269f22017-07-06 16:59:48 -0700113}
114
115var _ ModuleInstallPathContext = ModuleContext(nil)
116
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700117// errorfContext is the interface containing the Errorf method matching the
118// Errorf method in blueprint.SingletonContext.
119type errorfContext interface {
120 Errorf(format string, args ...interface{})
Colin Cross3f40fa42015-01-30 17:27:36 -0800121}
122
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700123var _ errorfContext = blueprint.SingletonContext(nil)
124
125// moduleErrorf is the interface containing the ModuleErrorf method matching
126// the ModuleErrorf method in blueprint.ModuleContext.
127type moduleErrorf interface {
128 ModuleErrorf(format string, args ...interface{})
Colin Cross3f40fa42015-01-30 17:27:36 -0800129}
130
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700131var _ moduleErrorf = blueprint.ModuleContext(nil)
132
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700133// reportPathError will register an error with the attached context. It
134// attempts ctx.ModuleErrorf for a better error message first, then falls
135// back to ctx.Errorf.
Colin Cross1ccfcc32018-02-22 13:54:26 -0800136func reportPathError(ctx PathContext, err error) {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +0100137 ReportPathErrorf(ctx, "%s", err.Error())
Colin Cross1ccfcc32018-02-22 13:54:26 -0800138}
139
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +0100140// ReportPathErrorf will register an error with the attached context. It
Colin Cross1ccfcc32018-02-22 13:54:26 -0800141// attempts ctx.ModuleErrorf for a better error message first, then falls
142// back to ctx.Errorf.
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +0100143func ReportPathErrorf(ctx PathContext, format string, args ...interface{}) {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700144 if mctx, ok := ctx.(moduleErrorf); ok {
145 mctx.ModuleErrorf(format, args...)
146 } else if ectx, ok := ctx.(errorfContext); ok {
147 ectx.Errorf(format, args...)
148 } else {
149 panic(fmt.Sprintf(format, args...))
Colin Crossf2298272015-05-12 11:36:53 -0700150 }
151}
152
Colin Cross5e708052019-08-06 13:59:50 -0700153func pathContextName(ctx PathContext, module blueprint.Module) string {
154 if x, ok := ctx.(interface{ ModuleName(blueprint.Module) string }); ok {
155 return x.ModuleName(module)
156 } else if x, ok := ctx.(interface{ OtherModuleName(blueprint.Module) string }); ok {
157 return x.OtherModuleName(module)
158 }
159 return "unknown"
160}
161
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700162type Path interface {
163 // Returns the path in string form
164 String() string
165
Colin Cross4f6fc9c2016-10-26 10:05:25 -0700166 // Ext returns the extension of the last element of the path
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700167 Ext() string
Colin Cross4f6fc9c2016-10-26 10:05:25 -0700168
169 // Base returns the last element of the path
170 Base() string
Colin Crossfaeb7aa2017-02-01 14:12:44 -0800171
172 // Rel returns the portion of the path relative to the directory it was created from. For
173 // example, Rel on a PathsForModuleSrc would return the path relative to the module source
Colin Cross0db55682017-12-05 15:36:55 -0800174 // directory, and OutputPath.Join("foo").Rel() would return "foo".
Colin Crossfaeb7aa2017-02-01 14:12:44 -0800175 Rel() string
Paul Duffin85d8f0d2021-03-24 10:18:18 +0000176
177 // RelativeToTop returns a new path relative to the top, it is provided solely for use in tests.
178 //
179 // It is guaranteed to always return the same type as it is called on, e.g. if called on an
180 // InstallPath then the returned value can be converted to an InstallPath.
181 //
182 // A standard build has the following structure:
183 // ../top/
184 // out/ - make install files go here.
185 // out/soong - this is the buildDir passed to NewTestConfig()
186 // ... - the source files
187 //
188 // This function converts a path so that it appears relative to the ../top/ directory, i.e.
189 // * Make install paths, which have the pattern "buildDir/../<path>" are converted into the top
190 // relative path "out/<path>"
191 // * Soong install paths and other writable paths, which have the pattern "buildDir/<path>" are
192 // converted into the top relative path "out/soong/<path>".
193 // * Source paths are already relative to the top.
194 // * Phony paths are not relative to anything.
195 // * toolDepPath have an absolute but known value in so don't need making relative to anything in
196 // order to test.
197 RelativeToTop() Path
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700198}
199
Paul Duffin85d8f0d2021-03-24 10:18:18 +0000200const (
201 OutDir = "out"
202 OutSoongDir = OutDir + "/soong"
203)
204
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700205// WritablePath is a type of path that can be used as an output for build rules.
206type WritablePath interface {
207 Path
208
Paul Duffin9b478b02019-12-10 13:41:51 +0000209 // return the path to the build directory.
Paul Duffind65c58b2021-03-24 09:22:07 +0000210 getBuildDir() string
Paul Duffin9b478b02019-12-10 13:41:51 +0000211
Jeff Gaston734e3802017-04-10 15:47:24 -0700212 // the writablePath method doesn't directly do anything,
213 // but it allows a struct to distinguish between whether or not it implements the WritablePath interface
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700214 writablePath()
Hans MÃ¥nssond3f2bd72020-11-27 12:37:28 +0100215
216 ReplaceExtension(ctx PathContext, ext string) OutputPath
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700217}
218
219type genPathProvider interface {
Liz Kammera830f3a2020-11-10 10:50:34 -0800220 genPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleGenPath
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700221}
222type objPathProvider interface {
Liz Kammera830f3a2020-11-10 10:50:34 -0800223 objPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleObjPath
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700224}
225type resPathProvider interface {
Liz Kammera830f3a2020-11-10 10:50:34 -0800226 resPathWithName(ctx ModuleOutPathContext, name string) ModuleResPath
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700227}
228
229// GenPathWithExt derives a new file path in ctx's generated sources directory
230// from the current path, but with the new extension.
Liz Kammera830f3a2020-11-10 10:50:34 -0800231func GenPathWithExt(ctx ModuleOutPathContext, subdir string, p Path, ext string) ModuleGenPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700232 if path, ok := p.(genPathProvider); ok {
Dan Willemsen21ec4902016-11-02 20:43:13 -0700233 return path.genPathWithExt(ctx, subdir, ext)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700234 }
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +0100235 ReportPathErrorf(ctx, "Tried to create generated file from unsupported path: %s(%s)", reflect.TypeOf(p).Name(), p)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700236 return PathForModuleGen(ctx)
237}
238
239// ObjPathWithExt derives a new file path in ctx's object directory from the
240// current path, but with the new extension.
Liz Kammera830f3a2020-11-10 10:50:34 -0800241func ObjPathWithExt(ctx ModuleOutPathContext, subdir string, p Path, ext string) ModuleObjPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700242 if path, ok := p.(objPathProvider); ok {
243 return path.objPathWithExt(ctx, subdir, ext)
244 }
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +0100245 ReportPathErrorf(ctx, "Tried to create object file from unsupported path: %s (%s)", reflect.TypeOf(p).Name(), p)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700246 return PathForModuleObj(ctx)
247}
248
249// ResPathWithName derives a new path in ctx's output resource directory, using
250// the current path to create the directory name, and the `name` argument for
251// the filename.
Liz Kammera830f3a2020-11-10 10:50:34 -0800252func ResPathWithName(ctx ModuleOutPathContext, p Path, name string) ModuleResPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700253 if path, ok := p.(resPathProvider); ok {
254 return path.resPathWithName(ctx, name)
255 }
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +0100256 ReportPathErrorf(ctx, "Tried to create res file from unsupported path: %s (%s)", reflect.TypeOf(p).Name(), p)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700257 return PathForModuleRes(ctx)
258}
259
260// OptionalPath is a container that may or may not contain a valid Path.
261type OptionalPath struct {
262 valid bool
263 path Path
264}
265
266// OptionalPathForPath returns an OptionalPath containing the path.
267func OptionalPathForPath(path Path) OptionalPath {
268 if path == nil {
269 return OptionalPath{}
270 }
271 return OptionalPath{valid: true, path: path}
272}
273
274// Valid returns whether there is a valid path
275func (p OptionalPath) Valid() bool {
276 return p.valid
277}
278
279// Path returns the Path embedded in this OptionalPath. You must be sure that
280// there is a valid path, since this method will panic if there is not.
281func (p OptionalPath) Path() Path {
282 if !p.valid {
283 panic("Requesting an invalid path")
284 }
285 return p.path
286}
287
Paul Duffinafdd4062021-03-30 19:44:07 +0100288// RelativeToTop returns an OptionalPath with the path that was embedded having been replaced by the
289// result of calling Path.RelativeToTop on it.
290func (p OptionalPath) RelativeToTop() OptionalPath {
Paul Duffina5b81352021-03-28 23:57:19 +0100291 if !p.valid {
292 return p
293 }
294 p.path = p.path.RelativeToTop()
295 return p
296}
297
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700298// String returns the string version of the Path, or "" if it isn't valid.
299func (p OptionalPath) String() string {
300 if p.valid {
301 return p.path.String()
302 } else {
303 return ""
Colin Crossf2298272015-05-12 11:36:53 -0700304 }
305}
Colin Cross6e18ca42015-07-14 18:55:36 -0700306
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700307// Paths is a slice of Path objects, with helpers to operate on the collection.
308type Paths []Path
309
Paul Duffin85d8f0d2021-03-24 10:18:18 +0000310// RelativeToTop creates a new Paths containing the result of calling Path.RelativeToTop on each
311// item in this slice.
312func (p Paths) RelativeToTop() Paths {
313 ensureTestOnly()
314 if p == nil {
315 return p
316 }
317 ret := make(Paths, len(p))
318 for i, path := range p {
319 ret[i] = path.RelativeToTop()
320 }
321 return ret
322}
323
Jingwen Chen40fd90a2020-06-15 05:24:19 +0000324func (paths Paths) containsPath(path Path) bool {
325 for _, p := range paths {
326 if p == path {
327 return true
328 }
329 }
330 return false
331}
332
Liz Kammer7aa52882021-02-11 09:16:14 -0500333// PathsForSource returns Paths rooted from SrcDir, *not* rooted from the module's local source
334// directory
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700335func PathsForSource(ctx PathContext, paths []string) Paths {
336 ret := make(Paths, len(paths))
337 for i, path := range paths {
338 ret[i] = PathForSource(ctx, path)
339 }
340 return ret
341}
342
Liz Kammer7aa52882021-02-11 09:16:14 -0500343// ExistentPathsForSources returns a list of Paths rooted from SrcDir, *not* rooted from the
344// module's local source directory, that are found in the tree. If any are not found, they are
345// 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 -0800346func ExistentPathsForSources(ctx PathContext, paths []string) Paths {
Dan Willemsen7b310ee2015-12-18 15:11:17 -0800347 ret := make(Paths, 0, len(paths))
348 for _, path := range paths {
Colin Cross32f38982018-02-22 11:47:25 -0800349 p := ExistentPathForSource(ctx, path)
Dan Willemsen7b310ee2015-12-18 15:11:17 -0800350 if p.Valid() {
351 ret = append(ret, p.Path())
352 }
353 }
354 return ret
355}
356
Liz Kammer620dea62021-04-14 17:36:10 -0400357// PathsForModuleSrc returns a Paths{} containing the resolved references in paths:
358// * filepath, relative to local module directory, resolves as a filepath relative to the local
359// source directory
360// * glob, relative to the local module directory, resolves as filepath(s), relative to the local
361// source directory.
362// * other modules using the ":name{.tag}" syntax. These modules must implement SourceFileProducer
363// or OutputFileProducer. These resolve as a filepath to an output filepath or generated source
364// filepath.
365// Properties passed as the paths argument must have been annotated with struct tag
Colin Cross41955e82019-05-29 14:40:35 -0700366// `android:"path"` so that dependencies on SourceFileProducer modules will have already been handled by the
Liz Kammer620dea62021-04-14 17:36:10 -0400367// path_deps mutator.
368// If a requested module is not found as a dependency:
369// * if ctx.Config().AllowMissingDependencies() is true, this module to be marked as having
370// missing dependencies
371// * otherwise, a ModuleError is thrown.
Liz Kammera830f3a2020-11-10 10:50:34 -0800372func PathsForModuleSrc(ctx ModuleMissingDepsPathContext, paths []string) Paths {
Colin Cross8a497952019-03-05 22:25:09 -0800373 return PathsForModuleSrcExcludes(ctx, paths, nil)
374}
375
Liz Kammer620dea62021-04-14 17:36:10 -0400376// PathsForModuleSrcExcludes returns a Paths{} containing the resolved references in paths, minus
377// those listed in excludes. Elements of paths and excludes are resolved as:
378// * filepath, relative to local module directory, resolves as a filepath relative to the local
379// source directory
380// * glob, relative to the local module directory, resolves as filepath(s), relative to the local
381// source directory. Not valid in excludes.
382// * other modules using the ":name{.tag}" syntax. These modules must implement SourceFileProducer
383// or OutputFileProducer. These resolve as a filepath to an output filepath or generated source
384// filepath.
385// excluding the items (similarly resolved
386// Properties passed as the paths argument must have been annotated with struct tag
387// `android:"path"` so that dependencies on SourceFileProducer modules will have already been handled by the
388// path_deps mutator.
389// If a requested module is not found as a dependency:
390// * if ctx.Config().AllowMissingDependencies() is true, this module to be marked as having
391// missing dependencies
392// * otherwise, a ModuleError is thrown.
Liz Kammera830f3a2020-11-10 10:50:34 -0800393func PathsForModuleSrcExcludes(ctx ModuleMissingDepsPathContext, paths, excludes []string) Paths {
Colin Crossba71a3f2019-03-18 12:12:48 -0700394 ret, missingDeps := PathsAndMissingDepsForModuleSrcExcludes(ctx, paths, excludes)
395 if ctx.Config().AllowMissingDependencies() {
396 ctx.AddMissingDependencies(missingDeps)
397 } else {
398 for _, m := range missingDeps {
399 ctx.ModuleErrorf(`missing dependency on %q, is the property annotated with android:"path"?`, m)
400 }
401 }
402 return ret
403}
404
Ulya Trafimovich4d2eeed2019-11-08 10:54:21 +0000405// OutputPaths is a slice of OutputPath objects, with helpers to operate on the collection.
406type OutputPaths []OutputPath
407
408// Paths returns the OutputPaths as a Paths
409func (p OutputPaths) Paths() Paths {
410 if p == nil {
411 return nil
412 }
413 ret := make(Paths, len(p))
414 for i, path := range p {
415 ret[i] = path
416 }
417 return ret
418}
419
420// Strings returns the string forms of the writable paths.
421func (p OutputPaths) Strings() []string {
422 if p == nil {
423 return nil
424 }
425 ret := make([]string, len(p))
426 for i, path := range p {
427 ret[i] = path.String()
428 }
429 return ret
430}
431
Liz Kammera830f3a2020-11-10 10:50:34 -0800432// Expands Paths to a SourceFileProducer or OutputFileProducer module dependency referenced via ":name" or ":name{.tag}" syntax.
433// If the dependency is not found, a missingErrorDependency is returned.
434// If the module dependency is not a SourceFileProducer or OutputFileProducer, appropriate errors will be returned.
435func getPathsFromModuleDep(ctx ModuleWithDepsPathContext, path, moduleName, tag string) (Paths, error) {
436 module := ctx.GetDirectDepWithTag(moduleName, sourceOrOutputDepTag(tag))
437 if module == nil {
438 return nil, missingDependencyError{[]string{moduleName}}
439 }
Colin Crossfa65cee2021-03-22 17:05:59 -0700440 if aModule, ok := module.(Module); ok && !aModule.Enabled() {
441 return nil, missingDependencyError{[]string{moduleName}}
442 }
Liz Kammera830f3a2020-11-10 10:50:34 -0800443 if outProducer, ok := module.(OutputFileProducer); ok {
444 outputFiles, err := outProducer.OutputFiles(tag)
445 if err != nil {
446 return nil, fmt.Errorf("path dependency %q: %s", path, err)
447 }
448 return outputFiles, nil
449 } else if tag != "" {
450 return nil, fmt.Errorf("path dependency %q is not an output file producing module", path)
451 } else if srcProducer, ok := module.(SourceFileProducer); ok {
452 return srcProducer.Srcs(), nil
453 } else {
454 return nil, fmt.Errorf("path dependency %q is not a source file producing module", path)
455 }
456}
457
Liz Kammer620dea62021-04-14 17:36:10 -0400458// PathsAndMissingDepsForModuleSrcExcludes returns a Paths{} containing the resolved references in
459// paths, minus those listed in excludes. Elements of paths and excludes are resolved as:
460// * filepath, relative to local module directory, resolves as a filepath relative to the local
461// source directory
462// * glob, relative to the local module directory, resolves as filepath(s), relative to the local
463// source directory. Not valid in excludes.
464// * other modules using the ":name{.tag}" syntax. These modules must implement SourceFileProducer
465// or OutputFileProducer. These resolve as a filepath to an output filepath or generated source
466// filepath.
467// and a list of the module names of missing module dependencies are returned as the second return.
468// Properties passed as the paths argument must have been annotated with struct tag
Colin Cross41955e82019-05-29 14:40:35 -0700469// `android:"path"` so that dependencies on SourceFileProducer modules will have already been handled by the
Liz Kammer620dea62021-04-14 17:36:10 -0400470// path_deps mutator.
Liz Kammera830f3a2020-11-10 10:50:34 -0800471func PathsAndMissingDepsForModuleSrcExcludes(ctx ModuleWithDepsPathContext, paths, excludes []string) (Paths, []string) {
Colin Cross8a497952019-03-05 22:25:09 -0800472 prefix := pathForModuleSrc(ctx).String()
473
474 var expandedExcludes []string
475 if excludes != nil {
476 expandedExcludes = make([]string, 0, len(excludes))
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700477 }
Colin Cross8a497952019-03-05 22:25:09 -0800478
Colin Crossba71a3f2019-03-18 12:12:48 -0700479 var missingExcludeDeps []string
480
Colin Cross8a497952019-03-05 22:25:09 -0800481 for _, e := range excludes {
Colin Cross41955e82019-05-29 14:40:35 -0700482 if m, t := SrcIsModuleWithTag(e); m != "" {
Liz Kammera830f3a2020-11-10 10:50:34 -0800483 modulePaths, err := getPathsFromModuleDep(ctx, e, m, t)
484 if m, ok := err.(missingDependencyError); ok {
485 missingExcludeDeps = append(missingExcludeDeps, m.missingDeps...)
486 } else if err != nil {
487 reportPathError(ctx, err)
Colin Cross8a497952019-03-05 22:25:09 -0800488 } else {
Liz Kammera830f3a2020-11-10 10:50:34 -0800489 expandedExcludes = append(expandedExcludes, modulePaths.Strings()...)
Colin Cross8a497952019-03-05 22:25:09 -0800490 }
491 } else {
492 expandedExcludes = append(expandedExcludes, filepath.Join(prefix, e))
493 }
494 }
495
496 if paths == nil {
Colin Crossba71a3f2019-03-18 12:12:48 -0700497 return nil, missingExcludeDeps
Colin Cross8a497952019-03-05 22:25:09 -0800498 }
499
Colin Crossba71a3f2019-03-18 12:12:48 -0700500 var missingDeps []string
501
Colin Cross8a497952019-03-05 22:25:09 -0800502 expandedSrcFiles := make(Paths, 0, len(paths))
503 for _, s := range paths {
504 srcFiles, err := expandOneSrcPath(ctx, s, expandedExcludes)
505 if depErr, ok := err.(missingDependencyError); ok {
Colin Crossba71a3f2019-03-18 12:12:48 -0700506 missingDeps = append(missingDeps, depErr.missingDeps...)
Colin Cross8a497952019-03-05 22:25:09 -0800507 } else if err != nil {
508 reportPathError(ctx, err)
509 }
510 expandedSrcFiles = append(expandedSrcFiles, srcFiles...)
511 }
Colin Crossba71a3f2019-03-18 12:12:48 -0700512
513 return expandedSrcFiles, append(missingDeps, missingExcludeDeps...)
Colin Cross8a497952019-03-05 22:25:09 -0800514}
515
516type missingDependencyError struct {
517 missingDeps []string
518}
519
520func (e missingDependencyError) Error() string {
521 return "missing dependencies: " + strings.Join(e.missingDeps, ", ")
522}
523
Liz Kammera830f3a2020-11-10 10:50:34 -0800524// Expands one path string to Paths rooted from the module's local source
525// directory, excluding those listed in the expandedExcludes.
526// Expands globs, references to SourceFileProducer or OutputFileProducer modules using the ":name" and ":name{.tag}" syntax.
527func expandOneSrcPath(ctx ModuleWithDepsPathContext, sPath string, expandedExcludes []string) (Paths, error) {
Jooyung Han7607dd32020-07-05 10:23:14 +0900528 excludePaths := func(paths Paths) Paths {
529 if len(expandedExcludes) == 0 {
530 return paths
531 }
532 remainder := make(Paths, 0, len(paths))
533 for _, p := range paths {
534 if !InList(p.String(), expandedExcludes) {
535 remainder = append(remainder, p)
536 }
537 }
538 return remainder
539 }
Liz Kammera830f3a2020-11-10 10:50:34 -0800540 if m, t := SrcIsModuleWithTag(sPath); m != "" {
541 modulePaths, err := getPathsFromModuleDep(ctx, sPath, m, t)
542 if err != nil {
543 return nil, err
Colin Cross8a497952019-03-05 22:25:09 -0800544 } else {
Liz Kammera830f3a2020-11-10 10:50:34 -0800545 return excludePaths(modulePaths), nil
Colin Cross8a497952019-03-05 22:25:09 -0800546 }
Liz Kammera830f3a2020-11-10 10:50:34 -0800547 } else if pathtools.IsGlob(sPath) {
548 paths := GlobFiles(ctx, pathForModuleSrc(ctx, sPath).String(), expandedExcludes)
Colin Cross8a497952019-03-05 22:25:09 -0800549 return PathsWithModuleSrcSubDir(ctx, paths, ""), nil
550 } else {
Liz Kammera830f3a2020-11-10 10:50:34 -0800551 p := pathForModuleSrc(ctx, sPath)
Colin Cross988414c2020-01-11 01:11:46 +0000552 if exists, _, err := ctx.Config().fs.Exists(p.String()); err != nil {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +0100553 ReportPathErrorf(ctx, "%s: %s", p, err.Error())
Pedro Loureiro5d190cc2021-02-15 15:41:33 +0000554 } else if !exists && !ctx.Config().TestAllowNonExistentPaths {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +0100555 ReportPathErrorf(ctx, "module source path %q does not exist", p)
Colin Cross8a497952019-03-05 22:25:09 -0800556 }
557
Jooyung Han7607dd32020-07-05 10:23:14 +0900558 if InList(p.String(), expandedExcludes) {
Colin Cross8a497952019-03-05 22:25:09 -0800559 return nil, nil
560 }
561 return Paths{p}, nil
562 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700563}
564
565// pathsForModuleSrcFromFullPath returns Paths rooted from the module's local
566// source directory, but strip the local source directory from the beginning of
Dan Willemsen540a78c2018-02-26 21:50:08 -0800567// each string. If incDirs is false, strip paths with a trailing '/' from the list.
Colin Crossfe4bc362018-09-12 10:02:13 -0700568// It intended for use in globs that only list files that exist, so it allows '$' in
569// filenames.
Liz Kammera830f3a2020-11-10 10:50:34 -0800570func pathsForModuleSrcFromFullPath(ctx EarlyModulePathContext, paths []string, incDirs bool) Paths {
Colin Cross6510f912017-11-29 00:27:14 -0800571 prefix := filepath.Join(ctx.Config().srcDir, ctx.ModuleDir()) + "/"
Colin Cross0f37af02017-09-27 17:42:05 -0700572 if prefix == "./" {
573 prefix = ""
574 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700575 ret := make(Paths, 0, len(paths))
576 for _, p := range paths {
Dan Willemsen540a78c2018-02-26 21:50:08 -0800577 if !incDirs && strings.HasSuffix(p, "/") {
578 continue
579 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700580 path := filepath.Clean(p)
581 if !strings.HasPrefix(path, prefix) {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +0100582 ReportPathErrorf(ctx, "Path %q is not in module source directory %q", p, prefix)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700583 continue
584 }
Colin Crosse3924e12018-08-15 20:18:53 -0700585
Colin Crossfe4bc362018-09-12 10:02:13 -0700586 srcPath, err := safePathForSource(ctx, ctx.ModuleDir(), path[len(prefix):])
Colin Crosse3924e12018-08-15 20:18:53 -0700587 if err != nil {
588 reportPathError(ctx, err)
589 continue
590 }
591
Colin Cross07e51612019-03-05 12:46:40 -0800592 srcPath.basePath.rel = srcPath.path
Colin Crosse3924e12018-08-15 20:18:53 -0700593
Colin Cross07e51612019-03-05 12:46:40 -0800594 ret = append(ret, srcPath)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700595 }
596 return ret
597}
598
Liz Kammera830f3a2020-11-10 10:50:34 -0800599// PathsWithOptionalDefaultForModuleSrc returns Paths rooted from the module's local source
600// directory. If input is nil, use the default if it exists. If input is empty, returns nil.
601func PathsWithOptionalDefaultForModuleSrc(ctx ModuleMissingDepsPathContext, input []string, def string) Paths {
Colin Cross0ddae7f2019-02-07 15:30:01 -0800602 if input != nil {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700603 return PathsForModuleSrc(ctx, input)
604 }
605 // Use Glob so that if the default doesn't exist, a dependency is added so that when it
606 // is created, we're run again.
Colin Cross6510f912017-11-29 00:27:14 -0800607 path := filepath.Join(ctx.Config().srcDir, ctx.ModuleDir(), def)
Liz Kammera830f3a2020-11-10 10:50:34 -0800608 return Glob(ctx, path, nil)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700609}
610
611// Strings returns the Paths in string form
612func (p Paths) Strings() []string {
613 if p == nil {
614 return nil
615 }
616 ret := make([]string, len(p))
617 for i, path := range p {
618 ret[i] = path.String()
619 }
620 return ret
621}
622
Colin Crossc0efd1d2020-07-03 11:56:24 -0700623func CopyOfPaths(paths Paths) Paths {
624 return append(Paths(nil), paths...)
625}
626
Colin Crossb6715442017-10-24 11:13:31 -0700627// FirstUniquePaths returns all unique elements of a Paths, keeping the first copy of each. It
628// modifies the Paths slice contents in place, and returns a subslice of the original slice.
Dan Willemsenfe92c962017-08-29 12:28:37 -0700629func FirstUniquePaths(list Paths) Paths {
Colin Cross27027c72020-02-28 15:34:17 -0800630 // 128 was chosen based on BenchmarkFirstUniquePaths results.
631 if len(list) > 128 {
632 return firstUniquePathsMap(list)
633 }
634 return firstUniquePathsList(list)
635}
636
Colin Crossc0efd1d2020-07-03 11:56:24 -0700637// SortedUniquePaths returns all unique elements of a Paths in sorted order. It modifies the
638// Paths slice contents in place, and returns a subslice of the original slice.
Jiyong Park33c77362020-05-29 22:00:16 +0900639func SortedUniquePaths(list Paths) Paths {
640 unique := FirstUniquePaths(list)
641 sort.Slice(unique, func(i, j int) bool {
642 return unique[i].String() < unique[j].String()
643 })
644 return unique
645}
646
Colin Cross27027c72020-02-28 15:34:17 -0800647func firstUniquePathsList(list Paths) Paths {
Dan Willemsenfe92c962017-08-29 12:28:37 -0700648 k := 0
649outer:
650 for i := 0; i < len(list); i++ {
651 for j := 0; j < k; j++ {
652 if list[i] == list[j] {
653 continue outer
654 }
655 }
656 list[k] = list[i]
657 k++
658 }
659 return list[:k]
660}
661
Colin Cross27027c72020-02-28 15:34:17 -0800662func firstUniquePathsMap(list Paths) Paths {
663 k := 0
664 seen := make(map[Path]bool, len(list))
665 for i := 0; i < len(list); i++ {
666 if seen[list[i]] {
667 continue
668 }
669 seen[list[i]] = true
670 list[k] = list[i]
671 k++
672 }
673 return list[:k]
674}
675
Colin Cross5d583952020-11-24 16:21:24 -0800676// FirstUniqueInstallPaths returns all unique elements of an InstallPaths, keeping the first copy of each. It
677// modifies the InstallPaths slice contents in place, and returns a subslice of the original slice.
678func FirstUniqueInstallPaths(list InstallPaths) InstallPaths {
679 // 128 was chosen based on BenchmarkFirstUniquePaths results.
680 if len(list) > 128 {
681 return firstUniqueInstallPathsMap(list)
682 }
683 return firstUniqueInstallPathsList(list)
684}
685
686func firstUniqueInstallPathsList(list InstallPaths) InstallPaths {
687 k := 0
688outer:
689 for i := 0; i < len(list); i++ {
690 for j := 0; j < k; j++ {
691 if list[i] == list[j] {
692 continue outer
693 }
694 }
695 list[k] = list[i]
696 k++
697 }
698 return list[:k]
699}
700
701func firstUniqueInstallPathsMap(list InstallPaths) InstallPaths {
702 k := 0
703 seen := make(map[InstallPath]bool, len(list))
704 for i := 0; i < len(list); i++ {
705 if seen[list[i]] {
706 continue
707 }
708 seen[list[i]] = true
709 list[k] = list[i]
710 k++
711 }
712 return list[:k]
713}
714
Colin Crossb6715442017-10-24 11:13:31 -0700715// LastUniquePaths returns all unique elements of a Paths, keeping the last copy of each. It
716// modifies the Paths slice contents in place, and returns a subslice of the original slice.
717func LastUniquePaths(list Paths) Paths {
718 totalSkip := 0
719 for i := len(list) - 1; i >= totalSkip; i-- {
720 skip := 0
721 for j := i - 1; j >= totalSkip; j-- {
722 if list[i] == list[j] {
723 skip++
724 } else {
725 list[j+skip] = list[j]
726 }
727 }
728 totalSkip += skip
729 }
730 return list[totalSkip:]
731}
732
Colin Crossa140bb02018-04-17 10:52:26 -0700733// ReversePaths returns a copy of a Paths in reverse order.
734func ReversePaths(list Paths) Paths {
735 if list == nil {
736 return nil
737 }
738 ret := make(Paths, len(list))
739 for i := range list {
740 ret[i] = list[len(list)-1-i]
741 }
742 return ret
743}
744
Jeff Gaston294356f2017-09-27 17:05:30 -0700745func indexPathList(s Path, list []Path) int {
746 for i, l := range list {
747 if l == s {
748 return i
749 }
750 }
751
752 return -1
753}
754
755func inPathList(p Path, list []Path) bool {
756 return indexPathList(p, list) != -1
757}
758
759func FilterPathList(list []Path, filter []Path) (remainder []Path, filtered []Path) {
Paul Duffin57b9e1d2019-12-13 00:03:35 +0000760 return FilterPathListPredicate(list, func(p Path) bool { return inPathList(p, filter) })
761}
762
763func FilterPathListPredicate(list []Path, predicate func(Path) bool) (remainder []Path, filtered []Path) {
Jeff Gaston294356f2017-09-27 17:05:30 -0700764 for _, l := range list {
Paul Duffin57b9e1d2019-12-13 00:03:35 +0000765 if predicate(l) {
Jeff Gaston294356f2017-09-27 17:05:30 -0700766 filtered = append(filtered, l)
767 } else {
768 remainder = append(remainder, l)
769 }
770 }
771
772 return
773}
774
Colin Cross93e85952017-08-15 13:34:18 -0700775// HasExt returns true of any of the paths have extension ext, otherwise false
776func (p Paths) HasExt(ext string) bool {
777 for _, path := range p {
778 if path.Ext() == ext {
779 return true
780 }
781 }
782
783 return false
784}
785
786// FilterByExt returns the subset of the paths that have extension ext
787func (p Paths) FilterByExt(ext string) Paths {
788 ret := make(Paths, 0, len(p))
789 for _, path := range p {
790 if path.Ext() == ext {
791 ret = append(ret, path)
792 }
793 }
794 return ret
795}
796
797// FilterOutByExt returns the subset of the paths that do not have extension ext
798func (p Paths) FilterOutByExt(ext string) Paths {
799 ret := make(Paths, 0, len(p))
800 for _, path := range p {
801 if path.Ext() != ext {
802 ret = append(ret, path)
803 }
804 }
805 return ret
806}
807
Colin Cross5e6cfbe2017-11-03 15:20:35 -0700808// DirectorySortedPaths is a slice of paths that are sorted such that all files in a directory
809// (including subdirectories) are in a contiguous subslice of the list, and can be found in
810// O(log(N)) time using a binary search on the directory prefix.
811type DirectorySortedPaths Paths
812
813func PathsToDirectorySortedPaths(paths Paths) DirectorySortedPaths {
814 ret := append(DirectorySortedPaths(nil), paths...)
815 sort.Slice(ret, func(i, j int) bool {
816 return ret[i].String() < ret[j].String()
817 })
818 return ret
819}
820
821// PathsInDirectory returns a subslice of the DirectorySortedPaths as a Paths that contains all entries
822// that are in the specified directory and its subdirectories.
823func (p DirectorySortedPaths) PathsInDirectory(dir string) Paths {
824 prefix := filepath.Clean(dir) + "/"
825 start := sort.Search(len(p), func(i int) bool {
826 return prefix < p[i].String()
827 })
828
829 ret := p[start:]
830
831 end := sort.Search(len(ret), func(i int) bool {
832 return !strings.HasPrefix(ret[i].String(), prefix)
833 })
834
835 ret = ret[:end]
836
837 return Paths(ret)
838}
839
Alex Humesky29e3bbe2020-11-20 21:30:13 -0500840// WritablePaths is a slice of WritablePath, used for multiple outputs.
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700841type WritablePaths []WritablePath
842
Paul Duffin85d8f0d2021-03-24 10:18:18 +0000843// RelativeToTop creates a new WritablePaths containing the result of calling Path.RelativeToTop on
844// each item in this slice.
845func (p WritablePaths) RelativeToTop() WritablePaths {
846 ensureTestOnly()
847 if p == nil {
848 return p
849 }
850 ret := make(WritablePaths, len(p))
851 for i, path := range p {
852 ret[i] = path.RelativeToTop().(WritablePath)
853 }
854 return ret
855}
856
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700857// Strings returns the string forms of the writable paths.
858func (p WritablePaths) Strings() []string {
859 if p == nil {
860 return nil
861 }
862 ret := make([]string, len(p))
863 for i, path := range p {
864 ret[i] = path.String()
865 }
866 return ret
867}
868
Colin Cross3bc7ffa2017-11-22 16:19:37 -0800869// Paths returns the WritablePaths as a Paths
870func (p WritablePaths) Paths() Paths {
871 if p == nil {
872 return nil
873 }
874 ret := make(Paths, len(p))
875 for i, path := range p {
876 ret[i] = path
877 }
878 return ret
879}
880
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700881type basePath struct {
Paul Duffin74abc5d2021-03-24 09:24:59 +0000882 path string
883 rel string
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700884}
885
886func (p basePath) Ext() string {
887 return filepath.Ext(p.path)
888}
889
Colin Cross4f6fc9c2016-10-26 10:05:25 -0700890func (p basePath) Base() string {
891 return filepath.Base(p.path)
892}
893
Colin Crossfaeb7aa2017-02-01 14:12:44 -0800894func (p basePath) Rel() string {
895 if p.rel != "" {
896 return p.rel
897 }
898 return p.path
899}
900
Colin Cross0875c522017-11-28 17:34:01 -0800901func (p basePath) String() string {
902 return p.path
903}
904
Colin Cross0db55682017-12-05 15:36:55 -0800905func (p basePath) withRel(rel string) basePath {
906 p.path = filepath.Join(p.path, rel)
907 p.rel = rel
908 return p
909}
910
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700911// SourcePath is a Path representing a file path rooted from SrcDir
912type SourcePath struct {
913 basePath
Paul Duffin580efc82021-03-24 09:04:03 +0000914
915 // The sources root, i.e. Config.SrcDir()
916 srcDir string
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700917}
918
Paul Duffin85d8f0d2021-03-24 10:18:18 +0000919func (p SourcePath) RelativeToTop() Path {
920 ensureTestOnly()
921 return p
922}
923
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700924var _ Path = SourcePath{}
925
Colin Cross0db55682017-12-05 15:36:55 -0800926func (p SourcePath) withRel(rel string) SourcePath {
927 p.basePath = p.basePath.withRel(rel)
928 return p
929}
930
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700931// safePathForSource is for paths that we expect are safe -- only for use by go
932// code that is embedding ninja variables in paths
Colin Crossfe4bc362018-09-12 10:02:13 -0700933func safePathForSource(ctx PathContext, pathComponents ...string) (SourcePath, error) {
934 p, err := validateSafePath(pathComponents...)
Paul Duffin74abc5d2021-03-24 09:24:59 +0000935 ret := SourcePath{basePath{p, ""}, ctx.Config().srcDir}
Colin Crossfe4bc362018-09-12 10:02:13 -0700936 if err != nil {
937 return ret, err
938 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700939
Colin Cross7b3dcc32019-01-24 13:14:39 -0800940 // absolute path already checked by validateSafePath
941 if strings.HasPrefix(ret.String(), ctx.Config().buildDir) {
Mikhail Naganovab1f5182019-02-08 13:17:55 -0800942 return ret, fmt.Errorf("source path %q is in output", ret.String())
Colin Cross6e18ca42015-07-14 18:55:36 -0700943 }
944
Colin Crossfe4bc362018-09-12 10:02:13 -0700945 return ret, err
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700946}
947
Colin Cross192e97a2018-02-22 14:21:02 -0800948// pathForSource creates a SourcePath from pathComponents, but does not check that it exists.
949func pathForSource(ctx PathContext, pathComponents ...string) (SourcePath, error) {
Colin Crossc48c1432018-02-23 07:09:01 +0000950 p, err := validatePath(pathComponents...)
Paul Duffin74abc5d2021-03-24 09:24:59 +0000951 ret := SourcePath{basePath{p, ""}, ctx.Config().srcDir}
Colin Cross94a32102018-02-22 14:21:02 -0800952 if err != nil {
Colin Cross192e97a2018-02-22 14:21:02 -0800953 return ret, err
Colin Cross94a32102018-02-22 14:21:02 -0800954 }
955
Colin Cross7b3dcc32019-01-24 13:14:39 -0800956 // absolute path already checked by validatePath
957 if strings.HasPrefix(ret.String(), ctx.Config().buildDir) {
Mikhail Naganovab1f5182019-02-08 13:17:55 -0800958 return ret, fmt.Errorf("source path %q is in output", ret.String())
Colin Crossc48c1432018-02-23 07:09:01 +0000959 }
960
Colin Cross192e97a2018-02-22 14:21:02 -0800961 return ret, nil
962}
963
964// existsWithDependencies returns true if the path exists, and adds appropriate dependencies to rerun if the
965// path does not exist.
966func existsWithDependencies(ctx PathContext, path SourcePath) (exists bool, err error) {
967 var files []string
968
969 if gctx, ok := ctx.(PathGlobContext); ok {
970 // Use glob to produce proper dependencies, even though we only want
971 // a single file.
972 files, err = gctx.GlobWithDeps(path.String(), nil)
973 } else {
Colin Cross82ea3fb2021-04-05 17:48:26 -0700974 var result pathtools.GlobResult
Colin Cross192e97a2018-02-22 14:21:02 -0800975 // We cannot add build statements in this context, so we fall back to
976 // AddNinjaFileDeps
Colin Cross82ea3fb2021-04-05 17:48:26 -0700977 result, err = ctx.Config().fs.Glob(path.String(), nil, pathtools.FollowSymlinks)
978 ctx.AddNinjaFileDeps(result.Deps...)
979 files = result.Matches
Colin Cross192e97a2018-02-22 14:21:02 -0800980 }
981
982 if err != nil {
983 return false, fmt.Errorf("glob: %s", err.Error())
984 }
985
986 return len(files) > 0, nil
987}
988
989// PathForSource joins the provided path components and validates that the result
990// neither escapes the source dir nor is in the out dir.
991// On error, it will return a usable, but invalid SourcePath, and report a ModuleError.
992func PathForSource(ctx PathContext, pathComponents ...string) SourcePath {
993 path, err := pathForSource(ctx, pathComponents...)
994 if err != nil {
995 reportPathError(ctx, err)
996 }
997
Colin Crosse3924e12018-08-15 20:18:53 -0700998 if pathtools.IsGlob(path.String()) {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +0100999 ReportPathErrorf(ctx, "path may not contain a glob: %s", path.String())
Colin Crosse3924e12018-08-15 20:18:53 -07001000 }
1001
Liz Kammera830f3a2020-11-10 10:50:34 -08001002 if modCtx, ok := ctx.(ModuleMissingDepsPathContext); ok && ctx.Config().AllowMissingDependencies() {
Colin Cross192e97a2018-02-22 14:21:02 -08001003 exists, err := existsWithDependencies(ctx, path)
1004 if err != nil {
1005 reportPathError(ctx, err)
1006 }
1007 if !exists {
1008 modCtx.AddMissingDependencies([]string{path.String()})
1009 }
Colin Cross988414c2020-01-11 01:11:46 +00001010 } else if exists, _, err := ctx.Config().fs.Exists(path.String()); err != nil {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001011 ReportPathErrorf(ctx, "%s: %s", path, err.Error())
Pedro Loureiro5d190cc2021-02-15 15:41:33 +00001012 } else if !exists && !ctx.Config().TestAllowNonExistentPaths {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001013 ReportPathErrorf(ctx, "source path %q does not exist", path)
Colin Cross192e97a2018-02-22 14:21:02 -08001014 }
1015 return path
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001016}
1017
Liz Kammer7aa52882021-02-11 09:16:14 -05001018// ExistentPathForSource returns an OptionalPath with the SourcePath, rooted from SrcDir, *not*
1019// rooted from the module's local source directory, if the path exists, or an empty OptionalPath if
1020// it doesn't exist. Dependencies are added so that the ninja file will be regenerated if the state
1021// of the path changes.
Colin Cross32f38982018-02-22 11:47:25 -08001022func ExistentPathForSource(ctx PathContext, pathComponents ...string) OptionalPath {
Colin Cross192e97a2018-02-22 14:21:02 -08001023 path, err := pathForSource(ctx, pathComponents...)
Colin Cross1ccfcc32018-02-22 13:54:26 -08001024 if err != nil {
1025 reportPathError(ctx, err)
1026 return OptionalPath{}
1027 }
Colin Crossc48c1432018-02-23 07:09:01 +00001028
Colin Crosse3924e12018-08-15 20:18:53 -07001029 if pathtools.IsGlob(path.String()) {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001030 ReportPathErrorf(ctx, "path may not contain a glob: %s", path.String())
Colin Crosse3924e12018-08-15 20:18:53 -07001031 return OptionalPath{}
1032 }
1033
Colin Cross192e97a2018-02-22 14:21:02 -08001034 exists, err := existsWithDependencies(ctx, path)
Colin Crossc48c1432018-02-23 07:09:01 +00001035 if err != nil {
1036 reportPathError(ctx, err)
1037 return OptionalPath{}
1038 }
Colin Cross192e97a2018-02-22 14:21:02 -08001039 if !exists {
Colin Crossc48c1432018-02-23 07:09:01 +00001040 return OptionalPath{}
1041 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001042 return OptionalPathForPath(path)
1043}
1044
1045func (p SourcePath) String() string {
Paul Duffin580efc82021-03-24 09:04:03 +00001046 return filepath.Join(p.srcDir, p.path)
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001047}
1048
1049// Join creates a new SourcePath with paths... joined with the current path. The
1050// provided paths... may not use '..' to escape from the current path.
1051func (p SourcePath) Join(ctx PathContext, paths ...string) SourcePath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001052 path, err := validatePath(paths...)
1053 if err != nil {
1054 reportPathError(ctx, err)
1055 }
Colin Cross0db55682017-12-05 15:36:55 -08001056 return p.withRel(path)
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001057}
1058
Colin Cross2fafa3e2019-03-05 12:39:51 -08001059// join is like Join but does less path validation.
1060func (p SourcePath) join(ctx PathContext, paths ...string) SourcePath {
1061 path, err := validateSafePath(paths...)
1062 if err != nil {
1063 reportPathError(ctx, err)
1064 }
1065 return p.withRel(path)
1066}
1067
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001068// OverlayPath returns the overlay for `path' if it exists. This assumes that the
1069// SourcePath is the path to a resource overlay directory.
Liz Kammera830f3a2020-11-10 10:50:34 -08001070func (p SourcePath) OverlayPath(ctx ModuleMissingDepsPathContext, path Path) OptionalPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001071 var relDir string
Colin Cross07e51612019-03-05 12:46:40 -08001072 if srcPath, ok := path.(SourcePath); ok {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001073 relDir = srcPath.path
1074 } else {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001075 ReportPathErrorf(ctx, "Cannot find relative path for %s(%s)", reflect.TypeOf(path).Name(), path)
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001076 return OptionalPath{}
1077 }
Paul Duffin580efc82021-03-24 09:04:03 +00001078 dir := filepath.Join(p.srcDir, p.path, relDir)
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001079 // Use Glob so that we are run again if the directory is added.
Colin Cross7f19f372016-11-01 11:10:25 -07001080 if pathtools.IsGlob(dir) {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001081 ReportPathErrorf(ctx, "Path may not contain a glob: %s", dir)
Dan Willemsen7b310ee2015-12-18 15:11:17 -08001082 }
Colin Cross461b4452018-02-23 09:22:42 -08001083 paths, err := ctx.GlobWithDeps(dir, nil)
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001084 if err != nil {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001085 ReportPathErrorf(ctx, "glob: %s", err.Error())
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001086 return OptionalPath{}
1087 }
1088 if len(paths) == 0 {
1089 return OptionalPath{}
1090 }
Paul Duffin580efc82021-03-24 09:04:03 +00001091 relPath := Rel(ctx, p.srcDir, paths[0])
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001092 return OptionalPathForPath(PathForSource(ctx, relPath))
1093}
1094
Colin Cross70dda7e2019-10-01 22:05:35 -07001095// OutputPath is a Path representing an intermediates file path rooted from the build directory
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001096type OutputPath struct {
1097 basePath
Paul Duffind65c58b2021-03-24 09:22:07 +00001098
1099 // The soong build directory, i.e. Config.BuildDir()
1100 buildDir string
1101
Colin Crossd63c9a72020-01-29 16:52:50 -08001102 fullPath string
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001103}
1104
Colin Cross702e0f82017-10-18 17:27:54 -07001105func (p OutputPath) withRel(rel string) OutputPath {
Colin Cross0db55682017-12-05 15:36:55 -08001106 p.basePath = p.basePath.withRel(rel)
Colin Crossd63c9a72020-01-29 16:52:50 -08001107 p.fullPath = filepath.Join(p.fullPath, rel)
Colin Cross702e0f82017-10-18 17:27:54 -07001108 return p
1109}
1110
Colin Cross3063b782018-08-15 11:19:12 -07001111func (p OutputPath) WithoutRel() OutputPath {
1112 p.basePath.rel = filepath.Base(p.basePath.path)
1113 return p
1114}
1115
Paul Duffind65c58b2021-03-24 09:22:07 +00001116func (p OutputPath) getBuildDir() string {
1117 return p.buildDir
Paul Duffin9b478b02019-12-10 13:41:51 +00001118}
1119
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001120func (p OutputPath) RelativeToTop() Path {
1121 return p.outputPathRelativeToTop()
1122}
1123
1124func (p OutputPath) outputPathRelativeToTop() OutputPath {
1125 p.fullPath = StringPathRelativeToTop(p.buildDir, p.fullPath)
1126 p.buildDir = OutSoongDir
1127 return p
1128}
1129
Paul Duffin0267d492021-02-02 10:05:52 +00001130func (p OutputPath) objPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleObjPath {
1131 return PathForModuleObj(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
1132}
1133
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001134var _ Path = OutputPath{}
Paul Duffin9b478b02019-12-10 13:41:51 +00001135var _ WritablePath = OutputPath{}
Paul Duffin0267d492021-02-02 10:05:52 +00001136var _ objPathProvider = OutputPath{}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001137
Chris Parsons8f232a22020-06-23 17:37:05 -04001138// toolDepPath is a Path representing a dependency of the build tool.
1139type toolDepPath struct {
1140 basePath
1141}
1142
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001143func (t toolDepPath) RelativeToTop() Path {
1144 ensureTestOnly()
1145 return t
1146}
1147
Chris Parsons8f232a22020-06-23 17:37:05 -04001148var _ Path = toolDepPath{}
1149
1150// pathForBuildToolDep returns a toolDepPath representing the given path string.
1151// There is no validation for the path, as it is "trusted": It may fail
1152// normal validation checks. For example, it may be an absolute path.
1153// Only use this function to construct paths for dependencies of the build
1154// tool invocation.
1155func pathForBuildToolDep(ctx PathContext, path string) toolDepPath {
Paul Duffin74abc5d2021-03-24 09:24:59 +00001156 return toolDepPath{basePath{path, ""}}
Chris Parsons8f232a22020-06-23 17:37:05 -04001157}
1158
Jeff Gaston734e3802017-04-10 15:47:24 -07001159// PathForOutput joins the provided paths and returns an OutputPath that is
1160// validated to not escape the build dir.
1161// On error, it will return a usable, but invalid OutputPath, and report a ModuleError.
1162func PathForOutput(ctx PathContext, pathComponents ...string) OutputPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001163 path, err := validatePath(pathComponents...)
1164 if err != nil {
1165 reportPathError(ctx, err)
1166 }
Colin Crossd63c9a72020-01-29 16:52:50 -08001167 fullPath := filepath.Join(ctx.Config().buildDir, path)
1168 path = fullPath[len(fullPath)-len(path):]
Paul Duffin74abc5d2021-03-24 09:24:59 +00001169 return OutputPath{basePath{path, ""}, ctx.Config().buildDir, fullPath}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001170}
1171
Colin Cross40e33732019-02-15 11:08:35 -08001172// PathsForOutput returns Paths rooted from buildDir
1173func PathsForOutput(ctx PathContext, paths []string) WritablePaths {
1174 ret := make(WritablePaths, len(paths))
1175 for i, path := range paths {
1176 ret[i] = PathForOutput(ctx, path)
1177 }
1178 return ret
1179}
1180
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001181func (p OutputPath) writablePath() {}
1182
1183func (p OutputPath) String() string {
Colin Crossd63c9a72020-01-29 16:52:50 -08001184 return p.fullPath
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001185}
1186
1187// Join creates a new OutputPath with paths... joined with the current path. The
1188// provided paths... may not use '..' to escape from the current path.
1189func (p OutputPath) Join(ctx PathContext, paths ...string) OutputPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001190 path, err := validatePath(paths...)
1191 if err != nil {
1192 reportPathError(ctx, err)
1193 }
Colin Cross0db55682017-12-05 15:36:55 -08001194 return p.withRel(path)
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001195}
1196
Colin Cross8854a5a2019-02-11 14:14:16 -08001197// ReplaceExtension creates a new OutputPath with the extension replaced with ext.
1198func (p OutputPath) ReplaceExtension(ctx PathContext, ext string) OutputPath {
1199 if strings.Contains(ext, "/") {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001200 ReportPathErrorf(ctx, "extension %q cannot contain /", ext)
Colin Cross8854a5a2019-02-11 14:14:16 -08001201 }
1202 ret := PathForOutput(ctx, pathtools.ReplaceExtension(p.path, ext))
Colin Cross2cdd5df2019-02-25 10:25:24 -08001203 ret.rel = pathtools.ReplaceExtension(p.rel, ext)
Colin Cross8854a5a2019-02-11 14:14:16 -08001204 return ret
1205}
1206
Colin Cross40e33732019-02-15 11:08:35 -08001207// InSameDir creates a new OutputPath from the directory of the current OutputPath joined with the elements in paths.
1208func (p OutputPath) InSameDir(ctx PathContext, paths ...string) OutputPath {
1209 path, err := validatePath(paths...)
1210 if err != nil {
1211 reportPathError(ctx, err)
1212 }
1213
1214 ret := PathForOutput(ctx, filepath.Dir(p.path), path)
Colin Cross2cdd5df2019-02-25 10:25:24 -08001215 ret.rel = filepath.Join(filepath.Dir(p.rel), path)
Colin Cross40e33732019-02-15 11:08:35 -08001216 return ret
1217}
1218
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001219// PathForIntermediates returns an OutputPath representing the top-level
1220// intermediates directory.
1221func PathForIntermediates(ctx PathContext, paths ...string) OutputPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001222 path, err := validatePath(paths...)
1223 if err != nil {
1224 reportPathError(ctx, err)
1225 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001226 return PathForOutput(ctx, ".intermediates", path)
1227}
1228
Colin Cross07e51612019-03-05 12:46:40 -08001229var _ genPathProvider = SourcePath{}
1230var _ objPathProvider = SourcePath{}
1231var _ resPathProvider = SourcePath{}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001232
Colin Cross07e51612019-03-05 12:46:40 -08001233// PathForModuleSrc returns a Path representing the paths... under the
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001234// module's local source directory.
Liz Kammera830f3a2020-11-10 10:50:34 -08001235func PathForModuleSrc(ctx ModuleMissingDepsPathContext, pathComponents ...string) Path {
Colin Cross8a497952019-03-05 22:25:09 -08001236 p, err := validatePath(pathComponents...)
1237 if err != nil {
1238 reportPathError(ctx, err)
Colin Cross192e97a2018-02-22 14:21:02 -08001239 }
Colin Cross8a497952019-03-05 22:25:09 -08001240 paths, err := expandOneSrcPath(ctx, p, nil)
1241 if err != nil {
1242 if depErr, ok := err.(missingDependencyError); ok {
1243 if ctx.Config().AllowMissingDependencies() {
1244 ctx.AddMissingDependencies(depErr.missingDeps)
1245 } else {
1246 ctx.ModuleErrorf(`%s, is the property annotated with android:"path"?`, depErr.Error())
1247 }
1248 } else {
1249 reportPathError(ctx, err)
1250 }
1251 return nil
1252 } else if len(paths) == 0 {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001253 ReportPathErrorf(ctx, "%q produced no files, expected exactly one", p)
Colin Cross8a497952019-03-05 22:25:09 -08001254 return nil
1255 } else if len(paths) > 1 {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001256 ReportPathErrorf(ctx, "%q produced %d files, expected exactly one", p, len(paths))
Colin Cross8a497952019-03-05 22:25:09 -08001257 }
1258 return paths[0]
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001259}
1260
Liz Kammera830f3a2020-11-10 10:50:34 -08001261func pathForModuleSrc(ctx EarlyModulePathContext, paths ...string) SourcePath {
Colin Cross07e51612019-03-05 12:46:40 -08001262 p, err := validatePath(paths...)
1263 if err != nil {
1264 reportPathError(ctx, err)
1265 }
1266
1267 path, err := pathForSource(ctx, ctx.ModuleDir(), p)
1268 if err != nil {
1269 reportPathError(ctx, err)
1270 }
1271
1272 path.basePath.rel = p
1273
1274 return path
1275}
1276
Colin Cross2fafa3e2019-03-05 12:39:51 -08001277// PathsWithModuleSrcSubDir takes a list of Paths and returns a new list of Paths where Rel() on each path
1278// will return the path relative to subDir in the module's source directory. If any input paths are not located
1279// inside subDir then a path error will be reported.
Liz Kammera830f3a2020-11-10 10:50:34 -08001280func PathsWithModuleSrcSubDir(ctx EarlyModulePathContext, paths Paths, subDir string) Paths {
Colin Cross2fafa3e2019-03-05 12:39:51 -08001281 paths = append(Paths(nil), paths...)
Colin Cross07e51612019-03-05 12:46:40 -08001282 subDirFullPath := pathForModuleSrc(ctx, subDir)
Colin Cross2fafa3e2019-03-05 12:39:51 -08001283 for i, path := range paths {
1284 rel := Rel(ctx, subDirFullPath.String(), path.String())
1285 paths[i] = subDirFullPath.join(ctx, rel)
1286 }
1287 return paths
1288}
1289
1290// PathWithModuleSrcSubDir takes a Path and returns a Path where Rel() will return the path relative to subDir in the
1291// 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 -08001292func PathWithModuleSrcSubDir(ctx EarlyModulePathContext, path Path, subDir string) Path {
Colin Cross07e51612019-03-05 12:46:40 -08001293 subDirFullPath := pathForModuleSrc(ctx, subDir)
Colin Cross2fafa3e2019-03-05 12:39:51 -08001294 rel := Rel(ctx, subDirFullPath.String(), path.String())
1295 return subDirFullPath.Join(ctx, rel)
1296}
1297
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001298// OptionalPathForModuleSrc returns an OptionalPath. The OptionalPath contains a
1299// valid path if p is non-nil.
Liz Kammera830f3a2020-11-10 10:50:34 -08001300func OptionalPathForModuleSrc(ctx ModuleMissingDepsPathContext, p *string) OptionalPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001301 if p == nil {
1302 return OptionalPath{}
1303 }
1304 return OptionalPathForPath(PathForModuleSrc(ctx, *p))
1305}
1306
Liz Kammera830f3a2020-11-10 10:50:34 -08001307func (p SourcePath) genPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleGenPath {
Colin Cross7fc17db2017-02-01 14:07:55 -08001308 return PathForModuleGen(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001309}
1310
Liz Kammera830f3a2020-11-10 10:50:34 -08001311func (p SourcePath) objPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleObjPath {
Colin Cross7fc17db2017-02-01 14:07:55 -08001312 return PathForModuleObj(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001313}
1314
Liz Kammera830f3a2020-11-10 10:50:34 -08001315func (p SourcePath) resPathWithName(ctx ModuleOutPathContext, name string) ModuleResPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001316 // TODO: Use full directory if the new ctx is not the current ctx?
1317 return PathForModuleRes(ctx, p.path, name)
1318}
1319
1320// ModuleOutPath is a Path representing a module's output directory.
1321type ModuleOutPath struct {
1322 OutputPath
1323}
1324
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001325func (p ModuleOutPath) RelativeToTop() Path {
1326 p.OutputPath = p.outputPathRelativeToTop()
1327 return p
1328}
1329
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001330var _ Path = ModuleOutPath{}
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001331var _ WritablePath = ModuleOutPath{}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001332
Liz Kammera830f3a2020-11-10 10:50:34 -08001333func (p ModuleOutPath) objPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleObjPath {
Pete Bentleyfcf55bf2019-08-16 20:14:32 +01001334 return PathForModuleObj(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
1335}
1336
Liz Kammera830f3a2020-11-10 10:50:34 -08001337// ModuleOutPathContext Subset of ModuleContext functions necessary for output path methods.
1338type ModuleOutPathContext interface {
1339 PathContext
1340
1341 ModuleName() string
1342 ModuleDir() string
1343 ModuleSubDir() string
1344}
1345
1346func pathForModuleOut(ctx ModuleOutPathContext) OutputPath {
Colin Cross702e0f82017-10-18 17:27:54 -07001347 return PathForOutput(ctx, ".intermediates", ctx.ModuleDir(), ctx.ModuleName(), ctx.ModuleSubDir())
1348}
1349
Logan Chien7eefdc42018-07-11 18:10:41 +08001350// PathForVndkRefAbiDump returns an OptionalPath representing the path of the
1351// reference abi dump for the given module. This is not guaranteed to be valid.
Liz Kammera830f3a2020-11-10 10:50:34 -08001352func PathForVndkRefAbiDump(ctx ModuleInstallPathContext, version, fileName string,
Hsin-Yi Chen53489642019-07-31 17:10:45 +08001353 isNdk, isLlndkOrVndk, isGzip bool) OptionalPath {
Logan Chien7eefdc42018-07-11 18:10:41 +08001354
Jayant Chowdharyac066c62018-02-20 10:53:31 -08001355 arches := ctx.DeviceConfig().Arches()
Logan Chien7eefdc42018-07-11 18:10:41 +08001356 if len(arches) == 0 {
1357 panic("device build with no primary arch")
1358 }
Jayant Chowdharyac066c62018-02-20 10:53:31 -08001359 currentArch := ctx.Arch()
1360 archNameAndVariant := currentArch.ArchType.String()
1361 if currentArch.ArchVariant != "" {
1362 archNameAndVariant += "_" + currentArch.ArchVariant
1363 }
Logan Chien5237bed2018-07-11 17:15:57 +08001364
1365 var dirName string
Hsin-Yi Chen53489642019-07-31 17:10:45 +08001366 if isNdk {
Logan Chien5237bed2018-07-11 17:15:57 +08001367 dirName = "ndk"
Hsin-Yi Chen53489642019-07-31 17:10:45 +08001368 } else if isLlndkOrVndk {
Logan Chien5237bed2018-07-11 17:15:57 +08001369 dirName = "vndk"
Logan Chien41eabe62019-04-10 13:33:58 +08001370 } else {
1371 dirName = "platform" // opt-in libs
Jayant Chowdhary3e231fd2017-02-08 13:45:53 -08001372 }
Logan Chien5237bed2018-07-11 17:15:57 +08001373
Jayant Chowdhary34ce67d2018-03-08 11:00:50 -08001374 binderBitness := ctx.DeviceConfig().BinderBitness()
Logan Chien7eefdc42018-07-11 18:10:41 +08001375
1376 var ext string
1377 if isGzip {
1378 ext = ".lsdump.gz"
1379 } else {
1380 ext = ".lsdump"
1381 }
1382
1383 return ExistentPathForSource(ctx, "prebuilts", "abi-dumps", dirName,
1384 version, binderBitness, archNameAndVariant, "source-based",
1385 fileName+ext)
Jayant Chowdhary3e231fd2017-02-08 13:45:53 -08001386}
1387
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001388// PathForModuleOut returns a Path representing the paths... under the module's
1389// output directory.
Liz Kammera830f3a2020-11-10 10:50:34 -08001390func PathForModuleOut(ctx ModuleOutPathContext, paths ...string) ModuleOutPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001391 p, err := validatePath(paths...)
1392 if err != nil {
1393 reportPathError(ctx, err)
1394 }
Colin Cross702e0f82017-10-18 17:27:54 -07001395 return ModuleOutPath{
Liz Kammera830f3a2020-11-10 10:50:34 -08001396 OutputPath: pathForModuleOut(ctx).withRel(p),
Colin Cross702e0f82017-10-18 17:27:54 -07001397 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001398}
1399
1400// ModuleGenPath is a Path representing the 'gen' directory in a module's output
1401// directory. Mainly used for generated sources.
1402type ModuleGenPath struct {
1403 ModuleOutPath
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001404}
1405
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001406func (p ModuleGenPath) RelativeToTop() Path {
1407 p.OutputPath = p.outputPathRelativeToTop()
1408 return p
1409}
1410
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001411var _ Path = ModuleGenPath{}
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001412var _ WritablePath = ModuleGenPath{}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001413var _ genPathProvider = ModuleGenPath{}
1414var _ objPathProvider = ModuleGenPath{}
1415
1416// PathForModuleGen returns a Path representing the paths... under the module's
1417// `gen' directory.
Liz Kammera830f3a2020-11-10 10:50:34 -08001418func PathForModuleGen(ctx ModuleOutPathContext, paths ...string) ModuleGenPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001419 p, err := validatePath(paths...)
1420 if err != nil {
1421 reportPathError(ctx, err)
1422 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001423 return ModuleGenPath{
Colin Cross702e0f82017-10-18 17:27:54 -07001424 ModuleOutPath: ModuleOutPath{
Liz Kammera830f3a2020-11-10 10:50:34 -08001425 OutputPath: pathForModuleOut(ctx).withRel("gen").withRel(p),
Colin Cross702e0f82017-10-18 17:27:54 -07001426 },
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001427 }
1428}
1429
Liz Kammera830f3a2020-11-10 10:50:34 -08001430func (p ModuleGenPath) genPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleGenPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001431 // TODO: make a different path for local vs remote generated files?
Dan Willemsen21ec4902016-11-02 20:43:13 -07001432 return PathForModuleGen(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001433}
1434
Liz Kammera830f3a2020-11-10 10:50:34 -08001435func (p ModuleGenPath) objPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleObjPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001436 return PathForModuleObj(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
1437}
1438
1439// ModuleObjPath is a Path representing the 'obj' directory in a module's output
1440// directory. Used for compiled objects.
1441type ModuleObjPath struct {
1442 ModuleOutPath
1443}
1444
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001445func (p ModuleObjPath) RelativeToTop() Path {
1446 p.OutputPath = p.outputPathRelativeToTop()
1447 return p
1448}
1449
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001450var _ Path = ModuleObjPath{}
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001451var _ WritablePath = ModuleObjPath{}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001452
1453// PathForModuleObj returns a Path representing the paths... under the module's
1454// 'obj' directory.
Liz Kammera830f3a2020-11-10 10:50:34 -08001455func PathForModuleObj(ctx ModuleOutPathContext, pathComponents ...string) ModuleObjPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001456 p, err := validatePath(pathComponents...)
1457 if err != nil {
1458 reportPathError(ctx, err)
1459 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001460 return ModuleObjPath{PathForModuleOut(ctx, "obj", p)}
1461}
1462
1463// ModuleResPath is a a Path representing the 'res' directory in a module's
1464// output directory.
1465type ModuleResPath struct {
1466 ModuleOutPath
1467}
1468
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001469func (p ModuleResPath) RelativeToTop() Path {
1470 p.OutputPath = p.outputPathRelativeToTop()
1471 return p
1472}
1473
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001474var _ Path = ModuleResPath{}
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001475var _ WritablePath = ModuleResPath{}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001476
1477// PathForModuleRes returns a Path representing the paths... under the module's
1478// 'res' directory.
Liz Kammera830f3a2020-11-10 10:50:34 -08001479func PathForModuleRes(ctx ModuleOutPathContext, pathComponents ...string) ModuleResPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001480 p, err := validatePath(pathComponents...)
1481 if err != nil {
1482 reportPathError(ctx, err)
1483 }
1484
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001485 return ModuleResPath{PathForModuleOut(ctx, "res", p)}
1486}
1487
Colin Cross70dda7e2019-10-01 22:05:35 -07001488// InstallPath is a Path representing a installed file path rooted from the build directory
1489type InstallPath struct {
1490 basePath
Colin Crossff6c33d2019-10-02 16:01:35 -07001491
Paul Duffind65c58b2021-03-24 09:22:07 +00001492 // The soong build directory, i.e. Config.BuildDir()
1493 buildDir string
1494
Jiyong Park957bcd92020-10-20 18:23:33 +09001495 // partitionDir is the part of the InstallPath that is automatically determined according to the context.
1496 // For example, it is host/<os>-<arch> for host modules, and target/product/<device>/<partition> for device modules.
1497 partitionDir string
1498
1499 // makePath indicates whether this path is for Soong (false) or Make (true).
1500 makePath bool
Colin Cross70dda7e2019-10-01 22:05:35 -07001501}
1502
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001503// Will panic if called from outside a test environment.
1504func ensureTestOnly() {
Martin Stjernholm32312eb2021-03-27 18:54:49 +00001505 if PrefixInList(os.Args, "-test.") {
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001506 return
1507 }
Martin Stjernholm32312eb2021-03-27 18:54:49 +00001508 panic(fmt.Errorf("Not in test. Command line:\n %s", strings.Join(os.Args, "\n ")))
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001509}
1510
1511func (p InstallPath) RelativeToTop() Path {
1512 ensureTestOnly()
1513 p.buildDir = OutSoongDir
1514 return p
1515}
1516
Paul Duffind65c58b2021-03-24 09:22:07 +00001517func (p InstallPath) getBuildDir() string {
1518 return p.buildDir
Paul Duffin9b478b02019-12-10 13:41:51 +00001519}
1520
Hans MÃ¥nssond3f2bd72020-11-27 12:37:28 +01001521func (p InstallPath) ReplaceExtension(ctx PathContext, ext string) OutputPath {
1522 panic("Not implemented")
1523}
1524
Paul Duffin9b478b02019-12-10 13:41:51 +00001525var _ Path = InstallPath{}
1526var _ WritablePath = InstallPath{}
1527
Colin Cross70dda7e2019-10-01 22:05:35 -07001528func (p InstallPath) writablePath() {}
1529
1530func (p InstallPath) String() string {
Jiyong Park957bcd92020-10-20 18:23:33 +09001531 if p.makePath {
1532 // Make path starts with out/ instead of out/soong.
Paul Duffind65c58b2021-03-24 09:22:07 +00001533 return filepath.Join(p.buildDir, "../", p.path)
Jiyong Park957bcd92020-10-20 18:23:33 +09001534 } else {
Paul Duffind65c58b2021-03-24 09:22:07 +00001535 return filepath.Join(p.buildDir, p.path)
Jiyong Park957bcd92020-10-20 18:23:33 +09001536 }
1537}
1538
1539// PartitionDir returns the path to the partition where the install path is rooted at. It is
1540// out/soong/target/product/<device>/<partition> for device modules, and out/soong/host/<os>-<arch> for host modules.
1541// The ./soong is dropped if the install path is for Make.
1542func (p InstallPath) PartitionDir() string {
1543 if p.makePath {
Paul Duffind65c58b2021-03-24 09:22:07 +00001544 return filepath.Join(p.buildDir, "../", p.partitionDir)
Jiyong Park957bcd92020-10-20 18:23:33 +09001545 } else {
Paul Duffind65c58b2021-03-24 09:22:07 +00001546 return filepath.Join(p.buildDir, p.partitionDir)
Jiyong Park957bcd92020-10-20 18:23:33 +09001547 }
Colin Cross70dda7e2019-10-01 22:05:35 -07001548}
1549
1550// Join creates a new InstallPath with paths... joined with the current path. The
1551// provided paths... may not use '..' to escape from the current path.
1552func (p InstallPath) Join(ctx PathContext, paths ...string) InstallPath {
1553 path, err := validatePath(paths...)
1554 if err != nil {
1555 reportPathError(ctx, err)
1556 }
1557 return p.withRel(path)
1558}
1559
1560func (p InstallPath) withRel(rel string) InstallPath {
1561 p.basePath = p.basePath.withRel(rel)
1562 return p
1563}
1564
Colin Crossff6c33d2019-10-02 16:01:35 -07001565// ToMakePath returns a new InstallPath that points to Make's install directory instead of Soong's,
1566// i.e. out/ instead of out/soong/.
1567func (p InstallPath) ToMakePath() InstallPath {
Jiyong Park957bcd92020-10-20 18:23:33 +09001568 p.makePath = true
Colin Crossff6c33d2019-10-02 16:01:35 -07001569 return p
Colin Cross70dda7e2019-10-01 22:05:35 -07001570}
1571
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001572// PathForModuleInstall returns a Path representing the install path for the
1573// module appended with paths...
Colin Cross70dda7e2019-10-01 22:05:35 -07001574func PathForModuleInstall(ctx ModuleInstallPathContext, pathComponents ...string) InstallPath {
Colin Cross6e359402020-02-10 15:29:54 -08001575 os := ctx.Os()
Jiyong Park87788b52020-09-01 12:37:45 +09001576 arch := ctx.Arch().ArchType
1577 forceOS, forceArch := ctx.InstallForceOS()
1578 if forceOS != nil {
Colin Cross6e359402020-02-10 15:29:54 -08001579 os = *forceOS
1580 }
Jiyong Park87788b52020-09-01 12:37:45 +09001581 if forceArch != nil {
1582 arch = *forceArch
1583 }
Colin Cross6e359402020-02-10 15:29:54 -08001584 partition := modulePartition(ctx, os)
Colin Cross609c49a2020-02-13 13:20:11 -08001585
Jiyong Park87788b52020-09-01 12:37:45 +09001586 ret := pathForInstall(ctx, os, arch, partition, ctx.Debug(), pathComponents...)
Colin Cross609c49a2020-02-13 13:20:11 -08001587
Jingwen Chencda22c92020-11-23 00:22:30 -05001588 if ctx.InstallBypassMake() && ctx.Config().KatiEnabled() {
Colin Cross609c49a2020-02-13 13:20:11 -08001589 ret = ret.ToMakePath()
1590 }
1591
1592 return ret
1593}
1594
Jiyong Park87788b52020-09-01 12:37:45 +09001595func pathForInstall(ctx PathContext, os OsType, arch ArchType, partition string, debug bool,
Colin Cross609c49a2020-02-13 13:20:11 -08001596 pathComponents ...string) InstallPath {
1597
Jiyong Park957bcd92020-10-20 18:23:33 +09001598 var partionPaths []string
Colin Cross609c49a2020-02-13 13:20:11 -08001599
Colin Cross6e359402020-02-10 15:29:54 -08001600 if os.Class == Device {
Jiyong Park957bcd92020-10-20 18:23:33 +09001601 partionPaths = []string{"target", "product", ctx.Config().DeviceName(), partition}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001602 } else {
Jiyong Park87788b52020-09-01 12:37:45 +09001603 osName := os.String()
1604 if os == Linux {
1605 // instead of linux_glibc
1606 osName = "linux"
Dan Willemsen866b5632017-09-22 12:28:24 -07001607 }
Jiyong Park87788b52020-09-01 12:37:45 +09001608 // SOONG_HOST_OUT is set to out/host/$(HOST_OS)-$(HOST_PREBUILT_ARCH)
1609 // and HOST_PREBUILT_ARCH is forcibly set to x86 even on x86_64 hosts. We don't seem
1610 // to have a plan to fix it (see the comment in build/make/core/envsetup.mk).
1611 // Let's keep using x86 for the existing cases until we have a need to support
1612 // other architectures.
1613 archName := arch.String()
1614 if os.Class == Host && (arch == X86_64 || arch == Common) {
1615 archName = "x86"
1616 }
Jiyong Park957bcd92020-10-20 18:23:33 +09001617 partionPaths = []string{"host", osName + "-" + archName, partition}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001618 }
Colin Cross609c49a2020-02-13 13:20:11 -08001619 if debug {
Jiyong Park957bcd92020-10-20 18:23:33 +09001620 partionPaths = append([]string{"debug"}, partionPaths...)
Dan Willemsen782a2d12015-12-21 14:55:28 -08001621 }
Colin Cross70dda7e2019-10-01 22:05:35 -07001622
Jiyong Park957bcd92020-10-20 18:23:33 +09001623 partionPath, err := validatePath(partionPaths...)
Colin Cross70dda7e2019-10-01 22:05:35 -07001624 if err != nil {
1625 reportPathError(ctx, err)
1626 }
Colin Crossff6c33d2019-10-02 16:01:35 -07001627
Jiyong Park957bcd92020-10-20 18:23:33 +09001628 base := InstallPath{
Paul Duffin74abc5d2021-03-24 09:24:59 +00001629 basePath: basePath{partionPath, ""},
Paul Duffind65c58b2021-03-24 09:22:07 +00001630 buildDir: ctx.Config().buildDir,
Jiyong Park957bcd92020-10-20 18:23:33 +09001631 partitionDir: partionPath,
1632 makePath: false,
1633 }
Colin Crossff6c33d2019-10-02 16:01:35 -07001634
Jiyong Park957bcd92020-10-20 18:23:33 +09001635 return base.Join(ctx, pathComponents...)
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001636}
1637
Nicolas Geoffray1228e9c2020-02-27 13:45:35 +00001638func pathForNdkOrSdkInstall(ctx PathContext, prefix string, paths []string) InstallPath {
Jiyong Park957bcd92020-10-20 18:23:33 +09001639 base := InstallPath{
Paul Duffin74abc5d2021-03-24 09:24:59 +00001640 basePath: basePath{prefix, ""},
Paul Duffind65c58b2021-03-24 09:22:07 +00001641 buildDir: ctx.Config().buildDir,
Jiyong Park957bcd92020-10-20 18:23:33 +09001642 partitionDir: prefix,
1643 makePath: false,
Colin Cross70dda7e2019-10-01 22:05:35 -07001644 }
Jiyong Park957bcd92020-10-20 18:23:33 +09001645 return base.Join(ctx, paths...)
Colin Cross70dda7e2019-10-01 22:05:35 -07001646}
1647
Nicolas Geoffray1228e9c2020-02-27 13:45:35 +00001648func PathForNdkInstall(ctx PathContext, paths ...string) InstallPath {
1649 return pathForNdkOrSdkInstall(ctx, "ndk", paths)
1650}
1651
1652func PathForMainlineSdksInstall(ctx PathContext, paths ...string) InstallPath {
1653 return pathForNdkOrSdkInstall(ctx, "mainline-sdks", paths)
1654}
1655
Colin Cross70dda7e2019-10-01 22:05:35 -07001656func InstallPathToOnDevicePath(ctx PathContext, path InstallPath) string {
Colin Cross43f08db2018-11-12 10:13:39 -08001657 rel := Rel(ctx, PathForOutput(ctx, "target", "product", ctx.Config().DeviceName()).String(), path.String())
1658
1659 return "/" + rel
1660}
1661
Colin Cross6e359402020-02-10 15:29:54 -08001662func modulePartition(ctx ModuleInstallPathContext, os OsType) string {
Colin Cross43f08db2018-11-12 10:13:39 -08001663 var partition string
Colin Cross6e359402020-02-10 15:29:54 -08001664 if ctx.InstallInTestcases() {
1665 // "testcases" install directory can be used for host or device modules.
Jaewoong Jung0949f312019-09-11 10:25:18 -07001666 partition = "testcases"
Colin Cross6e359402020-02-10 15:29:54 -08001667 } else if os.Class == Device {
1668 if ctx.InstallInData() {
1669 partition = "data"
1670 } else if ctx.InstallInRamdisk() {
1671 if ctx.DeviceConfig().BoardUsesRecoveryAsBoot() {
1672 partition = "recovery/root/first_stage_ramdisk"
1673 } else {
1674 partition = "ramdisk"
1675 }
1676 if !ctx.InstallInRoot() {
1677 partition += "/system"
1678 }
Yifan Hong60e0cfb2020-10-21 15:17:56 -07001679 } else if ctx.InstallInVendorRamdisk() {
Yifan Hong39143a92020-10-26 12:43:12 -07001680 // The module is only available after switching root into
1681 // /first_stage_ramdisk. To expose the module before switching root
1682 // on a device without a dedicated recovery partition, install the
1683 // recovery variant.
Yifan Hongdd8dacc2020-10-21 15:40:17 -07001684 if ctx.DeviceConfig().BoardMoveRecoveryResourcesToVendorBoot() {
Petri Gyntherac229562021-03-02 23:44:02 -08001685 partition = "vendor_ramdisk/first_stage_ramdisk"
Yifan Hongdd8dacc2020-10-21 15:40:17 -07001686 } else {
Petri Gyntherac229562021-03-02 23:44:02 -08001687 partition = "vendor_ramdisk"
Yifan Hongdd8dacc2020-10-21 15:40:17 -07001688 }
1689 if !ctx.InstallInRoot() {
1690 partition += "/system"
1691 }
Colin Cross6e359402020-02-10 15:29:54 -08001692 } else if ctx.InstallInRecovery() {
1693 if ctx.InstallInRoot() {
1694 partition = "recovery/root"
1695 } else {
1696 // the layout of recovery partion is the same as that of system partition
1697 partition = "recovery/root/system"
1698 }
1699 } else if ctx.SocSpecific() {
1700 partition = ctx.DeviceConfig().VendorPath()
1701 } else if ctx.DeviceSpecific() {
1702 partition = ctx.DeviceConfig().OdmPath()
1703 } else if ctx.ProductSpecific() {
1704 partition = ctx.DeviceConfig().ProductPath()
1705 } else if ctx.SystemExtSpecific() {
1706 partition = ctx.DeviceConfig().SystemExtPath()
1707 } else if ctx.InstallInRoot() {
1708 partition = "root"
Yifan Hong82db7352020-01-21 16:12:26 -08001709 } else {
Colin Cross6e359402020-02-10 15:29:54 -08001710 partition = "system"
Yifan Hong82db7352020-01-21 16:12:26 -08001711 }
Colin Cross6e359402020-02-10 15:29:54 -08001712 if ctx.InstallInSanitizerDir() {
1713 partition = "data/asan/" + partition
Yifan Hong82db7352020-01-21 16:12:26 -08001714 }
Colin Cross43f08db2018-11-12 10:13:39 -08001715 }
1716 return partition
1717}
1718
Colin Cross609c49a2020-02-13 13:20:11 -08001719type InstallPaths []InstallPath
1720
1721// Paths returns the InstallPaths as a Paths
1722func (p InstallPaths) Paths() Paths {
1723 if p == nil {
1724 return nil
1725 }
1726 ret := make(Paths, len(p))
1727 for i, path := range p {
1728 ret[i] = path
1729 }
1730 return ret
1731}
1732
1733// Strings returns the string forms of the install paths.
1734func (p InstallPaths) Strings() []string {
1735 if p == nil {
1736 return nil
1737 }
1738 ret := make([]string, len(p))
1739 for i, path := range p {
1740 ret[i] = path.String()
1741 }
1742 return ret
1743}
1744
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001745// validateSafePath validates a path that we trust (may contain ninja variables).
Dan Willemsen80a7c2a2015-12-21 14:57:11 -08001746// Ensures that each path component does not attempt to leave its component.
Colin Cross1ccfcc32018-02-22 13:54:26 -08001747func validateSafePath(pathComponents ...string) (string, error) {
Jeff Gaston734e3802017-04-10 15:47:24 -07001748 for _, path := range pathComponents {
Dan Willemsen80a7c2a2015-12-21 14:57:11 -08001749 path := filepath.Clean(path)
1750 if path == ".." || strings.HasPrefix(path, "../") || strings.HasPrefix(path, "/") {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001751 return "", fmt.Errorf("Path is outside directory: %s", path)
Dan Willemsen80a7c2a2015-12-21 14:57:11 -08001752 }
1753 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001754 // TODO: filepath.Join isn't necessarily correct with embedded ninja
1755 // variables. '..' may remove the entire ninja variable, even if it
1756 // will be expanded to multiple nested directories.
Colin Cross1ccfcc32018-02-22 13:54:26 -08001757 return filepath.Join(pathComponents...), nil
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001758}
1759
Dan Willemsen80a7c2a2015-12-21 14:57:11 -08001760// validatePath validates that a path does not include ninja variables, and that
1761// each path component does not attempt to leave its component. Returns a joined
1762// version of each path component.
Colin Cross1ccfcc32018-02-22 13:54:26 -08001763func validatePath(pathComponents ...string) (string, error) {
Jeff Gaston734e3802017-04-10 15:47:24 -07001764 for _, path := range pathComponents {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001765 if strings.Contains(path, "$") {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001766 return "", fmt.Errorf("Path contains invalid character($): %s", path)
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001767 }
1768 }
Colin Cross1ccfcc32018-02-22 13:54:26 -08001769 return validateSafePath(pathComponents...)
Colin Cross6e18ca42015-07-14 18:55:36 -07001770}
Colin Cross5b529592017-05-09 13:34:34 -07001771
Colin Cross0875c522017-11-28 17:34:01 -08001772func PathForPhony(ctx PathContext, phony string) WritablePath {
1773 if strings.ContainsAny(phony, "$/") {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001774 ReportPathErrorf(ctx, "Phony target contains invalid character ($ or /): %s", phony)
Colin Cross0875c522017-11-28 17:34:01 -08001775 }
Paul Duffin74abc5d2021-03-24 09:24:59 +00001776 return PhonyPath{basePath{phony, ""}}
Colin Cross0875c522017-11-28 17:34:01 -08001777}
1778
Colin Cross74e3fe42017-12-11 15:51:44 -08001779type PhonyPath struct {
1780 basePath
1781}
1782
1783func (p PhonyPath) writablePath() {}
1784
Paul Duffind65c58b2021-03-24 09:22:07 +00001785func (p PhonyPath) getBuildDir() string {
1786 // A phone path cannot contain any / so cannot be relative to the build directory.
1787 return ""
Paul Duffin9b478b02019-12-10 13:41:51 +00001788}
1789
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001790func (p PhonyPath) RelativeToTop() Path {
1791 ensureTestOnly()
1792 // A phony path cannot contain any / so does not have a build directory so switching to a new
1793 // build directory has no effect so just return this path.
1794 return p
1795}
1796
Hans MÃ¥nssond3f2bd72020-11-27 12:37:28 +01001797func (p PhonyPath) ReplaceExtension(ctx PathContext, ext string) OutputPath {
1798 panic("Not implemented")
1799}
1800
Colin Cross74e3fe42017-12-11 15:51:44 -08001801var _ Path = PhonyPath{}
1802var _ WritablePath = PhonyPath{}
1803
Colin Cross5b529592017-05-09 13:34:34 -07001804type testPath struct {
1805 basePath
1806}
1807
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001808func (p testPath) RelativeToTop() Path {
1809 ensureTestOnly()
1810 return p
1811}
1812
Colin Cross5b529592017-05-09 13:34:34 -07001813func (p testPath) String() string {
1814 return p.path
1815}
1816
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001817var _ Path = testPath{}
1818
Colin Cross40e33732019-02-15 11:08:35 -08001819// PathForTesting returns a Path constructed from joining the elements of paths with '/'. It should only be used from
1820// within tests.
Colin Cross5b529592017-05-09 13:34:34 -07001821func PathForTesting(paths ...string) Path {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001822 p, err := validateSafePath(paths...)
1823 if err != nil {
1824 panic(err)
1825 }
Colin Cross5b529592017-05-09 13:34:34 -07001826 return testPath{basePath{path: p, rel: p}}
1827}
1828
Colin Cross40e33732019-02-15 11:08:35 -08001829// PathsForTesting returns a Path constructed from each element in strs. It should only be used from within tests.
1830func PathsForTesting(strs ...string) Paths {
Colin Cross5b529592017-05-09 13:34:34 -07001831 p := make(Paths, len(strs))
1832 for i, s := range strs {
1833 p[i] = PathForTesting(s)
1834 }
1835
1836 return p
1837}
Colin Cross43f08db2018-11-12 10:13:39 -08001838
Colin Cross40e33732019-02-15 11:08:35 -08001839type testPathContext struct {
1840 config Config
Colin Cross40e33732019-02-15 11:08:35 -08001841}
1842
Colin Cross40e33732019-02-15 11:08:35 -08001843func (x *testPathContext) Config() Config { return x.config }
1844func (x *testPathContext) AddNinjaFileDeps(...string) {}
1845
1846// PathContextForTesting returns a PathContext that can be used in tests, for example to create an OutputPath with
1847// PathForOutput.
Colin Cross98be1bb2019-12-13 20:41:13 -08001848func PathContextForTesting(config Config) PathContext {
Colin Cross40e33732019-02-15 11:08:35 -08001849 return &testPathContext{
1850 config: config,
Colin Cross40e33732019-02-15 11:08:35 -08001851 }
1852}
1853
Ulya Trafimovichccc8c852020-10-14 11:29:07 +01001854type testModuleInstallPathContext struct {
1855 baseModuleContext
1856
1857 inData bool
1858 inTestcases bool
1859 inSanitizerDir bool
1860 inRamdisk bool
1861 inVendorRamdisk bool
1862 inRecovery bool
1863 inRoot bool
1864 forceOS *OsType
1865 forceArch *ArchType
1866}
1867
1868func (m testModuleInstallPathContext) Config() Config {
1869 return m.baseModuleContext.config
1870}
1871
1872func (testModuleInstallPathContext) AddNinjaFileDeps(deps ...string) {}
1873
1874func (m testModuleInstallPathContext) InstallInData() bool {
1875 return m.inData
1876}
1877
1878func (m testModuleInstallPathContext) InstallInTestcases() bool {
1879 return m.inTestcases
1880}
1881
1882func (m testModuleInstallPathContext) InstallInSanitizerDir() bool {
1883 return m.inSanitizerDir
1884}
1885
1886func (m testModuleInstallPathContext) InstallInRamdisk() bool {
1887 return m.inRamdisk
1888}
1889
1890func (m testModuleInstallPathContext) InstallInVendorRamdisk() bool {
1891 return m.inVendorRamdisk
1892}
1893
1894func (m testModuleInstallPathContext) InstallInRecovery() bool {
1895 return m.inRecovery
1896}
1897
1898func (m testModuleInstallPathContext) InstallInRoot() bool {
1899 return m.inRoot
1900}
1901
1902func (m testModuleInstallPathContext) InstallBypassMake() bool {
1903 return false
1904}
1905
1906func (m testModuleInstallPathContext) InstallForceOS() (*OsType, *ArchType) {
1907 return m.forceOS, m.forceArch
1908}
1909
1910// Construct a minimal ModuleInstallPathContext for testing. Note that baseModuleContext is
1911// default-initialized, which leaves blueprint.baseModuleContext set to nil, so methods that are
1912// delegated to it will panic.
1913func ModuleInstallPathContextForTesting(config Config) ModuleInstallPathContext {
1914 ctx := &testModuleInstallPathContext{}
1915 ctx.config = config
1916 ctx.os = Android
1917 return ctx
1918}
1919
Colin Cross43f08db2018-11-12 10:13:39 -08001920// Rel performs the same function as filepath.Rel, but reports errors to a PathContext, and reports an error if
1921// targetPath is not inside basePath.
1922func Rel(ctx PathContext, basePath string, targetPath string) string {
1923 rel, isRel := MaybeRel(ctx, basePath, targetPath)
1924 if !isRel {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001925 ReportPathErrorf(ctx, "path %q is not under path %q", targetPath, basePath)
Colin Cross43f08db2018-11-12 10:13:39 -08001926 return ""
1927 }
1928 return rel
1929}
1930
1931// MaybeRel performs the same function as filepath.Rel, but reports errors to a PathContext, and returns false if
1932// targetPath is not inside basePath.
1933func MaybeRel(ctx PathContext, basePath string, targetPath string) (string, bool) {
Dan Willemsen633c5022019-04-12 11:11:38 -07001934 rel, isRel, err := maybeRelErr(basePath, targetPath)
1935 if err != nil {
1936 reportPathError(ctx, err)
1937 }
1938 return rel, isRel
1939}
1940
1941func maybeRelErr(basePath string, targetPath string) (string, bool, error) {
Colin Cross43f08db2018-11-12 10:13:39 -08001942 // filepath.Rel returns an error if one path is absolute and the other is not, handle that case first.
1943 if filepath.IsAbs(basePath) != filepath.IsAbs(targetPath) {
Dan Willemsen633c5022019-04-12 11:11:38 -07001944 return "", false, nil
Colin Cross43f08db2018-11-12 10:13:39 -08001945 }
1946 rel, err := filepath.Rel(basePath, targetPath)
1947 if err != nil {
Dan Willemsen633c5022019-04-12 11:11:38 -07001948 return "", false, err
Colin Cross43f08db2018-11-12 10:13:39 -08001949 } else if rel == ".." || strings.HasPrefix(rel, "../") || strings.HasPrefix(rel, "/") {
Dan Willemsen633c5022019-04-12 11:11:38 -07001950 return "", false, nil
Colin Cross43f08db2018-11-12 10:13:39 -08001951 }
Dan Willemsen633c5022019-04-12 11:11:38 -07001952 return rel, true, nil
Colin Cross43f08db2018-11-12 10:13:39 -08001953}
Colin Cross988414c2020-01-11 01:11:46 +00001954
1955// Writes a file to the output directory. Attempting to write directly to the output directory
1956// will fail due to the sandbox of the soong_build process.
1957func WriteFileToOutputDir(path WritablePath, data []byte, perm os.FileMode) error {
1958 return ioutil.WriteFile(absolutePath(path.String()), data, perm)
1959}
1960
Liz Kammer2dd9ca42020-11-25 16:06:39 -08001961func RemoveAllOutputDir(path WritablePath) error {
1962 return os.RemoveAll(absolutePath(path.String()))
1963}
1964
1965func CreateOutputDirIfNonexistent(path WritablePath, perm os.FileMode) error {
1966 dir := absolutePath(path.String())
1967 if _, err := os.Stat(dir); os.IsNotExist(err) {
1968 return os.MkdirAll(dir, os.ModePerm)
1969 } else {
1970 return err
1971 }
1972}
1973
Colin Cross988414c2020-01-11 01:11:46 +00001974func absolutePath(path string) string {
1975 if filepath.IsAbs(path) {
1976 return path
1977 }
1978 return filepath.Join(absSrcDir, path)
1979}
Chris Parsons216e10a2020-07-09 17:12:52 -04001980
1981// A DataPath represents the path of a file to be used as data, for example
1982// a test library to be installed alongside a test.
1983// The data file should be installed (copied from `<SrcPath>`) to
1984// `<install_root>/<RelativeInstallPath>/<filename>`, or
1985// `<install_root>/<filename>` if RelativeInstallPath is empty.
1986type DataPath struct {
1987 // The path of the data file that should be copied into the data directory
1988 SrcPath Path
1989 // The install path of the data file, relative to the install root.
1990 RelativeInstallPath string
1991}
Colin Crossdcf71b22021-02-01 13:59:03 -08001992
1993// PathsIfNonNil returns a Paths containing only the non-nil input arguments.
1994func PathsIfNonNil(paths ...Path) Paths {
1995 if len(paths) == 0 {
1996 // Fast path for empty argument list
1997 return nil
1998 } else if len(paths) == 1 {
1999 // Fast path for a single argument
2000 if paths[0] != nil {
2001 return paths
2002 } else {
2003 return nil
2004 }
2005 }
2006 ret := make(Paths, 0, len(paths))
2007 for _, path := range paths {
2008 if path != nil {
2009 ret = append(ret, path)
2010 }
2011 }
2012 if len(ret) == 0 {
2013 return nil
2014 }
2015 return ret
2016}