blob: 128ec12d0f96a754e6d245dad7abb0e16e81b56f [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 Duffinef081852021-05-13 11:11:15 +0100290// AsPaths converts the OptionalPath into Paths.
291//
292// It returns nil if this is not valid, or a single length slice containing the Path embedded in
293// this OptionalPath.
294func (p OptionalPath) AsPaths() Paths {
295 if !p.valid {
296 return nil
297 }
298 return Paths{p.path}
299}
300
Paul Duffinafdd4062021-03-30 19:44:07 +0100301// RelativeToTop returns an OptionalPath with the path that was embedded having been replaced by the
302// result of calling Path.RelativeToTop on it.
303func (p OptionalPath) RelativeToTop() OptionalPath {
Paul Duffina5b81352021-03-28 23:57:19 +0100304 if !p.valid {
305 return p
306 }
307 p.path = p.path.RelativeToTop()
308 return p
309}
310
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700311// String returns the string version of the Path, or "" if it isn't valid.
312func (p OptionalPath) String() string {
313 if p.valid {
314 return p.path.String()
315 } else {
316 return ""
Colin Crossf2298272015-05-12 11:36:53 -0700317 }
318}
Colin Cross6e18ca42015-07-14 18:55:36 -0700319
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700320// Paths is a slice of Path objects, with helpers to operate on the collection.
321type Paths []Path
322
Paul Duffin85d8f0d2021-03-24 10:18:18 +0000323// RelativeToTop creates a new Paths containing the result of calling Path.RelativeToTop on each
324// item in this slice.
325func (p Paths) RelativeToTop() Paths {
326 ensureTestOnly()
327 if p == nil {
328 return p
329 }
330 ret := make(Paths, len(p))
331 for i, path := range p {
332 ret[i] = path.RelativeToTop()
333 }
334 return ret
335}
336
Jingwen Chen40fd90a2020-06-15 05:24:19 +0000337func (paths Paths) containsPath(path Path) bool {
338 for _, p := range paths {
339 if p == path {
340 return true
341 }
342 }
343 return false
344}
345
Liz Kammer7aa52882021-02-11 09:16:14 -0500346// PathsForSource returns Paths rooted from SrcDir, *not* rooted from the module's local source
347// directory
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700348func PathsForSource(ctx PathContext, paths []string) Paths {
349 ret := make(Paths, len(paths))
350 for i, path := range paths {
351 ret[i] = PathForSource(ctx, path)
352 }
353 return ret
354}
355
Liz Kammer7aa52882021-02-11 09:16:14 -0500356// ExistentPathsForSources returns a list of Paths rooted from SrcDir, *not* rooted from the
357// module's local source directory, that are found in the tree. If any are not found, they are
358// 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 -0800359func ExistentPathsForSources(ctx PathContext, paths []string) Paths {
Dan Willemsen7b310ee2015-12-18 15:11:17 -0800360 ret := make(Paths, 0, len(paths))
361 for _, path := range paths {
Colin Cross32f38982018-02-22 11:47:25 -0800362 p := ExistentPathForSource(ctx, path)
Dan Willemsen7b310ee2015-12-18 15:11:17 -0800363 if p.Valid() {
364 ret = append(ret, p.Path())
365 }
366 }
367 return ret
368}
369
Liz Kammer620dea62021-04-14 17:36:10 -0400370// PathsForModuleSrc returns a Paths{} containing the resolved references in paths:
371// * filepath, relative to local module directory, resolves as a filepath relative to the local
372// source directory
373// * glob, relative to the local module directory, resolves as filepath(s), relative to the local
374// source directory.
375// * other modules using the ":name{.tag}" syntax. These modules must implement SourceFileProducer
376// or OutputFileProducer. These resolve as a filepath to an output filepath or generated source
377// filepath.
378// Properties passed as the paths argument must have been annotated with struct tag
Colin Cross41955e82019-05-29 14:40:35 -0700379// `android:"path"` so that dependencies on SourceFileProducer modules will have already been handled by the
Liz Kammer620dea62021-04-14 17:36:10 -0400380// path_deps mutator.
381// If a requested module is not found as a dependency:
382// * if ctx.Config().AllowMissingDependencies() is true, this module to be marked as having
383// missing dependencies
384// * otherwise, a ModuleError is thrown.
Liz Kammera830f3a2020-11-10 10:50:34 -0800385func PathsForModuleSrc(ctx ModuleMissingDepsPathContext, paths []string) Paths {
Colin Cross8a497952019-03-05 22:25:09 -0800386 return PathsForModuleSrcExcludes(ctx, paths, nil)
387}
388
Liz Kammer620dea62021-04-14 17:36:10 -0400389// PathsForModuleSrcExcludes returns a Paths{} containing the resolved references in paths, minus
390// those listed in excludes. Elements of paths and excludes are resolved as:
391// * filepath, relative to local module directory, resolves as a filepath relative to the local
392// source directory
393// * glob, relative to the local module directory, resolves as filepath(s), relative to the local
394// source directory. Not valid in excludes.
395// * other modules using the ":name{.tag}" syntax. These modules must implement SourceFileProducer
396// or OutputFileProducer. These resolve as a filepath to an output filepath or generated source
397// filepath.
398// excluding the items (similarly resolved
399// Properties passed as the paths argument must have been annotated with struct tag
400// `android:"path"` so that dependencies on SourceFileProducer modules will have already been handled by the
401// path_deps mutator.
402// If a requested module is not found as a dependency:
403// * if ctx.Config().AllowMissingDependencies() is true, this module to be marked as having
404// missing dependencies
405// * otherwise, a ModuleError is thrown.
Liz Kammera830f3a2020-11-10 10:50:34 -0800406func PathsForModuleSrcExcludes(ctx ModuleMissingDepsPathContext, paths, excludes []string) Paths {
Colin Crossba71a3f2019-03-18 12:12:48 -0700407 ret, missingDeps := PathsAndMissingDepsForModuleSrcExcludes(ctx, paths, excludes)
408 if ctx.Config().AllowMissingDependencies() {
409 ctx.AddMissingDependencies(missingDeps)
410 } else {
411 for _, m := range missingDeps {
412 ctx.ModuleErrorf(`missing dependency on %q, is the property annotated with android:"path"?`, m)
413 }
414 }
415 return ret
416}
417
Ulya Trafimovich4d2eeed2019-11-08 10:54:21 +0000418// OutputPaths is a slice of OutputPath objects, with helpers to operate on the collection.
419type OutputPaths []OutputPath
420
421// Paths returns the OutputPaths as a Paths
422func (p OutputPaths) Paths() Paths {
423 if p == nil {
424 return nil
425 }
426 ret := make(Paths, len(p))
427 for i, path := range p {
428 ret[i] = path
429 }
430 return ret
431}
432
433// Strings returns the string forms of the writable paths.
434func (p OutputPaths) Strings() []string {
435 if p == nil {
436 return nil
437 }
438 ret := make([]string, len(p))
439 for i, path := range p {
440 ret[i] = path.String()
441 }
442 return ret
443}
444
Liz Kammera830f3a2020-11-10 10:50:34 -0800445// Expands Paths to a SourceFileProducer or OutputFileProducer module dependency referenced via ":name" or ":name{.tag}" syntax.
446// If the dependency is not found, a missingErrorDependency is returned.
447// If the module dependency is not a SourceFileProducer or OutputFileProducer, appropriate errors will be returned.
448func getPathsFromModuleDep(ctx ModuleWithDepsPathContext, path, moduleName, tag string) (Paths, error) {
449 module := ctx.GetDirectDepWithTag(moduleName, sourceOrOutputDepTag(tag))
450 if module == nil {
451 return nil, missingDependencyError{[]string{moduleName}}
452 }
Colin Crossfa65cee2021-03-22 17:05:59 -0700453 if aModule, ok := module.(Module); ok && !aModule.Enabled() {
454 return nil, missingDependencyError{[]string{moduleName}}
455 }
Liz Kammera830f3a2020-11-10 10:50:34 -0800456 if outProducer, ok := module.(OutputFileProducer); ok {
457 outputFiles, err := outProducer.OutputFiles(tag)
458 if err != nil {
459 return nil, fmt.Errorf("path dependency %q: %s", path, err)
460 }
461 return outputFiles, nil
462 } else if tag != "" {
463 return nil, fmt.Errorf("path dependency %q is not an output file producing module", path)
Colin Cross0e446152021-05-03 13:35:32 -0700464 } else if goBinary, ok := module.(bootstrap.GoBinaryTool); ok {
465 if rel, err := filepath.Rel(PathForOutput(ctx).String(), goBinary.InstallPath()); err == nil {
466 return Paths{PathForOutput(ctx, rel).WithoutRel()}, nil
467 } else {
468 return nil, fmt.Errorf("cannot find output path for %q: %w", goBinary.InstallPath(), err)
469 }
Liz Kammera830f3a2020-11-10 10:50:34 -0800470 } else if srcProducer, ok := module.(SourceFileProducer); ok {
471 return srcProducer.Srcs(), nil
472 } else {
473 return nil, fmt.Errorf("path dependency %q is not a source file producing module", path)
474 }
475}
476
Liz Kammer620dea62021-04-14 17:36:10 -0400477// PathsAndMissingDepsForModuleSrcExcludes returns a Paths{} containing the resolved references in
478// paths, minus those listed in excludes. Elements of paths and excludes are resolved as:
479// * filepath, relative to local module directory, resolves as a filepath relative to the local
480// source directory
481// * glob, relative to the local module directory, resolves as filepath(s), relative to the local
482// source directory. Not valid in excludes.
483// * other modules using the ":name{.tag}" syntax. These modules must implement SourceFileProducer
484// or OutputFileProducer. These resolve as a filepath to an output filepath or generated source
485// filepath.
486// and a list of the module names of missing module dependencies are returned as the second return.
487// Properties passed as the paths argument must have been annotated with struct tag
Colin Cross41955e82019-05-29 14:40:35 -0700488// `android:"path"` so that dependencies on SourceFileProducer modules will have already been handled by the
Liz Kammer620dea62021-04-14 17:36:10 -0400489// path_deps mutator.
Liz Kammera830f3a2020-11-10 10:50:34 -0800490func PathsAndMissingDepsForModuleSrcExcludes(ctx ModuleWithDepsPathContext, paths, excludes []string) (Paths, []string) {
Colin Cross8a497952019-03-05 22:25:09 -0800491 prefix := pathForModuleSrc(ctx).String()
492
493 var expandedExcludes []string
494 if excludes != nil {
495 expandedExcludes = make([]string, 0, len(excludes))
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700496 }
Colin Cross8a497952019-03-05 22:25:09 -0800497
Colin Crossba71a3f2019-03-18 12:12:48 -0700498 var missingExcludeDeps []string
499
Colin Cross8a497952019-03-05 22:25:09 -0800500 for _, e := range excludes {
Colin Cross41955e82019-05-29 14:40:35 -0700501 if m, t := SrcIsModuleWithTag(e); m != "" {
Liz Kammera830f3a2020-11-10 10:50:34 -0800502 modulePaths, err := getPathsFromModuleDep(ctx, e, m, t)
503 if m, ok := err.(missingDependencyError); ok {
504 missingExcludeDeps = append(missingExcludeDeps, m.missingDeps...)
505 } else if err != nil {
506 reportPathError(ctx, err)
Colin Cross8a497952019-03-05 22:25:09 -0800507 } else {
Liz Kammera830f3a2020-11-10 10:50:34 -0800508 expandedExcludes = append(expandedExcludes, modulePaths.Strings()...)
Colin Cross8a497952019-03-05 22:25:09 -0800509 }
510 } else {
511 expandedExcludes = append(expandedExcludes, filepath.Join(prefix, e))
512 }
513 }
514
515 if paths == nil {
Colin Crossba71a3f2019-03-18 12:12:48 -0700516 return nil, missingExcludeDeps
Colin Cross8a497952019-03-05 22:25:09 -0800517 }
518
Colin Crossba71a3f2019-03-18 12:12:48 -0700519 var missingDeps []string
520
Colin Cross8a497952019-03-05 22:25:09 -0800521 expandedSrcFiles := make(Paths, 0, len(paths))
522 for _, s := range paths {
523 srcFiles, err := expandOneSrcPath(ctx, s, expandedExcludes)
524 if depErr, ok := err.(missingDependencyError); ok {
Colin Crossba71a3f2019-03-18 12:12:48 -0700525 missingDeps = append(missingDeps, depErr.missingDeps...)
Colin Cross8a497952019-03-05 22:25:09 -0800526 } else if err != nil {
527 reportPathError(ctx, err)
528 }
529 expandedSrcFiles = append(expandedSrcFiles, srcFiles...)
530 }
Colin Crossba71a3f2019-03-18 12:12:48 -0700531
532 return expandedSrcFiles, append(missingDeps, missingExcludeDeps...)
Colin Cross8a497952019-03-05 22:25:09 -0800533}
534
535type missingDependencyError struct {
536 missingDeps []string
537}
538
539func (e missingDependencyError) Error() string {
540 return "missing dependencies: " + strings.Join(e.missingDeps, ", ")
541}
542
Liz Kammera830f3a2020-11-10 10:50:34 -0800543// Expands one path string to Paths rooted from the module's local source
544// directory, excluding those listed in the expandedExcludes.
545// Expands globs, references to SourceFileProducer or OutputFileProducer modules using the ":name" and ":name{.tag}" syntax.
546func expandOneSrcPath(ctx ModuleWithDepsPathContext, sPath string, expandedExcludes []string) (Paths, error) {
Jooyung Han7607dd32020-07-05 10:23:14 +0900547 excludePaths := func(paths Paths) Paths {
548 if len(expandedExcludes) == 0 {
549 return paths
550 }
551 remainder := make(Paths, 0, len(paths))
552 for _, p := range paths {
553 if !InList(p.String(), expandedExcludes) {
554 remainder = append(remainder, p)
555 }
556 }
557 return remainder
558 }
Liz Kammera830f3a2020-11-10 10:50:34 -0800559 if m, t := SrcIsModuleWithTag(sPath); m != "" {
560 modulePaths, err := getPathsFromModuleDep(ctx, sPath, m, t)
561 if err != nil {
562 return nil, err
Colin Cross8a497952019-03-05 22:25:09 -0800563 } else {
Liz Kammera830f3a2020-11-10 10:50:34 -0800564 return excludePaths(modulePaths), nil
Colin Cross8a497952019-03-05 22:25:09 -0800565 }
Liz Kammera830f3a2020-11-10 10:50:34 -0800566 } else if pathtools.IsGlob(sPath) {
567 paths := GlobFiles(ctx, pathForModuleSrc(ctx, sPath).String(), expandedExcludes)
Colin Cross8a497952019-03-05 22:25:09 -0800568 return PathsWithModuleSrcSubDir(ctx, paths, ""), nil
569 } else {
Liz Kammera830f3a2020-11-10 10:50:34 -0800570 p := pathForModuleSrc(ctx, sPath)
Colin Cross988414c2020-01-11 01:11:46 +0000571 if exists, _, err := ctx.Config().fs.Exists(p.String()); err != nil {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +0100572 ReportPathErrorf(ctx, "%s: %s", p, err.Error())
Pedro Loureiro5d190cc2021-02-15 15:41:33 +0000573 } else if !exists && !ctx.Config().TestAllowNonExistentPaths {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +0100574 ReportPathErrorf(ctx, "module source path %q does not exist", p)
Colin Cross8a497952019-03-05 22:25:09 -0800575 }
576
Jooyung Han7607dd32020-07-05 10:23:14 +0900577 if InList(p.String(), expandedExcludes) {
Colin Cross8a497952019-03-05 22:25:09 -0800578 return nil, nil
579 }
580 return Paths{p}, nil
581 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700582}
583
584// pathsForModuleSrcFromFullPath returns Paths rooted from the module's local
585// source directory, but strip the local source directory from the beginning of
Dan Willemsen540a78c2018-02-26 21:50:08 -0800586// each string. If incDirs is false, strip paths with a trailing '/' from the list.
Colin Crossfe4bc362018-09-12 10:02:13 -0700587// It intended for use in globs that only list files that exist, so it allows '$' in
588// filenames.
Liz Kammera830f3a2020-11-10 10:50:34 -0800589func pathsForModuleSrcFromFullPath(ctx EarlyModulePathContext, paths []string, incDirs bool) Paths {
Colin Cross6510f912017-11-29 00:27:14 -0800590 prefix := filepath.Join(ctx.Config().srcDir, ctx.ModuleDir()) + "/"
Colin Cross0f37af02017-09-27 17:42:05 -0700591 if prefix == "./" {
592 prefix = ""
593 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700594 ret := make(Paths, 0, len(paths))
595 for _, p := range paths {
Dan Willemsen540a78c2018-02-26 21:50:08 -0800596 if !incDirs && strings.HasSuffix(p, "/") {
597 continue
598 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700599 path := filepath.Clean(p)
600 if !strings.HasPrefix(path, prefix) {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +0100601 ReportPathErrorf(ctx, "Path %q is not in module source directory %q", p, prefix)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700602 continue
603 }
Colin Crosse3924e12018-08-15 20:18:53 -0700604
Colin Crossfe4bc362018-09-12 10:02:13 -0700605 srcPath, err := safePathForSource(ctx, ctx.ModuleDir(), path[len(prefix):])
Colin Crosse3924e12018-08-15 20:18:53 -0700606 if err != nil {
607 reportPathError(ctx, err)
608 continue
609 }
610
Colin Cross07e51612019-03-05 12:46:40 -0800611 srcPath.basePath.rel = srcPath.path
Colin Crosse3924e12018-08-15 20:18:53 -0700612
Colin Cross07e51612019-03-05 12:46:40 -0800613 ret = append(ret, srcPath)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700614 }
615 return ret
616}
617
Liz Kammera830f3a2020-11-10 10:50:34 -0800618// PathsWithOptionalDefaultForModuleSrc returns Paths rooted from the module's local source
619// directory. If input is nil, use the default if it exists. If input is empty, returns nil.
620func PathsWithOptionalDefaultForModuleSrc(ctx ModuleMissingDepsPathContext, input []string, def string) Paths {
Colin Cross0ddae7f2019-02-07 15:30:01 -0800621 if input != nil {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700622 return PathsForModuleSrc(ctx, input)
623 }
624 // Use Glob so that if the default doesn't exist, a dependency is added so that when it
625 // is created, we're run again.
Colin Cross6510f912017-11-29 00:27:14 -0800626 path := filepath.Join(ctx.Config().srcDir, ctx.ModuleDir(), def)
Liz Kammera830f3a2020-11-10 10:50:34 -0800627 return Glob(ctx, path, nil)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700628}
629
630// Strings returns the Paths in string form
631func (p Paths) Strings() []string {
632 if p == nil {
633 return nil
634 }
635 ret := make([]string, len(p))
636 for i, path := range p {
637 ret[i] = path.String()
638 }
639 return ret
640}
641
Colin Crossc0efd1d2020-07-03 11:56:24 -0700642func CopyOfPaths(paths Paths) Paths {
643 return append(Paths(nil), paths...)
644}
645
Colin Crossb6715442017-10-24 11:13:31 -0700646// FirstUniquePaths returns all unique elements of a Paths, keeping the first copy of each. It
647// modifies the Paths slice contents in place, and returns a subslice of the original slice.
Dan Willemsenfe92c962017-08-29 12:28:37 -0700648func FirstUniquePaths(list Paths) Paths {
Colin Cross27027c72020-02-28 15:34:17 -0800649 // 128 was chosen based on BenchmarkFirstUniquePaths results.
650 if len(list) > 128 {
651 return firstUniquePathsMap(list)
652 }
653 return firstUniquePathsList(list)
654}
655
Colin Crossc0efd1d2020-07-03 11:56:24 -0700656// SortedUniquePaths returns all unique elements of a Paths in sorted order. It modifies the
657// Paths slice contents in place, and returns a subslice of the original slice.
Jiyong Park33c77362020-05-29 22:00:16 +0900658func SortedUniquePaths(list Paths) Paths {
659 unique := FirstUniquePaths(list)
660 sort.Slice(unique, func(i, j int) bool {
661 return unique[i].String() < unique[j].String()
662 })
663 return unique
664}
665
Colin Cross27027c72020-02-28 15:34:17 -0800666func firstUniquePathsList(list Paths) Paths {
Dan Willemsenfe92c962017-08-29 12:28:37 -0700667 k := 0
668outer:
669 for i := 0; i < len(list); i++ {
670 for j := 0; j < k; j++ {
671 if list[i] == list[j] {
672 continue outer
673 }
674 }
675 list[k] = list[i]
676 k++
677 }
678 return list[:k]
679}
680
Colin Cross27027c72020-02-28 15:34:17 -0800681func firstUniquePathsMap(list Paths) Paths {
682 k := 0
683 seen := make(map[Path]bool, len(list))
684 for i := 0; i < len(list); i++ {
685 if seen[list[i]] {
686 continue
687 }
688 seen[list[i]] = true
689 list[k] = list[i]
690 k++
691 }
692 return list[:k]
693}
694
Colin Cross5d583952020-11-24 16:21:24 -0800695// FirstUniqueInstallPaths returns all unique elements of an InstallPaths, keeping the first copy of each. It
696// modifies the InstallPaths slice contents in place, and returns a subslice of the original slice.
697func FirstUniqueInstallPaths(list InstallPaths) InstallPaths {
698 // 128 was chosen based on BenchmarkFirstUniquePaths results.
699 if len(list) > 128 {
700 return firstUniqueInstallPathsMap(list)
701 }
702 return firstUniqueInstallPathsList(list)
703}
704
705func firstUniqueInstallPathsList(list InstallPaths) InstallPaths {
706 k := 0
707outer:
708 for i := 0; i < len(list); i++ {
709 for j := 0; j < k; j++ {
710 if list[i] == list[j] {
711 continue outer
712 }
713 }
714 list[k] = list[i]
715 k++
716 }
717 return list[:k]
718}
719
720func firstUniqueInstallPathsMap(list InstallPaths) InstallPaths {
721 k := 0
722 seen := make(map[InstallPath]bool, len(list))
723 for i := 0; i < len(list); i++ {
724 if seen[list[i]] {
725 continue
726 }
727 seen[list[i]] = true
728 list[k] = list[i]
729 k++
730 }
731 return list[:k]
732}
733
Colin Crossb6715442017-10-24 11:13:31 -0700734// LastUniquePaths returns all unique elements of a Paths, keeping the last copy of each. It
735// modifies the Paths slice contents in place, and returns a subslice of the original slice.
736func LastUniquePaths(list Paths) Paths {
737 totalSkip := 0
738 for i := len(list) - 1; i >= totalSkip; i-- {
739 skip := 0
740 for j := i - 1; j >= totalSkip; j-- {
741 if list[i] == list[j] {
742 skip++
743 } else {
744 list[j+skip] = list[j]
745 }
746 }
747 totalSkip += skip
748 }
749 return list[totalSkip:]
750}
751
Colin Crossa140bb02018-04-17 10:52:26 -0700752// ReversePaths returns a copy of a Paths in reverse order.
753func ReversePaths(list Paths) Paths {
754 if list == nil {
755 return nil
756 }
757 ret := make(Paths, len(list))
758 for i := range list {
759 ret[i] = list[len(list)-1-i]
760 }
761 return ret
762}
763
Jeff Gaston294356f2017-09-27 17:05:30 -0700764func indexPathList(s Path, list []Path) int {
765 for i, l := range list {
766 if l == s {
767 return i
768 }
769 }
770
771 return -1
772}
773
774func inPathList(p Path, list []Path) bool {
775 return indexPathList(p, list) != -1
776}
777
778func FilterPathList(list []Path, filter []Path) (remainder []Path, filtered []Path) {
Paul Duffin57b9e1d2019-12-13 00:03:35 +0000779 return FilterPathListPredicate(list, func(p Path) bool { return inPathList(p, filter) })
780}
781
782func FilterPathListPredicate(list []Path, predicate func(Path) bool) (remainder []Path, filtered []Path) {
Jeff Gaston294356f2017-09-27 17:05:30 -0700783 for _, l := range list {
Paul Duffin57b9e1d2019-12-13 00:03:35 +0000784 if predicate(l) {
Jeff Gaston294356f2017-09-27 17:05:30 -0700785 filtered = append(filtered, l)
786 } else {
787 remainder = append(remainder, l)
788 }
789 }
790
791 return
792}
793
Colin Cross93e85952017-08-15 13:34:18 -0700794// HasExt returns true of any of the paths have extension ext, otherwise false
795func (p Paths) HasExt(ext string) bool {
796 for _, path := range p {
797 if path.Ext() == ext {
798 return true
799 }
800 }
801
802 return false
803}
804
805// FilterByExt returns the subset of the paths that have extension ext
806func (p Paths) FilterByExt(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
816// FilterOutByExt returns the subset of the paths that do not have extension ext
817func (p Paths) FilterOutByExt(ext string) Paths {
818 ret := make(Paths, 0, len(p))
819 for _, path := range p {
820 if path.Ext() != ext {
821 ret = append(ret, path)
822 }
823 }
824 return ret
825}
826
Colin Cross5e6cfbe2017-11-03 15:20:35 -0700827// DirectorySortedPaths is a slice of paths that are sorted such that all files in a directory
828// (including subdirectories) are in a contiguous subslice of the list, and can be found in
829// O(log(N)) time using a binary search on the directory prefix.
830type DirectorySortedPaths Paths
831
832func PathsToDirectorySortedPaths(paths Paths) DirectorySortedPaths {
833 ret := append(DirectorySortedPaths(nil), paths...)
834 sort.Slice(ret, func(i, j int) bool {
835 return ret[i].String() < ret[j].String()
836 })
837 return ret
838}
839
840// PathsInDirectory returns a subslice of the DirectorySortedPaths as a Paths that contains all entries
841// that are in the specified directory and its subdirectories.
842func (p DirectorySortedPaths) PathsInDirectory(dir string) Paths {
843 prefix := filepath.Clean(dir) + "/"
844 start := sort.Search(len(p), func(i int) bool {
845 return prefix < p[i].String()
846 })
847
848 ret := p[start:]
849
850 end := sort.Search(len(ret), func(i int) bool {
851 return !strings.HasPrefix(ret[i].String(), prefix)
852 })
853
854 ret = ret[:end]
855
856 return Paths(ret)
857}
858
Alex Humesky29e3bbe2020-11-20 21:30:13 -0500859// WritablePaths is a slice of WritablePath, used for multiple outputs.
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700860type WritablePaths []WritablePath
861
Paul Duffin85d8f0d2021-03-24 10:18:18 +0000862// RelativeToTop creates a new WritablePaths containing the result of calling Path.RelativeToTop on
863// each item in this slice.
864func (p WritablePaths) RelativeToTop() WritablePaths {
865 ensureTestOnly()
866 if p == nil {
867 return p
868 }
869 ret := make(WritablePaths, len(p))
870 for i, path := range p {
871 ret[i] = path.RelativeToTop().(WritablePath)
872 }
873 return ret
874}
875
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700876// Strings returns the string forms of the writable paths.
877func (p WritablePaths) Strings() []string {
878 if p == nil {
879 return nil
880 }
881 ret := make([]string, len(p))
882 for i, path := range p {
883 ret[i] = path.String()
884 }
885 return ret
886}
887
Colin Cross3bc7ffa2017-11-22 16:19:37 -0800888// Paths returns the WritablePaths as a Paths
889func (p WritablePaths) Paths() Paths {
890 if p == nil {
891 return nil
892 }
893 ret := make(Paths, len(p))
894 for i, path := range p {
895 ret[i] = path
896 }
897 return ret
898}
899
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700900type basePath struct {
Paul Duffin74abc5d2021-03-24 09:24:59 +0000901 path string
902 rel string
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700903}
904
905func (p basePath) Ext() string {
906 return filepath.Ext(p.path)
907}
908
Colin Cross4f6fc9c2016-10-26 10:05:25 -0700909func (p basePath) Base() string {
910 return filepath.Base(p.path)
911}
912
Colin Crossfaeb7aa2017-02-01 14:12:44 -0800913func (p basePath) Rel() string {
914 if p.rel != "" {
915 return p.rel
916 }
917 return p.path
918}
919
Colin Cross0875c522017-11-28 17:34:01 -0800920func (p basePath) String() string {
921 return p.path
922}
923
Colin Cross0db55682017-12-05 15:36:55 -0800924func (p basePath) withRel(rel string) basePath {
925 p.path = filepath.Join(p.path, rel)
926 p.rel = rel
927 return p
928}
929
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700930// SourcePath is a Path representing a file path rooted from SrcDir
931type SourcePath struct {
932 basePath
Paul Duffin580efc82021-03-24 09:04:03 +0000933
934 // The sources root, i.e. Config.SrcDir()
935 srcDir string
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700936}
937
Paul Duffin85d8f0d2021-03-24 10:18:18 +0000938func (p SourcePath) RelativeToTop() Path {
939 ensureTestOnly()
940 return p
941}
942
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700943var _ Path = SourcePath{}
944
Colin Cross0db55682017-12-05 15:36:55 -0800945func (p SourcePath) withRel(rel string) SourcePath {
946 p.basePath = p.basePath.withRel(rel)
947 return p
948}
949
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700950// safePathForSource is for paths that we expect are safe -- only for use by go
951// code that is embedding ninja variables in paths
Colin Crossfe4bc362018-09-12 10:02:13 -0700952func safePathForSource(ctx PathContext, pathComponents ...string) (SourcePath, error) {
953 p, err := validateSafePath(pathComponents...)
Paul Duffin74abc5d2021-03-24 09:24:59 +0000954 ret := SourcePath{basePath{p, ""}, ctx.Config().srcDir}
Colin Crossfe4bc362018-09-12 10:02:13 -0700955 if err != nil {
956 return ret, err
957 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700958
Colin Cross7b3dcc32019-01-24 13:14:39 -0800959 // absolute path already checked by validateSafePath
960 if strings.HasPrefix(ret.String(), ctx.Config().buildDir) {
Mikhail Naganovab1f5182019-02-08 13:17:55 -0800961 return ret, fmt.Errorf("source path %q is in output", ret.String())
Colin Cross6e18ca42015-07-14 18:55:36 -0700962 }
963
Colin Crossfe4bc362018-09-12 10:02:13 -0700964 return ret, err
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700965}
966
Colin Cross192e97a2018-02-22 14:21:02 -0800967// pathForSource creates a SourcePath from pathComponents, but does not check that it exists.
968func pathForSource(ctx PathContext, pathComponents ...string) (SourcePath, error) {
Colin Crossc48c1432018-02-23 07:09:01 +0000969 p, err := validatePath(pathComponents...)
Paul Duffin74abc5d2021-03-24 09:24:59 +0000970 ret := SourcePath{basePath{p, ""}, ctx.Config().srcDir}
Colin Cross94a32102018-02-22 14:21:02 -0800971 if err != nil {
Colin Cross192e97a2018-02-22 14:21:02 -0800972 return ret, err
Colin Cross94a32102018-02-22 14:21:02 -0800973 }
974
Colin Cross7b3dcc32019-01-24 13:14:39 -0800975 // absolute path already checked by validatePath
976 if strings.HasPrefix(ret.String(), ctx.Config().buildDir) {
Mikhail Naganovab1f5182019-02-08 13:17:55 -0800977 return ret, fmt.Errorf("source path %q is in output", ret.String())
Colin Crossc48c1432018-02-23 07:09:01 +0000978 }
979
Colin Cross192e97a2018-02-22 14:21:02 -0800980 return ret, nil
981}
982
983// existsWithDependencies returns true if the path exists, and adds appropriate dependencies to rerun if the
984// path does not exist.
985func existsWithDependencies(ctx PathContext, path SourcePath) (exists bool, err error) {
986 var files []string
987
988 if gctx, ok := ctx.(PathGlobContext); ok {
989 // Use glob to produce proper dependencies, even though we only want
990 // a single file.
991 files, err = gctx.GlobWithDeps(path.String(), nil)
992 } else {
Colin Cross82ea3fb2021-04-05 17:48:26 -0700993 var result pathtools.GlobResult
Colin Cross192e97a2018-02-22 14:21:02 -0800994 // We cannot add build statements in this context, so we fall back to
995 // AddNinjaFileDeps
Colin Cross82ea3fb2021-04-05 17:48:26 -0700996 result, err = ctx.Config().fs.Glob(path.String(), nil, pathtools.FollowSymlinks)
997 ctx.AddNinjaFileDeps(result.Deps...)
998 files = result.Matches
Colin Cross192e97a2018-02-22 14:21:02 -0800999 }
1000
1001 if err != nil {
1002 return false, fmt.Errorf("glob: %s", err.Error())
1003 }
1004
1005 return len(files) > 0, nil
1006}
1007
1008// PathForSource joins the provided path components and validates that the result
1009// neither escapes the source dir nor is in the out dir.
1010// On error, it will return a usable, but invalid SourcePath, and report a ModuleError.
1011func PathForSource(ctx PathContext, pathComponents ...string) SourcePath {
1012 path, err := pathForSource(ctx, pathComponents...)
1013 if err != nil {
1014 reportPathError(ctx, err)
1015 }
1016
Colin Crosse3924e12018-08-15 20:18:53 -07001017 if pathtools.IsGlob(path.String()) {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001018 ReportPathErrorf(ctx, "path may not contain a glob: %s", path.String())
Colin Crosse3924e12018-08-15 20:18:53 -07001019 }
1020
Liz Kammera830f3a2020-11-10 10:50:34 -08001021 if modCtx, ok := ctx.(ModuleMissingDepsPathContext); ok && ctx.Config().AllowMissingDependencies() {
Colin Cross192e97a2018-02-22 14:21:02 -08001022 exists, err := existsWithDependencies(ctx, path)
1023 if err != nil {
1024 reportPathError(ctx, err)
1025 }
1026 if !exists {
1027 modCtx.AddMissingDependencies([]string{path.String()})
1028 }
Colin Cross988414c2020-01-11 01:11:46 +00001029 } else if exists, _, err := ctx.Config().fs.Exists(path.String()); err != nil {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001030 ReportPathErrorf(ctx, "%s: %s", path, err.Error())
Pedro Loureiro5d190cc2021-02-15 15:41:33 +00001031 } else if !exists && !ctx.Config().TestAllowNonExistentPaths {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001032 ReportPathErrorf(ctx, "source path %q does not exist", path)
Colin Cross192e97a2018-02-22 14:21:02 -08001033 }
1034 return path
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001035}
1036
Liz Kammer7aa52882021-02-11 09:16:14 -05001037// ExistentPathForSource returns an OptionalPath with the SourcePath, rooted from SrcDir, *not*
1038// rooted from the module's local source directory, if the path exists, or an empty OptionalPath if
1039// it doesn't exist. Dependencies are added so that the ninja file will be regenerated if the state
1040// of the path changes.
Colin Cross32f38982018-02-22 11:47:25 -08001041func ExistentPathForSource(ctx PathContext, pathComponents ...string) OptionalPath {
Colin Cross192e97a2018-02-22 14:21:02 -08001042 path, err := pathForSource(ctx, pathComponents...)
Colin Cross1ccfcc32018-02-22 13:54:26 -08001043 if err != nil {
1044 reportPathError(ctx, err)
1045 return OptionalPath{}
1046 }
Colin Crossc48c1432018-02-23 07:09:01 +00001047
Colin Crosse3924e12018-08-15 20:18:53 -07001048 if pathtools.IsGlob(path.String()) {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001049 ReportPathErrorf(ctx, "path may not contain a glob: %s", path.String())
Colin Crosse3924e12018-08-15 20:18:53 -07001050 return OptionalPath{}
1051 }
1052
Colin Cross192e97a2018-02-22 14:21:02 -08001053 exists, err := existsWithDependencies(ctx, path)
Colin Crossc48c1432018-02-23 07:09:01 +00001054 if err != nil {
1055 reportPathError(ctx, err)
1056 return OptionalPath{}
1057 }
Colin Cross192e97a2018-02-22 14:21:02 -08001058 if !exists {
Colin Crossc48c1432018-02-23 07:09:01 +00001059 return OptionalPath{}
1060 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001061 return OptionalPathForPath(path)
1062}
1063
1064func (p SourcePath) String() string {
Paul Duffin580efc82021-03-24 09:04:03 +00001065 return filepath.Join(p.srcDir, p.path)
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001066}
1067
1068// Join creates a new SourcePath with paths... joined with the current path. The
1069// provided paths... may not use '..' to escape from the current path.
1070func (p SourcePath) Join(ctx PathContext, paths ...string) SourcePath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001071 path, err := validatePath(paths...)
1072 if err != nil {
1073 reportPathError(ctx, err)
1074 }
Colin Cross0db55682017-12-05 15:36:55 -08001075 return p.withRel(path)
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001076}
1077
Colin Cross2fafa3e2019-03-05 12:39:51 -08001078// join is like Join but does less path validation.
1079func (p SourcePath) join(ctx PathContext, paths ...string) SourcePath {
1080 path, err := validateSafePath(paths...)
1081 if err != nil {
1082 reportPathError(ctx, err)
1083 }
1084 return p.withRel(path)
1085}
1086
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001087// OverlayPath returns the overlay for `path' if it exists. This assumes that the
1088// SourcePath is the path to a resource overlay directory.
Liz Kammera830f3a2020-11-10 10:50:34 -08001089func (p SourcePath) OverlayPath(ctx ModuleMissingDepsPathContext, path Path) OptionalPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001090 var relDir string
Colin Cross07e51612019-03-05 12:46:40 -08001091 if srcPath, ok := path.(SourcePath); ok {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001092 relDir = srcPath.path
1093 } else {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001094 ReportPathErrorf(ctx, "Cannot find relative path for %s(%s)", reflect.TypeOf(path).Name(), path)
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001095 return OptionalPath{}
1096 }
Paul Duffin580efc82021-03-24 09:04:03 +00001097 dir := filepath.Join(p.srcDir, p.path, relDir)
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001098 // Use Glob so that we are run again if the directory is added.
Colin Cross7f19f372016-11-01 11:10:25 -07001099 if pathtools.IsGlob(dir) {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001100 ReportPathErrorf(ctx, "Path may not contain a glob: %s", dir)
Dan Willemsen7b310ee2015-12-18 15:11:17 -08001101 }
Colin Cross461b4452018-02-23 09:22:42 -08001102 paths, err := ctx.GlobWithDeps(dir, nil)
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001103 if err != nil {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001104 ReportPathErrorf(ctx, "glob: %s", err.Error())
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001105 return OptionalPath{}
1106 }
1107 if len(paths) == 0 {
1108 return OptionalPath{}
1109 }
Paul Duffin580efc82021-03-24 09:04:03 +00001110 relPath := Rel(ctx, p.srcDir, paths[0])
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001111 return OptionalPathForPath(PathForSource(ctx, relPath))
1112}
1113
Colin Cross70dda7e2019-10-01 22:05:35 -07001114// OutputPath is a Path representing an intermediates file path rooted from the build directory
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001115type OutputPath struct {
1116 basePath
Paul Duffind65c58b2021-03-24 09:22:07 +00001117
1118 // The soong build directory, i.e. Config.BuildDir()
1119 buildDir string
1120
Colin Crossd63c9a72020-01-29 16:52:50 -08001121 fullPath string
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001122}
1123
Colin Cross702e0f82017-10-18 17:27:54 -07001124func (p OutputPath) withRel(rel string) OutputPath {
Colin Cross0db55682017-12-05 15:36:55 -08001125 p.basePath = p.basePath.withRel(rel)
Colin Crossd63c9a72020-01-29 16:52:50 -08001126 p.fullPath = filepath.Join(p.fullPath, rel)
Colin Cross702e0f82017-10-18 17:27:54 -07001127 return p
1128}
1129
Colin Cross3063b782018-08-15 11:19:12 -07001130func (p OutputPath) WithoutRel() OutputPath {
1131 p.basePath.rel = filepath.Base(p.basePath.path)
1132 return p
1133}
1134
Paul Duffind65c58b2021-03-24 09:22:07 +00001135func (p OutputPath) getBuildDir() string {
1136 return p.buildDir
Paul Duffin9b478b02019-12-10 13:41:51 +00001137}
1138
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001139func (p OutputPath) RelativeToTop() Path {
1140 return p.outputPathRelativeToTop()
1141}
1142
1143func (p OutputPath) outputPathRelativeToTop() OutputPath {
1144 p.fullPath = StringPathRelativeToTop(p.buildDir, p.fullPath)
1145 p.buildDir = OutSoongDir
1146 return p
1147}
1148
Paul Duffin0267d492021-02-02 10:05:52 +00001149func (p OutputPath) objPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleObjPath {
1150 return PathForModuleObj(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
1151}
1152
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001153var _ Path = OutputPath{}
Paul Duffin9b478b02019-12-10 13:41:51 +00001154var _ WritablePath = OutputPath{}
Paul Duffin0267d492021-02-02 10:05:52 +00001155var _ objPathProvider = OutputPath{}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001156
Chris Parsons8f232a22020-06-23 17:37:05 -04001157// toolDepPath is a Path representing a dependency of the build tool.
1158type toolDepPath struct {
1159 basePath
1160}
1161
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001162func (t toolDepPath) RelativeToTop() Path {
1163 ensureTestOnly()
1164 return t
1165}
1166
Chris Parsons8f232a22020-06-23 17:37:05 -04001167var _ Path = toolDepPath{}
1168
1169// pathForBuildToolDep returns a toolDepPath representing the given path string.
1170// There is no validation for the path, as it is "trusted": It may fail
1171// normal validation checks. For example, it may be an absolute path.
1172// Only use this function to construct paths for dependencies of the build
1173// tool invocation.
1174func pathForBuildToolDep(ctx PathContext, path string) toolDepPath {
Paul Duffin74abc5d2021-03-24 09:24:59 +00001175 return toolDepPath{basePath{path, ""}}
Chris Parsons8f232a22020-06-23 17:37:05 -04001176}
1177
Jeff Gaston734e3802017-04-10 15:47:24 -07001178// PathForOutput joins the provided paths and returns an OutputPath that is
1179// validated to not escape the build dir.
1180// On error, it will return a usable, but invalid OutputPath, and report a ModuleError.
1181func PathForOutput(ctx PathContext, pathComponents ...string) OutputPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001182 path, err := validatePath(pathComponents...)
1183 if err != nil {
1184 reportPathError(ctx, err)
1185 }
Colin Crossd63c9a72020-01-29 16:52:50 -08001186 fullPath := filepath.Join(ctx.Config().buildDir, path)
1187 path = fullPath[len(fullPath)-len(path):]
Paul Duffin74abc5d2021-03-24 09:24:59 +00001188 return OutputPath{basePath{path, ""}, ctx.Config().buildDir, fullPath}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001189}
1190
Colin Cross40e33732019-02-15 11:08:35 -08001191// PathsForOutput returns Paths rooted from buildDir
1192func PathsForOutput(ctx PathContext, paths []string) WritablePaths {
1193 ret := make(WritablePaths, len(paths))
1194 for i, path := range paths {
1195 ret[i] = PathForOutput(ctx, path)
1196 }
1197 return ret
1198}
1199
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001200func (p OutputPath) writablePath() {}
1201
1202func (p OutputPath) String() string {
Colin Crossd63c9a72020-01-29 16:52:50 -08001203 return p.fullPath
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001204}
1205
1206// Join creates a new OutputPath with paths... joined with the current path. The
1207// provided paths... may not use '..' to escape from the current path.
1208func (p OutputPath) Join(ctx PathContext, paths ...string) OutputPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001209 path, err := validatePath(paths...)
1210 if err != nil {
1211 reportPathError(ctx, err)
1212 }
Colin Cross0db55682017-12-05 15:36:55 -08001213 return p.withRel(path)
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001214}
1215
Colin Cross8854a5a2019-02-11 14:14:16 -08001216// ReplaceExtension creates a new OutputPath with the extension replaced with ext.
1217func (p OutputPath) ReplaceExtension(ctx PathContext, ext string) OutputPath {
1218 if strings.Contains(ext, "/") {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001219 ReportPathErrorf(ctx, "extension %q cannot contain /", ext)
Colin Cross8854a5a2019-02-11 14:14:16 -08001220 }
1221 ret := PathForOutput(ctx, pathtools.ReplaceExtension(p.path, ext))
Colin Cross2cdd5df2019-02-25 10:25:24 -08001222 ret.rel = pathtools.ReplaceExtension(p.rel, ext)
Colin Cross8854a5a2019-02-11 14:14:16 -08001223 return ret
1224}
1225
Colin Cross40e33732019-02-15 11:08:35 -08001226// InSameDir creates a new OutputPath from the directory of the current OutputPath joined with the elements in paths.
1227func (p OutputPath) InSameDir(ctx PathContext, paths ...string) OutputPath {
1228 path, err := validatePath(paths...)
1229 if err != nil {
1230 reportPathError(ctx, err)
1231 }
1232
1233 ret := PathForOutput(ctx, filepath.Dir(p.path), path)
Colin Cross2cdd5df2019-02-25 10:25:24 -08001234 ret.rel = filepath.Join(filepath.Dir(p.rel), path)
Colin Cross40e33732019-02-15 11:08:35 -08001235 return ret
1236}
1237
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001238// PathForIntermediates returns an OutputPath representing the top-level
1239// intermediates directory.
1240func PathForIntermediates(ctx PathContext, paths ...string) OutputPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001241 path, err := validatePath(paths...)
1242 if err != nil {
1243 reportPathError(ctx, err)
1244 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001245 return PathForOutput(ctx, ".intermediates", path)
1246}
1247
Colin Cross07e51612019-03-05 12:46:40 -08001248var _ genPathProvider = SourcePath{}
1249var _ objPathProvider = SourcePath{}
1250var _ resPathProvider = SourcePath{}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001251
Colin Cross07e51612019-03-05 12:46:40 -08001252// PathForModuleSrc returns a Path representing the paths... under the
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001253// module's local source directory.
Liz Kammera830f3a2020-11-10 10:50:34 -08001254func PathForModuleSrc(ctx ModuleMissingDepsPathContext, pathComponents ...string) Path {
Colin Cross8a497952019-03-05 22:25:09 -08001255 p, err := validatePath(pathComponents...)
1256 if err != nil {
1257 reportPathError(ctx, err)
Colin Cross192e97a2018-02-22 14:21:02 -08001258 }
Colin Cross8a497952019-03-05 22:25:09 -08001259 paths, err := expandOneSrcPath(ctx, p, nil)
1260 if err != nil {
1261 if depErr, ok := err.(missingDependencyError); ok {
1262 if ctx.Config().AllowMissingDependencies() {
1263 ctx.AddMissingDependencies(depErr.missingDeps)
1264 } else {
1265 ctx.ModuleErrorf(`%s, is the property annotated with android:"path"?`, depErr.Error())
1266 }
1267 } else {
1268 reportPathError(ctx, err)
1269 }
1270 return nil
1271 } else if len(paths) == 0 {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001272 ReportPathErrorf(ctx, "%q produced no files, expected exactly one", p)
Colin Cross8a497952019-03-05 22:25:09 -08001273 return nil
1274 } else if len(paths) > 1 {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001275 ReportPathErrorf(ctx, "%q produced %d files, expected exactly one", p, len(paths))
Colin Cross8a497952019-03-05 22:25:09 -08001276 }
1277 return paths[0]
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001278}
1279
Liz Kammera830f3a2020-11-10 10:50:34 -08001280func pathForModuleSrc(ctx EarlyModulePathContext, paths ...string) SourcePath {
Colin Cross07e51612019-03-05 12:46:40 -08001281 p, err := validatePath(paths...)
1282 if err != nil {
1283 reportPathError(ctx, err)
1284 }
1285
1286 path, err := pathForSource(ctx, ctx.ModuleDir(), p)
1287 if err != nil {
1288 reportPathError(ctx, err)
1289 }
1290
1291 path.basePath.rel = p
1292
1293 return path
1294}
1295
Colin Cross2fafa3e2019-03-05 12:39:51 -08001296// PathsWithModuleSrcSubDir takes a list of Paths and returns a new list of Paths where Rel() on each path
1297// will return the path relative to subDir in the module's source directory. If any input paths are not located
1298// inside subDir then a path error will be reported.
Liz Kammera830f3a2020-11-10 10:50:34 -08001299func PathsWithModuleSrcSubDir(ctx EarlyModulePathContext, paths Paths, subDir string) Paths {
Colin Cross2fafa3e2019-03-05 12:39:51 -08001300 paths = append(Paths(nil), paths...)
Colin Cross07e51612019-03-05 12:46:40 -08001301 subDirFullPath := pathForModuleSrc(ctx, subDir)
Colin Cross2fafa3e2019-03-05 12:39:51 -08001302 for i, path := range paths {
1303 rel := Rel(ctx, subDirFullPath.String(), path.String())
1304 paths[i] = subDirFullPath.join(ctx, rel)
1305 }
1306 return paths
1307}
1308
1309// PathWithModuleSrcSubDir takes a Path and returns a Path where Rel() will return the path relative to subDir in the
1310// 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 -08001311func PathWithModuleSrcSubDir(ctx EarlyModulePathContext, path Path, subDir string) Path {
Colin Cross07e51612019-03-05 12:46:40 -08001312 subDirFullPath := pathForModuleSrc(ctx, subDir)
Colin Cross2fafa3e2019-03-05 12:39:51 -08001313 rel := Rel(ctx, subDirFullPath.String(), path.String())
1314 return subDirFullPath.Join(ctx, rel)
1315}
1316
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001317// OptionalPathForModuleSrc returns an OptionalPath. The OptionalPath contains a
1318// valid path if p is non-nil.
Liz Kammera830f3a2020-11-10 10:50:34 -08001319func OptionalPathForModuleSrc(ctx ModuleMissingDepsPathContext, p *string) OptionalPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001320 if p == nil {
1321 return OptionalPath{}
1322 }
1323 return OptionalPathForPath(PathForModuleSrc(ctx, *p))
1324}
1325
Liz Kammera830f3a2020-11-10 10:50:34 -08001326func (p SourcePath) genPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleGenPath {
Colin Cross7fc17db2017-02-01 14:07:55 -08001327 return PathForModuleGen(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001328}
1329
Liz Kammera830f3a2020-11-10 10:50:34 -08001330func (p SourcePath) objPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleObjPath {
Colin Cross7fc17db2017-02-01 14:07:55 -08001331 return PathForModuleObj(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001332}
1333
Liz Kammera830f3a2020-11-10 10:50:34 -08001334func (p SourcePath) resPathWithName(ctx ModuleOutPathContext, name string) ModuleResPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001335 // TODO: Use full directory if the new ctx is not the current ctx?
1336 return PathForModuleRes(ctx, p.path, name)
1337}
1338
1339// ModuleOutPath is a Path representing a module's output directory.
1340type ModuleOutPath struct {
1341 OutputPath
1342}
1343
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001344func (p ModuleOutPath) RelativeToTop() Path {
1345 p.OutputPath = p.outputPathRelativeToTop()
1346 return p
1347}
1348
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001349var _ Path = ModuleOutPath{}
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001350var _ WritablePath = ModuleOutPath{}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001351
Liz Kammera830f3a2020-11-10 10:50:34 -08001352func (p ModuleOutPath) objPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleObjPath {
Pete Bentleyfcf55bf2019-08-16 20:14:32 +01001353 return PathForModuleObj(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
1354}
1355
Liz Kammera830f3a2020-11-10 10:50:34 -08001356// ModuleOutPathContext Subset of ModuleContext functions necessary for output path methods.
1357type ModuleOutPathContext interface {
1358 PathContext
1359
1360 ModuleName() string
1361 ModuleDir() string
1362 ModuleSubDir() string
1363}
1364
1365func pathForModuleOut(ctx ModuleOutPathContext) OutputPath {
Colin Cross702e0f82017-10-18 17:27:54 -07001366 return PathForOutput(ctx, ".intermediates", ctx.ModuleDir(), ctx.ModuleName(), ctx.ModuleSubDir())
1367}
1368
Logan Chien7eefdc42018-07-11 18:10:41 +08001369// PathForVndkRefAbiDump returns an OptionalPath representing the path of the
1370// reference abi dump for the given module. This is not guaranteed to be valid.
Liz Kammera830f3a2020-11-10 10:50:34 -08001371func PathForVndkRefAbiDump(ctx ModuleInstallPathContext, version, fileName string,
Hsin-Yi Chen53489642019-07-31 17:10:45 +08001372 isNdk, isLlndkOrVndk, isGzip bool) OptionalPath {
Logan Chien7eefdc42018-07-11 18:10:41 +08001373
Jayant Chowdharyac066c62018-02-20 10:53:31 -08001374 arches := ctx.DeviceConfig().Arches()
Logan Chien7eefdc42018-07-11 18:10:41 +08001375 if len(arches) == 0 {
1376 panic("device build with no primary arch")
1377 }
Jayant Chowdharyac066c62018-02-20 10:53:31 -08001378 currentArch := ctx.Arch()
1379 archNameAndVariant := currentArch.ArchType.String()
1380 if currentArch.ArchVariant != "" {
1381 archNameAndVariant += "_" + currentArch.ArchVariant
1382 }
Logan Chien5237bed2018-07-11 17:15:57 +08001383
1384 var dirName string
Hsin-Yi Chen53489642019-07-31 17:10:45 +08001385 if isNdk {
Logan Chien5237bed2018-07-11 17:15:57 +08001386 dirName = "ndk"
Hsin-Yi Chen53489642019-07-31 17:10:45 +08001387 } else if isLlndkOrVndk {
Logan Chien5237bed2018-07-11 17:15:57 +08001388 dirName = "vndk"
Logan Chien41eabe62019-04-10 13:33:58 +08001389 } else {
1390 dirName = "platform" // opt-in libs
Jayant Chowdhary3e231fd2017-02-08 13:45:53 -08001391 }
Logan Chien5237bed2018-07-11 17:15:57 +08001392
Jayant Chowdhary34ce67d2018-03-08 11:00:50 -08001393 binderBitness := ctx.DeviceConfig().BinderBitness()
Logan Chien7eefdc42018-07-11 18:10:41 +08001394
1395 var ext string
1396 if isGzip {
1397 ext = ".lsdump.gz"
1398 } else {
1399 ext = ".lsdump"
1400 }
1401
1402 return ExistentPathForSource(ctx, "prebuilts", "abi-dumps", dirName,
1403 version, binderBitness, archNameAndVariant, "source-based",
1404 fileName+ext)
Jayant Chowdhary3e231fd2017-02-08 13:45:53 -08001405}
1406
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001407// PathForModuleOut returns a Path representing the paths... under the module's
1408// output directory.
Liz Kammera830f3a2020-11-10 10:50:34 -08001409func PathForModuleOut(ctx ModuleOutPathContext, paths ...string) ModuleOutPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001410 p, err := validatePath(paths...)
1411 if err != nil {
1412 reportPathError(ctx, err)
1413 }
Colin Cross702e0f82017-10-18 17:27:54 -07001414 return ModuleOutPath{
Liz Kammera830f3a2020-11-10 10:50:34 -08001415 OutputPath: pathForModuleOut(ctx).withRel(p),
Colin Cross702e0f82017-10-18 17:27:54 -07001416 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001417}
1418
1419// ModuleGenPath is a Path representing the 'gen' directory in a module's output
1420// directory. Mainly used for generated sources.
1421type ModuleGenPath struct {
1422 ModuleOutPath
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001423}
1424
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001425func (p ModuleGenPath) RelativeToTop() Path {
1426 p.OutputPath = p.outputPathRelativeToTop()
1427 return p
1428}
1429
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001430var _ Path = ModuleGenPath{}
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001431var _ WritablePath = ModuleGenPath{}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001432var _ genPathProvider = ModuleGenPath{}
1433var _ objPathProvider = ModuleGenPath{}
1434
1435// PathForModuleGen returns a Path representing the paths... under the module's
1436// `gen' directory.
Liz Kammera830f3a2020-11-10 10:50:34 -08001437func PathForModuleGen(ctx ModuleOutPathContext, paths ...string) ModuleGenPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001438 p, err := validatePath(paths...)
1439 if err != nil {
1440 reportPathError(ctx, err)
1441 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001442 return ModuleGenPath{
Colin Cross702e0f82017-10-18 17:27:54 -07001443 ModuleOutPath: ModuleOutPath{
Liz Kammera830f3a2020-11-10 10:50:34 -08001444 OutputPath: pathForModuleOut(ctx).withRel("gen").withRel(p),
Colin Cross702e0f82017-10-18 17:27:54 -07001445 },
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001446 }
1447}
1448
Liz Kammera830f3a2020-11-10 10:50:34 -08001449func (p ModuleGenPath) genPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleGenPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001450 // TODO: make a different path for local vs remote generated files?
Dan Willemsen21ec4902016-11-02 20:43:13 -07001451 return PathForModuleGen(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001452}
1453
Liz Kammera830f3a2020-11-10 10:50:34 -08001454func (p ModuleGenPath) objPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleObjPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001455 return PathForModuleObj(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
1456}
1457
1458// ModuleObjPath is a Path representing the 'obj' directory in a module's output
1459// directory. Used for compiled objects.
1460type ModuleObjPath struct {
1461 ModuleOutPath
1462}
1463
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001464func (p ModuleObjPath) RelativeToTop() Path {
1465 p.OutputPath = p.outputPathRelativeToTop()
1466 return p
1467}
1468
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001469var _ Path = ModuleObjPath{}
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001470var _ WritablePath = ModuleObjPath{}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001471
1472// PathForModuleObj returns a Path representing the paths... under the module's
1473// 'obj' directory.
Liz Kammera830f3a2020-11-10 10:50:34 -08001474func PathForModuleObj(ctx ModuleOutPathContext, pathComponents ...string) ModuleObjPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001475 p, err := validatePath(pathComponents...)
1476 if err != nil {
1477 reportPathError(ctx, err)
1478 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001479 return ModuleObjPath{PathForModuleOut(ctx, "obj", p)}
1480}
1481
1482// ModuleResPath is a a Path representing the 'res' directory in a module's
1483// output directory.
1484type ModuleResPath struct {
1485 ModuleOutPath
1486}
1487
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001488func (p ModuleResPath) RelativeToTop() Path {
1489 p.OutputPath = p.outputPathRelativeToTop()
1490 return p
1491}
1492
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001493var _ Path = ModuleResPath{}
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001494var _ WritablePath = ModuleResPath{}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001495
1496// PathForModuleRes returns a Path representing the paths... under the module's
1497// 'res' directory.
Liz Kammera830f3a2020-11-10 10:50:34 -08001498func PathForModuleRes(ctx ModuleOutPathContext, pathComponents ...string) ModuleResPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001499 p, err := validatePath(pathComponents...)
1500 if err != nil {
1501 reportPathError(ctx, err)
1502 }
1503
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001504 return ModuleResPath{PathForModuleOut(ctx, "res", p)}
1505}
1506
Colin Cross70dda7e2019-10-01 22:05:35 -07001507// InstallPath is a Path representing a installed file path rooted from the build directory
1508type InstallPath struct {
1509 basePath
Colin Crossff6c33d2019-10-02 16:01:35 -07001510
Paul Duffind65c58b2021-03-24 09:22:07 +00001511 // The soong build directory, i.e. Config.BuildDir()
1512 buildDir string
1513
Jiyong Park957bcd92020-10-20 18:23:33 +09001514 // partitionDir is the part of the InstallPath that is automatically determined according to the context.
1515 // For example, it is host/<os>-<arch> for host modules, and target/product/<device>/<partition> for device modules.
1516 partitionDir string
1517
1518 // makePath indicates whether this path is for Soong (false) or Make (true).
1519 makePath bool
Colin Cross70dda7e2019-10-01 22:05:35 -07001520}
1521
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001522// Will panic if called from outside a test environment.
1523func ensureTestOnly() {
Martin Stjernholm32312eb2021-03-27 18:54:49 +00001524 if PrefixInList(os.Args, "-test.") {
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001525 return
1526 }
Martin Stjernholm32312eb2021-03-27 18:54:49 +00001527 panic(fmt.Errorf("Not in test. Command line:\n %s", strings.Join(os.Args, "\n ")))
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001528}
1529
1530func (p InstallPath) RelativeToTop() Path {
1531 ensureTestOnly()
1532 p.buildDir = OutSoongDir
1533 return p
1534}
1535
Paul Duffind65c58b2021-03-24 09:22:07 +00001536func (p InstallPath) getBuildDir() string {
1537 return p.buildDir
Paul Duffin9b478b02019-12-10 13:41:51 +00001538}
1539
Hans MÃ¥nssond3f2bd72020-11-27 12:37:28 +01001540func (p InstallPath) ReplaceExtension(ctx PathContext, ext string) OutputPath {
1541 panic("Not implemented")
1542}
1543
Paul Duffin9b478b02019-12-10 13:41:51 +00001544var _ Path = InstallPath{}
1545var _ WritablePath = InstallPath{}
1546
Colin Cross70dda7e2019-10-01 22:05:35 -07001547func (p InstallPath) writablePath() {}
1548
1549func (p InstallPath) String() string {
Jiyong Park957bcd92020-10-20 18:23:33 +09001550 if p.makePath {
1551 // Make path starts with out/ instead of out/soong.
Paul Duffind65c58b2021-03-24 09:22:07 +00001552 return filepath.Join(p.buildDir, "../", p.path)
Jiyong Park957bcd92020-10-20 18:23:33 +09001553 } else {
Paul Duffind65c58b2021-03-24 09:22:07 +00001554 return filepath.Join(p.buildDir, p.path)
Jiyong Park957bcd92020-10-20 18:23:33 +09001555 }
1556}
1557
1558// PartitionDir returns the path to the partition where the install path is rooted at. It is
1559// out/soong/target/product/<device>/<partition> for device modules, and out/soong/host/<os>-<arch> for host modules.
1560// The ./soong is dropped if the install path is for Make.
1561func (p InstallPath) PartitionDir() string {
1562 if p.makePath {
Paul Duffind65c58b2021-03-24 09:22:07 +00001563 return filepath.Join(p.buildDir, "../", p.partitionDir)
Jiyong Park957bcd92020-10-20 18:23:33 +09001564 } else {
Paul Duffind65c58b2021-03-24 09:22:07 +00001565 return filepath.Join(p.buildDir, p.partitionDir)
Jiyong Park957bcd92020-10-20 18:23:33 +09001566 }
Colin Cross70dda7e2019-10-01 22:05:35 -07001567}
1568
1569// Join creates a new InstallPath with paths... joined with the current path. The
1570// provided paths... may not use '..' to escape from the current path.
1571func (p InstallPath) Join(ctx PathContext, paths ...string) InstallPath {
1572 path, err := validatePath(paths...)
1573 if err != nil {
1574 reportPathError(ctx, err)
1575 }
1576 return p.withRel(path)
1577}
1578
1579func (p InstallPath) withRel(rel string) InstallPath {
1580 p.basePath = p.basePath.withRel(rel)
1581 return p
1582}
1583
Colin Crossff6c33d2019-10-02 16:01:35 -07001584// ToMakePath returns a new InstallPath that points to Make's install directory instead of Soong's,
1585// i.e. out/ instead of out/soong/.
1586func (p InstallPath) ToMakePath() InstallPath {
Jiyong Park957bcd92020-10-20 18:23:33 +09001587 p.makePath = true
Colin Crossff6c33d2019-10-02 16:01:35 -07001588 return p
Colin Cross70dda7e2019-10-01 22:05:35 -07001589}
1590
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001591// PathForModuleInstall returns a Path representing the install path for the
1592// module appended with paths...
Colin Cross70dda7e2019-10-01 22:05:35 -07001593func PathForModuleInstall(ctx ModuleInstallPathContext, pathComponents ...string) InstallPath {
Spandan Das5d1b9292021-06-03 19:36:41 +00001594 os, arch := osAndArch(ctx)
1595 partition := modulePartition(ctx, os)
1596 return makePathForInstall(ctx, os, arch, partition, ctx.Debug(), pathComponents...)
1597}
1598
1599// PathForModuleInPartitionInstall is similar to PathForModuleInstall but partition is provided by the caller
1600func PathForModuleInPartitionInstall(ctx ModuleInstallPathContext, partition string, pathComponents ...string) InstallPath {
1601 os, arch := osAndArch(ctx)
1602 return makePathForInstall(ctx, os, arch, partition, ctx.Debug(), pathComponents...)
1603}
1604
1605func osAndArch(ctx ModuleInstallPathContext) (OsType, ArchType) {
Colin Cross6e359402020-02-10 15:29:54 -08001606 os := ctx.Os()
Jiyong Park87788b52020-09-01 12:37:45 +09001607 arch := ctx.Arch().ArchType
1608 forceOS, forceArch := ctx.InstallForceOS()
1609 if forceOS != nil {
Colin Cross6e359402020-02-10 15:29:54 -08001610 os = *forceOS
1611 }
Jiyong Park87788b52020-09-01 12:37:45 +09001612 if forceArch != nil {
1613 arch = *forceArch
1614 }
Spandan Das5d1b9292021-06-03 19:36:41 +00001615 return os, arch
1616}
Colin Cross609c49a2020-02-13 13:20:11 -08001617
Spandan Das5d1b9292021-06-03 19:36:41 +00001618func makePathForInstall(ctx ModuleInstallPathContext, os OsType, arch ArchType, partition string, debug bool, pathComponents ...string) InstallPath {
1619 ret := pathForInstall(ctx, os, arch, partition, debug, pathComponents...)
Jingwen Chencda22c92020-11-23 00:22:30 -05001620 if ctx.InstallBypassMake() && ctx.Config().KatiEnabled() {
Colin Cross609c49a2020-02-13 13:20:11 -08001621 ret = ret.ToMakePath()
1622 }
Colin Cross609c49a2020-02-13 13:20:11 -08001623 return ret
1624}
1625
Jiyong Park87788b52020-09-01 12:37:45 +09001626func pathForInstall(ctx PathContext, os OsType, arch ArchType, partition string, debug bool,
Colin Cross609c49a2020-02-13 13:20:11 -08001627 pathComponents ...string) InstallPath {
1628
Jiyong Park957bcd92020-10-20 18:23:33 +09001629 var partionPaths []string
Colin Cross609c49a2020-02-13 13:20:11 -08001630
Colin Cross6e359402020-02-10 15:29:54 -08001631 if os.Class == Device {
Jiyong Park957bcd92020-10-20 18:23:33 +09001632 partionPaths = []string{"target", "product", ctx.Config().DeviceName(), partition}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001633 } else {
Jiyong Park87788b52020-09-01 12:37:45 +09001634 osName := os.String()
1635 if os == Linux {
1636 // instead of linux_glibc
1637 osName = "linux"
Dan Willemsen866b5632017-09-22 12:28:24 -07001638 }
Jiyong Park87788b52020-09-01 12:37:45 +09001639 // SOONG_HOST_OUT is set to out/host/$(HOST_OS)-$(HOST_PREBUILT_ARCH)
1640 // and HOST_PREBUILT_ARCH is forcibly set to x86 even on x86_64 hosts. We don't seem
1641 // to have a plan to fix it (see the comment in build/make/core/envsetup.mk).
1642 // Let's keep using x86 for the existing cases until we have a need to support
1643 // other architectures.
1644 archName := arch.String()
1645 if os.Class == Host && (arch == X86_64 || arch == Common) {
1646 archName = "x86"
1647 }
Jiyong Park957bcd92020-10-20 18:23:33 +09001648 partionPaths = []string{"host", osName + "-" + archName, partition}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001649 }
Colin Cross609c49a2020-02-13 13:20:11 -08001650 if debug {
Jiyong Park957bcd92020-10-20 18:23:33 +09001651 partionPaths = append([]string{"debug"}, partionPaths...)
Dan Willemsen782a2d12015-12-21 14:55:28 -08001652 }
Colin Cross70dda7e2019-10-01 22:05:35 -07001653
Jiyong Park957bcd92020-10-20 18:23:33 +09001654 partionPath, err := validatePath(partionPaths...)
Colin Cross70dda7e2019-10-01 22:05:35 -07001655 if err != nil {
1656 reportPathError(ctx, err)
1657 }
Colin Crossff6c33d2019-10-02 16:01:35 -07001658
Jiyong Park957bcd92020-10-20 18:23:33 +09001659 base := InstallPath{
Paul Duffin74abc5d2021-03-24 09:24:59 +00001660 basePath: basePath{partionPath, ""},
Paul Duffind65c58b2021-03-24 09:22:07 +00001661 buildDir: ctx.Config().buildDir,
Jiyong Park957bcd92020-10-20 18:23:33 +09001662 partitionDir: partionPath,
1663 makePath: false,
1664 }
Colin Crossff6c33d2019-10-02 16:01:35 -07001665
Jiyong Park957bcd92020-10-20 18:23:33 +09001666 return base.Join(ctx, pathComponents...)
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001667}
1668
Nicolas Geoffray1228e9c2020-02-27 13:45:35 +00001669func pathForNdkOrSdkInstall(ctx PathContext, prefix string, paths []string) InstallPath {
Jiyong Park957bcd92020-10-20 18:23:33 +09001670 base := InstallPath{
Paul Duffin74abc5d2021-03-24 09:24:59 +00001671 basePath: basePath{prefix, ""},
Paul Duffind65c58b2021-03-24 09:22:07 +00001672 buildDir: ctx.Config().buildDir,
Jiyong Park957bcd92020-10-20 18:23:33 +09001673 partitionDir: prefix,
1674 makePath: false,
Colin Cross70dda7e2019-10-01 22:05:35 -07001675 }
Jiyong Park957bcd92020-10-20 18:23:33 +09001676 return base.Join(ctx, paths...)
Colin Cross70dda7e2019-10-01 22:05:35 -07001677}
1678
Nicolas Geoffray1228e9c2020-02-27 13:45:35 +00001679func PathForNdkInstall(ctx PathContext, paths ...string) InstallPath {
1680 return pathForNdkOrSdkInstall(ctx, "ndk", paths)
1681}
1682
1683func PathForMainlineSdksInstall(ctx PathContext, paths ...string) InstallPath {
1684 return pathForNdkOrSdkInstall(ctx, "mainline-sdks", paths)
1685}
1686
Colin Cross70dda7e2019-10-01 22:05:35 -07001687func InstallPathToOnDevicePath(ctx PathContext, path InstallPath) string {
Colin Cross43f08db2018-11-12 10:13:39 -08001688 rel := Rel(ctx, PathForOutput(ctx, "target", "product", ctx.Config().DeviceName()).String(), path.String())
1689
1690 return "/" + rel
1691}
1692
Colin Cross6e359402020-02-10 15:29:54 -08001693func modulePartition(ctx ModuleInstallPathContext, os OsType) string {
Colin Cross43f08db2018-11-12 10:13:39 -08001694 var partition string
Colin Cross6e359402020-02-10 15:29:54 -08001695 if ctx.InstallInTestcases() {
1696 // "testcases" install directory can be used for host or device modules.
Jaewoong Jung0949f312019-09-11 10:25:18 -07001697 partition = "testcases"
Colin Cross6e359402020-02-10 15:29:54 -08001698 } else if os.Class == Device {
1699 if ctx.InstallInData() {
1700 partition = "data"
1701 } else if ctx.InstallInRamdisk() {
1702 if ctx.DeviceConfig().BoardUsesRecoveryAsBoot() {
1703 partition = "recovery/root/first_stage_ramdisk"
1704 } else {
1705 partition = "ramdisk"
1706 }
1707 if !ctx.InstallInRoot() {
1708 partition += "/system"
1709 }
Yifan Hong60e0cfb2020-10-21 15:17:56 -07001710 } else if ctx.InstallInVendorRamdisk() {
Yifan Hong39143a92020-10-26 12:43:12 -07001711 // The module is only available after switching root into
1712 // /first_stage_ramdisk. To expose the module before switching root
1713 // on a device without a dedicated recovery partition, install the
1714 // recovery variant.
Yifan Hongdd8dacc2020-10-21 15:40:17 -07001715 if ctx.DeviceConfig().BoardMoveRecoveryResourcesToVendorBoot() {
Petri Gyntherac229562021-03-02 23:44:02 -08001716 partition = "vendor_ramdisk/first_stage_ramdisk"
Yifan Hongdd8dacc2020-10-21 15:40:17 -07001717 } else {
Petri Gyntherac229562021-03-02 23:44:02 -08001718 partition = "vendor_ramdisk"
Yifan Hongdd8dacc2020-10-21 15:40:17 -07001719 }
1720 if !ctx.InstallInRoot() {
1721 partition += "/system"
1722 }
Inseob Kim08758f02021-04-08 21:13:22 +09001723 } else if ctx.InstallInDebugRamdisk() {
1724 partition = "debug_ramdisk"
Colin Cross6e359402020-02-10 15:29:54 -08001725 } else if ctx.InstallInRecovery() {
1726 if ctx.InstallInRoot() {
1727 partition = "recovery/root"
1728 } else {
1729 // the layout of recovery partion is the same as that of system partition
1730 partition = "recovery/root/system"
1731 }
1732 } else if ctx.SocSpecific() {
1733 partition = ctx.DeviceConfig().VendorPath()
1734 } else if ctx.DeviceSpecific() {
1735 partition = ctx.DeviceConfig().OdmPath()
1736 } else if ctx.ProductSpecific() {
1737 partition = ctx.DeviceConfig().ProductPath()
1738 } else if ctx.SystemExtSpecific() {
1739 partition = ctx.DeviceConfig().SystemExtPath()
1740 } else if ctx.InstallInRoot() {
1741 partition = "root"
Yifan Hong82db7352020-01-21 16:12:26 -08001742 } else {
Colin Cross6e359402020-02-10 15:29:54 -08001743 partition = "system"
Yifan Hong82db7352020-01-21 16:12:26 -08001744 }
Colin Cross6e359402020-02-10 15:29:54 -08001745 if ctx.InstallInSanitizerDir() {
1746 partition = "data/asan/" + partition
Yifan Hong82db7352020-01-21 16:12:26 -08001747 }
Colin Cross43f08db2018-11-12 10:13:39 -08001748 }
1749 return partition
1750}
1751
Colin Cross609c49a2020-02-13 13:20:11 -08001752type InstallPaths []InstallPath
1753
1754// Paths returns the InstallPaths as a Paths
1755func (p InstallPaths) Paths() Paths {
1756 if p == nil {
1757 return nil
1758 }
1759 ret := make(Paths, len(p))
1760 for i, path := range p {
1761 ret[i] = path
1762 }
1763 return ret
1764}
1765
1766// Strings returns the string forms of the install paths.
1767func (p InstallPaths) Strings() []string {
1768 if p == nil {
1769 return nil
1770 }
1771 ret := make([]string, len(p))
1772 for i, path := range p {
1773 ret[i] = path.String()
1774 }
1775 return ret
1776}
1777
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001778// validateSafePath validates a path that we trust (may contain ninja variables).
Dan Willemsen80a7c2a2015-12-21 14:57:11 -08001779// Ensures that each path component does not attempt to leave its component.
Colin Cross1ccfcc32018-02-22 13:54:26 -08001780func validateSafePath(pathComponents ...string) (string, error) {
Jeff Gaston734e3802017-04-10 15:47:24 -07001781 for _, path := range pathComponents {
Dan Willemsen80a7c2a2015-12-21 14:57:11 -08001782 path := filepath.Clean(path)
1783 if path == ".." || strings.HasPrefix(path, "../") || strings.HasPrefix(path, "/") {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001784 return "", fmt.Errorf("Path is outside directory: %s", path)
Dan Willemsen80a7c2a2015-12-21 14:57:11 -08001785 }
1786 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001787 // TODO: filepath.Join isn't necessarily correct with embedded ninja
1788 // variables. '..' may remove the entire ninja variable, even if it
1789 // will be expanded to multiple nested directories.
Colin Cross1ccfcc32018-02-22 13:54:26 -08001790 return filepath.Join(pathComponents...), nil
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001791}
1792
Dan Willemsen80a7c2a2015-12-21 14:57:11 -08001793// validatePath validates that a path does not include ninja variables, and that
1794// each path component does not attempt to leave its component. Returns a joined
1795// version of each path component.
Colin Cross1ccfcc32018-02-22 13:54:26 -08001796func validatePath(pathComponents ...string) (string, error) {
Jeff Gaston734e3802017-04-10 15:47:24 -07001797 for _, path := range pathComponents {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001798 if strings.Contains(path, "$") {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001799 return "", fmt.Errorf("Path contains invalid character($): %s", path)
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001800 }
1801 }
Colin Cross1ccfcc32018-02-22 13:54:26 -08001802 return validateSafePath(pathComponents...)
Colin Cross6e18ca42015-07-14 18:55:36 -07001803}
Colin Cross5b529592017-05-09 13:34:34 -07001804
Colin Cross0875c522017-11-28 17:34:01 -08001805func PathForPhony(ctx PathContext, phony string) WritablePath {
1806 if strings.ContainsAny(phony, "$/") {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001807 ReportPathErrorf(ctx, "Phony target contains invalid character ($ or /): %s", phony)
Colin Cross0875c522017-11-28 17:34:01 -08001808 }
Paul Duffin74abc5d2021-03-24 09:24:59 +00001809 return PhonyPath{basePath{phony, ""}}
Colin Cross0875c522017-11-28 17:34:01 -08001810}
1811
Colin Cross74e3fe42017-12-11 15:51:44 -08001812type PhonyPath struct {
1813 basePath
1814}
1815
1816func (p PhonyPath) writablePath() {}
1817
Paul Duffind65c58b2021-03-24 09:22:07 +00001818func (p PhonyPath) getBuildDir() string {
1819 // A phone path cannot contain any / so cannot be relative to the build directory.
1820 return ""
Paul Duffin9b478b02019-12-10 13:41:51 +00001821}
1822
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001823func (p PhonyPath) RelativeToTop() Path {
1824 ensureTestOnly()
1825 // A phony path cannot contain any / so does not have a build directory so switching to a new
1826 // build directory has no effect so just return this path.
1827 return p
1828}
1829
Hans MÃ¥nssond3f2bd72020-11-27 12:37:28 +01001830func (p PhonyPath) ReplaceExtension(ctx PathContext, ext string) OutputPath {
1831 panic("Not implemented")
1832}
1833
Colin Cross74e3fe42017-12-11 15:51:44 -08001834var _ Path = PhonyPath{}
1835var _ WritablePath = PhonyPath{}
1836
Colin Cross5b529592017-05-09 13:34:34 -07001837type testPath struct {
1838 basePath
1839}
1840
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001841func (p testPath) RelativeToTop() Path {
1842 ensureTestOnly()
1843 return p
1844}
1845
Colin Cross5b529592017-05-09 13:34:34 -07001846func (p testPath) String() string {
1847 return p.path
1848}
1849
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001850var _ Path = testPath{}
1851
Colin Cross40e33732019-02-15 11:08:35 -08001852// PathForTesting returns a Path constructed from joining the elements of paths with '/'. It should only be used from
1853// within tests.
Colin Cross5b529592017-05-09 13:34:34 -07001854func PathForTesting(paths ...string) Path {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001855 p, err := validateSafePath(paths...)
1856 if err != nil {
1857 panic(err)
1858 }
Colin Cross5b529592017-05-09 13:34:34 -07001859 return testPath{basePath{path: p, rel: p}}
1860}
1861
Colin Cross40e33732019-02-15 11:08:35 -08001862// PathsForTesting returns a Path constructed from each element in strs. It should only be used from within tests.
1863func PathsForTesting(strs ...string) Paths {
Colin Cross5b529592017-05-09 13:34:34 -07001864 p := make(Paths, len(strs))
1865 for i, s := range strs {
1866 p[i] = PathForTesting(s)
1867 }
1868
1869 return p
1870}
Colin Cross43f08db2018-11-12 10:13:39 -08001871
Colin Cross40e33732019-02-15 11:08:35 -08001872type testPathContext struct {
1873 config Config
Colin Cross40e33732019-02-15 11:08:35 -08001874}
1875
Colin Cross40e33732019-02-15 11:08:35 -08001876func (x *testPathContext) Config() Config { return x.config }
1877func (x *testPathContext) AddNinjaFileDeps(...string) {}
1878
1879// PathContextForTesting returns a PathContext that can be used in tests, for example to create an OutputPath with
1880// PathForOutput.
Colin Cross98be1bb2019-12-13 20:41:13 -08001881func PathContextForTesting(config Config) PathContext {
Colin Cross40e33732019-02-15 11:08:35 -08001882 return &testPathContext{
1883 config: config,
Colin Cross40e33732019-02-15 11:08:35 -08001884 }
1885}
1886
Ulya Trafimovichccc8c852020-10-14 11:29:07 +01001887type testModuleInstallPathContext struct {
1888 baseModuleContext
1889
1890 inData bool
1891 inTestcases bool
1892 inSanitizerDir bool
1893 inRamdisk bool
1894 inVendorRamdisk bool
Inseob Kim08758f02021-04-08 21:13:22 +09001895 inDebugRamdisk bool
Ulya Trafimovichccc8c852020-10-14 11:29:07 +01001896 inRecovery bool
1897 inRoot bool
1898 forceOS *OsType
1899 forceArch *ArchType
1900}
1901
1902func (m testModuleInstallPathContext) Config() Config {
1903 return m.baseModuleContext.config
1904}
1905
1906func (testModuleInstallPathContext) AddNinjaFileDeps(deps ...string) {}
1907
1908func (m testModuleInstallPathContext) InstallInData() bool {
1909 return m.inData
1910}
1911
1912func (m testModuleInstallPathContext) InstallInTestcases() bool {
1913 return m.inTestcases
1914}
1915
1916func (m testModuleInstallPathContext) InstallInSanitizerDir() bool {
1917 return m.inSanitizerDir
1918}
1919
1920func (m testModuleInstallPathContext) InstallInRamdisk() bool {
1921 return m.inRamdisk
1922}
1923
1924func (m testModuleInstallPathContext) InstallInVendorRamdisk() bool {
1925 return m.inVendorRamdisk
1926}
1927
Inseob Kim08758f02021-04-08 21:13:22 +09001928func (m testModuleInstallPathContext) InstallInDebugRamdisk() bool {
1929 return m.inDebugRamdisk
1930}
1931
Ulya Trafimovichccc8c852020-10-14 11:29:07 +01001932func (m testModuleInstallPathContext) InstallInRecovery() bool {
1933 return m.inRecovery
1934}
1935
1936func (m testModuleInstallPathContext) InstallInRoot() bool {
1937 return m.inRoot
1938}
1939
1940func (m testModuleInstallPathContext) InstallBypassMake() bool {
1941 return false
1942}
1943
1944func (m testModuleInstallPathContext) InstallForceOS() (*OsType, *ArchType) {
1945 return m.forceOS, m.forceArch
1946}
1947
1948// Construct a minimal ModuleInstallPathContext for testing. Note that baseModuleContext is
1949// default-initialized, which leaves blueprint.baseModuleContext set to nil, so methods that are
1950// delegated to it will panic.
1951func ModuleInstallPathContextForTesting(config Config) ModuleInstallPathContext {
1952 ctx := &testModuleInstallPathContext{}
1953 ctx.config = config
1954 ctx.os = Android
1955 return ctx
1956}
1957
Colin Cross43f08db2018-11-12 10:13:39 -08001958// Rel performs the same function as filepath.Rel, but reports errors to a PathContext, and reports an error if
1959// targetPath is not inside basePath.
1960func Rel(ctx PathContext, basePath string, targetPath string) string {
1961 rel, isRel := MaybeRel(ctx, basePath, targetPath)
1962 if !isRel {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001963 ReportPathErrorf(ctx, "path %q is not under path %q", targetPath, basePath)
Colin Cross43f08db2018-11-12 10:13:39 -08001964 return ""
1965 }
1966 return rel
1967}
1968
1969// MaybeRel performs the same function as filepath.Rel, but reports errors to a PathContext, and returns false if
1970// targetPath is not inside basePath.
1971func MaybeRel(ctx PathContext, basePath string, targetPath string) (string, bool) {
Dan Willemsen633c5022019-04-12 11:11:38 -07001972 rel, isRel, err := maybeRelErr(basePath, targetPath)
1973 if err != nil {
1974 reportPathError(ctx, err)
1975 }
1976 return rel, isRel
1977}
1978
1979func maybeRelErr(basePath string, targetPath string) (string, bool, error) {
Colin Cross43f08db2018-11-12 10:13:39 -08001980 // filepath.Rel returns an error if one path is absolute and the other is not, handle that case first.
1981 if filepath.IsAbs(basePath) != filepath.IsAbs(targetPath) {
Dan Willemsen633c5022019-04-12 11:11:38 -07001982 return "", false, nil
Colin Cross43f08db2018-11-12 10:13:39 -08001983 }
1984 rel, err := filepath.Rel(basePath, targetPath)
1985 if err != nil {
Dan Willemsen633c5022019-04-12 11:11:38 -07001986 return "", false, err
Colin Cross43f08db2018-11-12 10:13:39 -08001987 } else if rel == ".." || strings.HasPrefix(rel, "../") || strings.HasPrefix(rel, "/") {
Dan Willemsen633c5022019-04-12 11:11:38 -07001988 return "", false, nil
Colin Cross43f08db2018-11-12 10:13:39 -08001989 }
Dan Willemsen633c5022019-04-12 11:11:38 -07001990 return rel, true, nil
Colin Cross43f08db2018-11-12 10:13:39 -08001991}
Colin Cross988414c2020-01-11 01:11:46 +00001992
1993// Writes a file to the output directory. Attempting to write directly to the output directory
1994// will fail due to the sandbox of the soong_build process.
1995func WriteFileToOutputDir(path WritablePath, data []byte, perm os.FileMode) error {
1996 return ioutil.WriteFile(absolutePath(path.String()), data, perm)
1997}
1998
Liz Kammer2dd9ca42020-11-25 16:06:39 -08001999func RemoveAllOutputDir(path WritablePath) error {
2000 return os.RemoveAll(absolutePath(path.String()))
2001}
2002
2003func CreateOutputDirIfNonexistent(path WritablePath, perm os.FileMode) error {
2004 dir := absolutePath(path.String())
Liz Kammer09f947d2021-05-12 14:51:49 -04002005 return createDirIfNonexistent(dir, perm)
2006}
2007
2008func createDirIfNonexistent(dir string, perm os.FileMode) error {
Liz Kammer2dd9ca42020-11-25 16:06:39 -08002009 if _, err := os.Stat(dir); os.IsNotExist(err) {
2010 return os.MkdirAll(dir, os.ModePerm)
2011 } else {
2012 return err
2013 }
2014}
2015
Jingwen Chen78257e52021-05-21 02:34:24 +00002016// absolutePath is deliberately private so that Soong's Go plugins can't use it to find and
2017// read arbitrary files without going through the methods in the current package that track
2018// dependencies.
Colin Cross988414c2020-01-11 01:11:46 +00002019func absolutePath(path string) string {
2020 if filepath.IsAbs(path) {
2021 return path
2022 }
2023 return filepath.Join(absSrcDir, path)
2024}
Chris Parsons216e10a2020-07-09 17:12:52 -04002025
2026// A DataPath represents the path of a file to be used as data, for example
2027// a test library to be installed alongside a test.
2028// The data file should be installed (copied from `<SrcPath>`) to
2029// `<install_root>/<RelativeInstallPath>/<filename>`, or
2030// `<install_root>/<filename>` if RelativeInstallPath is empty.
2031type DataPath struct {
2032 // The path of the data file that should be copied into the data directory
2033 SrcPath Path
2034 // The install path of the data file, relative to the install root.
2035 RelativeInstallPath string
2036}
Colin Crossdcf71b22021-02-01 13:59:03 -08002037
2038// PathsIfNonNil returns a Paths containing only the non-nil input arguments.
2039func PathsIfNonNil(paths ...Path) Paths {
2040 if len(paths) == 0 {
2041 // Fast path for empty argument list
2042 return nil
2043 } else if len(paths) == 1 {
2044 // Fast path for a single argument
2045 if paths[0] != nil {
2046 return paths
2047 } else {
2048 return nil
2049 }
2050 }
2051 ret := make(Paths, 0, len(paths))
2052 for _, path := range paths {
2053 if path != nil {
2054 ret = append(ret, path)
2055 }
2056 }
2057 if len(ret) == 0 {
2058 return nil
2059 }
2060 return ret
2061}