blob: 7658299b4def88044428e1772021f5ee049e3e05 [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
174 // Rel returns the portion of the path relative to the directory it was created from. For
175 // example, Rel on a PathsForModuleSrc would return the path relative to the module source
Colin Cross0db55682017-12-05 15:36:55 -0800176 // directory, and OutputPath.Join("foo").Rel() would return "foo".
Colin Crossfaeb7aa2017-02-01 14:12:44 -0800177 Rel() string
Paul Duffin85d8f0d2021-03-24 10:18:18 +0000178
179 // RelativeToTop returns a new path relative to the top, it is provided solely for use in tests.
180 //
181 // It is guaranteed to always return the same type as it is called on, e.g. if called on an
182 // InstallPath then the returned value can be converted to an InstallPath.
183 //
184 // A standard build has the following structure:
185 // ../top/
186 // out/ - make install files go here.
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +0200187 // out/soong - this is the soongOutDir passed to NewTestConfig()
Paul Duffin85d8f0d2021-03-24 10:18:18 +0000188 // ... - the source files
189 //
190 // This function converts a path so that it appears relative to the ../top/ directory, i.e.
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +0200191 // * Make install paths, which have the pattern "soongOutDir/../<path>" are converted into the top
Paul Duffin85d8f0d2021-03-24 10:18:18 +0000192 // relative path "out/<path>"
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +0200193 // * Soong install paths and other writable paths, which have the pattern "soongOutDir/<path>" are
Paul Duffin85d8f0d2021-03-24 10:18:18 +0000194 // converted into the top relative path "out/soong/<path>".
195 // * Source paths are already relative to the top.
196 // * Phony paths are not relative to anything.
197 // * toolDepPath have an absolute but known value in so don't need making relative to anything in
198 // order to test.
199 RelativeToTop() Path
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700200}
201
Paul Duffin85d8f0d2021-03-24 10:18:18 +0000202const (
203 OutDir = "out"
204 OutSoongDir = OutDir + "/soong"
205)
206
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700207// WritablePath is a type of path that can be used as an output for build rules.
208type WritablePath interface {
209 Path
210
Paul Duffin9b478b02019-12-10 13:41:51 +0000211 // return the path to the build directory.
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +0200212 getSoongOutDir() string
Paul Duffin9b478b02019-12-10 13:41:51 +0000213
Jeff Gaston734e3802017-04-10 15:47:24 -0700214 // the writablePath method doesn't directly do anything,
215 // but it allows a struct to distinguish between whether or not it implements the WritablePath interface
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700216 writablePath()
Hans MÃ¥nssond3f2bd72020-11-27 12:37:28 +0100217
218 ReplaceExtension(ctx PathContext, ext string) OutputPath
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700219}
220
221type genPathProvider interface {
Liz Kammera830f3a2020-11-10 10:50:34 -0800222 genPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleGenPath
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700223}
224type objPathProvider interface {
Liz Kammera830f3a2020-11-10 10:50:34 -0800225 objPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleObjPath
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700226}
227type resPathProvider interface {
Liz Kammera830f3a2020-11-10 10:50:34 -0800228 resPathWithName(ctx ModuleOutPathContext, name string) ModuleResPath
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700229}
230
231// GenPathWithExt derives a new file path in ctx's generated sources directory
232// from the current path, but with the new extension.
Liz Kammera830f3a2020-11-10 10:50:34 -0800233func GenPathWithExt(ctx ModuleOutPathContext, subdir string, p Path, ext string) ModuleGenPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700234 if path, ok := p.(genPathProvider); ok {
Dan Willemsen21ec4902016-11-02 20:43:13 -0700235 return path.genPathWithExt(ctx, subdir, ext)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700236 }
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +0100237 ReportPathErrorf(ctx, "Tried to create generated file from unsupported path: %s(%s)", reflect.TypeOf(p).Name(), p)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700238 return PathForModuleGen(ctx)
239}
240
241// ObjPathWithExt derives a new file path in ctx's object directory from the
242// current path, but with the new extension.
Liz Kammera830f3a2020-11-10 10:50:34 -0800243func ObjPathWithExt(ctx ModuleOutPathContext, subdir string, p Path, ext string) ModuleObjPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700244 if path, ok := p.(objPathProvider); ok {
245 return path.objPathWithExt(ctx, subdir, ext)
246 }
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +0100247 ReportPathErrorf(ctx, "Tried to create object file from unsupported path: %s (%s)", reflect.TypeOf(p).Name(), p)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700248 return PathForModuleObj(ctx)
249}
250
251// ResPathWithName derives a new path in ctx's output resource directory, using
252// the current path to create the directory name, and the `name` argument for
253// the filename.
Liz Kammera830f3a2020-11-10 10:50:34 -0800254func ResPathWithName(ctx ModuleOutPathContext, p Path, name string) ModuleResPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700255 if path, ok := p.(resPathProvider); ok {
256 return path.resPathWithName(ctx, name)
257 }
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +0100258 ReportPathErrorf(ctx, "Tried to create res file from unsupported path: %s (%s)", reflect.TypeOf(p).Name(), p)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700259 return PathForModuleRes(ctx)
260}
261
262// OptionalPath is a container that may or may not contain a valid Path.
263type OptionalPath struct {
Martin Stjernholmc32dd1c2021-09-15 02:39:00 +0100264 path Path // nil if invalid.
265 invalidReason string // Not applicable if path != nil. "" if the reason is unknown.
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700266}
267
268// OptionalPathForPath returns an OptionalPath containing the path.
269func OptionalPathForPath(path Path) OptionalPath {
Martin Stjernholm2fee27f2021-09-16 14:11:12 +0100270 return OptionalPath{path: path}
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700271}
272
Martin Stjernholmc32dd1c2021-09-15 02:39:00 +0100273// InvalidOptionalPath returns an OptionalPath that is invalid with the given reason.
274func InvalidOptionalPath(reason string) OptionalPath {
275
276 return OptionalPath{invalidReason: reason}
277}
278
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700279// Valid returns whether there is a valid path
280func (p OptionalPath) Valid() bool {
Martin Stjernholm2fee27f2021-09-16 14:11:12 +0100281 return p.path != nil
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700282}
283
284// Path returns the Path embedded in this OptionalPath. You must be sure that
285// there is a valid path, since this method will panic if there is not.
286func (p OptionalPath) Path() Path {
Martin Stjernholm2fee27f2021-09-16 14:11:12 +0100287 if p.path == nil {
Martin Stjernholmc32dd1c2021-09-15 02:39:00 +0100288 msg := "Requesting an invalid path"
289 if p.invalidReason != "" {
290 msg += ": " + p.invalidReason
291 }
292 panic(msg)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700293 }
294 return p.path
295}
296
Martin Stjernholmc32dd1c2021-09-15 02:39:00 +0100297// InvalidReason returns the reason that the optional path is invalid, or "" if it is valid.
298func (p OptionalPath) InvalidReason() string {
299 if p.path != nil {
300 return ""
301 }
302 if p.invalidReason == "" {
303 return "unknown"
304 }
305 return p.invalidReason
306}
307
Paul Duffinef081852021-05-13 11:11:15 +0100308// AsPaths converts the OptionalPath into Paths.
309//
310// It returns nil if this is not valid, or a single length slice containing the Path embedded in
311// this OptionalPath.
312func (p OptionalPath) AsPaths() Paths {
Martin Stjernholm2fee27f2021-09-16 14:11:12 +0100313 if p.path == nil {
Paul Duffinef081852021-05-13 11:11:15 +0100314 return nil
315 }
316 return Paths{p.path}
317}
318
Paul Duffinafdd4062021-03-30 19:44:07 +0100319// RelativeToTop returns an OptionalPath with the path that was embedded having been replaced by the
320// result of calling Path.RelativeToTop on it.
321func (p OptionalPath) RelativeToTop() OptionalPath {
Martin Stjernholm2fee27f2021-09-16 14:11:12 +0100322 if p.path == nil {
Paul Duffina5b81352021-03-28 23:57:19 +0100323 return p
324 }
325 p.path = p.path.RelativeToTop()
326 return p
327}
328
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700329// String returns the string version of the Path, or "" if it isn't valid.
330func (p OptionalPath) String() string {
Martin Stjernholm2fee27f2021-09-16 14:11:12 +0100331 if p.path != nil {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700332 return p.path.String()
333 } else {
334 return ""
Colin Crossf2298272015-05-12 11:36:53 -0700335 }
336}
Colin Cross6e18ca42015-07-14 18:55:36 -0700337
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700338// Paths is a slice of Path objects, with helpers to operate on the collection.
339type Paths []Path
340
Paul Duffin85d8f0d2021-03-24 10:18:18 +0000341// RelativeToTop creates a new Paths containing the result of calling Path.RelativeToTop on each
342// item in this slice.
343func (p Paths) RelativeToTop() Paths {
344 ensureTestOnly()
345 if p == nil {
346 return p
347 }
348 ret := make(Paths, len(p))
349 for i, path := range p {
350 ret[i] = path.RelativeToTop()
351 }
352 return ret
353}
354
Jingwen Chen40fd90a2020-06-15 05:24:19 +0000355func (paths Paths) containsPath(path Path) bool {
356 for _, p := range paths {
357 if p == path {
358 return true
359 }
360 }
361 return false
362}
363
Liz Kammer7aa52882021-02-11 09:16:14 -0500364// PathsForSource returns Paths rooted from SrcDir, *not* rooted from the module's local source
365// directory
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700366func PathsForSource(ctx PathContext, paths []string) Paths {
367 ret := make(Paths, len(paths))
368 for i, path := range paths {
369 ret[i] = PathForSource(ctx, path)
370 }
371 return ret
372}
373
Liz Kammer7aa52882021-02-11 09:16:14 -0500374// ExistentPathsForSources returns a list of Paths rooted from SrcDir, *not* rooted from the
375// module's local source directory, that are found in the tree. If any are not found, they are
376// 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 -0700377func ExistentPathsForSources(ctx PathGlobContext, paths []string) Paths {
Dan Willemsen7b310ee2015-12-18 15:11:17 -0800378 ret := make(Paths, 0, len(paths))
379 for _, path := range paths {
Colin Cross32f38982018-02-22 11:47:25 -0800380 p := ExistentPathForSource(ctx, path)
Dan Willemsen7b310ee2015-12-18 15:11:17 -0800381 if p.Valid() {
382 ret = append(ret, p.Path())
383 }
384 }
385 return ret
386}
387
Liz Kammer620dea62021-04-14 17:36:10 -0400388// PathsForModuleSrc returns a Paths{} containing the resolved references in paths:
Colin Crossd079e0b2022-08-16 10:27:33 -0700389// - filepath, relative to local module directory, resolves as a filepath relative to the local
390// source directory
391// - glob, relative to the local module directory, resolves as filepath(s), relative to the local
392// source directory.
393// - other modules using the ":name{.tag}" syntax. These modules must implement SourceFileProducer
394// or OutputFileProducer. These resolve as a filepath to an output filepath or generated source
395// filepath.
396//
Liz Kammer620dea62021-04-14 17:36:10 -0400397// Properties passed as the paths argument must have been annotated with struct tag
Colin Cross41955e82019-05-29 14:40:35 -0700398// `android:"path"` so that dependencies on SourceFileProducer modules will have already been handled by the
Spandan Das950091c2023-07-19 22:26:37 +0000399// pathdeps mutator.
Liz Kammer620dea62021-04-14 17:36:10 -0400400// If a requested module is not found as a dependency:
Colin Crossd079e0b2022-08-16 10:27:33 -0700401// - if ctx.Config().AllowMissingDependencies() is true, this module to be marked as having
Liz Kammer620dea62021-04-14 17:36:10 -0400402// missing dependencies
Colin Crossd079e0b2022-08-16 10:27:33 -0700403// - otherwise, a ModuleError is thrown.
Liz Kammera830f3a2020-11-10 10:50:34 -0800404func PathsForModuleSrc(ctx ModuleMissingDepsPathContext, paths []string) Paths {
Colin Cross8a497952019-03-05 22:25:09 -0800405 return PathsForModuleSrcExcludes(ctx, paths, nil)
406}
407
Liz Kammer619be462022-01-28 15:13:39 -0500408type SourceInput struct {
409 Context ModuleMissingDepsPathContext
410 Paths []string
411 ExcludePaths []string
412 IncludeDirs bool
413}
414
Liz Kammer620dea62021-04-14 17:36:10 -0400415// PathsForModuleSrcExcludes returns a Paths{} containing the resolved references in paths, minus
416// those listed in excludes. Elements of paths and excludes are resolved as:
Colin Crossd079e0b2022-08-16 10:27:33 -0700417// - filepath, relative to local module directory, resolves as a filepath relative to the local
418// source directory
419// - glob, relative to the local module directory, resolves as filepath(s), relative to the local
420// source directory. Not valid in excludes.
421// - other modules using the ":name{.tag}" syntax. These modules must implement SourceFileProducer
422// or OutputFileProducer. These resolve as a filepath to an output filepath or generated source
423// filepath.
424//
Liz Kammer620dea62021-04-14 17:36:10 -0400425// excluding the items (similarly resolved
426// Properties passed as the paths argument must have been annotated with struct tag
427// `android:"path"` so that dependencies on SourceFileProducer modules will have already been handled by the
Spandan Das950091c2023-07-19 22:26:37 +0000428// pathdeps mutator.
Liz Kammer620dea62021-04-14 17:36:10 -0400429// If a requested module is not found as a dependency:
Colin Crossd079e0b2022-08-16 10:27:33 -0700430// - if ctx.Config().AllowMissingDependencies() is true, this module to be marked as having
Liz Kammer620dea62021-04-14 17:36:10 -0400431// missing dependencies
Colin Crossd079e0b2022-08-16 10:27:33 -0700432// - otherwise, a ModuleError is thrown.
Liz Kammera830f3a2020-11-10 10:50:34 -0800433func PathsForModuleSrcExcludes(ctx ModuleMissingDepsPathContext, paths, excludes []string) Paths {
Liz Kammer619be462022-01-28 15:13:39 -0500434 return PathsRelativeToModuleSourceDir(SourceInput{
435 Context: ctx,
436 Paths: paths,
437 ExcludePaths: excludes,
438 IncludeDirs: true,
439 })
440}
441
442func PathsRelativeToModuleSourceDir(input SourceInput) Paths {
443 ret, missingDeps := PathsAndMissingDepsRelativeToModuleSourceDir(input)
444 if input.Context.Config().AllowMissingDependencies() {
445 input.Context.AddMissingDependencies(missingDeps)
Colin Crossba71a3f2019-03-18 12:12:48 -0700446 } else {
447 for _, m := range missingDeps {
Liz Kammer619be462022-01-28 15:13:39 -0500448 input.Context.ModuleErrorf(`missing dependency on %q, is the property annotated with android:"path"?`, m)
Colin Crossba71a3f2019-03-18 12:12:48 -0700449 }
450 }
451 return ret
452}
453
Ulya Trafimovich4d2eeed2019-11-08 10:54:21 +0000454// OutputPaths is a slice of OutputPath objects, with helpers to operate on the collection.
455type OutputPaths []OutputPath
456
457// Paths returns the OutputPaths as a Paths
458func (p OutputPaths) Paths() Paths {
459 if p == nil {
460 return nil
461 }
462 ret := make(Paths, len(p))
463 for i, path := range p {
464 ret[i] = path
465 }
466 return ret
467}
468
469// Strings returns the string forms of the writable paths.
470func (p OutputPaths) Strings() []string {
471 if p == nil {
472 return nil
473 }
474 ret := make([]string, len(p))
475 for i, path := range p {
476 ret[i] = path.String()
477 }
478 return ret
479}
480
Colin Crossa44551f2021-10-25 15:36:21 -0700481// PathForGoBinary returns the path to the installed location of a bootstrap_go_binary module.
482func PathForGoBinary(ctx PathContext, goBinary bootstrap.GoBinaryTool) Path {
Cole Faust3b703f32023-10-16 13:30:51 -0700483 goBinaryInstallDir := pathForInstall(ctx, ctx.Config().BuildOS, ctx.Config().BuildArch, "bin")
Colin Crossa44551f2021-10-25 15:36:21 -0700484 rel := Rel(ctx, goBinaryInstallDir.String(), goBinary.InstallPath())
485 return goBinaryInstallDir.Join(ctx, rel)
486}
487
Liz Kammera830f3a2020-11-10 10:50:34 -0800488// Expands Paths to a SourceFileProducer or OutputFileProducer module dependency referenced via ":name" or ":name{.tag}" syntax.
489// If the dependency is not found, a missingErrorDependency is returned.
490// If the module dependency is not a SourceFileProducer or OutputFileProducer, appropriate errors will be returned.
491func getPathsFromModuleDep(ctx ModuleWithDepsPathContext, path, moduleName, tag string) (Paths, error) {
Paul Duffind5cf92e2021-07-09 17:38:55 +0100492 module := GetModuleFromPathDep(ctx, moduleName, tag)
Liz Kammera830f3a2020-11-10 10:50:34 -0800493 if module == nil {
494 return nil, missingDependencyError{[]string{moduleName}}
495 }
Colin Crossfa65cee2021-03-22 17:05:59 -0700496 if aModule, ok := module.(Module); ok && !aModule.Enabled() {
497 return nil, missingDependencyError{[]string{moduleName}}
498 }
Liz Kammera830f3a2020-11-10 10:50:34 -0800499 if outProducer, ok := module.(OutputFileProducer); ok {
500 outputFiles, err := outProducer.OutputFiles(tag)
501 if err != nil {
502 return nil, fmt.Errorf("path dependency %q: %s", path, err)
503 }
504 return outputFiles, nil
505 } else if tag != "" {
506 return nil, fmt.Errorf("path dependency %q is not an output file producing module", path)
Colin Cross0e446152021-05-03 13:35:32 -0700507 } else if goBinary, ok := module.(bootstrap.GoBinaryTool); ok {
Colin Crossa44551f2021-10-25 15:36:21 -0700508 goBinaryPath := PathForGoBinary(ctx, goBinary)
509 return Paths{goBinaryPath}, nil
Liz Kammera830f3a2020-11-10 10:50:34 -0800510 } else if srcProducer, ok := module.(SourceFileProducer); ok {
511 return srcProducer.Srcs(), nil
512 } else {
513 return nil, fmt.Errorf("path dependency %q is not a source file producing module", path)
514 }
515}
516
Paul Duffind5cf92e2021-07-09 17:38:55 +0100517// GetModuleFromPathDep will return the module that was added as a dependency automatically for
518// properties tagged with `android:"path"` or manually using ExtractSourceDeps or
519// ExtractSourcesDeps.
520//
521// The moduleName and tag supplied to this should be the values returned from SrcIsModuleWithTag.
522// Or, if no tag is expected then the moduleName should be the value returned by SrcIsModule and
523// the tag must be "".
524//
525// If tag is "" then the returned module will be the dependency that was added for ":moduleName".
526// Otherwise, it is the dependency that was added for ":moduleName{tag}".
Paul Duffind5cf92e2021-07-09 17:38:55 +0100527func GetModuleFromPathDep(ctx ModuleWithDepsPathContext, moduleName, tag string) blueprint.Module {
Paul Duffin40131a32021-07-09 17:10:35 +0100528 var found blueprint.Module
529 // The sourceOrOutputDepTag uniquely identifies the module dependency as it contains both the
530 // module name and the tag. Dependencies added automatically for properties tagged with
531 // `android:"path"` are deduped so are guaranteed to be unique. It is possible for duplicate
532 // dependencies to be added manually using ExtractSourcesDeps or ExtractSourceDeps but even then
533 // it will always be the case that the dependencies will be identical, i.e. the same tag and same
534 // moduleName referring to the same dependency module.
535 //
536 // It does not matter whether the moduleName is a fully qualified name or if the module
537 // dependency is a prebuilt module. All that matters is the same information is supplied to
538 // create the tag here as was supplied to create the tag when the dependency was added so that
539 // this finds the matching dependency module.
540 expectedTag := sourceOrOutputDepTag(moduleName, tag)
541 ctx.VisitDirectDepsBlueprint(func(module blueprint.Module) {
542 depTag := ctx.OtherModuleDependencyTag(module)
543 if depTag == expectedTag {
544 found = module
545 }
546 })
547 return found
Paul Duffind5cf92e2021-07-09 17:38:55 +0100548}
549
Liz Kammer620dea62021-04-14 17:36:10 -0400550// PathsAndMissingDepsForModuleSrcExcludes returns a Paths{} containing the resolved references in
551// paths, minus those listed in excludes. Elements of paths and excludes are resolved as:
Colin Crossd079e0b2022-08-16 10:27:33 -0700552// - filepath, relative to local module directory, resolves as a filepath relative to the local
553// source directory
554// - glob, relative to the local module directory, resolves as filepath(s), relative to the local
555// source directory. Not valid in excludes.
556// - other modules using the ":name{.tag}" syntax. These modules must implement SourceFileProducer
557// or OutputFileProducer. These resolve as a filepath to an output filepath or generated source
558// filepath.
559//
Liz Kammer620dea62021-04-14 17:36:10 -0400560// and a list of the module names of missing module dependencies are returned as the second return.
561// Properties passed as the paths argument must have been annotated with struct tag
Colin Cross41955e82019-05-29 14:40:35 -0700562// `android:"path"` so that dependencies on SourceFileProducer modules will have already been handled by the
Spandan Das950091c2023-07-19 22:26:37 +0000563// pathdeps mutator.
Liz Kammer619be462022-01-28 15:13:39 -0500564func PathsAndMissingDepsForModuleSrcExcludes(ctx ModuleMissingDepsPathContext, paths, excludes []string) (Paths, []string) {
565 return PathsAndMissingDepsRelativeToModuleSourceDir(SourceInput{
566 Context: ctx,
567 Paths: paths,
568 ExcludePaths: excludes,
569 IncludeDirs: true,
570 })
571}
572
573func PathsAndMissingDepsRelativeToModuleSourceDir(input SourceInput) (Paths, []string) {
574 prefix := pathForModuleSrc(input.Context).String()
Colin Cross8a497952019-03-05 22:25:09 -0800575
576 var expandedExcludes []string
Liz Kammer619be462022-01-28 15:13:39 -0500577 if input.ExcludePaths != nil {
578 expandedExcludes = make([]string, 0, len(input.ExcludePaths))
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700579 }
Colin Cross8a497952019-03-05 22:25:09 -0800580
Colin Crossba71a3f2019-03-18 12:12:48 -0700581 var missingExcludeDeps []string
Liz Kammer619be462022-01-28 15:13:39 -0500582 for _, e := range input.ExcludePaths {
Colin Cross41955e82019-05-29 14:40:35 -0700583 if m, t := SrcIsModuleWithTag(e); m != "" {
Liz Kammer619be462022-01-28 15:13:39 -0500584 modulePaths, err := getPathsFromModuleDep(input.Context, e, m, t)
Liz Kammera830f3a2020-11-10 10:50:34 -0800585 if m, ok := err.(missingDependencyError); ok {
586 missingExcludeDeps = append(missingExcludeDeps, m.missingDeps...)
587 } else if err != nil {
Liz Kammer619be462022-01-28 15:13:39 -0500588 reportPathError(input.Context, err)
Colin Cross8a497952019-03-05 22:25:09 -0800589 } else {
Liz Kammera830f3a2020-11-10 10:50:34 -0800590 expandedExcludes = append(expandedExcludes, modulePaths.Strings()...)
Colin Cross8a497952019-03-05 22:25:09 -0800591 }
592 } else {
593 expandedExcludes = append(expandedExcludes, filepath.Join(prefix, e))
594 }
595 }
596
Liz Kammer619be462022-01-28 15:13:39 -0500597 if input.Paths == nil {
Colin Crossba71a3f2019-03-18 12:12:48 -0700598 return nil, missingExcludeDeps
Colin Cross8a497952019-03-05 22:25:09 -0800599 }
600
Colin Crossba71a3f2019-03-18 12:12:48 -0700601 var missingDeps []string
602
Liz Kammer619be462022-01-28 15:13:39 -0500603 expandedSrcFiles := make(Paths, 0, len(input.Paths))
604 for _, s := range input.Paths {
605 srcFiles, err := expandOneSrcPath(sourcePathInput{
606 context: input.Context,
607 path: s,
608 expandedExcludes: expandedExcludes,
609 includeDirs: input.IncludeDirs,
610 })
Colin Cross8a497952019-03-05 22:25:09 -0800611 if depErr, ok := err.(missingDependencyError); ok {
Colin Crossba71a3f2019-03-18 12:12:48 -0700612 missingDeps = append(missingDeps, depErr.missingDeps...)
Colin Cross8a497952019-03-05 22:25:09 -0800613 } else if err != nil {
Liz Kammer619be462022-01-28 15:13:39 -0500614 reportPathError(input.Context, err)
Colin Cross8a497952019-03-05 22:25:09 -0800615 }
616 expandedSrcFiles = append(expandedSrcFiles, srcFiles...)
617 }
Colin Crossba71a3f2019-03-18 12:12:48 -0700618
619 return expandedSrcFiles, append(missingDeps, missingExcludeDeps...)
Colin Cross8a497952019-03-05 22:25:09 -0800620}
621
622type missingDependencyError struct {
623 missingDeps []string
624}
625
626func (e missingDependencyError) Error() string {
627 return "missing dependencies: " + strings.Join(e.missingDeps, ", ")
628}
629
Liz Kammer619be462022-01-28 15:13:39 -0500630type sourcePathInput struct {
631 context ModuleWithDepsPathContext
632 path string
633 expandedExcludes []string
634 includeDirs bool
635}
636
Liz Kammera830f3a2020-11-10 10:50:34 -0800637// Expands one path string to Paths rooted from the module's local source
638// directory, excluding those listed in the expandedExcludes.
639// Expands globs, references to SourceFileProducer or OutputFileProducer modules using the ":name" and ":name{.tag}" syntax.
Liz Kammer619be462022-01-28 15:13:39 -0500640func expandOneSrcPath(input sourcePathInput) (Paths, error) {
Jooyung Han7607dd32020-07-05 10:23:14 +0900641 excludePaths := func(paths Paths) Paths {
Liz Kammer619be462022-01-28 15:13:39 -0500642 if len(input.expandedExcludes) == 0 {
Jooyung Han7607dd32020-07-05 10:23:14 +0900643 return paths
644 }
645 remainder := make(Paths, 0, len(paths))
646 for _, p := range paths {
Liz Kammer619be462022-01-28 15:13:39 -0500647 if !InList(p.String(), input.expandedExcludes) {
Jooyung Han7607dd32020-07-05 10:23:14 +0900648 remainder = append(remainder, p)
649 }
650 }
651 return remainder
652 }
Liz Kammer619be462022-01-28 15:13:39 -0500653 if m, t := SrcIsModuleWithTag(input.path); m != "" {
654 modulePaths, err := getPathsFromModuleDep(input.context, input.path, m, t)
Liz Kammera830f3a2020-11-10 10:50:34 -0800655 if err != nil {
656 return nil, err
Colin Cross8a497952019-03-05 22:25:09 -0800657 } else {
Liz Kammera830f3a2020-11-10 10:50:34 -0800658 return excludePaths(modulePaths), nil
Colin Cross8a497952019-03-05 22:25:09 -0800659 }
Colin Cross8a497952019-03-05 22:25:09 -0800660 } else {
Liz Kammer619be462022-01-28 15:13:39 -0500661 p := pathForModuleSrc(input.context, input.path)
662 if pathtools.IsGlob(input.path) {
663 paths := GlobFiles(input.context, p.String(), input.expandedExcludes)
664 return PathsWithModuleSrcSubDir(input.context, paths, ""), nil
665 } else {
666 if exists, _, err := input.context.Config().fs.Exists(p.String()); err != nil {
667 ReportPathErrorf(input.context, "%s: %s", p, err.Error())
668 } else if !exists && !input.context.Config().TestAllowNonExistentPaths {
669 ReportPathErrorf(input.context, "module source path %q does not exist", p)
670 } else if !input.includeDirs {
671 if isDir, err := input.context.Config().fs.IsDir(p.String()); exists && err != nil {
672 ReportPathErrorf(input.context, "%s: %s", p, err.Error())
673 } else if isDir {
674 ReportPathErrorf(input.context, "module source path %q is a directory", p)
675 }
676 }
Colin Cross8a497952019-03-05 22:25:09 -0800677
Liz Kammer619be462022-01-28 15:13:39 -0500678 if InList(p.String(), input.expandedExcludes) {
679 return nil, nil
680 }
681 return Paths{p}, nil
Colin Cross8a497952019-03-05 22:25:09 -0800682 }
Colin Cross8a497952019-03-05 22:25:09 -0800683 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700684}
685
686// pathsForModuleSrcFromFullPath returns Paths rooted from the module's local
687// source directory, but strip the local source directory from the beginning of
Dan Willemsen540a78c2018-02-26 21:50:08 -0800688// each string. If incDirs is false, strip paths with a trailing '/' from the list.
Colin Crossfe4bc362018-09-12 10:02:13 -0700689// It intended for use in globs that only list files that exist, so it allows '$' in
690// filenames.
Liz Kammera830f3a2020-11-10 10:50:34 -0800691func pathsForModuleSrcFromFullPath(ctx EarlyModulePathContext, paths []string, incDirs bool) Paths {
Lukacs T. Berkif7e36d82021-08-16 17:05:09 +0200692 prefix := ctx.ModuleDir() + "/"
Colin Cross0f37af02017-09-27 17:42:05 -0700693 if prefix == "./" {
694 prefix = ""
695 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700696 ret := make(Paths, 0, len(paths))
697 for _, p := range paths {
Dan Willemsen540a78c2018-02-26 21:50:08 -0800698 if !incDirs && strings.HasSuffix(p, "/") {
699 continue
700 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700701 path := filepath.Clean(p)
702 if !strings.HasPrefix(path, prefix) {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +0100703 ReportPathErrorf(ctx, "Path %q is not in module source directory %q", p, prefix)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700704 continue
705 }
Colin Crosse3924e12018-08-15 20:18:53 -0700706
Colin Crossfe4bc362018-09-12 10:02:13 -0700707 srcPath, err := safePathForSource(ctx, ctx.ModuleDir(), path[len(prefix):])
Colin Crosse3924e12018-08-15 20:18:53 -0700708 if err != nil {
709 reportPathError(ctx, err)
710 continue
711 }
712
Colin Cross07e51612019-03-05 12:46:40 -0800713 srcPath.basePath.rel = srcPath.path
Colin Crosse3924e12018-08-15 20:18:53 -0700714
Colin Cross07e51612019-03-05 12:46:40 -0800715 ret = append(ret, srcPath)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700716 }
717 return ret
718}
719
Liz Kammera830f3a2020-11-10 10:50:34 -0800720// PathsWithOptionalDefaultForModuleSrc returns Paths rooted from the module's local source
721// directory. If input is nil, use the default if it exists. If input is empty, returns nil.
722func PathsWithOptionalDefaultForModuleSrc(ctx ModuleMissingDepsPathContext, input []string, def string) Paths {
Colin Cross0ddae7f2019-02-07 15:30:01 -0800723 if input != nil {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700724 return PathsForModuleSrc(ctx, input)
725 }
726 // Use Glob so that if the default doesn't exist, a dependency is added so that when it
727 // is created, we're run again.
Lukacs T. Berkif7e36d82021-08-16 17:05:09 +0200728 path := filepath.Join(ctx.ModuleDir(), def)
Liz Kammera830f3a2020-11-10 10:50:34 -0800729 return Glob(ctx, path, nil)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700730}
731
732// Strings returns the Paths in string form
733func (p Paths) Strings() []string {
734 if p == nil {
735 return nil
736 }
737 ret := make([]string, len(p))
738 for i, path := range p {
739 ret[i] = path.String()
740 }
741 return ret
742}
743
Colin Crossc0efd1d2020-07-03 11:56:24 -0700744func CopyOfPaths(paths Paths) Paths {
745 return append(Paths(nil), paths...)
746}
747
Colin Crossb6715442017-10-24 11:13:31 -0700748// FirstUniquePaths returns all unique elements of a Paths, keeping the first copy of each. It
749// modifies the Paths slice contents in place, and returns a subslice of the original slice.
Dan Willemsenfe92c962017-08-29 12:28:37 -0700750func FirstUniquePaths(list Paths) Paths {
Colin Cross27027c72020-02-28 15:34:17 -0800751 // 128 was chosen based on BenchmarkFirstUniquePaths results.
752 if len(list) > 128 {
753 return firstUniquePathsMap(list)
754 }
755 return firstUniquePathsList(list)
756}
757
Colin Crossc0efd1d2020-07-03 11:56:24 -0700758// SortedUniquePaths returns all unique elements of a Paths in sorted order. It modifies the
759// Paths slice contents in place, and returns a subslice of the original slice.
Jiyong Park33c77362020-05-29 22:00:16 +0900760func SortedUniquePaths(list Paths) Paths {
761 unique := FirstUniquePaths(list)
762 sort.Slice(unique, func(i, j int) bool {
763 return unique[i].String() < unique[j].String()
764 })
765 return unique
766}
767
Colin Cross27027c72020-02-28 15:34:17 -0800768func firstUniquePathsList(list Paths) Paths {
Dan Willemsenfe92c962017-08-29 12:28:37 -0700769 k := 0
770outer:
771 for i := 0; i < len(list); i++ {
772 for j := 0; j < k; j++ {
773 if list[i] == list[j] {
774 continue outer
775 }
776 }
777 list[k] = list[i]
778 k++
779 }
780 return list[:k]
781}
782
Colin Cross27027c72020-02-28 15:34:17 -0800783func firstUniquePathsMap(list Paths) Paths {
784 k := 0
785 seen := make(map[Path]bool, len(list))
786 for i := 0; i < len(list); i++ {
787 if seen[list[i]] {
788 continue
789 }
790 seen[list[i]] = true
791 list[k] = list[i]
792 k++
793 }
794 return list[:k]
795}
796
Colin Cross5d583952020-11-24 16:21:24 -0800797// FirstUniqueInstallPaths returns all unique elements of an InstallPaths, keeping the first copy of each. It
798// modifies the InstallPaths slice contents in place, and returns a subslice of the original slice.
799func FirstUniqueInstallPaths(list InstallPaths) InstallPaths {
800 // 128 was chosen based on BenchmarkFirstUniquePaths results.
801 if len(list) > 128 {
802 return firstUniqueInstallPathsMap(list)
803 }
804 return firstUniqueInstallPathsList(list)
805}
806
807func firstUniqueInstallPathsList(list InstallPaths) InstallPaths {
808 k := 0
809outer:
810 for i := 0; i < len(list); i++ {
811 for j := 0; j < k; j++ {
812 if list[i] == list[j] {
813 continue outer
814 }
815 }
816 list[k] = list[i]
817 k++
818 }
819 return list[:k]
820}
821
822func firstUniqueInstallPathsMap(list InstallPaths) InstallPaths {
823 k := 0
824 seen := make(map[InstallPath]bool, len(list))
825 for i := 0; i < len(list); i++ {
826 if seen[list[i]] {
827 continue
828 }
829 seen[list[i]] = true
830 list[k] = list[i]
831 k++
832 }
833 return list[:k]
834}
835
Colin Crossb6715442017-10-24 11:13:31 -0700836// LastUniquePaths returns all unique elements of a Paths, keeping the last copy of each. It
837// modifies the Paths slice contents in place, and returns a subslice of the original slice.
838func LastUniquePaths(list Paths) Paths {
839 totalSkip := 0
840 for i := len(list) - 1; i >= totalSkip; i-- {
841 skip := 0
842 for j := i - 1; j >= totalSkip; j-- {
843 if list[i] == list[j] {
844 skip++
845 } else {
846 list[j+skip] = list[j]
847 }
848 }
849 totalSkip += skip
850 }
851 return list[totalSkip:]
852}
853
Colin Crossa140bb02018-04-17 10:52:26 -0700854// ReversePaths returns a copy of a Paths in reverse order.
855func ReversePaths(list Paths) Paths {
856 if list == nil {
857 return nil
858 }
859 ret := make(Paths, len(list))
860 for i := range list {
861 ret[i] = list[len(list)-1-i]
862 }
863 return ret
864}
865
Jeff Gaston294356f2017-09-27 17:05:30 -0700866func indexPathList(s Path, list []Path) int {
867 for i, l := range list {
868 if l == s {
869 return i
870 }
871 }
872
873 return -1
874}
875
876func inPathList(p Path, list []Path) bool {
877 return indexPathList(p, list) != -1
878}
879
880func FilterPathList(list []Path, filter []Path) (remainder []Path, filtered []Path) {
Paul Duffin57b9e1d2019-12-13 00:03:35 +0000881 return FilterPathListPredicate(list, func(p Path) bool { return inPathList(p, filter) })
882}
883
884func FilterPathListPredicate(list []Path, predicate func(Path) bool) (remainder []Path, filtered []Path) {
Jeff Gaston294356f2017-09-27 17:05:30 -0700885 for _, l := range list {
Paul Duffin57b9e1d2019-12-13 00:03:35 +0000886 if predicate(l) {
Jeff Gaston294356f2017-09-27 17:05:30 -0700887 filtered = append(filtered, l)
888 } else {
889 remainder = append(remainder, l)
890 }
891 }
892
893 return
894}
895
Colin Cross93e85952017-08-15 13:34:18 -0700896// HasExt returns true of any of the paths have extension ext, otherwise false
897func (p Paths) HasExt(ext string) bool {
898 for _, path := range p {
899 if path.Ext() == ext {
900 return true
901 }
902 }
903
904 return false
905}
906
907// FilterByExt returns the subset of the paths that have extension ext
908func (p Paths) FilterByExt(ext string) Paths {
909 ret := make(Paths, 0, len(p))
910 for _, path := range p {
911 if path.Ext() == ext {
912 ret = append(ret, path)
913 }
914 }
915 return ret
916}
917
918// FilterOutByExt returns the subset of the paths that do not have extension ext
919func (p Paths) FilterOutByExt(ext string) Paths {
920 ret := make(Paths, 0, len(p))
921 for _, path := range p {
922 if path.Ext() != ext {
923 ret = append(ret, path)
924 }
925 }
926 return ret
927}
928
Colin Cross5e6cfbe2017-11-03 15:20:35 -0700929// DirectorySortedPaths is a slice of paths that are sorted such that all files in a directory
930// (including subdirectories) are in a contiguous subslice of the list, and can be found in
931// O(log(N)) time using a binary search on the directory prefix.
932type DirectorySortedPaths Paths
933
934func PathsToDirectorySortedPaths(paths Paths) DirectorySortedPaths {
935 ret := append(DirectorySortedPaths(nil), paths...)
936 sort.Slice(ret, func(i, j int) bool {
937 return ret[i].String() < ret[j].String()
938 })
939 return ret
940}
941
942// PathsInDirectory returns a subslice of the DirectorySortedPaths as a Paths that contains all entries
943// that are in the specified directory and its subdirectories.
944func (p DirectorySortedPaths) PathsInDirectory(dir string) Paths {
945 prefix := filepath.Clean(dir) + "/"
946 start := sort.Search(len(p), func(i int) bool {
947 return prefix < p[i].String()
948 })
949
950 ret := p[start:]
951
952 end := sort.Search(len(ret), func(i int) bool {
953 return !strings.HasPrefix(ret[i].String(), prefix)
954 })
955
956 ret = ret[:end]
957
958 return Paths(ret)
959}
960
Alex Humesky29e3bbe2020-11-20 21:30:13 -0500961// WritablePaths is a slice of WritablePath, used for multiple outputs.
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700962type WritablePaths []WritablePath
963
Paul Duffin85d8f0d2021-03-24 10:18:18 +0000964// RelativeToTop creates a new WritablePaths containing the result of calling Path.RelativeToTop on
965// each item in this slice.
966func (p WritablePaths) RelativeToTop() WritablePaths {
967 ensureTestOnly()
968 if p == nil {
969 return p
970 }
971 ret := make(WritablePaths, len(p))
972 for i, path := range p {
973 ret[i] = path.RelativeToTop().(WritablePath)
974 }
975 return ret
976}
977
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700978// Strings returns the string forms of the writable paths.
979func (p WritablePaths) Strings() []string {
980 if p == nil {
981 return nil
982 }
983 ret := make([]string, len(p))
984 for i, path := range p {
985 ret[i] = path.String()
986 }
987 return ret
988}
989
Colin Cross3bc7ffa2017-11-22 16:19:37 -0800990// Paths returns the WritablePaths as a Paths
991func (p WritablePaths) Paths() Paths {
992 if p == nil {
993 return nil
994 }
995 ret := make(Paths, len(p))
996 for i, path := range p {
997 ret[i] = path
998 }
999 return ret
1000}
1001
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001002type basePath struct {
Paul Duffin74abc5d2021-03-24 09:24:59 +00001003 path string
1004 rel string
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001005}
1006
1007func (p basePath) Ext() string {
1008 return filepath.Ext(p.path)
1009}
1010
Colin Cross4f6fc9c2016-10-26 10:05:25 -07001011func (p basePath) Base() string {
1012 return filepath.Base(p.path)
1013}
1014
Colin Crossfaeb7aa2017-02-01 14:12:44 -08001015func (p basePath) Rel() string {
1016 if p.rel != "" {
1017 return p.rel
1018 }
1019 return p.path
1020}
1021
Colin Cross0875c522017-11-28 17:34:01 -08001022func (p basePath) String() string {
1023 return p.path
1024}
1025
Colin Cross0db55682017-12-05 15:36:55 -08001026func (p basePath) withRel(rel string) basePath {
1027 p.path = filepath.Join(p.path, rel)
1028 p.rel = rel
1029 return p
1030}
1031
Cole Faustbc65a3f2023-08-01 16:38:55 +00001032func (p basePath) RelativeToTop() Path {
1033 ensureTestOnly()
1034 return p
1035}
1036
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001037// SourcePath is a Path representing a file path rooted from SrcDir
1038type SourcePath struct {
1039 basePath
1040}
1041
1042var _ Path = SourcePath{}
1043
Colin Cross0db55682017-12-05 15:36:55 -08001044func (p SourcePath) withRel(rel string) SourcePath {
1045 p.basePath = p.basePath.withRel(rel)
1046 return p
1047}
1048
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001049// safePathForSource is for paths that we expect are safe -- only for use by go
1050// code that is embedding ninja variables in paths
Colin Crossfe4bc362018-09-12 10:02:13 -07001051func safePathForSource(ctx PathContext, pathComponents ...string) (SourcePath, error) {
1052 p, err := validateSafePath(pathComponents...)
Cole Faust483d1f72023-01-09 14:35:27 -08001053 ret := SourcePath{basePath{p, ""}}
Colin Crossfe4bc362018-09-12 10:02:13 -07001054 if err != nil {
1055 return ret, err
1056 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001057
Colin Cross7b3dcc32019-01-24 13:14:39 -08001058 // absolute path already checked by validateSafePath
Inseob Kim5eb7ee92022-04-27 10:30:34 +09001059 // special-case api surface gen files for now
1060 if strings.HasPrefix(ret.String(), ctx.Config().soongOutDir) && !strings.Contains(ret.String(), ctx.Config().soongOutDir+"/.export") {
Mikhail Naganovab1f5182019-02-08 13:17:55 -08001061 return ret, fmt.Errorf("source path %q is in output", ret.String())
Colin Cross6e18ca42015-07-14 18:55:36 -07001062 }
1063
Colin Crossfe4bc362018-09-12 10:02:13 -07001064 return ret, err
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001065}
1066
Colin Cross192e97a2018-02-22 14:21:02 -08001067// pathForSource creates a SourcePath from pathComponents, but does not check that it exists.
1068func pathForSource(ctx PathContext, pathComponents ...string) (SourcePath, error) {
Colin Crossc48c1432018-02-23 07:09:01 +00001069 p, err := validatePath(pathComponents...)
Cole Faust483d1f72023-01-09 14:35:27 -08001070 ret := SourcePath{basePath{p, ""}}
Colin Cross94a32102018-02-22 14:21:02 -08001071 if err != nil {
Colin Cross192e97a2018-02-22 14:21:02 -08001072 return ret, err
Colin Cross94a32102018-02-22 14:21:02 -08001073 }
1074
Colin Cross7b3dcc32019-01-24 13:14:39 -08001075 // absolute path already checked by validatePath
Inseob Kim5eb7ee92022-04-27 10:30:34 +09001076 // special-case for now
1077 if strings.HasPrefix(ret.String(), ctx.Config().soongOutDir) && !strings.Contains(ret.String(), ctx.Config().soongOutDir+"/.export") {
Mikhail Naganovab1f5182019-02-08 13:17:55 -08001078 return ret, fmt.Errorf("source path %q is in output", ret.String())
Colin Crossc48c1432018-02-23 07:09:01 +00001079 }
1080
Colin Cross192e97a2018-02-22 14:21:02 -08001081 return ret, nil
1082}
1083
1084// existsWithDependencies returns true if the path exists, and adds appropriate dependencies to rerun if the
1085// path does not exist.
Colin Cross662d6142022-11-03 20:38:01 -07001086func existsWithDependencies(ctx PathGlobContext, path SourcePath) (exists bool, err error) {
Colin Cross192e97a2018-02-22 14:21:02 -08001087 var files []string
1088
Colin Cross662d6142022-11-03 20:38:01 -07001089 // Use glob to produce proper dependencies, even though we only want
1090 // a single file.
1091 files, err = ctx.GlobWithDeps(path.String(), nil)
Colin Cross192e97a2018-02-22 14:21:02 -08001092
1093 if err != nil {
1094 return false, fmt.Errorf("glob: %s", err.Error())
1095 }
1096
1097 return len(files) > 0, nil
1098}
1099
1100// PathForSource joins the provided path components and validates that the result
1101// neither escapes the source dir nor is in the out dir.
1102// On error, it will return a usable, but invalid SourcePath, and report a ModuleError.
1103func PathForSource(ctx PathContext, pathComponents ...string) SourcePath {
1104 path, err := pathForSource(ctx, pathComponents...)
1105 if err != nil {
1106 reportPathError(ctx, err)
1107 }
1108
Colin Crosse3924e12018-08-15 20:18:53 -07001109 if pathtools.IsGlob(path.String()) {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001110 ReportPathErrorf(ctx, "path may not contain a glob: %s", path.String())
Colin Crosse3924e12018-08-15 20:18:53 -07001111 }
1112
Liz Kammera830f3a2020-11-10 10:50:34 -08001113 if modCtx, ok := ctx.(ModuleMissingDepsPathContext); ok && ctx.Config().AllowMissingDependencies() {
Colin Cross662d6142022-11-03 20:38:01 -07001114 exists, err := existsWithDependencies(modCtx, path)
Colin Cross192e97a2018-02-22 14:21:02 -08001115 if err != nil {
1116 reportPathError(ctx, err)
1117 }
1118 if !exists {
1119 modCtx.AddMissingDependencies([]string{path.String()})
1120 }
Colin Cross988414c2020-01-11 01:11:46 +00001121 } else if exists, _, err := ctx.Config().fs.Exists(path.String()); err != nil {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001122 ReportPathErrorf(ctx, "%s: %s", path, err.Error())
Pedro Loureiro5d190cc2021-02-15 15:41:33 +00001123 } else if !exists && !ctx.Config().TestAllowNonExistentPaths {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001124 ReportPathErrorf(ctx, "source path %q does not exist", path)
Colin Cross192e97a2018-02-22 14:21:02 -08001125 }
1126 return path
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001127}
1128
Cole Faustbc65a3f2023-08-01 16:38:55 +00001129// PathForArbitraryOutput creates a path for the given components. Unlike PathForOutput,
1130// the path is relative to the root of the output folder, not the out/soong folder.
1131func PathForArbitraryOutput(ctx PathContext, pathComponents ...string) Path {
1132 p, err := validatePath(pathComponents...)
1133 if err != nil {
1134 reportPathError(ctx, err)
1135 }
1136 return basePath{path: filepath.Join(ctx.Config().OutDir(), p)}
1137}
1138
Spandan Dasc6c10fa2022-10-21 21:52:13 +00001139// MaybeExistentPathForSource joins the provided path components and validates that the result
1140// neither escapes the source dir nor is in the out dir.
1141// It does not validate whether the path exists.
1142func MaybeExistentPathForSource(ctx PathContext, pathComponents ...string) SourcePath {
1143 path, err := pathForSource(ctx, pathComponents...)
1144 if err != nil {
1145 reportPathError(ctx, err)
1146 }
1147
1148 if pathtools.IsGlob(path.String()) {
1149 ReportPathErrorf(ctx, "path may not contain a glob: %s", path.String())
1150 }
1151 return path
1152}
1153
Liz Kammer7aa52882021-02-11 09:16:14 -05001154// ExistentPathForSource returns an OptionalPath with the SourcePath, rooted from SrcDir, *not*
1155// rooted from the module's local source directory, if the path exists, or an empty OptionalPath if
1156// it doesn't exist. Dependencies are added so that the ninja file will be regenerated if the state
1157// of the path changes.
Colin Cross662d6142022-11-03 20:38:01 -07001158func ExistentPathForSource(ctx PathGlobContext, pathComponents ...string) OptionalPath {
Colin Cross192e97a2018-02-22 14:21:02 -08001159 path, err := pathForSource(ctx, pathComponents...)
Colin Cross1ccfcc32018-02-22 13:54:26 -08001160 if err != nil {
1161 reportPathError(ctx, err)
Martin Stjernholmc32dd1c2021-09-15 02:39:00 +01001162 // No need to put the error message into the returned path since it has been reported already.
Colin Cross1ccfcc32018-02-22 13:54:26 -08001163 return OptionalPath{}
1164 }
Colin Crossc48c1432018-02-23 07:09:01 +00001165
Colin Crosse3924e12018-08-15 20:18:53 -07001166 if pathtools.IsGlob(path.String()) {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001167 ReportPathErrorf(ctx, "path may not contain a glob: %s", path.String())
Colin Crosse3924e12018-08-15 20:18:53 -07001168 return OptionalPath{}
1169 }
1170
Colin Cross192e97a2018-02-22 14:21:02 -08001171 exists, err := existsWithDependencies(ctx, path)
Colin Crossc48c1432018-02-23 07:09:01 +00001172 if err != nil {
1173 reportPathError(ctx, err)
1174 return OptionalPath{}
1175 }
Colin Cross192e97a2018-02-22 14:21:02 -08001176 if !exists {
Martin Stjernholmc32dd1c2021-09-15 02:39:00 +01001177 return InvalidOptionalPath(path.String() + " does not exist")
Colin Crossc48c1432018-02-23 07:09:01 +00001178 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001179 return OptionalPathForPath(path)
1180}
1181
1182func (p SourcePath) String() string {
Cole Faust483d1f72023-01-09 14:35:27 -08001183 if p.path == "" {
1184 return "."
1185 }
1186 return p.path
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001187}
1188
1189// Join creates a new SourcePath with paths... joined with the current path. The
1190// provided paths... may not use '..' to escape from the current path.
1191func (p SourcePath) Join(ctx PathContext, paths ...string) SourcePath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001192 path, err := validatePath(paths...)
1193 if err != nil {
1194 reportPathError(ctx, err)
1195 }
Colin Cross0db55682017-12-05 15:36:55 -08001196 return p.withRel(path)
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001197}
1198
Colin Cross2fafa3e2019-03-05 12:39:51 -08001199// join is like Join but does less path validation.
1200func (p SourcePath) join(ctx PathContext, paths ...string) SourcePath {
1201 path, err := validateSafePath(paths...)
1202 if err != nil {
1203 reportPathError(ctx, err)
1204 }
1205 return p.withRel(path)
1206}
1207
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001208// OverlayPath returns the overlay for `path' if it exists. This assumes that the
1209// SourcePath is the path to a resource overlay directory.
Liz Kammera830f3a2020-11-10 10:50:34 -08001210func (p SourcePath) OverlayPath(ctx ModuleMissingDepsPathContext, path Path) OptionalPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001211 var relDir string
Colin Cross07e51612019-03-05 12:46:40 -08001212 if srcPath, ok := path.(SourcePath); ok {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001213 relDir = srcPath.path
1214 } else {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001215 ReportPathErrorf(ctx, "Cannot find relative path for %s(%s)", reflect.TypeOf(path).Name(), path)
Martin Stjernholmc32dd1c2021-09-15 02:39:00 +01001216 // No need to put the error message into the returned path since it has been reported already.
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001217 return OptionalPath{}
1218 }
Cole Faust483d1f72023-01-09 14:35:27 -08001219 dir := filepath.Join(p.path, relDir)
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001220 // Use Glob so that we are run again if the directory is added.
Colin Cross7f19f372016-11-01 11:10:25 -07001221 if pathtools.IsGlob(dir) {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001222 ReportPathErrorf(ctx, "Path may not contain a glob: %s", dir)
Dan Willemsen7b310ee2015-12-18 15:11:17 -08001223 }
Colin Cross461b4452018-02-23 09:22:42 -08001224 paths, err := ctx.GlobWithDeps(dir, nil)
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001225 if err != nil {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001226 ReportPathErrorf(ctx, "glob: %s", err.Error())
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001227 return OptionalPath{}
1228 }
1229 if len(paths) == 0 {
Martin Stjernholmc32dd1c2021-09-15 02:39:00 +01001230 return InvalidOptionalPath(dir + " does not exist")
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001231 }
Cole Faust483d1f72023-01-09 14:35:27 -08001232 return OptionalPathForPath(PathForSource(ctx, paths[0]))
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001233}
1234
Colin Cross70dda7e2019-10-01 22:05:35 -07001235// OutputPath is a Path representing an intermediates file path rooted from the build directory
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001236type OutputPath struct {
1237 basePath
Paul Duffind65c58b2021-03-24 09:22:07 +00001238
Lukacs T. Berkib078ade2021-08-31 10:42:08 +02001239 // The soong build directory, i.e. Config.SoongOutDir()
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02001240 soongOutDir string
Paul Duffind65c58b2021-03-24 09:22:07 +00001241
Colin Crossd63c9a72020-01-29 16:52:50 -08001242 fullPath string
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001243}
1244
Colin Cross702e0f82017-10-18 17:27:54 -07001245func (p OutputPath) withRel(rel string) OutputPath {
Colin Cross0db55682017-12-05 15:36:55 -08001246 p.basePath = p.basePath.withRel(rel)
Colin Crossd63c9a72020-01-29 16:52:50 -08001247 p.fullPath = filepath.Join(p.fullPath, rel)
Colin Cross702e0f82017-10-18 17:27:54 -07001248 return p
1249}
1250
Colin Cross3063b782018-08-15 11:19:12 -07001251func (p OutputPath) WithoutRel() OutputPath {
1252 p.basePath.rel = filepath.Base(p.basePath.path)
1253 return p
1254}
1255
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02001256func (p OutputPath) getSoongOutDir() string {
1257 return p.soongOutDir
Paul Duffin9b478b02019-12-10 13:41:51 +00001258}
1259
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001260func (p OutputPath) RelativeToTop() Path {
1261 return p.outputPathRelativeToTop()
1262}
1263
1264func (p OutputPath) outputPathRelativeToTop() OutputPath {
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02001265 p.fullPath = StringPathRelativeToTop(p.soongOutDir, p.fullPath)
1266 p.soongOutDir = OutSoongDir
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001267 return p
1268}
1269
Paul Duffin0267d492021-02-02 10:05:52 +00001270func (p OutputPath) objPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleObjPath {
1271 return PathForModuleObj(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
1272}
1273
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001274var _ Path = OutputPath{}
Paul Duffin9b478b02019-12-10 13:41:51 +00001275var _ WritablePath = OutputPath{}
Paul Duffin0267d492021-02-02 10:05:52 +00001276var _ objPathProvider = OutputPath{}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001277
Chris Parsons8f232a22020-06-23 17:37:05 -04001278// toolDepPath is a Path representing a dependency of the build tool.
1279type toolDepPath struct {
1280 basePath
1281}
1282
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001283func (t toolDepPath) RelativeToTop() Path {
1284 ensureTestOnly()
1285 return t
1286}
1287
Chris Parsons8f232a22020-06-23 17:37:05 -04001288var _ Path = toolDepPath{}
1289
1290// pathForBuildToolDep returns a toolDepPath representing the given path string.
1291// There is no validation for the path, as it is "trusted": It may fail
1292// normal validation checks. For example, it may be an absolute path.
1293// Only use this function to construct paths for dependencies of the build
1294// tool invocation.
1295func pathForBuildToolDep(ctx PathContext, path string) toolDepPath {
Paul Duffin74abc5d2021-03-24 09:24:59 +00001296 return toolDepPath{basePath{path, ""}}
Chris Parsons8f232a22020-06-23 17:37:05 -04001297}
1298
Jeff Gaston734e3802017-04-10 15:47:24 -07001299// PathForOutput joins the provided paths and returns an OutputPath that is
1300// validated to not escape the build dir.
1301// On error, it will return a usable, but invalid OutputPath, and report a ModuleError.
1302func PathForOutput(ctx PathContext, pathComponents ...string) OutputPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001303 path, err := validatePath(pathComponents...)
1304 if err != nil {
1305 reportPathError(ctx, err)
1306 }
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02001307 fullPath := filepath.Join(ctx.Config().soongOutDir, path)
Colin Crossd63c9a72020-01-29 16:52:50 -08001308 path = fullPath[len(fullPath)-len(path):]
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02001309 return OutputPath{basePath{path, ""}, ctx.Config().soongOutDir, fullPath}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001310}
1311
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02001312// PathsForOutput returns Paths rooted from soongOutDir
Colin Cross40e33732019-02-15 11:08:35 -08001313func PathsForOutput(ctx PathContext, paths []string) WritablePaths {
1314 ret := make(WritablePaths, len(paths))
1315 for i, path := range paths {
1316 ret[i] = PathForOutput(ctx, path)
1317 }
1318 return ret
1319}
1320
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001321func (p OutputPath) writablePath() {}
1322
1323func (p OutputPath) String() string {
Colin Crossd63c9a72020-01-29 16:52:50 -08001324 return p.fullPath
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001325}
1326
1327// Join creates a new OutputPath with paths... joined with the current path. The
1328// provided paths... may not use '..' to escape from the current path.
1329func (p OutputPath) Join(ctx PathContext, paths ...string) OutputPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001330 path, err := validatePath(paths...)
1331 if err != nil {
1332 reportPathError(ctx, err)
1333 }
Colin Cross0db55682017-12-05 15:36:55 -08001334 return p.withRel(path)
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001335}
1336
Colin Cross8854a5a2019-02-11 14:14:16 -08001337// ReplaceExtension creates a new OutputPath with the extension replaced with ext.
1338func (p OutputPath) ReplaceExtension(ctx PathContext, ext string) OutputPath {
1339 if strings.Contains(ext, "/") {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001340 ReportPathErrorf(ctx, "extension %q cannot contain /", ext)
Colin Cross8854a5a2019-02-11 14:14:16 -08001341 }
1342 ret := PathForOutput(ctx, pathtools.ReplaceExtension(p.path, ext))
Colin Cross2cdd5df2019-02-25 10:25:24 -08001343 ret.rel = pathtools.ReplaceExtension(p.rel, ext)
Colin Cross8854a5a2019-02-11 14:14:16 -08001344 return ret
1345}
1346
Colin Cross40e33732019-02-15 11:08:35 -08001347// InSameDir creates a new OutputPath from the directory of the current OutputPath joined with the elements in paths.
1348func (p OutputPath) InSameDir(ctx PathContext, paths ...string) OutputPath {
1349 path, err := validatePath(paths...)
1350 if err != nil {
1351 reportPathError(ctx, err)
1352 }
1353
1354 ret := PathForOutput(ctx, filepath.Dir(p.path), path)
Colin Cross2cdd5df2019-02-25 10:25:24 -08001355 ret.rel = filepath.Join(filepath.Dir(p.rel), path)
Colin Cross40e33732019-02-15 11:08:35 -08001356 return ret
1357}
1358
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001359// PathForIntermediates returns an OutputPath representing the top-level
1360// intermediates directory.
1361func PathForIntermediates(ctx PathContext, paths ...string) OutputPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001362 path, err := validatePath(paths...)
1363 if err != nil {
1364 reportPathError(ctx, err)
1365 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001366 return PathForOutput(ctx, ".intermediates", path)
1367}
1368
Colin Cross07e51612019-03-05 12:46:40 -08001369var _ genPathProvider = SourcePath{}
1370var _ objPathProvider = SourcePath{}
1371var _ resPathProvider = SourcePath{}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001372
Colin Cross07e51612019-03-05 12:46:40 -08001373// PathForModuleSrc returns a Path representing the paths... under the
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001374// module's local source directory.
Liz Kammera830f3a2020-11-10 10:50:34 -08001375func PathForModuleSrc(ctx ModuleMissingDepsPathContext, pathComponents ...string) Path {
Paul Duffin407501b2021-07-09 16:56:35 +01001376 // Just join the components textually just to make sure that it does not corrupt a fully qualified
1377 // module reference, e.g. if the pathComponents is "://other:foo" then using filepath.Join() or
1378 // validatePath() will corrupt it, e.g. replace "//" with "/". If the path is not a module
1379 // reference then it will be validated by expandOneSrcPath anyway when it calls expandOneSrcPath.
1380 p := strings.Join(pathComponents, string(filepath.Separator))
Liz Kammer619be462022-01-28 15:13:39 -05001381 paths, err := expandOneSrcPath(sourcePathInput{context: ctx, path: p, includeDirs: true})
Colin Cross8a497952019-03-05 22:25:09 -08001382 if err != nil {
1383 if depErr, ok := err.(missingDependencyError); ok {
1384 if ctx.Config().AllowMissingDependencies() {
1385 ctx.AddMissingDependencies(depErr.missingDeps)
1386 } else {
1387 ctx.ModuleErrorf(`%s, is the property annotated with android:"path"?`, depErr.Error())
1388 }
1389 } else {
1390 reportPathError(ctx, err)
1391 }
1392 return nil
1393 } else if len(paths) == 0 {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001394 ReportPathErrorf(ctx, "%q produced no files, expected exactly one", p)
Colin Cross8a497952019-03-05 22:25:09 -08001395 return nil
1396 } else if len(paths) > 1 {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001397 ReportPathErrorf(ctx, "%q produced %d files, expected exactly one", p, len(paths))
Colin Cross8a497952019-03-05 22:25:09 -08001398 }
1399 return paths[0]
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001400}
1401
Liz Kammera830f3a2020-11-10 10:50:34 -08001402func pathForModuleSrc(ctx EarlyModulePathContext, paths ...string) SourcePath {
Colin Cross07e51612019-03-05 12:46:40 -08001403 p, err := validatePath(paths...)
1404 if err != nil {
1405 reportPathError(ctx, err)
1406 }
1407
1408 path, err := pathForSource(ctx, ctx.ModuleDir(), p)
1409 if err != nil {
1410 reportPathError(ctx, err)
1411 }
1412
1413 path.basePath.rel = p
1414
1415 return path
1416}
1417
Colin Cross2fafa3e2019-03-05 12:39:51 -08001418// PathsWithModuleSrcSubDir takes a list of Paths and returns a new list of Paths where Rel() on each path
1419// will return the path relative to subDir in the module's source directory. If any input paths are not located
1420// inside subDir then a path error will be reported.
Liz Kammera830f3a2020-11-10 10:50:34 -08001421func PathsWithModuleSrcSubDir(ctx EarlyModulePathContext, paths Paths, subDir string) Paths {
Colin Cross2fafa3e2019-03-05 12:39:51 -08001422 paths = append(Paths(nil), paths...)
Colin Cross07e51612019-03-05 12:46:40 -08001423 subDirFullPath := pathForModuleSrc(ctx, subDir)
Colin Cross2fafa3e2019-03-05 12:39:51 -08001424 for i, path := range paths {
1425 rel := Rel(ctx, subDirFullPath.String(), path.String())
1426 paths[i] = subDirFullPath.join(ctx, rel)
1427 }
1428 return paths
1429}
1430
1431// PathWithModuleSrcSubDir takes a Path and returns a Path where Rel() will return the path relative to subDir in the
1432// 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 -08001433func PathWithModuleSrcSubDir(ctx EarlyModulePathContext, path Path, subDir string) Path {
Colin Cross07e51612019-03-05 12:46:40 -08001434 subDirFullPath := pathForModuleSrc(ctx, subDir)
Colin Cross2fafa3e2019-03-05 12:39:51 -08001435 rel := Rel(ctx, subDirFullPath.String(), path.String())
1436 return subDirFullPath.Join(ctx, rel)
1437}
1438
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001439// OptionalPathForModuleSrc returns an OptionalPath. The OptionalPath contains a
1440// valid path if p is non-nil.
Liz Kammera830f3a2020-11-10 10:50:34 -08001441func OptionalPathForModuleSrc(ctx ModuleMissingDepsPathContext, p *string) OptionalPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001442 if p == nil {
1443 return OptionalPath{}
1444 }
1445 return OptionalPathForPath(PathForModuleSrc(ctx, *p))
1446}
1447
Liz Kammera830f3a2020-11-10 10:50:34 -08001448func (p SourcePath) genPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleGenPath {
Colin Cross7fc17db2017-02-01 14:07:55 -08001449 return PathForModuleGen(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001450}
1451
Liz Kammera830f3a2020-11-10 10:50:34 -08001452func (p SourcePath) objPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleObjPath {
Colin Cross7fc17db2017-02-01 14:07:55 -08001453 return PathForModuleObj(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001454}
1455
Liz Kammera830f3a2020-11-10 10:50:34 -08001456func (p SourcePath) resPathWithName(ctx ModuleOutPathContext, name string) ModuleResPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001457 // TODO: Use full directory if the new ctx is not the current ctx?
1458 return PathForModuleRes(ctx, p.path, name)
1459}
1460
1461// ModuleOutPath is a Path representing a module's output directory.
1462type ModuleOutPath struct {
1463 OutputPath
1464}
1465
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001466func (p ModuleOutPath) RelativeToTop() Path {
1467 p.OutputPath = p.outputPathRelativeToTop()
1468 return p
1469}
1470
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001471var _ Path = ModuleOutPath{}
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001472var _ WritablePath = ModuleOutPath{}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001473
Liz Kammera830f3a2020-11-10 10:50:34 -08001474func (p ModuleOutPath) objPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleObjPath {
Pete Bentleyfcf55bf2019-08-16 20:14:32 +01001475 return PathForModuleObj(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
1476}
1477
Liz Kammera830f3a2020-11-10 10:50:34 -08001478// ModuleOutPathContext Subset of ModuleContext functions necessary for output path methods.
1479type ModuleOutPathContext interface {
1480 PathContext
1481
1482 ModuleName() string
1483 ModuleDir() string
1484 ModuleSubDir() string
Inseob Kim8ff69de2023-06-16 14:19:33 +09001485 SoongConfigTraceHash() string
Liz Kammera830f3a2020-11-10 10:50:34 -08001486}
1487
1488func pathForModuleOut(ctx ModuleOutPathContext) OutputPath {
Inseob Kim8ff69de2023-06-16 14:19:33 +09001489 return PathForOutput(ctx, ".intermediates", ctx.ModuleDir(), ctx.ModuleName(), ctx.ModuleSubDir(), ctx.SoongConfigTraceHash())
Colin Cross702e0f82017-10-18 17:27:54 -07001490}
1491
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001492// PathForModuleOut returns a Path representing the paths... under the module's
1493// output directory.
Liz Kammera830f3a2020-11-10 10:50:34 -08001494func PathForModuleOut(ctx ModuleOutPathContext, paths ...string) ModuleOutPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001495 p, err := validatePath(paths...)
1496 if err != nil {
1497 reportPathError(ctx, err)
1498 }
Colin Cross702e0f82017-10-18 17:27:54 -07001499 return ModuleOutPath{
Liz Kammera830f3a2020-11-10 10:50:34 -08001500 OutputPath: pathForModuleOut(ctx).withRel(p),
Colin Cross702e0f82017-10-18 17:27:54 -07001501 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001502}
1503
1504// ModuleGenPath is a Path representing the 'gen' directory in a module's output
1505// directory. Mainly used for generated sources.
1506type ModuleGenPath struct {
1507 ModuleOutPath
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001508}
1509
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001510func (p ModuleGenPath) RelativeToTop() Path {
1511 p.OutputPath = p.outputPathRelativeToTop()
1512 return p
1513}
1514
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001515var _ Path = ModuleGenPath{}
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001516var _ WritablePath = ModuleGenPath{}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001517var _ genPathProvider = ModuleGenPath{}
1518var _ objPathProvider = ModuleGenPath{}
1519
1520// PathForModuleGen returns a Path representing the paths... under the module's
1521// `gen' directory.
Liz Kammera830f3a2020-11-10 10:50:34 -08001522func PathForModuleGen(ctx ModuleOutPathContext, paths ...string) ModuleGenPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001523 p, err := validatePath(paths...)
1524 if err != nil {
1525 reportPathError(ctx, err)
1526 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001527 return ModuleGenPath{
Colin Cross702e0f82017-10-18 17:27:54 -07001528 ModuleOutPath: ModuleOutPath{
Liz Kammera830f3a2020-11-10 10:50:34 -08001529 OutputPath: pathForModuleOut(ctx).withRel("gen").withRel(p),
Colin Cross702e0f82017-10-18 17:27:54 -07001530 },
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001531 }
1532}
1533
Liz Kammera830f3a2020-11-10 10:50:34 -08001534func (p ModuleGenPath) genPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleGenPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001535 // TODO: make a different path for local vs remote generated files?
Dan Willemsen21ec4902016-11-02 20:43:13 -07001536 return PathForModuleGen(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001537}
1538
Liz Kammera830f3a2020-11-10 10:50:34 -08001539func (p ModuleGenPath) objPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleObjPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001540 return PathForModuleObj(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
1541}
1542
1543// ModuleObjPath is a Path representing the 'obj' directory in a module's output
1544// directory. Used for compiled objects.
1545type ModuleObjPath struct {
1546 ModuleOutPath
1547}
1548
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001549func (p ModuleObjPath) RelativeToTop() Path {
1550 p.OutputPath = p.outputPathRelativeToTop()
1551 return p
1552}
1553
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001554var _ Path = ModuleObjPath{}
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001555var _ WritablePath = ModuleObjPath{}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001556
1557// PathForModuleObj returns a Path representing the paths... under the module's
1558// 'obj' directory.
Liz Kammera830f3a2020-11-10 10:50:34 -08001559func PathForModuleObj(ctx ModuleOutPathContext, pathComponents ...string) ModuleObjPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001560 p, err := validatePath(pathComponents...)
1561 if err != nil {
1562 reportPathError(ctx, err)
1563 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001564 return ModuleObjPath{PathForModuleOut(ctx, "obj", p)}
1565}
1566
1567// ModuleResPath is a a Path representing the 'res' directory in a module's
1568// output directory.
1569type ModuleResPath struct {
1570 ModuleOutPath
1571}
1572
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001573func (p ModuleResPath) RelativeToTop() Path {
1574 p.OutputPath = p.outputPathRelativeToTop()
1575 return p
1576}
1577
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001578var _ Path = ModuleResPath{}
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001579var _ WritablePath = ModuleResPath{}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001580
1581// PathForModuleRes returns a Path representing the paths... under the module's
1582// 'res' directory.
Liz Kammera830f3a2020-11-10 10:50:34 -08001583func PathForModuleRes(ctx ModuleOutPathContext, pathComponents ...string) ModuleResPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001584 p, err := validatePath(pathComponents...)
1585 if err != nil {
1586 reportPathError(ctx, err)
1587 }
1588
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001589 return ModuleResPath{PathForModuleOut(ctx, "res", p)}
1590}
1591
Colin Cross70dda7e2019-10-01 22:05:35 -07001592// InstallPath is a Path representing a installed file path rooted from the build directory
1593type InstallPath struct {
1594 basePath
Colin Crossff6c33d2019-10-02 16:01:35 -07001595
Lukacs T. Berkib078ade2021-08-31 10:42:08 +02001596 // The soong build directory, i.e. Config.SoongOutDir()
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02001597 soongOutDir string
Paul Duffind65c58b2021-03-24 09:22:07 +00001598
Jiyong Park957bcd92020-10-20 18:23:33 +09001599 // partitionDir is the part of the InstallPath that is automatically determined according to the context.
1600 // For example, it is host/<os>-<arch> for host modules, and target/product/<device>/<partition> for device modules.
1601 partitionDir string
1602
Colin Crossb1692a32021-10-25 15:39:01 -07001603 partition string
1604
Jiyong Park957bcd92020-10-20 18:23:33 +09001605 // makePath indicates whether this path is for Soong (false) or Make (true).
1606 makePath bool
Colin Cross70dda7e2019-10-01 22:05:35 -07001607}
1608
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001609// Will panic if called from outside a test environment.
1610func ensureTestOnly() {
Martin Stjernholm32312eb2021-03-27 18:54:49 +00001611 if PrefixInList(os.Args, "-test.") {
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001612 return
1613 }
Martin Stjernholm32312eb2021-03-27 18:54:49 +00001614 panic(fmt.Errorf("Not in test. Command line:\n %s", strings.Join(os.Args, "\n ")))
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001615}
1616
1617func (p InstallPath) RelativeToTop() Path {
1618 ensureTestOnly()
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02001619 p.soongOutDir = OutSoongDir
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001620 return p
1621}
1622
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02001623func (p InstallPath) getSoongOutDir() string {
1624 return p.soongOutDir
Paul Duffin9b478b02019-12-10 13:41:51 +00001625}
1626
Hans MÃ¥nssond3f2bd72020-11-27 12:37:28 +01001627func (p InstallPath) ReplaceExtension(ctx PathContext, ext string) OutputPath {
1628 panic("Not implemented")
1629}
1630
Paul Duffin9b478b02019-12-10 13:41:51 +00001631var _ Path = InstallPath{}
1632var _ WritablePath = InstallPath{}
1633
Colin Cross70dda7e2019-10-01 22:05:35 -07001634func (p InstallPath) writablePath() {}
1635
1636func (p InstallPath) String() string {
Jiyong Park957bcd92020-10-20 18:23:33 +09001637 if p.makePath {
1638 // Make path starts with out/ instead of out/soong.
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02001639 return filepath.Join(p.soongOutDir, "../", p.path)
Jiyong Park957bcd92020-10-20 18:23:33 +09001640 } else {
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02001641 return filepath.Join(p.soongOutDir, p.path)
Jiyong Park957bcd92020-10-20 18:23:33 +09001642 }
1643}
1644
1645// PartitionDir returns the path to the partition where the install path is rooted at. It is
1646// out/soong/target/product/<device>/<partition> for device modules, and out/soong/host/<os>-<arch> for host modules.
1647// The ./soong is dropped if the install path is for Make.
1648func (p InstallPath) PartitionDir() string {
1649 if p.makePath {
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02001650 return filepath.Join(p.soongOutDir, "../", p.partitionDir)
Jiyong Park957bcd92020-10-20 18:23:33 +09001651 } else {
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02001652 return filepath.Join(p.soongOutDir, p.partitionDir)
Jiyong Park957bcd92020-10-20 18:23:33 +09001653 }
Colin Cross70dda7e2019-10-01 22:05:35 -07001654}
1655
Jihoon Kangf78a8902022-09-01 22:47:07 +00001656func (p InstallPath) Partition() string {
1657 return p.partition
1658}
1659
Colin Cross70dda7e2019-10-01 22:05:35 -07001660// Join creates a new InstallPath with paths... joined with the current path. The
1661// provided paths... may not use '..' to escape from the current path.
1662func (p InstallPath) Join(ctx PathContext, paths ...string) InstallPath {
1663 path, err := validatePath(paths...)
1664 if err != nil {
1665 reportPathError(ctx, err)
1666 }
1667 return p.withRel(path)
1668}
1669
1670func (p InstallPath) withRel(rel string) InstallPath {
1671 p.basePath = p.basePath.withRel(rel)
1672 return p
1673}
1674
Colin Crossc68db4b2021-11-11 18:59:15 -08001675// Deprecated: ToMakePath is a noop, PathForModuleInstall always returns Make paths when building
1676// embedded in Make.
Colin Crossff6c33d2019-10-02 16:01:35 -07001677func (p InstallPath) ToMakePath() InstallPath {
Jiyong Park957bcd92020-10-20 18:23:33 +09001678 p.makePath = true
Colin Crossff6c33d2019-10-02 16:01:35 -07001679 return p
Colin Cross70dda7e2019-10-01 22:05:35 -07001680}
1681
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001682// PathForModuleInstall returns a Path representing the install path for the
1683// module appended with paths...
Colin Cross70dda7e2019-10-01 22:05:35 -07001684func PathForModuleInstall(ctx ModuleInstallPathContext, pathComponents ...string) InstallPath {
Spandan Das5d1b9292021-06-03 19:36:41 +00001685 os, arch := osAndArch(ctx)
1686 partition := modulePartition(ctx, os)
Cole Faust3b703f32023-10-16 13:30:51 -07001687 return pathForInstall(ctx, os, arch, partition, pathComponents...)
Spandan Das5d1b9292021-06-03 19:36:41 +00001688}
1689
Colin Cross1d0eb7a2021-11-03 14:08:20 -07001690// PathForHostDexInstall returns an InstallPath representing the install path for the
1691// module appended with paths...
1692func PathForHostDexInstall(ctx ModuleInstallPathContext, pathComponents ...string) InstallPath {
Cole Faust3b703f32023-10-16 13:30:51 -07001693 return pathForInstall(ctx, ctx.Config().BuildOS, ctx.Config().BuildArch, "", pathComponents...)
Colin Cross1d0eb7a2021-11-03 14:08:20 -07001694}
1695
Spandan Das5d1b9292021-06-03 19:36:41 +00001696// PathForModuleInPartitionInstall is similar to PathForModuleInstall but partition is provided by the caller
1697func PathForModuleInPartitionInstall(ctx ModuleInstallPathContext, partition string, pathComponents ...string) InstallPath {
1698 os, arch := osAndArch(ctx)
Cole Faust3b703f32023-10-16 13:30:51 -07001699 return pathForInstall(ctx, os, arch, partition, pathComponents...)
Spandan Das5d1b9292021-06-03 19:36:41 +00001700}
1701
1702func osAndArch(ctx ModuleInstallPathContext) (OsType, ArchType) {
Colin Cross6e359402020-02-10 15:29:54 -08001703 os := ctx.Os()
Jiyong Park87788b52020-09-01 12:37:45 +09001704 arch := ctx.Arch().ArchType
1705 forceOS, forceArch := ctx.InstallForceOS()
1706 if forceOS != nil {
Colin Cross6e359402020-02-10 15:29:54 -08001707 os = *forceOS
1708 }
Jiyong Park87788b52020-09-01 12:37:45 +09001709 if forceArch != nil {
1710 arch = *forceArch
1711 }
Spandan Das5d1b9292021-06-03 19:36:41 +00001712 return os, arch
1713}
Colin Cross609c49a2020-02-13 13:20:11 -08001714
Cole Faust3b703f32023-10-16 13:30:51 -07001715func pathForInstall(ctx PathContext, os OsType, arch ArchType, partition string,
Colin Cross609c49a2020-02-13 13:20:11 -08001716 pathComponents ...string) InstallPath {
1717
Jiyong Park97859152023-02-14 17:05:48 +09001718 var partitionPaths []string
Colin Cross609c49a2020-02-13 13:20:11 -08001719
Colin Cross6e359402020-02-10 15:29:54 -08001720 if os.Class == Device {
Jiyong Park97859152023-02-14 17:05:48 +09001721 partitionPaths = []string{"target", "product", ctx.Config().DeviceName(), partition}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001722 } else {
Jiyong Park87788b52020-09-01 12:37:45 +09001723 osName := os.String()
Colin Crossa9b2aac2022-06-15 17:25:51 -07001724 if os == Linux {
Jiyong Park87788b52020-09-01 12:37:45 +09001725 // instead of linux_glibc
1726 osName = "linux"
Dan Willemsen866b5632017-09-22 12:28:24 -07001727 }
Colin Crossa9b2aac2022-06-15 17:25:51 -07001728 if os == LinuxMusl && ctx.Config().UseHostMusl() {
1729 // When using musl instead of glibc, use "linux" instead of "linux_musl". When cross
1730 // compiling we will still use "linux_musl".
1731 osName = "linux"
1732 }
1733
Jiyong Park87788b52020-09-01 12:37:45 +09001734 // SOONG_HOST_OUT is set to out/host/$(HOST_OS)-$(HOST_PREBUILT_ARCH)
1735 // and HOST_PREBUILT_ARCH is forcibly set to x86 even on x86_64 hosts. We don't seem
1736 // to have a plan to fix it (see the comment in build/make/core/envsetup.mk).
1737 // Let's keep using x86 for the existing cases until we have a need to support
1738 // other architectures.
1739 archName := arch.String()
1740 if os.Class == Host && (arch == X86_64 || arch == Common) {
1741 archName = "x86"
1742 }
Jiyong Park97859152023-02-14 17:05:48 +09001743 partitionPaths = []string{"host", osName + "-" + archName, partition}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001744 }
Colin Cross70dda7e2019-10-01 22:05:35 -07001745
Jiyong Park97859152023-02-14 17:05:48 +09001746 partitionPath, err := validatePath(partitionPaths...)
Colin Cross70dda7e2019-10-01 22:05:35 -07001747 if err != nil {
1748 reportPathError(ctx, err)
1749 }
Colin Crossff6c33d2019-10-02 16:01:35 -07001750
Jiyong Park957bcd92020-10-20 18:23:33 +09001751 base := InstallPath{
Jiyong Park97859152023-02-14 17:05:48 +09001752 basePath: basePath{partitionPath, ""},
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02001753 soongOutDir: ctx.Config().soongOutDir,
Jiyong Park97859152023-02-14 17:05:48 +09001754 partitionDir: partitionPath,
Colin Crossb1692a32021-10-25 15:39:01 -07001755 partition: partition,
Colin Crossc68db4b2021-11-11 18:59:15 -08001756 }
1757
1758 if ctx.Config().KatiEnabled() {
1759 base.makePath = true
Jiyong Park957bcd92020-10-20 18:23:33 +09001760 }
Colin Crossff6c33d2019-10-02 16:01:35 -07001761
Jiyong Park957bcd92020-10-20 18:23:33 +09001762 return base.Join(ctx, pathComponents...)
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001763}
1764
Nicolas Geoffray1228e9c2020-02-27 13:45:35 +00001765func pathForNdkOrSdkInstall(ctx PathContext, prefix string, paths []string) InstallPath {
Jiyong Park957bcd92020-10-20 18:23:33 +09001766 base := InstallPath{
Paul Duffin74abc5d2021-03-24 09:24:59 +00001767 basePath: basePath{prefix, ""},
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02001768 soongOutDir: ctx.Config().soongOutDir,
Jiyong Park957bcd92020-10-20 18:23:33 +09001769 partitionDir: prefix,
1770 makePath: false,
Colin Cross70dda7e2019-10-01 22:05:35 -07001771 }
Jiyong Park957bcd92020-10-20 18:23:33 +09001772 return base.Join(ctx, paths...)
Colin Cross70dda7e2019-10-01 22:05:35 -07001773}
1774
Nicolas Geoffray1228e9c2020-02-27 13:45:35 +00001775func PathForNdkInstall(ctx PathContext, paths ...string) InstallPath {
1776 return pathForNdkOrSdkInstall(ctx, "ndk", paths)
1777}
1778
1779func PathForMainlineSdksInstall(ctx PathContext, paths ...string) InstallPath {
1780 return pathForNdkOrSdkInstall(ctx, "mainline-sdks", paths)
1781}
1782
Colin Cross70dda7e2019-10-01 22:05:35 -07001783func InstallPathToOnDevicePath(ctx PathContext, path InstallPath) string {
Colin Crossb1692a32021-10-25 15:39:01 -07001784 rel := Rel(ctx, strings.TrimSuffix(path.PartitionDir(), path.partition), path.String())
Colin Cross43f08db2018-11-12 10:13:39 -08001785 return "/" + rel
1786}
1787
Colin Cross6e359402020-02-10 15:29:54 -08001788func modulePartition(ctx ModuleInstallPathContext, os OsType) string {
Colin Cross43f08db2018-11-12 10:13:39 -08001789 var partition string
Colin Cross6e359402020-02-10 15:29:54 -08001790 if ctx.InstallInTestcases() {
1791 // "testcases" install directory can be used for host or device modules.
Jaewoong Jung0949f312019-09-11 10:25:18 -07001792 partition = "testcases"
Colin Cross6e359402020-02-10 15:29:54 -08001793 } else if os.Class == Device {
1794 if ctx.InstallInData() {
1795 partition = "data"
1796 } else if ctx.InstallInRamdisk() {
1797 if ctx.DeviceConfig().BoardUsesRecoveryAsBoot() {
1798 partition = "recovery/root/first_stage_ramdisk"
1799 } else {
1800 partition = "ramdisk"
1801 }
1802 if !ctx.InstallInRoot() {
1803 partition += "/system"
1804 }
Yifan Hong60e0cfb2020-10-21 15:17:56 -07001805 } else if ctx.InstallInVendorRamdisk() {
Yifan Hong39143a92020-10-26 12:43:12 -07001806 // The module is only available after switching root into
1807 // /first_stage_ramdisk. To expose the module before switching root
1808 // on a device without a dedicated recovery partition, install the
1809 // recovery variant.
Yifan Hongdd8dacc2020-10-21 15:40:17 -07001810 if ctx.DeviceConfig().BoardMoveRecoveryResourcesToVendorBoot() {
Petri Gyntherac229562021-03-02 23:44:02 -08001811 partition = "vendor_ramdisk/first_stage_ramdisk"
Yifan Hongdd8dacc2020-10-21 15:40:17 -07001812 } else {
Petri Gyntherac229562021-03-02 23:44:02 -08001813 partition = "vendor_ramdisk"
Yifan Hongdd8dacc2020-10-21 15:40:17 -07001814 }
1815 if !ctx.InstallInRoot() {
1816 partition += "/system"
1817 }
Inseob Kim08758f02021-04-08 21:13:22 +09001818 } else if ctx.InstallInDebugRamdisk() {
1819 partition = "debug_ramdisk"
Colin Cross6e359402020-02-10 15:29:54 -08001820 } else if ctx.InstallInRecovery() {
1821 if ctx.InstallInRoot() {
1822 partition = "recovery/root"
1823 } else {
1824 // the layout of recovery partion is the same as that of system partition
1825 partition = "recovery/root/system"
1826 }
1827 } else if ctx.SocSpecific() {
1828 partition = ctx.DeviceConfig().VendorPath()
1829 } else if ctx.DeviceSpecific() {
1830 partition = ctx.DeviceConfig().OdmPath()
1831 } else if ctx.ProductSpecific() {
1832 partition = ctx.DeviceConfig().ProductPath()
1833 } else if ctx.SystemExtSpecific() {
1834 partition = ctx.DeviceConfig().SystemExtPath()
1835 } else if ctx.InstallInRoot() {
1836 partition = "root"
Yifan Hong82db7352020-01-21 16:12:26 -08001837 } else {
Colin Cross6e359402020-02-10 15:29:54 -08001838 partition = "system"
Yifan Hong82db7352020-01-21 16:12:26 -08001839 }
Colin Cross6e359402020-02-10 15:29:54 -08001840 if ctx.InstallInSanitizerDir() {
1841 partition = "data/asan/" + partition
Yifan Hong82db7352020-01-21 16:12:26 -08001842 }
Colin Cross43f08db2018-11-12 10:13:39 -08001843 }
1844 return partition
1845}
1846
Colin Cross609c49a2020-02-13 13:20:11 -08001847type InstallPaths []InstallPath
1848
1849// Paths returns the InstallPaths as a Paths
1850func (p InstallPaths) Paths() Paths {
1851 if p == nil {
1852 return nil
1853 }
1854 ret := make(Paths, len(p))
1855 for i, path := range p {
1856 ret[i] = path
1857 }
1858 return ret
1859}
1860
1861// Strings returns the string forms of the install paths.
1862func (p InstallPaths) Strings() []string {
1863 if p == nil {
1864 return nil
1865 }
1866 ret := make([]string, len(p))
1867 for i, path := range p {
1868 ret[i] = path.String()
1869 }
1870 return ret
1871}
1872
Jingwen Chen24d0c562023-02-07 09:29:36 +00001873// validatePathInternal ensures that a path does not leave its component, and
1874// optionally doesn't contain Ninja variables.
1875func validatePathInternal(allowNinjaVariables bool, pathComponents ...string) (string, error) {
Jeff Gaston734e3802017-04-10 15:47:24 -07001876 for _, path := range pathComponents {
Jingwen Chen24d0c562023-02-07 09:29:36 +00001877 if !allowNinjaVariables && strings.Contains(path, "$") {
1878 return "", fmt.Errorf("Path contains invalid character($): %s", path)
1879 }
1880
Dan Willemsen80a7c2a2015-12-21 14:57:11 -08001881 path := filepath.Clean(path)
1882 if path == ".." || strings.HasPrefix(path, "../") || strings.HasPrefix(path, "/") {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001883 return "", fmt.Errorf("Path is outside directory: %s", path)
Dan Willemsen80a7c2a2015-12-21 14:57:11 -08001884 }
1885 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001886 // TODO: filepath.Join isn't necessarily correct with embedded ninja
1887 // variables. '..' may remove the entire ninja variable, even if it
1888 // will be expanded to multiple nested directories.
Colin Cross1ccfcc32018-02-22 13:54:26 -08001889 return filepath.Join(pathComponents...), nil
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001890}
1891
Jingwen Chen24d0c562023-02-07 09:29:36 +00001892// validateSafePath validates a path that we trust (may contain ninja
1893// variables). Ensures that each path component does not attempt to leave its
1894// component. Returns a joined version of each path component.
1895func validateSafePath(pathComponents ...string) (string, error) {
1896 return validatePathInternal(true, pathComponents...)
1897}
1898
Dan Willemsen80a7c2a2015-12-21 14:57:11 -08001899// validatePath validates that a path does not include ninja variables, and that
1900// each path component does not attempt to leave its component. Returns a joined
1901// version of each path component.
Colin Cross1ccfcc32018-02-22 13:54:26 -08001902func validatePath(pathComponents ...string) (string, error) {
Jingwen Chen24d0c562023-02-07 09:29:36 +00001903 return validatePathInternal(false, pathComponents...)
Colin Cross6e18ca42015-07-14 18:55:36 -07001904}
Colin Cross5b529592017-05-09 13:34:34 -07001905
Colin Cross0875c522017-11-28 17:34:01 -08001906func PathForPhony(ctx PathContext, phony string) WritablePath {
1907 if strings.ContainsAny(phony, "$/") {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001908 ReportPathErrorf(ctx, "Phony target contains invalid character ($ or /): %s", phony)
Colin Cross0875c522017-11-28 17:34:01 -08001909 }
Paul Duffin74abc5d2021-03-24 09:24:59 +00001910 return PhonyPath{basePath{phony, ""}}
Colin Cross0875c522017-11-28 17:34:01 -08001911}
1912
Colin Cross74e3fe42017-12-11 15:51:44 -08001913type PhonyPath struct {
1914 basePath
1915}
1916
1917func (p PhonyPath) writablePath() {}
1918
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02001919func (p PhonyPath) getSoongOutDir() string {
Paul Duffind65c58b2021-03-24 09:22:07 +00001920 // A phone path cannot contain any / so cannot be relative to the build directory.
1921 return ""
Paul Duffin9b478b02019-12-10 13:41:51 +00001922}
1923
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001924func (p PhonyPath) RelativeToTop() Path {
1925 ensureTestOnly()
1926 // A phony path cannot contain any / so does not have a build directory so switching to a new
1927 // build directory has no effect so just return this path.
1928 return p
1929}
1930
Hans MÃ¥nssond3f2bd72020-11-27 12:37:28 +01001931func (p PhonyPath) ReplaceExtension(ctx PathContext, ext string) OutputPath {
1932 panic("Not implemented")
1933}
1934
Colin Cross74e3fe42017-12-11 15:51:44 -08001935var _ Path = PhonyPath{}
1936var _ WritablePath = PhonyPath{}
1937
Colin Cross5b529592017-05-09 13:34:34 -07001938type testPath struct {
1939 basePath
1940}
1941
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001942func (p testPath) RelativeToTop() Path {
1943 ensureTestOnly()
1944 return p
1945}
1946
Colin Cross5b529592017-05-09 13:34:34 -07001947func (p testPath) String() string {
1948 return p.path
1949}
1950
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001951var _ Path = testPath{}
1952
Colin Cross40e33732019-02-15 11:08:35 -08001953// PathForTesting returns a Path constructed from joining the elements of paths with '/'. It should only be used from
1954// within tests.
Colin Cross5b529592017-05-09 13:34:34 -07001955func PathForTesting(paths ...string) Path {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001956 p, err := validateSafePath(paths...)
1957 if err != nil {
1958 panic(err)
1959 }
Colin Cross5b529592017-05-09 13:34:34 -07001960 return testPath{basePath{path: p, rel: p}}
1961}
1962
Sam Delmerico2351eac2022-05-24 17:10:02 +00001963func PathForTestingWithRel(path, rel string) Path {
1964 p, err := validateSafePath(path, rel)
1965 if err != nil {
1966 panic(err)
1967 }
1968 r, err := validatePath(rel)
1969 if err != nil {
1970 panic(err)
1971 }
1972 return testPath{basePath{path: p, rel: r}}
1973}
1974
Colin Cross40e33732019-02-15 11:08:35 -08001975// PathsForTesting returns a Path constructed from each element in strs. It should only be used from within tests.
1976func PathsForTesting(strs ...string) Paths {
Colin Cross5b529592017-05-09 13:34:34 -07001977 p := make(Paths, len(strs))
1978 for i, s := range strs {
1979 p[i] = PathForTesting(s)
1980 }
1981
1982 return p
1983}
Colin Cross43f08db2018-11-12 10:13:39 -08001984
Colin Cross40e33732019-02-15 11:08:35 -08001985type testPathContext struct {
1986 config Config
Colin Cross40e33732019-02-15 11:08:35 -08001987}
1988
Colin Cross40e33732019-02-15 11:08:35 -08001989func (x *testPathContext) Config() Config { return x.config }
1990func (x *testPathContext) AddNinjaFileDeps(...string) {}
1991
1992// PathContextForTesting returns a PathContext that can be used in tests, for example to create an OutputPath with
1993// PathForOutput.
Colin Cross98be1bb2019-12-13 20:41:13 -08001994func PathContextForTesting(config Config) PathContext {
Colin Cross40e33732019-02-15 11:08:35 -08001995 return &testPathContext{
1996 config: config,
Colin Cross40e33732019-02-15 11:08:35 -08001997 }
1998}
1999
Ulya Trafimovichccc8c852020-10-14 11:29:07 +01002000type testModuleInstallPathContext struct {
2001 baseModuleContext
2002
2003 inData bool
2004 inTestcases bool
2005 inSanitizerDir bool
2006 inRamdisk bool
2007 inVendorRamdisk bool
Inseob Kim08758f02021-04-08 21:13:22 +09002008 inDebugRamdisk bool
Ulya Trafimovichccc8c852020-10-14 11:29:07 +01002009 inRecovery bool
2010 inRoot bool
2011 forceOS *OsType
2012 forceArch *ArchType
2013}
2014
2015func (m testModuleInstallPathContext) Config() Config {
2016 return m.baseModuleContext.config
2017}
2018
2019func (testModuleInstallPathContext) AddNinjaFileDeps(deps ...string) {}
2020
2021func (m testModuleInstallPathContext) InstallInData() bool {
2022 return m.inData
2023}
2024
2025func (m testModuleInstallPathContext) InstallInTestcases() bool {
2026 return m.inTestcases
2027}
2028
2029func (m testModuleInstallPathContext) InstallInSanitizerDir() bool {
2030 return m.inSanitizerDir
2031}
2032
2033func (m testModuleInstallPathContext) InstallInRamdisk() bool {
2034 return m.inRamdisk
2035}
2036
2037func (m testModuleInstallPathContext) InstallInVendorRamdisk() bool {
2038 return m.inVendorRamdisk
2039}
2040
Inseob Kim08758f02021-04-08 21:13:22 +09002041func (m testModuleInstallPathContext) InstallInDebugRamdisk() bool {
2042 return m.inDebugRamdisk
2043}
2044
Ulya Trafimovichccc8c852020-10-14 11:29:07 +01002045func (m testModuleInstallPathContext) InstallInRecovery() bool {
2046 return m.inRecovery
2047}
2048
2049func (m testModuleInstallPathContext) InstallInRoot() bool {
2050 return m.inRoot
2051}
2052
Ulya Trafimovichccc8c852020-10-14 11:29:07 +01002053func (m testModuleInstallPathContext) InstallForceOS() (*OsType, *ArchType) {
2054 return m.forceOS, m.forceArch
2055}
2056
2057// Construct a minimal ModuleInstallPathContext for testing. Note that baseModuleContext is
2058// default-initialized, which leaves blueprint.baseModuleContext set to nil, so methods that are
2059// delegated to it will panic.
2060func ModuleInstallPathContextForTesting(config Config) ModuleInstallPathContext {
2061 ctx := &testModuleInstallPathContext{}
2062 ctx.config = config
2063 ctx.os = Android
2064 return ctx
2065}
2066
Colin Cross43f08db2018-11-12 10:13:39 -08002067// Rel performs the same function as filepath.Rel, but reports errors to a PathContext, and reports an error if
2068// targetPath is not inside basePath.
2069func Rel(ctx PathContext, basePath string, targetPath string) string {
2070 rel, isRel := MaybeRel(ctx, basePath, targetPath)
2071 if !isRel {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01002072 ReportPathErrorf(ctx, "path %q is not under path %q", targetPath, basePath)
Colin Cross43f08db2018-11-12 10:13:39 -08002073 return ""
2074 }
2075 return rel
2076}
2077
2078// MaybeRel performs the same function as filepath.Rel, but reports errors to a PathContext, and returns false if
2079// targetPath is not inside basePath.
2080func MaybeRel(ctx PathContext, basePath string, targetPath string) (string, bool) {
Dan Willemsen633c5022019-04-12 11:11:38 -07002081 rel, isRel, err := maybeRelErr(basePath, targetPath)
2082 if err != nil {
2083 reportPathError(ctx, err)
2084 }
2085 return rel, isRel
2086}
2087
2088func maybeRelErr(basePath string, targetPath string) (string, bool, error) {
Colin Cross43f08db2018-11-12 10:13:39 -08002089 // filepath.Rel returns an error if one path is absolute and the other is not, handle that case first.
2090 if filepath.IsAbs(basePath) != filepath.IsAbs(targetPath) {
Dan Willemsen633c5022019-04-12 11:11:38 -07002091 return "", false, nil
Colin Cross43f08db2018-11-12 10:13:39 -08002092 }
2093 rel, err := filepath.Rel(basePath, targetPath)
2094 if err != nil {
Dan Willemsen633c5022019-04-12 11:11:38 -07002095 return "", false, err
Colin Cross43f08db2018-11-12 10:13:39 -08002096 } else if rel == ".." || strings.HasPrefix(rel, "../") || strings.HasPrefix(rel, "/") {
Dan Willemsen633c5022019-04-12 11:11:38 -07002097 return "", false, nil
Colin Cross43f08db2018-11-12 10:13:39 -08002098 }
Dan Willemsen633c5022019-04-12 11:11:38 -07002099 return rel, true, nil
Colin Cross43f08db2018-11-12 10:13:39 -08002100}
Colin Cross988414c2020-01-11 01:11:46 +00002101
2102// Writes a file to the output directory. Attempting to write directly to the output directory
2103// will fail due to the sandbox of the soong_build process.
Chris Parsons1a12d032023-02-06 22:37:41 -05002104// Only writes the file if the file doesn't exist or if it has different contents, to prevent
2105// updating the timestamp if no changes would be made. (This is better for incremental
2106// performance.)
Colin Cross988414c2020-01-11 01:11:46 +00002107func WriteFileToOutputDir(path WritablePath, data []byte, perm os.FileMode) error {
Colin Crossd6421132021-11-09 12:32:34 -08002108 absPath := absolutePath(path.String())
2109 err := os.MkdirAll(filepath.Dir(absPath), 0777)
2110 if err != nil {
2111 return err
2112 }
Chris Parsons1a12d032023-02-06 22:37:41 -05002113 return pathtools.WriteFileIfChanged(absPath, data, perm)
Colin Cross988414c2020-01-11 01:11:46 +00002114}
2115
Liz Kammer2dd9ca42020-11-25 16:06:39 -08002116func RemoveAllOutputDir(path WritablePath) error {
2117 return os.RemoveAll(absolutePath(path.String()))
2118}
2119
2120func CreateOutputDirIfNonexistent(path WritablePath, perm os.FileMode) error {
2121 dir := absolutePath(path.String())
Liz Kammer09f947d2021-05-12 14:51:49 -04002122 return createDirIfNonexistent(dir, perm)
2123}
2124
2125func createDirIfNonexistent(dir string, perm os.FileMode) error {
Liz Kammer2dd9ca42020-11-25 16:06:39 -08002126 if _, err := os.Stat(dir); os.IsNotExist(err) {
2127 return os.MkdirAll(dir, os.ModePerm)
2128 } else {
2129 return err
2130 }
2131}
2132
Jingwen Chen78257e52021-05-21 02:34:24 +00002133// absolutePath is deliberately private so that Soong's Go plugins can't use it to find and
2134// read arbitrary files without going through the methods in the current package that track
2135// dependencies.
Colin Cross988414c2020-01-11 01:11:46 +00002136func absolutePath(path string) string {
2137 if filepath.IsAbs(path) {
2138 return path
2139 }
2140 return filepath.Join(absSrcDir, path)
2141}
Chris Parsons216e10a2020-07-09 17:12:52 -04002142
2143// A DataPath represents the path of a file to be used as data, for example
2144// a test library to be installed alongside a test.
2145// The data file should be installed (copied from `<SrcPath>`) to
2146// `<install_root>/<RelativeInstallPath>/<filename>`, or
2147// `<install_root>/<filename>` if RelativeInstallPath is empty.
2148type DataPath struct {
2149 // The path of the data file that should be copied into the data directory
2150 SrcPath Path
2151 // The install path of the data file, relative to the install root.
2152 RelativeInstallPath string
2153}
Colin Crossdcf71b22021-02-01 13:59:03 -08002154
2155// PathsIfNonNil returns a Paths containing only the non-nil input arguments.
2156func PathsIfNonNil(paths ...Path) Paths {
2157 if len(paths) == 0 {
2158 // Fast path for empty argument list
2159 return nil
2160 } else if len(paths) == 1 {
2161 // Fast path for a single argument
2162 if paths[0] != nil {
2163 return paths
2164 } else {
2165 return nil
2166 }
2167 }
2168 ret := make(Paths, 0, len(paths))
2169 for _, path := range paths {
2170 if path != nil {
2171 ret = append(ret, path)
2172 }
2173 }
2174 if len(ret) == 0 {
2175 return nil
2176 }
2177 return ret
2178}
Chris Wailesb2703ad2021-07-30 13:25:42 -07002179
2180var thirdPartyDirPrefixExceptions = []*regexp.Regexp{
2181 regexp.MustCompile("^vendor/[^/]*google[^/]*/"),
2182 regexp.MustCompile("^hardware/google/"),
2183 regexp.MustCompile("^hardware/interfaces/"),
2184 regexp.MustCompile("^hardware/libhardware[^/]*/"),
2185 regexp.MustCompile("^hardware/ril/"),
2186}
2187
2188func IsThirdPartyPath(path string) bool {
2189 thirdPartyDirPrefixes := []string{"external/", "vendor/", "hardware/"}
2190
2191 if HasAnyPrefix(path, thirdPartyDirPrefixes) {
2192 for _, prefix := range thirdPartyDirPrefixExceptions {
2193 if prefix.MatchString(path) {
2194 return false
2195 }
2196 }
2197 return true
2198 }
2199 return false
2200}