blob: 82c8a247196758e7590f712c4098ebfae960ba84 [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.
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +0200189 // out/soong - this is the soongOutDir passed to NewTestConfig()
Paul Duffin85d8f0d2021-03-24 10:18:18 +0000190 // ... - the source files
191 //
192 // This function converts a path so that it appears relative to the ../top/ directory, i.e.
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +0200193 // * Make install paths, which have the pattern "soongOutDir/../<path>" are converted into the top
Paul Duffin85d8f0d2021-03-24 10:18:18 +0000194 // relative path "out/<path>"
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +0200195 // * Soong install paths and other writable paths, which have the pattern "soongOutDir/<path>" are
Paul Duffin85d8f0d2021-03-24 10:18:18 +0000196 // 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.
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +0200214 getSoongOutDir() 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 {
Martin Stjernholmc32dd1c2021-09-15 02:39:00 +0100266 path Path // nil if invalid.
267 invalidReason string // Not applicable if path != nil. "" if the reason is unknown.
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700268}
269
270// OptionalPathForPath returns an OptionalPath containing the path.
271func OptionalPathForPath(path Path) OptionalPath {
Martin Stjernholm2fee27f2021-09-16 14:11:12 +0100272 return OptionalPath{path: path}
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700273}
274
Martin Stjernholmc32dd1c2021-09-15 02:39:00 +0100275// InvalidOptionalPath returns an OptionalPath that is invalid with the given reason.
276func InvalidOptionalPath(reason string) OptionalPath {
277
278 return OptionalPath{invalidReason: reason}
279}
280
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700281// Valid returns whether there is a valid path
282func (p OptionalPath) Valid() bool {
Martin Stjernholm2fee27f2021-09-16 14:11:12 +0100283 return p.path != nil
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700284}
285
286// Path returns the Path embedded in this OptionalPath. You must be sure that
287// there is a valid path, since this method will panic if there is not.
288func (p OptionalPath) Path() Path {
Martin Stjernholm2fee27f2021-09-16 14:11:12 +0100289 if p.path == nil {
Martin Stjernholmc32dd1c2021-09-15 02:39:00 +0100290 msg := "Requesting an invalid path"
291 if p.invalidReason != "" {
292 msg += ": " + p.invalidReason
293 }
294 panic(msg)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700295 }
296 return p.path
297}
298
Martin Stjernholmc32dd1c2021-09-15 02:39:00 +0100299// InvalidReason returns the reason that the optional path is invalid, or "" if it is valid.
300func (p OptionalPath) InvalidReason() string {
301 if p.path != nil {
302 return ""
303 }
304 if p.invalidReason == "" {
305 return "unknown"
306 }
307 return p.invalidReason
308}
309
Paul Duffinef081852021-05-13 11:11:15 +0100310// AsPaths converts the OptionalPath into Paths.
311//
312// It returns nil if this is not valid, or a single length slice containing the Path embedded in
313// this OptionalPath.
314func (p OptionalPath) AsPaths() Paths {
Martin Stjernholm2fee27f2021-09-16 14:11:12 +0100315 if p.path == nil {
Paul Duffinef081852021-05-13 11:11:15 +0100316 return nil
317 }
318 return Paths{p.path}
319}
320
Paul Duffinafdd4062021-03-30 19:44:07 +0100321// RelativeToTop returns an OptionalPath with the path that was embedded having been replaced by the
322// result of calling Path.RelativeToTop on it.
323func (p OptionalPath) RelativeToTop() OptionalPath {
Martin Stjernholm2fee27f2021-09-16 14:11:12 +0100324 if p.path == nil {
Paul Duffina5b81352021-03-28 23:57:19 +0100325 return p
326 }
327 p.path = p.path.RelativeToTop()
328 return p
329}
330
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700331// String returns the string version of the Path, or "" if it isn't valid.
332func (p OptionalPath) String() string {
Martin Stjernholm2fee27f2021-09-16 14:11:12 +0100333 if p.path != nil {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700334 return p.path.String()
335 } else {
336 return ""
Colin Crossf2298272015-05-12 11:36:53 -0700337 }
338}
Colin Cross6e18ca42015-07-14 18:55:36 -0700339
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700340// Paths is a slice of Path objects, with helpers to operate on the collection.
341type Paths []Path
342
Paul Duffin85d8f0d2021-03-24 10:18:18 +0000343// RelativeToTop creates a new Paths containing the result of calling Path.RelativeToTop on each
344// item in this slice.
345func (p Paths) RelativeToTop() Paths {
346 ensureTestOnly()
347 if p == nil {
348 return p
349 }
350 ret := make(Paths, len(p))
351 for i, path := range p {
352 ret[i] = path.RelativeToTop()
353 }
354 return ret
355}
356
Jingwen Chen40fd90a2020-06-15 05:24:19 +0000357func (paths Paths) containsPath(path Path) bool {
358 for _, p := range paths {
359 if p == path {
360 return true
361 }
362 }
363 return false
364}
365
Liz Kammer7aa52882021-02-11 09:16:14 -0500366// PathsForSource returns Paths rooted from SrcDir, *not* rooted from the module's local source
367// directory
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700368func PathsForSource(ctx PathContext, paths []string) Paths {
369 ret := make(Paths, len(paths))
370 for i, path := range paths {
371 ret[i] = PathForSource(ctx, path)
372 }
373 return ret
374}
375
Liz Kammer7aa52882021-02-11 09:16:14 -0500376// ExistentPathsForSources returns a list of Paths rooted from SrcDir, *not* rooted from the
377// module's local source directory, that are found in the tree. If any are not found, they are
378// 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 -0800379func ExistentPathsForSources(ctx PathContext, paths []string) Paths {
Dan Willemsen7b310ee2015-12-18 15:11:17 -0800380 ret := make(Paths, 0, len(paths))
381 for _, path := range paths {
Colin Cross32f38982018-02-22 11:47:25 -0800382 p := ExistentPathForSource(ctx, path)
Dan Willemsen7b310ee2015-12-18 15:11:17 -0800383 if p.Valid() {
384 ret = append(ret, p.Path())
385 }
386 }
387 return ret
388}
389
Liz Kammer620dea62021-04-14 17:36:10 -0400390// PathsForModuleSrc returns a Paths{} containing the resolved references in paths:
391// * filepath, relative to local module directory, resolves as a filepath relative to the local
392// source directory
393// * glob, relative to the local module directory, resolves as filepath(s), relative to the local
394// source directory.
395// * other modules using the ":name{.tag}" syntax. These modules must implement SourceFileProducer
396// or OutputFileProducer. These resolve as a filepath to an output filepath or generated source
397// filepath.
398// Properties passed as the paths argument must have been annotated with struct tag
Colin Cross41955e82019-05-29 14:40:35 -0700399// `android:"path"` so that dependencies on SourceFileProducer modules will have already been handled by the
Liz Kammer620dea62021-04-14 17:36:10 -0400400// path_deps mutator.
401// If a requested module is not found as a dependency:
402// * if ctx.Config().AllowMissingDependencies() is true, this module to be marked as having
403// missing dependencies
404// * otherwise, a ModuleError is thrown.
Liz Kammera830f3a2020-11-10 10:50:34 -0800405func PathsForModuleSrc(ctx ModuleMissingDepsPathContext, paths []string) Paths {
Colin Cross8a497952019-03-05 22:25:09 -0800406 return PathsForModuleSrcExcludes(ctx, paths, nil)
407}
408
Liz Kammer620dea62021-04-14 17:36:10 -0400409// PathsForModuleSrcExcludes returns a Paths{} containing the resolved references in paths, minus
410// those listed in excludes. Elements of paths and excludes are resolved as:
411// * filepath, relative to local module directory, resolves as a filepath relative to the local
412// source directory
413// * glob, relative to the local module directory, resolves as filepath(s), relative to the local
414// source directory. Not valid in excludes.
415// * other modules using the ":name{.tag}" syntax. These modules must implement SourceFileProducer
416// or OutputFileProducer. These resolve as a filepath to an output filepath or generated source
417// filepath.
418// excluding the items (similarly resolved
419// Properties passed as the paths argument must have been annotated with struct tag
420// `android:"path"` so that dependencies on SourceFileProducer modules will have already been handled by the
421// path_deps mutator.
422// If a requested module is not found as a dependency:
423// * if ctx.Config().AllowMissingDependencies() is true, this module to be marked as having
424// missing dependencies
425// * otherwise, a ModuleError is thrown.
Liz Kammera830f3a2020-11-10 10:50:34 -0800426func PathsForModuleSrcExcludes(ctx ModuleMissingDepsPathContext, paths, excludes []string) Paths {
Colin Crossba71a3f2019-03-18 12:12:48 -0700427 ret, missingDeps := PathsAndMissingDepsForModuleSrcExcludes(ctx, paths, excludes)
428 if ctx.Config().AllowMissingDependencies() {
429 ctx.AddMissingDependencies(missingDeps)
430 } else {
431 for _, m := range missingDeps {
432 ctx.ModuleErrorf(`missing dependency on %q, is the property annotated with android:"path"?`, m)
433 }
434 }
435 return ret
436}
437
Ulya Trafimovich4d2eeed2019-11-08 10:54:21 +0000438// OutputPaths is a slice of OutputPath objects, with helpers to operate on the collection.
439type OutputPaths []OutputPath
440
441// Paths returns the OutputPaths as a Paths
442func (p OutputPaths) Paths() Paths {
443 if p == nil {
444 return nil
445 }
446 ret := make(Paths, len(p))
447 for i, path := range p {
448 ret[i] = path
449 }
450 return ret
451}
452
453// Strings returns the string forms of the writable paths.
454func (p OutputPaths) Strings() []string {
455 if p == nil {
456 return nil
457 }
458 ret := make([]string, len(p))
459 for i, path := range p {
460 ret[i] = path.String()
461 }
462 return ret
463}
464
Colin Crossa44551f2021-10-25 15:36:21 -0700465// PathForGoBinary returns the path to the installed location of a bootstrap_go_binary module.
466func PathForGoBinary(ctx PathContext, goBinary bootstrap.GoBinaryTool) Path {
467 goBinaryInstallDir := pathForInstall(ctx, ctx.Config().BuildOS, ctx.Config().BuildArch, "bin", false)
Colin Crossacfcc1f2021-10-25 15:40:32 -0700468 if ctx.Config().KatiEnabled() {
469 goBinaryInstallDir = goBinaryInstallDir.ToMakePath()
470 }
Colin Crossa44551f2021-10-25 15:36:21 -0700471 rel := Rel(ctx, goBinaryInstallDir.String(), goBinary.InstallPath())
472 return goBinaryInstallDir.Join(ctx, rel)
473}
474
Liz Kammera830f3a2020-11-10 10:50:34 -0800475// Expands Paths to a SourceFileProducer or OutputFileProducer module dependency referenced via ":name" or ":name{.tag}" syntax.
476// If the dependency is not found, a missingErrorDependency is returned.
477// If the module dependency is not a SourceFileProducer or OutputFileProducer, appropriate errors will be returned.
478func getPathsFromModuleDep(ctx ModuleWithDepsPathContext, path, moduleName, tag string) (Paths, error) {
Paul Duffind5cf92e2021-07-09 17:38:55 +0100479 module := GetModuleFromPathDep(ctx, moduleName, tag)
Liz Kammera830f3a2020-11-10 10:50:34 -0800480 if module == nil {
481 return nil, missingDependencyError{[]string{moduleName}}
482 }
Colin Crossfa65cee2021-03-22 17:05:59 -0700483 if aModule, ok := module.(Module); ok && !aModule.Enabled() {
484 return nil, missingDependencyError{[]string{moduleName}}
485 }
Liz Kammera830f3a2020-11-10 10:50:34 -0800486 if outProducer, ok := module.(OutputFileProducer); ok {
487 outputFiles, err := outProducer.OutputFiles(tag)
488 if err != nil {
489 return nil, fmt.Errorf("path dependency %q: %s", path, err)
490 }
491 return outputFiles, nil
492 } else if tag != "" {
493 return nil, fmt.Errorf("path dependency %q is not an output file producing module", path)
Colin Cross0e446152021-05-03 13:35:32 -0700494 } else if goBinary, ok := module.(bootstrap.GoBinaryTool); ok {
Colin Crossa44551f2021-10-25 15:36:21 -0700495 goBinaryPath := PathForGoBinary(ctx, goBinary)
496 return Paths{goBinaryPath}, nil
Liz Kammera830f3a2020-11-10 10:50:34 -0800497 } else if srcProducer, ok := module.(SourceFileProducer); ok {
498 return srcProducer.Srcs(), nil
499 } else {
500 return nil, fmt.Errorf("path dependency %q is not a source file producing module", path)
501 }
502}
503
Paul Duffind5cf92e2021-07-09 17:38:55 +0100504// GetModuleFromPathDep will return the module that was added as a dependency automatically for
505// properties tagged with `android:"path"` or manually using ExtractSourceDeps or
506// ExtractSourcesDeps.
507//
508// The moduleName and tag supplied to this should be the values returned from SrcIsModuleWithTag.
509// Or, if no tag is expected then the moduleName should be the value returned by SrcIsModule and
510// the tag must be "".
511//
512// If tag is "" then the returned module will be the dependency that was added for ":moduleName".
513// Otherwise, it is the dependency that was added for ":moduleName{tag}".
Paul Duffind5cf92e2021-07-09 17:38:55 +0100514func GetModuleFromPathDep(ctx ModuleWithDepsPathContext, moduleName, tag string) blueprint.Module {
Paul Duffin40131a32021-07-09 17:10:35 +0100515 var found blueprint.Module
516 // The sourceOrOutputDepTag uniquely identifies the module dependency as it contains both the
517 // module name and the tag. Dependencies added automatically for properties tagged with
518 // `android:"path"` are deduped so are guaranteed to be unique. It is possible for duplicate
519 // dependencies to be added manually using ExtractSourcesDeps or ExtractSourceDeps but even then
520 // it will always be the case that the dependencies will be identical, i.e. the same tag and same
521 // moduleName referring to the same dependency module.
522 //
523 // It does not matter whether the moduleName is a fully qualified name or if the module
524 // dependency is a prebuilt module. All that matters is the same information is supplied to
525 // create the tag here as was supplied to create the tag when the dependency was added so that
526 // this finds the matching dependency module.
527 expectedTag := sourceOrOutputDepTag(moduleName, tag)
528 ctx.VisitDirectDepsBlueprint(func(module blueprint.Module) {
529 depTag := ctx.OtherModuleDependencyTag(module)
530 if depTag == expectedTag {
531 found = module
532 }
533 })
534 return found
Paul Duffind5cf92e2021-07-09 17:38:55 +0100535}
536
Liz Kammer620dea62021-04-14 17:36:10 -0400537// PathsAndMissingDepsForModuleSrcExcludes returns a Paths{} containing the resolved references in
538// paths, minus those listed in excludes. Elements of paths and excludes are resolved as:
539// * filepath, relative to local module directory, resolves as a filepath relative to the local
540// source directory
541// * glob, relative to the local module directory, resolves as filepath(s), relative to the local
542// source directory. Not valid in excludes.
543// * other modules using the ":name{.tag}" syntax. These modules must implement SourceFileProducer
544// or OutputFileProducer. These resolve as a filepath to an output filepath or generated source
545// filepath.
546// and a list of the module names of missing module dependencies are returned as the second return.
547// Properties passed as the paths argument must have been annotated with struct tag
Colin Cross41955e82019-05-29 14:40:35 -0700548// `android:"path"` so that dependencies on SourceFileProducer modules will have already been handled by the
Liz Kammer620dea62021-04-14 17:36:10 -0400549// path_deps mutator.
Liz Kammera830f3a2020-11-10 10:50:34 -0800550func PathsAndMissingDepsForModuleSrcExcludes(ctx ModuleWithDepsPathContext, paths, excludes []string) (Paths, []string) {
Colin Cross8a497952019-03-05 22:25:09 -0800551 prefix := pathForModuleSrc(ctx).String()
552
553 var expandedExcludes []string
554 if excludes != nil {
555 expandedExcludes = make([]string, 0, len(excludes))
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700556 }
Colin Cross8a497952019-03-05 22:25:09 -0800557
Colin Crossba71a3f2019-03-18 12:12:48 -0700558 var missingExcludeDeps []string
559
Colin Cross8a497952019-03-05 22:25:09 -0800560 for _, e := range excludes {
Colin Cross41955e82019-05-29 14:40:35 -0700561 if m, t := SrcIsModuleWithTag(e); m != "" {
Liz Kammera830f3a2020-11-10 10:50:34 -0800562 modulePaths, err := getPathsFromModuleDep(ctx, e, m, t)
563 if m, ok := err.(missingDependencyError); ok {
564 missingExcludeDeps = append(missingExcludeDeps, m.missingDeps...)
565 } else if err != nil {
566 reportPathError(ctx, err)
Colin Cross8a497952019-03-05 22:25:09 -0800567 } else {
Liz Kammera830f3a2020-11-10 10:50:34 -0800568 expandedExcludes = append(expandedExcludes, modulePaths.Strings()...)
Colin Cross8a497952019-03-05 22:25:09 -0800569 }
570 } else {
571 expandedExcludes = append(expandedExcludes, filepath.Join(prefix, e))
572 }
573 }
574
575 if paths == nil {
Colin Crossba71a3f2019-03-18 12:12:48 -0700576 return nil, missingExcludeDeps
Colin Cross8a497952019-03-05 22:25:09 -0800577 }
578
Colin Crossba71a3f2019-03-18 12:12:48 -0700579 var missingDeps []string
580
Colin Cross8a497952019-03-05 22:25:09 -0800581 expandedSrcFiles := make(Paths, 0, len(paths))
582 for _, s := range paths {
583 srcFiles, err := expandOneSrcPath(ctx, s, expandedExcludes)
584 if depErr, ok := err.(missingDependencyError); ok {
Colin Crossba71a3f2019-03-18 12:12:48 -0700585 missingDeps = append(missingDeps, depErr.missingDeps...)
Colin Cross8a497952019-03-05 22:25:09 -0800586 } else if err != nil {
587 reportPathError(ctx, err)
588 }
589 expandedSrcFiles = append(expandedSrcFiles, srcFiles...)
590 }
Colin Crossba71a3f2019-03-18 12:12:48 -0700591
592 return expandedSrcFiles, append(missingDeps, missingExcludeDeps...)
Colin Cross8a497952019-03-05 22:25:09 -0800593}
594
595type missingDependencyError struct {
596 missingDeps []string
597}
598
599func (e missingDependencyError) Error() string {
600 return "missing dependencies: " + strings.Join(e.missingDeps, ", ")
601}
602
Liz Kammera830f3a2020-11-10 10:50:34 -0800603// Expands one path string to Paths rooted from the module's local source
604// directory, excluding those listed in the expandedExcludes.
605// Expands globs, references to SourceFileProducer or OutputFileProducer modules using the ":name" and ":name{.tag}" syntax.
606func expandOneSrcPath(ctx ModuleWithDepsPathContext, sPath string, expandedExcludes []string) (Paths, error) {
Jooyung Han7607dd32020-07-05 10:23:14 +0900607 excludePaths := func(paths Paths) Paths {
608 if len(expandedExcludes) == 0 {
609 return paths
610 }
611 remainder := make(Paths, 0, len(paths))
612 for _, p := range paths {
613 if !InList(p.String(), expandedExcludes) {
614 remainder = append(remainder, p)
615 }
616 }
617 return remainder
618 }
Liz Kammera830f3a2020-11-10 10:50:34 -0800619 if m, t := SrcIsModuleWithTag(sPath); m != "" {
620 modulePaths, err := getPathsFromModuleDep(ctx, sPath, m, t)
621 if err != nil {
622 return nil, err
Colin Cross8a497952019-03-05 22:25:09 -0800623 } else {
Liz Kammera830f3a2020-11-10 10:50:34 -0800624 return excludePaths(modulePaths), nil
Colin Cross8a497952019-03-05 22:25:09 -0800625 }
Liz Kammera830f3a2020-11-10 10:50:34 -0800626 } else if pathtools.IsGlob(sPath) {
627 paths := GlobFiles(ctx, pathForModuleSrc(ctx, sPath).String(), expandedExcludes)
Colin Cross8a497952019-03-05 22:25:09 -0800628 return PathsWithModuleSrcSubDir(ctx, paths, ""), nil
629 } else {
Liz Kammera830f3a2020-11-10 10:50:34 -0800630 p := pathForModuleSrc(ctx, sPath)
Colin Cross988414c2020-01-11 01:11:46 +0000631 if exists, _, err := ctx.Config().fs.Exists(p.String()); err != nil {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +0100632 ReportPathErrorf(ctx, "%s: %s", p, err.Error())
Pedro Loureiro5d190cc2021-02-15 15:41:33 +0000633 } else if !exists && !ctx.Config().TestAllowNonExistentPaths {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +0100634 ReportPathErrorf(ctx, "module source path %q does not exist", p)
Colin Cross8a497952019-03-05 22:25:09 -0800635 }
636
Jooyung Han7607dd32020-07-05 10:23:14 +0900637 if InList(p.String(), expandedExcludes) {
Colin Cross8a497952019-03-05 22:25:09 -0800638 return nil, nil
639 }
640 return Paths{p}, nil
641 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700642}
643
644// pathsForModuleSrcFromFullPath returns Paths rooted from the module's local
645// source directory, but strip the local source directory from the beginning of
Dan Willemsen540a78c2018-02-26 21:50:08 -0800646// each string. If incDirs is false, strip paths with a trailing '/' from the list.
Colin Crossfe4bc362018-09-12 10:02:13 -0700647// It intended for use in globs that only list files that exist, so it allows '$' in
648// filenames.
Liz Kammera830f3a2020-11-10 10:50:34 -0800649func pathsForModuleSrcFromFullPath(ctx EarlyModulePathContext, paths []string, incDirs bool) Paths {
Lukacs T. Berkif7e36d82021-08-16 17:05:09 +0200650 prefix := ctx.ModuleDir() + "/"
Colin Cross0f37af02017-09-27 17:42:05 -0700651 if prefix == "./" {
652 prefix = ""
653 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700654 ret := make(Paths, 0, len(paths))
655 for _, p := range paths {
Dan Willemsen540a78c2018-02-26 21:50:08 -0800656 if !incDirs && strings.HasSuffix(p, "/") {
657 continue
658 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700659 path := filepath.Clean(p)
660 if !strings.HasPrefix(path, prefix) {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +0100661 ReportPathErrorf(ctx, "Path %q is not in module source directory %q", p, prefix)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700662 continue
663 }
Colin Crosse3924e12018-08-15 20:18:53 -0700664
Colin Crossfe4bc362018-09-12 10:02:13 -0700665 srcPath, err := safePathForSource(ctx, ctx.ModuleDir(), path[len(prefix):])
Colin Crosse3924e12018-08-15 20:18:53 -0700666 if err != nil {
667 reportPathError(ctx, err)
668 continue
669 }
670
Colin Cross07e51612019-03-05 12:46:40 -0800671 srcPath.basePath.rel = srcPath.path
Colin Crosse3924e12018-08-15 20:18:53 -0700672
Colin Cross07e51612019-03-05 12:46:40 -0800673 ret = append(ret, srcPath)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700674 }
675 return ret
676}
677
Liz Kammera830f3a2020-11-10 10:50:34 -0800678// PathsWithOptionalDefaultForModuleSrc returns Paths rooted from the module's local source
679// directory. If input is nil, use the default if it exists. If input is empty, returns nil.
680func PathsWithOptionalDefaultForModuleSrc(ctx ModuleMissingDepsPathContext, input []string, def string) Paths {
Colin Cross0ddae7f2019-02-07 15:30:01 -0800681 if input != nil {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700682 return PathsForModuleSrc(ctx, input)
683 }
684 // Use Glob so that if the default doesn't exist, a dependency is added so that when it
685 // is created, we're run again.
Lukacs T. Berkif7e36d82021-08-16 17:05:09 +0200686 path := filepath.Join(ctx.ModuleDir(), def)
Liz Kammera830f3a2020-11-10 10:50:34 -0800687 return Glob(ctx, path, nil)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700688}
689
690// Strings returns the Paths in string form
691func (p Paths) Strings() []string {
692 if p == nil {
693 return nil
694 }
695 ret := make([]string, len(p))
696 for i, path := range p {
697 ret[i] = path.String()
698 }
699 return ret
700}
701
Colin Crossc0efd1d2020-07-03 11:56:24 -0700702func CopyOfPaths(paths Paths) Paths {
703 return append(Paths(nil), paths...)
704}
705
Colin Crossb6715442017-10-24 11:13:31 -0700706// FirstUniquePaths returns all unique elements of a Paths, keeping the first copy of each. It
707// modifies the Paths slice contents in place, and returns a subslice of the original slice.
Dan Willemsenfe92c962017-08-29 12:28:37 -0700708func FirstUniquePaths(list Paths) Paths {
Colin Cross27027c72020-02-28 15:34:17 -0800709 // 128 was chosen based on BenchmarkFirstUniquePaths results.
710 if len(list) > 128 {
711 return firstUniquePathsMap(list)
712 }
713 return firstUniquePathsList(list)
714}
715
Colin Crossc0efd1d2020-07-03 11:56:24 -0700716// SortedUniquePaths returns all unique elements of a Paths in sorted order. It modifies the
717// Paths slice contents in place, and returns a subslice of the original slice.
Jiyong Park33c77362020-05-29 22:00:16 +0900718func SortedUniquePaths(list Paths) Paths {
719 unique := FirstUniquePaths(list)
720 sort.Slice(unique, func(i, j int) bool {
721 return unique[i].String() < unique[j].String()
722 })
723 return unique
724}
725
Colin Cross27027c72020-02-28 15:34:17 -0800726func firstUniquePathsList(list Paths) Paths {
Dan Willemsenfe92c962017-08-29 12:28:37 -0700727 k := 0
728outer:
729 for i := 0; i < len(list); i++ {
730 for j := 0; j < k; j++ {
731 if list[i] == list[j] {
732 continue outer
733 }
734 }
735 list[k] = list[i]
736 k++
737 }
738 return list[:k]
739}
740
Colin Cross27027c72020-02-28 15:34:17 -0800741func firstUniquePathsMap(list Paths) Paths {
742 k := 0
743 seen := make(map[Path]bool, len(list))
744 for i := 0; i < len(list); i++ {
745 if seen[list[i]] {
746 continue
747 }
748 seen[list[i]] = true
749 list[k] = list[i]
750 k++
751 }
752 return list[:k]
753}
754
Colin Cross5d583952020-11-24 16:21:24 -0800755// FirstUniqueInstallPaths returns all unique elements of an InstallPaths, keeping the first copy of each. It
756// modifies the InstallPaths slice contents in place, and returns a subslice of the original slice.
757func FirstUniqueInstallPaths(list InstallPaths) InstallPaths {
758 // 128 was chosen based on BenchmarkFirstUniquePaths results.
759 if len(list) > 128 {
760 return firstUniqueInstallPathsMap(list)
761 }
762 return firstUniqueInstallPathsList(list)
763}
764
765func firstUniqueInstallPathsList(list InstallPaths) InstallPaths {
766 k := 0
767outer:
768 for i := 0; i < len(list); i++ {
769 for j := 0; j < k; j++ {
770 if list[i] == list[j] {
771 continue outer
772 }
773 }
774 list[k] = list[i]
775 k++
776 }
777 return list[:k]
778}
779
780func firstUniqueInstallPathsMap(list InstallPaths) InstallPaths {
781 k := 0
782 seen := make(map[InstallPath]bool, len(list))
783 for i := 0; i < len(list); i++ {
784 if seen[list[i]] {
785 continue
786 }
787 seen[list[i]] = true
788 list[k] = list[i]
789 k++
790 }
791 return list[:k]
792}
793
Colin Crossb6715442017-10-24 11:13:31 -0700794// LastUniquePaths returns all unique elements of a Paths, keeping the last copy of each. It
795// modifies the Paths slice contents in place, and returns a subslice of the original slice.
796func LastUniquePaths(list Paths) Paths {
797 totalSkip := 0
798 for i := len(list) - 1; i >= totalSkip; i-- {
799 skip := 0
800 for j := i - 1; j >= totalSkip; j-- {
801 if list[i] == list[j] {
802 skip++
803 } else {
804 list[j+skip] = list[j]
805 }
806 }
807 totalSkip += skip
808 }
809 return list[totalSkip:]
810}
811
Colin Crossa140bb02018-04-17 10:52:26 -0700812// ReversePaths returns a copy of a Paths in reverse order.
813func ReversePaths(list Paths) Paths {
814 if list == nil {
815 return nil
816 }
817 ret := make(Paths, len(list))
818 for i := range list {
819 ret[i] = list[len(list)-1-i]
820 }
821 return ret
822}
823
Jeff Gaston294356f2017-09-27 17:05:30 -0700824func indexPathList(s Path, list []Path) int {
825 for i, l := range list {
826 if l == s {
827 return i
828 }
829 }
830
831 return -1
832}
833
834func inPathList(p Path, list []Path) bool {
835 return indexPathList(p, list) != -1
836}
837
838func FilterPathList(list []Path, filter []Path) (remainder []Path, filtered []Path) {
Paul Duffin57b9e1d2019-12-13 00:03:35 +0000839 return FilterPathListPredicate(list, func(p Path) bool { return inPathList(p, filter) })
840}
841
842func FilterPathListPredicate(list []Path, predicate func(Path) bool) (remainder []Path, filtered []Path) {
Jeff Gaston294356f2017-09-27 17:05:30 -0700843 for _, l := range list {
Paul Duffin57b9e1d2019-12-13 00:03:35 +0000844 if predicate(l) {
Jeff Gaston294356f2017-09-27 17:05:30 -0700845 filtered = append(filtered, l)
846 } else {
847 remainder = append(remainder, l)
848 }
849 }
850
851 return
852}
853
Colin Cross93e85952017-08-15 13:34:18 -0700854// HasExt returns true of any of the paths have extension ext, otherwise false
855func (p Paths) HasExt(ext string) bool {
856 for _, path := range p {
857 if path.Ext() == ext {
858 return true
859 }
860 }
861
862 return false
863}
864
865// FilterByExt returns the subset of the paths that have extension ext
866func (p Paths) FilterByExt(ext string) Paths {
867 ret := make(Paths, 0, len(p))
868 for _, path := range p {
869 if path.Ext() == ext {
870 ret = append(ret, path)
871 }
872 }
873 return ret
874}
875
876// FilterOutByExt returns the subset of the paths that do not have extension ext
877func (p Paths) FilterOutByExt(ext string) Paths {
878 ret := make(Paths, 0, len(p))
879 for _, path := range p {
880 if path.Ext() != ext {
881 ret = append(ret, path)
882 }
883 }
884 return ret
885}
886
Colin Cross5e6cfbe2017-11-03 15:20:35 -0700887// DirectorySortedPaths is a slice of paths that are sorted such that all files in a directory
888// (including subdirectories) are in a contiguous subslice of the list, and can be found in
889// O(log(N)) time using a binary search on the directory prefix.
890type DirectorySortedPaths Paths
891
892func PathsToDirectorySortedPaths(paths Paths) DirectorySortedPaths {
893 ret := append(DirectorySortedPaths(nil), paths...)
894 sort.Slice(ret, func(i, j int) bool {
895 return ret[i].String() < ret[j].String()
896 })
897 return ret
898}
899
900// PathsInDirectory returns a subslice of the DirectorySortedPaths as a Paths that contains all entries
901// that are in the specified directory and its subdirectories.
902func (p DirectorySortedPaths) PathsInDirectory(dir string) Paths {
903 prefix := filepath.Clean(dir) + "/"
904 start := sort.Search(len(p), func(i int) bool {
905 return prefix < p[i].String()
906 })
907
908 ret := p[start:]
909
910 end := sort.Search(len(ret), func(i int) bool {
911 return !strings.HasPrefix(ret[i].String(), prefix)
912 })
913
914 ret = ret[:end]
915
916 return Paths(ret)
917}
918
Alex Humesky29e3bbe2020-11-20 21:30:13 -0500919// WritablePaths is a slice of WritablePath, used for multiple outputs.
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700920type WritablePaths []WritablePath
921
Paul Duffin85d8f0d2021-03-24 10:18:18 +0000922// RelativeToTop creates a new WritablePaths containing the result of calling Path.RelativeToTop on
923// each item in this slice.
924func (p WritablePaths) RelativeToTop() WritablePaths {
925 ensureTestOnly()
926 if p == nil {
927 return p
928 }
929 ret := make(WritablePaths, len(p))
930 for i, path := range p {
931 ret[i] = path.RelativeToTop().(WritablePath)
932 }
933 return ret
934}
935
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700936// Strings returns the string forms of the writable paths.
937func (p WritablePaths) Strings() []string {
938 if p == nil {
939 return nil
940 }
941 ret := make([]string, len(p))
942 for i, path := range p {
943 ret[i] = path.String()
944 }
945 return ret
946}
947
Colin Cross3bc7ffa2017-11-22 16:19:37 -0800948// Paths returns the WritablePaths as a Paths
949func (p WritablePaths) Paths() Paths {
950 if p == nil {
951 return nil
952 }
953 ret := make(Paths, len(p))
954 for i, path := range p {
955 ret[i] = path
956 }
957 return ret
958}
959
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700960type basePath struct {
Paul Duffin74abc5d2021-03-24 09:24:59 +0000961 path string
962 rel string
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700963}
964
965func (p basePath) Ext() string {
966 return filepath.Ext(p.path)
967}
968
Colin Cross4f6fc9c2016-10-26 10:05:25 -0700969func (p basePath) Base() string {
970 return filepath.Base(p.path)
971}
972
Colin Crossfaeb7aa2017-02-01 14:12:44 -0800973func (p basePath) Rel() string {
974 if p.rel != "" {
975 return p.rel
976 }
977 return p.path
978}
979
Colin Cross0875c522017-11-28 17:34:01 -0800980func (p basePath) String() string {
981 return p.path
982}
983
Colin Cross0db55682017-12-05 15:36:55 -0800984func (p basePath) withRel(rel string) basePath {
985 p.path = filepath.Join(p.path, rel)
986 p.rel = rel
987 return p
988}
989
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700990// SourcePath is a Path representing a file path rooted from SrcDir
991type SourcePath struct {
992 basePath
Paul Duffin580efc82021-03-24 09:04:03 +0000993
994 // The sources root, i.e. Config.SrcDir()
995 srcDir string
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700996}
997
Paul Duffin85d8f0d2021-03-24 10:18:18 +0000998func (p SourcePath) RelativeToTop() Path {
999 ensureTestOnly()
1000 return p
1001}
1002
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001003var _ Path = SourcePath{}
1004
Colin Cross0db55682017-12-05 15:36:55 -08001005func (p SourcePath) withRel(rel string) SourcePath {
1006 p.basePath = p.basePath.withRel(rel)
1007 return p
1008}
1009
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001010// safePathForSource is for paths that we expect are safe -- only for use by go
1011// code that is embedding ninja variables in paths
Colin Crossfe4bc362018-09-12 10:02:13 -07001012func safePathForSource(ctx PathContext, pathComponents ...string) (SourcePath, error) {
1013 p, err := validateSafePath(pathComponents...)
Lukacs T. Berkif7e36d82021-08-16 17:05:09 +02001014 ret := SourcePath{basePath{p, ""}, "."}
Colin Crossfe4bc362018-09-12 10:02:13 -07001015 if err != nil {
1016 return ret, err
1017 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001018
Colin Cross7b3dcc32019-01-24 13:14:39 -08001019 // absolute path already checked by validateSafePath
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02001020 if strings.HasPrefix(ret.String(), ctx.Config().soongOutDir) {
Mikhail Naganovab1f5182019-02-08 13:17:55 -08001021 return ret, fmt.Errorf("source path %q is in output", ret.String())
Colin Cross6e18ca42015-07-14 18:55:36 -07001022 }
1023
Colin Crossfe4bc362018-09-12 10:02:13 -07001024 return ret, err
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001025}
1026
Colin Cross192e97a2018-02-22 14:21:02 -08001027// pathForSource creates a SourcePath from pathComponents, but does not check that it exists.
1028func pathForSource(ctx PathContext, pathComponents ...string) (SourcePath, error) {
Colin Crossc48c1432018-02-23 07:09:01 +00001029 p, err := validatePath(pathComponents...)
Lukacs T. Berkif7e36d82021-08-16 17:05:09 +02001030 ret := SourcePath{basePath{p, ""}, "."}
Colin Cross94a32102018-02-22 14:21:02 -08001031 if err != nil {
Colin Cross192e97a2018-02-22 14:21:02 -08001032 return ret, err
Colin Cross94a32102018-02-22 14:21:02 -08001033 }
1034
Colin Cross7b3dcc32019-01-24 13:14:39 -08001035 // absolute path already checked by validatePath
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02001036 if strings.HasPrefix(ret.String(), ctx.Config().soongOutDir) {
Mikhail Naganovab1f5182019-02-08 13:17:55 -08001037 return ret, fmt.Errorf("source path %q is in output", ret.String())
Colin Crossc48c1432018-02-23 07:09:01 +00001038 }
1039
Colin Cross192e97a2018-02-22 14:21:02 -08001040 return ret, nil
1041}
1042
1043// existsWithDependencies returns true if the path exists, and adds appropriate dependencies to rerun if the
1044// path does not exist.
1045func existsWithDependencies(ctx PathContext, path SourcePath) (exists bool, err error) {
1046 var files []string
1047
1048 if gctx, ok := ctx.(PathGlobContext); ok {
1049 // Use glob to produce proper dependencies, even though we only want
1050 // a single file.
1051 files, err = gctx.GlobWithDeps(path.String(), nil)
1052 } else {
Colin Cross82ea3fb2021-04-05 17:48:26 -07001053 var result pathtools.GlobResult
Colin Cross192e97a2018-02-22 14:21:02 -08001054 // We cannot add build statements in this context, so we fall back to
1055 // AddNinjaFileDeps
Colin Cross82ea3fb2021-04-05 17:48:26 -07001056 result, err = ctx.Config().fs.Glob(path.String(), nil, pathtools.FollowSymlinks)
1057 ctx.AddNinjaFileDeps(result.Deps...)
1058 files = result.Matches
Colin Cross192e97a2018-02-22 14:21:02 -08001059 }
1060
1061 if err != nil {
1062 return false, fmt.Errorf("glob: %s", err.Error())
1063 }
1064
1065 return len(files) > 0, nil
1066}
1067
1068// PathForSource joins the provided path components and validates that the result
1069// neither escapes the source dir nor is in the out dir.
1070// On error, it will return a usable, but invalid SourcePath, and report a ModuleError.
1071func PathForSource(ctx PathContext, pathComponents ...string) SourcePath {
1072 path, err := pathForSource(ctx, pathComponents...)
1073 if err != nil {
1074 reportPathError(ctx, err)
1075 }
1076
Colin Crosse3924e12018-08-15 20:18:53 -07001077 if pathtools.IsGlob(path.String()) {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001078 ReportPathErrorf(ctx, "path may not contain a glob: %s", path.String())
Colin Crosse3924e12018-08-15 20:18:53 -07001079 }
1080
Liz Kammera830f3a2020-11-10 10:50:34 -08001081 if modCtx, ok := ctx.(ModuleMissingDepsPathContext); ok && ctx.Config().AllowMissingDependencies() {
Colin Cross192e97a2018-02-22 14:21:02 -08001082 exists, err := existsWithDependencies(ctx, path)
1083 if err != nil {
1084 reportPathError(ctx, err)
1085 }
1086 if !exists {
1087 modCtx.AddMissingDependencies([]string{path.String()})
1088 }
Colin Cross988414c2020-01-11 01:11:46 +00001089 } else if exists, _, err := ctx.Config().fs.Exists(path.String()); err != nil {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001090 ReportPathErrorf(ctx, "%s: %s", path, err.Error())
Pedro Loureiro5d190cc2021-02-15 15:41:33 +00001091 } else if !exists && !ctx.Config().TestAllowNonExistentPaths {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001092 ReportPathErrorf(ctx, "source path %q does not exist", path)
Colin Cross192e97a2018-02-22 14:21:02 -08001093 }
1094 return path
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001095}
1096
Liz Kammer7aa52882021-02-11 09:16:14 -05001097// ExistentPathForSource returns an OptionalPath with the SourcePath, rooted from SrcDir, *not*
1098// rooted from the module's local source directory, if the path exists, or an empty OptionalPath if
1099// it doesn't exist. Dependencies are added so that the ninja file will be regenerated if the state
1100// of the path changes.
Colin Cross32f38982018-02-22 11:47:25 -08001101func ExistentPathForSource(ctx PathContext, pathComponents ...string) OptionalPath {
Colin Cross192e97a2018-02-22 14:21:02 -08001102 path, err := pathForSource(ctx, pathComponents...)
Colin Cross1ccfcc32018-02-22 13:54:26 -08001103 if err != nil {
1104 reportPathError(ctx, err)
Martin Stjernholmc32dd1c2021-09-15 02:39:00 +01001105 // No need to put the error message into the returned path since it has been reported already.
Colin Cross1ccfcc32018-02-22 13:54:26 -08001106 return OptionalPath{}
1107 }
Colin Crossc48c1432018-02-23 07:09:01 +00001108
Colin Crosse3924e12018-08-15 20:18:53 -07001109 if pathtools.IsGlob(path.String()) {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001110 ReportPathErrorf(ctx, "path may not contain a glob: %s", path.String())
Colin Crosse3924e12018-08-15 20:18:53 -07001111 return OptionalPath{}
1112 }
1113
Colin Cross192e97a2018-02-22 14:21:02 -08001114 exists, err := existsWithDependencies(ctx, path)
Colin Crossc48c1432018-02-23 07:09:01 +00001115 if err != nil {
1116 reportPathError(ctx, err)
1117 return OptionalPath{}
1118 }
Colin Cross192e97a2018-02-22 14:21:02 -08001119 if !exists {
Martin Stjernholmc32dd1c2021-09-15 02:39:00 +01001120 return InvalidOptionalPath(path.String() + " does not exist")
Colin Crossc48c1432018-02-23 07:09:01 +00001121 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001122 return OptionalPathForPath(path)
1123}
1124
1125func (p SourcePath) String() string {
Paul Duffin580efc82021-03-24 09:04:03 +00001126 return filepath.Join(p.srcDir, p.path)
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001127}
1128
1129// Join creates a new SourcePath with paths... joined with the current path. The
1130// provided paths... may not use '..' to escape from the current path.
1131func (p SourcePath) Join(ctx PathContext, paths ...string) SourcePath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001132 path, err := validatePath(paths...)
1133 if err != nil {
1134 reportPathError(ctx, err)
1135 }
Colin Cross0db55682017-12-05 15:36:55 -08001136 return p.withRel(path)
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001137}
1138
Colin Cross2fafa3e2019-03-05 12:39:51 -08001139// join is like Join but does less path validation.
1140func (p SourcePath) join(ctx PathContext, paths ...string) SourcePath {
1141 path, err := validateSafePath(paths...)
1142 if err != nil {
1143 reportPathError(ctx, err)
1144 }
1145 return p.withRel(path)
1146}
1147
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001148// OverlayPath returns the overlay for `path' if it exists. This assumes that the
1149// SourcePath is the path to a resource overlay directory.
Liz Kammera830f3a2020-11-10 10:50:34 -08001150func (p SourcePath) OverlayPath(ctx ModuleMissingDepsPathContext, path Path) OptionalPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001151 var relDir string
Colin Cross07e51612019-03-05 12:46:40 -08001152 if srcPath, ok := path.(SourcePath); ok {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001153 relDir = srcPath.path
1154 } else {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001155 ReportPathErrorf(ctx, "Cannot find relative path for %s(%s)", reflect.TypeOf(path).Name(), path)
Martin Stjernholmc32dd1c2021-09-15 02:39:00 +01001156 // No need to put the error message into the returned path since it has been reported already.
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001157 return OptionalPath{}
1158 }
Paul Duffin580efc82021-03-24 09:04:03 +00001159 dir := filepath.Join(p.srcDir, p.path, relDir)
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001160 // Use Glob so that we are run again if the directory is added.
Colin Cross7f19f372016-11-01 11:10:25 -07001161 if pathtools.IsGlob(dir) {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001162 ReportPathErrorf(ctx, "Path may not contain a glob: %s", dir)
Dan Willemsen7b310ee2015-12-18 15:11:17 -08001163 }
Colin Cross461b4452018-02-23 09:22:42 -08001164 paths, err := ctx.GlobWithDeps(dir, nil)
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001165 if err != nil {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001166 ReportPathErrorf(ctx, "glob: %s", err.Error())
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001167 return OptionalPath{}
1168 }
1169 if len(paths) == 0 {
Martin Stjernholmc32dd1c2021-09-15 02:39:00 +01001170 return InvalidOptionalPath(dir + " does not exist")
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001171 }
Paul Duffin580efc82021-03-24 09:04:03 +00001172 relPath := Rel(ctx, p.srcDir, paths[0])
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001173 return OptionalPathForPath(PathForSource(ctx, relPath))
1174}
1175
Colin Cross70dda7e2019-10-01 22:05:35 -07001176// OutputPath is a Path representing an intermediates file path rooted from the build directory
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001177type OutputPath struct {
1178 basePath
Paul Duffind65c58b2021-03-24 09:22:07 +00001179
Lukacs T. Berkib078ade2021-08-31 10:42:08 +02001180 // The soong build directory, i.e. Config.SoongOutDir()
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02001181 soongOutDir string
Paul Duffind65c58b2021-03-24 09:22:07 +00001182
Colin Crossd63c9a72020-01-29 16:52:50 -08001183 fullPath string
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001184}
1185
Colin Cross702e0f82017-10-18 17:27:54 -07001186func (p OutputPath) withRel(rel string) OutputPath {
Colin Cross0db55682017-12-05 15:36:55 -08001187 p.basePath = p.basePath.withRel(rel)
Colin Crossd63c9a72020-01-29 16:52:50 -08001188 p.fullPath = filepath.Join(p.fullPath, rel)
Colin Cross702e0f82017-10-18 17:27:54 -07001189 return p
1190}
1191
Colin Cross3063b782018-08-15 11:19:12 -07001192func (p OutputPath) WithoutRel() OutputPath {
1193 p.basePath.rel = filepath.Base(p.basePath.path)
1194 return p
1195}
1196
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02001197func (p OutputPath) getSoongOutDir() string {
1198 return p.soongOutDir
Paul Duffin9b478b02019-12-10 13:41:51 +00001199}
1200
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001201func (p OutputPath) RelativeToTop() Path {
1202 return p.outputPathRelativeToTop()
1203}
1204
1205func (p OutputPath) outputPathRelativeToTop() OutputPath {
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02001206 p.fullPath = StringPathRelativeToTop(p.soongOutDir, p.fullPath)
1207 p.soongOutDir = OutSoongDir
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001208 return p
1209}
1210
Paul Duffin0267d492021-02-02 10:05:52 +00001211func (p OutputPath) objPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleObjPath {
1212 return PathForModuleObj(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
1213}
1214
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001215var _ Path = OutputPath{}
Paul Duffin9b478b02019-12-10 13:41:51 +00001216var _ WritablePath = OutputPath{}
Paul Duffin0267d492021-02-02 10:05:52 +00001217var _ objPathProvider = OutputPath{}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001218
Chris Parsons8f232a22020-06-23 17:37:05 -04001219// toolDepPath is a Path representing a dependency of the build tool.
1220type toolDepPath struct {
1221 basePath
1222}
1223
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001224func (t toolDepPath) RelativeToTop() Path {
1225 ensureTestOnly()
1226 return t
1227}
1228
Chris Parsons8f232a22020-06-23 17:37:05 -04001229var _ Path = toolDepPath{}
1230
1231// pathForBuildToolDep returns a toolDepPath representing the given path string.
1232// There is no validation for the path, as it is "trusted": It may fail
1233// normal validation checks. For example, it may be an absolute path.
1234// Only use this function to construct paths for dependencies of the build
1235// tool invocation.
1236func pathForBuildToolDep(ctx PathContext, path string) toolDepPath {
Paul Duffin74abc5d2021-03-24 09:24:59 +00001237 return toolDepPath{basePath{path, ""}}
Chris Parsons8f232a22020-06-23 17:37:05 -04001238}
1239
Jeff Gaston734e3802017-04-10 15:47:24 -07001240// PathForOutput joins the provided paths and returns an OutputPath that is
1241// validated to not escape the build dir.
1242// On error, it will return a usable, but invalid OutputPath, and report a ModuleError.
1243func PathForOutput(ctx PathContext, pathComponents ...string) OutputPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001244 path, err := validatePath(pathComponents...)
1245 if err != nil {
1246 reportPathError(ctx, err)
1247 }
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02001248 fullPath := filepath.Join(ctx.Config().soongOutDir, path)
Colin Crossd63c9a72020-01-29 16:52:50 -08001249 path = fullPath[len(fullPath)-len(path):]
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02001250 return OutputPath{basePath{path, ""}, ctx.Config().soongOutDir, fullPath}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001251}
1252
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02001253// PathsForOutput returns Paths rooted from soongOutDir
Colin Cross40e33732019-02-15 11:08:35 -08001254func PathsForOutput(ctx PathContext, paths []string) WritablePaths {
1255 ret := make(WritablePaths, len(paths))
1256 for i, path := range paths {
1257 ret[i] = PathForOutput(ctx, path)
1258 }
1259 return ret
1260}
1261
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001262func (p OutputPath) writablePath() {}
1263
1264func (p OutputPath) String() string {
Colin Crossd63c9a72020-01-29 16:52:50 -08001265 return p.fullPath
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001266}
1267
1268// Join creates a new OutputPath with paths... joined with the current path. The
1269// provided paths... may not use '..' to escape from the current path.
1270func (p OutputPath) Join(ctx PathContext, paths ...string) OutputPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001271 path, err := validatePath(paths...)
1272 if err != nil {
1273 reportPathError(ctx, err)
1274 }
Colin Cross0db55682017-12-05 15:36:55 -08001275 return p.withRel(path)
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001276}
1277
Colin Cross8854a5a2019-02-11 14:14:16 -08001278// ReplaceExtension creates a new OutputPath with the extension replaced with ext.
1279func (p OutputPath) ReplaceExtension(ctx PathContext, ext string) OutputPath {
1280 if strings.Contains(ext, "/") {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001281 ReportPathErrorf(ctx, "extension %q cannot contain /", ext)
Colin Cross8854a5a2019-02-11 14:14:16 -08001282 }
1283 ret := PathForOutput(ctx, pathtools.ReplaceExtension(p.path, ext))
Colin Cross2cdd5df2019-02-25 10:25:24 -08001284 ret.rel = pathtools.ReplaceExtension(p.rel, ext)
Colin Cross8854a5a2019-02-11 14:14:16 -08001285 return ret
1286}
1287
Colin Cross40e33732019-02-15 11:08:35 -08001288// InSameDir creates a new OutputPath from the directory of the current OutputPath joined with the elements in paths.
1289func (p OutputPath) InSameDir(ctx PathContext, paths ...string) OutputPath {
1290 path, err := validatePath(paths...)
1291 if err != nil {
1292 reportPathError(ctx, err)
1293 }
1294
1295 ret := PathForOutput(ctx, filepath.Dir(p.path), path)
Colin Cross2cdd5df2019-02-25 10:25:24 -08001296 ret.rel = filepath.Join(filepath.Dir(p.rel), path)
Colin Cross40e33732019-02-15 11:08:35 -08001297 return ret
1298}
1299
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001300// PathForIntermediates returns an OutputPath representing the top-level
1301// intermediates directory.
1302func PathForIntermediates(ctx PathContext, paths ...string) OutputPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001303 path, err := validatePath(paths...)
1304 if err != nil {
1305 reportPathError(ctx, err)
1306 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001307 return PathForOutput(ctx, ".intermediates", path)
1308}
1309
Colin Cross07e51612019-03-05 12:46:40 -08001310var _ genPathProvider = SourcePath{}
1311var _ objPathProvider = SourcePath{}
1312var _ resPathProvider = SourcePath{}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001313
Colin Cross07e51612019-03-05 12:46:40 -08001314// PathForModuleSrc returns a Path representing the paths... under the
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001315// module's local source directory.
Liz Kammera830f3a2020-11-10 10:50:34 -08001316func PathForModuleSrc(ctx ModuleMissingDepsPathContext, pathComponents ...string) Path {
Paul Duffin407501b2021-07-09 16:56:35 +01001317 // Just join the components textually just to make sure that it does not corrupt a fully qualified
1318 // module reference, e.g. if the pathComponents is "://other:foo" then using filepath.Join() or
1319 // validatePath() will corrupt it, e.g. replace "//" with "/". If the path is not a module
1320 // reference then it will be validated by expandOneSrcPath anyway when it calls expandOneSrcPath.
1321 p := strings.Join(pathComponents, string(filepath.Separator))
Colin Cross8a497952019-03-05 22:25:09 -08001322 paths, err := expandOneSrcPath(ctx, p, nil)
1323 if err != nil {
1324 if depErr, ok := err.(missingDependencyError); ok {
1325 if ctx.Config().AllowMissingDependencies() {
1326 ctx.AddMissingDependencies(depErr.missingDeps)
1327 } else {
1328 ctx.ModuleErrorf(`%s, is the property annotated with android:"path"?`, depErr.Error())
1329 }
1330 } else {
1331 reportPathError(ctx, err)
1332 }
1333 return nil
1334 } else if len(paths) == 0 {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001335 ReportPathErrorf(ctx, "%q produced no files, expected exactly one", p)
Colin Cross8a497952019-03-05 22:25:09 -08001336 return nil
1337 } else if len(paths) > 1 {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001338 ReportPathErrorf(ctx, "%q produced %d files, expected exactly one", p, len(paths))
Colin Cross8a497952019-03-05 22:25:09 -08001339 }
1340 return paths[0]
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001341}
1342
Liz Kammera830f3a2020-11-10 10:50:34 -08001343func pathForModuleSrc(ctx EarlyModulePathContext, paths ...string) SourcePath {
Colin Cross07e51612019-03-05 12:46:40 -08001344 p, err := validatePath(paths...)
1345 if err != nil {
1346 reportPathError(ctx, err)
1347 }
1348
1349 path, err := pathForSource(ctx, ctx.ModuleDir(), p)
1350 if err != nil {
1351 reportPathError(ctx, err)
1352 }
1353
1354 path.basePath.rel = p
1355
1356 return path
1357}
1358
Colin Cross2fafa3e2019-03-05 12:39:51 -08001359// PathsWithModuleSrcSubDir takes a list of Paths and returns a new list of Paths where Rel() on each path
1360// will return the path relative to subDir in the module's source directory. If any input paths are not located
1361// inside subDir then a path error will be reported.
Liz Kammera830f3a2020-11-10 10:50:34 -08001362func PathsWithModuleSrcSubDir(ctx EarlyModulePathContext, paths Paths, subDir string) Paths {
Colin Cross2fafa3e2019-03-05 12:39:51 -08001363 paths = append(Paths(nil), paths...)
Colin Cross07e51612019-03-05 12:46:40 -08001364 subDirFullPath := pathForModuleSrc(ctx, subDir)
Colin Cross2fafa3e2019-03-05 12:39:51 -08001365 for i, path := range paths {
1366 rel := Rel(ctx, subDirFullPath.String(), path.String())
1367 paths[i] = subDirFullPath.join(ctx, rel)
1368 }
1369 return paths
1370}
1371
1372// PathWithModuleSrcSubDir takes a Path and returns a Path where Rel() will return the path relative to subDir in the
1373// 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 -08001374func PathWithModuleSrcSubDir(ctx EarlyModulePathContext, path Path, subDir string) Path {
Colin Cross07e51612019-03-05 12:46:40 -08001375 subDirFullPath := pathForModuleSrc(ctx, subDir)
Colin Cross2fafa3e2019-03-05 12:39:51 -08001376 rel := Rel(ctx, subDirFullPath.String(), path.String())
1377 return subDirFullPath.Join(ctx, rel)
1378}
1379
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001380// OptionalPathForModuleSrc returns an OptionalPath. The OptionalPath contains a
1381// valid path if p is non-nil.
Liz Kammera830f3a2020-11-10 10:50:34 -08001382func OptionalPathForModuleSrc(ctx ModuleMissingDepsPathContext, p *string) OptionalPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001383 if p == nil {
1384 return OptionalPath{}
1385 }
1386 return OptionalPathForPath(PathForModuleSrc(ctx, *p))
1387}
1388
Liz Kammera830f3a2020-11-10 10:50:34 -08001389func (p SourcePath) genPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleGenPath {
Colin Cross7fc17db2017-02-01 14:07:55 -08001390 return PathForModuleGen(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001391}
1392
Liz Kammera830f3a2020-11-10 10:50:34 -08001393func (p SourcePath) objPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleObjPath {
Colin Cross7fc17db2017-02-01 14:07:55 -08001394 return PathForModuleObj(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001395}
1396
Liz Kammera830f3a2020-11-10 10:50:34 -08001397func (p SourcePath) resPathWithName(ctx ModuleOutPathContext, name string) ModuleResPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001398 // TODO: Use full directory if the new ctx is not the current ctx?
1399 return PathForModuleRes(ctx, p.path, name)
1400}
1401
1402// ModuleOutPath is a Path representing a module's output directory.
1403type ModuleOutPath struct {
1404 OutputPath
1405}
1406
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001407func (p ModuleOutPath) RelativeToTop() Path {
1408 p.OutputPath = p.outputPathRelativeToTop()
1409 return p
1410}
1411
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001412var _ Path = ModuleOutPath{}
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001413var _ WritablePath = ModuleOutPath{}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001414
Liz Kammera830f3a2020-11-10 10:50:34 -08001415func (p ModuleOutPath) objPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleObjPath {
Pete Bentleyfcf55bf2019-08-16 20:14:32 +01001416 return PathForModuleObj(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
1417}
1418
Liz Kammera830f3a2020-11-10 10:50:34 -08001419// ModuleOutPathContext Subset of ModuleContext functions necessary for output path methods.
1420type ModuleOutPathContext interface {
1421 PathContext
1422
1423 ModuleName() string
1424 ModuleDir() string
1425 ModuleSubDir() string
1426}
1427
1428func pathForModuleOut(ctx ModuleOutPathContext) OutputPath {
Colin Cross702e0f82017-10-18 17:27:54 -07001429 return PathForOutput(ctx, ".intermediates", ctx.ModuleDir(), ctx.ModuleName(), ctx.ModuleSubDir())
1430}
1431
Logan Chien7eefdc42018-07-11 18:10:41 +08001432// PathForVndkRefAbiDump returns an OptionalPath representing the path of the
1433// reference abi dump for the given module. This is not guaranteed to be valid.
Liz Kammera830f3a2020-11-10 10:50:34 -08001434func PathForVndkRefAbiDump(ctx ModuleInstallPathContext, version, fileName string,
Hsin-Yi Chen53489642019-07-31 17:10:45 +08001435 isNdk, isLlndkOrVndk, isGzip bool) OptionalPath {
Logan Chien7eefdc42018-07-11 18:10:41 +08001436
Jayant Chowdharyac066c62018-02-20 10:53:31 -08001437 arches := ctx.DeviceConfig().Arches()
Logan Chien7eefdc42018-07-11 18:10:41 +08001438 if len(arches) == 0 {
1439 panic("device build with no primary arch")
1440 }
Jayant Chowdharyac066c62018-02-20 10:53:31 -08001441 currentArch := ctx.Arch()
1442 archNameAndVariant := currentArch.ArchType.String()
1443 if currentArch.ArchVariant != "" {
1444 archNameAndVariant += "_" + currentArch.ArchVariant
1445 }
Logan Chien5237bed2018-07-11 17:15:57 +08001446
1447 var dirName string
Hsin-Yi Chen53489642019-07-31 17:10:45 +08001448 if isNdk {
Logan Chien5237bed2018-07-11 17:15:57 +08001449 dirName = "ndk"
Hsin-Yi Chen53489642019-07-31 17:10:45 +08001450 } else if isLlndkOrVndk {
Logan Chien5237bed2018-07-11 17:15:57 +08001451 dirName = "vndk"
Logan Chien41eabe62019-04-10 13:33:58 +08001452 } else {
1453 dirName = "platform" // opt-in libs
Jayant Chowdhary3e231fd2017-02-08 13:45:53 -08001454 }
Logan Chien5237bed2018-07-11 17:15:57 +08001455
Jayant Chowdhary34ce67d2018-03-08 11:00:50 -08001456 binderBitness := ctx.DeviceConfig().BinderBitness()
Logan Chien7eefdc42018-07-11 18:10:41 +08001457
1458 var ext string
1459 if isGzip {
1460 ext = ".lsdump.gz"
1461 } else {
1462 ext = ".lsdump"
1463 }
1464
1465 return ExistentPathForSource(ctx, "prebuilts", "abi-dumps", dirName,
1466 version, binderBitness, archNameAndVariant, "source-based",
1467 fileName+ext)
Jayant Chowdhary3e231fd2017-02-08 13:45:53 -08001468}
1469
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001470// PathForModuleOut returns a Path representing the paths... under the module's
1471// output directory.
Liz Kammera830f3a2020-11-10 10:50:34 -08001472func PathForModuleOut(ctx ModuleOutPathContext, paths ...string) ModuleOutPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001473 p, err := validatePath(paths...)
1474 if err != nil {
1475 reportPathError(ctx, err)
1476 }
Colin Cross702e0f82017-10-18 17:27:54 -07001477 return ModuleOutPath{
Liz Kammera830f3a2020-11-10 10:50:34 -08001478 OutputPath: pathForModuleOut(ctx).withRel(p),
Colin Cross702e0f82017-10-18 17:27:54 -07001479 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001480}
1481
1482// ModuleGenPath is a Path representing the 'gen' directory in a module's output
1483// directory. Mainly used for generated sources.
1484type ModuleGenPath struct {
1485 ModuleOutPath
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001486}
1487
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001488func (p ModuleGenPath) RelativeToTop() Path {
1489 p.OutputPath = p.outputPathRelativeToTop()
1490 return p
1491}
1492
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001493var _ Path = ModuleGenPath{}
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001494var _ WritablePath = ModuleGenPath{}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001495var _ genPathProvider = ModuleGenPath{}
1496var _ objPathProvider = ModuleGenPath{}
1497
1498// PathForModuleGen returns a Path representing the paths... under the module's
1499// `gen' directory.
Liz Kammera830f3a2020-11-10 10:50:34 -08001500func PathForModuleGen(ctx ModuleOutPathContext, paths ...string) ModuleGenPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001501 p, err := validatePath(paths...)
1502 if err != nil {
1503 reportPathError(ctx, err)
1504 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001505 return ModuleGenPath{
Colin Cross702e0f82017-10-18 17:27:54 -07001506 ModuleOutPath: ModuleOutPath{
Liz Kammera830f3a2020-11-10 10:50:34 -08001507 OutputPath: pathForModuleOut(ctx).withRel("gen").withRel(p),
Colin Cross702e0f82017-10-18 17:27:54 -07001508 },
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001509 }
1510}
1511
Liz Kammera830f3a2020-11-10 10:50:34 -08001512func (p ModuleGenPath) genPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleGenPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001513 // TODO: make a different path for local vs remote generated files?
Dan Willemsen21ec4902016-11-02 20:43:13 -07001514 return PathForModuleGen(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001515}
1516
Liz Kammera830f3a2020-11-10 10:50:34 -08001517func (p ModuleGenPath) objPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleObjPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001518 return PathForModuleObj(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
1519}
1520
1521// ModuleObjPath is a Path representing the 'obj' directory in a module's output
1522// directory. Used for compiled objects.
1523type ModuleObjPath struct {
1524 ModuleOutPath
1525}
1526
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001527func (p ModuleObjPath) RelativeToTop() Path {
1528 p.OutputPath = p.outputPathRelativeToTop()
1529 return p
1530}
1531
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001532var _ Path = ModuleObjPath{}
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001533var _ WritablePath = ModuleObjPath{}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001534
1535// PathForModuleObj returns a Path representing the paths... under the module's
1536// 'obj' directory.
Liz Kammera830f3a2020-11-10 10:50:34 -08001537func PathForModuleObj(ctx ModuleOutPathContext, pathComponents ...string) ModuleObjPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001538 p, err := validatePath(pathComponents...)
1539 if err != nil {
1540 reportPathError(ctx, err)
1541 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001542 return ModuleObjPath{PathForModuleOut(ctx, "obj", p)}
1543}
1544
1545// ModuleResPath is a a Path representing the 'res' directory in a module's
1546// output directory.
1547type ModuleResPath struct {
1548 ModuleOutPath
1549}
1550
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001551func (p ModuleResPath) RelativeToTop() Path {
1552 p.OutputPath = p.outputPathRelativeToTop()
1553 return p
1554}
1555
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001556var _ Path = ModuleResPath{}
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001557var _ WritablePath = ModuleResPath{}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001558
1559// PathForModuleRes returns a Path representing the paths... under the module's
1560// 'res' directory.
Liz Kammera830f3a2020-11-10 10:50:34 -08001561func PathForModuleRes(ctx ModuleOutPathContext, pathComponents ...string) ModuleResPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001562 p, err := validatePath(pathComponents...)
1563 if err != nil {
1564 reportPathError(ctx, err)
1565 }
1566
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001567 return ModuleResPath{PathForModuleOut(ctx, "res", p)}
1568}
1569
Colin Cross70dda7e2019-10-01 22:05:35 -07001570// InstallPath is a Path representing a installed file path rooted from the build directory
1571type InstallPath struct {
1572 basePath
Colin Crossff6c33d2019-10-02 16:01:35 -07001573
Lukacs T. Berkib078ade2021-08-31 10:42:08 +02001574 // The soong build directory, i.e. Config.SoongOutDir()
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02001575 soongOutDir string
Paul Duffind65c58b2021-03-24 09:22:07 +00001576
Jiyong Park957bcd92020-10-20 18:23:33 +09001577 // partitionDir is the part of the InstallPath that is automatically determined according to the context.
1578 // For example, it is host/<os>-<arch> for host modules, and target/product/<device>/<partition> for device modules.
1579 partitionDir string
1580
Colin Crossb1692a32021-10-25 15:39:01 -07001581 partition string
1582
Jiyong Park957bcd92020-10-20 18:23:33 +09001583 // makePath indicates whether this path is for Soong (false) or Make (true).
1584 makePath bool
Colin Cross70dda7e2019-10-01 22:05:35 -07001585}
1586
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001587// Will panic if called from outside a test environment.
1588func ensureTestOnly() {
Martin Stjernholm32312eb2021-03-27 18:54:49 +00001589 if PrefixInList(os.Args, "-test.") {
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001590 return
1591 }
Martin Stjernholm32312eb2021-03-27 18:54:49 +00001592 panic(fmt.Errorf("Not in test. Command line:\n %s", strings.Join(os.Args, "\n ")))
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001593}
1594
1595func (p InstallPath) RelativeToTop() Path {
1596 ensureTestOnly()
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02001597 p.soongOutDir = OutSoongDir
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001598 return p
1599}
1600
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02001601func (p InstallPath) getSoongOutDir() string {
1602 return p.soongOutDir
Paul Duffin9b478b02019-12-10 13:41:51 +00001603}
1604
Hans MÃ¥nssond3f2bd72020-11-27 12:37:28 +01001605func (p InstallPath) ReplaceExtension(ctx PathContext, ext string) OutputPath {
1606 panic("Not implemented")
1607}
1608
Paul Duffin9b478b02019-12-10 13:41:51 +00001609var _ Path = InstallPath{}
1610var _ WritablePath = InstallPath{}
1611
Colin Cross70dda7e2019-10-01 22:05:35 -07001612func (p InstallPath) writablePath() {}
1613
1614func (p InstallPath) String() string {
Jiyong Park957bcd92020-10-20 18:23:33 +09001615 if p.makePath {
1616 // Make path starts with out/ instead of out/soong.
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02001617 return filepath.Join(p.soongOutDir, "../", p.path)
Jiyong Park957bcd92020-10-20 18:23:33 +09001618 } else {
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02001619 return filepath.Join(p.soongOutDir, p.path)
Jiyong Park957bcd92020-10-20 18:23:33 +09001620 }
1621}
1622
1623// PartitionDir returns the path to the partition where the install path is rooted at. It is
1624// out/soong/target/product/<device>/<partition> for device modules, and out/soong/host/<os>-<arch> for host modules.
1625// The ./soong is dropped if the install path is for Make.
1626func (p InstallPath) PartitionDir() string {
1627 if p.makePath {
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02001628 return filepath.Join(p.soongOutDir, "../", p.partitionDir)
Jiyong Park957bcd92020-10-20 18:23:33 +09001629 } else {
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02001630 return filepath.Join(p.soongOutDir, p.partitionDir)
Jiyong Park957bcd92020-10-20 18:23:33 +09001631 }
Colin Cross70dda7e2019-10-01 22:05:35 -07001632}
1633
1634// Join creates a new InstallPath with paths... joined with the current path. The
1635// provided paths... may not use '..' to escape from the current path.
1636func (p InstallPath) Join(ctx PathContext, paths ...string) InstallPath {
1637 path, err := validatePath(paths...)
1638 if err != nil {
1639 reportPathError(ctx, err)
1640 }
1641 return p.withRel(path)
1642}
1643
1644func (p InstallPath) withRel(rel string) InstallPath {
1645 p.basePath = p.basePath.withRel(rel)
1646 return p
1647}
1648
Colin Crossff6c33d2019-10-02 16:01:35 -07001649// ToMakePath returns a new InstallPath that points to Make's install directory instead of Soong's,
1650// i.e. out/ instead of out/soong/.
1651func (p InstallPath) ToMakePath() InstallPath {
Jiyong Park957bcd92020-10-20 18:23:33 +09001652 p.makePath = true
Colin Crossff6c33d2019-10-02 16:01:35 -07001653 return p
Colin Cross70dda7e2019-10-01 22:05:35 -07001654}
1655
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001656// PathForModuleInstall returns a Path representing the install path for the
1657// module appended with paths...
Colin Cross70dda7e2019-10-01 22:05:35 -07001658func PathForModuleInstall(ctx ModuleInstallPathContext, pathComponents ...string) InstallPath {
Spandan Das5d1b9292021-06-03 19:36:41 +00001659 os, arch := osAndArch(ctx)
1660 partition := modulePartition(ctx, os)
1661 return makePathForInstall(ctx, os, arch, partition, ctx.Debug(), pathComponents...)
1662}
1663
1664// PathForModuleInPartitionInstall is similar to PathForModuleInstall but partition is provided by the caller
1665func PathForModuleInPartitionInstall(ctx ModuleInstallPathContext, partition string, pathComponents ...string) InstallPath {
1666 os, arch := osAndArch(ctx)
1667 return makePathForInstall(ctx, os, arch, partition, ctx.Debug(), pathComponents...)
1668}
1669
1670func osAndArch(ctx ModuleInstallPathContext) (OsType, ArchType) {
Colin Cross6e359402020-02-10 15:29:54 -08001671 os := ctx.Os()
Jiyong Park87788b52020-09-01 12:37:45 +09001672 arch := ctx.Arch().ArchType
1673 forceOS, forceArch := ctx.InstallForceOS()
1674 if forceOS != nil {
Colin Cross6e359402020-02-10 15:29:54 -08001675 os = *forceOS
1676 }
Jiyong Park87788b52020-09-01 12:37:45 +09001677 if forceArch != nil {
1678 arch = *forceArch
1679 }
Spandan Das5d1b9292021-06-03 19:36:41 +00001680 return os, arch
1681}
Colin Cross609c49a2020-02-13 13:20:11 -08001682
Spandan Das5d1b9292021-06-03 19:36:41 +00001683func makePathForInstall(ctx ModuleInstallPathContext, os OsType, arch ArchType, partition string, debug bool, pathComponents ...string) InstallPath {
1684 ret := pathForInstall(ctx, os, arch, partition, debug, pathComponents...)
Jingwen Chencda22c92020-11-23 00:22:30 -05001685 if ctx.InstallBypassMake() && ctx.Config().KatiEnabled() {
Colin Cross609c49a2020-02-13 13:20:11 -08001686 ret = ret.ToMakePath()
1687 }
Colin Cross609c49a2020-02-13 13:20:11 -08001688 return ret
1689}
1690
Jiyong Park87788b52020-09-01 12:37:45 +09001691func pathForInstall(ctx PathContext, os OsType, arch ArchType, partition string, debug bool,
Colin Cross609c49a2020-02-13 13:20:11 -08001692 pathComponents ...string) InstallPath {
1693
Jiyong Park957bcd92020-10-20 18:23:33 +09001694 var partionPaths []string
Colin Cross609c49a2020-02-13 13:20:11 -08001695
Colin Cross6e359402020-02-10 15:29:54 -08001696 if os.Class == Device {
Jiyong Park957bcd92020-10-20 18:23:33 +09001697 partionPaths = []string{"target", "product", ctx.Config().DeviceName(), partition}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001698 } else {
Jiyong Park87788b52020-09-01 12:37:45 +09001699 osName := os.String()
Colin Cross528d67e2021-07-23 22:23:07 +00001700 if os == Linux || os == LinuxMusl {
Jiyong Park87788b52020-09-01 12:37:45 +09001701 // instead of linux_glibc
1702 osName = "linux"
Dan Willemsen866b5632017-09-22 12:28:24 -07001703 }
Jiyong Park87788b52020-09-01 12:37:45 +09001704 // SOONG_HOST_OUT is set to out/host/$(HOST_OS)-$(HOST_PREBUILT_ARCH)
1705 // and HOST_PREBUILT_ARCH is forcibly set to x86 even on x86_64 hosts. We don't seem
1706 // to have a plan to fix it (see the comment in build/make/core/envsetup.mk).
1707 // Let's keep using x86 for the existing cases until we have a need to support
1708 // other architectures.
1709 archName := arch.String()
1710 if os.Class == Host && (arch == X86_64 || arch == Common) {
1711 archName = "x86"
1712 }
Jiyong Park957bcd92020-10-20 18:23:33 +09001713 partionPaths = []string{"host", osName + "-" + archName, partition}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001714 }
Colin Cross609c49a2020-02-13 13:20:11 -08001715 if debug {
Jiyong Park957bcd92020-10-20 18:23:33 +09001716 partionPaths = append([]string{"debug"}, partionPaths...)
Dan Willemsen782a2d12015-12-21 14:55:28 -08001717 }
Colin Cross70dda7e2019-10-01 22:05:35 -07001718
Jiyong Park957bcd92020-10-20 18:23:33 +09001719 partionPath, err := validatePath(partionPaths...)
Colin Cross70dda7e2019-10-01 22:05:35 -07001720 if err != nil {
1721 reportPathError(ctx, err)
1722 }
Colin Crossff6c33d2019-10-02 16:01:35 -07001723
Jiyong Park957bcd92020-10-20 18:23:33 +09001724 base := InstallPath{
Paul Duffin74abc5d2021-03-24 09:24:59 +00001725 basePath: basePath{partionPath, ""},
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02001726 soongOutDir: ctx.Config().soongOutDir,
Jiyong Park957bcd92020-10-20 18:23:33 +09001727 partitionDir: partionPath,
Colin Crossb1692a32021-10-25 15:39:01 -07001728 partition: partition,
Jiyong Park957bcd92020-10-20 18:23:33 +09001729 makePath: false,
1730 }
Colin Crossff6c33d2019-10-02 16:01:35 -07001731
Jiyong Park957bcd92020-10-20 18:23:33 +09001732 return base.Join(ctx, pathComponents...)
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001733}
1734
Nicolas Geoffray1228e9c2020-02-27 13:45:35 +00001735func pathForNdkOrSdkInstall(ctx PathContext, prefix string, paths []string) InstallPath {
Jiyong Park957bcd92020-10-20 18:23:33 +09001736 base := InstallPath{
Paul Duffin74abc5d2021-03-24 09:24:59 +00001737 basePath: basePath{prefix, ""},
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02001738 soongOutDir: ctx.Config().soongOutDir,
Jiyong Park957bcd92020-10-20 18:23:33 +09001739 partitionDir: prefix,
1740 makePath: false,
Colin Cross70dda7e2019-10-01 22:05:35 -07001741 }
Jiyong Park957bcd92020-10-20 18:23:33 +09001742 return base.Join(ctx, paths...)
Colin Cross70dda7e2019-10-01 22:05:35 -07001743}
1744
Nicolas Geoffray1228e9c2020-02-27 13:45:35 +00001745func PathForNdkInstall(ctx PathContext, paths ...string) InstallPath {
1746 return pathForNdkOrSdkInstall(ctx, "ndk", paths)
1747}
1748
1749func PathForMainlineSdksInstall(ctx PathContext, paths ...string) InstallPath {
1750 return pathForNdkOrSdkInstall(ctx, "mainline-sdks", paths)
1751}
1752
Colin Cross70dda7e2019-10-01 22:05:35 -07001753func InstallPathToOnDevicePath(ctx PathContext, path InstallPath) string {
Colin Crossb1692a32021-10-25 15:39:01 -07001754 rel := Rel(ctx, strings.TrimSuffix(path.PartitionDir(), path.partition), path.String())
Colin Cross43f08db2018-11-12 10:13:39 -08001755 return "/" + rel
1756}
1757
Colin Cross6e359402020-02-10 15:29:54 -08001758func modulePartition(ctx ModuleInstallPathContext, os OsType) string {
Colin Cross43f08db2018-11-12 10:13:39 -08001759 var partition string
Colin Cross6e359402020-02-10 15:29:54 -08001760 if ctx.InstallInTestcases() {
1761 // "testcases" install directory can be used for host or device modules.
Jaewoong Jung0949f312019-09-11 10:25:18 -07001762 partition = "testcases"
Colin Cross6e359402020-02-10 15:29:54 -08001763 } else if os.Class == Device {
1764 if ctx.InstallInData() {
1765 partition = "data"
1766 } else if ctx.InstallInRamdisk() {
1767 if ctx.DeviceConfig().BoardUsesRecoveryAsBoot() {
1768 partition = "recovery/root/first_stage_ramdisk"
1769 } else {
1770 partition = "ramdisk"
1771 }
1772 if !ctx.InstallInRoot() {
1773 partition += "/system"
1774 }
Yifan Hong60e0cfb2020-10-21 15:17:56 -07001775 } else if ctx.InstallInVendorRamdisk() {
Yifan Hong39143a92020-10-26 12:43:12 -07001776 // The module is only available after switching root into
1777 // /first_stage_ramdisk. To expose the module before switching root
1778 // on a device without a dedicated recovery partition, install the
1779 // recovery variant.
Yifan Hongdd8dacc2020-10-21 15:40:17 -07001780 if ctx.DeviceConfig().BoardMoveRecoveryResourcesToVendorBoot() {
Petri Gyntherac229562021-03-02 23:44:02 -08001781 partition = "vendor_ramdisk/first_stage_ramdisk"
Yifan Hongdd8dacc2020-10-21 15:40:17 -07001782 } else {
Petri Gyntherac229562021-03-02 23:44:02 -08001783 partition = "vendor_ramdisk"
Yifan Hongdd8dacc2020-10-21 15:40:17 -07001784 }
1785 if !ctx.InstallInRoot() {
1786 partition += "/system"
1787 }
Inseob Kim08758f02021-04-08 21:13:22 +09001788 } else if ctx.InstallInDebugRamdisk() {
1789 partition = "debug_ramdisk"
Colin Cross6e359402020-02-10 15:29:54 -08001790 } else if ctx.InstallInRecovery() {
1791 if ctx.InstallInRoot() {
1792 partition = "recovery/root"
1793 } else {
1794 // the layout of recovery partion is the same as that of system partition
1795 partition = "recovery/root/system"
1796 }
1797 } else if ctx.SocSpecific() {
1798 partition = ctx.DeviceConfig().VendorPath()
1799 } else if ctx.DeviceSpecific() {
1800 partition = ctx.DeviceConfig().OdmPath()
1801 } else if ctx.ProductSpecific() {
1802 partition = ctx.DeviceConfig().ProductPath()
1803 } else if ctx.SystemExtSpecific() {
1804 partition = ctx.DeviceConfig().SystemExtPath()
1805 } else if ctx.InstallInRoot() {
1806 partition = "root"
Yifan Hong82db7352020-01-21 16:12:26 -08001807 } else {
Colin Cross6e359402020-02-10 15:29:54 -08001808 partition = "system"
Yifan Hong82db7352020-01-21 16:12:26 -08001809 }
Colin Cross6e359402020-02-10 15:29:54 -08001810 if ctx.InstallInSanitizerDir() {
1811 partition = "data/asan/" + partition
Yifan Hong82db7352020-01-21 16:12:26 -08001812 }
Colin Cross43f08db2018-11-12 10:13:39 -08001813 }
1814 return partition
1815}
1816
Colin Cross609c49a2020-02-13 13:20:11 -08001817type InstallPaths []InstallPath
1818
1819// Paths returns the InstallPaths as a Paths
1820func (p InstallPaths) Paths() Paths {
1821 if p == nil {
1822 return nil
1823 }
1824 ret := make(Paths, len(p))
1825 for i, path := range p {
1826 ret[i] = path
1827 }
1828 return ret
1829}
1830
1831// Strings returns the string forms of the install paths.
1832func (p InstallPaths) Strings() []string {
1833 if p == nil {
1834 return nil
1835 }
1836 ret := make([]string, len(p))
1837 for i, path := range p {
1838 ret[i] = path.String()
1839 }
1840 return ret
1841}
1842
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001843// validateSafePath validates a path that we trust (may contain ninja variables).
Dan Willemsen80a7c2a2015-12-21 14:57:11 -08001844// Ensures that each path component does not attempt to leave its component.
Colin Cross1ccfcc32018-02-22 13:54:26 -08001845func validateSafePath(pathComponents ...string) (string, error) {
Jeff Gaston734e3802017-04-10 15:47:24 -07001846 for _, path := range pathComponents {
Dan Willemsen80a7c2a2015-12-21 14:57:11 -08001847 path := filepath.Clean(path)
1848 if path == ".." || strings.HasPrefix(path, "../") || strings.HasPrefix(path, "/") {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001849 return "", fmt.Errorf("Path is outside directory: %s", path)
Dan Willemsen80a7c2a2015-12-21 14:57:11 -08001850 }
1851 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001852 // TODO: filepath.Join isn't necessarily correct with embedded ninja
1853 // variables. '..' may remove the entire ninja variable, even if it
1854 // will be expanded to multiple nested directories.
Colin Cross1ccfcc32018-02-22 13:54:26 -08001855 return filepath.Join(pathComponents...), nil
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001856}
1857
Dan Willemsen80a7c2a2015-12-21 14:57:11 -08001858// validatePath validates that a path does not include ninja variables, and that
1859// each path component does not attempt to leave its component. Returns a joined
1860// version of each path component.
Colin Cross1ccfcc32018-02-22 13:54:26 -08001861func validatePath(pathComponents ...string) (string, error) {
Jeff Gaston734e3802017-04-10 15:47:24 -07001862 for _, path := range pathComponents {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001863 if strings.Contains(path, "$") {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001864 return "", fmt.Errorf("Path contains invalid character($): %s", path)
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001865 }
1866 }
Colin Cross1ccfcc32018-02-22 13:54:26 -08001867 return validateSafePath(pathComponents...)
Colin Cross6e18ca42015-07-14 18:55:36 -07001868}
Colin Cross5b529592017-05-09 13:34:34 -07001869
Colin Cross0875c522017-11-28 17:34:01 -08001870func PathForPhony(ctx PathContext, phony string) WritablePath {
1871 if strings.ContainsAny(phony, "$/") {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001872 ReportPathErrorf(ctx, "Phony target contains invalid character ($ or /): %s", phony)
Colin Cross0875c522017-11-28 17:34:01 -08001873 }
Paul Duffin74abc5d2021-03-24 09:24:59 +00001874 return PhonyPath{basePath{phony, ""}}
Colin Cross0875c522017-11-28 17:34:01 -08001875}
1876
Colin Cross74e3fe42017-12-11 15:51:44 -08001877type PhonyPath struct {
1878 basePath
1879}
1880
1881func (p PhonyPath) writablePath() {}
1882
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02001883func (p PhonyPath) getSoongOutDir() string {
Paul Duffind65c58b2021-03-24 09:22:07 +00001884 // A phone path cannot contain any / so cannot be relative to the build directory.
1885 return ""
Paul Duffin9b478b02019-12-10 13:41:51 +00001886}
1887
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001888func (p PhonyPath) RelativeToTop() Path {
1889 ensureTestOnly()
1890 // A phony path cannot contain any / so does not have a build directory so switching to a new
1891 // build directory has no effect so just return this path.
1892 return p
1893}
1894
Hans MÃ¥nssond3f2bd72020-11-27 12:37:28 +01001895func (p PhonyPath) ReplaceExtension(ctx PathContext, ext string) OutputPath {
1896 panic("Not implemented")
1897}
1898
Colin Cross74e3fe42017-12-11 15:51:44 -08001899var _ Path = PhonyPath{}
1900var _ WritablePath = PhonyPath{}
1901
Colin Cross5b529592017-05-09 13:34:34 -07001902type testPath struct {
1903 basePath
1904}
1905
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001906func (p testPath) RelativeToTop() Path {
1907 ensureTestOnly()
1908 return p
1909}
1910
Colin Cross5b529592017-05-09 13:34:34 -07001911func (p testPath) String() string {
1912 return p.path
1913}
1914
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001915var _ Path = testPath{}
1916
Colin Cross40e33732019-02-15 11:08:35 -08001917// PathForTesting returns a Path constructed from joining the elements of paths with '/'. It should only be used from
1918// within tests.
Colin Cross5b529592017-05-09 13:34:34 -07001919func PathForTesting(paths ...string) Path {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001920 p, err := validateSafePath(paths...)
1921 if err != nil {
1922 panic(err)
1923 }
Colin Cross5b529592017-05-09 13:34:34 -07001924 return testPath{basePath{path: p, rel: p}}
1925}
1926
Colin Cross40e33732019-02-15 11:08:35 -08001927// PathsForTesting returns a Path constructed from each element in strs. It should only be used from within tests.
1928func PathsForTesting(strs ...string) Paths {
Colin Cross5b529592017-05-09 13:34:34 -07001929 p := make(Paths, len(strs))
1930 for i, s := range strs {
1931 p[i] = PathForTesting(s)
1932 }
1933
1934 return p
1935}
Colin Cross43f08db2018-11-12 10:13:39 -08001936
Colin Cross40e33732019-02-15 11:08:35 -08001937type testPathContext struct {
1938 config Config
Colin Cross40e33732019-02-15 11:08:35 -08001939}
1940
Colin Cross40e33732019-02-15 11:08:35 -08001941func (x *testPathContext) Config() Config { return x.config }
1942func (x *testPathContext) AddNinjaFileDeps(...string) {}
1943
1944// PathContextForTesting returns a PathContext that can be used in tests, for example to create an OutputPath with
1945// PathForOutput.
Colin Cross98be1bb2019-12-13 20:41:13 -08001946func PathContextForTesting(config Config) PathContext {
Colin Cross40e33732019-02-15 11:08:35 -08001947 return &testPathContext{
1948 config: config,
Colin Cross40e33732019-02-15 11:08:35 -08001949 }
1950}
1951
Ulya Trafimovichccc8c852020-10-14 11:29:07 +01001952type testModuleInstallPathContext struct {
1953 baseModuleContext
1954
1955 inData bool
1956 inTestcases bool
1957 inSanitizerDir bool
1958 inRamdisk bool
1959 inVendorRamdisk bool
Inseob Kim08758f02021-04-08 21:13:22 +09001960 inDebugRamdisk bool
Ulya Trafimovichccc8c852020-10-14 11:29:07 +01001961 inRecovery bool
1962 inRoot bool
1963 forceOS *OsType
1964 forceArch *ArchType
1965}
1966
1967func (m testModuleInstallPathContext) Config() Config {
1968 return m.baseModuleContext.config
1969}
1970
1971func (testModuleInstallPathContext) AddNinjaFileDeps(deps ...string) {}
1972
1973func (m testModuleInstallPathContext) InstallInData() bool {
1974 return m.inData
1975}
1976
1977func (m testModuleInstallPathContext) InstallInTestcases() bool {
1978 return m.inTestcases
1979}
1980
1981func (m testModuleInstallPathContext) InstallInSanitizerDir() bool {
1982 return m.inSanitizerDir
1983}
1984
1985func (m testModuleInstallPathContext) InstallInRamdisk() bool {
1986 return m.inRamdisk
1987}
1988
1989func (m testModuleInstallPathContext) InstallInVendorRamdisk() bool {
1990 return m.inVendorRamdisk
1991}
1992
Inseob Kim08758f02021-04-08 21:13:22 +09001993func (m testModuleInstallPathContext) InstallInDebugRamdisk() bool {
1994 return m.inDebugRamdisk
1995}
1996
Ulya Trafimovichccc8c852020-10-14 11:29:07 +01001997func (m testModuleInstallPathContext) InstallInRecovery() bool {
1998 return m.inRecovery
1999}
2000
2001func (m testModuleInstallPathContext) InstallInRoot() bool {
2002 return m.inRoot
2003}
2004
2005func (m testModuleInstallPathContext) InstallBypassMake() bool {
2006 return false
2007}
2008
2009func (m testModuleInstallPathContext) InstallForceOS() (*OsType, *ArchType) {
2010 return m.forceOS, m.forceArch
2011}
2012
2013// Construct a minimal ModuleInstallPathContext for testing. Note that baseModuleContext is
2014// default-initialized, which leaves blueprint.baseModuleContext set to nil, so methods that are
2015// delegated to it will panic.
2016func ModuleInstallPathContextForTesting(config Config) ModuleInstallPathContext {
2017 ctx := &testModuleInstallPathContext{}
2018 ctx.config = config
2019 ctx.os = Android
2020 return ctx
2021}
2022
Colin Cross43f08db2018-11-12 10:13:39 -08002023// Rel performs the same function as filepath.Rel, but reports errors to a PathContext, and reports an error if
2024// targetPath is not inside basePath.
2025func Rel(ctx PathContext, basePath string, targetPath string) string {
2026 rel, isRel := MaybeRel(ctx, basePath, targetPath)
2027 if !isRel {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01002028 ReportPathErrorf(ctx, "path %q is not under path %q", targetPath, basePath)
Colin Cross43f08db2018-11-12 10:13:39 -08002029 return ""
2030 }
2031 return rel
2032}
2033
2034// MaybeRel performs the same function as filepath.Rel, but reports errors to a PathContext, and returns false if
2035// targetPath is not inside basePath.
2036func MaybeRel(ctx PathContext, basePath string, targetPath string) (string, bool) {
Dan Willemsen633c5022019-04-12 11:11:38 -07002037 rel, isRel, err := maybeRelErr(basePath, targetPath)
2038 if err != nil {
2039 reportPathError(ctx, err)
2040 }
2041 return rel, isRel
2042}
2043
2044func maybeRelErr(basePath string, targetPath string) (string, bool, error) {
Colin Cross43f08db2018-11-12 10:13:39 -08002045 // filepath.Rel returns an error if one path is absolute and the other is not, handle that case first.
2046 if filepath.IsAbs(basePath) != filepath.IsAbs(targetPath) {
Dan Willemsen633c5022019-04-12 11:11:38 -07002047 return "", false, nil
Colin Cross43f08db2018-11-12 10:13:39 -08002048 }
2049 rel, err := filepath.Rel(basePath, targetPath)
2050 if err != nil {
Dan Willemsen633c5022019-04-12 11:11:38 -07002051 return "", false, err
Colin Cross43f08db2018-11-12 10:13:39 -08002052 } else if rel == ".." || strings.HasPrefix(rel, "../") || strings.HasPrefix(rel, "/") {
Dan Willemsen633c5022019-04-12 11:11:38 -07002053 return "", false, nil
Colin Cross43f08db2018-11-12 10:13:39 -08002054 }
Dan Willemsen633c5022019-04-12 11:11:38 -07002055 return rel, true, nil
Colin Cross43f08db2018-11-12 10:13:39 -08002056}
Colin Cross988414c2020-01-11 01:11:46 +00002057
2058// Writes a file to the output directory. Attempting to write directly to the output directory
2059// will fail due to the sandbox of the soong_build process.
2060func WriteFileToOutputDir(path WritablePath, data []byte, perm os.FileMode) error {
2061 return ioutil.WriteFile(absolutePath(path.String()), data, perm)
2062}
2063
Liz Kammer2dd9ca42020-11-25 16:06:39 -08002064func RemoveAllOutputDir(path WritablePath) error {
2065 return os.RemoveAll(absolutePath(path.String()))
2066}
2067
2068func CreateOutputDirIfNonexistent(path WritablePath, perm os.FileMode) error {
2069 dir := absolutePath(path.String())
Liz Kammer09f947d2021-05-12 14:51:49 -04002070 return createDirIfNonexistent(dir, perm)
2071}
2072
2073func createDirIfNonexistent(dir string, perm os.FileMode) error {
Liz Kammer2dd9ca42020-11-25 16:06:39 -08002074 if _, err := os.Stat(dir); os.IsNotExist(err) {
2075 return os.MkdirAll(dir, os.ModePerm)
2076 } else {
2077 return err
2078 }
2079}
2080
Jingwen Chen78257e52021-05-21 02:34:24 +00002081// absolutePath is deliberately private so that Soong's Go plugins can't use it to find and
2082// read arbitrary files without going through the methods in the current package that track
2083// dependencies.
Colin Cross988414c2020-01-11 01:11:46 +00002084func absolutePath(path string) string {
2085 if filepath.IsAbs(path) {
2086 return path
2087 }
2088 return filepath.Join(absSrcDir, path)
2089}
Chris Parsons216e10a2020-07-09 17:12:52 -04002090
2091// A DataPath represents the path of a file to be used as data, for example
2092// a test library to be installed alongside a test.
2093// The data file should be installed (copied from `<SrcPath>`) to
2094// `<install_root>/<RelativeInstallPath>/<filename>`, or
2095// `<install_root>/<filename>` if RelativeInstallPath is empty.
2096type DataPath struct {
2097 // The path of the data file that should be copied into the data directory
2098 SrcPath Path
2099 // The install path of the data file, relative to the install root.
2100 RelativeInstallPath string
2101}
Colin Crossdcf71b22021-02-01 13:59:03 -08002102
2103// PathsIfNonNil returns a Paths containing only the non-nil input arguments.
2104func PathsIfNonNil(paths ...Path) Paths {
2105 if len(paths) == 0 {
2106 // Fast path for empty argument list
2107 return nil
2108 } else if len(paths) == 1 {
2109 // Fast path for a single argument
2110 if paths[0] != nil {
2111 return paths
2112 } else {
2113 return nil
2114 }
2115 }
2116 ret := make(Paths, 0, len(paths))
2117 for _, path := range paths {
2118 if path != nil {
2119 ret = append(ret, path)
2120 }
2121 }
2122 if len(ret) == 0 {
2123 return nil
2124 }
2125 return ret
2126}
Chris Wailesb2703ad2021-07-30 13:25:42 -07002127
2128var thirdPartyDirPrefixExceptions = []*regexp.Regexp{
2129 regexp.MustCompile("^vendor/[^/]*google[^/]*/"),
2130 regexp.MustCompile("^hardware/google/"),
2131 regexp.MustCompile("^hardware/interfaces/"),
2132 regexp.MustCompile("^hardware/libhardware[^/]*/"),
2133 regexp.MustCompile("^hardware/ril/"),
2134}
2135
2136func IsThirdPartyPath(path string) bool {
2137 thirdPartyDirPrefixes := []string{"external/", "vendor/", "hardware/"}
2138
2139 if HasAnyPrefix(path, thirdPartyDirPrefixes) {
2140 for _, prefix := range thirdPartyDirPrefixExceptions {
2141 if prefix.MatchString(path) {
2142 return false
2143 }
2144 }
2145 return true
2146 }
2147 return false
2148}