blob: d4b1d6e297f167ff0b980311a7da88b89eb413f6 [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 "os"
Colin Cross6a745c62015-06-16 16:38:10 -070020 "path/filepath"
Dan Willemsen34cc69e2015-09-23 15:26:20 -070021 "reflect"
Chris Wailesb2703ad2021-07-30 13:25:42 -070022 "regexp"
Colin Cross5e6cfbe2017-11-03 15:20:35 -070023 "sort"
Dan Willemsen34cc69e2015-09-23 15:26:20 -070024 "strings"
25
26 "github.com/google/blueprint"
Colin Cross0e446152021-05-03 13:35:32 -070027 "github.com/google/blueprint/bootstrap"
Dan Willemsen34cc69e2015-09-23 15:26:20 -070028 "github.com/google/blueprint/pathtools"
Colin Cross3f40fa42015-01-30 17:27:36 -080029)
30
Colin Cross988414c2020-01-11 01:11:46 +000031var absSrcDir string
32
Dan Willemsen34cc69e2015-09-23 15:26:20 -070033// PathContext is the subset of a (Module|Singleton)Context required by the
34// Path methods.
35type PathContext interface {
Colin Crossaabf6792017-11-29 00:27:14 -080036 Config() Config
Dan Willemsen7b310ee2015-12-18 15:11:17 -080037 AddNinjaFileDeps(deps ...string)
Colin Cross3f40fa42015-01-30 17:27:36 -080038}
39
Colin Cross7f19f372016-11-01 11:10:25 -070040type PathGlobContext interface {
Colin Cross662d6142022-11-03 20:38:01 -070041 PathContext
Colin Cross7f19f372016-11-01 11:10:25 -070042 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 {
Liz Kammera830f3a2020-11-10 10:50:34 -080059 PathGlobContext
60
61 ModuleDir() string
62 ModuleErrorf(fmt string, args ...interface{})
63}
64
65var _ EarlyModulePathContext = ModuleContext(nil)
66
67// Glob globs files and directories matching globPattern relative to ModuleDir(),
68// paths in the excludes parameter will be omitted.
69func Glob(ctx EarlyModulePathContext, globPattern string, excludes []string) Paths {
70 ret, err := ctx.GlobWithDeps(globPattern, excludes)
71 if err != nil {
72 ctx.ModuleErrorf("glob: %s", err.Error())
73 }
74 return pathsForModuleSrcFromFullPath(ctx, ret, true)
75}
76
77// GlobFiles globs *only* files (not directories) matching globPattern relative to ModuleDir().
78// Paths in the excludes parameter will be omitted.
79func GlobFiles(ctx EarlyModulePathContext, globPattern string, excludes []string) Paths {
80 ret, err := ctx.GlobWithDeps(globPattern, excludes)
81 if err != nil {
82 ctx.ModuleErrorf("glob: %s", err.Error())
83 }
84 return pathsForModuleSrcFromFullPath(ctx, ret, false)
85}
86
87// ModuleWithDepsPathContext is a subset of *ModuleContext methods required by
88// the Path methods that rely on module dependencies having been resolved.
89type ModuleWithDepsPathContext interface {
90 EarlyModulePathContext
Paul Duffin40131a32021-07-09 17:10:35 +010091 VisitDirectDepsBlueprint(visit func(blueprint.Module))
92 OtherModuleDependencyTag(m blueprint.Module) blueprint.DependencyTag
Liz Kammera830f3a2020-11-10 10:50:34 -080093}
94
95// ModuleMissingDepsPathContext is a subset of *ModuleContext methods required by
96// the Path methods that rely on module dependencies having been resolved and ability to report
97// missing dependency errors.
98type ModuleMissingDepsPathContext interface {
99 ModuleWithDepsPathContext
100 AddMissingDependencies(missingDeps []string)
101}
102
Dan Willemsen00269f22017-07-06 16:59:48 -0700103type ModuleInstallPathContext interface {
Colin Cross0ea8ba82019-06-06 14:33:29 -0700104 BaseModuleContext
Dan Willemsen00269f22017-07-06 16:59:48 -0700105
106 InstallInData() bool
Jaewoong Jung0949f312019-09-11 10:25:18 -0700107 InstallInTestcases() bool
Dan Willemsen00269f22017-07-06 16:59:48 -0700108 InstallInSanitizerDir() bool
Yifan Hong1b3348d2020-01-21 15:53:22 -0800109 InstallInRamdisk() bool
Yifan Hong60e0cfb2020-10-21 15:17:56 -0700110 InstallInVendorRamdisk() bool
Inseob Kim08758f02021-04-08 21:13:22 +0900111 InstallInDebugRamdisk() bool
Jiyong Parkf9332f12018-02-01 00:54:12 +0900112 InstallInRecovery() bool
Colin Cross90ba5f42019-10-02 11:10:58 -0700113 InstallInRoot() bool
Jiyong Park87788b52020-09-01 12:37:45 +0900114 InstallForceOS() (*OsType, *ArchType)
Dan Willemsen00269f22017-07-06 16:59:48 -0700115}
116
117var _ ModuleInstallPathContext = ModuleContext(nil)
118
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700119// errorfContext is the interface containing the Errorf method matching the
120// Errorf method in blueprint.SingletonContext.
121type errorfContext interface {
122 Errorf(format string, args ...interface{})
Colin Cross3f40fa42015-01-30 17:27:36 -0800123}
124
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700125var _ errorfContext = blueprint.SingletonContext(nil)
126
127// moduleErrorf is the interface containing the ModuleErrorf method matching
128// the ModuleErrorf method in blueprint.ModuleContext.
129type moduleErrorf interface {
130 ModuleErrorf(format string, args ...interface{})
Colin Cross3f40fa42015-01-30 17:27:36 -0800131}
132
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700133var _ moduleErrorf = blueprint.ModuleContext(nil)
134
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700135// reportPathError will register an error with the attached context. It
136// attempts ctx.ModuleErrorf for a better error message first, then falls
137// back to ctx.Errorf.
Colin Cross1ccfcc32018-02-22 13:54:26 -0800138func reportPathError(ctx PathContext, err error) {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +0100139 ReportPathErrorf(ctx, "%s", err.Error())
Colin Cross1ccfcc32018-02-22 13:54:26 -0800140}
141
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +0100142// ReportPathErrorf will register an error with the attached context. It
Colin Cross1ccfcc32018-02-22 13:54:26 -0800143// attempts ctx.ModuleErrorf for a better error message first, then falls
144// back to ctx.Errorf.
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +0100145func ReportPathErrorf(ctx PathContext, format string, args ...interface{}) {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700146 if mctx, ok := ctx.(moduleErrorf); ok {
147 mctx.ModuleErrorf(format, args...)
148 } else if ectx, ok := ctx.(errorfContext); ok {
149 ectx.Errorf(format, args...)
150 } else {
151 panic(fmt.Sprintf(format, args...))
Colin Crossf2298272015-05-12 11:36:53 -0700152 }
153}
154
Colin Cross5e708052019-08-06 13:59:50 -0700155func pathContextName(ctx PathContext, module blueprint.Module) string {
156 if x, ok := ctx.(interface{ ModuleName(blueprint.Module) string }); ok {
157 return x.ModuleName(module)
158 } else if x, ok := ctx.(interface{ OtherModuleName(blueprint.Module) string }); ok {
159 return x.OtherModuleName(module)
160 }
161 return "unknown"
162}
163
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700164type Path interface {
165 // Returns the path in string form
166 String() string
167
Colin Cross4f6fc9c2016-10-26 10:05:25 -0700168 // Ext returns the extension of the last element of the path
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700169 Ext() string
Colin Cross4f6fc9c2016-10-26 10:05:25 -0700170
171 // Base returns the last element of the path
172 Base() string
Colin Crossfaeb7aa2017-02-01 14:12:44 -0800173
Sam Delmericoa588d152023-06-16 10:28:04 -0400174 // Dir returns a path pointing the directory containing the path
175 Dir() Path
176
Colin Crossfaeb7aa2017-02-01 14:12:44 -0800177 // Rel returns the portion of the path relative to the directory it was created from. For
178 // example, Rel on a PathsForModuleSrc would return the path relative to the module source
Colin Cross0db55682017-12-05 15:36:55 -0800179 // directory, and OutputPath.Join("foo").Rel() would return "foo".
Colin Crossfaeb7aa2017-02-01 14:12:44 -0800180 Rel() string
Paul Duffin85d8f0d2021-03-24 10:18:18 +0000181
182 // RelativeToTop returns a new path relative to the top, it is provided solely for use in tests.
183 //
184 // It is guaranteed to always return the same type as it is called on, e.g. if called on an
185 // InstallPath then the returned value can be converted to an InstallPath.
186 //
187 // A standard build has the following structure:
188 // ../top/
189 // out/ - make install files go here.
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +0200190 // out/soong - this is the soongOutDir passed to NewTestConfig()
Paul Duffin85d8f0d2021-03-24 10:18:18 +0000191 // ... - the source files
192 //
193 // This function converts a path so that it appears relative to the ../top/ directory, i.e.
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +0200194 // * Make install paths, which have the pattern "soongOutDir/../<path>" are converted into the top
Paul Duffin85d8f0d2021-03-24 10:18:18 +0000195 // relative path "out/<path>"
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +0200196 // * Soong install paths and other writable paths, which have the pattern "soongOutDir/<path>" are
Paul Duffin85d8f0d2021-03-24 10:18:18 +0000197 // converted into the top relative path "out/soong/<path>".
198 // * Source paths are already relative to the top.
199 // * Phony paths are not relative to anything.
200 // * toolDepPath have an absolute but known value in so don't need making relative to anything in
201 // order to test.
202 RelativeToTop() Path
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700203}
204
Paul Duffin85d8f0d2021-03-24 10:18:18 +0000205const (
206 OutDir = "out"
207 OutSoongDir = OutDir + "/soong"
208)
209
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700210// WritablePath is a type of path that can be used as an output for build rules.
211type WritablePath interface {
212 Path
213
Paul Duffin9b478b02019-12-10 13:41:51 +0000214 // return the path to the build directory.
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +0200215 getSoongOutDir() string
Paul Duffin9b478b02019-12-10 13:41:51 +0000216
Jeff Gaston734e3802017-04-10 15:47:24 -0700217 // the writablePath method doesn't directly do anything,
218 // but it allows a struct to distinguish between whether or not it implements the WritablePath interface
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700219 writablePath()
Hans MÃ¥nssond3f2bd72020-11-27 12:37:28 +0100220
221 ReplaceExtension(ctx PathContext, ext string) OutputPath
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700222}
223
224type genPathProvider interface {
Liz Kammera830f3a2020-11-10 10:50:34 -0800225 genPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleGenPath
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700226}
227type objPathProvider interface {
Liz Kammera830f3a2020-11-10 10:50:34 -0800228 objPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleObjPath
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700229}
230type resPathProvider interface {
Liz Kammera830f3a2020-11-10 10:50:34 -0800231 resPathWithName(ctx ModuleOutPathContext, name string) ModuleResPath
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700232}
233
234// GenPathWithExt derives a new file path in ctx's generated sources directory
235// from the current path, but with the new extension.
Liz Kammera830f3a2020-11-10 10:50:34 -0800236func GenPathWithExt(ctx ModuleOutPathContext, subdir string, p Path, ext string) ModuleGenPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700237 if path, ok := p.(genPathProvider); ok {
Dan Willemsen21ec4902016-11-02 20:43:13 -0700238 return path.genPathWithExt(ctx, subdir, ext)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700239 }
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +0100240 ReportPathErrorf(ctx, "Tried to create generated file from unsupported path: %s(%s)", reflect.TypeOf(p).Name(), p)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700241 return PathForModuleGen(ctx)
242}
243
244// ObjPathWithExt derives a new file path in ctx's object directory from the
245// current path, but with the new extension.
Liz Kammera830f3a2020-11-10 10:50:34 -0800246func ObjPathWithExt(ctx ModuleOutPathContext, subdir string, p Path, ext string) ModuleObjPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700247 if path, ok := p.(objPathProvider); ok {
248 return path.objPathWithExt(ctx, subdir, ext)
249 }
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +0100250 ReportPathErrorf(ctx, "Tried to create object file from unsupported path: %s (%s)", reflect.TypeOf(p).Name(), p)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700251 return PathForModuleObj(ctx)
252}
253
254// ResPathWithName derives a new path in ctx's output resource directory, using
255// the current path to create the directory name, and the `name` argument for
256// the filename.
Liz Kammera830f3a2020-11-10 10:50:34 -0800257func ResPathWithName(ctx ModuleOutPathContext, p Path, name string) ModuleResPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700258 if path, ok := p.(resPathProvider); ok {
259 return path.resPathWithName(ctx, name)
260 }
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +0100261 ReportPathErrorf(ctx, "Tried to create res file from unsupported path: %s (%s)", reflect.TypeOf(p).Name(), p)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700262 return PathForModuleRes(ctx)
263}
264
265// OptionalPath is a container that may or may not contain a valid Path.
266type OptionalPath struct {
Martin Stjernholmc32dd1c2021-09-15 02:39:00 +0100267 path Path // nil if invalid.
268 invalidReason string // Not applicable if path != nil. "" if the reason is unknown.
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700269}
270
271// OptionalPathForPath returns an OptionalPath containing the path.
272func OptionalPathForPath(path Path) OptionalPath {
Martin Stjernholm2fee27f2021-09-16 14:11:12 +0100273 return OptionalPath{path: path}
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700274}
275
Martin Stjernholmc32dd1c2021-09-15 02:39:00 +0100276// InvalidOptionalPath returns an OptionalPath that is invalid with the given reason.
277func InvalidOptionalPath(reason string) OptionalPath {
278
279 return OptionalPath{invalidReason: reason}
280}
281
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700282// Valid returns whether there is a valid path
283func (p OptionalPath) Valid() bool {
Martin Stjernholm2fee27f2021-09-16 14:11:12 +0100284 return p.path != nil
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700285}
286
287// Path returns the Path embedded in this OptionalPath. You must be sure that
288// there is a valid path, since this method will panic if there is not.
289func (p OptionalPath) Path() Path {
Martin Stjernholm2fee27f2021-09-16 14:11:12 +0100290 if p.path == nil {
Martin Stjernholmc32dd1c2021-09-15 02:39:00 +0100291 msg := "Requesting an invalid path"
292 if p.invalidReason != "" {
293 msg += ": " + p.invalidReason
294 }
295 panic(msg)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700296 }
297 return p.path
298}
299
Martin Stjernholmc32dd1c2021-09-15 02:39:00 +0100300// InvalidReason returns the reason that the optional path is invalid, or "" if it is valid.
301func (p OptionalPath) InvalidReason() string {
302 if p.path != nil {
303 return ""
304 }
305 if p.invalidReason == "" {
306 return "unknown"
307 }
308 return p.invalidReason
309}
310
Paul Duffinef081852021-05-13 11:11:15 +0100311// AsPaths converts the OptionalPath into Paths.
312//
313// It returns nil if this is not valid, or a single length slice containing the Path embedded in
314// this OptionalPath.
315func (p OptionalPath) AsPaths() Paths {
Martin Stjernholm2fee27f2021-09-16 14:11:12 +0100316 if p.path == nil {
Paul Duffinef081852021-05-13 11:11:15 +0100317 return nil
318 }
319 return Paths{p.path}
320}
321
Paul Duffinafdd4062021-03-30 19:44:07 +0100322// RelativeToTop returns an OptionalPath with the path that was embedded having been replaced by the
323// result of calling Path.RelativeToTop on it.
324func (p OptionalPath) RelativeToTop() OptionalPath {
Martin Stjernholm2fee27f2021-09-16 14:11:12 +0100325 if p.path == nil {
Paul Duffina5b81352021-03-28 23:57:19 +0100326 return p
327 }
328 p.path = p.path.RelativeToTop()
329 return p
330}
331
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700332// String returns the string version of the Path, or "" if it isn't valid.
333func (p OptionalPath) String() string {
Martin Stjernholm2fee27f2021-09-16 14:11:12 +0100334 if p.path != nil {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700335 return p.path.String()
336 } else {
337 return ""
Colin Crossf2298272015-05-12 11:36:53 -0700338 }
339}
Colin Cross6e18ca42015-07-14 18:55:36 -0700340
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700341// Paths is a slice of Path objects, with helpers to operate on the collection.
342type Paths []Path
343
Paul Duffin85d8f0d2021-03-24 10:18:18 +0000344// RelativeToTop creates a new Paths containing the result of calling Path.RelativeToTop on each
345// item in this slice.
346func (p Paths) RelativeToTop() Paths {
347 ensureTestOnly()
348 if p == nil {
349 return p
350 }
351 ret := make(Paths, len(p))
352 for i, path := range p {
353 ret[i] = path.RelativeToTop()
354 }
355 return ret
356}
357
Jingwen Chen40fd90a2020-06-15 05:24:19 +0000358func (paths Paths) containsPath(path Path) bool {
359 for _, p := range paths {
360 if p == path {
361 return true
362 }
363 }
364 return false
365}
366
Liz Kammer7aa52882021-02-11 09:16:14 -0500367// PathsForSource returns Paths rooted from SrcDir, *not* rooted from the module's local source
368// directory
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700369func PathsForSource(ctx PathContext, paths []string) Paths {
370 ret := make(Paths, len(paths))
371 for i, path := range paths {
372 ret[i] = PathForSource(ctx, path)
373 }
374 return ret
375}
376
Liz Kammer7aa52882021-02-11 09:16:14 -0500377// ExistentPathsForSources returns a list of Paths rooted from SrcDir, *not* rooted from the
378// module's local source directory, that are found in the tree. If any are not found, they are
379// omitted from the list, and dependencies are added so that we're re-run when they are added.
Colin Cross662d6142022-11-03 20:38:01 -0700380func ExistentPathsForSources(ctx PathGlobContext, paths []string) Paths {
Dan Willemsen7b310ee2015-12-18 15:11:17 -0800381 ret := make(Paths, 0, len(paths))
382 for _, path := range paths {
Colin Cross32f38982018-02-22 11:47:25 -0800383 p := ExistentPathForSource(ctx, path)
Dan Willemsen7b310ee2015-12-18 15:11:17 -0800384 if p.Valid() {
385 ret = append(ret, p.Path())
386 }
387 }
388 return ret
389}
390
Liz Kammer620dea62021-04-14 17:36:10 -0400391// PathsForModuleSrc returns a Paths{} containing the resolved references in paths:
Colin Crossd079e0b2022-08-16 10:27:33 -0700392// - filepath, relative to local module directory, resolves as a filepath relative to the local
393// source directory
394// - glob, relative to the local module directory, resolves as filepath(s), relative to the local
395// source directory.
396// - other modules using the ":name{.tag}" syntax. These modules must implement SourceFileProducer
397// or OutputFileProducer. These resolve as a filepath to an output filepath or generated source
398// filepath.
399//
Liz Kammer620dea62021-04-14 17:36:10 -0400400// Properties passed as the paths argument must have been annotated with struct tag
Colin Cross41955e82019-05-29 14:40:35 -0700401// `android:"path"` so that dependencies on SourceFileProducer modules will have already been handled by the
Spandan Das950091c2023-07-19 22:26:37 +0000402// pathdeps mutator.
Liz Kammer620dea62021-04-14 17:36:10 -0400403// If a requested module is not found as a dependency:
Colin Crossd079e0b2022-08-16 10:27:33 -0700404// - if ctx.Config().AllowMissingDependencies() is true, this module to be marked as having
Liz Kammer620dea62021-04-14 17:36:10 -0400405// missing dependencies
Colin Crossd079e0b2022-08-16 10:27:33 -0700406// - otherwise, a ModuleError is thrown.
Liz Kammera830f3a2020-11-10 10:50:34 -0800407func PathsForModuleSrc(ctx ModuleMissingDepsPathContext, paths []string) Paths {
Colin Cross8a497952019-03-05 22:25:09 -0800408 return PathsForModuleSrcExcludes(ctx, paths, nil)
409}
410
Liz Kammer619be462022-01-28 15:13:39 -0500411type SourceInput struct {
412 Context ModuleMissingDepsPathContext
413 Paths []string
414 ExcludePaths []string
415 IncludeDirs bool
416}
417
Liz Kammer620dea62021-04-14 17:36:10 -0400418// PathsForModuleSrcExcludes returns a Paths{} containing the resolved references in paths, minus
419// those listed in excludes. Elements of paths and excludes are resolved as:
Colin Crossd079e0b2022-08-16 10:27:33 -0700420// - filepath, relative to local module directory, resolves as a filepath relative to the local
421// source directory
422// - glob, relative to the local module directory, resolves as filepath(s), relative to the local
423// source directory. Not valid in excludes.
424// - other modules using the ":name{.tag}" syntax. These modules must implement SourceFileProducer
425// or OutputFileProducer. These resolve as a filepath to an output filepath or generated source
426// filepath.
427//
Liz Kammer620dea62021-04-14 17:36:10 -0400428// excluding the items (similarly resolved
429// Properties passed as the paths argument must have been annotated with struct tag
430// `android:"path"` so that dependencies on SourceFileProducer modules will have already been handled by the
Spandan Das950091c2023-07-19 22:26:37 +0000431// pathdeps mutator.
Liz Kammer620dea62021-04-14 17:36:10 -0400432// If a requested module is not found as a dependency:
Colin Crossd079e0b2022-08-16 10:27:33 -0700433// - if ctx.Config().AllowMissingDependencies() is true, this module to be marked as having
Liz Kammer620dea62021-04-14 17:36:10 -0400434// missing dependencies
Colin Crossd079e0b2022-08-16 10:27:33 -0700435// - otherwise, a ModuleError is thrown.
Liz Kammera830f3a2020-11-10 10:50:34 -0800436func PathsForModuleSrcExcludes(ctx ModuleMissingDepsPathContext, paths, excludes []string) Paths {
Liz Kammer619be462022-01-28 15:13:39 -0500437 return PathsRelativeToModuleSourceDir(SourceInput{
438 Context: ctx,
439 Paths: paths,
440 ExcludePaths: excludes,
441 IncludeDirs: true,
442 })
443}
444
445func PathsRelativeToModuleSourceDir(input SourceInput) Paths {
446 ret, missingDeps := PathsAndMissingDepsRelativeToModuleSourceDir(input)
447 if input.Context.Config().AllowMissingDependencies() {
448 input.Context.AddMissingDependencies(missingDeps)
Colin Crossba71a3f2019-03-18 12:12:48 -0700449 } else {
450 for _, m := range missingDeps {
Liz Kammer619be462022-01-28 15:13:39 -0500451 input.Context.ModuleErrorf(`missing dependency on %q, is the property annotated with android:"path"?`, m)
Colin Crossba71a3f2019-03-18 12:12:48 -0700452 }
453 }
454 return ret
455}
456
Ulya Trafimovich4d2eeed2019-11-08 10:54:21 +0000457// OutputPaths is a slice of OutputPath objects, with helpers to operate on the collection.
458type OutputPaths []OutputPath
459
460// Paths returns the OutputPaths as a Paths
461func (p OutputPaths) Paths() Paths {
462 if p == nil {
463 return nil
464 }
465 ret := make(Paths, len(p))
466 for i, path := range p {
467 ret[i] = path
468 }
469 return ret
470}
471
472// Strings returns the string forms of the writable paths.
473func (p OutputPaths) Strings() []string {
474 if p == nil {
475 return nil
476 }
477 ret := make([]string, len(p))
478 for i, path := range p {
479 ret[i] = path.String()
480 }
481 return ret
482}
483
Colin Crossa44551f2021-10-25 15:36:21 -0700484// PathForGoBinary returns the path to the installed location of a bootstrap_go_binary module.
485func PathForGoBinary(ctx PathContext, goBinary bootstrap.GoBinaryTool) Path {
486 goBinaryInstallDir := pathForInstall(ctx, ctx.Config().BuildOS, ctx.Config().BuildArch, "bin", false)
487 rel := Rel(ctx, goBinaryInstallDir.String(), goBinary.InstallPath())
488 return goBinaryInstallDir.Join(ctx, rel)
489}
490
Liz Kammera830f3a2020-11-10 10:50:34 -0800491// Expands Paths to a SourceFileProducer or OutputFileProducer module dependency referenced via ":name" or ":name{.tag}" syntax.
492// If the dependency is not found, a missingErrorDependency is returned.
493// If the module dependency is not a SourceFileProducer or OutputFileProducer, appropriate errors will be returned.
494func getPathsFromModuleDep(ctx ModuleWithDepsPathContext, path, moduleName, tag string) (Paths, error) {
Paul Duffind5cf92e2021-07-09 17:38:55 +0100495 module := GetModuleFromPathDep(ctx, moduleName, tag)
Liz Kammera830f3a2020-11-10 10:50:34 -0800496 if module == nil {
497 return nil, missingDependencyError{[]string{moduleName}}
498 }
Colin Crossfa65cee2021-03-22 17:05:59 -0700499 if aModule, ok := module.(Module); ok && !aModule.Enabled() {
500 return nil, missingDependencyError{[]string{moduleName}}
501 }
Liz Kammera830f3a2020-11-10 10:50:34 -0800502 if outProducer, ok := module.(OutputFileProducer); ok {
503 outputFiles, err := outProducer.OutputFiles(tag)
504 if err != nil {
505 return nil, fmt.Errorf("path dependency %q: %s", path, err)
506 }
507 return outputFiles, nil
508 } else if tag != "" {
509 return nil, fmt.Errorf("path dependency %q is not an output file producing module", path)
Colin Cross0e446152021-05-03 13:35:32 -0700510 } else if goBinary, ok := module.(bootstrap.GoBinaryTool); ok {
Colin Crossa44551f2021-10-25 15:36:21 -0700511 goBinaryPath := PathForGoBinary(ctx, goBinary)
512 return Paths{goBinaryPath}, nil
Liz Kammera830f3a2020-11-10 10:50:34 -0800513 } else if srcProducer, ok := module.(SourceFileProducer); ok {
514 return srcProducer.Srcs(), nil
515 } else {
516 return nil, fmt.Errorf("path dependency %q is not a source file producing module", path)
517 }
518}
519
Paul Duffind5cf92e2021-07-09 17:38:55 +0100520// GetModuleFromPathDep will return the module that was added as a dependency automatically for
521// properties tagged with `android:"path"` or manually using ExtractSourceDeps or
522// ExtractSourcesDeps.
523//
524// The moduleName and tag supplied to this should be the values returned from SrcIsModuleWithTag.
525// Or, if no tag is expected then the moduleName should be the value returned by SrcIsModule and
526// the tag must be "".
527//
528// If tag is "" then the returned module will be the dependency that was added for ":moduleName".
529// Otherwise, it is the dependency that was added for ":moduleName{tag}".
Paul Duffind5cf92e2021-07-09 17:38:55 +0100530func GetModuleFromPathDep(ctx ModuleWithDepsPathContext, moduleName, tag string) blueprint.Module {
Paul Duffin40131a32021-07-09 17:10:35 +0100531 var found blueprint.Module
532 // The sourceOrOutputDepTag uniquely identifies the module dependency as it contains both the
533 // module name and the tag. Dependencies added automatically for properties tagged with
534 // `android:"path"` are deduped so are guaranteed to be unique. It is possible for duplicate
535 // dependencies to be added manually using ExtractSourcesDeps or ExtractSourceDeps but even then
536 // it will always be the case that the dependencies will be identical, i.e. the same tag and same
537 // moduleName referring to the same dependency module.
538 //
539 // It does not matter whether the moduleName is a fully qualified name or if the module
540 // dependency is a prebuilt module. All that matters is the same information is supplied to
541 // create the tag here as was supplied to create the tag when the dependency was added so that
542 // this finds the matching dependency module.
543 expectedTag := sourceOrOutputDepTag(moduleName, tag)
544 ctx.VisitDirectDepsBlueprint(func(module blueprint.Module) {
545 depTag := ctx.OtherModuleDependencyTag(module)
546 if depTag == expectedTag {
547 found = module
548 }
549 })
550 return found
Paul Duffind5cf92e2021-07-09 17:38:55 +0100551}
552
Liz Kammer620dea62021-04-14 17:36:10 -0400553// PathsAndMissingDepsForModuleSrcExcludes returns a Paths{} containing the resolved references in
554// paths, minus those listed in excludes. Elements of paths and excludes are resolved as:
Colin Crossd079e0b2022-08-16 10:27:33 -0700555// - filepath, relative to local module directory, resolves as a filepath relative to the local
556// source directory
557// - glob, relative to the local module directory, resolves as filepath(s), relative to the local
558// source directory. Not valid in excludes.
559// - other modules using the ":name{.tag}" syntax. These modules must implement SourceFileProducer
560// or OutputFileProducer. These resolve as a filepath to an output filepath or generated source
561// filepath.
562//
Liz Kammer620dea62021-04-14 17:36:10 -0400563// and a list of the module names of missing module dependencies are returned as the second return.
564// Properties passed as the paths argument must have been annotated with struct tag
Colin Cross41955e82019-05-29 14:40:35 -0700565// `android:"path"` so that dependencies on SourceFileProducer modules will have already been handled by the
Spandan Das950091c2023-07-19 22:26:37 +0000566// pathdeps mutator.
Liz Kammer619be462022-01-28 15:13:39 -0500567func PathsAndMissingDepsForModuleSrcExcludes(ctx ModuleMissingDepsPathContext, paths, excludes []string) (Paths, []string) {
568 return PathsAndMissingDepsRelativeToModuleSourceDir(SourceInput{
569 Context: ctx,
570 Paths: paths,
571 ExcludePaths: excludes,
572 IncludeDirs: true,
573 })
574}
575
576func PathsAndMissingDepsRelativeToModuleSourceDir(input SourceInput) (Paths, []string) {
577 prefix := pathForModuleSrc(input.Context).String()
Colin Cross8a497952019-03-05 22:25:09 -0800578
579 var expandedExcludes []string
Liz Kammer619be462022-01-28 15:13:39 -0500580 if input.ExcludePaths != nil {
581 expandedExcludes = make([]string, 0, len(input.ExcludePaths))
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700582 }
Colin Cross8a497952019-03-05 22:25:09 -0800583
Colin Crossba71a3f2019-03-18 12:12:48 -0700584 var missingExcludeDeps []string
Liz Kammer619be462022-01-28 15:13:39 -0500585 for _, e := range input.ExcludePaths {
Colin Cross41955e82019-05-29 14:40:35 -0700586 if m, t := SrcIsModuleWithTag(e); m != "" {
Liz Kammer619be462022-01-28 15:13:39 -0500587 modulePaths, err := getPathsFromModuleDep(input.Context, e, m, t)
Liz Kammera830f3a2020-11-10 10:50:34 -0800588 if m, ok := err.(missingDependencyError); ok {
589 missingExcludeDeps = append(missingExcludeDeps, m.missingDeps...)
590 } else if err != nil {
Liz Kammer619be462022-01-28 15:13:39 -0500591 reportPathError(input.Context, err)
Colin Cross8a497952019-03-05 22:25:09 -0800592 } else {
Liz Kammera830f3a2020-11-10 10:50:34 -0800593 expandedExcludes = append(expandedExcludes, modulePaths.Strings()...)
Colin Cross8a497952019-03-05 22:25:09 -0800594 }
595 } else {
596 expandedExcludes = append(expandedExcludes, filepath.Join(prefix, e))
597 }
598 }
599
Liz Kammer619be462022-01-28 15:13:39 -0500600 if input.Paths == nil {
Colin Crossba71a3f2019-03-18 12:12:48 -0700601 return nil, missingExcludeDeps
Colin Cross8a497952019-03-05 22:25:09 -0800602 }
603
Colin Crossba71a3f2019-03-18 12:12:48 -0700604 var missingDeps []string
605
Liz Kammer619be462022-01-28 15:13:39 -0500606 expandedSrcFiles := make(Paths, 0, len(input.Paths))
607 for _, s := range input.Paths {
608 srcFiles, err := expandOneSrcPath(sourcePathInput{
609 context: input.Context,
610 path: s,
611 expandedExcludes: expandedExcludes,
612 includeDirs: input.IncludeDirs,
613 })
Colin Cross8a497952019-03-05 22:25:09 -0800614 if depErr, ok := err.(missingDependencyError); ok {
Colin Crossba71a3f2019-03-18 12:12:48 -0700615 missingDeps = append(missingDeps, depErr.missingDeps...)
Colin Cross8a497952019-03-05 22:25:09 -0800616 } else if err != nil {
Liz Kammer619be462022-01-28 15:13:39 -0500617 reportPathError(input.Context, err)
Colin Cross8a497952019-03-05 22:25:09 -0800618 }
619 expandedSrcFiles = append(expandedSrcFiles, srcFiles...)
620 }
Colin Crossba71a3f2019-03-18 12:12:48 -0700621
622 return expandedSrcFiles, append(missingDeps, missingExcludeDeps...)
Colin Cross8a497952019-03-05 22:25:09 -0800623}
624
625type missingDependencyError struct {
626 missingDeps []string
627}
628
629func (e missingDependencyError) Error() string {
630 return "missing dependencies: " + strings.Join(e.missingDeps, ", ")
631}
632
Liz Kammer619be462022-01-28 15:13:39 -0500633type sourcePathInput struct {
634 context ModuleWithDepsPathContext
635 path string
636 expandedExcludes []string
637 includeDirs bool
638}
639
Liz Kammera830f3a2020-11-10 10:50:34 -0800640// Expands one path string to Paths rooted from the module's local source
641// directory, excluding those listed in the expandedExcludes.
642// Expands globs, references to SourceFileProducer or OutputFileProducer modules using the ":name" and ":name{.tag}" syntax.
Liz Kammer619be462022-01-28 15:13:39 -0500643func expandOneSrcPath(input sourcePathInput) (Paths, error) {
Jooyung Han7607dd32020-07-05 10:23:14 +0900644 excludePaths := func(paths Paths) Paths {
Liz Kammer619be462022-01-28 15:13:39 -0500645 if len(input.expandedExcludes) == 0 {
Jooyung Han7607dd32020-07-05 10:23:14 +0900646 return paths
647 }
648 remainder := make(Paths, 0, len(paths))
649 for _, p := range paths {
Liz Kammer619be462022-01-28 15:13:39 -0500650 if !InList(p.String(), input.expandedExcludes) {
Jooyung Han7607dd32020-07-05 10:23:14 +0900651 remainder = append(remainder, p)
652 }
653 }
654 return remainder
655 }
Liz Kammer619be462022-01-28 15:13:39 -0500656 if m, t := SrcIsModuleWithTag(input.path); m != "" {
657 modulePaths, err := getPathsFromModuleDep(input.context, input.path, m, t)
Liz Kammera830f3a2020-11-10 10:50:34 -0800658 if err != nil {
659 return nil, err
Colin Cross8a497952019-03-05 22:25:09 -0800660 } else {
Liz Kammera830f3a2020-11-10 10:50:34 -0800661 return excludePaths(modulePaths), nil
Colin Cross8a497952019-03-05 22:25:09 -0800662 }
Colin Cross8a497952019-03-05 22:25:09 -0800663 } else {
Liz Kammer619be462022-01-28 15:13:39 -0500664 p := pathForModuleSrc(input.context, input.path)
665 if pathtools.IsGlob(input.path) {
666 paths := GlobFiles(input.context, p.String(), input.expandedExcludes)
667 return PathsWithModuleSrcSubDir(input.context, paths, ""), nil
668 } else {
669 if exists, _, err := input.context.Config().fs.Exists(p.String()); err != nil {
670 ReportPathErrorf(input.context, "%s: %s", p, err.Error())
671 } else if !exists && !input.context.Config().TestAllowNonExistentPaths {
672 ReportPathErrorf(input.context, "module source path %q does not exist", p)
673 } else if !input.includeDirs {
674 if isDir, err := input.context.Config().fs.IsDir(p.String()); exists && err != nil {
675 ReportPathErrorf(input.context, "%s: %s", p, err.Error())
676 } else if isDir {
677 ReportPathErrorf(input.context, "module source path %q is a directory", p)
678 }
679 }
Colin Cross8a497952019-03-05 22:25:09 -0800680
Liz Kammer619be462022-01-28 15:13:39 -0500681 if InList(p.String(), input.expandedExcludes) {
682 return nil, nil
683 }
684 return Paths{p}, nil
Colin Cross8a497952019-03-05 22:25:09 -0800685 }
Colin Cross8a497952019-03-05 22:25:09 -0800686 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700687}
688
689// pathsForModuleSrcFromFullPath returns Paths rooted from the module's local
690// source directory, but strip the local source directory from the beginning of
Dan Willemsen540a78c2018-02-26 21:50:08 -0800691// each string. If incDirs is false, strip paths with a trailing '/' from the list.
Colin Crossfe4bc362018-09-12 10:02:13 -0700692// It intended for use in globs that only list files that exist, so it allows '$' in
693// filenames.
Liz Kammera830f3a2020-11-10 10:50:34 -0800694func pathsForModuleSrcFromFullPath(ctx EarlyModulePathContext, paths []string, incDirs bool) Paths {
Lukacs T. Berkif7e36d82021-08-16 17:05:09 +0200695 prefix := ctx.ModuleDir() + "/"
Colin Cross0f37af02017-09-27 17:42:05 -0700696 if prefix == "./" {
697 prefix = ""
698 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700699 ret := make(Paths, 0, len(paths))
700 for _, p := range paths {
Dan Willemsen540a78c2018-02-26 21:50:08 -0800701 if !incDirs && strings.HasSuffix(p, "/") {
702 continue
703 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700704 path := filepath.Clean(p)
705 if !strings.HasPrefix(path, prefix) {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +0100706 ReportPathErrorf(ctx, "Path %q is not in module source directory %q", p, prefix)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700707 continue
708 }
Colin Crosse3924e12018-08-15 20:18:53 -0700709
Colin Crossfe4bc362018-09-12 10:02:13 -0700710 srcPath, err := safePathForSource(ctx, ctx.ModuleDir(), path[len(prefix):])
Colin Crosse3924e12018-08-15 20:18:53 -0700711 if err != nil {
712 reportPathError(ctx, err)
713 continue
714 }
715
Colin Cross07e51612019-03-05 12:46:40 -0800716 srcPath.basePath.rel = srcPath.path
Colin Crosse3924e12018-08-15 20:18:53 -0700717
Colin Cross07e51612019-03-05 12:46:40 -0800718 ret = append(ret, srcPath)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700719 }
720 return ret
721}
722
Liz Kammera830f3a2020-11-10 10:50:34 -0800723// PathsWithOptionalDefaultForModuleSrc returns Paths rooted from the module's local source
724// directory. If input is nil, use the default if it exists. If input is empty, returns nil.
725func PathsWithOptionalDefaultForModuleSrc(ctx ModuleMissingDepsPathContext, input []string, def string) Paths {
Colin Cross0ddae7f2019-02-07 15:30:01 -0800726 if input != nil {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700727 return PathsForModuleSrc(ctx, input)
728 }
729 // Use Glob so that if the default doesn't exist, a dependency is added so that when it
730 // is created, we're run again.
Lukacs T. Berkif7e36d82021-08-16 17:05:09 +0200731 path := filepath.Join(ctx.ModuleDir(), def)
Liz Kammera830f3a2020-11-10 10:50:34 -0800732 return Glob(ctx, path, nil)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700733}
734
735// Strings returns the Paths in string form
736func (p Paths) Strings() []string {
737 if p == nil {
738 return nil
739 }
740 ret := make([]string, len(p))
741 for i, path := range p {
742 ret[i] = path.String()
743 }
744 return ret
745}
746
Colin Crossc0efd1d2020-07-03 11:56:24 -0700747func CopyOfPaths(paths Paths) Paths {
748 return append(Paths(nil), paths...)
749}
750
Colin Crossb6715442017-10-24 11:13:31 -0700751// FirstUniquePaths returns all unique elements of a Paths, keeping the first copy of each. It
752// modifies the Paths slice contents in place, and returns a subslice of the original slice.
Dan Willemsenfe92c962017-08-29 12:28:37 -0700753func FirstUniquePaths(list Paths) Paths {
Colin Cross27027c72020-02-28 15:34:17 -0800754 // 128 was chosen based on BenchmarkFirstUniquePaths results.
755 if len(list) > 128 {
756 return firstUniquePathsMap(list)
757 }
758 return firstUniquePathsList(list)
759}
760
Colin Crossc0efd1d2020-07-03 11:56:24 -0700761// SortedUniquePaths returns all unique elements of a Paths in sorted order. It modifies the
762// Paths slice contents in place, and returns a subslice of the original slice.
Jiyong Park33c77362020-05-29 22:00:16 +0900763func SortedUniquePaths(list Paths) Paths {
764 unique := FirstUniquePaths(list)
765 sort.Slice(unique, func(i, j int) bool {
766 return unique[i].String() < unique[j].String()
767 })
768 return unique
769}
770
Colin Cross27027c72020-02-28 15:34:17 -0800771func firstUniquePathsList(list Paths) Paths {
Dan Willemsenfe92c962017-08-29 12:28:37 -0700772 k := 0
773outer:
774 for i := 0; i < len(list); i++ {
775 for j := 0; j < k; j++ {
776 if list[i] == list[j] {
777 continue outer
778 }
779 }
780 list[k] = list[i]
781 k++
782 }
783 return list[:k]
784}
785
Colin Cross27027c72020-02-28 15:34:17 -0800786func firstUniquePathsMap(list Paths) Paths {
787 k := 0
788 seen := make(map[Path]bool, len(list))
789 for i := 0; i < len(list); i++ {
790 if seen[list[i]] {
791 continue
792 }
793 seen[list[i]] = true
794 list[k] = list[i]
795 k++
796 }
797 return list[:k]
798}
799
Colin Cross5d583952020-11-24 16:21:24 -0800800// FirstUniqueInstallPaths returns all unique elements of an InstallPaths, keeping the first copy of each. It
801// modifies the InstallPaths slice contents in place, and returns a subslice of the original slice.
802func FirstUniqueInstallPaths(list InstallPaths) InstallPaths {
803 // 128 was chosen based on BenchmarkFirstUniquePaths results.
804 if len(list) > 128 {
805 return firstUniqueInstallPathsMap(list)
806 }
807 return firstUniqueInstallPathsList(list)
808}
809
810func firstUniqueInstallPathsList(list InstallPaths) InstallPaths {
811 k := 0
812outer:
813 for i := 0; i < len(list); i++ {
814 for j := 0; j < k; j++ {
815 if list[i] == list[j] {
816 continue outer
817 }
818 }
819 list[k] = list[i]
820 k++
821 }
822 return list[:k]
823}
824
825func firstUniqueInstallPathsMap(list InstallPaths) InstallPaths {
826 k := 0
827 seen := make(map[InstallPath]bool, len(list))
828 for i := 0; i < len(list); i++ {
829 if seen[list[i]] {
830 continue
831 }
832 seen[list[i]] = true
833 list[k] = list[i]
834 k++
835 }
836 return list[:k]
837}
838
Colin Crossb6715442017-10-24 11:13:31 -0700839// LastUniquePaths returns all unique elements of a Paths, keeping the last copy of each. It
840// modifies the Paths slice contents in place, and returns a subslice of the original slice.
841func LastUniquePaths(list Paths) Paths {
842 totalSkip := 0
843 for i := len(list) - 1; i >= totalSkip; i-- {
844 skip := 0
845 for j := i - 1; j >= totalSkip; j-- {
846 if list[i] == list[j] {
847 skip++
848 } else {
849 list[j+skip] = list[j]
850 }
851 }
852 totalSkip += skip
853 }
854 return list[totalSkip:]
855}
856
Colin Crossa140bb02018-04-17 10:52:26 -0700857// ReversePaths returns a copy of a Paths in reverse order.
858func ReversePaths(list Paths) Paths {
859 if list == nil {
860 return nil
861 }
862 ret := make(Paths, len(list))
863 for i := range list {
864 ret[i] = list[len(list)-1-i]
865 }
866 return ret
867}
868
Jeff Gaston294356f2017-09-27 17:05:30 -0700869func indexPathList(s Path, list []Path) int {
870 for i, l := range list {
871 if l == s {
872 return i
873 }
874 }
875
876 return -1
877}
878
879func inPathList(p Path, list []Path) bool {
880 return indexPathList(p, list) != -1
881}
882
883func FilterPathList(list []Path, filter []Path) (remainder []Path, filtered []Path) {
Paul Duffin57b9e1d2019-12-13 00:03:35 +0000884 return FilterPathListPredicate(list, func(p Path) bool { return inPathList(p, filter) })
885}
886
887func FilterPathListPredicate(list []Path, predicate func(Path) bool) (remainder []Path, filtered []Path) {
Jeff Gaston294356f2017-09-27 17:05:30 -0700888 for _, l := range list {
Paul Duffin57b9e1d2019-12-13 00:03:35 +0000889 if predicate(l) {
Jeff Gaston294356f2017-09-27 17:05:30 -0700890 filtered = append(filtered, l)
891 } else {
892 remainder = append(remainder, l)
893 }
894 }
895
896 return
897}
898
Colin Cross93e85952017-08-15 13:34:18 -0700899// HasExt returns true of any of the paths have extension ext, otherwise false
900func (p Paths) HasExt(ext string) bool {
901 for _, path := range p {
902 if path.Ext() == ext {
903 return true
904 }
905 }
906
907 return false
908}
909
910// FilterByExt returns the subset of the paths that have extension ext
911func (p Paths) FilterByExt(ext string) Paths {
912 ret := make(Paths, 0, len(p))
913 for _, path := range p {
914 if path.Ext() == ext {
915 ret = append(ret, path)
916 }
917 }
918 return ret
919}
920
921// FilterOutByExt returns the subset of the paths that do not have extension ext
922func (p Paths) FilterOutByExt(ext string) Paths {
923 ret := make(Paths, 0, len(p))
924 for _, path := range p {
925 if path.Ext() != ext {
926 ret = append(ret, path)
927 }
928 }
929 return ret
930}
931
Colin Cross5e6cfbe2017-11-03 15:20:35 -0700932// DirectorySortedPaths is a slice of paths that are sorted such that all files in a directory
933// (including subdirectories) are in a contiguous subslice of the list, and can be found in
934// O(log(N)) time using a binary search on the directory prefix.
935type DirectorySortedPaths Paths
936
937func PathsToDirectorySortedPaths(paths Paths) DirectorySortedPaths {
938 ret := append(DirectorySortedPaths(nil), paths...)
939 sort.Slice(ret, func(i, j int) bool {
940 return ret[i].String() < ret[j].String()
941 })
942 return ret
943}
944
945// PathsInDirectory returns a subslice of the DirectorySortedPaths as a Paths that contains all entries
946// that are in the specified directory and its subdirectories.
947func (p DirectorySortedPaths) PathsInDirectory(dir string) Paths {
948 prefix := filepath.Clean(dir) + "/"
949 start := sort.Search(len(p), func(i int) bool {
950 return prefix < p[i].String()
951 })
952
953 ret := p[start:]
954
955 end := sort.Search(len(ret), func(i int) bool {
956 return !strings.HasPrefix(ret[i].String(), prefix)
957 })
958
959 ret = ret[:end]
960
961 return Paths(ret)
962}
963
Alex Humesky29e3bbe2020-11-20 21:30:13 -0500964// WritablePaths is a slice of WritablePath, used for multiple outputs.
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700965type WritablePaths []WritablePath
966
Paul Duffin85d8f0d2021-03-24 10:18:18 +0000967// RelativeToTop creates a new WritablePaths containing the result of calling Path.RelativeToTop on
968// each item in this slice.
969func (p WritablePaths) RelativeToTop() WritablePaths {
970 ensureTestOnly()
971 if p == nil {
972 return p
973 }
974 ret := make(WritablePaths, len(p))
975 for i, path := range p {
976 ret[i] = path.RelativeToTop().(WritablePath)
977 }
978 return ret
979}
980
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700981// Strings returns the string forms of the writable paths.
982func (p WritablePaths) Strings() []string {
983 if p == nil {
984 return nil
985 }
986 ret := make([]string, len(p))
987 for i, path := range p {
988 ret[i] = path.String()
989 }
990 return ret
991}
992
Colin Cross3bc7ffa2017-11-22 16:19:37 -0800993// Paths returns the WritablePaths as a Paths
994func (p WritablePaths) Paths() Paths {
995 if p == nil {
996 return nil
997 }
998 ret := make(Paths, len(p))
999 for i, path := range p {
1000 ret[i] = path
1001 }
1002 return ret
1003}
1004
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001005type basePath struct {
Paul Duffin74abc5d2021-03-24 09:24:59 +00001006 path string
1007 rel string
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001008}
1009
1010func (p basePath) Ext() string {
1011 return filepath.Ext(p.path)
1012}
1013
Colin Cross4f6fc9c2016-10-26 10:05:25 -07001014func (p basePath) Base() string {
1015 return filepath.Base(p.path)
1016}
1017
Sam Delmericoa588d152023-06-16 10:28:04 -04001018func (p basePath) Dir() Path {
1019 p.path = filepath.Dir(p.path)
1020 p.rel = filepath.Dir(p.rel)
1021 return p
1022}
1023
Colin Crossfaeb7aa2017-02-01 14:12:44 -08001024func (p basePath) Rel() string {
1025 if p.rel != "" {
1026 return p.rel
1027 }
1028 return p.path
1029}
1030
Colin Cross0875c522017-11-28 17:34:01 -08001031func (p basePath) String() string {
1032 return p.path
1033}
1034
Colin Cross0db55682017-12-05 15:36:55 -08001035func (p basePath) withRel(rel string) basePath {
1036 p.path = filepath.Join(p.path, rel)
1037 p.rel = rel
1038 return p
1039}
1040
Cole Faustbc65a3f2023-08-01 16:38:55 +00001041func (p basePath) RelativeToTop() Path {
1042 ensureTestOnly()
1043 return p
1044}
1045
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001046// SourcePath is a Path representing a file path rooted from SrcDir
1047type SourcePath struct {
1048 basePath
1049}
1050
1051var _ Path = SourcePath{}
1052
Colin Cross0db55682017-12-05 15:36:55 -08001053func (p SourcePath) withRel(rel string) SourcePath {
1054 p.basePath = p.basePath.withRel(rel)
1055 return p
1056}
1057
Sam Delmericoa588d152023-06-16 10:28:04 -04001058func (p SourcePath) Dir() Path {
1059 p.basePath = p.basePath.Dir().(basePath)
1060 return p
1061}
1062
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001063// safePathForSource is for paths that we expect are safe -- only for use by go
1064// code that is embedding ninja variables in paths
Colin Crossfe4bc362018-09-12 10:02:13 -07001065func safePathForSource(ctx PathContext, pathComponents ...string) (SourcePath, error) {
1066 p, err := validateSafePath(pathComponents...)
Cole Faust483d1f72023-01-09 14:35:27 -08001067 ret := SourcePath{basePath{p, ""}}
Colin Crossfe4bc362018-09-12 10:02:13 -07001068 if err != nil {
1069 return ret, err
1070 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001071
Colin Cross7b3dcc32019-01-24 13:14:39 -08001072 // absolute path already checked by validateSafePath
Inseob Kim5eb7ee92022-04-27 10:30:34 +09001073 // special-case api surface gen files for now
1074 if strings.HasPrefix(ret.String(), ctx.Config().soongOutDir) && !strings.Contains(ret.String(), ctx.Config().soongOutDir+"/.export") {
Mikhail Naganovab1f5182019-02-08 13:17:55 -08001075 return ret, fmt.Errorf("source path %q is in output", ret.String())
Colin Cross6e18ca42015-07-14 18:55:36 -07001076 }
1077
Colin Crossfe4bc362018-09-12 10:02:13 -07001078 return ret, err
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001079}
1080
Colin Cross192e97a2018-02-22 14:21:02 -08001081// pathForSource creates a SourcePath from pathComponents, but does not check that it exists.
1082func pathForSource(ctx PathContext, pathComponents ...string) (SourcePath, error) {
Colin Crossc48c1432018-02-23 07:09:01 +00001083 p, err := validatePath(pathComponents...)
Cole Faust483d1f72023-01-09 14:35:27 -08001084 ret := SourcePath{basePath{p, ""}}
Colin Cross94a32102018-02-22 14:21:02 -08001085 if err != nil {
Colin Cross192e97a2018-02-22 14:21:02 -08001086 return ret, err
Colin Cross94a32102018-02-22 14:21:02 -08001087 }
1088
Colin Cross7b3dcc32019-01-24 13:14:39 -08001089 // absolute path already checked by validatePath
Inseob Kim5eb7ee92022-04-27 10:30:34 +09001090 // special-case for now
1091 if strings.HasPrefix(ret.String(), ctx.Config().soongOutDir) && !strings.Contains(ret.String(), ctx.Config().soongOutDir+"/.export") {
Mikhail Naganovab1f5182019-02-08 13:17:55 -08001092 return ret, fmt.Errorf("source path %q is in output", ret.String())
Colin Crossc48c1432018-02-23 07:09:01 +00001093 }
1094
Colin Cross192e97a2018-02-22 14:21:02 -08001095 return ret, nil
1096}
1097
1098// existsWithDependencies returns true if the path exists, and adds appropriate dependencies to rerun if the
1099// path does not exist.
Colin Cross662d6142022-11-03 20:38:01 -07001100func existsWithDependencies(ctx PathGlobContext, path SourcePath) (exists bool, err error) {
Colin Cross192e97a2018-02-22 14:21:02 -08001101 var files []string
1102
Colin Cross662d6142022-11-03 20:38:01 -07001103 // Use glob to produce proper dependencies, even though we only want
1104 // a single file.
1105 files, err = ctx.GlobWithDeps(path.String(), nil)
Colin Cross192e97a2018-02-22 14:21:02 -08001106
1107 if err != nil {
1108 return false, fmt.Errorf("glob: %s", err.Error())
1109 }
1110
1111 return len(files) > 0, nil
1112}
1113
1114// PathForSource joins the provided path components and validates that the result
1115// neither escapes the source dir nor is in the out dir.
1116// On error, it will return a usable, but invalid SourcePath, and report a ModuleError.
1117func PathForSource(ctx PathContext, pathComponents ...string) SourcePath {
1118 path, err := pathForSource(ctx, pathComponents...)
1119 if err != nil {
1120 reportPathError(ctx, err)
1121 }
1122
Colin Crosse3924e12018-08-15 20:18:53 -07001123 if pathtools.IsGlob(path.String()) {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001124 ReportPathErrorf(ctx, "path may not contain a glob: %s", path.String())
Colin Crosse3924e12018-08-15 20:18:53 -07001125 }
1126
Liz Kammera830f3a2020-11-10 10:50:34 -08001127 if modCtx, ok := ctx.(ModuleMissingDepsPathContext); ok && ctx.Config().AllowMissingDependencies() {
Colin Cross662d6142022-11-03 20:38:01 -07001128 exists, err := existsWithDependencies(modCtx, path)
Colin Cross192e97a2018-02-22 14:21:02 -08001129 if err != nil {
1130 reportPathError(ctx, err)
1131 }
1132 if !exists {
1133 modCtx.AddMissingDependencies([]string{path.String()})
1134 }
Colin Cross988414c2020-01-11 01:11:46 +00001135 } else if exists, _, err := ctx.Config().fs.Exists(path.String()); err != nil {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001136 ReportPathErrorf(ctx, "%s: %s", path, err.Error())
Pedro Loureiro5d190cc2021-02-15 15:41:33 +00001137 } else if !exists && !ctx.Config().TestAllowNonExistentPaths {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001138 ReportPathErrorf(ctx, "source path %q does not exist", path)
Colin Cross192e97a2018-02-22 14:21:02 -08001139 }
1140 return path
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001141}
1142
Cole Faustbc65a3f2023-08-01 16:38:55 +00001143// PathForArbitraryOutput creates a path for the given components. Unlike PathForOutput,
1144// the path is relative to the root of the output folder, not the out/soong folder.
1145func PathForArbitraryOutput(ctx PathContext, pathComponents ...string) Path {
1146 p, err := validatePath(pathComponents...)
1147 if err != nil {
1148 reportPathError(ctx, err)
1149 }
1150 return basePath{path: filepath.Join(ctx.Config().OutDir(), p)}
1151}
1152
Spandan Dasc6c10fa2022-10-21 21:52:13 +00001153// MaybeExistentPathForSource joins the provided path components and validates that the result
1154// neither escapes the source dir nor is in the out dir.
1155// It does not validate whether the path exists.
1156func MaybeExistentPathForSource(ctx PathContext, pathComponents ...string) SourcePath {
1157 path, err := pathForSource(ctx, pathComponents...)
1158 if err != nil {
1159 reportPathError(ctx, err)
1160 }
1161
1162 if pathtools.IsGlob(path.String()) {
1163 ReportPathErrorf(ctx, "path may not contain a glob: %s", path.String())
1164 }
1165 return path
1166}
1167
Liz Kammer7aa52882021-02-11 09:16:14 -05001168// ExistentPathForSource returns an OptionalPath with the SourcePath, rooted from SrcDir, *not*
1169// rooted from the module's local source directory, if the path exists, or an empty OptionalPath if
1170// it doesn't exist. Dependencies are added so that the ninja file will be regenerated if the state
1171// of the path changes.
Colin Cross662d6142022-11-03 20:38:01 -07001172func ExistentPathForSource(ctx PathGlobContext, pathComponents ...string) OptionalPath {
Colin Cross192e97a2018-02-22 14:21:02 -08001173 path, err := pathForSource(ctx, pathComponents...)
Colin Cross1ccfcc32018-02-22 13:54:26 -08001174 if err != nil {
1175 reportPathError(ctx, err)
Martin Stjernholmc32dd1c2021-09-15 02:39:00 +01001176 // No need to put the error message into the returned path since it has been reported already.
Colin Cross1ccfcc32018-02-22 13:54:26 -08001177 return OptionalPath{}
1178 }
Colin Crossc48c1432018-02-23 07:09:01 +00001179
Colin Crosse3924e12018-08-15 20:18:53 -07001180 if pathtools.IsGlob(path.String()) {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001181 ReportPathErrorf(ctx, "path may not contain a glob: %s", path.String())
Colin Crosse3924e12018-08-15 20:18:53 -07001182 return OptionalPath{}
1183 }
1184
Colin Cross192e97a2018-02-22 14:21:02 -08001185 exists, err := existsWithDependencies(ctx, path)
Colin Crossc48c1432018-02-23 07:09:01 +00001186 if err != nil {
1187 reportPathError(ctx, err)
1188 return OptionalPath{}
1189 }
Colin Cross192e97a2018-02-22 14:21:02 -08001190 if !exists {
Martin Stjernholmc32dd1c2021-09-15 02:39:00 +01001191 return InvalidOptionalPath(path.String() + " does not exist")
Colin Crossc48c1432018-02-23 07:09:01 +00001192 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001193 return OptionalPathForPath(path)
1194}
1195
1196func (p SourcePath) String() string {
Cole Faust483d1f72023-01-09 14:35:27 -08001197 if p.path == "" {
1198 return "."
1199 }
1200 return p.path
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001201}
1202
1203// Join creates a new SourcePath with paths... joined with the current path. The
1204// provided paths... may not use '..' to escape from the current path.
1205func (p SourcePath) Join(ctx PathContext, paths ...string) SourcePath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001206 path, err := validatePath(paths...)
1207 if err != nil {
1208 reportPathError(ctx, err)
1209 }
Colin Cross0db55682017-12-05 15:36:55 -08001210 return p.withRel(path)
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001211}
1212
Colin Cross2fafa3e2019-03-05 12:39:51 -08001213// join is like Join but does less path validation.
1214func (p SourcePath) join(ctx PathContext, paths ...string) SourcePath {
1215 path, err := validateSafePath(paths...)
1216 if err != nil {
1217 reportPathError(ctx, err)
1218 }
1219 return p.withRel(path)
1220}
1221
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001222// OverlayPath returns the overlay for `path' if it exists. This assumes that the
1223// SourcePath is the path to a resource overlay directory.
Liz Kammera830f3a2020-11-10 10:50:34 -08001224func (p SourcePath) OverlayPath(ctx ModuleMissingDepsPathContext, path Path) OptionalPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001225 var relDir string
Colin Cross07e51612019-03-05 12:46:40 -08001226 if srcPath, ok := path.(SourcePath); ok {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001227 relDir = srcPath.path
1228 } else {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001229 ReportPathErrorf(ctx, "Cannot find relative path for %s(%s)", reflect.TypeOf(path).Name(), path)
Martin Stjernholmc32dd1c2021-09-15 02:39:00 +01001230 // No need to put the error message into the returned path since it has been reported already.
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001231 return OptionalPath{}
1232 }
Cole Faust483d1f72023-01-09 14:35:27 -08001233 dir := filepath.Join(p.path, relDir)
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001234 // Use Glob so that we are run again if the directory is added.
Colin Cross7f19f372016-11-01 11:10:25 -07001235 if pathtools.IsGlob(dir) {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001236 ReportPathErrorf(ctx, "Path may not contain a glob: %s", dir)
Dan Willemsen7b310ee2015-12-18 15:11:17 -08001237 }
Colin Cross461b4452018-02-23 09:22:42 -08001238 paths, err := ctx.GlobWithDeps(dir, nil)
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001239 if err != nil {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001240 ReportPathErrorf(ctx, "glob: %s", err.Error())
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001241 return OptionalPath{}
1242 }
1243 if len(paths) == 0 {
Martin Stjernholmc32dd1c2021-09-15 02:39:00 +01001244 return InvalidOptionalPath(dir + " does not exist")
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001245 }
Cole Faust483d1f72023-01-09 14:35:27 -08001246 return OptionalPathForPath(PathForSource(ctx, paths[0]))
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001247}
1248
Colin Cross70dda7e2019-10-01 22:05:35 -07001249// OutputPath is a Path representing an intermediates file path rooted from the build directory
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001250type OutputPath struct {
1251 basePath
Paul Duffind65c58b2021-03-24 09:22:07 +00001252
Lukacs T. Berkib078ade2021-08-31 10:42:08 +02001253 // The soong build directory, i.e. Config.SoongOutDir()
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02001254 soongOutDir string
Paul Duffind65c58b2021-03-24 09:22:07 +00001255
Colin Crossd63c9a72020-01-29 16:52:50 -08001256 fullPath string
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001257}
1258
Colin Cross702e0f82017-10-18 17:27:54 -07001259func (p OutputPath) withRel(rel string) OutputPath {
Colin Cross0db55682017-12-05 15:36:55 -08001260 p.basePath = p.basePath.withRel(rel)
Colin Crossd63c9a72020-01-29 16:52:50 -08001261 p.fullPath = filepath.Join(p.fullPath, rel)
Colin Cross702e0f82017-10-18 17:27:54 -07001262 return p
1263}
1264
Sam Delmericoa588d152023-06-16 10:28:04 -04001265func (p OutputPath) Dir() Path {
1266 p.basePath = p.basePath.Dir().(basePath)
1267 p.fullPath = filepath.Dir(p.fullPath)
1268 return p
1269}
1270
Colin Cross3063b782018-08-15 11:19:12 -07001271func (p OutputPath) WithoutRel() OutputPath {
1272 p.basePath.rel = filepath.Base(p.basePath.path)
1273 return p
1274}
1275
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02001276func (p OutputPath) getSoongOutDir() string {
1277 return p.soongOutDir
Paul Duffin9b478b02019-12-10 13:41:51 +00001278}
1279
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001280func (p OutputPath) RelativeToTop() Path {
1281 return p.outputPathRelativeToTop()
1282}
1283
1284func (p OutputPath) outputPathRelativeToTop() OutputPath {
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02001285 p.fullPath = StringPathRelativeToTop(p.soongOutDir, p.fullPath)
1286 p.soongOutDir = OutSoongDir
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001287 return p
1288}
1289
Paul Duffin0267d492021-02-02 10:05:52 +00001290func (p OutputPath) objPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleObjPath {
1291 return PathForModuleObj(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
1292}
1293
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001294var _ Path = OutputPath{}
Paul Duffin9b478b02019-12-10 13:41:51 +00001295var _ WritablePath = OutputPath{}
Paul Duffin0267d492021-02-02 10:05:52 +00001296var _ objPathProvider = OutputPath{}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001297
Chris Parsons8f232a22020-06-23 17:37:05 -04001298// toolDepPath is a Path representing a dependency of the build tool.
1299type toolDepPath struct {
1300 basePath
1301}
1302
Sam Delmericoa588d152023-06-16 10:28:04 -04001303func (p toolDepPath) Dir() Path {
1304 p.basePath = p.basePath.Dir().(basePath)
1305 return p
1306}
1307
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001308func (t toolDepPath) RelativeToTop() Path {
1309 ensureTestOnly()
1310 return t
1311}
1312
Chris Parsons8f232a22020-06-23 17:37:05 -04001313var _ Path = toolDepPath{}
1314
1315// pathForBuildToolDep returns a toolDepPath representing the given path string.
1316// There is no validation for the path, as it is "trusted": It may fail
1317// normal validation checks. For example, it may be an absolute path.
1318// Only use this function to construct paths for dependencies of the build
1319// tool invocation.
1320func pathForBuildToolDep(ctx PathContext, path string) toolDepPath {
Paul Duffin74abc5d2021-03-24 09:24:59 +00001321 return toolDepPath{basePath{path, ""}}
Chris Parsons8f232a22020-06-23 17:37:05 -04001322}
1323
Jeff Gaston734e3802017-04-10 15:47:24 -07001324// PathForOutput joins the provided paths and returns an OutputPath that is
1325// validated to not escape the build dir.
1326// On error, it will return a usable, but invalid OutputPath, and report a ModuleError.
1327func PathForOutput(ctx PathContext, pathComponents ...string) OutputPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001328 path, err := validatePath(pathComponents...)
1329 if err != nil {
1330 reportPathError(ctx, err)
1331 }
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02001332 fullPath := filepath.Join(ctx.Config().soongOutDir, path)
Colin Crossd63c9a72020-01-29 16:52:50 -08001333 path = fullPath[len(fullPath)-len(path):]
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02001334 return OutputPath{basePath{path, ""}, ctx.Config().soongOutDir, fullPath}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001335}
1336
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02001337// PathsForOutput returns Paths rooted from soongOutDir
Colin Cross40e33732019-02-15 11:08:35 -08001338func PathsForOutput(ctx PathContext, paths []string) WritablePaths {
1339 ret := make(WritablePaths, len(paths))
1340 for i, path := range paths {
1341 ret[i] = PathForOutput(ctx, path)
1342 }
1343 return ret
1344}
1345
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001346func (p OutputPath) writablePath() {}
1347
1348func (p OutputPath) String() string {
Colin Crossd63c9a72020-01-29 16:52:50 -08001349 return p.fullPath
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001350}
1351
1352// Join creates a new OutputPath with paths... joined with the current path. The
1353// provided paths... may not use '..' to escape from the current path.
1354func (p OutputPath) Join(ctx PathContext, paths ...string) OutputPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001355 path, err := validatePath(paths...)
1356 if err != nil {
1357 reportPathError(ctx, err)
1358 }
Colin Cross0db55682017-12-05 15:36:55 -08001359 return p.withRel(path)
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001360}
1361
Colin Cross8854a5a2019-02-11 14:14:16 -08001362// ReplaceExtension creates a new OutputPath with the extension replaced with ext.
1363func (p OutputPath) ReplaceExtension(ctx PathContext, ext string) OutputPath {
1364 if strings.Contains(ext, "/") {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001365 ReportPathErrorf(ctx, "extension %q cannot contain /", ext)
Colin Cross8854a5a2019-02-11 14:14:16 -08001366 }
1367 ret := PathForOutput(ctx, pathtools.ReplaceExtension(p.path, ext))
Colin Cross2cdd5df2019-02-25 10:25:24 -08001368 ret.rel = pathtools.ReplaceExtension(p.rel, ext)
Colin Cross8854a5a2019-02-11 14:14:16 -08001369 return ret
1370}
1371
Colin Cross40e33732019-02-15 11:08:35 -08001372// InSameDir creates a new OutputPath from the directory of the current OutputPath joined with the elements in paths.
1373func (p OutputPath) InSameDir(ctx PathContext, paths ...string) OutputPath {
1374 path, err := validatePath(paths...)
1375 if err != nil {
1376 reportPathError(ctx, err)
1377 }
1378
1379 ret := PathForOutput(ctx, filepath.Dir(p.path), path)
Colin Cross2cdd5df2019-02-25 10:25:24 -08001380 ret.rel = filepath.Join(filepath.Dir(p.rel), path)
Colin Cross40e33732019-02-15 11:08:35 -08001381 return ret
1382}
1383
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001384// PathForIntermediates returns an OutputPath representing the top-level
1385// intermediates directory.
1386func PathForIntermediates(ctx PathContext, paths ...string) OutputPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001387 path, err := validatePath(paths...)
1388 if err != nil {
1389 reportPathError(ctx, err)
1390 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001391 return PathForOutput(ctx, ".intermediates", path)
1392}
1393
Colin Cross07e51612019-03-05 12:46:40 -08001394var _ genPathProvider = SourcePath{}
1395var _ objPathProvider = SourcePath{}
1396var _ resPathProvider = SourcePath{}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001397
Colin Cross07e51612019-03-05 12:46:40 -08001398// PathForModuleSrc returns a Path representing the paths... under the
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001399// module's local source directory.
Liz Kammera830f3a2020-11-10 10:50:34 -08001400func PathForModuleSrc(ctx ModuleMissingDepsPathContext, pathComponents ...string) Path {
Paul Duffin407501b2021-07-09 16:56:35 +01001401 // Just join the components textually just to make sure that it does not corrupt a fully qualified
1402 // module reference, e.g. if the pathComponents is "://other:foo" then using filepath.Join() or
1403 // validatePath() will corrupt it, e.g. replace "//" with "/". If the path is not a module
1404 // reference then it will be validated by expandOneSrcPath anyway when it calls expandOneSrcPath.
1405 p := strings.Join(pathComponents, string(filepath.Separator))
Liz Kammer619be462022-01-28 15:13:39 -05001406 paths, err := expandOneSrcPath(sourcePathInput{context: ctx, path: p, includeDirs: true})
Colin Cross8a497952019-03-05 22:25:09 -08001407 if err != nil {
1408 if depErr, ok := err.(missingDependencyError); ok {
1409 if ctx.Config().AllowMissingDependencies() {
1410 ctx.AddMissingDependencies(depErr.missingDeps)
1411 } else {
1412 ctx.ModuleErrorf(`%s, is the property annotated with android:"path"?`, depErr.Error())
1413 }
1414 } else {
1415 reportPathError(ctx, err)
1416 }
1417 return nil
1418 } else if len(paths) == 0 {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001419 ReportPathErrorf(ctx, "%q produced no files, expected exactly one", p)
Colin Cross8a497952019-03-05 22:25:09 -08001420 return nil
1421 } else if len(paths) > 1 {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001422 ReportPathErrorf(ctx, "%q produced %d files, expected exactly one", p, len(paths))
Colin Cross8a497952019-03-05 22:25:09 -08001423 }
1424 return paths[0]
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001425}
1426
Liz Kammera830f3a2020-11-10 10:50:34 -08001427func pathForModuleSrc(ctx EarlyModulePathContext, paths ...string) SourcePath {
Colin Cross07e51612019-03-05 12:46:40 -08001428 p, err := validatePath(paths...)
1429 if err != nil {
1430 reportPathError(ctx, err)
1431 }
1432
1433 path, err := pathForSource(ctx, ctx.ModuleDir(), p)
1434 if err != nil {
1435 reportPathError(ctx, err)
1436 }
1437
1438 path.basePath.rel = p
1439
1440 return path
1441}
1442
Colin Cross2fafa3e2019-03-05 12:39:51 -08001443// PathsWithModuleSrcSubDir takes a list of Paths and returns a new list of Paths where Rel() on each path
1444// will return the path relative to subDir in the module's source directory. If any input paths are not located
1445// inside subDir then a path error will be reported.
Liz Kammera830f3a2020-11-10 10:50:34 -08001446func PathsWithModuleSrcSubDir(ctx EarlyModulePathContext, paths Paths, subDir string) Paths {
Colin Cross2fafa3e2019-03-05 12:39:51 -08001447 paths = append(Paths(nil), paths...)
Colin Cross07e51612019-03-05 12:46:40 -08001448 subDirFullPath := pathForModuleSrc(ctx, subDir)
Colin Cross2fafa3e2019-03-05 12:39:51 -08001449 for i, path := range paths {
1450 rel := Rel(ctx, subDirFullPath.String(), path.String())
1451 paths[i] = subDirFullPath.join(ctx, rel)
1452 }
1453 return paths
1454}
1455
1456// PathWithModuleSrcSubDir takes a Path and returns a Path where Rel() will return the path relative to subDir in the
1457// 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 -08001458func PathWithModuleSrcSubDir(ctx EarlyModulePathContext, path Path, subDir string) Path {
Colin Cross07e51612019-03-05 12:46:40 -08001459 subDirFullPath := pathForModuleSrc(ctx, subDir)
Colin Cross2fafa3e2019-03-05 12:39:51 -08001460 rel := Rel(ctx, subDirFullPath.String(), path.String())
1461 return subDirFullPath.Join(ctx, rel)
1462}
1463
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001464// OptionalPathForModuleSrc returns an OptionalPath. The OptionalPath contains a
1465// valid path if p is non-nil.
Liz Kammera830f3a2020-11-10 10:50:34 -08001466func OptionalPathForModuleSrc(ctx ModuleMissingDepsPathContext, p *string) OptionalPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001467 if p == nil {
1468 return OptionalPath{}
1469 }
1470 return OptionalPathForPath(PathForModuleSrc(ctx, *p))
1471}
1472
Liz Kammera830f3a2020-11-10 10:50:34 -08001473func (p SourcePath) genPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleGenPath {
Colin Cross7fc17db2017-02-01 14:07:55 -08001474 return PathForModuleGen(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001475}
1476
Liz Kammera830f3a2020-11-10 10:50:34 -08001477func (p SourcePath) objPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleObjPath {
Colin Cross7fc17db2017-02-01 14:07:55 -08001478 return PathForModuleObj(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001479}
1480
Liz Kammera830f3a2020-11-10 10:50:34 -08001481func (p SourcePath) resPathWithName(ctx ModuleOutPathContext, name string) ModuleResPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001482 // TODO: Use full directory if the new ctx is not the current ctx?
1483 return PathForModuleRes(ctx, p.path, name)
1484}
1485
1486// ModuleOutPath is a Path representing a module's output directory.
1487type ModuleOutPath struct {
1488 OutputPath
1489}
1490
Sam Delmericoa588d152023-06-16 10:28:04 -04001491func (p ModuleOutPath) Dir() Path {
1492 p.OutputPath = p.OutputPath.Dir().(OutputPath)
1493 return p
1494}
1495
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001496func (p ModuleOutPath) RelativeToTop() Path {
1497 p.OutputPath = p.outputPathRelativeToTop()
1498 return p
1499}
1500
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001501var _ Path = ModuleOutPath{}
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001502var _ WritablePath = ModuleOutPath{}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001503
Liz Kammera830f3a2020-11-10 10:50:34 -08001504func (p ModuleOutPath) objPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleObjPath {
Pete Bentleyfcf55bf2019-08-16 20:14:32 +01001505 return PathForModuleObj(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
1506}
1507
Liz Kammera830f3a2020-11-10 10:50:34 -08001508// ModuleOutPathContext Subset of ModuleContext functions necessary for output path methods.
1509type ModuleOutPathContext interface {
1510 PathContext
1511
1512 ModuleName() string
1513 ModuleDir() string
1514 ModuleSubDir() string
Inseob Kim8ff69de2023-06-16 14:19:33 +09001515 SoongConfigTraceHash() string
Liz Kammera830f3a2020-11-10 10:50:34 -08001516}
1517
1518func pathForModuleOut(ctx ModuleOutPathContext) OutputPath {
Inseob Kim8ff69de2023-06-16 14:19:33 +09001519 return PathForOutput(ctx, ".intermediates", ctx.ModuleDir(), ctx.ModuleName(), ctx.ModuleSubDir(), ctx.SoongConfigTraceHash())
Colin Cross702e0f82017-10-18 17:27:54 -07001520}
1521
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001522// PathForModuleOut returns a Path representing the paths... under the module's
1523// output directory.
Liz Kammera830f3a2020-11-10 10:50:34 -08001524func PathForModuleOut(ctx ModuleOutPathContext, paths ...string) ModuleOutPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001525 p, err := validatePath(paths...)
1526 if err != nil {
1527 reportPathError(ctx, err)
1528 }
Colin Cross702e0f82017-10-18 17:27:54 -07001529 return ModuleOutPath{
Liz Kammera830f3a2020-11-10 10:50:34 -08001530 OutputPath: pathForModuleOut(ctx).withRel(p),
Colin Cross702e0f82017-10-18 17:27:54 -07001531 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001532}
1533
1534// ModuleGenPath is a Path representing the 'gen' directory in a module's output
1535// directory. Mainly used for generated sources.
1536type ModuleGenPath struct {
1537 ModuleOutPath
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001538}
1539
Sam Delmericoa588d152023-06-16 10:28:04 -04001540func (p ModuleGenPath) Dir() Path {
1541 p.ModuleOutPath = p.ModuleOutPath.Dir().(ModuleOutPath)
1542 return p
1543}
1544
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001545func (p ModuleGenPath) RelativeToTop() Path {
1546 p.OutputPath = p.outputPathRelativeToTop()
1547 return p
1548}
1549
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001550var _ Path = ModuleGenPath{}
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001551var _ WritablePath = ModuleGenPath{}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001552var _ genPathProvider = ModuleGenPath{}
1553var _ objPathProvider = ModuleGenPath{}
1554
1555// PathForModuleGen returns a Path representing the paths... under the module's
1556// `gen' directory.
Liz Kammera830f3a2020-11-10 10:50:34 -08001557func PathForModuleGen(ctx ModuleOutPathContext, paths ...string) ModuleGenPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001558 p, err := validatePath(paths...)
1559 if err != nil {
1560 reportPathError(ctx, err)
1561 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001562 return ModuleGenPath{
Colin Cross702e0f82017-10-18 17:27:54 -07001563 ModuleOutPath: ModuleOutPath{
Liz Kammera830f3a2020-11-10 10:50:34 -08001564 OutputPath: pathForModuleOut(ctx).withRel("gen").withRel(p),
Colin Cross702e0f82017-10-18 17:27:54 -07001565 },
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001566 }
1567}
1568
Liz Kammera830f3a2020-11-10 10:50:34 -08001569func (p ModuleGenPath) genPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleGenPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001570 // TODO: make a different path for local vs remote generated files?
Dan Willemsen21ec4902016-11-02 20:43:13 -07001571 return PathForModuleGen(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001572}
1573
Liz Kammera830f3a2020-11-10 10:50:34 -08001574func (p ModuleGenPath) objPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleObjPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001575 return PathForModuleObj(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
1576}
1577
1578// ModuleObjPath is a Path representing the 'obj' directory in a module's output
1579// directory. Used for compiled objects.
1580type ModuleObjPath struct {
1581 ModuleOutPath
1582}
1583
Sam Delmericoa588d152023-06-16 10:28:04 -04001584func (p ModuleObjPath) Dir() Path {
1585 p.ModuleOutPath = p.ModuleOutPath.Dir().(ModuleOutPath)
1586 return p
1587}
1588
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001589func (p ModuleObjPath) RelativeToTop() Path {
1590 p.OutputPath = p.outputPathRelativeToTop()
1591 return p
1592}
1593
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001594var _ Path = ModuleObjPath{}
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001595var _ WritablePath = ModuleObjPath{}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001596
1597// PathForModuleObj returns a Path representing the paths... under the module's
1598// 'obj' directory.
Liz Kammera830f3a2020-11-10 10:50:34 -08001599func PathForModuleObj(ctx ModuleOutPathContext, pathComponents ...string) ModuleObjPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001600 p, err := validatePath(pathComponents...)
1601 if err != nil {
1602 reportPathError(ctx, err)
1603 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001604 return ModuleObjPath{PathForModuleOut(ctx, "obj", p)}
1605}
1606
1607// ModuleResPath is a a Path representing the 'res' directory in a module's
1608// output directory.
1609type ModuleResPath struct {
1610 ModuleOutPath
1611}
1612
Sam Delmericoa588d152023-06-16 10:28:04 -04001613func (p ModuleResPath) Dir() Path {
1614 p.ModuleOutPath = p.ModuleOutPath.Dir().(ModuleOutPath)
1615 return p
1616}
1617
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001618func (p ModuleResPath) RelativeToTop() Path {
1619 p.OutputPath = p.outputPathRelativeToTop()
1620 return p
1621}
1622
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001623var _ Path = ModuleResPath{}
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001624var _ WritablePath = ModuleResPath{}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001625
1626// PathForModuleRes returns a Path representing the paths... under the module's
1627// 'res' directory.
Liz Kammera830f3a2020-11-10 10:50:34 -08001628func PathForModuleRes(ctx ModuleOutPathContext, pathComponents ...string) ModuleResPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001629 p, err := validatePath(pathComponents...)
1630 if err != nil {
1631 reportPathError(ctx, err)
1632 }
1633
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001634 return ModuleResPath{PathForModuleOut(ctx, "res", p)}
1635}
1636
Colin Cross70dda7e2019-10-01 22:05:35 -07001637// InstallPath is a Path representing a installed file path rooted from the build directory
1638type InstallPath struct {
1639 basePath
Colin Crossff6c33d2019-10-02 16:01:35 -07001640
Lukacs T. Berkib078ade2021-08-31 10:42:08 +02001641 // The soong build directory, i.e. Config.SoongOutDir()
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02001642 soongOutDir string
Paul Duffind65c58b2021-03-24 09:22:07 +00001643
Jiyong Park957bcd92020-10-20 18:23:33 +09001644 // partitionDir is the part of the InstallPath that is automatically determined according to the context.
1645 // For example, it is host/<os>-<arch> for host modules, and target/product/<device>/<partition> for device modules.
1646 partitionDir string
1647
Colin Crossb1692a32021-10-25 15:39:01 -07001648 partition string
1649
Jiyong Park957bcd92020-10-20 18:23:33 +09001650 // makePath indicates whether this path is for Soong (false) or Make (true).
1651 makePath bool
Colin Cross70dda7e2019-10-01 22:05:35 -07001652}
1653
Sam Delmericoa588d152023-06-16 10:28:04 -04001654func (p InstallPath) Dir() Path {
1655 p.basePath = p.basePath.Dir().(basePath)
1656 return p
1657}
1658
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001659// Will panic if called from outside a test environment.
1660func ensureTestOnly() {
Martin Stjernholm32312eb2021-03-27 18:54:49 +00001661 if PrefixInList(os.Args, "-test.") {
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001662 return
1663 }
Martin Stjernholm32312eb2021-03-27 18:54:49 +00001664 panic(fmt.Errorf("Not in test. Command line:\n %s", strings.Join(os.Args, "\n ")))
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001665}
1666
1667func (p InstallPath) RelativeToTop() Path {
1668 ensureTestOnly()
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02001669 p.soongOutDir = OutSoongDir
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001670 return p
1671}
1672
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02001673func (p InstallPath) getSoongOutDir() string {
1674 return p.soongOutDir
Paul Duffin9b478b02019-12-10 13:41:51 +00001675}
1676
Hans MÃ¥nssond3f2bd72020-11-27 12:37:28 +01001677func (p InstallPath) ReplaceExtension(ctx PathContext, ext string) OutputPath {
1678 panic("Not implemented")
1679}
1680
Paul Duffin9b478b02019-12-10 13:41:51 +00001681var _ Path = InstallPath{}
1682var _ WritablePath = InstallPath{}
1683
Colin Cross70dda7e2019-10-01 22:05:35 -07001684func (p InstallPath) writablePath() {}
1685
1686func (p InstallPath) String() string {
Jiyong Park957bcd92020-10-20 18:23:33 +09001687 if p.makePath {
1688 // Make path starts with out/ instead of out/soong.
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02001689 return filepath.Join(p.soongOutDir, "../", p.path)
Jiyong Park957bcd92020-10-20 18:23:33 +09001690 } else {
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02001691 return filepath.Join(p.soongOutDir, p.path)
Jiyong Park957bcd92020-10-20 18:23:33 +09001692 }
1693}
1694
1695// PartitionDir returns the path to the partition where the install path is rooted at. It is
1696// out/soong/target/product/<device>/<partition> for device modules, and out/soong/host/<os>-<arch> for host modules.
1697// The ./soong is dropped if the install path is for Make.
1698func (p InstallPath) PartitionDir() string {
1699 if p.makePath {
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02001700 return filepath.Join(p.soongOutDir, "../", p.partitionDir)
Jiyong Park957bcd92020-10-20 18:23:33 +09001701 } else {
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02001702 return filepath.Join(p.soongOutDir, p.partitionDir)
Jiyong Park957bcd92020-10-20 18:23:33 +09001703 }
Colin Cross70dda7e2019-10-01 22:05:35 -07001704}
1705
Jihoon Kangf78a8902022-09-01 22:47:07 +00001706func (p InstallPath) Partition() string {
1707 return p.partition
1708}
1709
Colin Cross70dda7e2019-10-01 22:05:35 -07001710// Join creates a new InstallPath with paths... joined with the current path. The
1711// provided paths... may not use '..' to escape from the current path.
1712func (p InstallPath) Join(ctx PathContext, paths ...string) InstallPath {
1713 path, err := validatePath(paths...)
1714 if err != nil {
1715 reportPathError(ctx, err)
1716 }
1717 return p.withRel(path)
1718}
1719
1720func (p InstallPath) withRel(rel string) InstallPath {
1721 p.basePath = p.basePath.withRel(rel)
1722 return p
1723}
1724
Colin Crossc68db4b2021-11-11 18:59:15 -08001725// Deprecated: ToMakePath is a noop, PathForModuleInstall always returns Make paths when building
1726// embedded in Make.
Colin Crossff6c33d2019-10-02 16:01:35 -07001727func (p InstallPath) ToMakePath() InstallPath {
Jiyong Park957bcd92020-10-20 18:23:33 +09001728 p.makePath = true
Colin Crossff6c33d2019-10-02 16:01:35 -07001729 return p
Colin Cross70dda7e2019-10-01 22:05:35 -07001730}
1731
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001732// PathForModuleInstall returns a Path representing the install path for the
1733// module appended with paths...
Colin Cross70dda7e2019-10-01 22:05:35 -07001734func PathForModuleInstall(ctx ModuleInstallPathContext, pathComponents ...string) InstallPath {
Spandan Das5d1b9292021-06-03 19:36:41 +00001735 os, arch := osAndArch(ctx)
1736 partition := modulePartition(ctx, os)
1737 return makePathForInstall(ctx, os, arch, partition, ctx.Debug(), pathComponents...)
1738}
1739
Colin Cross1d0eb7a2021-11-03 14:08:20 -07001740// PathForHostDexInstall returns an InstallPath representing the install path for the
1741// module appended with paths...
1742func PathForHostDexInstall(ctx ModuleInstallPathContext, pathComponents ...string) InstallPath {
1743 return makePathForInstall(ctx, ctx.Config().BuildOS, ctx.Config().BuildArch, "", ctx.Debug(), pathComponents...)
1744}
1745
Spandan Das5d1b9292021-06-03 19:36:41 +00001746// PathForModuleInPartitionInstall is similar to PathForModuleInstall but partition is provided by the caller
1747func PathForModuleInPartitionInstall(ctx ModuleInstallPathContext, partition string, pathComponents ...string) InstallPath {
1748 os, arch := osAndArch(ctx)
1749 return makePathForInstall(ctx, os, arch, partition, ctx.Debug(), pathComponents...)
1750}
1751
1752func osAndArch(ctx ModuleInstallPathContext) (OsType, ArchType) {
Colin Cross6e359402020-02-10 15:29:54 -08001753 os := ctx.Os()
Jiyong Park87788b52020-09-01 12:37:45 +09001754 arch := ctx.Arch().ArchType
1755 forceOS, forceArch := ctx.InstallForceOS()
1756 if forceOS != nil {
Colin Cross6e359402020-02-10 15:29:54 -08001757 os = *forceOS
1758 }
Jiyong Park87788b52020-09-01 12:37:45 +09001759 if forceArch != nil {
1760 arch = *forceArch
1761 }
Spandan Das5d1b9292021-06-03 19:36:41 +00001762 return os, arch
1763}
Colin Cross609c49a2020-02-13 13:20:11 -08001764
Spandan Das5d1b9292021-06-03 19:36:41 +00001765func makePathForInstall(ctx ModuleInstallPathContext, os OsType, arch ArchType, partition string, debug bool, pathComponents ...string) InstallPath {
1766 ret := pathForInstall(ctx, os, arch, partition, debug, pathComponents...)
Colin Cross609c49a2020-02-13 13:20:11 -08001767 return ret
1768}
1769
Jiyong Park87788b52020-09-01 12:37:45 +09001770func pathForInstall(ctx PathContext, os OsType, arch ArchType, partition string, debug bool,
Colin Cross609c49a2020-02-13 13:20:11 -08001771 pathComponents ...string) InstallPath {
1772
Jiyong Park97859152023-02-14 17:05:48 +09001773 var partitionPaths []string
Colin Cross609c49a2020-02-13 13:20:11 -08001774
Colin Cross6e359402020-02-10 15:29:54 -08001775 if os.Class == Device {
Jiyong Park97859152023-02-14 17:05:48 +09001776 partitionPaths = []string{"target", "product", ctx.Config().DeviceName(), partition}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001777 } else {
Jiyong Park87788b52020-09-01 12:37:45 +09001778 osName := os.String()
Colin Crossa9b2aac2022-06-15 17:25:51 -07001779 if os == Linux {
Jiyong Park87788b52020-09-01 12:37:45 +09001780 // instead of linux_glibc
1781 osName = "linux"
Dan Willemsen866b5632017-09-22 12:28:24 -07001782 }
Colin Crossa9b2aac2022-06-15 17:25:51 -07001783 if os == LinuxMusl && ctx.Config().UseHostMusl() {
1784 // When using musl instead of glibc, use "linux" instead of "linux_musl". When cross
1785 // compiling we will still use "linux_musl".
1786 osName = "linux"
1787 }
1788
Jiyong Park87788b52020-09-01 12:37:45 +09001789 // SOONG_HOST_OUT is set to out/host/$(HOST_OS)-$(HOST_PREBUILT_ARCH)
1790 // and HOST_PREBUILT_ARCH is forcibly set to x86 even on x86_64 hosts. We don't seem
1791 // to have a plan to fix it (see the comment in build/make/core/envsetup.mk).
1792 // Let's keep using x86 for the existing cases until we have a need to support
1793 // other architectures.
1794 archName := arch.String()
1795 if os.Class == Host && (arch == X86_64 || arch == Common) {
1796 archName = "x86"
1797 }
Jiyong Park97859152023-02-14 17:05:48 +09001798 partitionPaths = []string{"host", osName + "-" + archName, partition}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001799 }
Colin Cross609c49a2020-02-13 13:20:11 -08001800 if debug {
Jiyong Park97859152023-02-14 17:05:48 +09001801 partitionPaths = append([]string{"debug"}, partitionPaths...)
Dan Willemsen782a2d12015-12-21 14:55:28 -08001802 }
Colin Cross70dda7e2019-10-01 22:05:35 -07001803
Jiyong Park97859152023-02-14 17:05:48 +09001804 partitionPath, err := validatePath(partitionPaths...)
Colin Cross70dda7e2019-10-01 22:05:35 -07001805 if err != nil {
1806 reportPathError(ctx, err)
1807 }
Colin Crossff6c33d2019-10-02 16:01:35 -07001808
Jiyong Park957bcd92020-10-20 18:23:33 +09001809 base := InstallPath{
Jiyong Park97859152023-02-14 17:05:48 +09001810 basePath: basePath{partitionPath, ""},
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02001811 soongOutDir: ctx.Config().soongOutDir,
Jiyong Park97859152023-02-14 17:05:48 +09001812 partitionDir: partitionPath,
Colin Crossb1692a32021-10-25 15:39:01 -07001813 partition: partition,
Colin Crossc68db4b2021-11-11 18:59:15 -08001814 }
1815
1816 if ctx.Config().KatiEnabled() {
1817 base.makePath = true
Jiyong Park957bcd92020-10-20 18:23:33 +09001818 }
Colin Crossff6c33d2019-10-02 16:01:35 -07001819
Jiyong Park957bcd92020-10-20 18:23:33 +09001820 return base.Join(ctx, pathComponents...)
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001821}
1822
Nicolas Geoffray1228e9c2020-02-27 13:45:35 +00001823func pathForNdkOrSdkInstall(ctx PathContext, prefix string, paths []string) InstallPath {
Jiyong Park957bcd92020-10-20 18:23:33 +09001824 base := InstallPath{
Paul Duffin74abc5d2021-03-24 09:24:59 +00001825 basePath: basePath{prefix, ""},
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02001826 soongOutDir: ctx.Config().soongOutDir,
Jiyong Park957bcd92020-10-20 18:23:33 +09001827 partitionDir: prefix,
1828 makePath: false,
Colin Cross70dda7e2019-10-01 22:05:35 -07001829 }
Jiyong Park957bcd92020-10-20 18:23:33 +09001830 return base.Join(ctx, paths...)
Colin Cross70dda7e2019-10-01 22:05:35 -07001831}
1832
Nicolas Geoffray1228e9c2020-02-27 13:45:35 +00001833func PathForNdkInstall(ctx PathContext, paths ...string) InstallPath {
1834 return pathForNdkOrSdkInstall(ctx, "ndk", paths)
1835}
1836
1837func PathForMainlineSdksInstall(ctx PathContext, paths ...string) InstallPath {
1838 return pathForNdkOrSdkInstall(ctx, "mainline-sdks", paths)
1839}
1840
Colin Cross70dda7e2019-10-01 22:05:35 -07001841func InstallPathToOnDevicePath(ctx PathContext, path InstallPath) string {
Colin Crossb1692a32021-10-25 15:39:01 -07001842 rel := Rel(ctx, strings.TrimSuffix(path.PartitionDir(), path.partition), path.String())
Colin Cross43f08db2018-11-12 10:13:39 -08001843 return "/" + rel
1844}
1845
Colin Cross6e359402020-02-10 15:29:54 -08001846func modulePartition(ctx ModuleInstallPathContext, os OsType) string {
Colin Cross43f08db2018-11-12 10:13:39 -08001847 var partition string
Colin Cross6e359402020-02-10 15:29:54 -08001848 if ctx.InstallInTestcases() {
1849 // "testcases" install directory can be used for host or device modules.
Jaewoong Jung0949f312019-09-11 10:25:18 -07001850 partition = "testcases"
Colin Cross6e359402020-02-10 15:29:54 -08001851 } else if os.Class == Device {
1852 if ctx.InstallInData() {
1853 partition = "data"
1854 } else if ctx.InstallInRamdisk() {
1855 if ctx.DeviceConfig().BoardUsesRecoveryAsBoot() {
1856 partition = "recovery/root/first_stage_ramdisk"
1857 } else {
1858 partition = "ramdisk"
1859 }
1860 if !ctx.InstallInRoot() {
1861 partition += "/system"
1862 }
Yifan Hong60e0cfb2020-10-21 15:17:56 -07001863 } else if ctx.InstallInVendorRamdisk() {
Yifan Hong39143a92020-10-26 12:43:12 -07001864 // The module is only available after switching root into
1865 // /first_stage_ramdisk. To expose the module before switching root
1866 // on a device without a dedicated recovery partition, install the
1867 // recovery variant.
Yifan Hongdd8dacc2020-10-21 15:40:17 -07001868 if ctx.DeviceConfig().BoardMoveRecoveryResourcesToVendorBoot() {
Petri Gyntherac229562021-03-02 23:44:02 -08001869 partition = "vendor_ramdisk/first_stage_ramdisk"
Yifan Hongdd8dacc2020-10-21 15:40:17 -07001870 } else {
Petri Gyntherac229562021-03-02 23:44:02 -08001871 partition = "vendor_ramdisk"
Yifan Hongdd8dacc2020-10-21 15:40:17 -07001872 }
1873 if !ctx.InstallInRoot() {
1874 partition += "/system"
1875 }
Inseob Kim08758f02021-04-08 21:13:22 +09001876 } else if ctx.InstallInDebugRamdisk() {
1877 partition = "debug_ramdisk"
Colin Cross6e359402020-02-10 15:29:54 -08001878 } else if ctx.InstallInRecovery() {
1879 if ctx.InstallInRoot() {
1880 partition = "recovery/root"
1881 } else {
1882 // the layout of recovery partion is the same as that of system partition
1883 partition = "recovery/root/system"
1884 }
1885 } else if ctx.SocSpecific() {
1886 partition = ctx.DeviceConfig().VendorPath()
1887 } else if ctx.DeviceSpecific() {
1888 partition = ctx.DeviceConfig().OdmPath()
1889 } else if ctx.ProductSpecific() {
1890 partition = ctx.DeviceConfig().ProductPath()
1891 } else if ctx.SystemExtSpecific() {
1892 partition = ctx.DeviceConfig().SystemExtPath()
1893 } else if ctx.InstallInRoot() {
1894 partition = "root"
Yifan Hong82db7352020-01-21 16:12:26 -08001895 } else {
Colin Cross6e359402020-02-10 15:29:54 -08001896 partition = "system"
Yifan Hong82db7352020-01-21 16:12:26 -08001897 }
Colin Cross6e359402020-02-10 15:29:54 -08001898 if ctx.InstallInSanitizerDir() {
1899 partition = "data/asan/" + partition
Yifan Hong82db7352020-01-21 16:12:26 -08001900 }
Colin Cross43f08db2018-11-12 10:13:39 -08001901 }
1902 return partition
1903}
1904
Colin Cross609c49a2020-02-13 13:20:11 -08001905type InstallPaths []InstallPath
1906
1907// Paths returns the InstallPaths as a Paths
1908func (p InstallPaths) Paths() Paths {
1909 if p == nil {
1910 return nil
1911 }
1912 ret := make(Paths, len(p))
1913 for i, path := range p {
1914 ret[i] = path
1915 }
1916 return ret
1917}
1918
1919// Strings returns the string forms of the install paths.
1920func (p InstallPaths) Strings() []string {
1921 if p == nil {
1922 return nil
1923 }
1924 ret := make([]string, len(p))
1925 for i, path := range p {
1926 ret[i] = path.String()
1927 }
1928 return ret
1929}
1930
Jingwen Chen24d0c562023-02-07 09:29:36 +00001931// validatePathInternal ensures that a path does not leave its component, and
1932// optionally doesn't contain Ninja variables.
1933func validatePathInternal(allowNinjaVariables bool, pathComponents ...string) (string, error) {
Jeff Gaston734e3802017-04-10 15:47:24 -07001934 for _, path := range pathComponents {
Jingwen Chen24d0c562023-02-07 09:29:36 +00001935 if !allowNinjaVariables && strings.Contains(path, "$") {
1936 return "", fmt.Errorf("Path contains invalid character($): %s", path)
1937 }
1938
Dan Willemsen80a7c2a2015-12-21 14:57:11 -08001939 path := filepath.Clean(path)
1940 if path == ".." || strings.HasPrefix(path, "../") || strings.HasPrefix(path, "/") {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001941 return "", fmt.Errorf("Path is outside directory: %s", path)
Dan Willemsen80a7c2a2015-12-21 14:57:11 -08001942 }
1943 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001944 // TODO: filepath.Join isn't necessarily correct with embedded ninja
1945 // variables. '..' may remove the entire ninja variable, even if it
1946 // will be expanded to multiple nested directories.
Colin Cross1ccfcc32018-02-22 13:54:26 -08001947 return filepath.Join(pathComponents...), nil
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001948}
1949
Jingwen Chen24d0c562023-02-07 09:29:36 +00001950// validateSafePath validates a path that we trust (may contain ninja
1951// variables). Ensures that each path component does not attempt to leave its
1952// component. Returns a joined version of each path component.
1953func validateSafePath(pathComponents ...string) (string, error) {
1954 return validatePathInternal(true, pathComponents...)
1955}
1956
Dan Willemsen80a7c2a2015-12-21 14:57:11 -08001957// validatePath validates that a path does not include ninja variables, and that
1958// each path component does not attempt to leave its component. Returns a joined
1959// version of each path component.
Colin Cross1ccfcc32018-02-22 13:54:26 -08001960func validatePath(pathComponents ...string) (string, error) {
Jingwen Chen24d0c562023-02-07 09:29:36 +00001961 return validatePathInternal(false, pathComponents...)
Colin Cross6e18ca42015-07-14 18:55:36 -07001962}
Colin Cross5b529592017-05-09 13:34:34 -07001963
Colin Cross0875c522017-11-28 17:34:01 -08001964func PathForPhony(ctx PathContext, phony string) WritablePath {
1965 if strings.ContainsAny(phony, "$/") {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001966 ReportPathErrorf(ctx, "Phony target contains invalid character ($ or /): %s", phony)
Colin Cross0875c522017-11-28 17:34:01 -08001967 }
Paul Duffin74abc5d2021-03-24 09:24:59 +00001968 return PhonyPath{basePath{phony, ""}}
Colin Cross0875c522017-11-28 17:34:01 -08001969}
1970
Colin Cross74e3fe42017-12-11 15:51:44 -08001971type PhonyPath struct {
1972 basePath
1973}
1974
Sam Delmericoa588d152023-06-16 10:28:04 -04001975func (p PhonyPath) Dir() Path {
1976 p.basePath = p.basePath.Dir().(basePath)
1977 return p
1978}
1979
Colin Cross74e3fe42017-12-11 15:51:44 -08001980func (p PhonyPath) writablePath() {}
1981
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02001982func (p PhonyPath) getSoongOutDir() string {
Paul Duffind65c58b2021-03-24 09:22:07 +00001983 // A phone path cannot contain any / so cannot be relative to the build directory.
1984 return ""
Paul Duffin9b478b02019-12-10 13:41:51 +00001985}
1986
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001987func (p PhonyPath) RelativeToTop() Path {
1988 ensureTestOnly()
1989 // A phony path cannot contain any / so does not have a build directory so switching to a new
1990 // build directory has no effect so just return this path.
1991 return p
1992}
1993
Hans MÃ¥nssond3f2bd72020-11-27 12:37:28 +01001994func (p PhonyPath) ReplaceExtension(ctx PathContext, ext string) OutputPath {
1995 panic("Not implemented")
1996}
1997
Colin Cross74e3fe42017-12-11 15:51:44 -08001998var _ Path = PhonyPath{}
1999var _ WritablePath = PhonyPath{}
2000
Colin Cross5b529592017-05-09 13:34:34 -07002001type testPath struct {
2002 basePath
2003}
2004
Sam Delmericoa588d152023-06-16 10:28:04 -04002005func (p testPath) Dir() Path {
2006 p.basePath = p.basePath.Dir().(basePath)
2007 return p
2008}
2009
Paul Duffin85d8f0d2021-03-24 10:18:18 +00002010func (p testPath) RelativeToTop() Path {
2011 ensureTestOnly()
2012 return p
2013}
2014
Colin Cross5b529592017-05-09 13:34:34 -07002015func (p testPath) String() string {
2016 return p.path
2017}
2018
Paul Duffin85d8f0d2021-03-24 10:18:18 +00002019var _ Path = testPath{}
2020
Colin Cross40e33732019-02-15 11:08:35 -08002021// PathForTesting returns a Path constructed from joining the elements of paths with '/'. It should only be used from
2022// within tests.
Colin Cross5b529592017-05-09 13:34:34 -07002023func PathForTesting(paths ...string) Path {
Colin Cross1ccfcc32018-02-22 13:54:26 -08002024 p, err := validateSafePath(paths...)
2025 if err != nil {
2026 panic(err)
2027 }
Colin Cross5b529592017-05-09 13:34:34 -07002028 return testPath{basePath{path: p, rel: p}}
2029}
2030
Sam Delmerico2351eac2022-05-24 17:10:02 +00002031func PathForTestingWithRel(path, rel string) Path {
2032 p, err := validateSafePath(path, rel)
2033 if err != nil {
2034 panic(err)
2035 }
2036 r, err := validatePath(rel)
2037 if err != nil {
2038 panic(err)
2039 }
2040 return testPath{basePath{path: p, rel: r}}
2041}
2042
Colin Cross40e33732019-02-15 11:08:35 -08002043// PathsForTesting returns a Path constructed from each element in strs. It should only be used from within tests.
2044func PathsForTesting(strs ...string) Paths {
Colin Cross5b529592017-05-09 13:34:34 -07002045 p := make(Paths, len(strs))
2046 for i, s := range strs {
2047 p[i] = PathForTesting(s)
2048 }
2049
2050 return p
2051}
Colin Cross43f08db2018-11-12 10:13:39 -08002052
Colin Cross40e33732019-02-15 11:08:35 -08002053type testPathContext struct {
2054 config Config
Colin Cross40e33732019-02-15 11:08:35 -08002055}
2056
Colin Cross40e33732019-02-15 11:08:35 -08002057func (x *testPathContext) Config() Config { return x.config }
2058func (x *testPathContext) AddNinjaFileDeps(...string) {}
2059
2060// PathContextForTesting returns a PathContext that can be used in tests, for example to create an OutputPath with
2061// PathForOutput.
Colin Cross98be1bb2019-12-13 20:41:13 -08002062func PathContextForTesting(config Config) PathContext {
Colin Cross40e33732019-02-15 11:08:35 -08002063 return &testPathContext{
2064 config: config,
Colin Cross40e33732019-02-15 11:08:35 -08002065 }
2066}
2067
Ulya Trafimovichccc8c852020-10-14 11:29:07 +01002068type testModuleInstallPathContext struct {
2069 baseModuleContext
2070
2071 inData bool
2072 inTestcases bool
2073 inSanitizerDir bool
2074 inRamdisk bool
2075 inVendorRamdisk bool
Inseob Kim08758f02021-04-08 21:13:22 +09002076 inDebugRamdisk bool
Ulya Trafimovichccc8c852020-10-14 11:29:07 +01002077 inRecovery bool
2078 inRoot bool
2079 forceOS *OsType
2080 forceArch *ArchType
2081}
2082
2083func (m testModuleInstallPathContext) Config() Config {
2084 return m.baseModuleContext.config
2085}
2086
2087func (testModuleInstallPathContext) AddNinjaFileDeps(deps ...string) {}
2088
2089func (m testModuleInstallPathContext) InstallInData() bool {
2090 return m.inData
2091}
2092
2093func (m testModuleInstallPathContext) InstallInTestcases() bool {
2094 return m.inTestcases
2095}
2096
2097func (m testModuleInstallPathContext) InstallInSanitizerDir() bool {
2098 return m.inSanitizerDir
2099}
2100
2101func (m testModuleInstallPathContext) InstallInRamdisk() bool {
2102 return m.inRamdisk
2103}
2104
2105func (m testModuleInstallPathContext) InstallInVendorRamdisk() bool {
2106 return m.inVendorRamdisk
2107}
2108
Inseob Kim08758f02021-04-08 21:13:22 +09002109func (m testModuleInstallPathContext) InstallInDebugRamdisk() bool {
2110 return m.inDebugRamdisk
2111}
2112
Ulya Trafimovichccc8c852020-10-14 11:29:07 +01002113func (m testModuleInstallPathContext) InstallInRecovery() bool {
2114 return m.inRecovery
2115}
2116
2117func (m testModuleInstallPathContext) InstallInRoot() bool {
2118 return m.inRoot
2119}
2120
Ulya Trafimovichccc8c852020-10-14 11:29:07 +01002121func (m testModuleInstallPathContext) InstallForceOS() (*OsType, *ArchType) {
2122 return m.forceOS, m.forceArch
2123}
2124
2125// Construct a minimal ModuleInstallPathContext for testing. Note that baseModuleContext is
2126// default-initialized, which leaves blueprint.baseModuleContext set to nil, so methods that are
2127// delegated to it will panic.
2128func ModuleInstallPathContextForTesting(config Config) ModuleInstallPathContext {
2129 ctx := &testModuleInstallPathContext{}
2130 ctx.config = config
2131 ctx.os = Android
2132 return ctx
2133}
2134
Colin Cross43f08db2018-11-12 10:13:39 -08002135// Rel performs the same function as filepath.Rel, but reports errors to a PathContext, and reports an error if
2136// targetPath is not inside basePath.
2137func Rel(ctx PathContext, basePath string, targetPath string) string {
2138 rel, isRel := MaybeRel(ctx, basePath, targetPath)
2139 if !isRel {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01002140 ReportPathErrorf(ctx, "path %q is not under path %q", targetPath, basePath)
Colin Cross43f08db2018-11-12 10:13:39 -08002141 return ""
2142 }
2143 return rel
2144}
2145
2146// MaybeRel performs the same function as filepath.Rel, but reports errors to a PathContext, and returns false if
2147// targetPath is not inside basePath.
2148func MaybeRel(ctx PathContext, basePath string, targetPath string) (string, bool) {
Dan Willemsen633c5022019-04-12 11:11:38 -07002149 rel, isRel, err := maybeRelErr(basePath, targetPath)
2150 if err != nil {
2151 reportPathError(ctx, err)
2152 }
2153 return rel, isRel
2154}
2155
2156func maybeRelErr(basePath string, targetPath string) (string, bool, error) {
Colin Cross43f08db2018-11-12 10:13:39 -08002157 // filepath.Rel returns an error if one path is absolute and the other is not, handle that case first.
2158 if filepath.IsAbs(basePath) != filepath.IsAbs(targetPath) {
Dan Willemsen633c5022019-04-12 11:11:38 -07002159 return "", false, nil
Colin Cross43f08db2018-11-12 10:13:39 -08002160 }
2161 rel, err := filepath.Rel(basePath, targetPath)
2162 if err != nil {
Dan Willemsen633c5022019-04-12 11:11:38 -07002163 return "", false, err
Colin Cross43f08db2018-11-12 10:13:39 -08002164 } else if rel == ".." || strings.HasPrefix(rel, "../") || strings.HasPrefix(rel, "/") {
Dan Willemsen633c5022019-04-12 11:11:38 -07002165 return "", false, nil
Colin Cross43f08db2018-11-12 10:13:39 -08002166 }
Dan Willemsen633c5022019-04-12 11:11:38 -07002167 return rel, true, nil
Colin Cross43f08db2018-11-12 10:13:39 -08002168}
Colin Cross988414c2020-01-11 01:11:46 +00002169
2170// Writes a file to the output directory. Attempting to write directly to the output directory
2171// will fail due to the sandbox of the soong_build process.
Chris Parsons1a12d032023-02-06 22:37:41 -05002172// Only writes the file if the file doesn't exist or if it has different contents, to prevent
2173// updating the timestamp if no changes would be made. (This is better for incremental
2174// performance.)
Colin Cross988414c2020-01-11 01:11:46 +00002175func WriteFileToOutputDir(path WritablePath, data []byte, perm os.FileMode) error {
Colin Crossd6421132021-11-09 12:32:34 -08002176 absPath := absolutePath(path.String())
2177 err := os.MkdirAll(filepath.Dir(absPath), 0777)
2178 if err != nil {
2179 return err
2180 }
Chris Parsons1a12d032023-02-06 22:37:41 -05002181 return pathtools.WriteFileIfChanged(absPath, data, perm)
Colin Cross988414c2020-01-11 01:11:46 +00002182}
2183
Liz Kammer2dd9ca42020-11-25 16:06:39 -08002184func RemoveAllOutputDir(path WritablePath) error {
2185 return os.RemoveAll(absolutePath(path.String()))
2186}
2187
2188func CreateOutputDirIfNonexistent(path WritablePath, perm os.FileMode) error {
2189 dir := absolutePath(path.String())
Liz Kammer09f947d2021-05-12 14:51:49 -04002190 return createDirIfNonexistent(dir, perm)
2191}
2192
2193func createDirIfNonexistent(dir string, perm os.FileMode) error {
Liz Kammer2dd9ca42020-11-25 16:06:39 -08002194 if _, err := os.Stat(dir); os.IsNotExist(err) {
2195 return os.MkdirAll(dir, os.ModePerm)
2196 } else {
2197 return err
2198 }
2199}
2200
Jingwen Chen78257e52021-05-21 02:34:24 +00002201// absolutePath is deliberately private so that Soong's Go plugins can't use it to find and
2202// read arbitrary files without going through the methods in the current package that track
2203// dependencies.
Colin Cross988414c2020-01-11 01:11:46 +00002204func absolutePath(path string) string {
2205 if filepath.IsAbs(path) {
2206 return path
2207 }
2208 return filepath.Join(absSrcDir, path)
2209}
Chris Parsons216e10a2020-07-09 17:12:52 -04002210
2211// A DataPath represents the path of a file to be used as data, for example
2212// a test library to be installed alongside a test.
2213// The data file should be installed (copied from `<SrcPath>`) to
2214// `<install_root>/<RelativeInstallPath>/<filename>`, or
2215// `<install_root>/<filename>` if RelativeInstallPath is empty.
2216type DataPath struct {
2217 // The path of the data file that should be copied into the data directory
2218 SrcPath Path
2219 // The install path of the data file, relative to the install root.
2220 RelativeInstallPath string
2221}
Colin Crossdcf71b22021-02-01 13:59:03 -08002222
2223// PathsIfNonNil returns a Paths containing only the non-nil input arguments.
2224func PathsIfNonNil(paths ...Path) Paths {
2225 if len(paths) == 0 {
2226 // Fast path for empty argument list
2227 return nil
2228 } else if len(paths) == 1 {
2229 // Fast path for a single argument
2230 if paths[0] != nil {
2231 return paths
2232 } else {
2233 return nil
2234 }
2235 }
2236 ret := make(Paths, 0, len(paths))
2237 for _, path := range paths {
2238 if path != nil {
2239 ret = append(ret, path)
2240 }
2241 }
2242 if len(ret) == 0 {
2243 return nil
2244 }
2245 return ret
2246}
Chris Wailesb2703ad2021-07-30 13:25:42 -07002247
2248var thirdPartyDirPrefixExceptions = []*regexp.Regexp{
2249 regexp.MustCompile("^vendor/[^/]*google[^/]*/"),
2250 regexp.MustCompile("^hardware/google/"),
2251 regexp.MustCompile("^hardware/interfaces/"),
2252 regexp.MustCompile("^hardware/libhardware[^/]*/"),
2253 regexp.MustCompile("^hardware/ril/"),
2254}
2255
2256func IsThirdPartyPath(path string) bool {
2257 thirdPartyDirPrefixes := []string{"external/", "vendor/", "hardware/"}
2258
2259 if HasAnyPrefix(path, thirdPartyDirPrefixes) {
2260 for _, prefix := range thirdPartyDirPrefixExceptions {
2261 if prefix.MatchString(path) {
2262 return false
2263 }
2264 }
2265 return true
2266 }
2267 return false
2268}