blob: 71caaab83a225278bc70eb52f99adabf79f5a9a7 [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"
Chris Wailesb2703ad2021-07-30 13:25:42 -070023 "regexp"
Colin Cross5e6cfbe2017-11-03 15:20:35 -070024 "sort"
Dan Willemsen34cc69e2015-09-23 15:26:20 -070025 "strings"
26
27 "github.com/google/blueprint"
Colin Cross0e446152021-05-03 13:35:32 -070028 "github.com/google/blueprint/bootstrap"
Dan Willemsen34cc69e2015-09-23 15:26:20 -070029 "github.com/google/blueprint/pathtools"
Colin Cross3f40fa42015-01-30 17:27:36 -080030)
31
Colin Cross988414c2020-01-11 01:11:46 +000032var absSrcDir string
33
Dan Willemsen34cc69e2015-09-23 15:26:20 -070034// PathContext is the subset of a (Module|Singleton)Context required by the
35// Path methods.
36type PathContext interface {
Colin Crossaabf6792017-11-29 00:27:14 -080037 Config() Config
Dan Willemsen7b310ee2015-12-18 15:11:17 -080038 AddNinjaFileDeps(deps ...string)
Colin Cross3f40fa42015-01-30 17:27:36 -080039}
40
Colin Cross7f19f372016-11-01 11:10:25 -070041type PathGlobContext interface {
42 GlobWithDeps(globPattern string, excludes []string) ([]string, error)
43}
44
Colin Crossaabf6792017-11-29 00:27:14 -080045var _ PathContext = SingletonContext(nil)
46var _ PathContext = ModuleContext(nil)
Dan Willemsen34cc69e2015-09-23 15:26:20 -070047
Ulya Trafimovich8640ab92020-05-11 18:06:15 +010048// "Null" path context is a minimal path context for a given config.
49type NullPathContext struct {
50 config Config
51}
52
53func (NullPathContext) AddNinjaFileDeps(...string) {}
54func (ctx NullPathContext) Config() Config { return ctx.config }
55
Liz Kammera830f3a2020-11-10 10:50:34 -080056// EarlyModulePathContext is a subset of EarlyModuleContext methods required by the
57// Path methods. These path methods can be called before any mutators have run.
58type EarlyModulePathContext interface {
59 PathContext
60 PathGlobContext
61
62 ModuleDir() string
63 ModuleErrorf(fmt string, args ...interface{})
64}
65
66var _ EarlyModulePathContext = ModuleContext(nil)
67
68// Glob globs files and directories matching globPattern relative to ModuleDir(),
69// paths in the excludes parameter will be omitted.
70func Glob(ctx EarlyModulePathContext, globPattern string, excludes []string) Paths {
71 ret, err := ctx.GlobWithDeps(globPattern, excludes)
72 if err != nil {
73 ctx.ModuleErrorf("glob: %s", err.Error())
74 }
75 return pathsForModuleSrcFromFullPath(ctx, ret, true)
76}
77
78// GlobFiles globs *only* files (not directories) matching globPattern relative to ModuleDir().
79// Paths in the excludes parameter will be omitted.
80func GlobFiles(ctx EarlyModulePathContext, globPattern string, excludes []string) Paths {
81 ret, err := ctx.GlobWithDeps(globPattern, excludes)
82 if err != nil {
83 ctx.ModuleErrorf("glob: %s", err.Error())
84 }
85 return pathsForModuleSrcFromFullPath(ctx, ret, false)
86}
87
88// ModuleWithDepsPathContext is a subset of *ModuleContext methods required by
89// the Path methods that rely on module dependencies having been resolved.
90type ModuleWithDepsPathContext interface {
91 EarlyModulePathContext
Paul Duffin40131a32021-07-09 17:10:35 +010092 VisitDirectDepsBlueprint(visit func(blueprint.Module))
93 OtherModuleDependencyTag(m blueprint.Module) blueprint.DependencyTag
Liz Kammera830f3a2020-11-10 10:50:34 -080094}
95
96// ModuleMissingDepsPathContext is a subset of *ModuleContext methods required by
97// the Path methods that rely on module dependencies having been resolved and ability to report
98// missing dependency errors.
99type ModuleMissingDepsPathContext interface {
100 ModuleWithDepsPathContext
101 AddMissingDependencies(missingDeps []string)
102}
103
Dan Willemsen00269f22017-07-06 16:59:48 -0700104type ModuleInstallPathContext interface {
Colin Cross0ea8ba82019-06-06 14:33:29 -0700105 BaseModuleContext
Dan Willemsen00269f22017-07-06 16:59:48 -0700106
107 InstallInData() bool
Jaewoong Jung0949f312019-09-11 10:25:18 -0700108 InstallInTestcases() bool
Dan Willemsen00269f22017-07-06 16:59:48 -0700109 InstallInSanitizerDir() bool
Yifan Hong1b3348d2020-01-21 15:53:22 -0800110 InstallInRamdisk() bool
Yifan Hong60e0cfb2020-10-21 15:17:56 -0700111 InstallInVendorRamdisk() bool
Inseob Kim08758f02021-04-08 21:13:22 +0900112 InstallInDebugRamdisk() bool
Jiyong Parkf9332f12018-02-01 00:54:12 +0900113 InstallInRecovery() bool
Colin Cross90ba5f42019-10-02 11:10:58 -0700114 InstallInRoot() bool
Colin Cross607d8582019-07-29 16:44:46 -0700115 InstallBypassMake() bool
Jiyong Park87788b52020-09-01 12:37:45 +0900116 InstallForceOS() (*OsType, *ArchType)
Dan Willemsen00269f22017-07-06 16:59:48 -0700117}
118
119var _ ModuleInstallPathContext = ModuleContext(nil)
120
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700121// errorfContext is the interface containing the Errorf method matching the
122// Errorf method in blueprint.SingletonContext.
123type errorfContext interface {
124 Errorf(format string, args ...interface{})
Colin Cross3f40fa42015-01-30 17:27:36 -0800125}
126
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700127var _ errorfContext = blueprint.SingletonContext(nil)
128
129// moduleErrorf is the interface containing the ModuleErrorf method matching
130// the ModuleErrorf method in blueprint.ModuleContext.
131type moduleErrorf interface {
132 ModuleErrorf(format string, args ...interface{})
Colin Cross3f40fa42015-01-30 17:27:36 -0800133}
134
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700135var _ moduleErrorf = blueprint.ModuleContext(nil)
136
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700137// reportPathError will register an error with the attached context. It
138// attempts ctx.ModuleErrorf for a better error message first, then falls
139// back to ctx.Errorf.
Colin Cross1ccfcc32018-02-22 13:54:26 -0800140func reportPathError(ctx PathContext, err error) {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +0100141 ReportPathErrorf(ctx, "%s", err.Error())
Colin Cross1ccfcc32018-02-22 13:54:26 -0800142}
143
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +0100144// ReportPathErrorf will register an error with the attached context. It
Colin Cross1ccfcc32018-02-22 13:54:26 -0800145// attempts ctx.ModuleErrorf for a better error message first, then falls
146// back to ctx.Errorf.
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +0100147func ReportPathErrorf(ctx PathContext, format string, args ...interface{}) {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700148 if mctx, ok := ctx.(moduleErrorf); ok {
149 mctx.ModuleErrorf(format, args...)
150 } else if ectx, ok := ctx.(errorfContext); ok {
151 ectx.Errorf(format, args...)
152 } else {
153 panic(fmt.Sprintf(format, args...))
Colin Crossf2298272015-05-12 11:36:53 -0700154 }
155}
156
Colin Cross5e708052019-08-06 13:59:50 -0700157func pathContextName(ctx PathContext, module blueprint.Module) string {
158 if x, ok := ctx.(interface{ ModuleName(blueprint.Module) string }); ok {
159 return x.ModuleName(module)
160 } else if x, ok := ctx.(interface{ OtherModuleName(blueprint.Module) string }); ok {
161 return x.OtherModuleName(module)
162 }
163 return "unknown"
164}
165
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700166type Path interface {
167 // Returns the path in string form
168 String() string
169
Colin Cross4f6fc9c2016-10-26 10:05:25 -0700170 // Ext returns the extension of the last element of the path
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700171 Ext() string
Colin Cross4f6fc9c2016-10-26 10:05:25 -0700172
173 // Base returns the last element of the path
174 Base() string
Colin Crossfaeb7aa2017-02-01 14:12:44 -0800175
176 // Rel returns the portion of the path relative to the directory it was created from. For
177 // example, Rel on a PathsForModuleSrc would return the path relative to the module source
Colin Cross0db55682017-12-05 15:36:55 -0800178 // directory, and OutputPath.Join("foo").Rel() would return "foo".
Colin Crossfaeb7aa2017-02-01 14:12:44 -0800179 Rel() string
Paul Duffin85d8f0d2021-03-24 10:18:18 +0000180
181 // RelativeToTop returns a new path relative to the top, it is provided solely for use in tests.
182 //
183 // It is guaranteed to always return the same type as it is called on, e.g. if called on an
184 // InstallPath then the returned value can be converted to an InstallPath.
185 //
186 // A standard build has the following structure:
187 // ../top/
188 // out/ - make install files go here.
189 // out/soong - this is the buildDir passed to NewTestConfig()
190 // ... - the source files
191 //
192 // This function converts a path so that it appears relative to the ../top/ directory, i.e.
193 // * Make install paths, which have the pattern "buildDir/../<path>" are converted into the top
194 // relative path "out/<path>"
195 // * Soong install paths and other writable paths, which have the pattern "buildDir/<path>" are
196 // converted into the top relative path "out/soong/<path>".
197 // * Source paths are already relative to the top.
198 // * Phony paths are not relative to anything.
199 // * toolDepPath have an absolute but known value in so don't need making relative to anything in
200 // order to test.
201 RelativeToTop() Path
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700202}
203
Paul Duffin85d8f0d2021-03-24 10:18:18 +0000204const (
205 OutDir = "out"
206 OutSoongDir = OutDir + "/soong"
207)
208
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700209// WritablePath is a type of path that can be used as an output for build rules.
210type WritablePath interface {
211 Path
212
Paul Duffin9b478b02019-12-10 13:41:51 +0000213 // return the path to the build directory.
Paul Duffind65c58b2021-03-24 09:22:07 +0000214 getBuildDir() string
Paul Duffin9b478b02019-12-10 13:41:51 +0000215
Jeff Gaston734e3802017-04-10 15:47:24 -0700216 // the writablePath method doesn't directly do anything,
217 // but it allows a struct to distinguish between whether or not it implements the WritablePath interface
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700218 writablePath()
Hans MÃ¥nssond3f2bd72020-11-27 12:37:28 +0100219
220 ReplaceExtension(ctx PathContext, ext string) OutputPath
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700221}
222
223type genPathProvider interface {
Liz Kammera830f3a2020-11-10 10:50:34 -0800224 genPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleGenPath
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700225}
226type objPathProvider interface {
Liz Kammera830f3a2020-11-10 10:50:34 -0800227 objPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleObjPath
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700228}
229type resPathProvider interface {
Liz Kammera830f3a2020-11-10 10:50:34 -0800230 resPathWithName(ctx ModuleOutPathContext, name string) ModuleResPath
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700231}
232
233// GenPathWithExt derives a new file path in ctx's generated sources directory
234// from the current path, but with the new extension.
Liz Kammera830f3a2020-11-10 10:50:34 -0800235func GenPathWithExt(ctx ModuleOutPathContext, subdir string, p Path, ext string) ModuleGenPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700236 if path, ok := p.(genPathProvider); ok {
Dan Willemsen21ec4902016-11-02 20:43:13 -0700237 return path.genPathWithExt(ctx, subdir, ext)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700238 }
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +0100239 ReportPathErrorf(ctx, "Tried to create generated file from unsupported path: %s(%s)", reflect.TypeOf(p).Name(), p)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700240 return PathForModuleGen(ctx)
241}
242
243// ObjPathWithExt derives a new file path in ctx's object directory from the
244// current path, but with the new extension.
Liz Kammera830f3a2020-11-10 10:50:34 -0800245func ObjPathWithExt(ctx ModuleOutPathContext, subdir string, p Path, ext string) ModuleObjPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700246 if path, ok := p.(objPathProvider); ok {
247 return path.objPathWithExt(ctx, subdir, ext)
248 }
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +0100249 ReportPathErrorf(ctx, "Tried to create object file from unsupported path: %s (%s)", reflect.TypeOf(p).Name(), p)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700250 return PathForModuleObj(ctx)
251}
252
253// ResPathWithName derives a new path in ctx's output resource directory, using
254// the current path to create the directory name, and the `name` argument for
255// the filename.
Liz Kammera830f3a2020-11-10 10:50:34 -0800256func ResPathWithName(ctx ModuleOutPathContext, p Path, name string) ModuleResPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700257 if path, ok := p.(resPathProvider); ok {
258 return path.resPathWithName(ctx, name)
259 }
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +0100260 ReportPathErrorf(ctx, "Tried to create res file from unsupported path: %s (%s)", reflect.TypeOf(p).Name(), p)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700261 return PathForModuleRes(ctx)
262}
263
264// OptionalPath is a container that may or may not contain a valid Path.
265type OptionalPath struct {
266 valid bool
267 path Path
268}
269
270// OptionalPathForPath returns an OptionalPath containing the path.
271func OptionalPathForPath(path Path) OptionalPath {
272 if path == nil {
273 return OptionalPath{}
274 }
275 return OptionalPath{valid: true, path: path}
276}
277
278// Valid returns whether there is a valid path
279func (p OptionalPath) Valid() bool {
280 return p.valid
281}
282
283// Path returns the Path embedded in this OptionalPath. You must be sure that
284// there is a valid path, since this method will panic if there is not.
285func (p OptionalPath) Path() Path {
286 if !p.valid {
287 panic("Requesting an invalid path")
288 }
289 return p.path
290}
291
Paul Duffinef081852021-05-13 11:11:15 +0100292// AsPaths converts the OptionalPath into Paths.
293//
294// It returns nil if this is not valid, or a single length slice containing the Path embedded in
295// this OptionalPath.
296func (p OptionalPath) AsPaths() Paths {
297 if !p.valid {
298 return nil
299 }
300 return Paths{p.path}
301}
302
Paul Duffinafdd4062021-03-30 19:44:07 +0100303// RelativeToTop returns an OptionalPath with the path that was embedded having been replaced by the
304// result of calling Path.RelativeToTop on it.
305func (p OptionalPath) RelativeToTop() OptionalPath {
Paul Duffina5b81352021-03-28 23:57:19 +0100306 if !p.valid {
307 return p
308 }
309 p.path = p.path.RelativeToTop()
310 return p
311}
312
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700313// String returns the string version of the Path, or "" if it isn't valid.
314func (p OptionalPath) String() string {
315 if p.valid {
316 return p.path.String()
317 } else {
318 return ""
Colin Crossf2298272015-05-12 11:36:53 -0700319 }
320}
Colin Cross6e18ca42015-07-14 18:55:36 -0700321
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700322// Paths is a slice of Path objects, with helpers to operate on the collection.
323type Paths []Path
324
Paul Duffin85d8f0d2021-03-24 10:18:18 +0000325// RelativeToTop creates a new Paths containing the result of calling Path.RelativeToTop on each
326// item in this slice.
327func (p Paths) RelativeToTop() Paths {
328 ensureTestOnly()
329 if p == nil {
330 return p
331 }
332 ret := make(Paths, len(p))
333 for i, path := range p {
334 ret[i] = path.RelativeToTop()
335 }
336 return ret
337}
338
Jingwen Chen40fd90a2020-06-15 05:24:19 +0000339func (paths Paths) containsPath(path Path) bool {
340 for _, p := range paths {
341 if p == path {
342 return true
343 }
344 }
345 return false
346}
347
Liz Kammer7aa52882021-02-11 09:16:14 -0500348// PathsForSource returns Paths rooted from SrcDir, *not* rooted from the module's local source
349// directory
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700350func PathsForSource(ctx PathContext, paths []string) Paths {
351 ret := make(Paths, len(paths))
352 for i, path := range paths {
353 ret[i] = PathForSource(ctx, path)
354 }
355 return ret
356}
357
Liz Kammer7aa52882021-02-11 09:16:14 -0500358// ExistentPathsForSources returns a list of Paths rooted from SrcDir, *not* rooted from the
359// module's local source directory, that are found in the tree. If any are not found, they are
360// 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 -0800361func ExistentPathsForSources(ctx PathContext, paths []string) Paths {
Dan Willemsen7b310ee2015-12-18 15:11:17 -0800362 ret := make(Paths, 0, len(paths))
363 for _, path := range paths {
Colin Cross32f38982018-02-22 11:47:25 -0800364 p := ExistentPathForSource(ctx, path)
Dan Willemsen7b310ee2015-12-18 15:11:17 -0800365 if p.Valid() {
366 ret = append(ret, p.Path())
367 }
368 }
369 return ret
370}
371
Liz Kammer620dea62021-04-14 17:36:10 -0400372// PathsForModuleSrc returns a Paths{} containing the resolved references in paths:
373// * filepath, relative to local module directory, resolves as a filepath relative to the local
374// source directory
375// * glob, relative to the local module directory, resolves as filepath(s), relative to the local
376// source directory.
377// * other modules using the ":name{.tag}" syntax. These modules must implement SourceFileProducer
378// or OutputFileProducer. These resolve as a filepath to an output filepath or generated source
379// filepath.
380// Properties passed as the paths argument must have been annotated with struct tag
Colin Cross41955e82019-05-29 14:40:35 -0700381// `android:"path"` so that dependencies on SourceFileProducer modules will have already been handled by the
Liz Kammer620dea62021-04-14 17:36:10 -0400382// path_deps mutator.
383// If a requested module is not found as a dependency:
384// * if ctx.Config().AllowMissingDependencies() is true, this module to be marked as having
385// missing dependencies
386// * otherwise, a ModuleError is thrown.
Liz Kammera830f3a2020-11-10 10:50:34 -0800387func PathsForModuleSrc(ctx ModuleMissingDepsPathContext, paths []string) Paths {
Colin Cross8a497952019-03-05 22:25:09 -0800388 return PathsForModuleSrcExcludes(ctx, paths, nil)
389}
390
Liz Kammer620dea62021-04-14 17:36:10 -0400391// PathsForModuleSrcExcludes returns a Paths{} containing the resolved references in paths, minus
392// those listed in excludes. Elements of paths and excludes are resolved as:
393// * filepath, relative to local module directory, resolves as a filepath relative to the local
394// source directory
395// * glob, relative to the local module directory, resolves as filepath(s), relative to the local
396// source directory. Not valid in excludes.
397// * other modules using the ":name{.tag}" syntax. These modules must implement SourceFileProducer
398// or OutputFileProducer. These resolve as a filepath to an output filepath or generated source
399// filepath.
400// excluding the items (similarly resolved
401// Properties passed as the paths argument must have been annotated with struct tag
402// `android:"path"` so that dependencies on SourceFileProducer modules will have already been handled by the
403// path_deps mutator.
404// If a requested module is not found as a dependency:
405// * if ctx.Config().AllowMissingDependencies() is true, this module to be marked as having
406// missing dependencies
407// * otherwise, a ModuleError is thrown.
Liz Kammera830f3a2020-11-10 10:50:34 -0800408func PathsForModuleSrcExcludes(ctx ModuleMissingDepsPathContext, paths, excludes []string) Paths {
Colin Crossba71a3f2019-03-18 12:12:48 -0700409 ret, missingDeps := PathsAndMissingDepsForModuleSrcExcludes(ctx, paths, excludes)
410 if ctx.Config().AllowMissingDependencies() {
411 ctx.AddMissingDependencies(missingDeps)
412 } else {
413 for _, m := range missingDeps {
414 ctx.ModuleErrorf(`missing dependency on %q, is the property annotated with android:"path"?`, m)
415 }
416 }
417 return ret
418}
419
Ulya Trafimovich4d2eeed2019-11-08 10:54:21 +0000420// OutputPaths is a slice of OutputPath objects, with helpers to operate on the collection.
421type OutputPaths []OutputPath
422
423// Paths returns the OutputPaths as a Paths
424func (p OutputPaths) Paths() Paths {
425 if p == nil {
426 return nil
427 }
428 ret := make(Paths, len(p))
429 for i, path := range p {
430 ret[i] = path
431 }
432 return ret
433}
434
435// Strings returns the string forms of the writable paths.
436func (p OutputPaths) Strings() []string {
437 if p == nil {
438 return nil
439 }
440 ret := make([]string, len(p))
441 for i, path := range p {
442 ret[i] = path.String()
443 }
444 return ret
445}
446
Liz Kammera830f3a2020-11-10 10:50:34 -0800447// Expands Paths to a SourceFileProducer or OutputFileProducer module dependency referenced via ":name" or ":name{.tag}" syntax.
448// If the dependency is not found, a missingErrorDependency is returned.
449// If the module dependency is not a SourceFileProducer or OutputFileProducer, appropriate errors will be returned.
450func getPathsFromModuleDep(ctx ModuleWithDepsPathContext, path, moduleName, tag string) (Paths, error) {
Paul Duffind5cf92e2021-07-09 17:38:55 +0100451 module := GetModuleFromPathDep(ctx, moduleName, tag)
Liz Kammera830f3a2020-11-10 10:50:34 -0800452 if module == nil {
453 return nil, missingDependencyError{[]string{moduleName}}
454 }
Colin Crossfa65cee2021-03-22 17:05:59 -0700455 if aModule, ok := module.(Module); ok && !aModule.Enabled() {
456 return nil, missingDependencyError{[]string{moduleName}}
457 }
Liz Kammera830f3a2020-11-10 10:50:34 -0800458 if outProducer, ok := module.(OutputFileProducer); ok {
459 outputFiles, err := outProducer.OutputFiles(tag)
460 if err != nil {
461 return nil, fmt.Errorf("path dependency %q: %s", path, err)
462 }
463 return outputFiles, nil
464 } else if tag != "" {
465 return nil, fmt.Errorf("path dependency %q is not an output file producing module", path)
Colin Cross0e446152021-05-03 13:35:32 -0700466 } else if goBinary, ok := module.(bootstrap.GoBinaryTool); ok {
467 if rel, err := filepath.Rel(PathForOutput(ctx).String(), goBinary.InstallPath()); err == nil {
468 return Paths{PathForOutput(ctx, rel).WithoutRel()}, nil
469 } else {
470 return nil, fmt.Errorf("cannot find output path for %q: %w", goBinary.InstallPath(), err)
471 }
Liz Kammera830f3a2020-11-10 10:50:34 -0800472 } else if srcProducer, ok := module.(SourceFileProducer); ok {
473 return srcProducer.Srcs(), nil
474 } else {
475 return nil, fmt.Errorf("path dependency %q is not a source file producing module", path)
476 }
477}
478
Paul Duffind5cf92e2021-07-09 17:38:55 +0100479// GetModuleFromPathDep will return the module that was added as a dependency automatically for
480// properties tagged with `android:"path"` or manually using ExtractSourceDeps or
481// ExtractSourcesDeps.
482//
483// The moduleName and tag supplied to this should be the values returned from SrcIsModuleWithTag.
484// Or, if no tag is expected then the moduleName should be the value returned by SrcIsModule and
485// the tag must be "".
486//
487// If tag is "" then the returned module will be the dependency that was added for ":moduleName".
488// Otherwise, it is the dependency that was added for ":moduleName{tag}".
Paul Duffind5cf92e2021-07-09 17:38:55 +0100489func GetModuleFromPathDep(ctx ModuleWithDepsPathContext, moduleName, tag string) blueprint.Module {
Paul Duffin40131a32021-07-09 17:10:35 +0100490 var found blueprint.Module
491 // The sourceOrOutputDepTag uniquely identifies the module dependency as it contains both the
492 // module name and the tag. Dependencies added automatically for properties tagged with
493 // `android:"path"` are deduped so are guaranteed to be unique. It is possible for duplicate
494 // dependencies to be added manually using ExtractSourcesDeps or ExtractSourceDeps but even then
495 // it will always be the case that the dependencies will be identical, i.e. the same tag and same
496 // moduleName referring to the same dependency module.
497 //
498 // It does not matter whether the moduleName is a fully qualified name or if the module
499 // dependency is a prebuilt module. All that matters is the same information is supplied to
500 // create the tag here as was supplied to create the tag when the dependency was added so that
501 // this finds the matching dependency module.
502 expectedTag := sourceOrOutputDepTag(moduleName, tag)
503 ctx.VisitDirectDepsBlueprint(func(module blueprint.Module) {
504 depTag := ctx.OtherModuleDependencyTag(module)
505 if depTag == expectedTag {
506 found = module
507 }
508 })
509 return found
Paul Duffind5cf92e2021-07-09 17:38:55 +0100510}
511
Liz Kammer620dea62021-04-14 17:36:10 -0400512// PathsAndMissingDepsForModuleSrcExcludes returns a Paths{} containing the resolved references in
513// paths, minus those listed in excludes. Elements of paths and excludes are resolved as:
514// * filepath, relative to local module directory, resolves as a filepath relative to the local
515// source directory
516// * glob, relative to the local module directory, resolves as filepath(s), relative to the local
517// source directory. Not valid in excludes.
518// * other modules using the ":name{.tag}" syntax. These modules must implement SourceFileProducer
519// or OutputFileProducer. These resolve as a filepath to an output filepath or generated source
520// filepath.
521// and a list of the module names of missing module dependencies are returned as the second return.
522// Properties passed as the paths argument must have been annotated with struct tag
Colin Cross41955e82019-05-29 14:40:35 -0700523// `android:"path"` so that dependencies on SourceFileProducer modules will have already been handled by the
Liz Kammer620dea62021-04-14 17:36:10 -0400524// path_deps mutator.
Liz Kammera830f3a2020-11-10 10:50:34 -0800525func PathsAndMissingDepsForModuleSrcExcludes(ctx ModuleWithDepsPathContext, paths, excludes []string) (Paths, []string) {
Colin Cross8a497952019-03-05 22:25:09 -0800526 prefix := pathForModuleSrc(ctx).String()
527
528 var expandedExcludes []string
529 if excludes != nil {
530 expandedExcludes = make([]string, 0, len(excludes))
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700531 }
Colin Cross8a497952019-03-05 22:25:09 -0800532
Colin Crossba71a3f2019-03-18 12:12:48 -0700533 var missingExcludeDeps []string
534
Colin Cross8a497952019-03-05 22:25:09 -0800535 for _, e := range excludes {
Colin Cross41955e82019-05-29 14:40:35 -0700536 if m, t := SrcIsModuleWithTag(e); m != "" {
Liz Kammera830f3a2020-11-10 10:50:34 -0800537 modulePaths, err := getPathsFromModuleDep(ctx, e, m, t)
538 if m, ok := err.(missingDependencyError); ok {
539 missingExcludeDeps = append(missingExcludeDeps, m.missingDeps...)
540 } else if err != nil {
541 reportPathError(ctx, err)
Colin Cross8a497952019-03-05 22:25:09 -0800542 } else {
Liz Kammera830f3a2020-11-10 10:50:34 -0800543 expandedExcludes = append(expandedExcludes, modulePaths.Strings()...)
Colin Cross8a497952019-03-05 22:25:09 -0800544 }
545 } else {
546 expandedExcludes = append(expandedExcludes, filepath.Join(prefix, e))
547 }
548 }
549
550 if paths == nil {
Colin Crossba71a3f2019-03-18 12:12:48 -0700551 return nil, missingExcludeDeps
Colin Cross8a497952019-03-05 22:25:09 -0800552 }
553
Colin Crossba71a3f2019-03-18 12:12:48 -0700554 var missingDeps []string
555
Colin Cross8a497952019-03-05 22:25:09 -0800556 expandedSrcFiles := make(Paths, 0, len(paths))
557 for _, s := range paths {
558 srcFiles, err := expandOneSrcPath(ctx, s, expandedExcludes)
559 if depErr, ok := err.(missingDependencyError); ok {
Colin Crossba71a3f2019-03-18 12:12:48 -0700560 missingDeps = append(missingDeps, depErr.missingDeps...)
Colin Cross8a497952019-03-05 22:25:09 -0800561 } else if err != nil {
562 reportPathError(ctx, err)
563 }
564 expandedSrcFiles = append(expandedSrcFiles, srcFiles...)
565 }
Colin Crossba71a3f2019-03-18 12:12:48 -0700566
567 return expandedSrcFiles, append(missingDeps, missingExcludeDeps...)
Colin Cross8a497952019-03-05 22:25:09 -0800568}
569
570type missingDependencyError struct {
571 missingDeps []string
572}
573
574func (e missingDependencyError) Error() string {
575 return "missing dependencies: " + strings.Join(e.missingDeps, ", ")
576}
577
Liz Kammera830f3a2020-11-10 10:50:34 -0800578// Expands one path string to Paths rooted from the module's local source
579// directory, excluding those listed in the expandedExcludes.
580// Expands globs, references to SourceFileProducer or OutputFileProducer modules using the ":name" and ":name{.tag}" syntax.
581func expandOneSrcPath(ctx ModuleWithDepsPathContext, sPath string, expandedExcludes []string) (Paths, error) {
Jooyung Han7607dd32020-07-05 10:23:14 +0900582 excludePaths := func(paths Paths) Paths {
583 if len(expandedExcludes) == 0 {
584 return paths
585 }
586 remainder := make(Paths, 0, len(paths))
587 for _, p := range paths {
588 if !InList(p.String(), expandedExcludes) {
589 remainder = append(remainder, p)
590 }
591 }
592 return remainder
593 }
Liz Kammera830f3a2020-11-10 10:50:34 -0800594 if m, t := SrcIsModuleWithTag(sPath); m != "" {
595 modulePaths, err := getPathsFromModuleDep(ctx, sPath, m, t)
596 if err != nil {
597 return nil, err
Colin Cross8a497952019-03-05 22:25:09 -0800598 } else {
Liz Kammera830f3a2020-11-10 10:50:34 -0800599 return excludePaths(modulePaths), nil
Colin Cross8a497952019-03-05 22:25:09 -0800600 }
Liz Kammera830f3a2020-11-10 10:50:34 -0800601 } else if pathtools.IsGlob(sPath) {
602 paths := GlobFiles(ctx, pathForModuleSrc(ctx, sPath).String(), expandedExcludes)
Colin Cross8a497952019-03-05 22:25:09 -0800603 return PathsWithModuleSrcSubDir(ctx, paths, ""), nil
604 } else {
Liz Kammera830f3a2020-11-10 10:50:34 -0800605 p := pathForModuleSrc(ctx, sPath)
Colin Cross988414c2020-01-11 01:11:46 +0000606 if exists, _, err := ctx.Config().fs.Exists(p.String()); err != nil {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +0100607 ReportPathErrorf(ctx, "%s: %s", p, err.Error())
Pedro Loureiro5d190cc2021-02-15 15:41:33 +0000608 } else if !exists && !ctx.Config().TestAllowNonExistentPaths {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +0100609 ReportPathErrorf(ctx, "module source path %q does not exist", p)
Colin Cross8a497952019-03-05 22:25:09 -0800610 }
611
Jooyung Han7607dd32020-07-05 10:23:14 +0900612 if InList(p.String(), expandedExcludes) {
Colin Cross8a497952019-03-05 22:25:09 -0800613 return nil, nil
614 }
615 return Paths{p}, nil
616 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700617}
618
619// pathsForModuleSrcFromFullPath returns Paths rooted from the module's local
620// source directory, but strip the local source directory from the beginning of
Dan Willemsen540a78c2018-02-26 21:50:08 -0800621// each string. If incDirs is false, strip paths with a trailing '/' from the list.
Colin Crossfe4bc362018-09-12 10:02:13 -0700622// It intended for use in globs that only list files that exist, so it allows '$' in
623// filenames.
Liz Kammera830f3a2020-11-10 10:50:34 -0800624func pathsForModuleSrcFromFullPath(ctx EarlyModulePathContext, paths []string, incDirs bool) Paths {
Lukacs T. Berkif7e36d82021-08-16 17:05:09 +0200625 prefix := ctx.ModuleDir() + "/"
Colin Cross0f37af02017-09-27 17:42:05 -0700626 if prefix == "./" {
627 prefix = ""
628 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700629 ret := make(Paths, 0, len(paths))
630 for _, p := range paths {
Dan Willemsen540a78c2018-02-26 21:50:08 -0800631 if !incDirs && strings.HasSuffix(p, "/") {
632 continue
633 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700634 path := filepath.Clean(p)
635 if !strings.HasPrefix(path, prefix) {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +0100636 ReportPathErrorf(ctx, "Path %q is not in module source directory %q", p, prefix)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700637 continue
638 }
Colin Crosse3924e12018-08-15 20:18:53 -0700639
Colin Crossfe4bc362018-09-12 10:02:13 -0700640 srcPath, err := safePathForSource(ctx, ctx.ModuleDir(), path[len(prefix):])
Colin Crosse3924e12018-08-15 20:18:53 -0700641 if err != nil {
642 reportPathError(ctx, err)
643 continue
644 }
645
Colin Cross07e51612019-03-05 12:46:40 -0800646 srcPath.basePath.rel = srcPath.path
Colin Crosse3924e12018-08-15 20:18:53 -0700647
Colin Cross07e51612019-03-05 12:46:40 -0800648 ret = append(ret, srcPath)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700649 }
650 return ret
651}
652
Liz Kammera830f3a2020-11-10 10:50:34 -0800653// PathsWithOptionalDefaultForModuleSrc returns Paths rooted from the module's local source
654// directory. If input is nil, use the default if it exists. If input is empty, returns nil.
655func PathsWithOptionalDefaultForModuleSrc(ctx ModuleMissingDepsPathContext, input []string, def string) Paths {
Colin Cross0ddae7f2019-02-07 15:30:01 -0800656 if input != nil {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700657 return PathsForModuleSrc(ctx, input)
658 }
659 // Use Glob so that if the default doesn't exist, a dependency is added so that when it
660 // is created, we're run again.
Lukacs T. Berkif7e36d82021-08-16 17:05:09 +0200661 path := filepath.Join(ctx.ModuleDir(), def)
Liz Kammera830f3a2020-11-10 10:50:34 -0800662 return Glob(ctx, path, nil)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700663}
664
665// Strings returns the Paths in string form
666func (p Paths) Strings() []string {
667 if p == nil {
668 return nil
669 }
670 ret := make([]string, len(p))
671 for i, path := range p {
672 ret[i] = path.String()
673 }
674 return ret
675}
676
Colin Crossc0efd1d2020-07-03 11:56:24 -0700677func CopyOfPaths(paths Paths) Paths {
678 return append(Paths(nil), paths...)
679}
680
Colin Crossb6715442017-10-24 11:13:31 -0700681// FirstUniquePaths returns all unique elements of a Paths, keeping the first copy of each. It
682// modifies the Paths slice contents in place, and returns a subslice of the original slice.
Dan Willemsenfe92c962017-08-29 12:28:37 -0700683func FirstUniquePaths(list Paths) Paths {
Colin Cross27027c72020-02-28 15:34:17 -0800684 // 128 was chosen based on BenchmarkFirstUniquePaths results.
685 if len(list) > 128 {
686 return firstUniquePathsMap(list)
687 }
688 return firstUniquePathsList(list)
689}
690
Colin Crossc0efd1d2020-07-03 11:56:24 -0700691// SortedUniquePaths returns all unique elements of a Paths in sorted order. It modifies the
692// Paths slice contents in place, and returns a subslice of the original slice.
Jiyong Park33c77362020-05-29 22:00:16 +0900693func SortedUniquePaths(list Paths) Paths {
694 unique := FirstUniquePaths(list)
695 sort.Slice(unique, func(i, j int) bool {
696 return unique[i].String() < unique[j].String()
697 })
698 return unique
699}
700
Colin Cross27027c72020-02-28 15:34:17 -0800701func firstUniquePathsList(list Paths) Paths {
Dan Willemsenfe92c962017-08-29 12:28:37 -0700702 k := 0
703outer:
704 for i := 0; i < len(list); i++ {
705 for j := 0; j < k; j++ {
706 if list[i] == list[j] {
707 continue outer
708 }
709 }
710 list[k] = list[i]
711 k++
712 }
713 return list[:k]
714}
715
Colin Cross27027c72020-02-28 15:34:17 -0800716func firstUniquePathsMap(list Paths) Paths {
717 k := 0
718 seen := make(map[Path]bool, len(list))
719 for i := 0; i < len(list); i++ {
720 if seen[list[i]] {
721 continue
722 }
723 seen[list[i]] = true
724 list[k] = list[i]
725 k++
726 }
727 return list[:k]
728}
729
Colin Cross5d583952020-11-24 16:21:24 -0800730// FirstUniqueInstallPaths returns all unique elements of an InstallPaths, keeping the first copy of each. It
731// modifies the InstallPaths slice contents in place, and returns a subslice of the original slice.
732func FirstUniqueInstallPaths(list InstallPaths) InstallPaths {
733 // 128 was chosen based on BenchmarkFirstUniquePaths results.
734 if len(list) > 128 {
735 return firstUniqueInstallPathsMap(list)
736 }
737 return firstUniqueInstallPathsList(list)
738}
739
740func firstUniqueInstallPathsList(list InstallPaths) InstallPaths {
741 k := 0
742outer:
743 for i := 0; i < len(list); i++ {
744 for j := 0; j < k; j++ {
745 if list[i] == list[j] {
746 continue outer
747 }
748 }
749 list[k] = list[i]
750 k++
751 }
752 return list[:k]
753}
754
755func firstUniqueInstallPathsMap(list InstallPaths) InstallPaths {
756 k := 0
757 seen := make(map[InstallPath]bool, len(list))
758 for i := 0; i < len(list); i++ {
759 if seen[list[i]] {
760 continue
761 }
762 seen[list[i]] = true
763 list[k] = list[i]
764 k++
765 }
766 return list[:k]
767}
768
Colin Crossb6715442017-10-24 11:13:31 -0700769// LastUniquePaths returns all unique elements of a Paths, keeping the last copy of each. It
770// modifies the Paths slice contents in place, and returns a subslice of the original slice.
771func LastUniquePaths(list Paths) Paths {
772 totalSkip := 0
773 for i := len(list) - 1; i >= totalSkip; i-- {
774 skip := 0
775 for j := i - 1; j >= totalSkip; j-- {
776 if list[i] == list[j] {
777 skip++
778 } else {
779 list[j+skip] = list[j]
780 }
781 }
782 totalSkip += skip
783 }
784 return list[totalSkip:]
785}
786
Colin Crossa140bb02018-04-17 10:52:26 -0700787// ReversePaths returns a copy of a Paths in reverse order.
788func ReversePaths(list Paths) Paths {
789 if list == nil {
790 return nil
791 }
792 ret := make(Paths, len(list))
793 for i := range list {
794 ret[i] = list[len(list)-1-i]
795 }
796 return ret
797}
798
Jeff Gaston294356f2017-09-27 17:05:30 -0700799func indexPathList(s Path, list []Path) int {
800 for i, l := range list {
801 if l == s {
802 return i
803 }
804 }
805
806 return -1
807}
808
809func inPathList(p Path, list []Path) bool {
810 return indexPathList(p, list) != -1
811}
812
813func FilterPathList(list []Path, filter []Path) (remainder []Path, filtered []Path) {
Paul Duffin57b9e1d2019-12-13 00:03:35 +0000814 return FilterPathListPredicate(list, func(p Path) bool { return inPathList(p, filter) })
815}
816
817func FilterPathListPredicate(list []Path, predicate func(Path) bool) (remainder []Path, filtered []Path) {
Jeff Gaston294356f2017-09-27 17:05:30 -0700818 for _, l := range list {
Paul Duffin57b9e1d2019-12-13 00:03:35 +0000819 if predicate(l) {
Jeff Gaston294356f2017-09-27 17:05:30 -0700820 filtered = append(filtered, l)
821 } else {
822 remainder = append(remainder, l)
823 }
824 }
825
826 return
827}
828
Colin Cross93e85952017-08-15 13:34:18 -0700829// HasExt returns true of any of the paths have extension ext, otherwise false
830func (p Paths) HasExt(ext string) bool {
831 for _, path := range p {
832 if path.Ext() == ext {
833 return true
834 }
835 }
836
837 return false
838}
839
840// FilterByExt returns the subset of the paths that have extension ext
841func (p Paths) FilterByExt(ext string) Paths {
842 ret := make(Paths, 0, len(p))
843 for _, path := range p {
844 if path.Ext() == ext {
845 ret = append(ret, path)
846 }
847 }
848 return ret
849}
850
851// FilterOutByExt returns the subset of the paths that do not have extension ext
852func (p Paths) FilterOutByExt(ext string) Paths {
853 ret := make(Paths, 0, len(p))
854 for _, path := range p {
855 if path.Ext() != ext {
856 ret = append(ret, path)
857 }
858 }
859 return ret
860}
861
Colin Cross5e6cfbe2017-11-03 15:20:35 -0700862// DirectorySortedPaths is a slice of paths that are sorted such that all files in a directory
863// (including subdirectories) are in a contiguous subslice of the list, and can be found in
864// O(log(N)) time using a binary search on the directory prefix.
865type DirectorySortedPaths Paths
866
867func PathsToDirectorySortedPaths(paths Paths) DirectorySortedPaths {
868 ret := append(DirectorySortedPaths(nil), paths...)
869 sort.Slice(ret, func(i, j int) bool {
870 return ret[i].String() < ret[j].String()
871 })
872 return ret
873}
874
875// PathsInDirectory returns a subslice of the DirectorySortedPaths as a Paths that contains all entries
876// that are in the specified directory and its subdirectories.
877func (p DirectorySortedPaths) PathsInDirectory(dir string) Paths {
878 prefix := filepath.Clean(dir) + "/"
879 start := sort.Search(len(p), func(i int) bool {
880 return prefix < p[i].String()
881 })
882
883 ret := p[start:]
884
885 end := sort.Search(len(ret), func(i int) bool {
886 return !strings.HasPrefix(ret[i].String(), prefix)
887 })
888
889 ret = ret[:end]
890
891 return Paths(ret)
892}
893
Alex Humesky29e3bbe2020-11-20 21:30:13 -0500894// WritablePaths is a slice of WritablePath, used for multiple outputs.
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700895type WritablePaths []WritablePath
896
Paul Duffin85d8f0d2021-03-24 10:18:18 +0000897// RelativeToTop creates a new WritablePaths containing the result of calling Path.RelativeToTop on
898// each item in this slice.
899func (p WritablePaths) RelativeToTop() WritablePaths {
900 ensureTestOnly()
901 if p == nil {
902 return p
903 }
904 ret := make(WritablePaths, len(p))
905 for i, path := range p {
906 ret[i] = path.RelativeToTop().(WritablePath)
907 }
908 return ret
909}
910
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700911// Strings returns the string forms of the writable paths.
912func (p WritablePaths) Strings() []string {
913 if p == nil {
914 return nil
915 }
916 ret := make([]string, len(p))
917 for i, path := range p {
918 ret[i] = path.String()
919 }
920 return ret
921}
922
Colin Cross3bc7ffa2017-11-22 16:19:37 -0800923// Paths returns the WritablePaths as a Paths
924func (p WritablePaths) Paths() Paths {
925 if p == nil {
926 return nil
927 }
928 ret := make(Paths, len(p))
929 for i, path := range p {
930 ret[i] = path
931 }
932 return ret
933}
934
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700935type basePath struct {
Paul Duffin74abc5d2021-03-24 09:24:59 +0000936 path string
937 rel string
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700938}
939
940func (p basePath) Ext() string {
941 return filepath.Ext(p.path)
942}
943
Colin Cross4f6fc9c2016-10-26 10:05:25 -0700944func (p basePath) Base() string {
945 return filepath.Base(p.path)
946}
947
Colin Crossfaeb7aa2017-02-01 14:12:44 -0800948func (p basePath) Rel() string {
949 if p.rel != "" {
950 return p.rel
951 }
952 return p.path
953}
954
Colin Cross0875c522017-11-28 17:34:01 -0800955func (p basePath) String() string {
956 return p.path
957}
958
Colin Cross0db55682017-12-05 15:36:55 -0800959func (p basePath) withRel(rel string) basePath {
960 p.path = filepath.Join(p.path, rel)
961 p.rel = rel
962 return p
963}
964
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700965// SourcePath is a Path representing a file path rooted from SrcDir
966type SourcePath struct {
967 basePath
Paul Duffin580efc82021-03-24 09:04:03 +0000968
969 // The sources root, i.e. Config.SrcDir()
970 srcDir string
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700971}
972
Paul Duffin85d8f0d2021-03-24 10:18:18 +0000973func (p SourcePath) RelativeToTop() Path {
974 ensureTestOnly()
975 return p
976}
977
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700978var _ Path = SourcePath{}
979
Colin Cross0db55682017-12-05 15:36:55 -0800980func (p SourcePath) withRel(rel string) SourcePath {
981 p.basePath = p.basePath.withRel(rel)
982 return p
983}
984
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700985// safePathForSource is for paths that we expect are safe -- only for use by go
986// code that is embedding ninja variables in paths
Colin Crossfe4bc362018-09-12 10:02:13 -0700987func safePathForSource(ctx PathContext, pathComponents ...string) (SourcePath, error) {
988 p, err := validateSafePath(pathComponents...)
Lukacs T. Berkif7e36d82021-08-16 17:05:09 +0200989 ret := SourcePath{basePath{p, ""}, "."}
Colin Crossfe4bc362018-09-12 10:02:13 -0700990 if err != nil {
991 return ret, err
992 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700993
Colin Cross7b3dcc32019-01-24 13:14:39 -0800994 // absolute path already checked by validateSafePath
995 if strings.HasPrefix(ret.String(), ctx.Config().buildDir) {
Mikhail Naganovab1f5182019-02-08 13:17:55 -0800996 return ret, fmt.Errorf("source path %q is in output", ret.String())
Colin Cross6e18ca42015-07-14 18:55:36 -0700997 }
998
Colin Crossfe4bc362018-09-12 10:02:13 -0700999 return ret, err
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001000}
1001
Colin Cross192e97a2018-02-22 14:21:02 -08001002// pathForSource creates a SourcePath from pathComponents, but does not check that it exists.
1003func pathForSource(ctx PathContext, pathComponents ...string) (SourcePath, error) {
Colin Crossc48c1432018-02-23 07:09:01 +00001004 p, err := validatePath(pathComponents...)
Lukacs T. Berkif7e36d82021-08-16 17:05:09 +02001005 ret := SourcePath{basePath{p, ""}, "."}
Colin Cross94a32102018-02-22 14:21:02 -08001006 if err != nil {
Colin Cross192e97a2018-02-22 14:21:02 -08001007 return ret, err
Colin Cross94a32102018-02-22 14:21:02 -08001008 }
1009
Colin Cross7b3dcc32019-01-24 13:14:39 -08001010 // absolute path already checked by validatePath
1011 if strings.HasPrefix(ret.String(), ctx.Config().buildDir) {
Mikhail Naganovab1f5182019-02-08 13:17:55 -08001012 return ret, fmt.Errorf("source path %q is in output", ret.String())
Colin Crossc48c1432018-02-23 07:09:01 +00001013 }
1014
Colin Cross192e97a2018-02-22 14:21:02 -08001015 return ret, nil
1016}
1017
1018// existsWithDependencies returns true if the path exists, and adds appropriate dependencies to rerun if the
1019// path does not exist.
1020func existsWithDependencies(ctx PathContext, path SourcePath) (exists bool, err error) {
1021 var files []string
1022
1023 if gctx, ok := ctx.(PathGlobContext); ok {
1024 // Use glob to produce proper dependencies, even though we only want
1025 // a single file.
1026 files, err = gctx.GlobWithDeps(path.String(), nil)
1027 } else {
Colin Cross82ea3fb2021-04-05 17:48:26 -07001028 var result pathtools.GlobResult
Colin Cross192e97a2018-02-22 14:21:02 -08001029 // We cannot add build statements in this context, so we fall back to
1030 // AddNinjaFileDeps
Colin Cross82ea3fb2021-04-05 17:48:26 -07001031 result, err = ctx.Config().fs.Glob(path.String(), nil, pathtools.FollowSymlinks)
1032 ctx.AddNinjaFileDeps(result.Deps...)
1033 files = result.Matches
Colin Cross192e97a2018-02-22 14:21:02 -08001034 }
1035
1036 if err != nil {
1037 return false, fmt.Errorf("glob: %s", err.Error())
1038 }
1039
1040 return len(files) > 0, nil
1041}
1042
1043// PathForSource joins the provided path components and validates that the result
1044// neither escapes the source dir nor is in the out dir.
1045// On error, it will return a usable, but invalid SourcePath, and report a ModuleError.
1046func PathForSource(ctx PathContext, pathComponents ...string) SourcePath {
1047 path, err := pathForSource(ctx, pathComponents...)
1048 if err != nil {
1049 reportPathError(ctx, err)
1050 }
1051
Colin Crosse3924e12018-08-15 20:18:53 -07001052 if pathtools.IsGlob(path.String()) {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001053 ReportPathErrorf(ctx, "path may not contain a glob: %s", path.String())
Colin Crosse3924e12018-08-15 20:18:53 -07001054 }
1055
Liz Kammera830f3a2020-11-10 10:50:34 -08001056 if modCtx, ok := ctx.(ModuleMissingDepsPathContext); ok && ctx.Config().AllowMissingDependencies() {
Colin Cross192e97a2018-02-22 14:21:02 -08001057 exists, err := existsWithDependencies(ctx, path)
1058 if err != nil {
1059 reportPathError(ctx, err)
1060 }
1061 if !exists {
1062 modCtx.AddMissingDependencies([]string{path.String()})
1063 }
Colin Cross988414c2020-01-11 01:11:46 +00001064 } else if exists, _, err := ctx.Config().fs.Exists(path.String()); err != nil {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001065 ReportPathErrorf(ctx, "%s: %s", path, err.Error())
Pedro Loureiro5d190cc2021-02-15 15:41:33 +00001066 } else if !exists && !ctx.Config().TestAllowNonExistentPaths {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001067 ReportPathErrorf(ctx, "source path %q does not exist", path)
Colin Cross192e97a2018-02-22 14:21:02 -08001068 }
1069 return path
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001070}
1071
Liz Kammer7aa52882021-02-11 09:16:14 -05001072// ExistentPathForSource returns an OptionalPath with the SourcePath, rooted from SrcDir, *not*
1073// rooted from the module's local source directory, if the path exists, or an empty OptionalPath if
1074// it doesn't exist. Dependencies are added so that the ninja file will be regenerated if the state
1075// of the path changes.
Colin Cross32f38982018-02-22 11:47:25 -08001076func ExistentPathForSource(ctx PathContext, pathComponents ...string) OptionalPath {
Colin Cross192e97a2018-02-22 14:21:02 -08001077 path, err := pathForSource(ctx, pathComponents...)
Colin Cross1ccfcc32018-02-22 13:54:26 -08001078 if err != nil {
1079 reportPathError(ctx, err)
1080 return OptionalPath{}
1081 }
Colin Crossc48c1432018-02-23 07:09:01 +00001082
Colin Crosse3924e12018-08-15 20:18:53 -07001083 if pathtools.IsGlob(path.String()) {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001084 ReportPathErrorf(ctx, "path may not contain a glob: %s", path.String())
Colin Crosse3924e12018-08-15 20:18:53 -07001085 return OptionalPath{}
1086 }
1087
Colin Cross192e97a2018-02-22 14:21:02 -08001088 exists, err := existsWithDependencies(ctx, path)
Colin Crossc48c1432018-02-23 07:09:01 +00001089 if err != nil {
1090 reportPathError(ctx, err)
1091 return OptionalPath{}
1092 }
Colin Cross192e97a2018-02-22 14:21:02 -08001093 if !exists {
Colin Crossc48c1432018-02-23 07:09:01 +00001094 return OptionalPath{}
1095 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001096 return OptionalPathForPath(path)
1097}
1098
1099func (p SourcePath) String() string {
Paul Duffin580efc82021-03-24 09:04:03 +00001100 return filepath.Join(p.srcDir, p.path)
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001101}
1102
1103// Join creates a new SourcePath with paths... joined with the current path. The
1104// provided paths... may not use '..' to escape from the current path.
1105func (p SourcePath) Join(ctx PathContext, paths ...string) SourcePath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001106 path, err := validatePath(paths...)
1107 if err != nil {
1108 reportPathError(ctx, err)
1109 }
Colin Cross0db55682017-12-05 15:36:55 -08001110 return p.withRel(path)
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001111}
1112
Colin Cross2fafa3e2019-03-05 12:39:51 -08001113// join is like Join but does less path validation.
1114func (p SourcePath) join(ctx PathContext, paths ...string) SourcePath {
1115 path, err := validateSafePath(paths...)
1116 if err != nil {
1117 reportPathError(ctx, err)
1118 }
1119 return p.withRel(path)
1120}
1121
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001122// OverlayPath returns the overlay for `path' if it exists. This assumes that the
1123// SourcePath is the path to a resource overlay directory.
Liz Kammera830f3a2020-11-10 10:50:34 -08001124func (p SourcePath) OverlayPath(ctx ModuleMissingDepsPathContext, path Path) OptionalPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001125 var relDir string
Colin Cross07e51612019-03-05 12:46:40 -08001126 if srcPath, ok := path.(SourcePath); ok {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001127 relDir = srcPath.path
1128 } else {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001129 ReportPathErrorf(ctx, "Cannot find relative path for %s(%s)", reflect.TypeOf(path).Name(), path)
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001130 return OptionalPath{}
1131 }
Paul Duffin580efc82021-03-24 09:04:03 +00001132 dir := filepath.Join(p.srcDir, p.path, relDir)
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001133 // Use Glob so that we are run again if the directory is added.
Colin Cross7f19f372016-11-01 11:10:25 -07001134 if pathtools.IsGlob(dir) {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001135 ReportPathErrorf(ctx, "Path may not contain a glob: %s", dir)
Dan Willemsen7b310ee2015-12-18 15:11:17 -08001136 }
Colin Cross461b4452018-02-23 09:22:42 -08001137 paths, err := ctx.GlobWithDeps(dir, nil)
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001138 if err != nil {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001139 ReportPathErrorf(ctx, "glob: %s", err.Error())
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001140 return OptionalPath{}
1141 }
1142 if len(paths) == 0 {
1143 return OptionalPath{}
1144 }
Paul Duffin580efc82021-03-24 09:04:03 +00001145 relPath := Rel(ctx, p.srcDir, paths[0])
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001146 return OptionalPathForPath(PathForSource(ctx, relPath))
1147}
1148
Colin Cross70dda7e2019-10-01 22:05:35 -07001149// OutputPath is a Path representing an intermediates file path rooted from the build directory
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001150type OutputPath struct {
1151 basePath
Paul Duffind65c58b2021-03-24 09:22:07 +00001152
1153 // The soong build directory, i.e. Config.BuildDir()
1154 buildDir string
1155
Colin Crossd63c9a72020-01-29 16:52:50 -08001156 fullPath string
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001157}
1158
Colin Cross702e0f82017-10-18 17:27:54 -07001159func (p OutputPath) withRel(rel string) OutputPath {
Colin Cross0db55682017-12-05 15:36:55 -08001160 p.basePath = p.basePath.withRel(rel)
Colin Crossd63c9a72020-01-29 16:52:50 -08001161 p.fullPath = filepath.Join(p.fullPath, rel)
Colin Cross702e0f82017-10-18 17:27:54 -07001162 return p
1163}
1164
Colin Cross3063b782018-08-15 11:19:12 -07001165func (p OutputPath) WithoutRel() OutputPath {
1166 p.basePath.rel = filepath.Base(p.basePath.path)
1167 return p
1168}
1169
Paul Duffind65c58b2021-03-24 09:22:07 +00001170func (p OutputPath) getBuildDir() string {
1171 return p.buildDir
Paul Duffin9b478b02019-12-10 13:41:51 +00001172}
1173
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001174func (p OutputPath) RelativeToTop() Path {
1175 return p.outputPathRelativeToTop()
1176}
1177
1178func (p OutputPath) outputPathRelativeToTop() OutputPath {
1179 p.fullPath = StringPathRelativeToTop(p.buildDir, p.fullPath)
1180 p.buildDir = OutSoongDir
1181 return p
1182}
1183
Paul Duffin0267d492021-02-02 10:05:52 +00001184func (p OutputPath) objPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleObjPath {
1185 return PathForModuleObj(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
1186}
1187
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001188var _ Path = OutputPath{}
Paul Duffin9b478b02019-12-10 13:41:51 +00001189var _ WritablePath = OutputPath{}
Paul Duffin0267d492021-02-02 10:05:52 +00001190var _ objPathProvider = OutputPath{}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001191
Chris Parsons8f232a22020-06-23 17:37:05 -04001192// toolDepPath is a Path representing a dependency of the build tool.
1193type toolDepPath struct {
1194 basePath
1195}
1196
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001197func (t toolDepPath) RelativeToTop() Path {
1198 ensureTestOnly()
1199 return t
1200}
1201
Chris Parsons8f232a22020-06-23 17:37:05 -04001202var _ Path = toolDepPath{}
1203
1204// pathForBuildToolDep returns a toolDepPath representing the given path string.
1205// There is no validation for the path, as it is "trusted": It may fail
1206// normal validation checks. For example, it may be an absolute path.
1207// Only use this function to construct paths for dependencies of the build
1208// tool invocation.
1209func pathForBuildToolDep(ctx PathContext, path string) toolDepPath {
Paul Duffin74abc5d2021-03-24 09:24:59 +00001210 return toolDepPath{basePath{path, ""}}
Chris Parsons8f232a22020-06-23 17:37:05 -04001211}
1212
Jeff Gaston734e3802017-04-10 15:47:24 -07001213// PathForOutput joins the provided paths and returns an OutputPath that is
1214// validated to not escape the build dir.
1215// On error, it will return a usable, but invalid OutputPath, and report a ModuleError.
1216func PathForOutput(ctx PathContext, pathComponents ...string) OutputPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001217 path, err := validatePath(pathComponents...)
1218 if err != nil {
1219 reportPathError(ctx, err)
1220 }
Colin Crossd63c9a72020-01-29 16:52:50 -08001221 fullPath := filepath.Join(ctx.Config().buildDir, path)
1222 path = fullPath[len(fullPath)-len(path):]
Paul Duffin74abc5d2021-03-24 09:24:59 +00001223 return OutputPath{basePath{path, ""}, ctx.Config().buildDir, fullPath}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001224}
1225
Colin Cross40e33732019-02-15 11:08:35 -08001226// PathsForOutput returns Paths rooted from buildDir
1227func PathsForOutput(ctx PathContext, paths []string) WritablePaths {
1228 ret := make(WritablePaths, len(paths))
1229 for i, path := range paths {
1230 ret[i] = PathForOutput(ctx, path)
1231 }
1232 return ret
1233}
1234
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001235func (p OutputPath) writablePath() {}
1236
1237func (p OutputPath) String() string {
Colin Crossd63c9a72020-01-29 16:52:50 -08001238 return p.fullPath
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001239}
1240
1241// Join creates a new OutputPath with paths... joined with the current path. The
1242// provided paths... may not use '..' to escape from the current path.
1243func (p OutputPath) Join(ctx PathContext, paths ...string) OutputPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001244 path, err := validatePath(paths...)
1245 if err != nil {
1246 reportPathError(ctx, err)
1247 }
Colin Cross0db55682017-12-05 15:36:55 -08001248 return p.withRel(path)
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001249}
1250
Colin Cross8854a5a2019-02-11 14:14:16 -08001251// ReplaceExtension creates a new OutputPath with the extension replaced with ext.
1252func (p OutputPath) ReplaceExtension(ctx PathContext, ext string) OutputPath {
1253 if strings.Contains(ext, "/") {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001254 ReportPathErrorf(ctx, "extension %q cannot contain /", ext)
Colin Cross8854a5a2019-02-11 14:14:16 -08001255 }
1256 ret := PathForOutput(ctx, pathtools.ReplaceExtension(p.path, ext))
Colin Cross2cdd5df2019-02-25 10:25:24 -08001257 ret.rel = pathtools.ReplaceExtension(p.rel, ext)
Colin Cross8854a5a2019-02-11 14:14:16 -08001258 return ret
1259}
1260
Colin Cross40e33732019-02-15 11:08:35 -08001261// InSameDir creates a new OutputPath from the directory of the current OutputPath joined with the elements in paths.
1262func (p OutputPath) InSameDir(ctx PathContext, paths ...string) OutputPath {
1263 path, err := validatePath(paths...)
1264 if err != nil {
1265 reportPathError(ctx, err)
1266 }
1267
1268 ret := PathForOutput(ctx, filepath.Dir(p.path), path)
Colin Cross2cdd5df2019-02-25 10:25:24 -08001269 ret.rel = filepath.Join(filepath.Dir(p.rel), path)
Colin Cross40e33732019-02-15 11:08:35 -08001270 return ret
1271}
1272
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001273// PathForIntermediates returns an OutputPath representing the top-level
1274// intermediates directory.
1275func PathForIntermediates(ctx PathContext, paths ...string) OutputPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001276 path, err := validatePath(paths...)
1277 if err != nil {
1278 reportPathError(ctx, err)
1279 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001280 return PathForOutput(ctx, ".intermediates", path)
1281}
1282
Colin Cross07e51612019-03-05 12:46:40 -08001283var _ genPathProvider = SourcePath{}
1284var _ objPathProvider = SourcePath{}
1285var _ resPathProvider = SourcePath{}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001286
Colin Cross07e51612019-03-05 12:46:40 -08001287// PathForModuleSrc returns a Path representing the paths... under the
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001288// module's local source directory.
Liz Kammera830f3a2020-11-10 10:50:34 -08001289func PathForModuleSrc(ctx ModuleMissingDepsPathContext, pathComponents ...string) Path {
Paul Duffin407501b2021-07-09 16:56:35 +01001290 // Just join the components textually just to make sure that it does not corrupt a fully qualified
1291 // module reference, e.g. if the pathComponents is "://other:foo" then using filepath.Join() or
1292 // validatePath() will corrupt it, e.g. replace "//" with "/". If the path is not a module
1293 // reference then it will be validated by expandOneSrcPath anyway when it calls expandOneSrcPath.
1294 p := strings.Join(pathComponents, string(filepath.Separator))
Colin Cross8a497952019-03-05 22:25:09 -08001295 paths, err := expandOneSrcPath(ctx, p, nil)
1296 if err != nil {
1297 if depErr, ok := err.(missingDependencyError); ok {
1298 if ctx.Config().AllowMissingDependencies() {
1299 ctx.AddMissingDependencies(depErr.missingDeps)
1300 } else {
1301 ctx.ModuleErrorf(`%s, is the property annotated with android:"path"?`, depErr.Error())
1302 }
1303 } else {
1304 reportPathError(ctx, err)
1305 }
1306 return nil
1307 } else if len(paths) == 0 {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001308 ReportPathErrorf(ctx, "%q produced no files, expected exactly one", p)
Colin Cross8a497952019-03-05 22:25:09 -08001309 return nil
1310 } else if len(paths) > 1 {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001311 ReportPathErrorf(ctx, "%q produced %d files, expected exactly one", p, len(paths))
Colin Cross8a497952019-03-05 22:25:09 -08001312 }
1313 return paths[0]
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001314}
1315
Liz Kammera830f3a2020-11-10 10:50:34 -08001316func pathForModuleSrc(ctx EarlyModulePathContext, paths ...string) SourcePath {
Colin Cross07e51612019-03-05 12:46:40 -08001317 p, err := validatePath(paths...)
1318 if err != nil {
1319 reportPathError(ctx, err)
1320 }
1321
1322 path, err := pathForSource(ctx, ctx.ModuleDir(), p)
1323 if err != nil {
1324 reportPathError(ctx, err)
1325 }
1326
1327 path.basePath.rel = p
1328
1329 return path
1330}
1331
Colin Cross2fafa3e2019-03-05 12:39:51 -08001332// PathsWithModuleSrcSubDir takes a list of Paths and returns a new list of Paths where Rel() on each path
1333// will return the path relative to subDir in the module's source directory. If any input paths are not located
1334// inside subDir then a path error will be reported.
Liz Kammera830f3a2020-11-10 10:50:34 -08001335func PathsWithModuleSrcSubDir(ctx EarlyModulePathContext, paths Paths, subDir string) Paths {
Colin Cross2fafa3e2019-03-05 12:39:51 -08001336 paths = append(Paths(nil), paths...)
Colin Cross07e51612019-03-05 12:46:40 -08001337 subDirFullPath := pathForModuleSrc(ctx, subDir)
Colin Cross2fafa3e2019-03-05 12:39:51 -08001338 for i, path := range paths {
1339 rel := Rel(ctx, subDirFullPath.String(), path.String())
1340 paths[i] = subDirFullPath.join(ctx, rel)
1341 }
1342 return paths
1343}
1344
1345// PathWithModuleSrcSubDir takes a Path and returns a Path where Rel() will return the path relative to subDir in the
1346// 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 -08001347func PathWithModuleSrcSubDir(ctx EarlyModulePathContext, path Path, subDir string) Path {
Colin Cross07e51612019-03-05 12:46:40 -08001348 subDirFullPath := pathForModuleSrc(ctx, subDir)
Colin Cross2fafa3e2019-03-05 12:39:51 -08001349 rel := Rel(ctx, subDirFullPath.String(), path.String())
1350 return subDirFullPath.Join(ctx, rel)
1351}
1352
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001353// OptionalPathForModuleSrc returns an OptionalPath. The OptionalPath contains a
1354// valid path if p is non-nil.
Liz Kammera830f3a2020-11-10 10:50:34 -08001355func OptionalPathForModuleSrc(ctx ModuleMissingDepsPathContext, p *string) OptionalPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001356 if p == nil {
1357 return OptionalPath{}
1358 }
1359 return OptionalPathForPath(PathForModuleSrc(ctx, *p))
1360}
1361
Liz Kammera830f3a2020-11-10 10:50:34 -08001362func (p SourcePath) genPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleGenPath {
Colin Cross7fc17db2017-02-01 14:07:55 -08001363 return PathForModuleGen(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001364}
1365
Liz Kammera830f3a2020-11-10 10:50:34 -08001366func (p SourcePath) objPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleObjPath {
Colin Cross7fc17db2017-02-01 14:07:55 -08001367 return PathForModuleObj(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001368}
1369
Liz Kammera830f3a2020-11-10 10:50:34 -08001370func (p SourcePath) resPathWithName(ctx ModuleOutPathContext, name string) ModuleResPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001371 // TODO: Use full directory if the new ctx is not the current ctx?
1372 return PathForModuleRes(ctx, p.path, name)
1373}
1374
1375// ModuleOutPath is a Path representing a module's output directory.
1376type ModuleOutPath struct {
1377 OutputPath
1378}
1379
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001380func (p ModuleOutPath) RelativeToTop() Path {
1381 p.OutputPath = p.outputPathRelativeToTop()
1382 return p
1383}
1384
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001385var _ Path = ModuleOutPath{}
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001386var _ WritablePath = ModuleOutPath{}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001387
Liz Kammera830f3a2020-11-10 10:50:34 -08001388func (p ModuleOutPath) objPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleObjPath {
Pete Bentleyfcf55bf2019-08-16 20:14:32 +01001389 return PathForModuleObj(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
1390}
1391
Liz Kammera830f3a2020-11-10 10:50:34 -08001392// ModuleOutPathContext Subset of ModuleContext functions necessary for output path methods.
1393type ModuleOutPathContext interface {
1394 PathContext
1395
1396 ModuleName() string
1397 ModuleDir() string
1398 ModuleSubDir() string
1399}
1400
1401func pathForModuleOut(ctx ModuleOutPathContext) OutputPath {
Colin Cross702e0f82017-10-18 17:27:54 -07001402 return PathForOutput(ctx, ".intermediates", ctx.ModuleDir(), ctx.ModuleName(), ctx.ModuleSubDir())
1403}
1404
Logan Chien7eefdc42018-07-11 18:10:41 +08001405// PathForVndkRefAbiDump returns an OptionalPath representing the path of the
1406// reference abi dump for the given module. This is not guaranteed to be valid.
Liz Kammera830f3a2020-11-10 10:50:34 -08001407func PathForVndkRefAbiDump(ctx ModuleInstallPathContext, version, fileName string,
Hsin-Yi Chen53489642019-07-31 17:10:45 +08001408 isNdk, isLlndkOrVndk, isGzip bool) OptionalPath {
Logan Chien7eefdc42018-07-11 18:10:41 +08001409
Jayant Chowdharyac066c62018-02-20 10:53:31 -08001410 arches := ctx.DeviceConfig().Arches()
Logan Chien7eefdc42018-07-11 18:10:41 +08001411 if len(arches) == 0 {
1412 panic("device build with no primary arch")
1413 }
Jayant Chowdharyac066c62018-02-20 10:53:31 -08001414 currentArch := ctx.Arch()
1415 archNameAndVariant := currentArch.ArchType.String()
1416 if currentArch.ArchVariant != "" {
1417 archNameAndVariant += "_" + currentArch.ArchVariant
1418 }
Logan Chien5237bed2018-07-11 17:15:57 +08001419
1420 var dirName string
Hsin-Yi Chen53489642019-07-31 17:10:45 +08001421 if isNdk {
Logan Chien5237bed2018-07-11 17:15:57 +08001422 dirName = "ndk"
Hsin-Yi Chen53489642019-07-31 17:10:45 +08001423 } else if isLlndkOrVndk {
Logan Chien5237bed2018-07-11 17:15:57 +08001424 dirName = "vndk"
Logan Chien41eabe62019-04-10 13:33:58 +08001425 } else {
1426 dirName = "platform" // opt-in libs
Jayant Chowdhary3e231fd2017-02-08 13:45:53 -08001427 }
Logan Chien5237bed2018-07-11 17:15:57 +08001428
Jayant Chowdhary34ce67d2018-03-08 11:00:50 -08001429 binderBitness := ctx.DeviceConfig().BinderBitness()
Logan Chien7eefdc42018-07-11 18:10:41 +08001430
1431 var ext string
1432 if isGzip {
1433 ext = ".lsdump.gz"
1434 } else {
1435 ext = ".lsdump"
1436 }
1437
1438 return ExistentPathForSource(ctx, "prebuilts", "abi-dumps", dirName,
1439 version, binderBitness, archNameAndVariant, "source-based",
1440 fileName+ext)
Jayant Chowdhary3e231fd2017-02-08 13:45:53 -08001441}
1442
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001443// PathForModuleOut returns a Path representing the paths... under the module's
1444// output directory.
Liz Kammera830f3a2020-11-10 10:50:34 -08001445func PathForModuleOut(ctx ModuleOutPathContext, paths ...string) ModuleOutPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001446 p, err := validatePath(paths...)
1447 if err != nil {
1448 reportPathError(ctx, err)
1449 }
Colin Cross702e0f82017-10-18 17:27:54 -07001450 return ModuleOutPath{
Liz Kammera830f3a2020-11-10 10:50:34 -08001451 OutputPath: pathForModuleOut(ctx).withRel(p),
Colin Cross702e0f82017-10-18 17:27:54 -07001452 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001453}
1454
1455// ModuleGenPath is a Path representing the 'gen' directory in a module's output
1456// directory. Mainly used for generated sources.
1457type ModuleGenPath struct {
1458 ModuleOutPath
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001459}
1460
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001461func (p ModuleGenPath) RelativeToTop() Path {
1462 p.OutputPath = p.outputPathRelativeToTop()
1463 return p
1464}
1465
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001466var _ Path = ModuleGenPath{}
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001467var _ WritablePath = ModuleGenPath{}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001468var _ genPathProvider = ModuleGenPath{}
1469var _ objPathProvider = ModuleGenPath{}
1470
1471// PathForModuleGen returns a Path representing the paths... under the module's
1472// `gen' directory.
Liz Kammera830f3a2020-11-10 10:50:34 -08001473func PathForModuleGen(ctx ModuleOutPathContext, paths ...string) ModuleGenPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001474 p, err := validatePath(paths...)
1475 if err != nil {
1476 reportPathError(ctx, err)
1477 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001478 return ModuleGenPath{
Colin Cross702e0f82017-10-18 17:27:54 -07001479 ModuleOutPath: ModuleOutPath{
Liz Kammera830f3a2020-11-10 10:50:34 -08001480 OutputPath: pathForModuleOut(ctx).withRel("gen").withRel(p),
Colin Cross702e0f82017-10-18 17:27:54 -07001481 },
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001482 }
1483}
1484
Liz Kammera830f3a2020-11-10 10:50:34 -08001485func (p ModuleGenPath) genPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleGenPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001486 // TODO: make a different path for local vs remote generated files?
Dan Willemsen21ec4902016-11-02 20:43:13 -07001487 return PathForModuleGen(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001488}
1489
Liz Kammera830f3a2020-11-10 10:50:34 -08001490func (p ModuleGenPath) objPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleObjPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001491 return PathForModuleObj(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
1492}
1493
1494// ModuleObjPath is a Path representing the 'obj' directory in a module's output
1495// directory. Used for compiled objects.
1496type ModuleObjPath struct {
1497 ModuleOutPath
1498}
1499
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001500func (p ModuleObjPath) RelativeToTop() Path {
1501 p.OutputPath = p.outputPathRelativeToTop()
1502 return p
1503}
1504
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001505var _ Path = ModuleObjPath{}
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001506var _ WritablePath = ModuleObjPath{}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001507
1508// PathForModuleObj returns a Path representing the paths... under the module's
1509// 'obj' directory.
Liz Kammera830f3a2020-11-10 10:50:34 -08001510func PathForModuleObj(ctx ModuleOutPathContext, pathComponents ...string) ModuleObjPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001511 p, err := validatePath(pathComponents...)
1512 if err != nil {
1513 reportPathError(ctx, err)
1514 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001515 return ModuleObjPath{PathForModuleOut(ctx, "obj", p)}
1516}
1517
1518// ModuleResPath is a a Path representing the 'res' directory in a module's
1519// output directory.
1520type ModuleResPath struct {
1521 ModuleOutPath
1522}
1523
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001524func (p ModuleResPath) RelativeToTop() Path {
1525 p.OutputPath = p.outputPathRelativeToTop()
1526 return p
1527}
1528
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001529var _ Path = ModuleResPath{}
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001530var _ WritablePath = ModuleResPath{}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001531
1532// PathForModuleRes returns a Path representing the paths... under the module's
1533// 'res' directory.
Liz Kammera830f3a2020-11-10 10:50:34 -08001534func PathForModuleRes(ctx ModuleOutPathContext, pathComponents ...string) ModuleResPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001535 p, err := validatePath(pathComponents...)
1536 if err != nil {
1537 reportPathError(ctx, err)
1538 }
1539
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001540 return ModuleResPath{PathForModuleOut(ctx, "res", p)}
1541}
1542
Colin Cross70dda7e2019-10-01 22:05:35 -07001543// InstallPath is a Path representing a installed file path rooted from the build directory
1544type InstallPath struct {
1545 basePath
Colin Crossff6c33d2019-10-02 16:01:35 -07001546
Paul Duffind65c58b2021-03-24 09:22:07 +00001547 // The soong build directory, i.e. Config.BuildDir()
1548 buildDir string
1549
Jiyong Park957bcd92020-10-20 18:23:33 +09001550 // partitionDir is the part of the InstallPath that is automatically determined according to the context.
1551 // For example, it is host/<os>-<arch> for host modules, and target/product/<device>/<partition> for device modules.
1552 partitionDir string
1553
1554 // makePath indicates whether this path is for Soong (false) or Make (true).
1555 makePath bool
Colin Cross70dda7e2019-10-01 22:05:35 -07001556}
1557
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001558// Will panic if called from outside a test environment.
1559func ensureTestOnly() {
Martin Stjernholm32312eb2021-03-27 18:54:49 +00001560 if PrefixInList(os.Args, "-test.") {
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001561 return
1562 }
Martin Stjernholm32312eb2021-03-27 18:54:49 +00001563 panic(fmt.Errorf("Not in test. Command line:\n %s", strings.Join(os.Args, "\n ")))
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001564}
1565
1566func (p InstallPath) RelativeToTop() Path {
1567 ensureTestOnly()
1568 p.buildDir = OutSoongDir
1569 return p
1570}
1571
Paul Duffind65c58b2021-03-24 09:22:07 +00001572func (p InstallPath) getBuildDir() string {
1573 return p.buildDir
Paul Duffin9b478b02019-12-10 13:41:51 +00001574}
1575
Hans MÃ¥nssond3f2bd72020-11-27 12:37:28 +01001576func (p InstallPath) ReplaceExtension(ctx PathContext, ext string) OutputPath {
1577 panic("Not implemented")
1578}
1579
Paul Duffin9b478b02019-12-10 13:41:51 +00001580var _ Path = InstallPath{}
1581var _ WritablePath = InstallPath{}
1582
Colin Cross70dda7e2019-10-01 22:05:35 -07001583func (p InstallPath) writablePath() {}
1584
1585func (p InstallPath) String() string {
Jiyong Park957bcd92020-10-20 18:23:33 +09001586 if p.makePath {
1587 // Make path starts with out/ instead of out/soong.
Paul Duffind65c58b2021-03-24 09:22:07 +00001588 return filepath.Join(p.buildDir, "../", p.path)
Jiyong Park957bcd92020-10-20 18:23:33 +09001589 } else {
Paul Duffind65c58b2021-03-24 09:22:07 +00001590 return filepath.Join(p.buildDir, p.path)
Jiyong Park957bcd92020-10-20 18:23:33 +09001591 }
1592}
1593
1594// PartitionDir returns the path to the partition where the install path is rooted at. It is
1595// out/soong/target/product/<device>/<partition> for device modules, and out/soong/host/<os>-<arch> for host modules.
1596// The ./soong is dropped if the install path is for Make.
1597func (p InstallPath) PartitionDir() string {
1598 if p.makePath {
Paul Duffind65c58b2021-03-24 09:22:07 +00001599 return filepath.Join(p.buildDir, "../", p.partitionDir)
Jiyong Park957bcd92020-10-20 18:23:33 +09001600 } else {
Paul Duffind65c58b2021-03-24 09:22:07 +00001601 return filepath.Join(p.buildDir, p.partitionDir)
Jiyong Park957bcd92020-10-20 18:23:33 +09001602 }
Colin Cross70dda7e2019-10-01 22:05:35 -07001603}
1604
1605// Join creates a new InstallPath with paths... joined with the current path. The
1606// provided paths... may not use '..' to escape from the current path.
1607func (p InstallPath) Join(ctx PathContext, paths ...string) InstallPath {
1608 path, err := validatePath(paths...)
1609 if err != nil {
1610 reportPathError(ctx, err)
1611 }
1612 return p.withRel(path)
1613}
1614
1615func (p InstallPath) withRel(rel string) InstallPath {
1616 p.basePath = p.basePath.withRel(rel)
1617 return p
1618}
1619
Colin Crossff6c33d2019-10-02 16:01:35 -07001620// ToMakePath returns a new InstallPath that points to Make's install directory instead of Soong's,
1621// i.e. out/ instead of out/soong/.
1622func (p InstallPath) ToMakePath() InstallPath {
Jiyong Park957bcd92020-10-20 18:23:33 +09001623 p.makePath = true
Colin Crossff6c33d2019-10-02 16:01:35 -07001624 return p
Colin Cross70dda7e2019-10-01 22:05:35 -07001625}
1626
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001627// PathForModuleInstall returns a Path representing the install path for the
1628// module appended with paths...
Colin Cross70dda7e2019-10-01 22:05:35 -07001629func PathForModuleInstall(ctx ModuleInstallPathContext, pathComponents ...string) InstallPath {
Spandan Das5d1b9292021-06-03 19:36:41 +00001630 os, arch := osAndArch(ctx)
1631 partition := modulePartition(ctx, os)
1632 return makePathForInstall(ctx, os, arch, partition, ctx.Debug(), pathComponents...)
1633}
1634
1635// PathForModuleInPartitionInstall is similar to PathForModuleInstall but partition is provided by the caller
1636func PathForModuleInPartitionInstall(ctx ModuleInstallPathContext, partition string, pathComponents ...string) InstallPath {
1637 os, arch := osAndArch(ctx)
1638 return makePathForInstall(ctx, os, arch, partition, ctx.Debug(), pathComponents...)
1639}
1640
1641func osAndArch(ctx ModuleInstallPathContext) (OsType, ArchType) {
Colin Cross6e359402020-02-10 15:29:54 -08001642 os := ctx.Os()
Jiyong Park87788b52020-09-01 12:37:45 +09001643 arch := ctx.Arch().ArchType
1644 forceOS, forceArch := ctx.InstallForceOS()
1645 if forceOS != nil {
Colin Cross6e359402020-02-10 15:29:54 -08001646 os = *forceOS
1647 }
Jiyong Park87788b52020-09-01 12:37:45 +09001648 if forceArch != nil {
1649 arch = *forceArch
1650 }
Spandan Das5d1b9292021-06-03 19:36:41 +00001651 return os, arch
1652}
Colin Cross609c49a2020-02-13 13:20:11 -08001653
Spandan Das5d1b9292021-06-03 19:36:41 +00001654func makePathForInstall(ctx ModuleInstallPathContext, os OsType, arch ArchType, partition string, debug bool, pathComponents ...string) InstallPath {
1655 ret := pathForInstall(ctx, os, arch, partition, debug, pathComponents...)
Jingwen Chencda22c92020-11-23 00:22:30 -05001656 if ctx.InstallBypassMake() && ctx.Config().KatiEnabled() {
Colin Cross609c49a2020-02-13 13:20:11 -08001657 ret = ret.ToMakePath()
1658 }
Colin Cross609c49a2020-02-13 13:20:11 -08001659 return ret
1660}
1661
Jiyong Park87788b52020-09-01 12:37:45 +09001662func pathForInstall(ctx PathContext, os OsType, arch ArchType, partition string, debug bool,
Colin Cross609c49a2020-02-13 13:20:11 -08001663 pathComponents ...string) InstallPath {
1664
Jiyong Park957bcd92020-10-20 18:23:33 +09001665 var partionPaths []string
Colin Cross609c49a2020-02-13 13:20:11 -08001666
Colin Cross6e359402020-02-10 15:29:54 -08001667 if os.Class == Device {
Jiyong Park957bcd92020-10-20 18:23:33 +09001668 partionPaths = []string{"target", "product", ctx.Config().DeviceName(), partition}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001669 } else {
Jiyong Park87788b52020-09-01 12:37:45 +09001670 osName := os.String()
Colin Cross528d67e2021-07-23 22:23:07 +00001671 if os == Linux || os == LinuxMusl {
Jiyong Park87788b52020-09-01 12:37:45 +09001672 // instead of linux_glibc
1673 osName = "linux"
Dan Willemsen866b5632017-09-22 12:28:24 -07001674 }
Jiyong Park87788b52020-09-01 12:37:45 +09001675 // SOONG_HOST_OUT is set to out/host/$(HOST_OS)-$(HOST_PREBUILT_ARCH)
1676 // and HOST_PREBUILT_ARCH is forcibly set to x86 even on x86_64 hosts. We don't seem
1677 // to have a plan to fix it (see the comment in build/make/core/envsetup.mk).
1678 // Let's keep using x86 for the existing cases until we have a need to support
1679 // other architectures.
1680 archName := arch.String()
1681 if os.Class == Host && (arch == X86_64 || arch == Common) {
1682 archName = "x86"
1683 }
Jiyong Park957bcd92020-10-20 18:23:33 +09001684 partionPaths = []string{"host", osName + "-" + archName, partition}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001685 }
Colin Cross609c49a2020-02-13 13:20:11 -08001686 if debug {
Jiyong Park957bcd92020-10-20 18:23:33 +09001687 partionPaths = append([]string{"debug"}, partionPaths...)
Dan Willemsen782a2d12015-12-21 14:55:28 -08001688 }
Colin Cross70dda7e2019-10-01 22:05:35 -07001689
Jiyong Park957bcd92020-10-20 18:23:33 +09001690 partionPath, err := validatePath(partionPaths...)
Colin Cross70dda7e2019-10-01 22:05:35 -07001691 if err != nil {
1692 reportPathError(ctx, err)
1693 }
Colin Crossff6c33d2019-10-02 16:01:35 -07001694
Jiyong Park957bcd92020-10-20 18:23:33 +09001695 base := InstallPath{
Paul Duffin74abc5d2021-03-24 09:24:59 +00001696 basePath: basePath{partionPath, ""},
Paul Duffind65c58b2021-03-24 09:22:07 +00001697 buildDir: ctx.Config().buildDir,
Jiyong Park957bcd92020-10-20 18:23:33 +09001698 partitionDir: partionPath,
1699 makePath: false,
1700 }
Colin Crossff6c33d2019-10-02 16:01:35 -07001701
Jiyong Park957bcd92020-10-20 18:23:33 +09001702 return base.Join(ctx, pathComponents...)
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001703}
1704
Nicolas Geoffray1228e9c2020-02-27 13:45:35 +00001705func pathForNdkOrSdkInstall(ctx PathContext, prefix string, paths []string) InstallPath {
Jiyong Park957bcd92020-10-20 18:23:33 +09001706 base := InstallPath{
Paul Duffin74abc5d2021-03-24 09:24:59 +00001707 basePath: basePath{prefix, ""},
Paul Duffind65c58b2021-03-24 09:22:07 +00001708 buildDir: ctx.Config().buildDir,
Jiyong Park957bcd92020-10-20 18:23:33 +09001709 partitionDir: prefix,
1710 makePath: false,
Colin Cross70dda7e2019-10-01 22:05:35 -07001711 }
Jiyong Park957bcd92020-10-20 18:23:33 +09001712 return base.Join(ctx, paths...)
Colin Cross70dda7e2019-10-01 22:05:35 -07001713}
1714
Nicolas Geoffray1228e9c2020-02-27 13:45:35 +00001715func PathForNdkInstall(ctx PathContext, paths ...string) InstallPath {
1716 return pathForNdkOrSdkInstall(ctx, "ndk", paths)
1717}
1718
1719func PathForMainlineSdksInstall(ctx PathContext, paths ...string) InstallPath {
1720 return pathForNdkOrSdkInstall(ctx, "mainline-sdks", paths)
1721}
1722
Colin Cross70dda7e2019-10-01 22:05:35 -07001723func InstallPathToOnDevicePath(ctx PathContext, path InstallPath) string {
Colin Cross43f08db2018-11-12 10:13:39 -08001724 rel := Rel(ctx, PathForOutput(ctx, "target", "product", ctx.Config().DeviceName()).String(), path.String())
1725
1726 return "/" + rel
1727}
1728
Colin Cross6e359402020-02-10 15:29:54 -08001729func modulePartition(ctx ModuleInstallPathContext, os OsType) string {
Colin Cross43f08db2018-11-12 10:13:39 -08001730 var partition string
Colin Cross6e359402020-02-10 15:29:54 -08001731 if ctx.InstallInTestcases() {
1732 // "testcases" install directory can be used for host or device modules.
Jaewoong Jung0949f312019-09-11 10:25:18 -07001733 partition = "testcases"
Colin Cross6e359402020-02-10 15:29:54 -08001734 } else if os.Class == Device {
1735 if ctx.InstallInData() {
1736 partition = "data"
1737 } else if ctx.InstallInRamdisk() {
1738 if ctx.DeviceConfig().BoardUsesRecoveryAsBoot() {
1739 partition = "recovery/root/first_stage_ramdisk"
1740 } else {
1741 partition = "ramdisk"
1742 }
1743 if !ctx.InstallInRoot() {
1744 partition += "/system"
1745 }
Yifan Hong60e0cfb2020-10-21 15:17:56 -07001746 } else if ctx.InstallInVendorRamdisk() {
Yifan Hong39143a92020-10-26 12:43:12 -07001747 // The module is only available after switching root into
1748 // /first_stage_ramdisk. To expose the module before switching root
1749 // on a device without a dedicated recovery partition, install the
1750 // recovery variant.
Yifan Hongdd8dacc2020-10-21 15:40:17 -07001751 if ctx.DeviceConfig().BoardMoveRecoveryResourcesToVendorBoot() {
Petri Gyntherac229562021-03-02 23:44:02 -08001752 partition = "vendor_ramdisk/first_stage_ramdisk"
Yifan Hongdd8dacc2020-10-21 15:40:17 -07001753 } else {
Petri Gyntherac229562021-03-02 23:44:02 -08001754 partition = "vendor_ramdisk"
Yifan Hongdd8dacc2020-10-21 15:40:17 -07001755 }
1756 if !ctx.InstallInRoot() {
1757 partition += "/system"
1758 }
Inseob Kim08758f02021-04-08 21:13:22 +09001759 } else if ctx.InstallInDebugRamdisk() {
1760 partition = "debug_ramdisk"
Colin Cross6e359402020-02-10 15:29:54 -08001761 } else if ctx.InstallInRecovery() {
1762 if ctx.InstallInRoot() {
1763 partition = "recovery/root"
1764 } else {
1765 // the layout of recovery partion is the same as that of system partition
1766 partition = "recovery/root/system"
1767 }
1768 } else if ctx.SocSpecific() {
1769 partition = ctx.DeviceConfig().VendorPath()
1770 } else if ctx.DeviceSpecific() {
1771 partition = ctx.DeviceConfig().OdmPath()
1772 } else if ctx.ProductSpecific() {
1773 partition = ctx.DeviceConfig().ProductPath()
1774 } else if ctx.SystemExtSpecific() {
1775 partition = ctx.DeviceConfig().SystemExtPath()
1776 } else if ctx.InstallInRoot() {
1777 partition = "root"
Yifan Hong82db7352020-01-21 16:12:26 -08001778 } else {
Colin Cross6e359402020-02-10 15:29:54 -08001779 partition = "system"
Yifan Hong82db7352020-01-21 16:12:26 -08001780 }
Colin Cross6e359402020-02-10 15:29:54 -08001781 if ctx.InstallInSanitizerDir() {
1782 partition = "data/asan/" + partition
Yifan Hong82db7352020-01-21 16:12:26 -08001783 }
Colin Cross43f08db2018-11-12 10:13:39 -08001784 }
1785 return partition
1786}
1787
Colin Cross609c49a2020-02-13 13:20:11 -08001788type InstallPaths []InstallPath
1789
1790// Paths returns the InstallPaths as a Paths
1791func (p InstallPaths) Paths() Paths {
1792 if p == nil {
1793 return nil
1794 }
1795 ret := make(Paths, len(p))
1796 for i, path := range p {
1797 ret[i] = path
1798 }
1799 return ret
1800}
1801
1802// Strings returns the string forms of the install paths.
1803func (p InstallPaths) Strings() []string {
1804 if p == nil {
1805 return nil
1806 }
1807 ret := make([]string, len(p))
1808 for i, path := range p {
1809 ret[i] = path.String()
1810 }
1811 return ret
1812}
1813
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001814// validateSafePath validates a path that we trust (may contain ninja variables).
Dan Willemsen80a7c2a2015-12-21 14:57:11 -08001815// Ensures that each path component does not attempt to leave its component.
Colin Cross1ccfcc32018-02-22 13:54:26 -08001816func validateSafePath(pathComponents ...string) (string, error) {
Jeff Gaston734e3802017-04-10 15:47:24 -07001817 for _, path := range pathComponents {
Dan Willemsen80a7c2a2015-12-21 14:57:11 -08001818 path := filepath.Clean(path)
1819 if path == ".." || strings.HasPrefix(path, "../") || strings.HasPrefix(path, "/") {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001820 return "", fmt.Errorf("Path is outside directory: %s", path)
Dan Willemsen80a7c2a2015-12-21 14:57:11 -08001821 }
1822 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001823 // TODO: filepath.Join isn't necessarily correct with embedded ninja
1824 // variables. '..' may remove the entire ninja variable, even if it
1825 // will be expanded to multiple nested directories.
Colin Cross1ccfcc32018-02-22 13:54:26 -08001826 return filepath.Join(pathComponents...), nil
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001827}
1828
Dan Willemsen80a7c2a2015-12-21 14:57:11 -08001829// validatePath validates that a path does not include ninja variables, and that
1830// each path component does not attempt to leave its component. Returns a joined
1831// version of each path component.
Colin Cross1ccfcc32018-02-22 13:54:26 -08001832func validatePath(pathComponents ...string) (string, error) {
Jeff Gaston734e3802017-04-10 15:47:24 -07001833 for _, path := range pathComponents {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001834 if strings.Contains(path, "$") {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001835 return "", fmt.Errorf("Path contains invalid character($): %s", path)
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001836 }
1837 }
Colin Cross1ccfcc32018-02-22 13:54:26 -08001838 return validateSafePath(pathComponents...)
Colin Cross6e18ca42015-07-14 18:55:36 -07001839}
Colin Cross5b529592017-05-09 13:34:34 -07001840
Colin Cross0875c522017-11-28 17:34:01 -08001841func PathForPhony(ctx PathContext, phony string) WritablePath {
1842 if strings.ContainsAny(phony, "$/") {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001843 ReportPathErrorf(ctx, "Phony target contains invalid character ($ or /): %s", phony)
Colin Cross0875c522017-11-28 17:34:01 -08001844 }
Paul Duffin74abc5d2021-03-24 09:24:59 +00001845 return PhonyPath{basePath{phony, ""}}
Colin Cross0875c522017-11-28 17:34:01 -08001846}
1847
Colin Cross74e3fe42017-12-11 15:51:44 -08001848type PhonyPath struct {
1849 basePath
1850}
1851
1852func (p PhonyPath) writablePath() {}
1853
Paul Duffind65c58b2021-03-24 09:22:07 +00001854func (p PhonyPath) getBuildDir() string {
1855 // A phone path cannot contain any / so cannot be relative to the build directory.
1856 return ""
Paul Duffin9b478b02019-12-10 13:41:51 +00001857}
1858
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001859func (p PhonyPath) RelativeToTop() Path {
1860 ensureTestOnly()
1861 // A phony path cannot contain any / so does not have a build directory so switching to a new
1862 // build directory has no effect so just return this path.
1863 return p
1864}
1865
Hans MÃ¥nssond3f2bd72020-11-27 12:37:28 +01001866func (p PhonyPath) ReplaceExtension(ctx PathContext, ext string) OutputPath {
1867 panic("Not implemented")
1868}
1869
Colin Cross74e3fe42017-12-11 15:51:44 -08001870var _ Path = PhonyPath{}
1871var _ WritablePath = PhonyPath{}
1872
Colin Cross5b529592017-05-09 13:34:34 -07001873type testPath struct {
1874 basePath
1875}
1876
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001877func (p testPath) RelativeToTop() Path {
1878 ensureTestOnly()
1879 return p
1880}
1881
Colin Cross5b529592017-05-09 13:34:34 -07001882func (p testPath) String() string {
1883 return p.path
1884}
1885
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001886var _ Path = testPath{}
1887
Colin Cross40e33732019-02-15 11:08:35 -08001888// PathForTesting returns a Path constructed from joining the elements of paths with '/'. It should only be used from
1889// within tests.
Colin Cross5b529592017-05-09 13:34:34 -07001890func PathForTesting(paths ...string) Path {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001891 p, err := validateSafePath(paths...)
1892 if err != nil {
1893 panic(err)
1894 }
Colin Cross5b529592017-05-09 13:34:34 -07001895 return testPath{basePath{path: p, rel: p}}
1896}
1897
Colin Cross40e33732019-02-15 11:08:35 -08001898// PathsForTesting returns a Path constructed from each element in strs. It should only be used from within tests.
1899func PathsForTesting(strs ...string) Paths {
Colin Cross5b529592017-05-09 13:34:34 -07001900 p := make(Paths, len(strs))
1901 for i, s := range strs {
1902 p[i] = PathForTesting(s)
1903 }
1904
1905 return p
1906}
Colin Cross43f08db2018-11-12 10:13:39 -08001907
Colin Cross40e33732019-02-15 11:08:35 -08001908type testPathContext struct {
1909 config Config
Colin Cross40e33732019-02-15 11:08:35 -08001910}
1911
Colin Cross40e33732019-02-15 11:08:35 -08001912func (x *testPathContext) Config() Config { return x.config }
1913func (x *testPathContext) AddNinjaFileDeps(...string) {}
1914
1915// PathContextForTesting returns a PathContext that can be used in tests, for example to create an OutputPath with
1916// PathForOutput.
Colin Cross98be1bb2019-12-13 20:41:13 -08001917func PathContextForTesting(config Config) PathContext {
Colin Cross40e33732019-02-15 11:08:35 -08001918 return &testPathContext{
1919 config: config,
Colin Cross40e33732019-02-15 11:08:35 -08001920 }
1921}
1922
Ulya Trafimovichccc8c852020-10-14 11:29:07 +01001923type testModuleInstallPathContext struct {
1924 baseModuleContext
1925
1926 inData bool
1927 inTestcases bool
1928 inSanitizerDir bool
1929 inRamdisk bool
1930 inVendorRamdisk bool
Inseob Kim08758f02021-04-08 21:13:22 +09001931 inDebugRamdisk bool
Ulya Trafimovichccc8c852020-10-14 11:29:07 +01001932 inRecovery bool
1933 inRoot bool
1934 forceOS *OsType
1935 forceArch *ArchType
1936}
1937
1938func (m testModuleInstallPathContext) Config() Config {
1939 return m.baseModuleContext.config
1940}
1941
1942func (testModuleInstallPathContext) AddNinjaFileDeps(deps ...string) {}
1943
1944func (m testModuleInstallPathContext) InstallInData() bool {
1945 return m.inData
1946}
1947
1948func (m testModuleInstallPathContext) InstallInTestcases() bool {
1949 return m.inTestcases
1950}
1951
1952func (m testModuleInstallPathContext) InstallInSanitizerDir() bool {
1953 return m.inSanitizerDir
1954}
1955
1956func (m testModuleInstallPathContext) InstallInRamdisk() bool {
1957 return m.inRamdisk
1958}
1959
1960func (m testModuleInstallPathContext) InstallInVendorRamdisk() bool {
1961 return m.inVendorRamdisk
1962}
1963
Inseob Kim08758f02021-04-08 21:13:22 +09001964func (m testModuleInstallPathContext) InstallInDebugRamdisk() bool {
1965 return m.inDebugRamdisk
1966}
1967
Ulya Trafimovichccc8c852020-10-14 11:29:07 +01001968func (m testModuleInstallPathContext) InstallInRecovery() bool {
1969 return m.inRecovery
1970}
1971
1972func (m testModuleInstallPathContext) InstallInRoot() bool {
1973 return m.inRoot
1974}
1975
1976func (m testModuleInstallPathContext) InstallBypassMake() bool {
1977 return false
1978}
1979
1980func (m testModuleInstallPathContext) InstallForceOS() (*OsType, *ArchType) {
1981 return m.forceOS, m.forceArch
1982}
1983
1984// Construct a minimal ModuleInstallPathContext for testing. Note that baseModuleContext is
1985// default-initialized, which leaves blueprint.baseModuleContext set to nil, so methods that are
1986// delegated to it will panic.
1987func ModuleInstallPathContextForTesting(config Config) ModuleInstallPathContext {
1988 ctx := &testModuleInstallPathContext{}
1989 ctx.config = config
1990 ctx.os = Android
1991 return ctx
1992}
1993
Colin Cross43f08db2018-11-12 10:13:39 -08001994// Rel performs the same function as filepath.Rel, but reports errors to a PathContext, and reports an error if
1995// targetPath is not inside basePath.
1996func Rel(ctx PathContext, basePath string, targetPath string) string {
1997 rel, isRel := MaybeRel(ctx, basePath, targetPath)
1998 if !isRel {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001999 ReportPathErrorf(ctx, "path %q is not under path %q", targetPath, basePath)
Colin Cross43f08db2018-11-12 10:13:39 -08002000 return ""
2001 }
2002 return rel
2003}
2004
2005// MaybeRel performs the same function as filepath.Rel, but reports errors to a PathContext, and returns false if
2006// targetPath is not inside basePath.
2007func MaybeRel(ctx PathContext, basePath string, targetPath string) (string, bool) {
Dan Willemsen633c5022019-04-12 11:11:38 -07002008 rel, isRel, err := maybeRelErr(basePath, targetPath)
2009 if err != nil {
2010 reportPathError(ctx, err)
2011 }
2012 return rel, isRel
2013}
2014
2015func maybeRelErr(basePath string, targetPath string) (string, bool, error) {
Colin Cross43f08db2018-11-12 10:13:39 -08002016 // filepath.Rel returns an error if one path is absolute and the other is not, handle that case first.
2017 if filepath.IsAbs(basePath) != filepath.IsAbs(targetPath) {
Dan Willemsen633c5022019-04-12 11:11:38 -07002018 return "", false, nil
Colin Cross43f08db2018-11-12 10:13:39 -08002019 }
2020 rel, err := filepath.Rel(basePath, targetPath)
2021 if err != nil {
Dan Willemsen633c5022019-04-12 11:11:38 -07002022 return "", false, err
Colin Cross43f08db2018-11-12 10:13:39 -08002023 } else if rel == ".." || strings.HasPrefix(rel, "../") || strings.HasPrefix(rel, "/") {
Dan Willemsen633c5022019-04-12 11:11:38 -07002024 return "", false, nil
Colin Cross43f08db2018-11-12 10:13:39 -08002025 }
Dan Willemsen633c5022019-04-12 11:11:38 -07002026 return rel, true, nil
Colin Cross43f08db2018-11-12 10:13:39 -08002027}
Colin Cross988414c2020-01-11 01:11:46 +00002028
2029// Writes a file to the output directory. Attempting to write directly to the output directory
2030// will fail due to the sandbox of the soong_build process.
2031func WriteFileToOutputDir(path WritablePath, data []byte, perm os.FileMode) error {
2032 return ioutil.WriteFile(absolutePath(path.String()), data, perm)
2033}
2034
Liz Kammer2dd9ca42020-11-25 16:06:39 -08002035func RemoveAllOutputDir(path WritablePath) error {
2036 return os.RemoveAll(absolutePath(path.String()))
2037}
2038
2039func CreateOutputDirIfNonexistent(path WritablePath, perm os.FileMode) error {
2040 dir := absolutePath(path.String())
Liz Kammer09f947d2021-05-12 14:51:49 -04002041 return createDirIfNonexistent(dir, perm)
2042}
2043
2044func createDirIfNonexistent(dir string, perm os.FileMode) error {
Liz Kammer2dd9ca42020-11-25 16:06:39 -08002045 if _, err := os.Stat(dir); os.IsNotExist(err) {
2046 return os.MkdirAll(dir, os.ModePerm)
2047 } else {
2048 return err
2049 }
2050}
2051
Jingwen Chen78257e52021-05-21 02:34:24 +00002052// absolutePath is deliberately private so that Soong's Go plugins can't use it to find and
2053// read arbitrary files without going through the methods in the current package that track
2054// dependencies.
Colin Cross988414c2020-01-11 01:11:46 +00002055func absolutePath(path string) string {
2056 if filepath.IsAbs(path) {
2057 return path
2058 }
2059 return filepath.Join(absSrcDir, path)
2060}
Chris Parsons216e10a2020-07-09 17:12:52 -04002061
2062// A DataPath represents the path of a file to be used as data, for example
2063// a test library to be installed alongside a test.
2064// The data file should be installed (copied from `<SrcPath>`) to
2065// `<install_root>/<RelativeInstallPath>/<filename>`, or
2066// `<install_root>/<filename>` if RelativeInstallPath is empty.
2067type DataPath struct {
2068 // The path of the data file that should be copied into the data directory
2069 SrcPath Path
2070 // The install path of the data file, relative to the install root.
2071 RelativeInstallPath string
2072}
Colin Crossdcf71b22021-02-01 13:59:03 -08002073
2074// PathsIfNonNil returns a Paths containing only the non-nil input arguments.
2075func PathsIfNonNil(paths ...Path) Paths {
2076 if len(paths) == 0 {
2077 // Fast path for empty argument list
2078 return nil
2079 } else if len(paths) == 1 {
2080 // Fast path for a single argument
2081 if paths[0] != nil {
2082 return paths
2083 } else {
2084 return nil
2085 }
2086 }
2087 ret := make(Paths, 0, len(paths))
2088 for _, path := range paths {
2089 if path != nil {
2090 ret = append(ret, path)
2091 }
2092 }
2093 if len(ret) == 0 {
2094 return nil
2095 }
2096 return ret
2097}
Chris Wailesb2703ad2021-07-30 13:25:42 -07002098
2099var thirdPartyDirPrefixExceptions = []*regexp.Regexp{
2100 regexp.MustCompile("^vendor/[^/]*google[^/]*/"),
2101 regexp.MustCompile("^hardware/google/"),
2102 regexp.MustCompile("^hardware/interfaces/"),
2103 regexp.MustCompile("^hardware/libhardware[^/]*/"),
2104 regexp.MustCompile("^hardware/ril/"),
2105}
2106
2107func IsThirdPartyPath(path string) bool {
2108 thirdPartyDirPrefixes := []string{"external/", "vendor/", "hardware/"}
2109
2110 if HasAnyPrefix(path, thirdPartyDirPrefixes) {
2111 for _, prefix := range thirdPartyDirPrefixExceptions {
2112 if prefix.MatchString(path) {
2113 return false
2114 }
2115 }
2116 return true
2117 }
2118 return false
2119}