blob: 5d458cbb1f07026a59f39dbf99e59aaa83215dda [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"
Colin Cross0e446152021-05-03 13:35:32 -070027 "github.com/google/blueprint/bootstrap"
Dan Willemsen34cc69e2015-09-23 15:26:20 -070028 "github.com/google/blueprint/pathtools"
Colin Cross3f40fa42015-01-30 17:27:36 -080029)
30
Colin Cross988414c2020-01-11 01:11:46 +000031var absSrcDir string
32
Dan Willemsen34cc69e2015-09-23 15:26:20 -070033// PathContext is the subset of a (Module|Singleton)Context required by the
34// Path methods.
35type PathContext interface {
Colin Crossaabf6792017-11-29 00:27:14 -080036 Config() Config
Dan Willemsen7b310ee2015-12-18 15:11:17 -080037 AddNinjaFileDeps(deps ...string)
Colin Cross3f40fa42015-01-30 17:27:36 -080038}
39
Colin Cross7f19f372016-11-01 11:10:25 -070040type PathGlobContext interface {
41 GlobWithDeps(globPattern string, excludes []string) ([]string, error)
42}
43
Colin Crossaabf6792017-11-29 00:27:14 -080044var _ PathContext = SingletonContext(nil)
45var _ PathContext = ModuleContext(nil)
Dan Willemsen34cc69e2015-09-23 15:26:20 -070046
Ulya Trafimovich8640ab92020-05-11 18:06:15 +010047// "Null" path context is a minimal path context for a given config.
48type NullPathContext struct {
49 config Config
50}
51
52func (NullPathContext) AddNinjaFileDeps(...string) {}
53func (ctx NullPathContext) Config() Config { return ctx.config }
54
Liz Kammera830f3a2020-11-10 10:50:34 -080055// EarlyModulePathContext is a subset of EarlyModuleContext methods required by the
56// Path methods. These path methods can be called before any mutators have run.
57type EarlyModulePathContext interface {
58 PathContext
59 PathGlobContext
60
61 ModuleDir() string
62 ModuleErrorf(fmt string, args ...interface{})
63}
64
65var _ EarlyModulePathContext = ModuleContext(nil)
66
67// Glob globs files and directories matching globPattern relative to ModuleDir(),
68// paths in the excludes parameter will be omitted.
69func Glob(ctx EarlyModulePathContext, globPattern string, excludes []string) Paths {
70 ret, err := ctx.GlobWithDeps(globPattern, excludes)
71 if err != nil {
72 ctx.ModuleErrorf("glob: %s", err.Error())
73 }
74 return pathsForModuleSrcFromFullPath(ctx, ret, true)
75}
76
77// GlobFiles globs *only* files (not directories) matching globPattern relative to ModuleDir().
78// Paths in the excludes parameter will be omitted.
79func GlobFiles(ctx EarlyModulePathContext, globPattern string, excludes []string) Paths {
80 ret, err := ctx.GlobWithDeps(globPattern, excludes)
81 if err != nil {
82 ctx.ModuleErrorf("glob: %s", err.Error())
83 }
84 return pathsForModuleSrcFromFullPath(ctx, ret, false)
85}
86
87// ModuleWithDepsPathContext is a subset of *ModuleContext methods required by
88// the Path methods that rely on module dependencies having been resolved.
89type ModuleWithDepsPathContext interface {
90 EarlyModulePathContext
91 GetDirectDepWithTag(name string, tag blueprint.DependencyTag) blueprint.Module
92}
93
94// ModuleMissingDepsPathContext is a subset of *ModuleContext methods required by
95// the Path methods that rely on module dependencies having been resolved and ability to report
96// missing dependency errors.
97type ModuleMissingDepsPathContext interface {
98 ModuleWithDepsPathContext
99 AddMissingDependencies(missingDeps []string)
100}
101
Dan Willemsen00269f22017-07-06 16:59:48 -0700102type ModuleInstallPathContext interface {
Colin Cross0ea8ba82019-06-06 14:33:29 -0700103 BaseModuleContext
Dan Willemsen00269f22017-07-06 16:59:48 -0700104
105 InstallInData() bool
Jaewoong Jung0949f312019-09-11 10:25:18 -0700106 InstallInTestcases() bool
Dan Willemsen00269f22017-07-06 16:59:48 -0700107 InstallInSanitizerDir() bool
Yifan Hong1b3348d2020-01-21 15:53:22 -0800108 InstallInRamdisk() bool
Yifan Hong60e0cfb2020-10-21 15:17:56 -0700109 InstallInVendorRamdisk() bool
Inseob Kim08758f02021-04-08 21:13:22 +0900110 InstallInDebugRamdisk() bool
Jiyong Parkf9332f12018-02-01 00:54:12 +0900111 InstallInRecovery() bool
Colin Cross90ba5f42019-10-02 11:10:58 -0700112 InstallInRoot() bool
Colin Cross607d8582019-07-29 16:44:46 -0700113 InstallBypassMake() bool
Jiyong Park87788b52020-09-01 12:37:45 +0900114 InstallForceOS() (*OsType, *ArchType)
Dan Willemsen00269f22017-07-06 16:59:48 -0700115}
116
117var _ ModuleInstallPathContext = ModuleContext(nil)
118
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700119// errorfContext is the interface containing the Errorf method matching the
120// Errorf method in blueprint.SingletonContext.
121type errorfContext interface {
122 Errorf(format string, args ...interface{})
Colin Cross3f40fa42015-01-30 17:27:36 -0800123}
124
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700125var _ errorfContext = blueprint.SingletonContext(nil)
126
127// moduleErrorf is the interface containing the ModuleErrorf method matching
128// the ModuleErrorf method in blueprint.ModuleContext.
129type moduleErrorf interface {
130 ModuleErrorf(format string, args ...interface{})
Colin Cross3f40fa42015-01-30 17:27:36 -0800131}
132
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700133var _ moduleErrorf = blueprint.ModuleContext(nil)
134
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700135// reportPathError will register an error with the attached context. It
136// attempts ctx.ModuleErrorf for a better error message first, then falls
137// back to ctx.Errorf.
Colin Cross1ccfcc32018-02-22 13:54:26 -0800138func reportPathError(ctx PathContext, err error) {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +0100139 ReportPathErrorf(ctx, "%s", err.Error())
Colin Cross1ccfcc32018-02-22 13:54:26 -0800140}
141
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +0100142// ReportPathErrorf will register an error with the attached context. It
Colin Cross1ccfcc32018-02-22 13:54:26 -0800143// attempts ctx.ModuleErrorf for a better error message first, then falls
144// back to ctx.Errorf.
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +0100145func ReportPathErrorf(ctx PathContext, format string, args ...interface{}) {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700146 if mctx, ok := ctx.(moduleErrorf); ok {
147 mctx.ModuleErrorf(format, args...)
148 } else if ectx, ok := ctx.(errorfContext); ok {
149 ectx.Errorf(format, args...)
150 } else {
151 panic(fmt.Sprintf(format, args...))
Colin Crossf2298272015-05-12 11:36:53 -0700152 }
153}
154
Colin Cross5e708052019-08-06 13:59:50 -0700155func pathContextName(ctx PathContext, module blueprint.Module) string {
156 if x, ok := ctx.(interface{ ModuleName(blueprint.Module) string }); ok {
157 return x.ModuleName(module)
158 } else if x, ok := ctx.(interface{ OtherModuleName(blueprint.Module) string }); ok {
159 return x.OtherModuleName(module)
160 }
161 return "unknown"
162}
163
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700164type Path interface {
165 // Returns the path in string form
166 String() string
167
Colin Cross4f6fc9c2016-10-26 10:05:25 -0700168 // Ext returns the extension of the last element of the path
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700169 Ext() string
Colin Cross4f6fc9c2016-10-26 10:05:25 -0700170
171 // Base returns the last element of the path
172 Base() string
Colin Crossfaeb7aa2017-02-01 14:12:44 -0800173
174 // Rel returns the portion of the path relative to the directory it was created from. For
175 // example, Rel on a PathsForModuleSrc would return the path relative to the module source
Colin Cross0db55682017-12-05 15:36:55 -0800176 // directory, and OutputPath.Join("foo").Rel() would return "foo".
Colin Crossfaeb7aa2017-02-01 14:12:44 -0800177 Rel() string
Paul Duffin85d8f0d2021-03-24 10:18:18 +0000178
179 // RelativeToTop returns a new path relative to the top, it is provided solely for use in tests.
180 //
181 // It is guaranteed to always return the same type as it is called on, e.g. if called on an
182 // InstallPath then the returned value can be converted to an InstallPath.
183 //
184 // A standard build has the following structure:
185 // ../top/
186 // out/ - make install files go here.
187 // out/soong - this is the buildDir passed to NewTestConfig()
188 // ... - the source files
189 //
190 // This function converts a path so that it appears relative to the ../top/ directory, i.e.
191 // * Make install paths, which have the pattern "buildDir/../<path>" are converted into the top
192 // relative path "out/<path>"
193 // * Soong install paths and other writable paths, which have the pattern "buildDir/<path>" are
194 // converted into the top relative path "out/soong/<path>".
195 // * Source paths are already relative to the top.
196 // * Phony paths are not relative to anything.
197 // * toolDepPath have an absolute but known value in so don't need making relative to anything in
198 // order to test.
199 RelativeToTop() Path
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700200}
201
Paul Duffin85d8f0d2021-03-24 10:18:18 +0000202const (
203 OutDir = "out"
204 OutSoongDir = OutDir + "/soong"
205)
206
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700207// WritablePath is a type of path that can be used as an output for build rules.
208type WritablePath interface {
209 Path
210
Paul Duffin9b478b02019-12-10 13:41:51 +0000211 // return the path to the build directory.
Paul Duffind65c58b2021-03-24 09:22:07 +0000212 getBuildDir() string
Paul Duffin9b478b02019-12-10 13:41:51 +0000213
Jeff Gaston734e3802017-04-10 15:47:24 -0700214 // the writablePath method doesn't directly do anything,
215 // but it allows a struct to distinguish between whether or not it implements the WritablePath interface
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700216 writablePath()
Hans MÃ¥nssond3f2bd72020-11-27 12:37:28 +0100217
218 ReplaceExtension(ctx PathContext, ext string) OutputPath
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700219}
220
221type genPathProvider interface {
Liz Kammera830f3a2020-11-10 10:50:34 -0800222 genPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleGenPath
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700223}
224type objPathProvider interface {
Liz Kammera830f3a2020-11-10 10:50:34 -0800225 objPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleObjPath
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700226}
227type resPathProvider interface {
Liz Kammera830f3a2020-11-10 10:50:34 -0800228 resPathWithName(ctx ModuleOutPathContext, name string) ModuleResPath
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700229}
230
231// GenPathWithExt derives a new file path in ctx's generated sources directory
232// from the current path, but with the new extension.
Liz Kammera830f3a2020-11-10 10:50:34 -0800233func GenPathWithExt(ctx ModuleOutPathContext, subdir string, p Path, ext string) ModuleGenPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700234 if path, ok := p.(genPathProvider); ok {
Dan Willemsen21ec4902016-11-02 20:43:13 -0700235 return path.genPathWithExt(ctx, subdir, ext)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700236 }
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +0100237 ReportPathErrorf(ctx, "Tried to create generated file from unsupported path: %s(%s)", reflect.TypeOf(p).Name(), p)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700238 return PathForModuleGen(ctx)
239}
240
241// ObjPathWithExt derives a new file path in ctx's object directory from the
242// current path, but with the new extension.
Liz Kammera830f3a2020-11-10 10:50:34 -0800243func ObjPathWithExt(ctx ModuleOutPathContext, subdir string, p Path, ext string) ModuleObjPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700244 if path, ok := p.(objPathProvider); ok {
245 return path.objPathWithExt(ctx, subdir, ext)
246 }
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +0100247 ReportPathErrorf(ctx, "Tried to create object file from unsupported path: %s (%s)", reflect.TypeOf(p).Name(), p)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700248 return PathForModuleObj(ctx)
249}
250
251// ResPathWithName derives a new path in ctx's output resource directory, using
252// the current path to create the directory name, and the `name` argument for
253// the filename.
Liz Kammera830f3a2020-11-10 10:50:34 -0800254func ResPathWithName(ctx ModuleOutPathContext, p Path, name string) ModuleResPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700255 if path, ok := p.(resPathProvider); ok {
256 return path.resPathWithName(ctx, name)
257 }
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +0100258 ReportPathErrorf(ctx, "Tried to create res file from unsupported path: %s (%s)", reflect.TypeOf(p).Name(), p)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700259 return PathForModuleRes(ctx)
260}
261
262// OptionalPath is a container that may or may not contain a valid Path.
263type OptionalPath struct {
264 valid bool
265 path Path
266}
267
268// OptionalPathForPath returns an OptionalPath containing the path.
269func OptionalPathForPath(path Path) OptionalPath {
270 if path == nil {
271 return OptionalPath{}
272 }
273 return OptionalPath{valid: true, path: path}
274}
275
276// Valid returns whether there is a valid path
277func (p OptionalPath) Valid() bool {
278 return p.valid
279}
280
281// Path returns the Path embedded in this OptionalPath. You must be sure that
282// there is a valid path, since this method will panic if there is not.
283func (p OptionalPath) Path() Path {
284 if !p.valid {
285 panic("Requesting an invalid path")
286 }
287 return p.path
288}
289
Paul Duffinafdd4062021-03-30 19:44:07 +0100290// RelativeToTop returns an OptionalPath with the path that was embedded having been replaced by the
291// result of calling Path.RelativeToTop on it.
292func (p OptionalPath) RelativeToTop() OptionalPath {
Paul Duffina5b81352021-03-28 23:57:19 +0100293 if !p.valid {
294 return p
295 }
296 p.path = p.path.RelativeToTop()
297 return p
298}
299
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700300// String returns the string version of the Path, or "" if it isn't valid.
301func (p OptionalPath) String() string {
302 if p.valid {
303 return p.path.String()
304 } else {
305 return ""
Colin Crossf2298272015-05-12 11:36:53 -0700306 }
307}
Colin Cross6e18ca42015-07-14 18:55:36 -0700308
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700309// Paths is a slice of Path objects, with helpers to operate on the collection.
310type Paths []Path
311
Paul Duffin85d8f0d2021-03-24 10:18:18 +0000312// RelativeToTop creates a new Paths containing the result of calling Path.RelativeToTop on each
313// item in this slice.
314func (p Paths) RelativeToTop() Paths {
315 ensureTestOnly()
316 if p == nil {
317 return p
318 }
319 ret := make(Paths, len(p))
320 for i, path := range p {
321 ret[i] = path.RelativeToTop()
322 }
323 return ret
324}
325
Jingwen Chen40fd90a2020-06-15 05:24:19 +0000326func (paths Paths) containsPath(path Path) bool {
327 for _, p := range paths {
328 if p == path {
329 return true
330 }
331 }
332 return false
333}
334
Liz Kammer7aa52882021-02-11 09:16:14 -0500335// PathsForSource returns Paths rooted from SrcDir, *not* rooted from the module's local source
336// directory
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700337func PathsForSource(ctx PathContext, paths []string) Paths {
338 ret := make(Paths, len(paths))
339 for i, path := range paths {
340 ret[i] = PathForSource(ctx, path)
341 }
342 return ret
343}
344
Liz Kammer7aa52882021-02-11 09:16:14 -0500345// ExistentPathsForSources returns a list of Paths rooted from SrcDir, *not* rooted from the
346// module's local source directory, that are found in the tree. If any are not found, they are
347// 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 -0800348func ExistentPathsForSources(ctx PathContext, paths []string) Paths {
Dan Willemsen7b310ee2015-12-18 15:11:17 -0800349 ret := make(Paths, 0, len(paths))
350 for _, path := range paths {
Colin Cross32f38982018-02-22 11:47:25 -0800351 p := ExistentPathForSource(ctx, path)
Dan Willemsen7b310ee2015-12-18 15:11:17 -0800352 if p.Valid() {
353 ret = append(ret, p.Path())
354 }
355 }
356 return ret
357}
358
Liz Kammer620dea62021-04-14 17:36:10 -0400359// PathsForModuleSrc returns a Paths{} containing the resolved references in paths:
360// * filepath, relative to local module directory, resolves as a filepath relative to the local
361// source directory
362// * glob, relative to the local module directory, resolves as filepath(s), relative to the local
363// source directory.
364// * other modules using the ":name{.tag}" syntax. These modules must implement SourceFileProducer
365// or OutputFileProducer. These resolve as a filepath to an output filepath or generated source
366// filepath.
367// Properties passed as the paths argument must have been annotated with struct tag
Colin Cross41955e82019-05-29 14:40:35 -0700368// `android:"path"` so that dependencies on SourceFileProducer modules will have already been handled by the
Liz Kammer620dea62021-04-14 17:36:10 -0400369// path_deps mutator.
370// If a requested module is not found as a dependency:
371// * if ctx.Config().AllowMissingDependencies() is true, this module to be marked as having
372// missing dependencies
373// * otherwise, a ModuleError is thrown.
Liz Kammera830f3a2020-11-10 10:50:34 -0800374func PathsForModuleSrc(ctx ModuleMissingDepsPathContext, paths []string) Paths {
Colin Cross8a497952019-03-05 22:25:09 -0800375 return PathsForModuleSrcExcludes(ctx, paths, nil)
376}
377
Liz Kammer620dea62021-04-14 17:36:10 -0400378// PathsForModuleSrcExcludes returns a Paths{} containing the resolved references in paths, minus
379// those listed in excludes. Elements of paths and excludes are resolved as:
380// * filepath, relative to local module directory, resolves as a filepath relative to the local
381// source directory
382// * glob, relative to the local module directory, resolves as filepath(s), relative to the local
383// source directory. Not valid in excludes.
384// * other modules using the ":name{.tag}" syntax. These modules must implement SourceFileProducer
385// or OutputFileProducer. These resolve as a filepath to an output filepath or generated source
386// filepath.
387// excluding the items (similarly resolved
388// Properties passed as the paths argument must have been annotated with struct tag
389// `android:"path"` so that dependencies on SourceFileProducer modules will have already been handled by the
390// path_deps mutator.
391// If a requested module is not found as a dependency:
392// * if ctx.Config().AllowMissingDependencies() is true, this module to be marked as having
393// missing dependencies
394// * otherwise, a ModuleError is thrown.
Liz Kammera830f3a2020-11-10 10:50:34 -0800395func PathsForModuleSrcExcludes(ctx ModuleMissingDepsPathContext, paths, excludes []string) Paths {
Colin Crossba71a3f2019-03-18 12:12:48 -0700396 ret, missingDeps := PathsAndMissingDepsForModuleSrcExcludes(ctx, paths, excludes)
397 if ctx.Config().AllowMissingDependencies() {
398 ctx.AddMissingDependencies(missingDeps)
399 } else {
400 for _, m := range missingDeps {
401 ctx.ModuleErrorf(`missing dependency on %q, is the property annotated with android:"path"?`, m)
402 }
403 }
404 return ret
405}
406
Ulya Trafimovich4d2eeed2019-11-08 10:54:21 +0000407// OutputPaths is a slice of OutputPath objects, with helpers to operate on the collection.
408type OutputPaths []OutputPath
409
410// Paths returns the OutputPaths as a Paths
411func (p OutputPaths) Paths() Paths {
412 if p == nil {
413 return nil
414 }
415 ret := make(Paths, len(p))
416 for i, path := range p {
417 ret[i] = path
418 }
419 return ret
420}
421
422// Strings returns the string forms of the writable paths.
423func (p OutputPaths) Strings() []string {
424 if p == nil {
425 return nil
426 }
427 ret := make([]string, len(p))
428 for i, path := range p {
429 ret[i] = path.String()
430 }
431 return ret
432}
433
Liz Kammera830f3a2020-11-10 10:50:34 -0800434// Expands Paths to a SourceFileProducer or OutputFileProducer module dependency referenced via ":name" or ":name{.tag}" syntax.
435// If the dependency is not found, a missingErrorDependency is returned.
436// If the module dependency is not a SourceFileProducer or OutputFileProducer, appropriate errors will be returned.
437func getPathsFromModuleDep(ctx ModuleWithDepsPathContext, path, moduleName, tag string) (Paths, error) {
438 module := ctx.GetDirectDepWithTag(moduleName, sourceOrOutputDepTag(tag))
439 if module == nil {
440 return nil, missingDependencyError{[]string{moduleName}}
441 }
Colin Crossfa65cee2021-03-22 17:05:59 -0700442 if aModule, ok := module.(Module); ok && !aModule.Enabled() {
443 return nil, missingDependencyError{[]string{moduleName}}
444 }
Liz Kammera830f3a2020-11-10 10:50:34 -0800445 if outProducer, ok := module.(OutputFileProducer); ok {
446 outputFiles, err := outProducer.OutputFiles(tag)
447 if err != nil {
448 return nil, fmt.Errorf("path dependency %q: %s", path, err)
449 }
450 return outputFiles, nil
451 } else if tag != "" {
452 return nil, fmt.Errorf("path dependency %q is not an output file producing module", path)
Colin Cross0e446152021-05-03 13:35:32 -0700453 } else if goBinary, ok := module.(bootstrap.GoBinaryTool); ok {
454 if rel, err := filepath.Rel(PathForOutput(ctx).String(), goBinary.InstallPath()); err == nil {
455 return Paths{PathForOutput(ctx, rel).WithoutRel()}, nil
456 } else {
457 return nil, fmt.Errorf("cannot find output path for %q: %w", goBinary.InstallPath(), err)
458 }
Liz Kammera830f3a2020-11-10 10:50:34 -0800459 } else if srcProducer, ok := module.(SourceFileProducer); ok {
460 return srcProducer.Srcs(), nil
461 } else {
462 return nil, fmt.Errorf("path dependency %q is not a source file producing module", path)
463 }
464}
465
Liz Kammer620dea62021-04-14 17:36:10 -0400466// PathsAndMissingDepsForModuleSrcExcludes returns a Paths{} containing the resolved references in
467// paths, minus those listed in excludes. Elements of paths and excludes are resolved as:
468// * filepath, relative to local module directory, resolves as a filepath relative to the local
469// source directory
470// * glob, relative to the local module directory, resolves as filepath(s), relative to the local
471// source directory. Not valid in excludes.
472// * other modules using the ":name{.tag}" syntax. These modules must implement SourceFileProducer
473// or OutputFileProducer. These resolve as a filepath to an output filepath or generated source
474// filepath.
475// and a list of the module names of missing module dependencies are returned as the second return.
476// Properties passed as the paths argument must have been annotated with struct tag
Colin Cross41955e82019-05-29 14:40:35 -0700477// `android:"path"` so that dependencies on SourceFileProducer modules will have already been handled by the
Liz Kammer620dea62021-04-14 17:36:10 -0400478// path_deps mutator.
Liz Kammera830f3a2020-11-10 10:50:34 -0800479func PathsAndMissingDepsForModuleSrcExcludes(ctx ModuleWithDepsPathContext, paths, excludes []string) (Paths, []string) {
Colin Cross8a497952019-03-05 22:25:09 -0800480 prefix := pathForModuleSrc(ctx).String()
481
482 var expandedExcludes []string
483 if excludes != nil {
484 expandedExcludes = make([]string, 0, len(excludes))
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700485 }
Colin Cross8a497952019-03-05 22:25:09 -0800486
Colin Crossba71a3f2019-03-18 12:12:48 -0700487 var missingExcludeDeps []string
488
Colin Cross8a497952019-03-05 22:25:09 -0800489 for _, e := range excludes {
Colin Cross41955e82019-05-29 14:40:35 -0700490 if m, t := SrcIsModuleWithTag(e); m != "" {
Liz Kammera830f3a2020-11-10 10:50:34 -0800491 modulePaths, err := getPathsFromModuleDep(ctx, e, m, t)
492 if m, ok := err.(missingDependencyError); ok {
493 missingExcludeDeps = append(missingExcludeDeps, m.missingDeps...)
494 } else if err != nil {
495 reportPathError(ctx, err)
Colin Cross8a497952019-03-05 22:25:09 -0800496 } else {
Liz Kammera830f3a2020-11-10 10:50:34 -0800497 expandedExcludes = append(expandedExcludes, modulePaths.Strings()...)
Colin Cross8a497952019-03-05 22:25:09 -0800498 }
499 } else {
500 expandedExcludes = append(expandedExcludes, filepath.Join(prefix, e))
501 }
502 }
503
504 if paths == nil {
Colin Crossba71a3f2019-03-18 12:12:48 -0700505 return nil, missingExcludeDeps
Colin Cross8a497952019-03-05 22:25:09 -0800506 }
507
Colin Crossba71a3f2019-03-18 12:12:48 -0700508 var missingDeps []string
509
Colin Cross8a497952019-03-05 22:25:09 -0800510 expandedSrcFiles := make(Paths, 0, len(paths))
511 for _, s := range paths {
512 srcFiles, err := expandOneSrcPath(ctx, s, expandedExcludes)
513 if depErr, ok := err.(missingDependencyError); ok {
Colin Crossba71a3f2019-03-18 12:12:48 -0700514 missingDeps = append(missingDeps, depErr.missingDeps...)
Colin Cross8a497952019-03-05 22:25:09 -0800515 } else if err != nil {
516 reportPathError(ctx, err)
517 }
518 expandedSrcFiles = append(expandedSrcFiles, srcFiles...)
519 }
Colin Crossba71a3f2019-03-18 12:12:48 -0700520
521 return expandedSrcFiles, append(missingDeps, missingExcludeDeps...)
Colin Cross8a497952019-03-05 22:25:09 -0800522}
523
524type missingDependencyError struct {
525 missingDeps []string
526}
527
528func (e missingDependencyError) Error() string {
529 return "missing dependencies: " + strings.Join(e.missingDeps, ", ")
530}
531
Liz Kammera830f3a2020-11-10 10:50:34 -0800532// Expands one path string to Paths rooted from the module's local source
533// directory, excluding those listed in the expandedExcludes.
534// Expands globs, references to SourceFileProducer or OutputFileProducer modules using the ":name" and ":name{.tag}" syntax.
535func expandOneSrcPath(ctx ModuleWithDepsPathContext, sPath string, expandedExcludes []string) (Paths, error) {
Jooyung Han7607dd32020-07-05 10:23:14 +0900536 excludePaths := func(paths Paths) Paths {
537 if len(expandedExcludes) == 0 {
538 return paths
539 }
540 remainder := make(Paths, 0, len(paths))
541 for _, p := range paths {
542 if !InList(p.String(), expandedExcludes) {
543 remainder = append(remainder, p)
544 }
545 }
546 return remainder
547 }
Liz Kammera830f3a2020-11-10 10:50:34 -0800548 if m, t := SrcIsModuleWithTag(sPath); m != "" {
549 modulePaths, err := getPathsFromModuleDep(ctx, sPath, m, t)
550 if err != nil {
551 return nil, err
Colin Cross8a497952019-03-05 22:25:09 -0800552 } else {
Liz Kammera830f3a2020-11-10 10:50:34 -0800553 return excludePaths(modulePaths), nil
Colin Cross8a497952019-03-05 22:25:09 -0800554 }
Liz Kammera830f3a2020-11-10 10:50:34 -0800555 } else if pathtools.IsGlob(sPath) {
556 paths := GlobFiles(ctx, pathForModuleSrc(ctx, sPath).String(), expandedExcludes)
Colin Cross8a497952019-03-05 22:25:09 -0800557 return PathsWithModuleSrcSubDir(ctx, paths, ""), nil
558 } else {
Liz Kammera830f3a2020-11-10 10:50:34 -0800559 p := pathForModuleSrc(ctx, sPath)
Colin Cross988414c2020-01-11 01:11:46 +0000560 if exists, _, err := ctx.Config().fs.Exists(p.String()); err != nil {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +0100561 ReportPathErrorf(ctx, "%s: %s", p, err.Error())
Pedro Loureiro5d190cc2021-02-15 15:41:33 +0000562 } else if !exists && !ctx.Config().TestAllowNonExistentPaths {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +0100563 ReportPathErrorf(ctx, "module source path %q does not exist", p)
Colin Cross8a497952019-03-05 22:25:09 -0800564 }
565
Jooyung Han7607dd32020-07-05 10:23:14 +0900566 if InList(p.String(), expandedExcludes) {
Colin Cross8a497952019-03-05 22:25:09 -0800567 return nil, nil
568 }
569 return Paths{p}, nil
570 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700571}
572
573// pathsForModuleSrcFromFullPath returns Paths rooted from the module's local
574// source directory, but strip the local source directory from the beginning of
Dan Willemsen540a78c2018-02-26 21:50:08 -0800575// each string. If incDirs is false, strip paths with a trailing '/' from the list.
Colin Crossfe4bc362018-09-12 10:02:13 -0700576// It intended for use in globs that only list files that exist, so it allows '$' in
577// filenames.
Liz Kammera830f3a2020-11-10 10:50:34 -0800578func pathsForModuleSrcFromFullPath(ctx EarlyModulePathContext, paths []string, incDirs bool) Paths {
Colin Cross6510f912017-11-29 00:27:14 -0800579 prefix := filepath.Join(ctx.Config().srcDir, ctx.ModuleDir()) + "/"
Colin Cross0f37af02017-09-27 17:42:05 -0700580 if prefix == "./" {
581 prefix = ""
582 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700583 ret := make(Paths, 0, len(paths))
584 for _, p := range paths {
Dan Willemsen540a78c2018-02-26 21:50:08 -0800585 if !incDirs && strings.HasSuffix(p, "/") {
586 continue
587 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700588 path := filepath.Clean(p)
589 if !strings.HasPrefix(path, prefix) {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +0100590 ReportPathErrorf(ctx, "Path %q is not in module source directory %q", p, prefix)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700591 continue
592 }
Colin Crosse3924e12018-08-15 20:18:53 -0700593
Colin Crossfe4bc362018-09-12 10:02:13 -0700594 srcPath, err := safePathForSource(ctx, ctx.ModuleDir(), path[len(prefix):])
Colin Crosse3924e12018-08-15 20:18:53 -0700595 if err != nil {
596 reportPathError(ctx, err)
597 continue
598 }
599
Colin Cross07e51612019-03-05 12:46:40 -0800600 srcPath.basePath.rel = srcPath.path
Colin Crosse3924e12018-08-15 20:18:53 -0700601
Colin Cross07e51612019-03-05 12:46:40 -0800602 ret = append(ret, srcPath)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700603 }
604 return ret
605}
606
Liz Kammera830f3a2020-11-10 10:50:34 -0800607// PathsWithOptionalDefaultForModuleSrc returns Paths rooted from the module's local source
608// directory. If input is nil, use the default if it exists. If input is empty, returns nil.
609func PathsWithOptionalDefaultForModuleSrc(ctx ModuleMissingDepsPathContext, input []string, def string) Paths {
Colin Cross0ddae7f2019-02-07 15:30:01 -0800610 if input != nil {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700611 return PathsForModuleSrc(ctx, input)
612 }
613 // Use Glob so that if the default doesn't exist, a dependency is added so that when it
614 // is created, we're run again.
Colin Cross6510f912017-11-29 00:27:14 -0800615 path := filepath.Join(ctx.Config().srcDir, ctx.ModuleDir(), def)
Liz Kammera830f3a2020-11-10 10:50:34 -0800616 return Glob(ctx, path, nil)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700617}
618
619// Strings returns the Paths in string form
620func (p Paths) Strings() []string {
621 if p == nil {
622 return nil
623 }
624 ret := make([]string, len(p))
625 for i, path := range p {
626 ret[i] = path.String()
627 }
628 return ret
629}
630
Colin Crossc0efd1d2020-07-03 11:56:24 -0700631func CopyOfPaths(paths Paths) Paths {
632 return append(Paths(nil), paths...)
633}
634
Colin Crossb6715442017-10-24 11:13:31 -0700635// FirstUniquePaths returns all unique elements of a Paths, keeping the first copy of each. It
636// modifies the Paths slice contents in place, and returns a subslice of the original slice.
Dan Willemsenfe92c962017-08-29 12:28:37 -0700637func FirstUniquePaths(list Paths) Paths {
Colin Cross27027c72020-02-28 15:34:17 -0800638 // 128 was chosen based on BenchmarkFirstUniquePaths results.
639 if len(list) > 128 {
640 return firstUniquePathsMap(list)
641 }
642 return firstUniquePathsList(list)
643}
644
Colin Crossc0efd1d2020-07-03 11:56:24 -0700645// SortedUniquePaths returns all unique elements of a Paths in sorted order. It modifies the
646// Paths slice contents in place, and returns a subslice of the original slice.
Jiyong Park33c77362020-05-29 22:00:16 +0900647func SortedUniquePaths(list Paths) Paths {
648 unique := FirstUniquePaths(list)
649 sort.Slice(unique, func(i, j int) bool {
650 return unique[i].String() < unique[j].String()
651 })
652 return unique
653}
654
Colin Cross27027c72020-02-28 15:34:17 -0800655func firstUniquePathsList(list Paths) Paths {
Dan Willemsenfe92c962017-08-29 12:28:37 -0700656 k := 0
657outer:
658 for i := 0; i < len(list); i++ {
659 for j := 0; j < k; j++ {
660 if list[i] == list[j] {
661 continue outer
662 }
663 }
664 list[k] = list[i]
665 k++
666 }
667 return list[:k]
668}
669
Colin Cross27027c72020-02-28 15:34:17 -0800670func firstUniquePathsMap(list Paths) Paths {
671 k := 0
672 seen := make(map[Path]bool, len(list))
673 for i := 0; i < len(list); i++ {
674 if seen[list[i]] {
675 continue
676 }
677 seen[list[i]] = true
678 list[k] = list[i]
679 k++
680 }
681 return list[:k]
682}
683
Colin Cross5d583952020-11-24 16:21:24 -0800684// FirstUniqueInstallPaths returns all unique elements of an InstallPaths, keeping the first copy of each. It
685// modifies the InstallPaths slice contents in place, and returns a subslice of the original slice.
686func FirstUniqueInstallPaths(list InstallPaths) InstallPaths {
687 // 128 was chosen based on BenchmarkFirstUniquePaths results.
688 if len(list) > 128 {
689 return firstUniqueInstallPathsMap(list)
690 }
691 return firstUniqueInstallPathsList(list)
692}
693
694func firstUniqueInstallPathsList(list InstallPaths) InstallPaths {
695 k := 0
696outer:
697 for i := 0; i < len(list); i++ {
698 for j := 0; j < k; j++ {
699 if list[i] == list[j] {
700 continue outer
701 }
702 }
703 list[k] = list[i]
704 k++
705 }
706 return list[:k]
707}
708
709func firstUniqueInstallPathsMap(list InstallPaths) InstallPaths {
710 k := 0
711 seen := make(map[InstallPath]bool, len(list))
712 for i := 0; i < len(list); i++ {
713 if seen[list[i]] {
714 continue
715 }
716 seen[list[i]] = true
717 list[k] = list[i]
718 k++
719 }
720 return list[:k]
721}
722
Colin Crossb6715442017-10-24 11:13:31 -0700723// LastUniquePaths returns all unique elements of a Paths, keeping the last copy of each. It
724// modifies the Paths slice contents in place, and returns a subslice of the original slice.
725func LastUniquePaths(list Paths) Paths {
726 totalSkip := 0
727 for i := len(list) - 1; i >= totalSkip; i-- {
728 skip := 0
729 for j := i - 1; j >= totalSkip; j-- {
730 if list[i] == list[j] {
731 skip++
732 } else {
733 list[j+skip] = list[j]
734 }
735 }
736 totalSkip += skip
737 }
738 return list[totalSkip:]
739}
740
Colin Crossa140bb02018-04-17 10:52:26 -0700741// ReversePaths returns a copy of a Paths in reverse order.
742func ReversePaths(list Paths) Paths {
743 if list == nil {
744 return nil
745 }
746 ret := make(Paths, len(list))
747 for i := range list {
748 ret[i] = list[len(list)-1-i]
749 }
750 return ret
751}
752
Jeff Gaston294356f2017-09-27 17:05:30 -0700753func indexPathList(s Path, list []Path) int {
754 for i, l := range list {
755 if l == s {
756 return i
757 }
758 }
759
760 return -1
761}
762
763func inPathList(p Path, list []Path) bool {
764 return indexPathList(p, list) != -1
765}
766
767func FilterPathList(list []Path, filter []Path) (remainder []Path, filtered []Path) {
Paul Duffin57b9e1d2019-12-13 00:03:35 +0000768 return FilterPathListPredicate(list, func(p Path) bool { return inPathList(p, filter) })
769}
770
771func FilterPathListPredicate(list []Path, predicate func(Path) bool) (remainder []Path, filtered []Path) {
Jeff Gaston294356f2017-09-27 17:05:30 -0700772 for _, l := range list {
Paul Duffin57b9e1d2019-12-13 00:03:35 +0000773 if predicate(l) {
Jeff Gaston294356f2017-09-27 17:05:30 -0700774 filtered = append(filtered, l)
775 } else {
776 remainder = append(remainder, l)
777 }
778 }
779
780 return
781}
782
Colin Cross93e85952017-08-15 13:34:18 -0700783// HasExt returns true of any of the paths have extension ext, otherwise false
784func (p Paths) HasExt(ext string) bool {
785 for _, path := range p {
786 if path.Ext() == ext {
787 return true
788 }
789 }
790
791 return false
792}
793
794// FilterByExt returns the subset of the paths that have extension ext
795func (p Paths) FilterByExt(ext string) Paths {
796 ret := make(Paths, 0, len(p))
797 for _, path := range p {
798 if path.Ext() == ext {
799 ret = append(ret, path)
800 }
801 }
802 return ret
803}
804
805// FilterOutByExt returns the subset of the paths that do not have extension ext
806func (p Paths) FilterOutByExt(ext string) Paths {
807 ret := make(Paths, 0, len(p))
808 for _, path := range p {
809 if path.Ext() != ext {
810 ret = append(ret, path)
811 }
812 }
813 return ret
814}
815
Colin Cross5e6cfbe2017-11-03 15:20:35 -0700816// DirectorySortedPaths is a slice of paths that are sorted such that all files in a directory
817// (including subdirectories) are in a contiguous subslice of the list, and can be found in
818// O(log(N)) time using a binary search on the directory prefix.
819type DirectorySortedPaths Paths
820
821func PathsToDirectorySortedPaths(paths Paths) DirectorySortedPaths {
822 ret := append(DirectorySortedPaths(nil), paths...)
823 sort.Slice(ret, func(i, j int) bool {
824 return ret[i].String() < ret[j].String()
825 })
826 return ret
827}
828
829// PathsInDirectory returns a subslice of the DirectorySortedPaths as a Paths that contains all entries
830// that are in the specified directory and its subdirectories.
831func (p DirectorySortedPaths) PathsInDirectory(dir string) Paths {
832 prefix := filepath.Clean(dir) + "/"
833 start := sort.Search(len(p), func(i int) bool {
834 return prefix < p[i].String()
835 })
836
837 ret := p[start:]
838
839 end := sort.Search(len(ret), func(i int) bool {
840 return !strings.HasPrefix(ret[i].String(), prefix)
841 })
842
843 ret = ret[:end]
844
845 return Paths(ret)
846}
847
Alex Humesky29e3bbe2020-11-20 21:30:13 -0500848// WritablePaths is a slice of WritablePath, used for multiple outputs.
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700849type WritablePaths []WritablePath
850
Paul Duffin85d8f0d2021-03-24 10:18:18 +0000851// RelativeToTop creates a new WritablePaths containing the result of calling Path.RelativeToTop on
852// each item in this slice.
853func (p WritablePaths) RelativeToTop() WritablePaths {
854 ensureTestOnly()
855 if p == nil {
856 return p
857 }
858 ret := make(WritablePaths, len(p))
859 for i, path := range p {
860 ret[i] = path.RelativeToTop().(WritablePath)
861 }
862 return ret
863}
864
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700865// Strings returns the string forms of the writable paths.
866func (p WritablePaths) Strings() []string {
867 if p == nil {
868 return nil
869 }
870 ret := make([]string, len(p))
871 for i, path := range p {
872 ret[i] = path.String()
873 }
874 return ret
875}
876
Colin Cross3bc7ffa2017-11-22 16:19:37 -0800877// Paths returns the WritablePaths as a Paths
878func (p WritablePaths) Paths() Paths {
879 if p == nil {
880 return nil
881 }
882 ret := make(Paths, len(p))
883 for i, path := range p {
884 ret[i] = path
885 }
886 return ret
887}
888
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700889type basePath struct {
Paul Duffin74abc5d2021-03-24 09:24:59 +0000890 path string
891 rel string
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700892}
893
894func (p basePath) Ext() string {
895 return filepath.Ext(p.path)
896}
897
Colin Cross4f6fc9c2016-10-26 10:05:25 -0700898func (p basePath) Base() string {
899 return filepath.Base(p.path)
900}
901
Colin Crossfaeb7aa2017-02-01 14:12:44 -0800902func (p basePath) Rel() string {
903 if p.rel != "" {
904 return p.rel
905 }
906 return p.path
907}
908
Colin Cross0875c522017-11-28 17:34:01 -0800909func (p basePath) String() string {
910 return p.path
911}
912
Colin Cross0db55682017-12-05 15:36:55 -0800913func (p basePath) withRel(rel string) basePath {
914 p.path = filepath.Join(p.path, rel)
915 p.rel = rel
916 return p
917}
918
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700919// SourcePath is a Path representing a file path rooted from SrcDir
920type SourcePath struct {
921 basePath
Paul Duffin580efc82021-03-24 09:04:03 +0000922
923 // The sources root, i.e. Config.SrcDir()
924 srcDir string
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700925}
926
Paul Duffin85d8f0d2021-03-24 10:18:18 +0000927func (p SourcePath) RelativeToTop() Path {
928 ensureTestOnly()
929 return p
930}
931
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700932var _ Path = SourcePath{}
933
Colin Cross0db55682017-12-05 15:36:55 -0800934func (p SourcePath) withRel(rel string) SourcePath {
935 p.basePath = p.basePath.withRel(rel)
936 return p
937}
938
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700939// safePathForSource is for paths that we expect are safe -- only for use by go
940// code that is embedding ninja variables in paths
Colin Crossfe4bc362018-09-12 10:02:13 -0700941func safePathForSource(ctx PathContext, pathComponents ...string) (SourcePath, error) {
942 p, err := validateSafePath(pathComponents...)
Paul Duffin74abc5d2021-03-24 09:24:59 +0000943 ret := SourcePath{basePath{p, ""}, ctx.Config().srcDir}
Colin Crossfe4bc362018-09-12 10:02:13 -0700944 if err != nil {
945 return ret, err
946 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700947
Colin Cross7b3dcc32019-01-24 13:14:39 -0800948 // absolute path already checked by validateSafePath
949 if strings.HasPrefix(ret.String(), ctx.Config().buildDir) {
Mikhail Naganovab1f5182019-02-08 13:17:55 -0800950 return ret, fmt.Errorf("source path %q is in output", ret.String())
Colin Cross6e18ca42015-07-14 18:55:36 -0700951 }
952
Colin Crossfe4bc362018-09-12 10:02:13 -0700953 return ret, err
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700954}
955
Colin Cross192e97a2018-02-22 14:21:02 -0800956// pathForSource creates a SourcePath from pathComponents, but does not check that it exists.
957func pathForSource(ctx PathContext, pathComponents ...string) (SourcePath, error) {
Colin Crossc48c1432018-02-23 07:09:01 +0000958 p, err := validatePath(pathComponents...)
Paul Duffin74abc5d2021-03-24 09:24:59 +0000959 ret := SourcePath{basePath{p, ""}, ctx.Config().srcDir}
Colin Cross94a32102018-02-22 14:21:02 -0800960 if err != nil {
Colin Cross192e97a2018-02-22 14:21:02 -0800961 return ret, err
Colin Cross94a32102018-02-22 14:21:02 -0800962 }
963
Colin Cross7b3dcc32019-01-24 13:14:39 -0800964 // absolute path already checked by validatePath
965 if strings.HasPrefix(ret.String(), ctx.Config().buildDir) {
Mikhail Naganovab1f5182019-02-08 13:17:55 -0800966 return ret, fmt.Errorf("source path %q is in output", ret.String())
Colin Crossc48c1432018-02-23 07:09:01 +0000967 }
968
Colin Cross192e97a2018-02-22 14:21:02 -0800969 return ret, nil
970}
971
972// existsWithDependencies returns true if the path exists, and adds appropriate dependencies to rerun if the
973// path does not exist.
974func existsWithDependencies(ctx PathContext, path SourcePath) (exists bool, err error) {
975 var files []string
976
977 if gctx, ok := ctx.(PathGlobContext); ok {
978 // Use glob to produce proper dependencies, even though we only want
979 // a single file.
980 files, err = gctx.GlobWithDeps(path.String(), nil)
981 } else {
Colin Cross82ea3fb2021-04-05 17:48:26 -0700982 var result pathtools.GlobResult
Colin Cross192e97a2018-02-22 14:21:02 -0800983 // We cannot add build statements in this context, so we fall back to
984 // AddNinjaFileDeps
Colin Cross82ea3fb2021-04-05 17:48:26 -0700985 result, err = ctx.Config().fs.Glob(path.String(), nil, pathtools.FollowSymlinks)
986 ctx.AddNinjaFileDeps(result.Deps...)
987 files = result.Matches
Colin Cross192e97a2018-02-22 14:21:02 -0800988 }
989
990 if err != nil {
991 return false, fmt.Errorf("glob: %s", err.Error())
992 }
993
994 return len(files) > 0, nil
995}
996
997// PathForSource joins the provided path components and validates that the result
998// neither escapes the source dir nor is in the out dir.
999// On error, it will return a usable, but invalid SourcePath, and report a ModuleError.
1000func PathForSource(ctx PathContext, pathComponents ...string) SourcePath {
1001 path, err := pathForSource(ctx, pathComponents...)
1002 if err != nil {
1003 reportPathError(ctx, err)
1004 }
1005
Colin Crosse3924e12018-08-15 20:18:53 -07001006 if pathtools.IsGlob(path.String()) {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001007 ReportPathErrorf(ctx, "path may not contain a glob: %s", path.String())
Colin Crosse3924e12018-08-15 20:18:53 -07001008 }
1009
Liz Kammera830f3a2020-11-10 10:50:34 -08001010 if modCtx, ok := ctx.(ModuleMissingDepsPathContext); ok && ctx.Config().AllowMissingDependencies() {
Colin Cross192e97a2018-02-22 14:21:02 -08001011 exists, err := existsWithDependencies(ctx, path)
1012 if err != nil {
1013 reportPathError(ctx, err)
1014 }
1015 if !exists {
1016 modCtx.AddMissingDependencies([]string{path.String()})
1017 }
Colin Cross988414c2020-01-11 01:11:46 +00001018 } else if exists, _, err := ctx.Config().fs.Exists(path.String()); err != nil {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001019 ReportPathErrorf(ctx, "%s: %s", path, err.Error())
Pedro Loureiro5d190cc2021-02-15 15:41:33 +00001020 } else if !exists && !ctx.Config().TestAllowNonExistentPaths {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001021 ReportPathErrorf(ctx, "source path %q does not exist", path)
Colin Cross192e97a2018-02-22 14:21:02 -08001022 }
1023 return path
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001024}
1025
Liz Kammer7aa52882021-02-11 09:16:14 -05001026// ExistentPathForSource returns an OptionalPath with the SourcePath, rooted from SrcDir, *not*
1027// rooted from the module's local source directory, if the path exists, or an empty OptionalPath if
1028// it doesn't exist. Dependencies are added so that the ninja file will be regenerated if the state
1029// of the path changes.
Colin Cross32f38982018-02-22 11:47:25 -08001030func ExistentPathForSource(ctx PathContext, pathComponents ...string) OptionalPath {
Colin Cross192e97a2018-02-22 14:21:02 -08001031 path, err := pathForSource(ctx, pathComponents...)
Colin Cross1ccfcc32018-02-22 13:54:26 -08001032 if err != nil {
1033 reportPathError(ctx, err)
1034 return OptionalPath{}
1035 }
Colin Crossc48c1432018-02-23 07:09:01 +00001036
Colin Crosse3924e12018-08-15 20:18:53 -07001037 if pathtools.IsGlob(path.String()) {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001038 ReportPathErrorf(ctx, "path may not contain a glob: %s", path.String())
Colin Crosse3924e12018-08-15 20:18:53 -07001039 return OptionalPath{}
1040 }
1041
Colin Cross192e97a2018-02-22 14:21:02 -08001042 exists, err := existsWithDependencies(ctx, path)
Colin Crossc48c1432018-02-23 07:09:01 +00001043 if err != nil {
1044 reportPathError(ctx, err)
1045 return OptionalPath{}
1046 }
Colin Cross192e97a2018-02-22 14:21:02 -08001047 if !exists {
Colin Crossc48c1432018-02-23 07:09:01 +00001048 return OptionalPath{}
1049 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001050 return OptionalPathForPath(path)
1051}
1052
1053func (p SourcePath) String() string {
Paul Duffin580efc82021-03-24 09:04:03 +00001054 return filepath.Join(p.srcDir, p.path)
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001055}
1056
1057// Join creates a new SourcePath with paths... joined with the current path. The
1058// provided paths... may not use '..' to escape from the current path.
1059func (p SourcePath) Join(ctx PathContext, paths ...string) SourcePath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001060 path, err := validatePath(paths...)
1061 if err != nil {
1062 reportPathError(ctx, err)
1063 }
Colin Cross0db55682017-12-05 15:36:55 -08001064 return p.withRel(path)
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001065}
1066
Colin Cross2fafa3e2019-03-05 12:39:51 -08001067// join is like Join but does less path validation.
1068func (p SourcePath) join(ctx PathContext, paths ...string) SourcePath {
1069 path, err := validateSafePath(paths...)
1070 if err != nil {
1071 reportPathError(ctx, err)
1072 }
1073 return p.withRel(path)
1074}
1075
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001076// OverlayPath returns the overlay for `path' if it exists. This assumes that the
1077// SourcePath is the path to a resource overlay directory.
Liz Kammera830f3a2020-11-10 10:50:34 -08001078func (p SourcePath) OverlayPath(ctx ModuleMissingDepsPathContext, path Path) OptionalPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001079 var relDir string
Colin Cross07e51612019-03-05 12:46:40 -08001080 if srcPath, ok := path.(SourcePath); ok {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001081 relDir = srcPath.path
1082 } else {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001083 ReportPathErrorf(ctx, "Cannot find relative path for %s(%s)", reflect.TypeOf(path).Name(), path)
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001084 return OptionalPath{}
1085 }
Paul Duffin580efc82021-03-24 09:04:03 +00001086 dir := filepath.Join(p.srcDir, p.path, relDir)
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001087 // Use Glob so that we are run again if the directory is added.
Colin Cross7f19f372016-11-01 11:10:25 -07001088 if pathtools.IsGlob(dir) {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001089 ReportPathErrorf(ctx, "Path may not contain a glob: %s", dir)
Dan Willemsen7b310ee2015-12-18 15:11:17 -08001090 }
Colin Cross461b4452018-02-23 09:22:42 -08001091 paths, err := ctx.GlobWithDeps(dir, nil)
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001092 if err != nil {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001093 ReportPathErrorf(ctx, "glob: %s", err.Error())
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001094 return OptionalPath{}
1095 }
1096 if len(paths) == 0 {
1097 return OptionalPath{}
1098 }
Paul Duffin580efc82021-03-24 09:04:03 +00001099 relPath := Rel(ctx, p.srcDir, paths[0])
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001100 return OptionalPathForPath(PathForSource(ctx, relPath))
1101}
1102
Colin Cross70dda7e2019-10-01 22:05:35 -07001103// OutputPath is a Path representing an intermediates file path rooted from the build directory
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001104type OutputPath struct {
1105 basePath
Paul Duffind65c58b2021-03-24 09:22:07 +00001106
1107 // The soong build directory, i.e. Config.BuildDir()
1108 buildDir string
1109
Colin Crossd63c9a72020-01-29 16:52:50 -08001110 fullPath string
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001111}
1112
Colin Cross702e0f82017-10-18 17:27:54 -07001113func (p OutputPath) withRel(rel string) OutputPath {
Colin Cross0db55682017-12-05 15:36:55 -08001114 p.basePath = p.basePath.withRel(rel)
Colin Crossd63c9a72020-01-29 16:52:50 -08001115 p.fullPath = filepath.Join(p.fullPath, rel)
Colin Cross702e0f82017-10-18 17:27:54 -07001116 return p
1117}
1118
Colin Cross3063b782018-08-15 11:19:12 -07001119func (p OutputPath) WithoutRel() OutputPath {
1120 p.basePath.rel = filepath.Base(p.basePath.path)
1121 return p
1122}
1123
Paul Duffind65c58b2021-03-24 09:22:07 +00001124func (p OutputPath) getBuildDir() string {
1125 return p.buildDir
Paul Duffin9b478b02019-12-10 13:41:51 +00001126}
1127
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001128func (p OutputPath) RelativeToTop() Path {
1129 return p.outputPathRelativeToTop()
1130}
1131
1132func (p OutputPath) outputPathRelativeToTop() OutputPath {
1133 p.fullPath = StringPathRelativeToTop(p.buildDir, p.fullPath)
1134 p.buildDir = OutSoongDir
1135 return p
1136}
1137
Paul Duffin0267d492021-02-02 10:05:52 +00001138func (p OutputPath) objPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleObjPath {
1139 return PathForModuleObj(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
1140}
1141
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001142var _ Path = OutputPath{}
Paul Duffin9b478b02019-12-10 13:41:51 +00001143var _ WritablePath = OutputPath{}
Paul Duffin0267d492021-02-02 10:05:52 +00001144var _ objPathProvider = OutputPath{}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001145
Chris Parsons8f232a22020-06-23 17:37:05 -04001146// toolDepPath is a Path representing a dependency of the build tool.
1147type toolDepPath struct {
1148 basePath
1149}
1150
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001151func (t toolDepPath) RelativeToTop() Path {
1152 ensureTestOnly()
1153 return t
1154}
1155
Chris Parsons8f232a22020-06-23 17:37:05 -04001156var _ Path = toolDepPath{}
1157
1158// pathForBuildToolDep returns a toolDepPath representing the given path string.
1159// There is no validation for the path, as it is "trusted": It may fail
1160// normal validation checks. For example, it may be an absolute path.
1161// Only use this function to construct paths for dependencies of the build
1162// tool invocation.
1163func pathForBuildToolDep(ctx PathContext, path string) toolDepPath {
Paul Duffin74abc5d2021-03-24 09:24:59 +00001164 return toolDepPath{basePath{path, ""}}
Chris Parsons8f232a22020-06-23 17:37:05 -04001165}
1166
Jeff Gaston734e3802017-04-10 15:47:24 -07001167// PathForOutput joins the provided paths and returns an OutputPath that is
1168// validated to not escape the build dir.
1169// On error, it will return a usable, but invalid OutputPath, and report a ModuleError.
1170func PathForOutput(ctx PathContext, pathComponents ...string) OutputPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001171 path, err := validatePath(pathComponents...)
1172 if err != nil {
1173 reportPathError(ctx, err)
1174 }
Colin Crossd63c9a72020-01-29 16:52:50 -08001175 fullPath := filepath.Join(ctx.Config().buildDir, path)
1176 path = fullPath[len(fullPath)-len(path):]
Paul Duffin74abc5d2021-03-24 09:24:59 +00001177 return OutputPath{basePath{path, ""}, ctx.Config().buildDir, fullPath}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001178}
1179
Colin Cross40e33732019-02-15 11:08:35 -08001180// PathsForOutput returns Paths rooted from buildDir
1181func PathsForOutput(ctx PathContext, paths []string) WritablePaths {
1182 ret := make(WritablePaths, len(paths))
1183 for i, path := range paths {
1184 ret[i] = PathForOutput(ctx, path)
1185 }
1186 return ret
1187}
1188
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001189func (p OutputPath) writablePath() {}
1190
1191func (p OutputPath) String() string {
Colin Crossd63c9a72020-01-29 16:52:50 -08001192 return p.fullPath
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001193}
1194
1195// Join creates a new OutputPath with paths... joined with the current path. The
1196// provided paths... may not use '..' to escape from the current path.
1197func (p OutputPath) Join(ctx PathContext, paths ...string) OutputPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001198 path, err := validatePath(paths...)
1199 if err != nil {
1200 reportPathError(ctx, err)
1201 }
Colin Cross0db55682017-12-05 15:36:55 -08001202 return p.withRel(path)
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001203}
1204
Colin Cross8854a5a2019-02-11 14:14:16 -08001205// ReplaceExtension creates a new OutputPath with the extension replaced with ext.
1206func (p OutputPath) ReplaceExtension(ctx PathContext, ext string) OutputPath {
1207 if strings.Contains(ext, "/") {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001208 ReportPathErrorf(ctx, "extension %q cannot contain /", ext)
Colin Cross8854a5a2019-02-11 14:14:16 -08001209 }
1210 ret := PathForOutput(ctx, pathtools.ReplaceExtension(p.path, ext))
Colin Cross2cdd5df2019-02-25 10:25:24 -08001211 ret.rel = pathtools.ReplaceExtension(p.rel, ext)
Colin Cross8854a5a2019-02-11 14:14:16 -08001212 return ret
1213}
1214
Colin Cross40e33732019-02-15 11:08:35 -08001215// InSameDir creates a new OutputPath from the directory of the current OutputPath joined with the elements in paths.
1216func (p OutputPath) InSameDir(ctx PathContext, paths ...string) OutputPath {
1217 path, err := validatePath(paths...)
1218 if err != nil {
1219 reportPathError(ctx, err)
1220 }
1221
1222 ret := PathForOutput(ctx, filepath.Dir(p.path), path)
Colin Cross2cdd5df2019-02-25 10:25:24 -08001223 ret.rel = filepath.Join(filepath.Dir(p.rel), path)
Colin Cross40e33732019-02-15 11:08:35 -08001224 return ret
1225}
1226
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001227// PathForIntermediates returns an OutputPath representing the top-level
1228// intermediates directory.
1229func PathForIntermediates(ctx PathContext, paths ...string) OutputPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001230 path, err := validatePath(paths...)
1231 if err != nil {
1232 reportPathError(ctx, err)
1233 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001234 return PathForOutput(ctx, ".intermediates", path)
1235}
1236
Colin Cross07e51612019-03-05 12:46:40 -08001237var _ genPathProvider = SourcePath{}
1238var _ objPathProvider = SourcePath{}
1239var _ resPathProvider = SourcePath{}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001240
Colin Cross07e51612019-03-05 12:46:40 -08001241// PathForModuleSrc returns a Path representing the paths... under the
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001242// module's local source directory.
Liz Kammera830f3a2020-11-10 10:50:34 -08001243func PathForModuleSrc(ctx ModuleMissingDepsPathContext, pathComponents ...string) Path {
Colin Cross8a497952019-03-05 22:25:09 -08001244 p, err := validatePath(pathComponents...)
1245 if err != nil {
1246 reportPathError(ctx, err)
Colin Cross192e97a2018-02-22 14:21:02 -08001247 }
Colin Cross8a497952019-03-05 22:25:09 -08001248 paths, err := expandOneSrcPath(ctx, p, nil)
1249 if err != nil {
1250 if depErr, ok := err.(missingDependencyError); ok {
1251 if ctx.Config().AllowMissingDependencies() {
1252 ctx.AddMissingDependencies(depErr.missingDeps)
1253 } else {
1254 ctx.ModuleErrorf(`%s, is the property annotated with android:"path"?`, depErr.Error())
1255 }
1256 } else {
1257 reportPathError(ctx, err)
1258 }
1259 return nil
1260 } else if len(paths) == 0 {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001261 ReportPathErrorf(ctx, "%q produced no files, expected exactly one", p)
Colin Cross8a497952019-03-05 22:25:09 -08001262 return nil
1263 } else if len(paths) > 1 {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001264 ReportPathErrorf(ctx, "%q produced %d files, expected exactly one", p, len(paths))
Colin Cross8a497952019-03-05 22:25:09 -08001265 }
1266 return paths[0]
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001267}
1268
Liz Kammera830f3a2020-11-10 10:50:34 -08001269func pathForModuleSrc(ctx EarlyModulePathContext, paths ...string) SourcePath {
Colin Cross07e51612019-03-05 12:46:40 -08001270 p, err := validatePath(paths...)
1271 if err != nil {
1272 reportPathError(ctx, err)
1273 }
1274
1275 path, err := pathForSource(ctx, ctx.ModuleDir(), p)
1276 if err != nil {
1277 reportPathError(ctx, err)
1278 }
1279
1280 path.basePath.rel = p
1281
1282 return path
1283}
1284
Colin Cross2fafa3e2019-03-05 12:39:51 -08001285// PathsWithModuleSrcSubDir takes a list of Paths and returns a new list of Paths where Rel() on each path
1286// will return the path relative to subDir in the module's source directory. If any input paths are not located
1287// inside subDir then a path error will be reported.
Liz Kammera830f3a2020-11-10 10:50:34 -08001288func PathsWithModuleSrcSubDir(ctx EarlyModulePathContext, paths Paths, subDir string) Paths {
Colin Cross2fafa3e2019-03-05 12:39:51 -08001289 paths = append(Paths(nil), paths...)
Colin Cross07e51612019-03-05 12:46:40 -08001290 subDirFullPath := pathForModuleSrc(ctx, subDir)
Colin Cross2fafa3e2019-03-05 12:39:51 -08001291 for i, path := range paths {
1292 rel := Rel(ctx, subDirFullPath.String(), path.String())
1293 paths[i] = subDirFullPath.join(ctx, rel)
1294 }
1295 return paths
1296}
1297
1298// PathWithModuleSrcSubDir takes a Path and returns a Path where Rel() will return the path relative to subDir in the
1299// 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 -08001300func PathWithModuleSrcSubDir(ctx EarlyModulePathContext, path Path, subDir string) Path {
Colin Cross07e51612019-03-05 12:46:40 -08001301 subDirFullPath := pathForModuleSrc(ctx, subDir)
Colin Cross2fafa3e2019-03-05 12:39:51 -08001302 rel := Rel(ctx, subDirFullPath.String(), path.String())
1303 return subDirFullPath.Join(ctx, rel)
1304}
1305
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001306// OptionalPathForModuleSrc returns an OptionalPath. The OptionalPath contains a
1307// valid path if p is non-nil.
Liz Kammera830f3a2020-11-10 10:50:34 -08001308func OptionalPathForModuleSrc(ctx ModuleMissingDepsPathContext, p *string) OptionalPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001309 if p == nil {
1310 return OptionalPath{}
1311 }
1312 return OptionalPathForPath(PathForModuleSrc(ctx, *p))
1313}
1314
Liz Kammera830f3a2020-11-10 10:50:34 -08001315func (p SourcePath) genPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleGenPath {
Colin Cross7fc17db2017-02-01 14:07:55 -08001316 return PathForModuleGen(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001317}
1318
Liz Kammera830f3a2020-11-10 10:50:34 -08001319func (p SourcePath) objPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleObjPath {
Colin Cross7fc17db2017-02-01 14:07:55 -08001320 return PathForModuleObj(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001321}
1322
Liz Kammera830f3a2020-11-10 10:50:34 -08001323func (p SourcePath) resPathWithName(ctx ModuleOutPathContext, name string) ModuleResPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001324 // TODO: Use full directory if the new ctx is not the current ctx?
1325 return PathForModuleRes(ctx, p.path, name)
1326}
1327
1328// ModuleOutPath is a Path representing a module's output directory.
1329type ModuleOutPath struct {
1330 OutputPath
1331}
1332
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001333func (p ModuleOutPath) RelativeToTop() Path {
1334 p.OutputPath = p.outputPathRelativeToTop()
1335 return p
1336}
1337
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001338var _ Path = ModuleOutPath{}
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001339var _ WritablePath = ModuleOutPath{}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001340
Liz Kammera830f3a2020-11-10 10:50:34 -08001341func (p ModuleOutPath) objPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleObjPath {
Pete Bentleyfcf55bf2019-08-16 20:14:32 +01001342 return PathForModuleObj(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
1343}
1344
Liz Kammera830f3a2020-11-10 10:50:34 -08001345// ModuleOutPathContext Subset of ModuleContext functions necessary for output path methods.
1346type ModuleOutPathContext interface {
1347 PathContext
1348
1349 ModuleName() string
1350 ModuleDir() string
1351 ModuleSubDir() string
1352}
1353
1354func pathForModuleOut(ctx ModuleOutPathContext) OutputPath {
Colin Cross702e0f82017-10-18 17:27:54 -07001355 return PathForOutput(ctx, ".intermediates", ctx.ModuleDir(), ctx.ModuleName(), ctx.ModuleSubDir())
1356}
1357
Logan Chien7eefdc42018-07-11 18:10:41 +08001358// PathForVndkRefAbiDump returns an OptionalPath representing the path of the
1359// reference abi dump for the given module. This is not guaranteed to be valid.
Liz Kammera830f3a2020-11-10 10:50:34 -08001360func PathForVndkRefAbiDump(ctx ModuleInstallPathContext, version, fileName string,
Hsin-Yi Chen53489642019-07-31 17:10:45 +08001361 isNdk, isLlndkOrVndk, isGzip bool) OptionalPath {
Logan Chien7eefdc42018-07-11 18:10:41 +08001362
Jayant Chowdharyac066c62018-02-20 10:53:31 -08001363 arches := ctx.DeviceConfig().Arches()
Logan Chien7eefdc42018-07-11 18:10:41 +08001364 if len(arches) == 0 {
1365 panic("device build with no primary arch")
1366 }
Jayant Chowdharyac066c62018-02-20 10:53:31 -08001367 currentArch := ctx.Arch()
1368 archNameAndVariant := currentArch.ArchType.String()
1369 if currentArch.ArchVariant != "" {
1370 archNameAndVariant += "_" + currentArch.ArchVariant
1371 }
Logan Chien5237bed2018-07-11 17:15:57 +08001372
1373 var dirName string
Hsin-Yi Chen53489642019-07-31 17:10:45 +08001374 if isNdk {
Logan Chien5237bed2018-07-11 17:15:57 +08001375 dirName = "ndk"
Hsin-Yi Chen53489642019-07-31 17:10:45 +08001376 } else if isLlndkOrVndk {
Logan Chien5237bed2018-07-11 17:15:57 +08001377 dirName = "vndk"
Logan Chien41eabe62019-04-10 13:33:58 +08001378 } else {
1379 dirName = "platform" // opt-in libs
Jayant Chowdhary3e231fd2017-02-08 13:45:53 -08001380 }
Logan Chien5237bed2018-07-11 17:15:57 +08001381
Jayant Chowdhary34ce67d2018-03-08 11:00:50 -08001382 binderBitness := ctx.DeviceConfig().BinderBitness()
Logan Chien7eefdc42018-07-11 18:10:41 +08001383
1384 var ext string
1385 if isGzip {
1386 ext = ".lsdump.gz"
1387 } else {
1388 ext = ".lsdump"
1389 }
1390
1391 return ExistentPathForSource(ctx, "prebuilts", "abi-dumps", dirName,
1392 version, binderBitness, archNameAndVariant, "source-based",
1393 fileName+ext)
Jayant Chowdhary3e231fd2017-02-08 13:45:53 -08001394}
1395
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001396// PathForModuleOut returns a Path representing the paths... under the module's
1397// output directory.
Liz Kammera830f3a2020-11-10 10:50:34 -08001398func PathForModuleOut(ctx ModuleOutPathContext, paths ...string) ModuleOutPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001399 p, err := validatePath(paths...)
1400 if err != nil {
1401 reportPathError(ctx, err)
1402 }
Colin Cross702e0f82017-10-18 17:27:54 -07001403 return ModuleOutPath{
Liz Kammera830f3a2020-11-10 10:50:34 -08001404 OutputPath: pathForModuleOut(ctx).withRel(p),
Colin Cross702e0f82017-10-18 17:27:54 -07001405 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001406}
1407
1408// ModuleGenPath is a Path representing the 'gen' directory in a module's output
1409// directory. Mainly used for generated sources.
1410type ModuleGenPath struct {
1411 ModuleOutPath
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001412}
1413
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001414func (p ModuleGenPath) RelativeToTop() Path {
1415 p.OutputPath = p.outputPathRelativeToTop()
1416 return p
1417}
1418
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001419var _ Path = ModuleGenPath{}
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001420var _ WritablePath = ModuleGenPath{}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001421var _ genPathProvider = ModuleGenPath{}
1422var _ objPathProvider = ModuleGenPath{}
1423
1424// PathForModuleGen returns a Path representing the paths... under the module's
1425// `gen' directory.
Liz Kammera830f3a2020-11-10 10:50:34 -08001426func PathForModuleGen(ctx ModuleOutPathContext, paths ...string) ModuleGenPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001427 p, err := validatePath(paths...)
1428 if err != nil {
1429 reportPathError(ctx, err)
1430 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001431 return ModuleGenPath{
Colin Cross702e0f82017-10-18 17:27:54 -07001432 ModuleOutPath: ModuleOutPath{
Liz Kammera830f3a2020-11-10 10:50:34 -08001433 OutputPath: pathForModuleOut(ctx).withRel("gen").withRel(p),
Colin Cross702e0f82017-10-18 17:27:54 -07001434 },
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001435 }
1436}
1437
Liz Kammera830f3a2020-11-10 10:50:34 -08001438func (p ModuleGenPath) genPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleGenPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001439 // TODO: make a different path for local vs remote generated files?
Dan Willemsen21ec4902016-11-02 20:43:13 -07001440 return PathForModuleGen(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001441}
1442
Liz Kammera830f3a2020-11-10 10:50:34 -08001443func (p ModuleGenPath) objPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleObjPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001444 return PathForModuleObj(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
1445}
1446
1447// ModuleObjPath is a Path representing the 'obj' directory in a module's output
1448// directory. Used for compiled objects.
1449type ModuleObjPath struct {
1450 ModuleOutPath
1451}
1452
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001453func (p ModuleObjPath) RelativeToTop() Path {
1454 p.OutputPath = p.outputPathRelativeToTop()
1455 return p
1456}
1457
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001458var _ Path = ModuleObjPath{}
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001459var _ WritablePath = ModuleObjPath{}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001460
1461// PathForModuleObj returns a Path representing the paths... under the module's
1462// 'obj' directory.
Liz Kammera830f3a2020-11-10 10:50:34 -08001463func PathForModuleObj(ctx ModuleOutPathContext, pathComponents ...string) ModuleObjPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001464 p, err := validatePath(pathComponents...)
1465 if err != nil {
1466 reportPathError(ctx, err)
1467 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001468 return ModuleObjPath{PathForModuleOut(ctx, "obj", p)}
1469}
1470
1471// ModuleResPath is a a Path representing the 'res' directory in a module's
1472// output directory.
1473type ModuleResPath struct {
1474 ModuleOutPath
1475}
1476
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001477func (p ModuleResPath) RelativeToTop() Path {
1478 p.OutputPath = p.outputPathRelativeToTop()
1479 return p
1480}
1481
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001482var _ Path = ModuleResPath{}
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001483var _ WritablePath = ModuleResPath{}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001484
1485// PathForModuleRes returns a Path representing the paths... under the module's
1486// 'res' directory.
Liz Kammera830f3a2020-11-10 10:50:34 -08001487func PathForModuleRes(ctx ModuleOutPathContext, pathComponents ...string) ModuleResPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001488 p, err := validatePath(pathComponents...)
1489 if err != nil {
1490 reportPathError(ctx, err)
1491 }
1492
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001493 return ModuleResPath{PathForModuleOut(ctx, "res", p)}
1494}
1495
Colin Cross70dda7e2019-10-01 22:05:35 -07001496// InstallPath is a Path representing a installed file path rooted from the build directory
1497type InstallPath struct {
1498 basePath
Colin Crossff6c33d2019-10-02 16:01:35 -07001499
Paul Duffind65c58b2021-03-24 09:22:07 +00001500 // The soong build directory, i.e. Config.BuildDir()
1501 buildDir string
1502
Jiyong Park957bcd92020-10-20 18:23:33 +09001503 // partitionDir is the part of the InstallPath that is automatically determined according to the context.
1504 // For example, it is host/<os>-<arch> for host modules, and target/product/<device>/<partition> for device modules.
1505 partitionDir string
1506
1507 // makePath indicates whether this path is for Soong (false) or Make (true).
1508 makePath bool
Colin Cross70dda7e2019-10-01 22:05:35 -07001509}
1510
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001511// Will panic if called from outside a test environment.
1512func ensureTestOnly() {
Martin Stjernholm32312eb2021-03-27 18:54:49 +00001513 if PrefixInList(os.Args, "-test.") {
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001514 return
1515 }
Martin Stjernholm32312eb2021-03-27 18:54:49 +00001516 panic(fmt.Errorf("Not in test. Command line:\n %s", strings.Join(os.Args, "\n ")))
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001517}
1518
1519func (p InstallPath) RelativeToTop() Path {
1520 ensureTestOnly()
1521 p.buildDir = OutSoongDir
1522 return p
1523}
1524
Paul Duffind65c58b2021-03-24 09:22:07 +00001525func (p InstallPath) getBuildDir() string {
1526 return p.buildDir
Paul Duffin9b478b02019-12-10 13:41:51 +00001527}
1528
Hans MÃ¥nssond3f2bd72020-11-27 12:37:28 +01001529func (p InstallPath) ReplaceExtension(ctx PathContext, ext string) OutputPath {
1530 panic("Not implemented")
1531}
1532
Paul Duffin9b478b02019-12-10 13:41:51 +00001533var _ Path = InstallPath{}
1534var _ WritablePath = InstallPath{}
1535
Colin Cross70dda7e2019-10-01 22:05:35 -07001536func (p InstallPath) writablePath() {}
1537
1538func (p InstallPath) String() string {
Jiyong Park957bcd92020-10-20 18:23:33 +09001539 if p.makePath {
1540 // Make path starts with out/ instead of out/soong.
Paul Duffind65c58b2021-03-24 09:22:07 +00001541 return filepath.Join(p.buildDir, "../", p.path)
Jiyong Park957bcd92020-10-20 18:23:33 +09001542 } else {
Paul Duffind65c58b2021-03-24 09:22:07 +00001543 return filepath.Join(p.buildDir, p.path)
Jiyong Park957bcd92020-10-20 18:23:33 +09001544 }
1545}
1546
1547// PartitionDir returns the path to the partition where the install path is rooted at. It is
1548// out/soong/target/product/<device>/<partition> for device modules, and out/soong/host/<os>-<arch> for host modules.
1549// The ./soong is dropped if the install path is for Make.
1550func (p InstallPath) PartitionDir() string {
1551 if p.makePath {
Paul Duffind65c58b2021-03-24 09:22:07 +00001552 return filepath.Join(p.buildDir, "../", p.partitionDir)
Jiyong Park957bcd92020-10-20 18:23:33 +09001553 } else {
Paul Duffind65c58b2021-03-24 09:22:07 +00001554 return filepath.Join(p.buildDir, p.partitionDir)
Jiyong Park957bcd92020-10-20 18:23:33 +09001555 }
Colin Cross70dda7e2019-10-01 22:05:35 -07001556}
1557
1558// Join creates a new InstallPath with paths... joined with the current path. The
1559// provided paths... may not use '..' to escape from the current path.
1560func (p InstallPath) Join(ctx PathContext, paths ...string) InstallPath {
1561 path, err := validatePath(paths...)
1562 if err != nil {
1563 reportPathError(ctx, err)
1564 }
1565 return p.withRel(path)
1566}
1567
1568func (p InstallPath) withRel(rel string) InstallPath {
1569 p.basePath = p.basePath.withRel(rel)
1570 return p
1571}
1572
Colin Crossff6c33d2019-10-02 16:01:35 -07001573// ToMakePath returns a new InstallPath that points to Make's install directory instead of Soong's,
1574// i.e. out/ instead of out/soong/.
1575func (p InstallPath) ToMakePath() InstallPath {
Jiyong Park957bcd92020-10-20 18:23:33 +09001576 p.makePath = true
Colin Crossff6c33d2019-10-02 16:01:35 -07001577 return p
Colin Cross70dda7e2019-10-01 22:05:35 -07001578}
1579
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001580// PathForModuleInstall returns a Path representing the install path for the
1581// module appended with paths...
Colin Cross70dda7e2019-10-01 22:05:35 -07001582func PathForModuleInstall(ctx ModuleInstallPathContext, pathComponents ...string) InstallPath {
Colin Cross6e359402020-02-10 15:29:54 -08001583 os := ctx.Os()
Jiyong Park87788b52020-09-01 12:37:45 +09001584 arch := ctx.Arch().ArchType
1585 forceOS, forceArch := ctx.InstallForceOS()
1586 if forceOS != nil {
Colin Cross6e359402020-02-10 15:29:54 -08001587 os = *forceOS
1588 }
Jiyong Park87788b52020-09-01 12:37:45 +09001589 if forceArch != nil {
1590 arch = *forceArch
1591 }
Colin Cross6e359402020-02-10 15:29:54 -08001592 partition := modulePartition(ctx, os)
Colin Cross609c49a2020-02-13 13:20:11 -08001593
Jiyong Park87788b52020-09-01 12:37:45 +09001594 ret := pathForInstall(ctx, os, arch, partition, ctx.Debug(), pathComponents...)
Colin Cross609c49a2020-02-13 13:20:11 -08001595
Jingwen Chencda22c92020-11-23 00:22:30 -05001596 if ctx.InstallBypassMake() && ctx.Config().KatiEnabled() {
Colin Cross609c49a2020-02-13 13:20:11 -08001597 ret = ret.ToMakePath()
1598 }
1599
1600 return ret
1601}
1602
Jiyong Park87788b52020-09-01 12:37:45 +09001603func pathForInstall(ctx PathContext, os OsType, arch ArchType, partition string, debug bool,
Colin Cross609c49a2020-02-13 13:20:11 -08001604 pathComponents ...string) InstallPath {
1605
Jiyong Park957bcd92020-10-20 18:23:33 +09001606 var partionPaths []string
Colin Cross609c49a2020-02-13 13:20:11 -08001607
Colin Cross6e359402020-02-10 15:29:54 -08001608 if os.Class == Device {
Jiyong Park957bcd92020-10-20 18:23:33 +09001609 partionPaths = []string{"target", "product", ctx.Config().DeviceName(), partition}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001610 } else {
Jiyong Park87788b52020-09-01 12:37:45 +09001611 osName := os.String()
1612 if os == Linux {
1613 // instead of linux_glibc
1614 osName = "linux"
Dan Willemsen866b5632017-09-22 12:28:24 -07001615 }
Jiyong Park87788b52020-09-01 12:37:45 +09001616 // SOONG_HOST_OUT is set to out/host/$(HOST_OS)-$(HOST_PREBUILT_ARCH)
1617 // and HOST_PREBUILT_ARCH is forcibly set to x86 even on x86_64 hosts. We don't seem
1618 // to have a plan to fix it (see the comment in build/make/core/envsetup.mk).
1619 // Let's keep using x86 for the existing cases until we have a need to support
1620 // other architectures.
1621 archName := arch.String()
1622 if os.Class == Host && (arch == X86_64 || arch == Common) {
1623 archName = "x86"
1624 }
Jiyong Park957bcd92020-10-20 18:23:33 +09001625 partionPaths = []string{"host", osName + "-" + archName, partition}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001626 }
Colin Cross609c49a2020-02-13 13:20:11 -08001627 if debug {
Jiyong Park957bcd92020-10-20 18:23:33 +09001628 partionPaths = append([]string{"debug"}, partionPaths...)
Dan Willemsen782a2d12015-12-21 14:55:28 -08001629 }
Colin Cross70dda7e2019-10-01 22:05:35 -07001630
Jiyong Park957bcd92020-10-20 18:23:33 +09001631 partionPath, err := validatePath(partionPaths...)
Colin Cross70dda7e2019-10-01 22:05:35 -07001632 if err != nil {
1633 reportPathError(ctx, err)
1634 }
Colin Crossff6c33d2019-10-02 16:01:35 -07001635
Jiyong Park957bcd92020-10-20 18:23:33 +09001636 base := InstallPath{
Paul Duffin74abc5d2021-03-24 09:24:59 +00001637 basePath: basePath{partionPath, ""},
Paul Duffind65c58b2021-03-24 09:22:07 +00001638 buildDir: ctx.Config().buildDir,
Jiyong Park957bcd92020-10-20 18:23:33 +09001639 partitionDir: partionPath,
1640 makePath: false,
1641 }
Colin Crossff6c33d2019-10-02 16:01:35 -07001642
Jiyong Park957bcd92020-10-20 18:23:33 +09001643 return base.Join(ctx, pathComponents...)
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001644}
1645
Nicolas Geoffray1228e9c2020-02-27 13:45:35 +00001646func pathForNdkOrSdkInstall(ctx PathContext, prefix string, paths []string) InstallPath {
Jiyong Park957bcd92020-10-20 18:23:33 +09001647 base := InstallPath{
Paul Duffin74abc5d2021-03-24 09:24:59 +00001648 basePath: basePath{prefix, ""},
Paul Duffind65c58b2021-03-24 09:22:07 +00001649 buildDir: ctx.Config().buildDir,
Jiyong Park957bcd92020-10-20 18:23:33 +09001650 partitionDir: prefix,
1651 makePath: false,
Colin Cross70dda7e2019-10-01 22:05:35 -07001652 }
Jiyong Park957bcd92020-10-20 18:23:33 +09001653 return base.Join(ctx, paths...)
Colin Cross70dda7e2019-10-01 22:05:35 -07001654}
1655
Nicolas Geoffray1228e9c2020-02-27 13:45:35 +00001656func PathForNdkInstall(ctx PathContext, paths ...string) InstallPath {
1657 return pathForNdkOrSdkInstall(ctx, "ndk", paths)
1658}
1659
1660func PathForMainlineSdksInstall(ctx PathContext, paths ...string) InstallPath {
1661 return pathForNdkOrSdkInstall(ctx, "mainline-sdks", paths)
1662}
1663
Colin Cross70dda7e2019-10-01 22:05:35 -07001664func InstallPathToOnDevicePath(ctx PathContext, path InstallPath) string {
Colin Cross43f08db2018-11-12 10:13:39 -08001665 rel := Rel(ctx, PathForOutput(ctx, "target", "product", ctx.Config().DeviceName()).String(), path.String())
1666
1667 return "/" + rel
1668}
1669
Colin Cross6e359402020-02-10 15:29:54 -08001670func modulePartition(ctx ModuleInstallPathContext, os OsType) string {
Colin Cross43f08db2018-11-12 10:13:39 -08001671 var partition string
Colin Cross6e359402020-02-10 15:29:54 -08001672 if ctx.InstallInTestcases() {
1673 // "testcases" install directory can be used for host or device modules.
Jaewoong Jung0949f312019-09-11 10:25:18 -07001674 partition = "testcases"
Colin Cross6e359402020-02-10 15:29:54 -08001675 } else if os.Class == Device {
1676 if ctx.InstallInData() {
1677 partition = "data"
1678 } else if ctx.InstallInRamdisk() {
1679 if ctx.DeviceConfig().BoardUsesRecoveryAsBoot() {
1680 partition = "recovery/root/first_stage_ramdisk"
1681 } else {
1682 partition = "ramdisk"
1683 }
1684 if !ctx.InstallInRoot() {
1685 partition += "/system"
1686 }
Yifan Hong60e0cfb2020-10-21 15:17:56 -07001687 } else if ctx.InstallInVendorRamdisk() {
Yifan Hong39143a92020-10-26 12:43:12 -07001688 // The module is only available after switching root into
1689 // /first_stage_ramdisk. To expose the module before switching root
1690 // on a device without a dedicated recovery partition, install the
1691 // recovery variant.
Yifan Hongdd8dacc2020-10-21 15:40:17 -07001692 if ctx.DeviceConfig().BoardMoveRecoveryResourcesToVendorBoot() {
Petri Gyntherac229562021-03-02 23:44:02 -08001693 partition = "vendor_ramdisk/first_stage_ramdisk"
Yifan Hongdd8dacc2020-10-21 15:40:17 -07001694 } else {
Petri Gyntherac229562021-03-02 23:44:02 -08001695 partition = "vendor_ramdisk"
Yifan Hongdd8dacc2020-10-21 15:40:17 -07001696 }
1697 if !ctx.InstallInRoot() {
1698 partition += "/system"
1699 }
Inseob Kim08758f02021-04-08 21:13:22 +09001700 } else if ctx.InstallInDebugRamdisk() {
1701 partition = "debug_ramdisk"
Colin Cross6e359402020-02-10 15:29:54 -08001702 } else if ctx.InstallInRecovery() {
1703 if ctx.InstallInRoot() {
1704 partition = "recovery/root"
1705 } else {
1706 // the layout of recovery partion is the same as that of system partition
1707 partition = "recovery/root/system"
1708 }
1709 } else if ctx.SocSpecific() {
1710 partition = ctx.DeviceConfig().VendorPath()
1711 } else if ctx.DeviceSpecific() {
1712 partition = ctx.DeviceConfig().OdmPath()
1713 } else if ctx.ProductSpecific() {
1714 partition = ctx.DeviceConfig().ProductPath()
1715 } else if ctx.SystemExtSpecific() {
1716 partition = ctx.DeviceConfig().SystemExtPath()
1717 } else if ctx.InstallInRoot() {
1718 partition = "root"
Yifan Hong82db7352020-01-21 16:12:26 -08001719 } else {
Colin Cross6e359402020-02-10 15:29:54 -08001720 partition = "system"
Yifan Hong82db7352020-01-21 16:12:26 -08001721 }
Colin Cross6e359402020-02-10 15:29:54 -08001722 if ctx.InstallInSanitizerDir() {
1723 partition = "data/asan/" + partition
Yifan Hong82db7352020-01-21 16:12:26 -08001724 }
Colin Cross43f08db2018-11-12 10:13:39 -08001725 }
1726 return partition
1727}
1728
Colin Cross609c49a2020-02-13 13:20:11 -08001729type InstallPaths []InstallPath
1730
1731// Paths returns the InstallPaths as a Paths
1732func (p InstallPaths) Paths() Paths {
1733 if p == nil {
1734 return nil
1735 }
1736 ret := make(Paths, len(p))
1737 for i, path := range p {
1738 ret[i] = path
1739 }
1740 return ret
1741}
1742
1743// Strings returns the string forms of the install paths.
1744func (p InstallPaths) Strings() []string {
1745 if p == nil {
1746 return nil
1747 }
1748 ret := make([]string, len(p))
1749 for i, path := range p {
1750 ret[i] = path.String()
1751 }
1752 return ret
1753}
1754
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001755// validateSafePath validates a path that we trust (may contain ninja variables).
Dan Willemsen80a7c2a2015-12-21 14:57:11 -08001756// Ensures that each path component does not attempt to leave its component.
Colin Cross1ccfcc32018-02-22 13:54:26 -08001757func validateSafePath(pathComponents ...string) (string, error) {
Jeff Gaston734e3802017-04-10 15:47:24 -07001758 for _, path := range pathComponents {
Dan Willemsen80a7c2a2015-12-21 14:57:11 -08001759 path := filepath.Clean(path)
1760 if path == ".." || strings.HasPrefix(path, "../") || strings.HasPrefix(path, "/") {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001761 return "", fmt.Errorf("Path is outside directory: %s", path)
Dan Willemsen80a7c2a2015-12-21 14:57:11 -08001762 }
1763 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001764 // TODO: filepath.Join isn't necessarily correct with embedded ninja
1765 // variables. '..' may remove the entire ninja variable, even if it
1766 // will be expanded to multiple nested directories.
Colin Cross1ccfcc32018-02-22 13:54:26 -08001767 return filepath.Join(pathComponents...), nil
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001768}
1769
Dan Willemsen80a7c2a2015-12-21 14:57:11 -08001770// validatePath validates that a path does not include ninja variables, and that
1771// each path component does not attempt to leave its component. Returns a joined
1772// version of each path component.
Colin Cross1ccfcc32018-02-22 13:54:26 -08001773func validatePath(pathComponents ...string) (string, error) {
Jeff Gaston734e3802017-04-10 15:47:24 -07001774 for _, path := range pathComponents {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001775 if strings.Contains(path, "$") {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001776 return "", fmt.Errorf("Path contains invalid character($): %s", path)
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001777 }
1778 }
Colin Cross1ccfcc32018-02-22 13:54:26 -08001779 return validateSafePath(pathComponents...)
Colin Cross6e18ca42015-07-14 18:55:36 -07001780}
Colin Cross5b529592017-05-09 13:34:34 -07001781
Colin Cross0875c522017-11-28 17:34:01 -08001782func PathForPhony(ctx PathContext, phony string) WritablePath {
1783 if strings.ContainsAny(phony, "$/") {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001784 ReportPathErrorf(ctx, "Phony target contains invalid character ($ or /): %s", phony)
Colin Cross0875c522017-11-28 17:34:01 -08001785 }
Paul Duffin74abc5d2021-03-24 09:24:59 +00001786 return PhonyPath{basePath{phony, ""}}
Colin Cross0875c522017-11-28 17:34:01 -08001787}
1788
Colin Cross74e3fe42017-12-11 15:51:44 -08001789type PhonyPath struct {
1790 basePath
1791}
1792
1793func (p PhonyPath) writablePath() {}
1794
Paul Duffind65c58b2021-03-24 09:22:07 +00001795func (p PhonyPath) getBuildDir() string {
1796 // A phone path cannot contain any / so cannot be relative to the build directory.
1797 return ""
Paul Duffin9b478b02019-12-10 13:41:51 +00001798}
1799
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001800func (p PhonyPath) RelativeToTop() Path {
1801 ensureTestOnly()
1802 // A phony path cannot contain any / so does not have a build directory so switching to a new
1803 // build directory has no effect so just return this path.
1804 return p
1805}
1806
Hans MÃ¥nssond3f2bd72020-11-27 12:37:28 +01001807func (p PhonyPath) ReplaceExtension(ctx PathContext, ext string) OutputPath {
1808 panic("Not implemented")
1809}
1810
Colin Cross74e3fe42017-12-11 15:51:44 -08001811var _ Path = PhonyPath{}
1812var _ WritablePath = PhonyPath{}
1813
Colin Cross5b529592017-05-09 13:34:34 -07001814type testPath struct {
1815 basePath
1816}
1817
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001818func (p testPath) RelativeToTop() Path {
1819 ensureTestOnly()
1820 return p
1821}
1822
Colin Cross5b529592017-05-09 13:34:34 -07001823func (p testPath) String() string {
1824 return p.path
1825}
1826
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001827var _ Path = testPath{}
1828
Colin Cross40e33732019-02-15 11:08:35 -08001829// PathForTesting returns a Path constructed from joining the elements of paths with '/'. It should only be used from
1830// within tests.
Colin Cross5b529592017-05-09 13:34:34 -07001831func PathForTesting(paths ...string) Path {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001832 p, err := validateSafePath(paths...)
1833 if err != nil {
1834 panic(err)
1835 }
Colin Cross5b529592017-05-09 13:34:34 -07001836 return testPath{basePath{path: p, rel: p}}
1837}
1838
Colin Cross40e33732019-02-15 11:08:35 -08001839// PathsForTesting returns a Path constructed from each element in strs. It should only be used from within tests.
1840func PathsForTesting(strs ...string) Paths {
Colin Cross5b529592017-05-09 13:34:34 -07001841 p := make(Paths, len(strs))
1842 for i, s := range strs {
1843 p[i] = PathForTesting(s)
1844 }
1845
1846 return p
1847}
Colin Cross43f08db2018-11-12 10:13:39 -08001848
Colin Cross40e33732019-02-15 11:08:35 -08001849type testPathContext struct {
1850 config Config
Colin Cross40e33732019-02-15 11:08:35 -08001851}
1852
Colin Cross40e33732019-02-15 11:08:35 -08001853func (x *testPathContext) Config() Config { return x.config }
1854func (x *testPathContext) AddNinjaFileDeps(...string) {}
1855
1856// PathContextForTesting returns a PathContext that can be used in tests, for example to create an OutputPath with
1857// PathForOutput.
Colin Cross98be1bb2019-12-13 20:41:13 -08001858func PathContextForTesting(config Config) PathContext {
Colin Cross40e33732019-02-15 11:08:35 -08001859 return &testPathContext{
1860 config: config,
Colin Cross40e33732019-02-15 11:08:35 -08001861 }
1862}
1863
Ulya Trafimovichccc8c852020-10-14 11:29:07 +01001864type testModuleInstallPathContext struct {
1865 baseModuleContext
1866
1867 inData bool
1868 inTestcases bool
1869 inSanitizerDir bool
1870 inRamdisk bool
1871 inVendorRamdisk bool
Inseob Kim08758f02021-04-08 21:13:22 +09001872 inDebugRamdisk bool
Ulya Trafimovichccc8c852020-10-14 11:29:07 +01001873 inRecovery bool
1874 inRoot bool
1875 forceOS *OsType
1876 forceArch *ArchType
1877}
1878
1879func (m testModuleInstallPathContext) Config() Config {
1880 return m.baseModuleContext.config
1881}
1882
1883func (testModuleInstallPathContext) AddNinjaFileDeps(deps ...string) {}
1884
1885func (m testModuleInstallPathContext) InstallInData() bool {
1886 return m.inData
1887}
1888
1889func (m testModuleInstallPathContext) InstallInTestcases() bool {
1890 return m.inTestcases
1891}
1892
1893func (m testModuleInstallPathContext) InstallInSanitizerDir() bool {
1894 return m.inSanitizerDir
1895}
1896
1897func (m testModuleInstallPathContext) InstallInRamdisk() bool {
1898 return m.inRamdisk
1899}
1900
1901func (m testModuleInstallPathContext) InstallInVendorRamdisk() bool {
1902 return m.inVendorRamdisk
1903}
1904
Inseob Kim08758f02021-04-08 21:13:22 +09001905func (m testModuleInstallPathContext) InstallInDebugRamdisk() bool {
1906 return m.inDebugRamdisk
1907}
1908
Ulya Trafimovichccc8c852020-10-14 11:29:07 +01001909func (m testModuleInstallPathContext) InstallInRecovery() bool {
1910 return m.inRecovery
1911}
1912
1913func (m testModuleInstallPathContext) InstallInRoot() bool {
1914 return m.inRoot
1915}
1916
1917func (m testModuleInstallPathContext) InstallBypassMake() bool {
1918 return false
1919}
1920
1921func (m testModuleInstallPathContext) InstallForceOS() (*OsType, *ArchType) {
1922 return m.forceOS, m.forceArch
1923}
1924
1925// Construct a minimal ModuleInstallPathContext for testing. Note that baseModuleContext is
1926// default-initialized, which leaves blueprint.baseModuleContext set to nil, so methods that are
1927// delegated to it will panic.
1928func ModuleInstallPathContextForTesting(config Config) ModuleInstallPathContext {
1929 ctx := &testModuleInstallPathContext{}
1930 ctx.config = config
1931 ctx.os = Android
1932 return ctx
1933}
1934
Colin Cross43f08db2018-11-12 10:13:39 -08001935// Rel performs the same function as filepath.Rel, but reports errors to a PathContext, and reports an error if
1936// targetPath is not inside basePath.
1937func Rel(ctx PathContext, basePath string, targetPath string) string {
1938 rel, isRel := MaybeRel(ctx, basePath, targetPath)
1939 if !isRel {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001940 ReportPathErrorf(ctx, "path %q is not under path %q", targetPath, basePath)
Colin Cross43f08db2018-11-12 10:13:39 -08001941 return ""
1942 }
1943 return rel
1944}
1945
1946// MaybeRel performs the same function as filepath.Rel, but reports errors to a PathContext, and returns false if
1947// targetPath is not inside basePath.
1948func MaybeRel(ctx PathContext, basePath string, targetPath string) (string, bool) {
Dan Willemsen633c5022019-04-12 11:11:38 -07001949 rel, isRel, err := maybeRelErr(basePath, targetPath)
1950 if err != nil {
1951 reportPathError(ctx, err)
1952 }
1953 return rel, isRel
1954}
1955
1956func maybeRelErr(basePath string, targetPath string) (string, bool, error) {
Colin Cross43f08db2018-11-12 10:13:39 -08001957 // filepath.Rel returns an error if one path is absolute and the other is not, handle that case first.
1958 if filepath.IsAbs(basePath) != filepath.IsAbs(targetPath) {
Dan Willemsen633c5022019-04-12 11:11:38 -07001959 return "", false, nil
Colin Cross43f08db2018-11-12 10:13:39 -08001960 }
1961 rel, err := filepath.Rel(basePath, targetPath)
1962 if err != nil {
Dan Willemsen633c5022019-04-12 11:11:38 -07001963 return "", false, err
Colin Cross43f08db2018-11-12 10:13:39 -08001964 } else if rel == ".." || strings.HasPrefix(rel, "../") || strings.HasPrefix(rel, "/") {
Dan Willemsen633c5022019-04-12 11:11:38 -07001965 return "", false, nil
Colin Cross43f08db2018-11-12 10:13:39 -08001966 }
Dan Willemsen633c5022019-04-12 11:11:38 -07001967 return rel, true, nil
Colin Cross43f08db2018-11-12 10:13:39 -08001968}
Colin Cross988414c2020-01-11 01:11:46 +00001969
1970// Writes a file to the output directory. Attempting to write directly to the output directory
1971// will fail due to the sandbox of the soong_build process.
1972func WriteFileToOutputDir(path WritablePath, data []byte, perm os.FileMode) error {
1973 return ioutil.WriteFile(absolutePath(path.String()), data, perm)
1974}
1975
Liz Kammer2dd9ca42020-11-25 16:06:39 -08001976func RemoveAllOutputDir(path WritablePath) error {
1977 return os.RemoveAll(absolutePath(path.String()))
1978}
1979
1980func CreateOutputDirIfNonexistent(path WritablePath, perm os.FileMode) error {
1981 dir := absolutePath(path.String())
1982 if _, err := os.Stat(dir); os.IsNotExist(err) {
1983 return os.MkdirAll(dir, os.ModePerm)
1984 } else {
1985 return err
1986 }
1987}
1988
Colin Cross988414c2020-01-11 01:11:46 +00001989func absolutePath(path string) string {
1990 if filepath.IsAbs(path) {
1991 return path
1992 }
1993 return filepath.Join(absSrcDir, path)
1994}
Chris Parsons216e10a2020-07-09 17:12:52 -04001995
1996// A DataPath represents the path of a file to be used as data, for example
1997// a test library to be installed alongside a test.
1998// The data file should be installed (copied from `<SrcPath>`) to
1999// `<install_root>/<RelativeInstallPath>/<filename>`, or
2000// `<install_root>/<filename>` if RelativeInstallPath is empty.
2001type DataPath struct {
2002 // The path of the data file that should be copied into the data directory
2003 SrcPath Path
2004 // The install path of the data file, relative to the install root.
2005 RelativeInstallPath string
2006}
Colin Crossdcf71b22021-02-01 13:59:03 -08002007
2008// PathsIfNonNil returns a Paths containing only the non-nil input arguments.
2009func PathsIfNonNil(paths ...Path) Paths {
2010 if len(paths) == 0 {
2011 // Fast path for empty argument list
2012 return nil
2013 } else if len(paths) == 1 {
2014 // Fast path for a single argument
2015 if paths[0] != nil {
2016 return paths
2017 } else {
2018 return nil
2019 }
2020 }
2021 ret := make(Paths, 0, len(paths))
2022 for _, path := range paths {
2023 if path != nil {
2024 ret = append(ret, path)
2025 }
2026 }
2027 if len(ret) == 0 {
2028 return nil
2029 }
2030 return ret
2031}