blob: 026cb8747c249efa35b56bc7df682982fa6c1d6c [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
Inseob Kimf84e9c02021-04-08 21:13:22 +0900109 InstallInDebugRamdisk() bool
Jiyong Parkf9332f12018-02-01 00:54:12 +0900110 InstallInRecovery() bool
Colin Cross90ba5f42019-10-02 11:10:58 -0700111 InstallInRoot() bool
Colin Cross607d8582019-07-29 16:44:46 -0700112 InstallBypassMake() bool
Jiyong Park87788b52020-09-01 12:37:45 +0900113 InstallForceOS() (*OsType, *ArchType)
Dan Willemsen00269f22017-07-06 16:59:48 -0700114}
115
116var _ ModuleInstallPathContext = ModuleContext(nil)
117
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700118// errorfContext is the interface containing the Errorf method matching the
119// Errorf method in blueprint.SingletonContext.
120type errorfContext interface {
121 Errorf(format string, args ...interface{})
Colin Cross3f40fa42015-01-30 17:27:36 -0800122}
123
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700124var _ errorfContext = blueprint.SingletonContext(nil)
125
126// moduleErrorf is the interface containing the ModuleErrorf method matching
127// the ModuleErrorf method in blueprint.ModuleContext.
128type moduleErrorf interface {
129 ModuleErrorf(format string, args ...interface{})
Colin Cross3f40fa42015-01-30 17:27:36 -0800130}
131
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700132var _ moduleErrorf = blueprint.ModuleContext(nil)
133
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700134// reportPathError will register an error with the attached context. It
135// attempts ctx.ModuleErrorf for a better error message first, then falls
136// back to ctx.Errorf.
Colin Cross1ccfcc32018-02-22 13:54:26 -0800137func reportPathError(ctx PathContext, err error) {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +0100138 ReportPathErrorf(ctx, "%s", err.Error())
Colin Cross1ccfcc32018-02-22 13:54:26 -0800139}
140
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +0100141// ReportPathErrorf will register an error with the attached context. It
Colin Cross1ccfcc32018-02-22 13:54:26 -0800142// attempts ctx.ModuleErrorf for a better error message first, then falls
143// back to ctx.Errorf.
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +0100144func ReportPathErrorf(ctx PathContext, format string, args ...interface{}) {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700145 if mctx, ok := ctx.(moduleErrorf); ok {
146 mctx.ModuleErrorf(format, args...)
147 } else if ectx, ok := ctx.(errorfContext); ok {
148 ectx.Errorf(format, args...)
149 } else {
150 panic(fmt.Sprintf(format, args...))
Colin Crossf2298272015-05-12 11:36:53 -0700151 }
152}
153
Colin Cross5e708052019-08-06 13:59:50 -0700154func pathContextName(ctx PathContext, module blueprint.Module) string {
155 if x, ok := ctx.(interface{ ModuleName(blueprint.Module) string }); ok {
156 return x.ModuleName(module)
157 } else if x, ok := ctx.(interface{ OtherModuleName(blueprint.Module) string }); ok {
158 return x.OtherModuleName(module)
159 }
160 return "unknown"
161}
162
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700163type Path interface {
164 // Returns the path in string form
165 String() string
166
Colin Cross4f6fc9c2016-10-26 10:05:25 -0700167 // Ext returns the extension of the last element of the path
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700168 Ext() string
Colin Cross4f6fc9c2016-10-26 10:05:25 -0700169
170 // Base returns the last element of the path
171 Base() string
Colin Crossfaeb7aa2017-02-01 14:12:44 -0800172
173 // Rel returns the portion of the path relative to the directory it was created from. For
174 // example, Rel on a PathsForModuleSrc would return the path relative to the module source
Colin Cross0db55682017-12-05 15:36:55 -0800175 // directory, and OutputPath.Join("foo").Rel() would return "foo".
Colin Crossfaeb7aa2017-02-01 14:12:44 -0800176 Rel() string
Paul Duffin85d8f0d2021-03-24 10:18:18 +0000177
178 // RelativeToTop returns a new path relative to the top, it is provided solely for use in tests.
179 //
180 // It is guaranteed to always return the same type as it is called on, e.g. if called on an
181 // InstallPath then the returned value can be converted to an InstallPath.
182 //
183 // A standard build has the following structure:
184 // ../top/
185 // out/ - make install files go here.
186 // out/soong - this is the buildDir passed to NewTestConfig()
187 // ... - the source files
188 //
189 // This function converts a path so that it appears relative to the ../top/ directory, i.e.
190 // * Make install paths, which have the pattern "buildDir/../<path>" are converted into the top
191 // relative path "out/<path>"
192 // * Soong install paths and other writable paths, which have the pattern "buildDir/<path>" are
193 // converted into the top relative path "out/soong/<path>".
194 // * Source paths are already relative to the top.
195 // * Phony paths are not relative to anything.
196 // * toolDepPath have an absolute but known value in so don't need making relative to anything in
197 // order to test.
198 RelativeToTop() Path
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700199}
200
Paul Duffin85d8f0d2021-03-24 10:18:18 +0000201const (
202 OutDir = "out"
203 OutSoongDir = OutDir + "/soong"
204)
205
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700206// WritablePath is a type of path that can be used as an output for build rules.
207type WritablePath interface {
208 Path
209
Paul Duffin9b478b02019-12-10 13:41:51 +0000210 // return the path to the build directory.
Paul Duffind65c58b2021-03-24 09:22:07 +0000211 getBuildDir() string
Paul Duffin9b478b02019-12-10 13:41:51 +0000212
Jeff Gaston734e3802017-04-10 15:47:24 -0700213 // the writablePath method doesn't directly do anything,
214 // but it allows a struct to distinguish between whether or not it implements the WritablePath interface
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700215 writablePath()
Hans MÃ¥nssond3f2bd72020-11-27 12:37:28 +0100216
217 ReplaceExtension(ctx PathContext, ext string) OutputPath
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700218}
219
220type genPathProvider interface {
Liz Kammera830f3a2020-11-10 10:50:34 -0800221 genPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleGenPath
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700222}
223type objPathProvider interface {
Liz Kammera830f3a2020-11-10 10:50:34 -0800224 objPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleObjPath
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700225}
226type resPathProvider interface {
Liz Kammera830f3a2020-11-10 10:50:34 -0800227 resPathWithName(ctx ModuleOutPathContext, name string) ModuleResPath
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700228}
229
230// GenPathWithExt derives a new file path in ctx's generated sources directory
231// from the current path, but with the new extension.
Liz Kammera830f3a2020-11-10 10:50:34 -0800232func GenPathWithExt(ctx ModuleOutPathContext, subdir string, p Path, ext string) ModuleGenPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700233 if path, ok := p.(genPathProvider); ok {
Dan Willemsen21ec4902016-11-02 20:43:13 -0700234 return path.genPathWithExt(ctx, subdir, ext)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700235 }
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +0100236 ReportPathErrorf(ctx, "Tried to create generated file from unsupported path: %s(%s)", reflect.TypeOf(p).Name(), p)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700237 return PathForModuleGen(ctx)
238}
239
240// ObjPathWithExt derives a new file path in ctx's object directory from the
241// current path, but with the new extension.
Liz Kammera830f3a2020-11-10 10:50:34 -0800242func ObjPathWithExt(ctx ModuleOutPathContext, subdir string, p Path, ext string) ModuleObjPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700243 if path, ok := p.(objPathProvider); ok {
244 return path.objPathWithExt(ctx, subdir, ext)
245 }
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +0100246 ReportPathErrorf(ctx, "Tried to create object file from unsupported path: %s (%s)", reflect.TypeOf(p).Name(), p)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700247 return PathForModuleObj(ctx)
248}
249
250// ResPathWithName derives a new path in ctx's output resource directory, using
251// the current path to create the directory name, and the `name` argument for
252// the filename.
Liz Kammera830f3a2020-11-10 10:50:34 -0800253func ResPathWithName(ctx ModuleOutPathContext, p Path, name string) ModuleResPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700254 if path, ok := p.(resPathProvider); ok {
255 return path.resPathWithName(ctx, name)
256 }
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +0100257 ReportPathErrorf(ctx, "Tried to create res file from unsupported path: %s (%s)", reflect.TypeOf(p).Name(), p)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700258 return PathForModuleRes(ctx)
259}
260
261// OptionalPath is a container that may or may not contain a valid Path.
262type OptionalPath struct {
263 valid bool
264 path Path
265}
266
267// OptionalPathForPath returns an OptionalPath containing the path.
268func OptionalPathForPath(path Path) OptionalPath {
269 if path == nil {
270 return OptionalPath{}
271 }
272 return OptionalPath{valid: true, path: path}
273}
274
275// Valid returns whether there is a valid path
276func (p OptionalPath) Valid() bool {
277 return p.valid
278}
279
280// Path returns the Path embedded in this OptionalPath. You must be sure that
281// there is a valid path, since this method will panic if there is not.
282func (p OptionalPath) Path() Path {
283 if !p.valid {
284 panic("Requesting an invalid path")
285 }
286 return p.path
287}
288
Paul Duffinafdd4062021-03-30 19:44:07 +0100289// RelativeToTop returns an OptionalPath with the path that was embedded having been replaced by the
290// result of calling Path.RelativeToTop on it.
291func (p OptionalPath) RelativeToTop() OptionalPath {
Paul Duffina5b81352021-03-28 23:57:19 +0100292 if !p.valid {
293 return p
294 }
295 p.path = p.path.RelativeToTop()
296 return p
297}
298
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700299// String returns the string version of the Path, or "" if it isn't valid.
300func (p OptionalPath) String() string {
301 if p.valid {
302 return p.path.String()
303 } else {
304 return ""
Colin Crossf2298272015-05-12 11:36:53 -0700305 }
306}
Colin Cross6e18ca42015-07-14 18:55:36 -0700307
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700308// Paths is a slice of Path objects, with helpers to operate on the collection.
309type Paths []Path
310
Paul Duffin85d8f0d2021-03-24 10:18:18 +0000311// RelativeToTop creates a new Paths containing the result of calling Path.RelativeToTop on each
312// item in this slice.
313func (p Paths) RelativeToTop() Paths {
314 ensureTestOnly()
315 if p == nil {
316 return p
317 }
318 ret := make(Paths, len(p))
319 for i, path := range p {
320 ret[i] = path.RelativeToTop()
321 }
322 return ret
323}
324
Jingwen Chen40fd90a2020-06-15 05:24:19 +0000325func (paths Paths) containsPath(path Path) bool {
326 for _, p := range paths {
327 if p == path {
328 return true
329 }
330 }
331 return false
332}
333
Liz Kammer7aa52882021-02-11 09:16:14 -0500334// PathsForSource returns Paths rooted from SrcDir, *not* rooted from the module's local source
335// directory
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700336func PathsForSource(ctx PathContext, paths []string) Paths {
337 ret := make(Paths, len(paths))
338 for i, path := range paths {
339 ret[i] = PathForSource(ctx, path)
340 }
341 return ret
342}
343
Liz Kammer7aa52882021-02-11 09:16:14 -0500344// ExistentPathsForSources returns a list of Paths rooted from SrcDir, *not* rooted from the
345// module's local source directory, that are found in the tree. If any are not found, they are
346// omitted from the list, and dependencies are added so that we're re-run when they are added.
Colin Cross32f38982018-02-22 11:47:25 -0800347func ExistentPathsForSources(ctx PathContext, paths []string) Paths {
Dan Willemsen7b310ee2015-12-18 15:11:17 -0800348 ret := make(Paths, 0, len(paths))
349 for _, path := range paths {
Colin Cross32f38982018-02-22 11:47:25 -0800350 p := ExistentPathForSource(ctx, path)
Dan Willemsen7b310ee2015-12-18 15:11:17 -0800351 if p.Valid() {
352 ret = append(ret, p.Path())
353 }
354 }
355 return ret
356}
357
Liz Kammer620dea62021-04-14 17:36:10 -0400358// PathsForModuleSrc returns a Paths{} containing the resolved references in paths:
359// * filepath, relative to local module directory, resolves as a filepath relative to the local
360// source directory
361// * glob, relative to the local module directory, resolves as filepath(s), relative to the local
362// source directory.
363// * other modules using the ":name{.tag}" syntax. These modules must implement SourceFileProducer
364// or OutputFileProducer. These resolve as a filepath to an output filepath or generated source
365// filepath.
366// Properties passed as the paths argument must have been annotated with struct tag
Colin Cross41955e82019-05-29 14:40:35 -0700367// `android:"path"` so that dependencies on SourceFileProducer modules will have already been handled by the
Liz Kammer620dea62021-04-14 17:36:10 -0400368// path_deps mutator.
369// If a requested module is not found as a dependency:
370// * if ctx.Config().AllowMissingDependencies() is true, this module to be marked as having
371// missing dependencies
372// * otherwise, a ModuleError is thrown.
Liz Kammera830f3a2020-11-10 10:50:34 -0800373func PathsForModuleSrc(ctx ModuleMissingDepsPathContext, paths []string) Paths {
Colin Cross8a497952019-03-05 22:25:09 -0800374 return PathsForModuleSrcExcludes(ctx, paths, nil)
375}
376
Liz Kammer620dea62021-04-14 17:36:10 -0400377// PathsForModuleSrcExcludes returns a Paths{} containing the resolved references in paths, minus
378// those listed in excludes. Elements of paths and excludes are resolved as:
379// * filepath, relative to local module directory, resolves as a filepath relative to the local
380// source directory
381// * glob, relative to the local module directory, resolves as filepath(s), relative to the local
382// source directory. Not valid in excludes.
383// * other modules using the ":name{.tag}" syntax. These modules must implement SourceFileProducer
384// or OutputFileProducer. These resolve as a filepath to an output filepath or generated source
385// filepath.
386// excluding the items (similarly resolved
387// Properties passed as the paths argument must have been annotated with struct tag
388// `android:"path"` so that dependencies on SourceFileProducer modules will have already been handled by the
389// path_deps mutator.
390// If a requested module is not found as a dependency:
391// * if ctx.Config().AllowMissingDependencies() is true, this module to be marked as having
392// missing dependencies
393// * otherwise, a ModuleError is thrown.
Liz Kammera830f3a2020-11-10 10:50:34 -0800394func PathsForModuleSrcExcludes(ctx ModuleMissingDepsPathContext, paths, excludes []string) Paths {
Colin Crossba71a3f2019-03-18 12:12:48 -0700395 ret, missingDeps := PathsAndMissingDepsForModuleSrcExcludes(ctx, paths, excludes)
396 if ctx.Config().AllowMissingDependencies() {
397 ctx.AddMissingDependencies(missingDeps)
398 } else {
399 for _, m := range missingDeps {
400 ctx.ModuleErrorf(`missing dependency on %q, is the property annotated with android:"path"?`, m)
401 }
402 }
403 return ret
404}
405
Ulya Trafimovich4d2eeed2019-11-08 10:54:21 +0000406// OutputPaths is a slice of OutputPath objects, with helpers to operate on the collection.
407type OutputPaths []OutputPath
408
409// Paths returns the OutputPaths as a Paths
410func (p OutputPaths) Paths() Paths {
411 if p == nil {
412 return nil
413 }
414 ret := make(Paths, len(p))
415 for i, path := range p {
416 ret[i] = path
417 }
418 return ret
419}
420
421// Strings returns the string forms of the writable paths.
422func (p OutputPaths) Strings() []string {
423 if p == nil {
424 return nil
425 }
426 ret := make([]string, len(p))
427 for i, path := range p {
428 ret[i] = path.String()
429 }
430 return ret
431}
432
Liz Kammera830f3a2020-11-10 10:50:34 -0800433// Expands Paths to a SourceFileProducer or OutputFileProducer module dependency referenced via ":name" or ":name{.tag}" syntax.
434// If the dependency is not found, a missingErrorDependency is returned.
435// If the module dependency is not a SourceFileProducer or OutputFileProducer, appropriate errors will be returned.
436func getPathsFromModuleDep(ctx ModuleWithDepsPathContext, path, moduleName, tag string) (Paths, error) {
437 module := ctx.GetDirectDepWithTag(moduleName, sourceOrOutputDepTag(tag))
438 if module == nil {
439 return nil, missingDependencyError{[]string{moduleName}}
440 }
Colin Crossfa65cee2021-03-22 17:05:59 -0700441 if aModule, ok := module.(Module); ok && !aModule.Enabled() {
442 return nil, missingDependencyError{[]string{moduleName}}
443 }
Liz Kammera830f3a2020-11-10 10:50:34 -0800444 if outProducer, ok := module.(OutputFileProducer); ok {
445 outputFiles, err := outProducer.OutputFiles(tag)
446 if err != nil {
447 return nil, fmt.Errorf("path dependency %q: %s", path, err)
448 }
449 return outputFiles, nil
450 } else if tag != "" {
451 return nil, fmt.Errorf("path dependency %q is not an output file producing module", path)
452 } else if srcProducer, ok := module.(SourceFileProducer); ok {
453 return srcProducer.Srcs(), nil
454 } else {
455 return nil, fmt.Errorf("path dependency %q is not a source file producing module", path)
456 }
457}
458
Liz Kammer620dea62021-04-14 17:36:10 -0400459// PathsAndMissingDepsForModuleSrcExcludes returns a Paths{} containing the resolved references in
460// paths, minus those listed in excludes. Elements of paths and excludes are resolved as:
461// * filepath, relative to local module directory, resolves as a filepath relative to the local
462// source directory
463// * glob, relative to the local module directory, resolves as filepath(s), relative to the local
464// source directory. Not valid in excludes.
465// * other modules using the ":name{.tag}" syntax. These modules must implement SourceFileProducer
466// or OutputFileProducer. These resolve as a filepath to an output filepath or generated source
467// filepath.
468// and a list of the module names of missing module dependencies are returned as the second return.
469// Properties passed as the paths argument must have been annotated with struct tag
Colin Cross41955e82019-05-29 14:40:35 -0700470// `android:"path"` so that dependencies on SourceFileProducer modules will have already been handled by the
Liz Kammer620dea62021-04-14 17:36:10 -0400471// path_deps mutator.
Liz Kammera830f3a2020-11-10 10:50:34 -0800472func PathsAndMissingDepsForModuleSrcExcludes(ctx ModuleWithDepsPathContext, paths, excludes []string) (Paths, []string) {
Colin Cross8a497952019-03-05 22:25:09 -0800473 prefix := pathForModuleSrc(ctx).String()
474
475 var expandedExcludes []string
476 if excludes != nil {
477 expandedExcludes = make([]string, 0, len(excludes))
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700478 }
Colin Cross8a497952019-03-05 22:25:09 -0800479
Colin Crossba71a3f2019-03-18 12:12:48 -0700480 var missingExcludeDeps []string
481
Colin Cross8a497952019-03-05 22:25:09 -0800482 for _, e := range excludes {
Colin Cross41955e82019-05-29 14:40:35 -0700483 if m, t := SrcIsModuleWithTag(e); m != "" {
Liz Kammera830f3a2020-11-10 10:50:34 -0800484 modulePaths, err := getPathsFromModuleDep(ctx, e, m, t)
485 if m, ok := err.(missingDependencyError); ok {
486 missingExcludeDeps = append(missingExcludeDeps, m.missingDeps...)
487 } else if err != nil {
488 reportPathError(ctx, err)
Colin Cross8a497952019-03-05 22:25:09 -0800489 } else {
Liz Kammera830f3a2020-11-10 10:50:34 -0800490 expandedExcludes = append(expandedExcludes, modulePaths.Strings()...)
Colin Cross8a497952019-03-05 22:25:09 -0800491 }
492 } else {
493 expandedExcludes = append(expandedExcludes, filepath.Join(prefix, e))
494 }
495 }
496
497 if paths == nil {
Colin Crossba71a3f2019-03-18 12:12:48 -0700498 return nil, missingExcludeDeps
Colin Cross8a497952019-03-05 22:25:09 -0800499 }
500
Colin Crossba71a3f2019-03-18 12:12:48 -0700501 var missingDeps []string
502
Colin Cross8a497952019-03-05 22:25:09 -0800503 expandedSrcFiles := make(Paths, 0, len(paths))
504 for _, s := range paths {
505 srcFiles, err := expandOneSrcPath(ctx, s, expandedExcludes)
506 if depErr, ok := err.(missingDependencyError); ok {
Colin Crossba71a3f2019-03-18 12:12:48 -0700507 missingDeps = append(missingDeps, depErr.missingDeps...)
Colin Cross8a497952019-03-05 22:25:09 -0800508 } else if err != nil {
509 reportPathError(ctx, err)
510 }
511 expandedSrcFiles = append(expandedSrcFiles, srcFiles...)
512 }
Colin Crossba71a3f2019-03-18 12:12:48 -0700513
514 return expandedSrcFiles, append(missingDeps, missingExcludeDeps...)
Colin Cross8a497952019-03-05 22:25:09 -0800515}
516
517type missingDependencyError struct {
518 missingDeps []string
519}
520
521func (e missingDependencyError) Error() string {
522 return "missing dependencies: " + strings.Join(e.missingDeps, ", ")
523}
524
Liz Kammera830f3a2020-11-10 10:50:34 -0800525// Expands one path string to Paths rooted from the module's local source
526// directory, excluding those listed in the expandedExcludes.
527// Expands globs, references to SourceFileProducer or OutputFileProducer modules using the ":name" and ":name{.tag}" syntax.
528func expandOneSrcPath(ctx ModuleWithDepsPathContext, sPath string, expandedExcludes []string) (Paths, error) {
Jooyung Han7607dd32020-07-05 10:23:14 +0900529 excludePaths := func(paths Paths) Paths {
530 if len(expandedExcludes) == 0 {
531 return paths
532 }
533 remainder := make(Paths, 0, len(paths))
534 for _, p := range paths {
535 if !InList(p.String(), expandedExcludes) {
536 remainder = append(remainder, p)
537 }
538 }
539 return remainder
540 }
Liz Kammera830f3a2020-11-10 10:50:34 -0800541 if m, t := SrcIsModuleWithTag(sPath); m != "" {
542 modulePaths, err := getPathsFromModuleDep(ctx, sPath, m, t)
543 if err != nil {
544 return nil, err
Colin Cross8a497952019-03-05 22:25:09 -0800545 } else {
Liz Kammera830f3a2020-11-10 10:50:34 -0800546 return excludePaths(modulePaths), nil
Colin Cross8a497952019-03-05 22:25:09 -0800547 }
Liz Kammera830f3a2020-11-10 10:50:34 -0800548 } else if pathtools.IsGlob(sPath) {
549 paths := GlobFiles(ctx, pathForModuleSrc(ctx, sPath).String(), expandedExcludes)
Colin Cross8a497952019-03-05 22:25:09 -0800550 return PathsWithModuleSrcSubDir(ctx, paths, ""), nil
551 } else {
Liz Kammera830f3a2020-11-10 10:50:34 -0800552 p := pathForModuleSrc(ctx, sPath)
Colin Cross988414c2020-01-11 01:11:46 +0000553 if exists, _, err := ctx.Config().fs.Exists(p.String()); err != nil {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +0100554 ReportPathErrorf(ctx, "%s: %s", p, err.Error())
Pedro Loureiro5d190cc2021-02-15 15:41:33 +0000555 } else if !exists && !ctx.Config().TestAllowNonExistentPaths {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +0100556 ReportPathErrorf(ctx, "module source path %q does not exist", p)
Colin Cross8a497952019-03-05 22:25:09 -0800557 }
558
Jooyung Han7607dd32020-07-05 10:23:14 +0900559 if InList(p.String(), expandedExcludes) {
Colin Cross8a497952019-03-05 22:25:09 -0800560 return nil, nil
561 }
562 return Paths{p}, nil
563 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700564}
565
566// pathsForModuleSrcFromFullPath returns Paths rooted from the module's local
567// source directory, but strip the local source directory from the beginning of
Dan Willemsen540a78c2018-02-26 21:50:08 -0800568// each string. If incDirs is false, strip paths with a trailing '/' from the list.
Colin Crossfe4bc362018-09-12 10:02:13 -0700569// It intended for use in globs that only list files that exist, so it allows '$' in
570// filenames.
Liz Kammera830f3a2020-11-10 10:50:34 -0800571func pathsForModuleSrcFromFullPath(ctx EarlyModulePathContext, paths []string, incDirs bool) Paths {
Colin Cross6510f912017-11-29 00:27:14 -0800572 prefix := filepath.Join(ctx.Config().srcDir, ctx.ModuleDir()) + "/"
Colin Cross0f37af02017-09-27 17:42:05 -0700573 if prefix == "./" {
574 prefix = ""
575 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700576 ret := make(Paths, 0, len(paths))
577 for _, p := range paths {
Dan Willemsen540a78c2018-02-26 21:50:08 -0800578 if !incDirs && strings.HasSuffix(p, "/") {
579 continue
580 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700581 path := filepath.Clean(p)
582 if !strings.HasPrefix(path, prefix) {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +0100583 ReportPathErrorf(ctx, "Path %q is not in module source directory %q", p, prefix)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700584 continue
585 }
Colin Crosse3924e12018-08-15 20:18:53 -0700586
Colin Crossfe4bc362018-09-12 10:02:13 -0700587 srcPath, err := safePathForSource(ctx, ctx.ModuleDir(), path[len(prefix):])
Colin Crosse3924e12018-08-15 20:18:53 -0700588 if err != nil {
589 reportPathError(ctx, err)
590 continue
591 }
592
Colin Cross07e51612019-03-05 12:46:40 -0800593 srcPath.basePath.rel = srcPath.path
Colin Crosse3924e12018-08-15 20:18:53 -0700594
Colin Cross07e51612019-03-05 12:46:40 -0800595 ret = append(ret, srcPath)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700596 }
597 return ret
598}
599
Liz Kammera830f3a2020-11-10 10:50:34 -0800600// PathsWithOptionalDefaultForModuleSrc returns Paths rooted from the module's local source
601// directory. If input is nil, use the default if it exists. If input is empty, returns nil.
602func PathsWithOptionalDefaultForModuleSrc(ctx ModuleMissingDepsPathContext, input []string, def string) Paths {
Colin Cross0ddae7f2019-02-07 15:30:01 -0800603 if input != nil {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700604 return PathsForModuleSrc(ctx, input)
605 }
606 // Use Glob so that if the default doesn't exist, a dependency is added so that when it
607 // is created, we're run again.
Colin Cross6510f912017-11-29 00:27:14 -0800608 path := filepath.Join(ctx.Config().srcDir, ctx.ModuleDir(), def)
Liz Kammera830f3a2020-11-10 10:50:34 -0800609 return Glob(ctx, path, nil)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700610}
611
612// Strings returns the Paths in string form
613func (p Paths) Strings() []string {
614 if p == nil {
615 return nil
616 }
617 ret := make([]string, len(p))
618 for i, path := range p {
619 ret[i] = path.String()
620 }
621 return ret
622}
623
Colin Crossc0efd1d2020-07-03 11:56:24 -0700624func CopyOfPaths(paths Paths) Paths {
625 return append(Paths(nil), paths...)
626}
627
Colin Crossb6715442017-10-24 11:13:31 -0700628// FirstUniquePaths returns all unique elements of a Paths, keeping the first copy of each. It
629// modifies the Paths slice contents in place, and returns a subslice of the original slice.
Dan Willemsenfe92c962017-08-29 12:28:37 -0700630func FirstUniquePaths(list Paths) Paths {
Colin Cross27027c72020-02-28 15:34:17 -0800631 // 128 was chosen based on BenchmarkFirstUniquePaths results.
632 if len(list) > 128 {
633 return firstUniquePathsMap(list)
634 }
635 return firstUniquePathsList(list)
636}
637
Colin Crossc0efd1d2020-07-03 11:56:24 -0700638// SortedUniquePaths returns all unique elements of a Paths in sorted order. It modifies the
639// Paths slice contents in place, and returns a subslice of the original slice.
Jiyong Park33c77362020-05-29 22:00:16 +0900640func SortedUniquePaths(list Paths) Paths {
641 unique := FirstUniquePaths(list)
642 sort.Slice(unique, func(i, j int) bool {
643 return unique[i].String() < unique[j].String()
644 })
645 return unique
646}
647
Colin Cross27027c72020-02-28 15:34:17 -0800648func firstUniquePathsList(list Paths) Paths {
Dan Willemsenfe92c962017-08-29 12:28:37 -0700649 k := 0
650outer:
651 for i := 0; i < len(list); i++ {
652 for j := 0; j < k; j++ {
653 if list[i] == list[j] {
654 continue outer
655 }
656 }
657 list[k] = list[i]
658 k++
659 }
660 return list[:k]
661}
662
Colin Cross27027c72020-02-28 15:34:17 -0800663func firstUniquePathsMap(list Paths) Paths {
664 k := 0
665 seen := make(map[Path]bool, len(list))
666 for i := 0; i < len(list); i++ {
667 if seen[list[i]] {
668 continue
669 }
670 seen[list[i]] = true
671 list[k] = list[i]
672 k++
673 }
674 return list[:k]
675}
676
Colin Cross5d583952020-11-24 16:21:24 -0800677// FirstUniqueInstallPaths returns all unique elements of an InstallPaths, keeping the first copy of each. It
678// modifies the InstallPaths slice contents in place, and returns a subslice of the original slice.
679func FirstUniqueInstallPaths(list InstallPaths) InstallPaths {
680 // 128 was chosen based on BenchmarkFirstUniquePaths results.
681 if len(list) > 128 {
682 return firstUniqueInstallPathsMap(list)
683 }
684 return firstUniqueInstallPathsList(list)
685}
686
687func firstUniqueInstallPathsList(list InstallPaths) InstallPaths {
688 k := 0
689outer:
690 for i := 0; i < len(list); i++ {
691 for j := 0; j < k; j++ {
692 if list[i] == list[j] {
693 continue outer
694 }
695 }
696 list[k] = list[i]
697 k++
698 }
699 return list[:k]
700}
701
702func firstUniqueInstallPathsMap(list InstallPaths) InstallPaths {
703 k := 0
704 seen := make(map[InstallPath]bool, len(list))
705 for i := 0; i < len(list); i++ {
706 if seen[list[i]] {
707 continue
708 }
709 seen[list[i]] = true
710 list[k] = list[i]
711 k++
712 }
713 return list[:k]
714}
715
Colin Crossb6715442017-10-24 11:13:31 -0700716// LastUniquePaths returns all unique elements of a Paths, keeping the last copy of each. It
717// modifies the Paths slice contents in place, and returns a subslice of the original slice.
718func LastUniquePaths(list Paths) Paths {
719 totalSkip := 0
720 for i := len(list) - 1; i >= totalSkip; i-- {
721 skip := 0
722 for j := i - 1; j >= totalSkip; j-- {
723 if list[i] == list[j] {
724 skip++
725 } else {
726 list[j+skip] = list[j]
727 }
728 }
729 totalSkip += skip
730 }
731 return list[totalSkip:]
732}
733
Colin Crossa140bb02018-04-17 10:52:26 -0700734// ReversePaths returns a copy of a Paths in reverse order.
735func ReversePaths(list Paths) Paths {
736 if list == nil {
737 return nil
738 }
739 ret := make(Paths, len(list))
740 for i := range list {
741 ret[i] = list[len(list)-1-i]
742 }
743 return ret
744}
745
Jeff Gaston294356f2017-09-27 17:05:30 -0700746func indexPathList(s Path, list []Path) int {
747 for i, l := range list {
748 if l == s {
749 return i
750 }
751 }
752
753 return -1
754}
755
756func inPathList(p Path, list []Path) bool {
757 return indexPathList(p, list) != -1
758}
759
760func FilterPathList(list []Path, filter []Path) (remainder []Path, filtered []Path) {
Paul Duffin57b9e1d2019-12-13 00:03:35 +0000761 return FilterPathListPredicate(list, func(p Path) bool { return inPathList(p, filter) })
762}
763
764func FilterPathListPredicate(list []Path, predicate func(Path) bool) (remainder []Path, filtered []Path) {
Jeff Gaston294356f2017-09-27 17:05:30 -0700765 for _, l := range list {
Paul Duffin57b9e1d2019-12-13 00:03:35 +0000766 if predicate(l) {
Jeff Gaston294356f2017-09-27 17:05:30 -0700767 filtered = append(filtered, l)
768 } else {
769 remainder = append(remainder, l)
770 }
771 }
772
773 return
774}
775
Colin Cross93e85952017-08-15 13:34:18 -0700776// HasExt returns true of any of the paths have extension ext, otherwise false
777func (p Paths) HasExt(ext string) bool {
778 for _, path := range p {
779 if path.Ext() == ext {
780 return true
781 }
782 }
783
784 return false
785}
786
787// FilterByExt returns the subset of the paths that have extension ext
788func (p Paths) FilterByExt(ext string) Paths {
789 ret := make(Paths, 0, len(p))
790 for _, path := range p {
791 if path.Ext() == ext {
792 ret = append(ret, path)
793 }
794 }
795 return ret
796}
797
798// FilterOutByExt returns the subset of the paths that do not have extension ext
799func (p Paths) FilterOutByExt(ext string) Paths {
800 ret := make(Paths, 0, len(p))
801 for _, path := range p {
802 if path.Ext() != ext {
803 ret = append(ret, path)
804 }
805 }
806 return ret
807}
808
Colin Cross5e6cfbe2017-11-03 15:20:35 -0700809// DirectorySortedPaths is a slice of paths that are sorted such that all files in a directory
810// (including subdirectories) are in a contiguous subslice of the list, and can be found in
811// O(log(N)) time using a binary search on the directory prefix.
812type DirectorySortedPaths Paths
813
814func PathsToDirectorySortedPaths(paths Paths) DirectorySortedPaths {
815 ret := append(DirectorySortedPaths(nil), paths...)
816 sort.Slice(ret, func(i, j int) bool {
817 return ret[i].String() < ret[j].String()
818 })
819 return ret
820}
821
822// PathsInDirectory returns a subslice of the DirectorySortedPaths as a Paths that contains all entries
823// that are in the specified directory and its subdirectories.
824func (p DirectorySortedPaths) PathsInDirectory(dir string) Paths {
825 prefix := filepath.Clean(dir) + "/"
826 start := sort.Search(len(p), func(i int) bool {
827 return prefix < p[i].String()
828 })
829
830 ret := p[start:]
831
832 end := sort.Search(len(ret), func(i int) bool {
833 return !strings.HasPrefix(ret[i].String(), prefix)
834 })
835
836 ret = ret[:end]
837
838 return Paths(ret)
839}
840
Alex Humesky29e3bbe2020-11-20 21:30:13 -0500841// WritablePaths is a slice of WritablePath, used for multiple outputs.
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700842type WritablePaths []WritablePath
843
Paul Duffin85d8f0d2021-03-24 10:18:18 +0000844// RelativeToTop creates a new WritablePaths containing the result of calling Path.RelativeToTop on
845// each item in this slice.
846func (p WritablePaths) RelativeToTop() WritablePaths {
847 ensureTestOnly()
848 if p == nil {
849 return p
850 }
851 ret := make(WritablePaths, len(p))
852 for i, path := range p {
853 ret[i] = path.RelativeToTop().(WritablePath)
854 }
855 return ret
856}
857
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700858// Strings returns the string forms of the writable paths.
859func (p WritablePaths) Strings() []string {
860 if p == nil {
861 return nil
862 }
863 ret := make([]string, len(p))
864 for i, path := range p {
865 ret[i] = path.String()
866 }
867 return ret
868}
869
Colin Cross3bc7ffa2017-11-22 16:19:37 -0800870// Paths returns the WritablePaths as a Paths
871func (p WritablePaths) Paths() Paths {
872 if p == nil {
873 return nil
874 }
875 ret := make(Paths, len(p))
876 for i, path := range p {
877 ret[i] = path
878 }
879 return ret
880}
881
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700882type basePath struct {
Paul Duffin74abc5d2021-03-24 09:24:59 +0000883 path string
884 rel string
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700885}
886
887func (p basePath) Ext() string {
888 return filepath.Ext(p.path)
889}
890
Colin Cross4f6fc9c2016-10-26 10:05:25 -0700891func (p basePath) Base() string {
892 return filepath.Base(p.path)
893}
894
Colin Crossfaeb7aa2017-02-01 14:12:44 -0800895func (p basePath) Rel() string {
896 if p.rel != "" {
897 return p.rel
898 }
899 return p.path
900}
901
Colin Cross0875c522017-11-28 17:34:01 -0800902func (p basePath) String() string {
903 return p.path
904}
905
Colin Cross0db55682017-12-05 15:36:55 -0800906func (p basePath) withRel(rel string) basePath {
907 p.path = filepath.Join(p.path, rel)
908 p.rel = rel
909 return p
910}
911
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700912// SourcePath is a Path representing a file path rooted from SrcDir
913type SourcePath struct {
914 basePath
Paul Duffin580efc82021-03-24 09:04:03 +0000915
916 // The sources root, i.e. Config.SrcDir()
917 srcDir string
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700918}
919
Paul Duffin85d8f0d2021-03-24 10:18:18 +0000920func (p SourcePath) RelativeToTop() Path {
921 ensureTestOnly()
922 return p
923}
924
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700925var _ Path = SourcePath{}
926
Colin Cross0db55682017-12-05 15:36:55 -0800927func (p SourcePath) withRel(rel string) SourcePath {
928 p.basePath = p.basePath.withRel(rel)
929 return p
930}
931
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700932// safePathForSource is for paths that we expect are safe -- only for use by go
933// code that is embedding ninja variables in paths
Colin Crossfe4bc362018-09-12 10:02:13 -0700934func safePathForSource(ctx PathContext, pathComponents ...string) (SourcePath, error) {
935 p, err := validateSafePath(pathComponents...)
Paul Duffin74abc5d2021-03-24 09:24:59 +0000936 ret := SourcePath{basePath{p, ""}, ctx.Config().srcDir}
Colin Crossfe4bc362018-09-12 10:02:13 -0700937 if err != nil {
938 return ret, err
939 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700940
Colin Cross7b3dcc32019-01-24 13:14:39 -0800941 // absolute path already checked by validateSafePath
942 if strings.HasPrefix(ret.String(), ctx.Config().buildDir) {
Mikhail Naganovab1f5182019-02-08 13:17:55 -0800943 return ret, fmt.Errorf("source path %q is in output", ret.String())
Colin Cross6e18ca42015-07-14 18:55:36 -0700944 }
945
Colin Crossfe4bc362018-09-12 10:02:13 -0700946 return ret, err
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700947}
948
Colin Cross192e97a2018-02-22 14:21:02 -0800949// pathForSource creates a SourcePath from pathComponents, but does not check that it exists.
950func pathForSource(ctx PathContext, pathComponents ...string) (SourcePath, error) {
Colin Crossc48c1432018-02-23 07:09:01 +0000951 p, err := validatePath(pathComponents...)
Paul Duffin74abc5d2021-03-24 09:24:59 +0000952 ret := SourcePath{basePath{p, ""}, ctx.Config().srcDir}
Colin Cross94a32102018-02-22 14:21:02 -0800953 if err != nil {
Colin Cross192e97a2018-02-22 14:21:02 -0800954 return ret, err
Colin Cross94a32102018-02-22 14:21:02 -0800955 }
956
Colin Cross7b3dcc32019-01-24 13:14:39 -0800957 // absolute path already checked by validatePath
958 if strings.HasPrefix(ret.String(), ctx.Config().buildDir) {
Mikhail Naganovab1f5182019-02-08 13:17:55 -0800959 return ret, fmt.Errorf("source path %q is in output", ret.String())
Colin Crossc48c1432018-02-23 07:09:01 +0000960 }
961
Colin Cross192e97a2018-02-22 14:21:02 -0800962 return ret, nil
963}
964
965// existsWithDependencies returns true if the path exists, and adds appropriate dependencies to rerun if the
966// path does not exist.
967func existsWithDependencies(ctx PathContext, path SourcePath) (exists bool, err error) {
968 var files []string
969
970 if gctx, ok := ctx.(PathGlobContext); ok {
971 // Use glob to produce proper dependencies, even though we only want
972 // a single file.
973 files, err = gctx.GlobWithDeps(path.String(), nil)
974 } else {
Colin Cross82ea3fb2021-04-05 17:48:26 -0700975 var result pathtools.GlobResult
Colin Cross192e97a2018-02-22 14:21:02 -0800976 // We cannot add build statements in this context, so we fall back to
977 // AddNinjaFileDeps
Colin Cross82ea3fb2021-04-05 17:48:26 -0700978 result, err = ctx.Config().fs.Glob(path.String(), nil, pathtools.FollowSymlinks)
979 ctx.AddNinjaFileDeps(result.Deps...)
980 files = result.Matches
Colin Cross192e97a2018-02-22 14:21:02 -0800981 }
982
983 if err != nil {
984 return false, fmt.Errorf("glob: %s", err.Error())
985 }
986
987 return len(files) > 0, nil
988}
989
990// PathForSource joins the provided path components and validates that the result
991// neither escapes the source dir nor is in the out dir.
992// On error, it will return a usable, but invalid SourcePath, and report a ModuleError.
993func PathForSource(ctx PathContext, pathComponents ...string) SourcePath {
994 path, err := pathForSource(ctx, pathComponents...)
995 if err != nil {
996 reportPathError(ctx, err)
997 }
998
Colin Crosse3924e12018-08-15 20:18:53 -0700999 if pathtools.IsGlob(path.String()) {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001000 ReportPathErrorf(ctx, "path may not contain a glob: %s", path.String())
Colin Crosse3924e12018-08-15 20:18:53 -07001001 }
1002
Liz Kammera830f3a2020-11-10 10:50:34 -08001003 if modCtx, ok := ctx.(ModuleMissingDepsPathContext); ok && ctx.Config().AllowMissingDependencies() {
Colin Cross192e97a2018-02-22 14:21:02 -08001004 exists, err := existsWithDependencies(ctx, path)
1005 if err != nil {
1006 reportPathError(ctx, err)
1007 }
1008 if !exists {
1009 modCtx.AddMissingDependencies([]string{path.String()})
1010 }
Colin Cross988414c2020-01-11 01:11:46 +00001011 } else if exists, _, err := ctx.Config().fs.Exists(path.String()); err != nil {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001012 ReportPathErrorf(ctx, "%s: %s", path, err.Error())
Pedro Loureiro5d190cc2021-02-15 15:41:33 +00001013 } else if !exists && !ctx.Config().TestAllowNonExistentPaths {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001014 ReportPathErrorf(ctx, "source path %q does not exist", path)
Colin Cross192e97a2018-02-22 14:21:02 -08001015 }
1016 return path
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001017}
1018
Liz Kammer7aa52882021-02-11 09:16:14 -05001019// ExistentPathForSource returns an OptionalPath with the SourcePath, rooted from SrcDir, *not*
1020// rooted from the module's local source directory, if the path exists, or an empty OptionalPath if
1021// it doesn't exist. Dependencies are added so that the ninja file will be regenerated if the state
1022// of the path changes.
Colin Cross32f38982018-02-22 11:47:25 -08001023func ExistentPathForSource(ctx PathContext, pathComponents ...string) OptionalPath {
Colin Cross192e97a2018-02-22 14:21:02 -08001024 path, err := pathForSource(ctx, pathComponents...)
Colin Cross1ccfcc32018-02-22 13:54:26 -08001025 if err != nil {
1026 reportPathError(ctx, err)
1027 return OptionalPath{}
1028 }
Colin Crossc48c1432018-02-23 07:09:01 +00001029
Colin Crosse3924e12018-08-15 20:18:53 -07001030 if pathtools.IsGlob(path.String()) {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001031 ReportPathErrorf(ctx, "path may not contain a glob: %s", path.String())
Colin Crosse3924e12018-08-15 20:18:53 -07001032 return OptionalPath{}
1033 }
1034
Colin Cross192e97a2018-02-22 14:21:02 -08001035 exists, err := existsWithDependencies(ctx, path)
Colin Crossc48c1432018-02-23 07:09:01 +00001036 if err != nil {
1037 reportPathError(ctx, err)
1038 return OptionalPath{}
1039 }
Colin Cross192e97a2018-02-22 14:21:02 -08001040 if !exists {
Colin Crossc48c1432018-02-23 07:09:01 +00001041 return OptionalPath{}
1042 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001043 return OptionalPathForPath(path)
1044}
1045
1046func (p SourcePath) String() string {
Paul Duffin580efc82021-03-24 09:04:03 +00001047 return filepath.Join(p.srcDir, p.path)
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001048}
1049
1050// Join creates a new SourcePath with paths... joined with the current path. The
1051// provided paths... may not use '..' to escape from the current path.
1052func (p SourcePath) Join(ctx PathContext, paths ...string) SourcePath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001053 path, err := validatePath(paths...)
1054 if err != nil {
1055 reportPathError(ctx, err)
1056 }
Colin Cross0db55682017-12-05 15:36:55 -08001057 return p.withRel(path)
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001058}
1059
Colin Cross2fafa3e2019-03-05 12:39:51 -08001060// join is like Join but does less path validation.
1061func (p SourcePath) join(ctx PathContext, paths ...string) SourcePath {
1062 path, err := validateSafePath(paths...)
1063 if err != nil {
1064 reportPathError(ctx, err)
1065 }
1066 return p.withRel(path)
1067}
1068
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001069// OverlayPath returns the overlay for `path' if it exists. This assumes that the
1070// SourcePath is the path to a resource overlay directory.
Liz Kammera830f3a2020-11-10 10:50:34 -08001071func (p SourcePath) OverlayPath(ctx ModuleMissingDepsPathContext, path Path) OptionalPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001072 var relDir string
Colin Cross07e51612019-03-05 12:46:40 -08001073 if srcPath, ok := path.(SourcePath); ok {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001074 relDir = srcPath.path
1075 } else {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001076 ReportPathErrorf(ctx, "Cannot find relative path for %s(%s)", reflect.TypeOf(path).Name(), path)
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001077 return OptionalPath{}
1078 }
Paul Duffin580efc82021-03-24 09:04:03 +00001079 dir := filepath.Join(p.srcDir, p.path, relDir)
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001080 // Use Glob so that we are run again if the directory is added.
Colin Cross7f19f372016-11-01 11:10:25 -07001081 if pathtools.IsGlob(dir) {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001082 ReportPathErrorf(ctx, "Path may not contain a glob: %s", dir)
Dan Willemsen7b310ee2015-12-18 15:11:17 -08001083 }
Colin Cross461b4452018-02-23 09:22:42 -08001084 paths, err := ctx.GlobWithDeps(dir, nil)
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001085 if err != nil {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001086 ReportPathErrorf(ctx, "glob: %s", err.Error())
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001087 return OptionalPath{}
1088 }
1089 if len(paths) == 0 {
1090 return OptionalPath{}
1091 }
Paul Duffin580efc82021-03-24 09:04:03 +00001092 relPath := Rel(ctx, p.srcDir, paths[0])
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001093 return OptionalPathForPath(PathForSource(ctx, relPath))
1094}
1095
Colin Cross70dda7e2019-10-01 22:05:35 -07001096// OutputPath is a Path representing an intermediates file path rooted from the build directory
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001097type OutputPath struct {
1098 basePath
Paul Duffind65c58b2021-03-24 09:22:07 +00001099
1100 // The soong build directory, i.e. Config.BuildDir()
1101 buildDir string
1102
Colin Crossd63c9a72020-01-29 16:52:50 -08001103 fullPath string
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001104}
1105
Colin Cross702e0f82017-10-18 17:27:54 -07001106func (p OutputPath) withRel(rel string) OutputPath {
Colin Cross0db55682017-12-05 15:36:55 -08001107 p.basePath = p.basePath.withRel(rel)
Colin Crossd63c9a72020-01-29 16:52:50 -08001108 p.fullPath = filepath.Join(p.fullPath, rel)
Colin Cross702e0f82017-10-18 17:27:54 -07001109 return p
1110}
1111
Colin Cross3063b782018-08-15 11:19:12 -07001112func (p OutputPath) WithoutRel() OutputPath {
1113 p.basePath.rel = filepath.Base(p.basePath.path)
1114 return p
1115}
1116
Paul Duffind65c58b2021-03-24 09:22:07 +00001117func (p OutputPath) getBuildDir() string {
1118 return p.buildDir
Paul Duffin9b478b02019-12-10 13:41:51 +00001119}
1120
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001121func (p OutputPath) RelativeToTop() Path {
1122 return p.outputPathRelativeToTop()
1123}
1124
1125func (p OutputPath) outputPathRelativeToTop() OutputPath {
1126 p.fullPath = StringPathRelativeToTop(p.buildDir, p.fullPath)
1127 p.buildDir = OutSoongDir
1128 return p
1129}
1130
Paul Duffin0267d492021-02-02 10:05:52 +00001131func (p OutputPath) objPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleObjPath {
1132 return PathForModuleObj(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
1133}
1134
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001135var _ Path = OutputPath{}
Paul Duffin9b478b02019-12-10 13:41:51 +00001136var _ WritablePath = OutputPath{}
Paul Duffin0267d492021-02-02 10:05:52 +00001137var _ objPathProvider = OutputPath{}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001138
Chris Parsons8f232a22020-06-23 17:37:05 -04001139// toolDepPath is a Path representing a dependency of the build tool.
1140type toolDepPath struct {
1141 basePath
1142}
1143
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001144func (t toolDepPath) RelativeToTop() Path {
1145 ensureTestOnly()
1146 return t
1147}
1148
Chris Parsons8f232a22020-06-23 17:37:05 -04001149var _ Path = toolDepPath{}
1150
1151// pathForBuildToolDep returns a toolDepPath representing the given path string.
1152// There is no validation for the path, as it is "trusted": It may fail
1153// normal validation checks. For example, it may be an absolute path.
1154// Only use this function to construct paths for dependencies of the build
1155// tool invocation.
1156func pathForBuildToolDep(ctx PathContext, path string) toolDepPath {
Paul Duffin74abc5d2021-03-24 09:24:59 +00001157 return toolDepPath{basePath{path, ""}}
Chris Parsons8f232a22020-06-23 17:37:05 -04001158}
1159
Jeff Gaston734e3802017-04-10 15:47:24 -07001160// PathForOutput joins the provided paths and returns an OutputPath that is
1161// validated to not escape the build dir.
1162// On error, it will return a usable, but invalid OutputPath, and report a ModuleError.
1163func PathForOutput(ctx PathContext, pathComponents ...string) OutputPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001164 path, err := validatePath(pathComponents...)
1165 if err != nil {
1166 reportPathError(ctx, err)
1167 }
Colin Crossd63c9a72020-01-29 16:52:50 -08001168 fullPath := filepath.Join(ctx.Config().buildDir, path)
1169 path = fullPath[len(fullPath)-len(path):]
Paul Duffin74abc5d2021-03-24 09:24:59 +00001170 return OutputPath{basePath{path, ""}, ctx.Config().buildDir, fullPath}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001171}
1172
Colin Cross40e33732019-02-15 11:08:35 -08001173// PathsForOutput returns Paths rooted from buildDir
1174func PathsForOutput(ctx PathContext, paths []string) WritablePaths {
1175 ret := make(WritablePaths, len(paths))
1176 for i, path := range paths {
1177 ret[i] = PathForOutput(ctx, path)
1178 }
1179 return ret
1180}
1181
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001182func (p OutputPath) writablePath() {}
1183
1184func (p OutputPath) String() string {
Colin Crossd63c9a72020-01-29 16:52:50 -08001185 return p.fullPath
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001186}
1187
1188// Join creates a new OutputPath with paths... joined with the current path. The
1189// provided paths... may not use '..' to escape from the current path.
1190func (p OutputPath) Join(ctx PathContext, paths ...string) OutputPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001191 path, err := validatePath(paths...)
1192 if err != nil {
1193 reportPathError(ctx, err)
1194 }
Colin Cross0db55682017-12-05 15:36:55 -08001195 return p.withRel(path)
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001196}
1197
Colin Cross8854a5a2019-02-11 14:14:16 -08001198// ReplaceExtension creates a new OutputPath with the extension replaced with ext.
1199func (p OutputPath) ReplaceExtension(ctx PathContext, ext string) OutputPath {
1200 if strings.Contains(ext, "/") {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001201 ReportPathErrorf(ctx, "extension %q cannot contain /", ext)
Colin Cross8854a5a2019-02-11 14:14:16 -08001202 }
1203 ret := PathForOutput(ctx, pathtools.ReplaceExtension(p.path, ext))
Colin Cross2cdd5df2019-02-25 10:25:24 -08001204 ret.rel = pathtools.ReplaceExtension(p.rel, ext)
Colin Cross8854a5a2019-02-11 14:14:16 -08001205 return ret
1206}
1207
Colin Cross40e33732019-02-15 11:08:35 -08001208// InSameDir creates a new OutputPath from the directory of the current OutputPath joined with the elements in paths.
1209func (p OutputPath) InSameDir(ctx PathContext, paths ...string) OutputPath {
1210 path, err := validatePath(paths...)
1211 if err != nil {
1212 reportPathError(ctx, err)
1213 }
1214
1215 ret := PathForOutput(ctx, filepath.Dir(p.path), path)
Colin Cross2cdd5df2019-02-25 10:25:24 -08001216 ret.rel = filepath.Join(filepath.Dir(p.rel), path)
Colin Cross40e33732019-02-15 11:08:35 -08001217 return ret
1218}
1219
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001220// PathForIntermediates returns an OutputPath representing the top-level
1221// intermediates directory.
1222func PathForIntermediates(ctx PathContext, paths ...string) OutputPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001223 path, err := validatePath(paths...)
1224 if err != nil {
1225 reportPathError(ctx, err)
1226 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001227 return PathForOutput(ctx, ".intermediates", path)
1228}
1229
Colin Cross07e51612019-03-05 12:46:40 -08001230var _ genPathProvider = SourcePath{}
1231var _ objPathProvider = SourcePath{}
1232var _ resPathProvider = SourcePath{}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001233
Colin Cross07e51612019-03-05 12:46:40 -08001234// PathForModuleSrc returns a Path representing the paths... under the
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001235// module's local source directory.
Liz Kammera830f3a2020-11-10 10:50:34 -08001236func PathForModuleSrc(ctx ModuleMissingDepsPathContext, pathComponents ...string) Path {
Colin Cross8a497952019-03-05 22:25:09 -08001237 p, err := validatePath(pathComponents...)
1238 if err != nil {
1239 reportPathError(ctx, err)
Colin Cross192e97a2018-02-22 14:21:02 -08001240 }
Colin Cross8a497952019-03-05 22:25:09 -08001241 paths, err := expandOneSrcPath(ctx, p, nil)
1242 if err != nil {
1243 if depErr, ok := err.(missingDependencyError); ok {
1244 if ctx.Config().AllowMissingDependencies() {
1245 ctx.AddMissingDependencies(depErr.missingDeps)
1246 } else {
1247 ctx.ModuleErrorf(`%s, is the property annotated with android:"path"?`, depErr.Error())
1248 }
1249 } else {
1250 reportPathError(ctx, err)
1251 }
1252 return nil
1253 } else if len(paths) == 0 {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001254 ReportPathErrorf(ctx, "%q produced no files, expected exactly one", p)
Colin Cross8a497952019-03-05 22:25:09 -08001255 return nil
1256 } else if len(paths) > 1 {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001257 ReportPathErrorf(ctx, "%q produced %d files, expected exactly one", p, len(paths))
Colin Cross8a497952019-03-05 22:25:09 -08001258 }
1259 return paths[0]
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001260}
1261
Liz Kammera830f3a2020-11-10 10:50:34 -08001262func pathForModuleSrc(ctx EarlyModulePathContext, paths ...string) SourcePath {
Colin Cross07e51612019-03-05 12:46:40 -08001263 p, err := validatePath(paths...)
1264 if err != nil {
1265 reportPathError(ctx, err)
1266 }
1267
1268 path, err := pathForSource(ctx, ctx.ModuleDir(), p)
1269 if err != nil {
1270 reportPathError(ctx, err)
1271 }
1272
1273 path.basePath.rel = p
1274
1275 return path
1276}
1277
Colin Cross2fafa3e2019-03-05 12:39:51 -08001278// PathsWithModuleSrcSubDir takes a list of Paths and returns a new list of Paths where Rel() on each path
1279// will return the path relative to subDir in the module's source directory. If any input paths are not located
1280// inside subDir then a path error will be reported.
Liz Kammera830f3a2020-11-10 10:50:34 -08001281func PathsWithModuleSrcSubDir(ctx EarlyModulePathContext, paths Paths, subDir string) Paths {
Colin Cross2fafa3e2019-03-05 12:39:51 -08001282 paths = append(Paths(nil), paths...)
Colin Cross07e51612019-03-05 12:46:40 -08001283 subDirFullPath := pathForModuleSrc(ctx, subDir)
Colin Cross2fafa3e2019-03-05 12:39:51 -08001284 for i, path := range paths {
1285 rel := Rel(ctx, subDirFullPath.String(), path.String())
1286 paths[i] = subDirFullPath.join(ctx, rel)
1287 }
1288 return paths
1289}
1290
1291// PathWithModuleSrcSubDir takes a Path and returns a Path where Rel() will return the path relative to subDir in the
1292// 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 -08001293func PathWithModuleSrcSubDir(ctx EarlyModulePathContext, path Path, subDir string) Path {
Colin Cross07e51612019-03-05 12:46:40 -08001294 subDirFullPath := pathForModuleSrc(ctx, subDir)
Colin Cross2fafa3e2019-03-05 12:39:51 -08001295 rel := Rel(ctx, subDirFullPath.String(), path.String())
1296 return subDirFullPath.Join(ctx, rel)
1297}
1298
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001299// OptionalPathForModuleSrc returns an OptionalPath. The OptionalPath contains a
1300// valid path if p is non-nil.
Liz Kammera830f3a2020-11-10 10:50:34 -08001301func OptionalPathForModuleSrc(ctx ModuleMissingDepsPathContext, p *string) OptionalPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001302 if p == nil {
1303 return OptionalPath{}
1304 }
1305 return OptionalPathForPath(PathForModuleSrc(ctx, *p))
1306}
1307
Liz Kammera830f3a2020-11-10 10:50:34 -08001308func (p SourcePath) genPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleGenPath {
Colin Cross7fc17db2017-02-01 14:07:55 -08001309 return PathForModuleGen(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001310}
1311
Liz Kammera830f3a2020-11-10 10:50:34 -08001312func (p SourcePath) objPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleObjPath {
Colin Cross7fc17db2017-02-01 14:07:55 -08001313 return PathForModuleObj(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001314}
1315
Liz Kammera830f3a2020-11-10 10:50:34 -08001316func (p SourcePath) resPathWithName(ctx ModuleOutPathContext, name string) ModuleResPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001317 // TODO: Use full directory if the new ctx is not the current ctx?
1318 return PathForModuleRes(ctx, p.path, name)
1319}
1320
1321// ModuleOutPath is a Path representing a module's output directory.
1322type ModuleOutPath struct {
1323 OutputPath
1324}
1325
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001326func (p ModuleOutPath) RelativeToTop() Path {
1327 p.OutputPath = p.outputPathRelativeToTop()
1328 return p
1329}
1330
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001331var _ Path = ModuleOutPath{}
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001332var _ WritablePath = ModuleOutPath{}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001333
Liz Kammera830f3a2020-11-10 10:50:34 -08001334func (p ModuleOutPath) objPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleObjPath {
Pete Bentleyfcf55bf2019-08-16 20:14:32 +01001335 return PathForModuleObj(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
1336}
1337
Liz Kammera830f3a2020-11-10 10:50:34 -08001338// ModuleOutPathContext Subset of ModuleContext functions necessary for output path methods.
1339type ModuleOutPathContext interface {
1340 PathContext
1341
1342 ModuleName() string
1343 ModuleDir() string
1344 ModuleSubDir() string
1345}
1346
1347func pathForModuleOut(ctx ModuleOutPathContext) OutputPath {
Colin Cross702e0f82017-10-18 17:27:54 -07001348 return PathForOutput(ctx, ".intermediates", ctx.ModuleDir(), ctx.ModuleName(), ctx.ModuleSubDir())
1349}
1350
Logan Chien7eefdc42018-07-11 18:10:41 +08001351// PathForVndkRefAbiDump returns an OptionalPath representing the path of the
1352// reference abi dump for the given module. This is not guaranteed to be valid.
Liz Kammera830f3a2020-11-10 10:50:34 -08001353func PathForVndkRefAbiDump(ctx ModuleInstallPathContext, version, fileName string,
Hsin-Yi Chen53489642019-07-31 17:10:45 +08001354 isNdk, isLlndkOrVndk, isGzip bool) OptionalPath {
Logan Chien7eefdc42018-07-11 18:10:41 +08001355
Jayant Chowdharyac066c62018-02-20 10:53:31 -08001356 arches := ctx.DeviceConfig().Arches()
Logan Chien7eefdc42018-07-11 18:10:41 +08001357 if len(arches) == 0 {
1358 panic("device build with no primary arch")
1359 }
Jayant Chowdharyac066c62018-02-20 10:53:31 -08001360 currentArch := ctx.Arch()
1361 archNameAndVariant := currentArch.ArchType.String()
1362 if currentArch.ArchVariant != "" {
1363 archNameAndVariant += "_" + currentArch.ArchVariant
1364 }
Logan Chien5237bed2018-07-11 17:15:57 +08001365
1366 var dirName string
Hsin-Yi Chen53489642019-07-31 17:10:45 +08001367 if isNdk {
Logan Chien5237bed2018-07-11 17:15:57 +08001368 dirName = "ndk"
Hsin-Yi Chen53489642019-07-31 17:10:45 +08001369 } else if isLlndkOrVndk {
Logan Chien5237bed2018-07-11 17:15:57 +08001370 dirName = "vndk"
Logan Chien41eabe62019-04-10 13:33:58 +08001371 } else {
1372 dirName = "platform" // opt-in libs
Jayant Chowdhary3e231fd2017-02-08 13:45:53 -08001373 }
Logan Chien5237bed2018-07-11 17:15:57 +08001374
Jayant Chowdhary34ce67d2018-03-08 11:00:50 -08001375 binderBitness := ctx.DeviceConfig().BinderBitness()
Logan Chien7eefdc42018-07-11 18:10:41 +08001376
1377 var ext string
1378 if isGzip {
1379 ext = ".lsdump.gz"
1380 } else {
1381 ext = ".lsdump"
1382 }
1383
1384 return ExistentPathForSource(ctx, "prebuilts", "abi-dumps", dirName,
1385 version, binderBitness, archNameAndVariant, "source-based",
1386 fileName+ext)
Jayant Chowdhary3e231fd2017-02-08 13:45:53 -08001387}
1388
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001389// PathForModuleOut returns a Path representing the paths... under the module's
1390// output directory.
Liz Kammera830f3a2020-11-10 10:50:34 -08001391func PathForModuleOut(ctx ModuleOutPathContext, paths ...string) ModuleOutPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001392 p, err := validatePath(paths...)
1393 if err != nil {
1394 reportPathError(ctx, err)
1395 }
Colin Cross702e0f82017-10-18 17:27:54 -07001396 return ModuleOutPath{
Liz Kammera830f3a2020-11-10 10:50:34 -08001397 OutputPath: pathForModuleOut(ctx).withRel(p),
Colin Cross702e0f82017-10-18 17:27:54 -07001398 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001399}
1400
1401// ModuleGenPath is a Path representing the 'gen' directory in a module's output
1402// directory. Mainly used for generated sources.
1403type ModuleGenPath struct {
1404 ModuleOutPath
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001405}
1406
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001407func (p ModuleGenPath) RelativeToTop() Path {
1408 p.OutputPath = p.outputPathRelativeToTop()
1409 return p
1410}
1411
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001412var _ Path = ModuleGenPath{}
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001413var _ WritablePath = ModuleGenPath{}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001414var _ genPathProvider = ModuleGenPath{}
1415var _ objPathProvider = ModuleGenPath{}
1416
1417// PathForModuleGen returns a Path representing the paths... under the module's
1418// `gen' directory.
Liz Kammera830f3a2020-11-10 10:50:34 -08001419func PathForModuleGen(ctx ModuleOutPathContext, paths ...string) ModuleGenPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001420 p, err := validatePath(paths...)
1421 if err != nil {
1422 reportPathError(ctx, err)
1423 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001424 return ModuleGenPath{
Colin Cross702e0f82017-10-18 17:27:54 -07001425 ModuleOutPath: ModuleOutPath{
Liz Kammera830f3a2020-11-10 10:50:34 -08001426 OutputPath: pathForModuleOut(ctx).withRel("gen").withRel(p),
Colin Cross702e0f82017-10-18 17:27:54 -07001427 },
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001428 }
1429}
1430
Liz Kammera830f3a2020-11-10 10:50:34 -08001431func (p ModuleGenPath) genPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleGenPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001432 // TODO: make a different path for local vs remote generated files?
Dan Willemsen21ec4902016-11-02 20:43:13 -07001433 return PathForModuleGen(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001434}
1435
Liz Kammera830f3a2020-11-10 10:50:34 -08001436func (p ModuleGenPath) objPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleObjPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001437 return PathForModuleObj(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
1438}
1439
1440// ModuleObjPath is a Path representing the 'obj' directory in a module's output
1441// directory. Used for compiled objects.
1442type ModuleObjPath struct {
1443 ModuleOutPath
1444}
1445
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001446func (p ModuleObjPath) RelativeToTop() Path {
1447 p.OutputPath = p.outputPathRelativeToTop()
1448 return p
1449}
1450
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001451var _ Path = ModuleObjPath{}
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001452var _ WritablePath = ModuleObjPath{}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001453
1454// PathForModuleObj returns a Path representing the paths... under the module's
1455// 'obj' directory.
Liz Kammera830f3a2020-11-10 10:50:34 -08001456func PathForModuleObj(ctx ModuleOutPathContext, pathComponents ...string) ModuleObjPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001457 p, err := validatePath(pathComponents...)
1458 if err != nil {
1459 reportPathError(ctx, err)
1460 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001461 return ModuleObjPath{PathForModuleOut(ctx, "obj", p)}
1462}
1463
1464// ModuleResPath is a a Path representing the 'res' directory in a module's
1465// output directory.
1466type ModuleResPath struct {
1467 ModuleOutPath
1468}
1469
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001470func (p ModuleResPath) RelativeToTop() Path {
1471 p.OutputPath = p.outputPathRelativeToTop()
1472 return p
1473}
1474
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001475var _ Path = ModuleResPath{}
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001476var _ WritablePath = ModuleResPath{}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001477
1478// PathForModuleRes returns a Path representing the paths... under the module's
1479// 'res' directory.
Liz Kammera830f3a2020-11-10 10:50:34 -08001480func PathForModuleRes(ctx ModuleOutPathContext, pathComponents ...string) ModuleResPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001481 p, err := validatePath(pathComponents...)
1482 if err != nil {
1483 reportPathError(ctx, err)
1484 }
1485
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001486 return ModuleResPath{PathForModuleOut(ctx, "res", p)}
1487}
1488
Colin Cross70dda7e2019-10-01 22:05:35 -07001489// InstallPath is a Path representing a installed file path rooted from the build directory
1490type InstallPath struct {
1491 basePath
Colin Crossff6c33d2019-10-02 16:01:35 -07001492
Paul Duffind65c58b2021-03-24 09:22:07 +00001493 // The soong build directory, i.e. Config.BuildDir()
1494 buildDir string
1495
Jiyong Park957bcd92020-10-20 18:23:33 +09001496 // partitionDir is the part of the InstallPath that is automatically determined according to the context.
1497 // For example, it is host/<os>-<arch> for host modules, and target/product/<device>/<partition> for device modules.
1498 partitionDir string
1499
1500 // makePath indicates whether this path is for Soong (false) or Make (true).
1501 makePath bool
Colin Cross70dda7e2019-10-01 22:05:35 -07001502}
1503
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001504// Will panic if called from outside a test environment.
1505func ensureTestOnly() {
Martin Stjernholm32312eb2021-03-27 18:54:49 +00001506 if PrefixInList(os.Args, "-test.") {
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001507 return
1508 }
Martin Stjernholm32312eb2021-03-27 18:54:49 +00001509 panic(fmt.Errorf("Not in test. Command line:\n %s", strings.Join(os.Args, "\n ")))
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001510}
1511
1512func (p InstallPath) RelativeToTop() Path {
1513 ensureTestOnly()
1514 p.buildDir = OutSoongDir
1515 return p
1516}
1517
Paul Duffind65c58b2021-03-24 09:22:07 +00001518func (p InstallPath) getBuildDir() string {
1519 return p.buildDir
Paul Duffin9b478b02019-12-10 13:41:51 +00001520}
1521
Hans MÃ¥nssond3f2bd72020-11-27 12:37:28 +01001522func (p InstallPath) ReplaceExtension(ctx PathContext, ext string) OutputPath {
1523 panic("Not implemented")
1524}
1525
Paul Duffin9b478b02019-12-10 13:41:51 +00001526var _ Path = InstallPath{}
1527var _ WritablePath = InstallPath{}
1528
Colin Cross70dda7e2019-10-01 22:05:35 -07001529func (p InstallPath) writablePath() {}
1530
1531func (p InstallPath) String() string {
Jiyong Park957bcd92020-10-20 18:23:33 +09001532 if p.makePath {
1533 // Make path starts with out/ instead of out/soong.
Paul Duffind65c58b2021-03-24 09:22:07 +00001534 return filepath.Join(p.buildDir, "../", p.path)
Jiyong Park957bcd92020-10-20 18:23:33 +09001535 } else {
Paul Duffind65c58b2021-03-24 09:22:07 +00001536 return filepath.Join(p.buildDir, p.path)
Jiyong Park957bcd92020-10-20 18:23:33 +09001537 }
1538}
1539
1540// PartitionDir returns the path to the partition where the install path is rooted at. It is
1541// out/soong/target/product/<device>/<partition> for device modules, and out/soong/host/<os>-<arch> for host modules.
1542// The ./soong is dropped if the install path is for Make.
1543func (p InstallPath) PartitionDir() string {
1544 if p.makePath {
Paul Duffind65c58b2021-03-24 09:22:07 +00001545 return filepath.Join(p.buildDir, "../", p.partitionDir)
Jiyong Park957bcd92020-10-20 18:23:33 +09001546 } else {
Paul Duffind65c58b2021-03-24 09:22:07 +00001547 return filepath.Join(p.buildDir, p.partitionDir)
Jiyong Park957bcd92020-10-20 18:23:33 +09001548 }
Colin Cross70dda7e2019-10-01 22:05:35 -07001549}
1550
1551// Join creates a new InstallPath with paths... joined with the current path. The
1552// provided paths... may not use '..' to escape from the current path.
1553func (p InstallPath) Join(ctx PathContext, paths ...string) InstallPath {
1554 path, err := validatePath(paths...)
1555 if err != nil {
1556 reportPathError(ctx, err)
1557 }
1558 return p.withRel(path)
1559}
1560
1561func (p InstallPath) withRel(rel string) InstallPath {
1562 p.basePath = p.basePath.withRel(rel)
1563 return p
1564}
1565
Colin Crossff6c33d2019-10-02 16:01:35 -07001566// ToMakePath returns a new InstallPath that points to Make's install directory instead of Soong's,
1567// i.e. out/ instead of out/soong/.
1568func (p InstallPath) ToMakePath() InstallPath {
Jiyong Park957bcd92020-10-20 18:23:33 +09001569 p.makePath = true
Colin Crossff6c33d2019-10-02 16:01:35 -07001570 return p
Colin Cross70dda7e2019-10-01 22:05:35 -07001571}
1572
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001573// PathForModuleInstall returns a Path representing the install path for the
1574// module appended with paths...
Colin Cross70dda7e2019-10-01 22:05:35 -07001575func PathForModuleInstall(ctx ModuleInstallPathContext, pathComponents ...string) InstallPath {
Colin Cross6e359402020-02-10 15:29:54 -08001576 os := ctx.Os()
Jiyong Park87788b52020-09-01 12:37:45 +09001577 arch := ctx.Arch().ArchType
1578 forceOS, forceArch := ctx.InstallForceOS()
1579 if forceOS != nil {
Colin Cross6e359402020-02-10 15:29:54 -08001580 os = *forceOS
1581 }
Jiyong Park87788b52020-09-01 12:37:45 +09001582 if forceArch != nil {
1583 arch = *forceArch
1584 }
Colin Cross6e359402020-02-10 15:29:54 -08001585 partition := modulePartition(ctx, os)
Colin Cross609c49a2020-02-13 13:20:11 -08001586
Jiyong Park87788b52020-09-01 12:37:45 +09001587 ret := pathForInstall(ctx, os, arch, partition, ctx.Debug(), pathComponents...)
Colin Cross609c49a2020-02-13 13:20:11 -08001588
Jingwen Chencda22c92020-11-23 00:22:30 -05001589 if ctx.InstallBypassMake() && ctx.Config().KatiEnabled() {
Colin Cross609c49a2020-02-13 13:20:11 -08001590 ret = ret.ToMakePath()
1591 }
1592
1593 return ret
1594}
1595
Jiyong Park87788b52020-09-01 12:37:45 +09001596func pathForInstall(ctx PathContext, os OsType, arch ArchType, partition string, debug bool,
Colin Cross609c49a2020-02-13 13:20:11 -08001597 pathComponents ...string) InstallPath {
1598
Jiyong Park957bcd92020-10-20 18:23:33 +09001599 var partionPaths []string
Colin Cross609c49a2020-02-13 13:20:11 -08001600
Colin Cross6e359402020-02-10 15:29:54 -08001601 if os.Class == Device {
Jiyong Park957bcd92020-10-20 18:23:33 +09001602 partionPaths = []string{"target", "product", ctx.Config().DeviceName(), partition}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001603 } else {
Jiyong Park87788b52020-09-01 12:37:45 +09001604 osName := os.String()
1605 if os == Linux {
1606 // instead of linux_glibc
1607 osName = "linux"
Dan Willemsen866b5632017-09-22 12:28:24 -07001608 }
Jiyong Park87788b52020-09-01 12:37:45 +09001609 // SOONG_HOST_OUT is set to out/host/$(HOST_OS)-$(HOST_PREBUILT_ARCH)
1610 // and HOST_PREBUILT_ARCH is forcibly set to x86 even on x86_64 hosts. We don't seem
1611 // to have a plan to fix it (see the comment in build/make/core/envsetup.mk).
1612 // Let's keep using x86 for the existing cases until we have a need to support
1613 // other architectures.
1614 archName := arch.String()
1615 if os.Class == Host && (arch == X86_64 || arch == Common) {
1616 archName = "x86"
1617 }
Jiyong Park957bcd92020-10-20 18:23:33 +09001618 partionPaths = []string{"host", osName + "-" + archName, partition}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001619 }
Colin Cross609c49a2020-02-13 13:20:11 -08001620 if debug {
Jiyong Park957bcd92020-10-20 18:23:33 +09001621 partionPaths = append([]string{"debug"}, partionPaths...)
Dan Willemsen782a2d12015-12-21 14:55:28 -08001622 }
Colin Cross70dda7e2019-10-01 22:05:35 -07001623
Jiyong Park957bcd92020-10-20 18:23:33 +09001624 partionPath, err := validatePath(partionPaths...)
Colin Cross70dda7e2019-10-01 22:05:35 -07001625 if err != nil {
1626 reportPathError(ctx, err)
1627 }
Colin Crossff6c33d2019-10-02 16:01:35 -07001628
Jiyong Park957bcd92020-10-20 18:23:33 +09001629 base := InstallPath{
Paul Duffin74abc5d2021-03-24 09:24:59 +00001630 basePath: basePath{partionPath, ""},
Paul Duffind65c58b2021-03-24 09:22:07 +00001631 buildDir: ctx.Config().buildDir,
Jiyong Park957bcd92020-10-20 18:23:33 +09001632 partitionDir: partionPath,
1633 makePath: false,
1634 }
Colin Crossff6c33d2019-10-02 16:01:35 -07001635
Jiyong Park957bcd92020-10-20 18:23:33 +09001636 return base.Join(ctx, pathComponents...)
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001637}
1638
Nicolas Geoffray1228e9c2020-02-27 13:45:35 +00001639func pathForNdkOrSdkInstall(ctx PathContext, prefix string, paths []string) InstallPath {
Jiyong Park957bcd92020-10-20 18:23:33 +09001640 base := InstallPath{
Paul Duffin74abc5d2021-03-24 09:24:59 +00001641 basePath: basePath{prefix, ""},
Paul Duffind65c58b2021-03-24 09:22:07 +00001642 buildDir: ctx.Config().buildDir,
Jiyong Park957bcd92020-10-20 18:23:33 +09001643 partitionDir: prefix,
1644 makePath: false,
Colin Cross70dda7e2019-10-01 22:05:35 -07001645 }
Jiyong Park957bcd92020-10-20 18:23:33 +09001646 return base.Join(ctx, paths...)
Colin Cross70dda7e2019-10-01 22:05:35 -07001647}
1648
Nicolas Geoffray1228e9c2020-02-27 13:45:35 +00001649func PathForNdkInstall(ctx PathContext, paths ...string) InstallPath {
1650 return pathForNdkOrSdkInstall(ctx, "ndk", paths)
1651}
1652
1653func PathForMainlineSdksInstall(ctx PathContext, paths ...string) InstallPath {
1654 return pathForNdkOrSdkInstall(ctx, "mainline-sdks", paths)
1655}
1656
Colin Cross70dda7e2019-10-01 22:05:35 -07001657func InstallPathToOnDevicePath(ctx PathContext, path InstallPath) string {
Colin Cross43f08db2018-11-12 10:13:39 -08001658 rel := Rel(ctx, PathForOutput(ctx, "target", "product", ctx.Config().DeviceName()).String(), path.String())
1659
1660 return "/" + rel
1661}
1662
Colin Cross6e359402020-02-10 15:29:54 -08001663func modulePartition(ctx ModuleInstallPathContext, os OsType) string {
Colin Cross43f08db2018-11-12 10:13:39 -08001664 var partition string
Colin Cross6e359402020-02-10 15:29:54 -08001665 if ctx.InstallInTestcases() {
1666 // "testcases" install directory can be used for host or device modules.
Jaewoong Jung0949f312019-09-11 10:25:18 -07001667 partition = "testcases"
Colin Cross6e359402020-02-10 15:29:54 -08001668 } else if os.Class == Device {
1669 if ctx.InstallInData() {
1670 partition = "data"
1671 } else if ctx.InstallInRamdisk() {
1672 if ctx.DeviceConfig().BoardUsesRecoveryAsBoot() {
1673 partition = "recovery/root/first_stage_ramdisk"
1674 } else {
1675 partition = "ramdisk"
1676 }
1677 if !ctx.InstallInRoot() {
1678 partition += "/system"
1679 }
Yifan Hong60e0cfb2020-10-21 15:17:56 -07001680 } else if ctx.InstallInVendorRamdisk() {
Yifan Hong39143a92020-10-26 12:43:12 -07001681 // The module is only available after switching root into
1682 // /first_stage_ramdisk. To expose the module before switching root
1683 // on a device without a dedicated recovery partition, install the
1684 // recovery variant.
Yifan Hongdd8dacc2020-10-21 15:40:17 -07001685 if ctx.DeviceConfig().BoardMoveRecoveryResourcesToVendorBoot() {
Petri Gyntherac229562021-03-02 23:44:02 -08001686 partition = "vendor_ramdisk/first_stage_ramdisk"
Yifan Hongdd8dacc2020-10-21 15:40:17 -07001687 } else {
Petri Gyntherac229562021-03-02 23:44:02 -08001688 partition = "vendor_ramdisk"
Yifan Hongdd8dacc2020-10-21 15:40:17 -07001689 }
1690 if !ctx.InstallInRoot() {
1691 partition += "/system"
1692 }
Inseob Kimf84e9c02021-04-08 21:13:22 +09001693 } else if ctx.InstallInDebugRamdisk() {
1694 // The module is only available after switching root into
1695 // /first_stage_ramdisk. To expose the module before switching root
1696 // on a device without a dedicated recovery partition, install the
1697 // recovery variant.
1698 if ctx.DeviceConfig().BoardUsesRecoveryAsBoot() {
1699 partition = "debug_ramdisk/first_stage_ramdisk"
1700 } else {
1701 partition = "debug_ramdisk"
1702 }
Colin Cross6e359402020-02-10 15:29:54 -08001703 } else if ctx.InstallInRecovery() {
1704 if ctx.InstallInRoot() {
1705 partition = "recovery/root"
1706 } else {
1707 // the layout of recovery partion is the same as that of system partition
1708 partition = "recovery/root/system"
1709 }
1710 } else if ctx.SocSpecific() {
1711 partition = ctx.DeviceConfig().VendorPath()
1712 } else if ctx.DeviceSpecific() {
1713 partition = ctx.DeviceConfig().OdmPath()
1714 } else if ctx.ProductSpecific() {
1715 partition = ctx.DeviceConfig().ProductPath()
1716 } else if ctx.SystemExtSpecific() {
1717 partition = ctx.DeviceConfig().SystemExtPath()
1718 } else if ctx.InstallInRoot() {
1719 partition = "root"
Yifan Hong82db7352020-01-21 16:12:26 -08001720 } else {
Colin Cross6e359402020-02-10 15:29:54 -08001721 partition = "system"
Yifan Hong82db7352020-01-21 16:12:26 -08001722 }
Colin Cross6e359402020-02-10 15:29:54 -08001723 if ctx.InstallInSanitizerDir() {
1724 partition = "data/asan/" + partition
Yifan Hong82db7352020-01-21 16:12:26 -08001725 }
Colin Cross43f08db2018-11-12 10:13:39 -08001726 }
1727 return partition
1728}
1729
Colin Cross609c49a2020-02-13 13:20:11 -08001730type InstallPaths []InstallPath
1731
1732// Paths returns the InstallPaths as a Paths
1733func (p InstallPaths) Paths() Paths {
1734 if p == nil {
1735 return nil
1736 }
1737 ret := make(Paths, len(p))
1738 for i, path := range p {
1739 ret[i] = path
1740 }
1741 return ret
1742}
1743
1744// Strings returns the string forms of the install paths.
1745func (p InstallPaths) Strings() []string {
1746 if p == nil {
1747 return nil
1748 }
1749 ret := make([]string, len(p))
1750 for i, path := range p {
1751 ret[i] = path.String()
1752 }
1753 return ret
1754}
1755
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001756// validateSafePath validates a path that we trust (may contain ninja variables).
Dan Willemsen80a7c2a2015-12-21 14:57:11 -08001757// Ensures that each path component does not attempt to leave its component.
Colin Cross1ccfcc32018-02-22 13:54:26 -08001758func validateSafePath(pathComponents ...string) (string, error) {
Jeff Gaston734e3802017-04-10 15:47:24 -07001759 for _, path := range pathComponents {
Dan Willemsen80a7c2a2015-12-21 14:57:11 -08001760 path := filepath.Clean(path)
1761 if path == ".." || strings.HasPrefix(path, "../") || strings.HasPrefix(path, "/") {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001762 return "", fmt.Errorf("Path is outside directory: %s", path)
Dan Willemsen80a7c2a2015-12-21 14:57:11 -08001763 }
1764 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001765 // TODO: filepath.Join isn't necessarily correct with embedded ninja
1766 // variables. '..' may remove the entire ninja variable, even if it
1767 // will be expanded to multiple nested directories.
Colin Cross1ccfcc32018-02-22 13:54:26 -08001768 return filepath.Join(pathComponents...), nil
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001769}
1770
Dan Willemsen80a7c2a2015-12-21 14:57:11 -08001771// validatePath validates that a path does not include ninja variables, and that
1772// each path component does not attempt to leave its component. Returns a joined
1773// version of each path component.
Colin Cross1ccfcc32018-02-22 13:54:26 -08001774func validatePath(pathComponents ...string) (string, error) {
Jeff Gaston734e3802017-04-10 15:47:24 -07001775 for _, path := range pathComponents {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001776 if strings.Contains(path, "$") {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001777 return "", fmt.Errorf("Path contains invalid character($): %s", path)
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001778 }
1779 }
Colin Cross1ccfcc32018-02-22 13:54:26 -08001780 return validateSafePath(pathComponents...)
Colin Cross6e18ca42015-07-14 18:55:36 -07001781}
Colin Cross5b529592017-05-09 13:34:34 -07001782
Colin Cross0875c522017-11-28 17:34:01 -08001783func PathForPhony(ctx PathContext, phony string) WritablePath {
1784 if strings.ContainsAny(phony, "$/") {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001785 ReportPathErrorf(ctx, "Phony target contains invalid character ($ or /): %s", phony)
Colin Cross0875c522017-11-28 17:34:01 -08001786 }
Paul Duffin74abc5d2021-03-24 09:24:59 +00001787 return PhonyPath{basePath{phony, ""}}
Colin Cross0875c522017-11-28 17:34:01 -08001788}
1789
Colin Cross74e3fe42017-12-11 15:51:44 -08001790type PhonyPath struct {
1791 basePath
1792}
1793
1794func (p PhonyPath) writablePath() {}
1795
Paul Duffind65c58b2021-03-24 09:22:07 +00001796func (p PhonyPath) getBuildDir() string {
1797 // A phone path cannot contain any / so cannot be relative to the build directory.
1798 return ""
Paul Duffin9b478b02019-12-10 13:41:51 +00001799}
1800
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001801func (p PhonyPath) RelativeToTop() Path {
1802 ensureTestOnly()
1803 // A phony path cannot contain any / so does not have a build directory so switching to a new
1804 // build directory has no effect so just return this path.
1805 return p
1806}
1807
Hans MÃ¥nssond3f2bd72020-11-27 12:37:28 +01001808func (p PhonyPath) ReplaceExtension(ctx PathContext, ext string) OutputPath {
1809 panic("Not implemented")
1810}
1811
Colin Cross74e3fe42017-12-11 15:51:44 -08001812var _ Path = PhonyPath{}
1813var _ WritablePath = PhonyPath{}
1814
Colin Cross5b529592017-05-09 13:34:34 -07001815type testPath struct {
1816 basePath
1817}
1818
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001819func (p testPath) RelativeToTop() Path {
1820 ensureTestOnly()
1821 return p
1822}
1823
Colin Cross5b529592017-05-09 13:34:34 -07001824func (p testPath) String() string {
1825 return p.path
1826}
1827
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001828var _ Path = testPath{}
1829
Colin Cross40e33732019-02-15 11:08:35 -08001830// PathForTesting returns a Path constructed from joining the elements of paths with '/'. It should only be used from
1831// within tests.
Colin Cross5b529592017-05-09 13:34:34 -07001832func PathForTesting(paths ...string) Path {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001833 p, err := validateSafePath(paths...)
1834 if err != nil {
1835 panic(err)
1836 }
Colin Cross5b529592017-05-09 13:34:34 -07001837 return testPath{basePath{path: p, rel: p}}
1838}
1839
Colin Cross40e33732019-02-15 11:08:35 -08001840// PathsForTesting returns a Path constructed from each element in strs. It should only be used from within tests.
1841func PathsForTesting(strs ...string) Paths {
Colin Cross5b529592017-05-09 13:34:34 -07001842 p := make(Paths, len(strs))
1843 for i, s := range strs {
1844 p[i] = PathForTesting(s)
1845 }
1846
1847 return p
1848}
Colin Cross43f08db2018-11-12 10:13:39 -08001849
Colin Cross40e33732019-02-15 11:08:35 -08001850type testPathContext struct {
1851 config Config
Colin Cross40e33732019-02-15 11:08:35 -08001852}
1853
Colin Cross40e33732019-02-15 11:08:35 -08001854func (x *testPathContext) Config() Config { return x.config }
1855func (x *testPathContext) AddNinjaFileDeps(...string) {}
1856
1857// PathContextForTesting returns a PathContext that can be used in tests, for example to create an OutputPath with
1858// PathForOutput.
Colin Cross98be1bb2019-12-13 20:41:13 -08001859func PathContextForTesting(config Config) PathContext {
Colin Cross40e33732019-02-15 11:08:35 -08001860 return &testPathContext{
1861 config: config,
Colin Cross40e33732019-02-15 11:08:35 -08001862 }
1863}
1864
Ulya Trafimovichccc8c852020-10-14 11:29:07 +01001865type testModuleInstallPathContext struct {
1866 baseModuleContext
1867
1868 inData bool
1869 inTestcases bool
1870 inSanitizerDir bool
1871 inRamdisk bool
1872 inVendorRamdisk bool
Inseob Kimf84e9c02021-04-08 21:13:22 +09001873 inDebugRamdisk bool
Ulya Trafimovichccc8c852020-10-14 11:29:07 +01001874 inRecovery bool
1875 inRoot bool
1876 forceOS *OsType
1877 forceArch *ArchType
1878}
1879
1880func (m testModuleInstallPathContext) Config() Config {
1881 return m.baseModuleContext.config
1882}
1883
1884func (testModuleInstallPathContext) AddNinjaFileDeps(deps ...string) {}
1885
1886func (m testModuleInstallPathContext) InstallInData() bool {
1887 return m.inData
1888}
1889
1890func (m testModuleInstallPathContext) InstallInTestcases() bool {
1891 return m.inTestcases
1892}
1893
1894func (m testModuleInstallPathContext) InstallInSanitizerDir() bool {
1895 return m.inSanitizerDir
1896}
1897
1898func (m testModuleInstallPathContext) InstallInRamdisk() bool {
1899 return m.inRamdisk
1900}
1901
1902func (m testModuleInstallPathContext) InstallInVendorRamdisk() bool {
1903 return m.inVendorRamdisk
1904}
1905
Inseob Kimf84e9c02021-04-08 21:13:22 +09001906func (m testModuleInstallPathContext) InstallInDebugRamdisk() bool {
1907 return m.inDebugRamdisk
1908}
1909
Ulya Trafimovichccc8c852020-10-14 11:29:07 +01001910func (m testModuleInstallPathContext) InstallInRecovery() bool {
1911 return m.inRecovery
1912}
1913
1914func (m testModuleInstallPathContext) InstallInRoot() bool {
1915 return m.inRoot
1916}
1917
1918func (m testModuleInstallPathContext) InstallBypassMake() bool {
1919 return false
1920}
1921
1922func (m testModuleInstallPathContext) InstallForceOS() (*OsType, *ArchType) {
1923 return m.forceOS, m.forceArch
1924}
1925
1926// Construct a minimal ModuleInstallPathContext for testing. Note that baseModuleContext is
1927// default-initialized, which leaves blueprint.baseModuleContext set to nil, so methods that are
1928// delegated to it will panic.
1929func ModuleInstallPathContextForTesting(config Config) ModuleInstallPathContext {
1930 ctx := &testModuleInstallPathContext{}
1931 ctx.config = config
1932 ctx.os = Android
1933 return ctx
1934}
1935
Colin Cross43f08db2018-11-12 10:13:39 -08001936// Rel performs the same function as filepath.Rel, but reports errors to a PathContext, and reports an error if
1937// targetPath is not inside basePath.
1938func Rel(ctx PathContext, basePath string, targetPath string) string {
1939 rel, isRel := MaybeRel(ctx, basePath, targetPath)
1940 if !isRel {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001941 ReportPathErrorf(ctx, "path %q is not under path %q", targetPath, basePath)
Colin Cross43f08db2018-11-12 10:13:39 -08001942 return ""
1943 }
1944 return rel
1945}
1946
1947// MaybeRel performs the same function as filepath.Rel, but reports errors to a PathContext, and returns false if
1948// targetPath is not inside basePath.
1949func MaybeRel(ctx PathContext, basePath string, targetPath string) (string, bool) {
Dan Willemsen633c5022019-04-12 11:11:38 -07001950 rel, isRel, err := maybeRelErr(basePath, targetPath)
1951 if err != nil {
1952 reportPathError(ctx, err)
1953 }
1954 return rel, isRel
1955}
1956
1957func maybeRelErr(basePath string, targetPath string) (string, bool, error) {
Colin Cross43f08db2018-11-12 10:13:39 -08001958 // filepath.Rel returns an error if one path is absolute and the other is not, handle that case first.
1959 if filepath.IsAbs(basePath) != filepath.IsAbs(targetPath) {
Dan Willemsen633c5022019-04-12 11:11:38 -07001960 return "", false, nil
Colin Cross43f08db2018-11-12 10:13:39 -08001961 }
1962 rel, err := filepath.Rel(basePath, targetPath)
1963 if err != nil {
Dan Willemsen633c5022019-04-12 11:11:38 -07001964 return "", false, err
Colin Cross43f08db2018-11-12 10:13:39 -08001965 } else if rel == ".." || strings.HasPrefix(rel, "../") || strings.HasPrefix(rel, "/") {
Dan Willemsen633c5022019-04-12 11:11:38 -07001966 return "", false, nil
Colin Cross43f08db2018-11-12 10:13:39 -08001967 }
Dan Willemsen633c5022019-04-12 11:11:38 -07001968 return rel, true, nil
Colin Cross43f08db2018-11-12 10:13:39 -08001969}
Colin Cross988414c2020-01-11 01:11:46 +00001970
1971// Writes a file to the output directory. Attempting to write directly to the output directory
1972// will fail due to the sandbox of the soong_build process.
1973func WriteFileToOutputDir(path WritablePath, data []byte, perm os.FileMode) error {
1974 return ioutil.WriteFile(absolutePath(path.String()), data, perm)
1975}
1976
Liz Kammer2dd9ca42020-11-25 16:06:39 -08001977func RemoveAllOutputDir(path WritablePath) error {
1978 return os.RemoveAll(absolutePath(path.String()))
1979}
1980
1981func CreateOutputDirIfNonexistent(path WritablePath, perm os.FileMode) error {
1982 dir := absolutePath(path.String())
1983 if _, err := os.Stat(dir); os.IsNotExist(err) {
1984 return os.MkdirAll(dir, os.ModePerm)
1985 } else {
1986 return err
1987 }
1988}
1989
Colin Cross988414c2020-01-11 01:11:46 +00001990func absolutePath(path string) string {
1991 if filepath.IsAbs(path) {
1992 return path
1993 }
1994 return filepath.Join(absSrcDir, path)
1995}
Chris Parsons216e10a2020-07-09 17:12:52 -04001996
1997// A DataPath represents the path of a file to be used as data, for example
1998// a test library to be installed alongside a test.
1999// The data file should be installed (copied from `<SrcPath>`) to
2000// `<install_root>/<RelativeInstallPath>/<filename>`, or
2001// `<install_root>/<filename>` if RelativeInstallPath is empty.
2002type DataPath struct {
2003 // The path of the data file that should be copied into the data directory
2004 SrcPath Path
2005 // The install path of the data file, relative to the install root.
2006 RelativeInstallPath string
2007}
Colin Crossdcf71b22021-02-01 13:59:03 -08002008
2009// PathsIfNonNil returns a Paths containing only the non-nil input arguments.
2010func PathsIfNonNil(paths ...Path) Paths {
2011 if len(paths) == 0 {
2012 // Fast path for empty argument list
2013 return nil
2014 } else if len(paths) == 1 {
2015 // Fast path for a single argument
2016 if paths[0] != nil {
2017 return paths
2018 } else {
2019 return nil
2020 }
2021 }
2022 ret := make(Paths, 0, len(paths))
2023 for _, path := range paths {
2024 if path != nil {
2025 ret = append(ret, path)
2026 }
2027 }
2028 if len(ret) == 0 {
2029 return nil
2030 }
2031 return ret
2032}