blob: e0e5ae5800037857fa1f726711991a09cba351c6 [file] [log] [blame]
Colin Cross3f40fa42015-01-30 17:27:36 -08001// Copyright 2015 Google Inc. All rights reserved.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
Colin Cross635c3b02016-05-18 15:37:25 -070015package android
Colin Cross3f40fa42015-01-30 17:27:36 -080016
17import (
Colin Cross6e18ca42015-07-14 18:55:36 -070018 "fmt"
Colin Cross988414c2020-01-11 01:11:46 +000019 "io/ioutil"
20 "os"
Colin Cross6a745c62015-06-16 16:38:10 -070021 "path/filepath"
Dan Willemsen34cc69e2015-09-23 15:26:20 -070022 "reflect"
Chris Wailesb2703ad2021-07-30 13:25:42 -070023 "regexp"
Colin Cross5e6cfbe2017-11-03 15:20:35 -070024 "sort"
Dan Willemsen34cc69e2015-09-23 15:26:20 -070025 "strings"
26
27 "github.com/google/blueprint"
Colin Cross0e446152021-05-03 13:35:32 -070028 "github.com/google/blueprint/bootstrap"
Dan Willemsen34cc69e2015-09-23 15:26:20 -070029 "github.com/google/blueprint/pathtools"
Colin Cross3f40fa42015-01-30 17:27:36 -080030)
31
Colin Cross988414c2020-01-11 01:11:46 +000032var absSrcDir string
33
Dan Willemsen34cc69e2015-09-23 15:26:20 -070034// PathContext is the subset of a (Module|Singleton)Context required by the
35// Path methods.
36type PathContext interface {
Colin Crossaabf6792017-11-29 00:27:14 -080037 Config() Config
Dan Willemsen7b310ee2015-12-18 15:11:17 -080038 AddNinjaFileDeps(deps ...string)
Colin Cross3f40fa42015-01-30 17:27:36 -080039}
40
Colin Cross7f19f372016-11-01 11:10:25 -070041type PathGlobContext interface {
42 GlobWithDeps(globPattern string, excludes []string) ([]string, error)
43}
44
Colin Crossaabf6792017-11-29 00:27:14 -080045var _ PathContext = SingletonContext(nil)
46var _ PathContext = ModuleContext(nil)
Dan Willemsen34cc69e2015-09-23 15:26:20 -070047
Ulya Trafimovich8640ab92020-05-11 18:06:15 +010048// "Null" path context is a minimal path context for a given config.
49type NullPathContext struct {
50 config Config
51}
52
53func (NullPathContext) AddNinjaFileDeps(...string) {}
54func (ctx NullPathContext) Config() Config { return ctx.config }
55
Liz Kammera830f3a2020-11-10 10:50:34 -080056// EarlyModulePathContext is a subset of EarlyModuleContext methods required by the
57// Path methods. These path methods can be called before any mutators have run.
58type EarlyModulePathContext interface {
59 PathContext
60 PathGlobContext
61
62 ModuleDir() string
63 ModuleErrorf(fmt string, args ...interface{})
64}
65
66var _ EarlyModulePathContext = ModuleContext(nil)
67
68// Glob globs files and directories matching globPattern relative to ModuleDir(),
69// paths in the excludes parameter will be omitted.
70func Glob(ctx EarlyModulePathContext, globPattern string, excludes []string) Paths {
71 ret, err := ctx.GlobWithDeps(globPattern, excludes)
72 if err != nil {
73 ctx.ModuleErrorf("glob: %s", err.Error())
74 }
75 return pathsForModuleSrcFromFullPath(ctx, ret, true)
76}
77
78// GlobFiles globs *only* files (not directories) matching globPattern relative to ModuleDir().
79// Paths in the excludes parameter will be omitted.
80func GlobFiles(ctx EarlyModulePathContext, globPattern string, excludes []string) Paths {
81 ret, err := ctx.GlobWithDeps(globPattern, excludes)
82 if err != nil {
83 ctx.ModuleErrorf("glob: %s", err.Error())
84 }
85 return pathsForModuleSrcFromFullPath(ctx, ret, false)
86}
87
88// ModuleWithDepsPathContext is a subset of *ModuleContext methods required by
89// the Path methods that rely on module dependencies having been resolved.
90type ModuleWithDepsPathContext interface {
91 EarlyModulePathContext
Paul Duffin40131a32021-07-09 17:10:35 +010092 VisitDirectDepsBlueprint(visit func(blueprint.Module))
93 OtherModuleDependencyTag(m blueprint.Module) blueprint.DependencyTag
Liz Kammera830f3a2020-11-10 10:50:34 -080094}
95
96// ModuleMissingDepsPathContext is a subset of *ModuleContext methods required by
97// the Path methods that rely on module dependencies having been resolved and ability to report
98// missing dependency errors.
99type ModuleMissingDepsPathContext interface {
100 ModuleWithDepsPathContext
101 AddMissingDependencies(missingDeps []string)
102}
103
Dan Willemsen00269f22017-07-06 16:59:48 -0700104type ModuleInstallPathContext interface {
Colin Cross0ea8ba82019-06-06 14:33:29 -0700105 BaseModuleContext
Dan Willemsen00269f22017-07-06 16:59:48 -0700106
107 InstallInData() bool
Jaewoong Jung0949f312019-09-11 10:25:18 -0700108 InstallInTestcases() bool
Dan Willemsen00269f22017-07-06 16:59:48 -0700109 InstallInSanitizerDir() bool
Yifan Hong1b3348d2020-01-21 15:53:22 -0800110 InstallInRamdisk() bool
Yifan Hong60e0cfb2020-10-21 15:17:56 -0700111 InstallInVendorRamdisk() bool
Inseob Kim08758f02021-04-08 21:13:22 +0900112 InstallInDebugRamdisk() bool
Jiyong Parkf9332f12018-02-01 00:54:12 +0900113 InstallInRecovery() bool
Colin Cross90ba5f42019-10-02 11:10:58 -0700114 InstallInRoot() bool
Jiyong Park87788b52020-09-01 12:37:45 +0900115 InstallForceOS() (*OsType, *ArchType)
Dan Willemsen00269f22017-07-06 16:59:48 -0700116}
117
118var _ ModuleInstallPathContext = ModuleContext(nil)
119
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700120// errorfContext is the interface containing the Errorf method matching the
121// Errorf method in blueprint.SingletonContext.
122type errorfContext interface {
123 Errorf(format string, args ...interface{})
Colin Cross3f40fa42015-01-30 17:27:36 -0800124}
125
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700126var _ errorfContext = blueprint.SingletonContext(nil)
127
128// moduleErrorf is the interface containing the ModuleErrorf method matching
129// the ModuleErrorf method in blueprint.ModuleContext.
130type moduleErrorf interface {
131 ModuleErrorf(format string, args ...interface{})
Colin Cross3f40fa42015-01-30 17:27:36 -0800132}
133
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700134var _ moduleErrorf = blueprint.ModuleContext(nil)
135
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700136// reportPathError will register an error with the attached context. It
137// attempts ctx.ModuleErrorf for a better error message first, then falls
138// back to ctx.Errorf.
Colin Cross1ccfcc32018-02-22 13:54:26 -0800139func reportPathError(ctx PathContext, err error) {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +0100140 ReportPathErrorf(ctx, "%s", err.Error())
Colin Cross1ccfcc32018-02-22 13:54:26 -0800141}
142
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +0100143// ReportPathErrorf will register an error with the attached context. It
Colin Cross1ccfcc32018-02-22 13:54:26 -0800144// attempts ctx.ModuleErrorf for a better error message first, then falls
145// back to ctx.Errorf.
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +0100146func ReportPathErrorf(ctx PathContext, format string, args ...interface{}) {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700147 if mctx, ok := ctx.(moduleErrorf); ok {
148 mctx.ModuleErrorf(format, args...)
149 } else if ectx, ok := ctx.(errorfContext); ok {
150 ectx.Errorf(format, args...)
151 } else {
152 panic(fmt.Sprintf(format, args...))
Colin Crossf2298272015-05-12 11:36:53 -0700153 }
154}
155
Colin Cross5e708052019-08-06 13:59:50 -0700156func pathContextName(ctx PathContext, module blueprint.Module) string {
157 if x, ok := ctx.(interface{ ModuleName(blueprint.Module) string }); ok {
158 return x.ModuleName(module)
159 } else if x, ok := ctx.(interface{ OtherModuleName(blueprint.Module) string }); ok {
160 return x.OtherModuleName(module)
161 }
162 return "unknown"
163}
164
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700165type Path interface {
166 // Returns the path in string form
167 String() string
168
Colin Cross4f6fc9c2016-10-26 10:05:25 -0700169 // Ext returns the extension of the last element of the path
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700170 Ext() string
Colin Cross4f6fc9c2016-10-26 10:05:25 -0700171
172 // Base returns the last element of the path
173 Base() string
Colin Crossfaeb7aa2017-02-01 14:12:44 -0800174
175 // Rel returns the portion of the path relative to the directory it was created from. For
176 // example, Rel on a PathsForModuleSrc would return the path relative to the module source
Colin Cross0db55682017-12-05 15:36:55 -0800177 // directory, and OutputPath.Join("foo").Rel() would return "foo".
Colin Crossfaeb7aa2017-02-01 14:12:44 -0800178 Rel() string
Paul Duffin85d8f0d2021-03-24 10:18:18 +0000179
180 // RelativeToTop returns a new path relative to the top, it is provided solely for use in tests.
181 //
182 // It is guaranteed to always return the same type as it is called on, e.g. if called on an
183 // InstallPath then the returned value can be converted to an InstallPath.
184 //
185 // A standard build has the following structure:
186 // ../top/
187 // out/ - make install files go here.
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +0200188 // out/soong - this is the soongOutDir passed to NewTestConfig()
Paul Duffin85d8f0d2021-03-24 10:18:18 +0000189 // ... - the source files
190 //
191 // This function converts a path so that it appears relative to the ../top/ directory, i.e.
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +0200192 // * Make install paths, which have the pattern "soongOutDir/../<path>" are converted into the top
Paul Duffin85d8f0d2021-03-24 10:18:18 +0000193 // relative path "out/<path>"
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +0200194 // * Soong install paths and other writable paths, which have the pattern "soongOutDir/<path>" are
Paul Duffin85d8f0d2021-03-24 10:18:18 +0000195 // converted into the top relative path "out/soong/<path>".
196 // * Source paths are already relative to the top.
197 // * Phony paths are not relative to anything.
198 // * toolDepPath have an absolute but known value in so don't need making relative to anything in
199 // order to test.
200 RelativeToTop() Path
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700201}
202
Paul Duffin85d8f0d2021-03-24 10:18:18 +0000203const (
204 OutDir = "out"
205 OutSoongDir = OutDir + "/soong"
206)
207
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700208// WritablePath is a type of path that can be used as an output for build rules.
209type WritablePath interface {
210 Path
211
Paul Duffin9b478b02019-12-10 13:41:51 +0000212 // return the path to the build directory.
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +0200213 getSoongOutDir() string
Paul Duffin9b478b02019-12-10 13:41:51 +0000214
Jeff Gaston734e3802017-04-10 15:47:24 -0700215 // the writablePath method doesn't directly do anything,
216 // but it allows a struct to distinguish between whether or not it implements the WritablePath interface
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700217 writablePath()
Hans MÃ¥nssond3f2bd72020-11-27 12:37:28 +0100218
219 ReplaceExtension(ctx PathContext, ext string) OutputPath
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700220}
221
222type genPathProvider interface {
Liz Kammera830f3a2020-11-10 10:50:34 -0800223 genPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleGenPath
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700224}
225type objPathProvider interface {
Liz Kammera830f3a2020-11-10 10:50:34 -0800226 objPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleObjPath
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700227}
228type resPathProvider interface {
Liz Kammera830f3a2020-11-10 10:50:34 -0800229 resPathWithName(ctx ModuleOutPathContext, name string) ModuleResPath
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700230}
231
232// GenPathWithExt derives a new file path in ctx's generated sources directory
233// from the current path, but with the new extension.
Liz Kammera830f3a2020-11-10 10:50:34 -0800234func GenPathWithExt(ctx ModuleOutPathContext, subdir string, p Path, ext string) ModuleGenPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700235 if path, ok := p.(genPathProvider); ok {
Dan Willemsen21ec4902016-11-02 20:43:13 -0700236 return path.genPathWithExt(ctx, subdir, ext)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700237 }
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +0100238 ReportPathErrorf(ctx, "Tried to create generated file from unsupported path: %s(%s)", reflect.TypeOf(p).Name(), p)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700239 return PathForModuleGen(ctx)
240}
241
242// ObjPathWithExt derives a new file path in ctx's object directory from the
243// current path, but with the new extension.
Liz Kammera830f3a2020-11-10 10:50:34 -0800244func ObjPathWithExt(ctx ModuleOutPathContext, subdir string, p Path, ext string) ModuleObjPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700245 if path, ok := p.(objPathProvider); ok {
246 return path.objPathWithExt(ctx, subdir, ext)
247 }
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +0100248 ReportPathErrorf(ctx, "Tried to create object file from unsupported path: %s (%s)", reflect.TypeOf(p).Name(), p)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700249 return PathForModuleObj(ctx)
250}
251
252// ResPathWithName derives a new path in ctx's output resource directory, using
253// the current path to create the directory name, and the `name` argument for
254// the filename.
Liz Kammera830f3a2020-11-10 10:50:34 -0800255func ResPathWithName(ctx ModuleOutPathContext, p Path, name string) ModuleResPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700256 if path, ok := p.(resPathProvider); ok {
257 return path.resPathWithName(ctx, name)
258 }
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +0100259 ReportPathErrorf(ctx, "Tried to create res file from unsupported path: %s (%s)", reflect.TypeOf(p).Name(), p)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700260 return PathForModuleRes(ctx)
261}
262
263// OptionalPath is a container that may or may not contain a valid Path.
264type OptionalPath struct {
Martin Stjernholmc32dd1c2021-09-15 02:39:00 +0100265 path Path // nil if invalid.
266 invalidReason string // Not applicable if path != nil. "" if the reason is unknown.
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700267}
268
269// OptionalPathForPath returns an OptionalPath containing the path.
270func OptionalPathForPath(path Path) OptionalPath {
Martin Stjernholm2fee27f2021-09-16 14:11:12 +0100271 return OptionalPath{path: path}
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700272}
273
Martin Stjernholmc32dd1c2021-09-15 02:39:00 +0100274// InvalidOptionalPath returns an OptionalPath that is invalid with the given reason.
275func InvalidOptionalPath(reason string) OptionalPath {
276
277 return OptionalPath{invalidReason: reason}
278}
279
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700280// Valid returns whether there is a valid path
281func (p OptionalPath) Valid() bool {
Martin Stjernholm2fee27f2021-09-16 14:11:12 +0100282 return p.path != nil
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700283}
284
285// Path returns the Path embedded in this OptionalPath. You must be sure that
286// there is a valid path, since this method will panic if there is not.
287func (p OptionalPath) Path() Path {
Martin Stjernholm2fee27f2021-09-16 14:11:12 +0100288 if p.path == nil {
Martin Stjernholmc32dd1c2021-09-15 02:39:00 +0100289 msg := "Requesting an invalid path"
290 if p.invalidReason != "" {
291 msg += ": " + p.invalidReason
292 }
293 panic(msg)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700294 }
295 return p.path
296}
297
Martin Stjernholmc32dd1c2021-09-15 02:39:00 +0100298// InvalidReason returns the reason that the optional path is invalid, or "" if it is valid.
299func (p OptionalPath) InvalidReason() string {
300 if p.path != nil {
301 return ""
302 }
303 if p.invalidReason == "" {
304 return "unknown"
305 }
306 return p.invalidReason
307}
308
Paul Duffinef081852021-05-13 11:11:15 +0100309// AsPaths converts the OptionalPath into Paths.
310//
311// It returns nil if this is not valid, or a single length slice containing the Path embedded in
312// this OptionalPath.
313func (p OptionalPath) AsPaths() Paths {
Martin Stjernholm2fee27f2021-09-16 14:11:12 +0100314 if p.path == nil {
Paul Duffinef081852021-05-13 11:11:15 +0100315 return nil
316 }
317 return Paths{p.path}
318}
319
Paul Duffinafdd4062021-03-30 19:44:07 +0100320// RelativeToTop returns an OptionalPath with the path that was embedded having been replaced by the
321// result of calling Path.RelativeToTop on it.
322func (p OptionalPath) RelativeToTop() OptionalPath {
Martin Stjernholm2fee27f2021-09-16 14:11:12 +0100323 if p.path == nil {
Paul Duffina5b81352021-03-28 23:57:19 +0100324 return p
325 }
326 p.path = p.path.RelativeToTop()
327 return p
328}
329
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700330// String returns the string version of the Path, or "" if it isn't valid.
331func (p OptionalPath) String() string {
Martin Stjernholm2fee27f2021-09-16 14:11:12 +0100332 if p.path != nil {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700333 return p.path.String()
334 } else {
335 return ""
Colin Crossf2298272015-05-12 11:36:53 -0700336 }
337}
Colin Cross6e18ca42015-07-14 18:55:36 -0700338
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700339// Paths is a slice of Path objects, with helpers to operate on the collection.
340type Paths []Path
341
Paul Duffin85d8f0d2021-03-24 10:18:18 +0000342// RelativeToTop creates a new Paths containing the result of calling Path.RelativeToTop on each
343// item in this slice.
344func (p Paths) RelativeToTop() Paths {
345 ensureTestOnly()
346 if p == nil {
347 return p
348 }
349 ret := make(Paths, len(p))
350 for i, path := range p {
351 ret[i] = path.RelativeToTop()
352 }
353 return ret
354}
355
Jingwen Chen40fd90a2020-06-15 05:24:19 +0000356func (paths Paths) containsPath(path Path) bool {
357 for _, p := range paths {
358 if p == path {
359 return true
360 }
361 }
362 return false
363}
364
Liz Kammer7aa52882021-02-11 09:16:14 -0500365// PathsForSource returns Paths rooted from SrcDir, *not* rooted from the module's local source
366// directory
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700367func PathsForSource(ctx PathContext, paths []string) Paths {
368 ret := make(Paths, len(paths))
369 for i, path := range paths {
370 ret[i] = PathForSource(ctx, path)
371 }
372 return ret
373}
374
Liz Kammer7aa52882021-02-11 09:16:14 -0500375// ExistentPathsForSources returns a list of Paths rooted from SrcDir, *not* rooted from the
376// module's local source directory, that are found in the tree. If any are not found, they are
377// omitted from the list, and dependencies are added so that we're re-run when they are added.
Colin Cross32f38982018-02-22 11:47:25 -0800378func ExistentPathsForSources(ctx PathContext, paths []string) Paths {
Dan Willemsen7b310ee2015-12-18 15:11:17 -0800379 ret := make(Paths, 0, len(paths))
380 for _, path := range paths {
Colin Cross32f38982018-02-22 11:47:25 -0800381 p := ExistentPathForSource(ctx, path)
Dan Willemsen7b310ee2015-12-18 15:11:17 -0800382 if p.Valid() {
383 ret = append(ret, p.Path())
384 }
385 }
386 return ret
387}
388
Liz Kammer620dea62021-04-14 17:36:10 -0400389// PathsForModuleSrc returns a Paths{} containing the resolved references in paths:
390// * filepath, relative to local module directory, resolves as a filepath relative to the local
391// source directory
392// * glob, relative to the local module directory, resolves as filepath(s), relative to the local
393// source directory.
394// * other modules using the ":name{.tag}" syntax. These modules must implement SourceFileProducer
395// or OutputFileProducer. These resolve as a filepath to an output filepath or generated source
396// filepath.
397// 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
Liz Kammer620dea62021-04-14 17:36:10 -0400399// path_deps mutator.
400// If a requested module is not found as a dependency:
401// * if ctx.Config().AllowMissingDependencies() is true, this module to be marked as having
402// missing dependencies
403// * 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:
417// * 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// excluding the items (similarly resolved
425// Properties passed as the paths argument must have been annotated with struct tag
426// `android:"path"` so that dependencies on SourceFileProducer modules will have already been handled by the
427// path_deps mutator.
428// If a requested module is not found as a dependency:
429// * if ctx.Config().AllowMissingDependencies() is true, this module to be marked as having
430// missing dependencies
431// * otherwise, a ModuleError is thrown.
Liz Kammera830f3a2020-11-10 10:50:34 -0800432func PathsForModuleSrcExcludes(ctx ModuleMissingDepsPathContext, paths, excludes []string) Paths {
Liz Kammer619be462022-01-28 15:13:39 -0500433 return PathsRelativeToModuleSourceDir(SourceInput{
434 Context: ctx,
435 Paths: paths,
436 ExcludePaths: excludes,
437 IncludeDirs: true,
438 })
439}
440
441func PathsRelativeToModuleSourceDir(input SourceInput) Paths {
442 ret, missingDeps := PathsAndMissingDepsRelativeToModuleSourceDir(input)
443 if input.Context.Config().AllowMissingDependencies() {
444 input.Context.AddMissingDependencies(missingDeps)
Colin Crossba71a3f2019-03-18 12:12:48 -0700445 } else {
446 for _, m := range missingDeps {
Liz Kammer619be462022-01-28 15:13:39 -0500447 input.Context.ModuleErrorf(`missing dependency on %q, is the property annotated with android:"path"?`, m)
Colin Crossba71a3f2019-03-18 12:12:48 -0700448 }
449 }
450 return ret
451}
452
Ulya Trafimovich4d2eeed2019-11-08 10:54:21 +0000453// OutputPaths is a slice of OutputPath objects, with helpers to operate on the collection.
454type OutputPaths []OutputPath
455
456// Paths returns the OutputPaths as a Paths
457func (p OutputPaths) Paths() Paths {
458 if p == nil {
459 return nil
460 }
461 ret := make(Paths, len(p))
462 for i, path := range p {
463 ret[i] = path
464 }
465 return ret
466}
467
468// Strings returns the string forms of the writable paths.
469func (p OutputPaths) Strings() []string {
470 if p == nil {
471 return nil
472 }
473 ret := make([]string, len(p))
474 for i, path := range p {
475 ret[i] = path.String()
476 }
477 return ret
478}
479
Colin Crossa44551f2021-10-25 15:36:21 -0700480// PathForGoBinary returns the path to the installed location of a bootstrap_go_binary module.
481func PathForGoBinary(ctx PathContext, goBinary bootstrap.GoBinaryTool) Path {
482 goBinaryInstallDir := pathForInstall(ctx, ctx.Config().BuildOS, ctx.Config().BuildArch, "bin", false)
483 rel := Rel(ctx, goBinaryInstallDir.String(), goBinary.InstallPath())
484 return goBinaryInstallDir.Join(ctx, rel)
485}
486
Liz Kammera830f3a2020-11-10 10:50:34 -0800487// Expands Paths to a SourceFileProducer or OutputFileProducer module dependency referenced via ":name" or ":name{.tag}" syntax.
488// If the dependency is not found, a missingErrorDependency is returned.
489// If the module dependency is not a SourceFileProducer or OutputFileProducer, appropriate errors will be returned.
490func getPathsFromModuleDep(ctx ModuleWithDepsPathContext, path, moduleName, tag string) (Paths, error) {
Paul Duffind5cf92e2021-07-09 17:38:55 +0100491 module := GetModuleFromPathDep(ctx, moduleName, tag)
Liz Kammera830f3a2020-11-10 10:50:34 -0800492 if module == nil {
493 return nil, missingDependencyError{[]string{moduleName}}
494 }
Colin Crossfa65cee2021-03-22 17:05:59 -0700495 if aModule, ok := module.(Module); ok && !aModule.Enabled() {
496 return nil, missingDependencyError{[]string{moduleName}}
497 }
Liz Kammera830f3a2020-11-10 10:50:34 -0800498 if outProducer, ok := module.(OutputFileProducer); ok {
499 outputFiles, err := outProducer.OutputFiles(tag)
500 if err != nil {
501 return nil, fmt.Errorf("path dependency %q: %s", path, err)
502 }
503 return outputFiles, nil
504 } else if tag != "" {
505 return nil, fmt.Errorf("path dependency %q is not an output file producing module", path)
Colin Cross0e446152021-05-03 13:35:32 -0700506 } else if goBinary, ok := module.(bootstrap.GoBinaryTool); ok {
Colin Crossa44551f2021-10-25 15:36:21 -0700507 goBinaryPath := PathForGoBinary(ctx, goBinary)
508 return Paths{goBinaryPath}, nil
Liz Kammera830f3a2020-11-10 10:50:34 -0800509 } else if srcProducer, ok := module.(SourceFileProducer); ok {
510 return srcProducer.Srcs(), nil
511 } else {
512 return nil, fmt.Errorf("path dependency %q is not a source file producing module", path)
513 }
514}
515
Paul Duffind5cf92e2021-07-09 17:38:55 +0100516// GetModuleFromPathDep will return the module that was added as a dependency automatically for
517// properties tagged with `android:"path"` or manually using ExtractSourceDeps or
518// ExtractSourcesDeps.
519//
520// The moduleName and tag supplied to this should be the values returned from SrcIsModuleWithTag.
521// Or, if no tag is expected then the moduleName should be the value returned by SrcIsModule and
522// the tag must be "".
523//
524// If tag is "" then the returned module will be the dependency that was added for ":moduleName".
525// Otherwise, it is the dependency that was added for ":moduleName{tag}".
Paul Duffind5cf92e2021-07-09 17:38:55 +0100526func GetModuleFromPathDep(ctx ModuleWithDepsPathContext, moduleName, tag string) blueprint.Module {
Paul Duffin40131a32021-07-09 17:10:35 +0100527 var found blueprint.Module
528 // The sourceOrOutputDepTag uniquely identifies the module dependency as it contains both the
529 // module name and the tag. Dependencies added automatically for properties tagged with
530 // `android:"path"` are deduped so are guaranteed to be unique. It is possible for duplicate
531 // dependencies to be added manually using ExtractSourcesDeps or ExtractSourceDeps but even then
532 // it will always be the case that the dependencies will be identical, i.e. the same tag and same
533 // moduleName referring to the same dependency module.
534 //
535 // It does not matter whether the moduleName is a fully qualified name or if the module
536 // dependency is a prebuilt module. All that matters is the same information is supplied to
537 // create the tag here as was supplied to create the tag when the dependency was added so that
538 // this finds the matching dependency module.
539 expectedTag := sourceOrOutputDepTag(moduleName, tag)
540 ctx.VisitDirectDepsBlueprint(func(module blueprint.Module) {
541 depTag := ctx.OtherModuleDependencyTag(module)
542 if depTag == expectedTag {
543 found = module
544 }
545 })
546 return found
Paul Duffind5cf92e2021-07-09 17:38:55 +0100547}
548
Liz Kammer620dea62021-04-14 17:36:10 -0400549// PathsAndMissingDepsForModuleSrcExcludes returns a Paths{} containing the resolved references in
550// paths, minus those listed in excludes. Elements of paths and excludes are resolved as:
551// * filepath, relative to local module directory, resolves as a filepath relative to the local
552// source directory
553// * glob, relative to the local module directory, resolves as filepath(s), relative to the local
554// source directory. Not valid in excludes.
555// * other modules using the ":name{.tag}" syntax. These modules must implement SourceFileProducer
556// or OutputFileProducer. These resolve as a filepath to an output filepath or generated source
557// filepath.
558// and a list of the module names of missing module dependencies are returned as the second return.
559// Properties passed as the paths argument must have been annotated with struct tag
Colin Cross41955e82019-05-29 14:40:35 -0700560// `android:"path"` so that dependencies on SourceFileProducer modules will have already been handled by the
Liz Kammer620dea62021-04-14 17:36:10 -0400561// path_deps mutator.
Liz Kammer619be462022-01-28 15:13:39 -0500562func PathsAndMissingDepsForModuleSrcExcludes(ctx ModuleMissingDepsPathContext, paths, excludes []string) (Paths, []string) {
563 return PathsAndMissingDepsRelativeToModuleSourceDir(SourceInput{
564 Context: ctx,
565 Paths: paths,
566 ExcludePaths: excludes,
567 IncludeDirs: true,
568 })
569}
570
571func PathsAndMissingDepsRelativeToModuleSourceDir(input SourceInput) (Paths, []string) {
572 prefix := pathForModuleSrc(input.Context).String()
Colin Cross8a497952019-03-05 22:25:09 -0800573
574 var expandedExcludes []string
Liz Kammer619be462022-01-28 15:13:39 -0500575 if input.ExcludePaths != nil {
576 expandedExcludes = make([]string, 0, len(input.ExcludePaths))
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700577 }
Colin Cross8a497952019-03-05 22:25:09 -0800578
Colin Crossba71a3f2019-03-18 12:12:48 -0700579 var missingExcludeDeps []string
Liz Kammer619be462022-01-28 15:13:39 -0500580 for _, e := range input.ExcludePaths {
Colin Cross41955e82019-05-29 14:40:35 -0700581 if m, t := SrcIsModuleWithTag(e); m != "" {
Liz Kammer619be462022-01-28 15:13:39 -0500582 modulePaths, err := getPathsFromModuleDep(input.Context, e, m, t)
Liz Kammera830f3a2020-11-10 10:50:34 -0800583 if m, ok := err.(missingDependencyError); ok {
584 missingExcludeDeps = append(missingExcludeDeps, m.missingDeps...)
585 } else if err != nil {
Liz Kammer619be462022-01-28 15:13:39 -0500586 reportPathError(input.Context, err)
Colin Cross8a497952019-03-05 22:25:09 -0800587 } else {
Liz Kammera830f3a2020-11-10 10:50:34 -0800588 expandedExcludes = append(expandedExcludes, modulePaths.Strings()...)
Colin Cross8a497952019-03-05 22:25:09 -0800589 }
590 } else {
591 expandedExcludes = append(expandedExcludes, filepath.Join(prefix, e))
592 }
593 }
594
Liz Kammer619be462022-01-28 15:13:39 -0500595 if input.Paths == nil {
Colin Crossba71a3f2019-03-18 12:12:48 -0700596 return nil, missingExcludeDeps
Colin Cross8a497952019-03-05 22:25:09 -0800597 }
598
Colin Crossba71a3f2019-03-18 12:12:48 -0700599 var missingDeps []string
600
Liz Kammer619be462022-01-28 15:13:39 -0500601 expandedSrcFiles := make(Paths, 0, len(input.Paths))
602 for _, s := range input.Paths {
603 srcFiles, err := expandOneSrcPath(sourcePathInput{
604 context: input.Context,
605 path: s,
606 expandedExcludes: expandedExcludes,
607 includeDirs: input.IncludeDirs,
608 })
Colin Cross8a497952019-03-05 22:25:09 -0800609 if depErr, ok := err.(missingDependencyError); ok {
Colin Crossba71a3f2019-03-18 12:12:48 -0700610 missingDeps = append(missingDeps, depErr.missingDeps...)
Colin Cross8a497952019-03-05 22:25:09 -0800611 } else if err != nil {
Liz Kammer619be462022-01-28 15:13:39 -0500612 reportPathError(input.Context, err)
Colin Cross8a497952019-03-05 22:25:09 -0800613 }
614 expandedSrcFiles = append(expandedSrcFiles, srcFiles...)
615 }
Colin Crossba71a3f2019-03-18 12:12:48 -0700616
617 return expandedSrcFiles, append(missingDeps, missingExcludeDeps...)
Colin Cross8a497952019-03-05 22:25:09 -0800618}
619
620type missingDependencyError struct {
621 missingDeps []string
622}
623
624func (e missingDependencyError) Error() string {
625 return "missing dependencies: " + strings.Join(e.missingDeps, ", ")
626}
627
Liz Kammer619be462022-01-28 15:13:39 -0500628type sourcePathInput struct {
629 context ModuleWithDepsPathContext
630 path string
631 expandedExcludes []string
632 includeDirs bool
633}
634
Liz Kammera830f3a2020-11-10 10:50:34 -0800635// Expands one path string to Paths rooted from the module's local source
636// directory, excluding those listed in the expandedExcludes.
637// Expands globs, references to SourceFileProducer or OutputFileProducer modules using the ":name" and ":name{.tag}" syntax.
Liz Kammer619be462022-01-28 15:13:39 -0500638func expandOneSrcPath(input sourcePathInput) (Paths, error) {
Jooyung Han7607dd32020-07-05 10:23:14 +0900639 excludePaths := func(paths Paths) Paths {
Liz Kammer619be462022-01-28 15:13:39 -0500640 if len(input.expandedExcludes) == 0 {
Jooyung Han7607dd32020-07-05 10:23:14 +0900641 return paths
642 }
643 remainder := make(Paths, 0, len(paths))
644 for _, p := range paths {
Liz Kammer619be462022-01-28 15:13:39 -0500645 if !InList(p.String(), input.expandedExcludes) {
Jooyung Han7607dd32020-07-05 10:23:14 +0900646 remainder = append(remainder, p)
647 }
648 }
649 return remainder
650 }
Liz Kammer619be462022-01-28 15:13:39 -0500651 if m, t := SrcIsModuleWithTag(input.path); m != "" {
652 modulePaths, err := getPathsFromModuleDep(input.context, input.path, m, t)
Liz Kammera830f3a2020-11-10 10:50:34 -0800653 if err != nil {
654 return nil, err
Colin Cross8a497952019-03-05 22:25:09 -0800655 } else {
Liz Kammera830f3a2020-11-10 10:50:34 -0800656 return excludePaths(modulePaths), nil
Colin Cross8a497952019-03-05 22:25:09 -0800657 }
Colin Cross8a497952019-03-05 22:25:09 -0800658 } else {
Liz Kammer619be462022-01-28 15:13:39 -0500659 p := pathForModuleSrc(input.context, input.path)
660 if pathtools.IsGlob(input.path) {
661 paths := GlobFiles(input.context, p.String(), input.expandedExcludes)
662 return PathsWithModuleSrcSubDir(input.context, paths, ""), nil
663 } else {
664 if exists, _, err := input.context.Config().fs.Exists(p.String()); err != nil {
665 ReportPathErrorf(input.context, "%s: %s", p, err.Error())
666 } else if !exists && !input.context.Config().TestAllowNonExistentPaths {
667 ReportPathErrorf(input.context, "module source path %q does not exist", p)
668 } else if !input.includeDirs {
669 if isDir, err := input.context.Config().fs.IsDir(p.String()); exists && err != nil {
670 ReportPathErrorf(input.context, "%s: %s", p, err.Error())
671 } else if isDir {
672 ReportPathErrorf(input.context, "module source path %q is a directory", p)
673 }
674 }
Colin Cross8a497952019-03-05 22:25:09 -0800675
Liz Kammer619be462022-01-28 15:13:39 -0500676 if InList(p.String(), input.expandedExcludes) {
677 return nil, nil
678 }
679 return Paths{p}, nil
Colin Cross8a497952019-03-05 22:25:09 -0800680 }
Colin Cross8a497952019-03-05 22:25:09 -0800681 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700682}
683
684// pathsForModuleSrcFromFullPath returns Paths rooted from the module's local
685// source directory, but strip the local source directory from the beginning of
Dan Willemsen540a78c2018-02-26 21:50:08 -0800686// each string. If incDirs is false, strip paths with a trailing '/' from the list.
Colin Crossfe4bc362018-09-12 10:02:13 -0700687// It intended for use in globs that only list files that exist, so it allows '$' in
688// filenames.
Liz Kammera830f3a2020-11-10 10:50:34 -0800689func pathsForModuleSrcFromFullPath(ctx EarlyModulePathContext, paths []string, incDirs bool) Paths {
Lukacs T. Berkif7e36d82021-08-16 17:05:09 +0200690 prefix := ctx.ModuleDir() + "/"
Colin Cross0f37af02017-09-27 17:42:05 -0700691 if prefix == "./" {
692 prefix = ""
693 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700694 ret := make(Paths, 0, len(paths))
695 for _, p := range paths {
Dan Willemsen540a78c2018-02-26 21:50:08 -0800696 if !incDirs && strings.HasSuffix(p, "/") {
697 continue
698 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700699 path := filepath.Clean(p)
700 if !strings.HasPrefix(path, prefix) {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +0100701 ReportPathErrorf(ctx, "Path %q is not in module source directory %q", p, prefix)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700702 continue
703 }
Colin Crosse3924e12018-08-15 20:18:53 -0700704
Colin Crossfe4bc362018-09-12 10:02:13 -0700705 srcPath, err := safePathForSource(ctx, ctx.ModuleDir(), path[len(prefix):])
Colin Crosse3924e12018-08-15 20:18:53 -0700706 if err != nil {
707 reportPathError(ctx, err)
708 continue
709 }
710
Colin Cross07e51612019-03-05 12:46:40 -0800711 srcPath.basePath.rel = srcPath.path
Colin Crosse3924e12018-08-15 20:18:53 -0700712
Colin Cross07e51612019-03-05 12:46:40 -0800713 ret = append(ret, srcPath)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700714 }
715 return ret
716}
717
Liz Kammera830f3a2020-11-10 10:50:34 -0800718// PathsWithOptionalDefaultForModuleSrc returns Paths rooted from the module's local source
719// directory. If input is nil, use the default if it exists. If input is empty, returns nil.
720func PathsWithOptionalDefaultForModuleSrc(ctx ModuleMissingDepsPathContext, input []string, def string) Paths {
Colin Cross0ddae7f2019-02-07 15:30:01 -0800721 if input != nil {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700722 return PathsForModuleSrc(ctx, input)
723 }
724 // Use Glob so that if the default doesn't exist, a dependency is added so that when it
725 // is created, we're run again.
Lukacs T. Berkif7e36d82021-08-16 17:05:09 +0200726 path := filepath.Join(ctx.ModuleDir(), def)
Liz Kammera830f3a2020-11-10 10:50:34 -0800727 return Glob(ctx, path, nil)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700728}
729
730// Strings returns the Paths in string form
731func (p Paths) Strings() []string {
732 if p == nil {
733 return nil
734 }
735 ret := make([]string, len(p))
736 for i, path := range p {
737 ret[i] = path.String()
738 }
739 return ret
740}
741
Colin Crossc0efd1d2020-07-03 11:56:24 -0700742func CopyOfPaths(paths Paths) Paths {
743 return append(Paths(nil), paths...)
744}
745
Colin Crossb6715442017-10-24 11:13:31 -0700746// FirstUniquePaths returns all unique elements of a Paths, keeping the first copy of each. It
747// modifies the Paths slice contents in place, and returns a subslice of the original slice.
Dan Willemsenfe92c962017-08-29 12:28:37 -0700748func FirstUniquePaths(list Paths) Paths {
Colin Cross27027c72020-02-28 15:34:17 -0800749 // 128 was chosen based on BenchmarkFirstUniquePaths results.
750 if len(list) > 128 {
751 return firstUniquePathsMap(list)
752 }
753 return firstUniquePathsList(list)
754}
755
Colin Crossc0efd1d2020-07-03 11:56:24 -0700756// SortedUniquePaths returns all unique elements of a Paths in sorted order. It modifies the
757// Paths slice contents in place, and returns a subslice of the original slice.
Jiyong Park33c77362020-05-29 22:00:16 +0900758func SortedUniquePaths(list Paths) Paths {
759 unique := FirstUniquePaths(list)
760 sort.Slice(unique, func(i, j int) bool {
761 return unique[i].String() < unique[j].String()
762 })
763 return unique
764}
765
Colin Cross27027c72020-02-28 15:34:17 -0800766func firstUniquePathsList(list Paths) Paths {
Dan Willemsenfe92c962017-08-29 12:28:37 -0700767 k := 0
768outer:
769 for i := 0; i < len(list); i++ {
770 for j := 0; j < k; j++ {
771 if list[i] == list[j] {
772 continue outer
773 }
774 }
775 list[k] = list[i]
776 k++
777 }
778 return list[:k]
779}
780
Colin Cross27027c72020-02-28 15:34:17 -0800781func firstUniquePathsMap(list Paths) Paths {
782 k := 0
783 seen := make(map[Path]bool, len(list))
784 for i := 0; i < len(list); i++ {
785 if seen[list[i]] {
786 continue
787 }
788 seen[list[i]] = true
789 list[k] = list[i]
790 k++
791 }
792 return list[:k]
793}
794
Colin Cross5d583952020-11-24 16:21:24 -0800795// FirstUniqueInstallPaths returns all unique elements of an InstallPaths, keeping the first copy of each. It
796// modifies the InstallPaths slice contents in place, and returns a subslice of the original slice.
797func FirstUniqueInstallPaths(list InstallPaths) InstallPaths {
798 // 128 was chosen based on BenchmarkFirstUniquePaths results.
799 if len(list) > 128 {
800 return firstUniqueInstallPathsMap(list)
801 }
802 return firstUniqueInstallPathsList(list)
803}
804
805func firstUniqueInstallPathsList(list InstallPaths) InstallPaths {
806 k := 0
807outer:
808 for i := 0; i < len(list); i++ {
809 for j := 0; j < k; j++ {
810 if list[i] == list[j] {
811 continue outer
812 }
813 }
814 list[k] = list[i]
815 k++
816 }
817 return list[:k]
818}
819
820func firstUniqueInstallPathsMap(list InstallPaths) InstallPaths {
821 k := 0
822 seen := make(map[InstallPath]bool, len(list))
823 for i := 0; i < len(list); i++ {
824 if seen[list[i]] {
825 continue
826 }
827 seen[list[i]] = true
828 list[k] = list[i]
829 k++
830 }
831 return list[:k]
832}
833
Colin Crossb6715442017-10-24 11:13:31 -0700834// LastUniquePaths returns all unique elements of a Paths, keeping the last copy of each. It
835// modifies the Paths slice contents in place, and returns a subslice of the original slice.
836func LastUniquePaths(list Paths) Paths {
837 totalSkip := 0
838 for i := len(list) - 1; i >= totalSkip; i-- {
839 skip := 0
840 for j := i - 1; j >= totalSkip; j-- {
841 if list[i] == list[j] {
842 skip++
843 } else {
844 list[j+skip] = list[j]
845 }
846 }
847 totalSkip += skip
848 }
849 return list[totalSkip:]
850}
851
Colin Crossa140bb02018-04-17 10:52:26 -0700852// ReversePaths returns a copy of a Paths in reverse order.
853func ReversePaths(list Paths) Paths {
854 if list == nil {
855 return nil
856 }
857 ret := make(Paths, len(list))
858 for i := range list {
859 ret[i] = list[len(list)-1-i]
860 }
861 return ret
862}
863
Jeff Gaston294356f2017-09-27 17:05:30 -0700864func indexPathList(s Path, list []Path) int {
865 for i, l := range list {
866 if l == s {
867 return i
868 }
869 }
870
871 return -1
872}
873
874func inPathList(p Path, list []Path) bool {
875 return indexPathList(p, list) != -1
876}
877
878func FilterPathList(list []Path, filter []Path) (remainder []Path, filtered []Path) {
Paul Duffin57b9e1d2019-12-13 00:03:35 +0000879 return FilterPathListPredicate(list, func(p Path) bool { return inPathList(p, filter) })
880}
881
882func FilterPathListPredicate(list []Path, predicate func(Path) bool) (remainder []Path, filtered []Path) {
Jeff Gaston294356f2017-09-27 17:05:30 -0700883 for _, l := range list {
Paul Duffin57b9e1d2019-12-13 00:03:35 +0000884 if predicate(l) {
Jeff Gaston294356f2017-09-27 17:05:30 -0700885 filtered = append(filtered, l)
886 } else {
887 remainder = append(remainder, l)
888 }
889 }
890
891 return
892}
893
Colin Cross93e85952017-08-15 13:34:18 -0700894// HasExt returns true of any of the paths have extension ext, otherwise false
895func (p Paths) HasExt(ext string) bool {
896 for _, path := range p {
897 if path.Ext() == ext {
898 return true
899 }
900 }
901
902 return false
903}
904
905// FilterByExt returns the subset of the paths that have extension ext
906func (p Paths) FilterByExt(ext string) Paths {
907 ret := make(Paths, 0, len(p))
908 for _, path := range p {
909 if path.Ext() == ext {
910 ret = append(ret, path)
911 }
912 }
913 return ret
914}
915
916// FilterOutByExt returns the subset of the paths that do not have extension ext
917func (p Paths) FilterOutByExt(ext string) Paths {
918 ret := make(Paths, 0, len(p))
919 for _, path := range p {
920 if path.Ext() != ext {
921 ret = append(ret, path)
922 }
923 }
924 return ret
925}
926
Colin Cross5e6cfbe2017-11-03 15:20:35 -0700927// DirectorySortedPaths is a slice of paths that are sorted such that all files in a directory
928// (including subdirectories) are in a contiguous subslice of the list, and can be found in
929// O(log(N)) time using a binary search on the directory prefix.
930type DirectorySortedPaths Paths
931
932func PathsToDirectorySortedPaths(paths Paths) DirectorySortedPaths {
933 ret := append(DirectorySortedPaths(nil), paths...)
934 sort.Slice(ret, func(i, j int) bool {
935 return ret[i].String() < ret[j].String()
936 })
937 return ret
938}
939
940// PathsInDirectory returns a subslice of the DirectorySortedPaths as a Paths that contains all entries
941// that are in the specified directory and its subdirectories.
942func (p DirectorySortedPaths) PathsInDirectory(dir string) Paths {
943 prefix := filepath.Clean(dir) + "/"
944 start := sort.Search(len(p), func(i int) bool {
945 return prefix < p[i].String()
946 })
947
948 ret := p[start:]
949
950 end := sort.Search(len(ret), func(i int) bool {
951 return !strings.HasPrefix(ret[i].String(), prefix)
952 })
953
954 ret = ret[:end]
955
956 return Paths(ret)
957}
958
Alex Humesky29e3bbe2020-11-20 21:30:13 -0500959// WritablePaths is a slice of WritablePath, used for multiple outputs.
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700960type WritablePaths []WritablePath
961
Paul Duffin85d8f0d2021-03-24 10:18:18 +0000962// RelativeToTop creates a new WritablePaths containing the result of calling Path.RelativeToTop on
963// each item in this slice.
964func (p WritablePaths) RelativeToTop() WritablePaths {
965 ensureTestOnly()
966 if p == nil {
967 return p
968 }
969 ret := make(WritablePaths, len(p))
970 for i, path := range p {
971 ret[i] = path.RelativeToTop().(WritablePath)
972 }
973 return ret
974}
975
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700976// Strings returns the string forms of the writable paths.
977func (p WritablePaths) Strings() []string {
978 if p == nil {
979 return nil
980 }
981 ret := make([]string, len(p))
982 for i, path := range p {
983 ret[i] = path.String()
984 }
985 return ret
986}
987
Colin Cross3bc7ffa2017-11-22 16:19:37 -0800988// Paths returns the WritablePaths as a Paths
989func (p WritablePaths) Paths() Paths {
990 if p == nil {
991 return nil
992 }
993 ret := make(Paths, len(p))
994 for i, path := range p {
995 ret[i] = path
996 }
997 return ret
998}
999
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001000type basePath struct {
Paul Duffin74abc5d2021-03-24 09:24:59 +00001001 path string
1002 rel string
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001003}
1004
1005func (p basePath) Ext() string {
1006 return filepath.Ext(p.path)
1007}
1008
Colin Cross4f6fc9c2016-10-26 10:05:25 -07001009func (p basePath) Base() string {
1010 return filepath.Base(p.path)
1011}
1012
Colin Crossfaeb7aa2017-02-01 14:12:44 -08001013func (p basePath) Rel() string {
1014 if p.rel != "" {
1015 return p.rel
1016 }
1017 return p.path
1018}
1019
Colin Cross0875c522017-11-28 17:34:01 -08001020func (p basePath) String() string {
1021 return p.path
1022}
1023
Colin Cross0db55682017-12-05 15:36:55 -08001024func (p basePath) withRel(rel string) basePath {
1025 p.path = filepath.Join(p.path, rel)
1026 p.rel = rel
1027 return p
1028}
1029
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001030// SourcePath is a Path representing a file path rooted from SrcDir
1031type SourcePath struct {
1032 basePath
Paul Duffin580efc82021-03-24 09:04:03 +00001033
1034 // The sources root, i.e. Config.SrcDir()
1035 srcDir string
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001036}
1037
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001038func (p SourcePath) RelativeToTop() Path {
1039 ensureTestOnly()
1040 return p
1041}
1042
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001043var _ Path = SourcePath{}
1044
Colin Cross0db55682017-12-05 15:36:55 -08001045func (p SourcePath) withRel(rel string) SourcePath {
1046 p.basePath = p.basePath.withRel(rel)
1047 return p
1048}
1049
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001050// safePathForSource is for paths that we expect are safe -- only for use by go
1051// code that is embedding ninja variables in paths
Colin Crossfe4bc362018-09-12 10:02:13 -07001052func safePathForSource(ctx PathContext, pathComponents ...string) (SourcePath, error) {
1053 p, err := validateSafePath(pathComponents...)
Lukacs T. Berkif7e36d82021-08-16 17:05:09 +02001054 ret := SourcePath{basePath{p, ""}, "."}
Colin Crossfe4bc362018-09-12 10:02:13 -07001055 if err != nil {
1056 return ret, err
1057 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001058
Colin Cross7b3dcc32019-01-24 13:14:39 -08001059 // absolute path already checked by validateSafePath
Inseob Kim5eb7ee92022-04-27 10:30:34 +09001060 // special-case api surface gen files for now
1061 if strings.HasPrefix(ret.String(), ctx.Config().soongOutDir) && !strings.Contains(ret.String(), ctx.Config().soongOutDir+"/.export") {
Mikhail Naganovab1f5182019-02-08 13:17:55 -08001062 return ret, fmt.Errorf("source path %q is in output", ret.String())
Colin Cross6e18ca42015-07-14 18:55:36 -07001063 }
1064
Colin Crossfe4bc362018-09-12 10:02:13 -07001065 return ret, err
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001066}
1067
Colin Cross192e97a2018-02-22 14:21:02 -08001068// pathForSource creates a SourcePath from pathComponents, but does not check that it exists.
1069func pathForSource(ctx PathContext, pathComponents ...string) (SourcePath, error) {
Colin Crossc48c1432018-02-23 07:09:01 +00001070 p, err := validatePath(pathComponents...)
Lukacs T. Berkif7e36d82021-08-16 17:05:09 +02001071 ret := SourcePath{basePath{p, ""}, "."}
Colin Cross94a32102018-02-22 14:21:02 -08001072 if err != nil {
Colin Cross192e97a2018-02-22 14:21:02 -08001073 return ret, err
Colin Cross94a32102018-02-22 14:21:02 -08001074 }
1075
Colin Cross7b3dcc32019-01-24 13:14:39 -08001076 // absolute path already checked by validatePath
Inseob Kim5eb7ee92022-04-27 10:30:34 +09001077 // special-case for now
1078 if strings.HasPrefix(ret.String(), ctx.Config().soongOutDir) && !strings.Contains(ret.String(), ctx.Config().soongOutDir+"/.export") {
Mikhail Naganovab1f5182019-02-08 13:17:55 -08001079 return ret, fmt.Errorf("source path %q is in output", ret.String())
Colin Crossc48c1432018-02-23 07:09:01 +00001080 }
1081
Colin Cross192e97a2018-02-22 14:21:02 -08001082 return ret, nil
1083}
1084
1085// existsWithDependencies returns true if the path exists, and adds appropriate dependencies to rerun if the
1086// path does not exist.
1087func existsWithDependencies(ctx PathContext, path SourcePath) (exists bool, err error) {
1088 var files []string
1089
1090 if gctx, ok := ctx.(PathGlobContext); ok {
1091 // Use glob to produce proper dependencies, even though we only want
1092 // a single file.
1093 files, err = gctx.GlobWithDeps(path.String(), nil)
1094 } else {
Colin Cross82ea3fb2021-04-05 17:48:26 -07001095 var result pathtools.GlobResult
Colin Cross192e97a2018-02-22 14:21:02 -08001096 // We cannot add build statements in this context, so we fall back to
1097 // AddNinjaFileDeps
Colin Cross82ea3fb2021-04-05 17:48:26 -07001098 result, err = ctx.Config().fs.Glob(path.String(), nil, pathtools.FollowSymlinks)
1099 ctx.AddNinjaFileDeps(result.Deps...)
1100 files = result.Matches
Colin Cross192e97a2018-02-22 14:21:02 -08001101 }
1102
1103 if err != nil {
1104 return false, fmt.Errorf("glob: %s", err.Error())
1105 }
1106
1107 return len(files) > 0, nil
1108}
1109
1110// PathForSource joins the provided path components and validates that the result
1111// neither escapes the source dir nor is in the out dir.
1112// On error, it will return a usable, but invalid SourcePath, and report a ModuleError.
1113func PathForSource(ctx PathContext, pathComponents ...string) SourcePath {
1114 path, err := pathForSource(ctx, pathComponents...)
1115 if err != nil {
1116 reportPathError(ctx, err)
1117 }
1118
Colin Crosse3924e12018-08-15 20:18:53 -07001119 if pathtools.IsGlob(path.String()) {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001120 ReportPathErrorf(ctx, "path may not contain a glob: %s", path.String())
Colin Crosse3924e12018-08-15 20:18:53 -07001121 }
1122
Liz Kammera830f3a2020-11-10 10:50:34 -08001123 if modCtx, ok := ctx.(ModuleMissingDepsPathContext); ok && ctx.Config().AllowMissingDependencies() {
Colin Cross192e97a2018-02-22 14:21:02 -08001124 exists, err := existsWithDependencies(ctx, path)
1125 if err != nil {
1126 reportPathError(ctx, err)
1127 }
1128 if !exists {
1129 modCtx.AddMissingDependencies([]string{path.String()})
1130 }
Colin Cross988414c2020-01-11 01:11:46 +00001131 } else if exists, _, err := ctx.Config().fs.Exists(path.String()); err != nil {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001132 ReportPathErrorf(ctx, "%s: %s", path, err.Error())
Pedro Loureiro5d190cc2021-02-15 15:41:33 +00001133 } else if !exists && !ctx.Config().TestAllowNonExistentPaths {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001134 ReportPathErrorf(ctx, "source path %q does not exist", path)
Colin Cross192e97a2018-02-22 14:21:02 -08001135 }
1136 return path
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001137}
1138
Liz Kammer7aa52882021-02-11 09:16:14 -05001139// ExistentPathForSource returns an OptionalPath with the SourcePath, rooted from SrcDir, *not*
1140// rooted from the module's local source directory, if the path exists, or an empty OptionalPath if
1141// it doesn't exist. Dependencies are added so that the ninja file will be regenerated if the state
1142// of the path changes.
Colin Cross32f38982018-02-22 11:47:25 -08001143func ExistentPathForSource(ctx PathContext, pathComponents ...string) OptionalPath {
Colin Cross192e97a2018-02-22 14:21:02 -08001144 path, err := pathForSource(ctx, pathComponents...)
Colin Cross1ccfcc32018-02-22 13:54:26 -08001145 if err != nil {
1146 reportPathError(ctx, err)
Martin Stjernholmc32dd1c2021-09-15 02:39:00 +01001147 // No need to put the error message into the returned path since it has been reported already.
Colin Cross1ccfcc32018-02-22 13:54:26 -08001148 return OptionalPath{}
1149 }
Colin Crossc48c1432018-02-23 07:09:01 +00001150
Colin Crosse3924e12018-08-15 20:18:53 -07001151 if pathtools.IsGlob(path.String()) {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001152 ReportPathErrorf(ctx, "path may not contain a glob: %s", path.String())
Colin Crosse3924e12018-08-15 20:18:53 -07001153 return OptionalPath{}
1154 }
1155
Colin Cross192e97a2018-02-22 14:21:02 -08001156 exists, err := existsWithDependencies(ctx, path)
Colin Crossc48c1432018-02-23 07:09:01 +00001157 if err != nil {
1158 reportPathError(ctx, err)
1159 return OptionalPath{}
1160 }
Colin Cross192e97a2018-02-22 14:21:02 -08001161 if !exists {
Martin Stjernholmc32dd1c2021-09-15 02:39:00 +01001162 return InvalidOptionalPath(path.String() + " does not exist")
Colin Crossc48c1432018-02-23 07:09:01 +00001163 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001164 return OptionalPathForPath(path)
1165}
1166
1167func (p SourcePath) String() string {
Paul Duffin580efc82021-03-24 09:04:03 +00001168 return filepath.Join(p.srcDir, p.path)
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001169}
1170
1171// Join creates a new SourcePath with paths... joined with the current path. The
1172// provided paths... may not use '..' to escape from the current path.
1173func (p SourcePath) Join(ctx PathContext, paths ...string) SourcePath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001174 path, err := validatePath(paths...)
1175 if err != nil {
1176 reportPathError(ctx, err)
1177 }
Colin Cross0db55682017-12-05 15:36:55 -08001178 return p.withRel(path)
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001179}
1180
Colin Cross2fafa3e2019-03-05 12:39:51 -08001181// join is like Join but does less path validation.
1182func (p SourcePath) join(ctx PathContext, paths ...string) SourcePath {
1183 path, err := validateSafePath(paths...)
1184 if err != nil {
1185 reportPathError(ctx, err)
1186 }
1187 return p.withRel(path)
1188}
1189
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001190// OverlayPath returns the overlay for `path' if it exists. This assumes that the
1191// SourcePath is the path to a resource overlay directory.
Liz Kammera830f3a2020-11-10 10:50:34 -08001192func (p SourcePath) OverlayPath(ctx ModuleMissingDepsPathContext, path Path) OptionalPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001193 var relDir string
Colin Cross07e51612019-03-05 12:46:40 -08001194 if srcPath, ok := path.(SourcePath); ok {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001195 relDir = srcPath.path
1196 } else {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001197 ReportPathErrorf(ctx, "Cannot find relative path for %s(%s)", reflect.TypeOf(path).Name(), path)
Martin Stjernholmc32dd1c2021-09-15 02:39:00 +01001198 // No need to put the error message into the returned path since it has been reported already.
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001199 return OptionalPath{}
1200 }
Paul Duffin580efc82021-03-24 09:04:03 +00001201 dir := filepath.Join(p.srcDir, p.path, relDir)
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001202 // Use Glob so that we are run again if the directory is added.
Colin Cross7f19f372016-11-01 11:10:25 -07001203 if pathtools.IsGlob(dir) {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001204 ReportPathErrorf(ctx, "Path may not contain a glob: %s", dir)
Dan Willemsen7b310ee2015-12-18 15:11:17 -08001205 }
Colin Cross461b4452018-02-23 09:22:42 -08001206 paths, err := ctx.GlobWithDeps(dir, nil)
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001207 if err != nil {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001208 ReportPathErrorf(ctx, "glob: %s", err.Error())
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001209 return OptionalPath{}
1210 }
1211 if len(paths) == 0 {
Martin Stjernholmc32dd1c2021-09-15 02:39:00 +01001212 return InvalidOptionalPath(dir + " does not exist")
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001213 }
Paul Duffin580efc82021-03-24 09:04:03 +00001214 relPath := Rel(ctx, p.srcDir, paths[0])
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001215 return OptionalPathForPath(PathForSource(ctx, relPath))
1216}
1217
Colin Cross70dda7e2019-10-01 22:05:35 -07001218// OutputPath is a Path representing an intermediates file path rooted from the build directory
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001219type OutputPath struct {
1220 basePath
Paul Duffind65c58b2021-03-24 09:22:07 +00001221
Lukacs T. Berkib078ade2021-08-31 10:42:08 +02001222 // The soong build directory, i.e. Config.SoongOutDir()
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02001223 soongOutDir string
Paul Duffind65c58b2021-03-24 09:22:07 +00001224
Colin Crossd63c9a72020-01-29 16:52:50 -08001225 fullPath string
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001226}
1227
Colin Cross702e0f82017-10-18 17:27:54 -07001228func (p OutputPath) withRel(rel string) OutputPath {
Colin Cross0db55682017-12-05 15:36:55 -08001229 p.basePath = p.basePath.withRel(rel)
Colin Crossd63c9a72020-01-29 16:52:50 -08001230 p.fullPath = filepath.Join(p.fullPath, rel)
Colin Cross702e0f82017-10-18 17:27:54 -07001231 return p
1232}
1233
Colin Cross3063b782018-08-15 11:19:12 -07001234func (p OutputPath) WithoutRel() OutputPath {
1235 p.basePath.rel = filepath.Base(p.basePath.path)
1236 return p
1237}
1238
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02001239func (p OutputPath) getSoongOutDir() string {
1240 return p.soongOutDir
Paul Duffin9b478b02019-12-10 13:41:51 +00001241}
1242
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001243func (p OutputPath) RelativeToTop() Path {
1244 return p.outputPathRelativeToTop()
1245}
1246
1247func (p OutputPath) outputPathRelativeToTop() OutputPath {
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02001248 p.fullPath = StringPathRelativeToTop(p.soongOutDir, p.fullPath)
1249 p.soongOutDir = OutSoongDir
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001250 return p
1251}
1252
Paul Duffin0267d492021-02-02 10:05:52 +00001253func (p OutputPath) objPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleObjPath {
1254 return PathForModuleObj(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
1255}
1256
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001257var _ Path = OutputPath{}
Paul Duffin9b478b02019-12-10 13:41:51 +00001258var _ WritablePath = OutputPath{}
Paul Duffin0267d492021-02-02 10:05:52 +00001259var _ objPathProvider = OutputPath{}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001260
Chris Parsons8f232a22020-06-23 17:37:05 -04001261// toolDepPath is a Path representing a dependency of the build tool.
1262type toolDepPath struct {
1263 basePath
1264}
1265
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001266func (t toolDepPath) RelativeToTop() Path {
1267 ensureTestOnly()
1268 return t
1269}
1270
Chris Parsons8f232a22020-06-23 17:37:05 -04001271var _ Path = toolDepPath{}
1272
1273// pathForBuildToolDep returns a toolDepPath representing the given path string.
1274// There is no validation for the path, as it is "trusted": It may fail
1275// normal validation checks. For example, it may be an absolute path.
1276// Only use this function to construct paths for dependencies of the build
1277// tool invocation.
1278func pathForBuildToolDep(ctx PathContext, path string) toolDepPath {
Paul Duffin74abc5d2021-03-24 09:24:59 +00001279 return toolDepPath{basePath{path, ""}}
Chris Parsons8f232a22020-06-23 17:37:05 -04001280}
1281
Jeff Gaston734e3802017-04-10 15:47:24 -07001282// PathForOutput joins the provided paths and returns an OutputPath that is
1283// validated to not escape the build dir.
1284// On error, it will return a usable, but invalid OutputPath, and report a ModuleError.
1285func PathForOutput(ctx PathContext, pathComponents ...string) OutputPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001286 path, err := validatePath(pathComponents...)
1287 if err != nil {
1288 reportPathError(ctx, err)
1289 }
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02001290 fullPath := filepath.Join(ctx.Config().soongOutDir, path)
Colin Crossd63c9a72020-01-29 16:52:50 -08001291 path = fullPath[len(fullPath)-len(path):]
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02001292 return OutputPath{basePath{path, ""}, ctx.Config().soongOutDir, fullPath}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001293}
1294
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02001295// PathsForOutput returns Paths rooted from soongOutDir
Colin Cross40e33732019-02-15 11:08:35 -08001296func PathsForOutput(ctx PathContext, paths []string) WritablePaths {
1297 ret := make(WritablePaths, len(paths))
1298 for i, path := range paths {
1299 ret[i] = PathForOutput(ctx, path)
1300 }
1301 return ret
1302}
1303
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001304func (p OutputPath) writablePath() {}
1305
1306func (p OutputPath) String() string {
Colin Crossd63c9a72020-01-29 16:52:50 -08001307 return p.fullPath
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001308}
1309
1310// Join creates a new OutputPath with paths... joined with the current path. The
1311// provided paths... may not use '..' to escape from the current path.
1312func (p OutputPath) Join(ctx PathContext, paths ...string) OutputPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001313 path, err := validatePath(paths...)
1314 if err != nil {
1315 reportPathError(ctx, err)
1316 }
Colin Cross0db55682017-12-05 15:36:55 -08001317 return p.withRel(path)
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001318}
1319
Colin Cross8854a5a2019-02-11 14:14:16 -08001320// ReplaceExtension creates a new OutputPath with the extension replaced with ext.
1321func (p OutputPath) ReplaceExtension(ctx PathContext, ext string) OutputPath {
1322 if strings.Contains(ext, "/") {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001323 ReportPathErrorf(ctx, "extension %q cannot contain /", ext)
Colin Cross8854a5a2019-02-11 14:14:16 -08001324 }
1325 ret := PathForOutput(ctx, pathtools.ReplaceExtension(p.path, ext))
Colin Cross2cdd5df2019-02-25 10:25:24 -08001326 ret.rel = pathtools.ReplaceExtension(p.rel, ext)
Colin Cross8854a5a2019-02-11 14:14:16 -08001327 return ret
1328}
1329
Colin Cross40e33732019-02-15 11:08:35 -08001330// InSameDir creates a new OutputPath from the directory of the current OutputPath joined with the elements in paths.
1331func (p OutputPath) InSameDir(ctx PathContext, paths ...string) OutputPath {
1332 path, err := validatePath(paths...)
1333 if err != nil {
1334 reportPathError(ctx, err)
1335 }
1336
1337 ret := PathForOutput(ctx, filepath.Dir(p.path), path)
Colin Cross2cdd5df2019-02-25 10:25:24 -08001338 ret.rel = filepath.Join(filepath.Dir(p.rel), path)
Colin Cross40e33732019-02-15 11:08:35 -08001339 return ret
1340}
1341
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001342// PathForIntermediates returns an OutputPath representing the top-level
1343// intermediates directory.
1344func PathForIntermediates(ctx PathContext, paths ...string) OutputPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001345 path, err := validatePath(paths...)
1346 if err != nil {
1347 reportPathError(ctx, err)
1348 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001349 return PathForOutput(ctx, ".intermediates", path)
1350}
1351
Colin Cross07e51612019-03-05 12:46:40 -08001352var _ genPathProvider = SourcePath{}
1353var _ objPathProvider = SourcePath{}
1354var _ resPathProvider = SourcePath{}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001355
Colin Cross07e51612019-03-05 12:46:40 -08001356// PathForModuleSrc returns a Path representing the paths... under the
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001357// module's local source directory.
Liz Kammera830f3a2020-11-10 10:50:34 -08001358func PathForModuleSrc(ctx ModuleMissingDepsPathContext, pathComponents ...string) Path {
Paul Duffin407501b2021-07-09 16:56:35 +01001359 // Just join the components textually just to make sure that it does not corrupt a fully qualified
1360 // module reference, e.g. if the pathComponents is "://other:foo" then using filepath.Join() or
1361 // validatePath() will corrupt it, e.g. replace "//" with "/". If the path is not a module
1362 // reference then it will be validated by expandOneSrcPath anyway when it calls expandOneSrcPath.
1363 p := strings.Join(pathComponents, string(filepath.Separator))
Liz Kammer619be462022-01-28 15:13:39 -05001364 paths, err := expandOneSrcPath(sourcePathInput{context: ctx, path: p, includeDirs: true})
Colin Cross8a497952019-03-05 22:25:09 -08001365 if err != nil {
1366 if depErr, ok := err.(missingDependencyError); ok {
1367 if ctx.Config().AllowMissingDependencies() {
1368 ctx.AddMissingDependencies(depErr.missingDeps)
1369 } else {
1370 ctx.ModuleErrorf(`%s, is the property annotated with android:"path"?`, depErr.Error())
1371 }
1372 } else {
1373 reportPathError(ctx, err)
1374 }
1375 return nil
1376 } else if len(paths) == 0 {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001377 ReportPathErrorf(ctx, "%q produced no files, expected exactly one", p)
Colin Cross8a497952019-03-05 22:25:09 -08001378 return nil
1379 } else if len(paths) > 1 {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001380 ReportPathErrorf(ctx, "%q produced %d files, expected exactly one", p, len(paths))
Colin Cross8a497952019-03-05 22:25:09 -08001381 }
1382 return paths[0]
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001383}
1384
Liz Kammera830f3a2020-11-10 10:50:34 -08001385func pathForModuleSrc(ctx EarlyModulePathContext, paths ...string) SourcePath {
Colin Cross07e51612019-03-05 12:46:40 -08001386 p, err := validatePath(paths...)
1387 if err != nil {
1388 reportPathError(ctx, err)
1389 }
1390
1391 path, err := pathForSource(ctx, ctx.ModuleDir(), p)
1392 if err != nil {
1393 reportPathError(ctx, err)
1394 }
1395
1396 path.basePath.rel = p
1397
1398 return path
1399}
1400
Colin Cross2fafa3e2019-03-05 12:39:51 -08001401// PathsWithModuleSrcSubDir takes a list of Paths and returns a new list of Paths where Rel() on each path
1402// will return the path relative to subDir in the module's source directory. If any input paths are not located
1403// inside subDir then a path error will be reported.
Liz Kammera830f3a2020-11-10 10:50:34 -08001404func PathsWithModuleSrcSubDir(ctx EarlyModulePathContext, paths Paths, subDir string) Paths {
Colin Cross2fafa3e2019-03-05 12:39:51 -08001405 paths = append(Paths(nil), paths...)
Colin Cross07e51612019-03-05 12:46:40 -08001406 subDirFullPath := pathForModuleSrc(ctx, subDir)
Colin Cross2fafa3e2019-03-05 12:39:51 -08001407 for i, path := range paths {
1408 rel := Rel(ctx, subDirFullPath.String(), path.String())
1409 paths[i] = subDirFullPath.join(ctx, rel)
1410 }
1411 return paths
1412}
1413
1414// PathWithModuleSrcSubDir takes a Path and returns a Path where Rel() will return the path relative to subDir in the
1415// 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 -08001416func PathWithModuleSrcSubDir(ctx EarlyModulePathContext, path Path, subDir string) Path {
Colin Cross07e51612019-03-05 12:46:40 -08001417 subDirFullPath := pathForModuleSrc(ctx, subDir)
Colin Cross2fafa3e2019-03-05 12:39:51 -08001418 rel := Rel(ctx, subDirFullPath.String(), path.String())
1419 return subDirFullPath.Join(ctx, rel)
1420}
1421
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001422// OptionalPathForModuleSrc returns an OptionalPath. The OptionalPath contains a
1423// valid path if p is non-nil.
Liz Kammera830f3a2020-11-10 10:50:34 -08001424func OptionalPathForModuleSrc(ctx ModuleMissingDepsPathContext, p *string) OptionalPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001425 if p == nil {
1426 return OptionalPath{}
1427 }
1428 return OptionalPathForPath(PathForModuleSrc(ctx, *p))
1429}
1430
Liz Kammera830f3a2020-11-10 10:50:34 -08001431func (p SourcePath) genPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleGenPath {
Colin Cross7fc17db2017-02-01 14:07:55 -08001432 return PathForModuleGen(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001433}
1434
Liz Kammera830f3a2020-11-10 10:50:34 -08001435func (p SourcePath) objPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleObjPath {
Colin Cross7fc17db2017-02-01 14:07:55 -08001436 return PathForModuleObj(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001437}
1438
Liz Kammera830f3a2020-11-10 10:50:34 -08001439func (p SourcePath) resPathWithName(ctx ModuleOutPathContext, name string) ModuleResPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001440 // TODO: Use full directory if the new ctx is not the current ctx?
1441 return PathForModuleRes(ctx, p.path, name)
1442}
1443
1444// ModuleOutPath is a Path representing a module's output directory.
1445type ModuleOutPath struct {
1446 OutputPath
1447}
1448
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001449func (p ModuleOutPath) RelativeToTop() Path {
1450 p.OutputPath = p.outputPathRelativeToTop()
1451 return p
1452}
1453
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001454var _ Path = ModuleOutPath{}
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001455var _ WritablePath = ModuleOutPath{}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001456
Liz Kammera830f3a2020-11-10 10:50:34 -08001457func (p ModuleOutPath) objPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleObjPath {
Pete Bentleyfcf55bf2019-08-16 20:14:32 +01001458 return PathForModuleObj(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
1459}
1460
Liz Kammera830f3a2020-11-10 10:50:34 -08001461// ModuleOutPathContext Subset of ModuleContext functions necessary for output path methods.
1462type ModuleOutPathContext interface {
1463 PathContext
1464
1465 ModuleName() string
1466 ModuleDir() string
1467 ModuleSubDir() string
1468}
1469
1470func pathForModuleOut(ctx ModuleOutPathContext) OutputPath {
Colin Cross702e0f82017-10-18 17:27:54 -07001471 return PathForOutput(ctx, ".intermediates", ctx.ModuleDir(), ctx.ModuleName(), ctx.ModuleSubDir())
1472}
1473
Logan Chien7eefdc42018-07-11 18:10:41 +08001474// PathForVndkRefAbiDump returns an OptionalPath representing the path of the
1475// reference abi dump for the given module. This is not guaranteed to be valid.
Liz Kammera830f3a2020-11-10 10:50:34 -08001476func PathForVndkRefAbiDump(ctx ModuleInstallPathContext, version, fileName string,
Hsin-Yi Chen53489642019-07-31 17:10:45 +08001477 isNdk, isLlndkOrVndk, isGzip bool) OptionalPath {
Logan Chien7eefdc42018-07-11 18:10:41 +08001478
Hsin-Yi Chenee68c432022-03-09 15:18:19 +08001479 currentArchType := ctx.Arch().ArchType
1480 primaryArchType := ctx.Config().DevicePrimaryArchType()
1481 archName := currentArchType.String()
1482 if currentArchType != primaryArchType {
1483 archName += "_" + primaryArchType.String()
Jayant Chowdharyac066c62018-02-20 10:53:31 -08001484 }
Logan Chien5237bed2018-07-11 17:15:57 +08001485
1486 var dirName string
Hsin-Yi Chen53489642019-07-31 17:10:45 +08001487 if isNdk {
Logan Chien5237bed2018-07-11 17:15:57 +08001488 dirName = "ndk"
Hsin-Yi Chen53489642019-07-31 17:10:45 +08001489 } else if isLlndkOrVndk {
Logan Chien5237bed2018-07-11 17:15:57 +08001490 dirName = "vndk"
Logan Chien41eabe62019-04-10 13:33:58 +08001491 } else {
1492 dirName = "platform" // opt-in libs
Jayant Chowdhary3e231fd2017-02-08 13:45:53 -08001493 }
Logan Chien5237bed2018-07-11 17:15:57 +08001494
Jayant Chowdhary34ce67d2018-03-08 11:00:50 -08001495 binderBitness := ctx.DeviceConfig().BinderBitness()
Logan Chien7eefdc42018-07-11 18:10:41 +08001496
1497 var ext string
1498 if isGzip {
1499 ext = ".lsdump.gz"
1500 } else {
1501 ext = ".lsdump"
1502 }
1503
1504 return ExistentPathForSource(ctx, "prebuilts", "abi-dumps", dirName,
Hsin-Yi Chenee68c432022-03-09 15:18:19 +08001505 version, binderBitness, archName, "source-based",
Logan Chien7eefdc42018-07-11 18:10:41 +08001506 fileName+ext)
Jayant Chowdhary3e231fd2017-02-08 13:45:53 -08001507}
1508
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001509// PathForModuleOut returns a Path representing the paths... under the module's
1510// output directory.
Liz Kammera830f3a2020-11-10 10:50:34 -08001511func PathForModuleOut(ctx ModuleOutPathContext, paths ...string) ModuleOutPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001512 p, err := validatePath(paths...)
1513 if err != nil {
1514 reportPathError(ctx, err)
1515 }
Colin Cross702e0f82017-10-18 17:27:54 -07001516 return ModuleOutPath{
Liz Kammera830f3a2020-11-10 10:50:34 -08001517 OutputPath: pathForModuleOut(ctx).withRel(p),
Colin Cross702e0f82017-10-18 17:27:54 -07001518 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001519}
1520
1521// ModuleGenPath is a Path representing the 'gen' directory in a module's output
1522// directory. Mainly used for generated sources.
1523type ModuleGenPath struct {
1524 ModuleOutPath
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001525}
1526
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001527func (p ModuleGenPath) RelativeToTop() Path {
1528 p.OutputPath = p.outputPathRelativeToTop()
1529 return p
1530}
1531
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001532var _ Path = ModuleGenPath{}
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001533var _ WritablePath = ModuleGenPath{}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001534var _ genPathProvider = ModuleGenPath{}
1535var _ objPathProvider = ModuleGenPath{}
1536
1537// PathForModuleGen returns a Path representing the paths... under the module's
1538// `gen' directory.
Liz Kammera830f3a2020-11-10 10:50:34 -08001539func PathForModuleGen(ctx ModuleOutPathContext, paths ...string) ModuleGenPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001540 p, err := validatePath(paths...)
1541 if err != nil {
1542 reportPathError(ctx, err)
1543 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001544 return ModuleGenPath{
Colin Cross702e0f82017-10-18 17:27:54 -07001545 ModuleOutPath: ModuleOutPath{
Liz Kammera830f3a2020-11-10 10:50:34 -08001546 OutputPath: pathForModuleOut(ctx).withRel("gen").withRel(p),
Colin Cross702e0f82017-10-18 17:27:54 -07001547 },
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001548 }
1549}
1550
Liz Kammera830f3a2020-11-10 10:50:34 -08001551func (p ModuleGenPath) genPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleGenPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001552 // TODO: make a different path for local vs remote generated files?
Dan Willemsen21ec4902016-11-02 20:43:13 -07001553 return PathForModuleGen(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001554}
1555
Liz Kammera830f3a2020-11-10 10:50:34 -08001556func (p ModuleGenPath) objPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleObjPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001557 return PathForModuleObj(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
1558}
1559
1560// ModuleObjPath is a Path representing the 'obj' directory in a module's output
1561// directory. Used for compiled objects.
1562type ModuleObjPath struct {
1563 ModuleOutPath
1564}
1565
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001566func (p ModuleObjPath) RelativeToTop() Path {
1567 p.OutputPath = p.outputPathRelativeToTop()
1568 return p
1569}
1570
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001571var _ Path = ModuleObjPath{}
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001572var _ WritablePath = ModuleObjPath{}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001573
1574// PathForModuleObj returns a Path representing the paths... under the module's
1575// 'obj' directory.
Liz Kammera830f3a2020-11-10 10:50:34 -08001576func PathForModuleObj(ctx ModuleOutPathContext, pathComponents ...string) ModuleObjPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001577 p, err := validatePath(pathComponents...)
1578 if err != nil {
1579 reportPathError(ctx, err)
1580 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001581 return ModuleObjPath{PathForModuleOut(ctx, "obj", p)}
1582}
1583
1584// ModuleResPath is a a Path representing the 'res' directory in a module's
1585// output directory.
1586type ModuleResPath struct {
1587 ModuleOutPath
1588}
1589
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001590func (p ModuleResPath) RelativeToTop() Path {
1591 p.OutputPath = p.outputPathRelativeToTop()
1592 return p
1593}
1594
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001595var _ Path = ModuleResPath{}
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001596var _ WritablePath = ModuleResPath{}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001597
1598// PathForModuleRes returns a Path representing the paths... under the module's
1599// 'res' directory.
Liz Kammera830f3a2020-11-10 10:50:34 -08001600func PathForModuleRes(ctx ModuleOutPathContext, pathComponents ...string) ModuleResPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001601 p, err := validatePath(pathComponents...)
1602 if err != nil {
1603 reportPathError(ctx, err)
1604 }
1605
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001606 return ModuleResPath{PathForModuleOut(ctx, "res", p)}
1607}
1608
Colin Cross70dda7e2019-10-01 22:05:35 -07001609// InstallPath is a Path representing a installed file path rooted from the build directory
1610type InstallPath struct {
1611 basePath
Colin Crossff6c33d2019-10-02 16:01:35 -07001612
Lukacs T. Berkib078ade2021-08-31 10:42:08 +02001613 // The soong build directory, i.e. Config.SoongOutDir()
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02001614 soongOutDir string
Paul Duffind65c58b2021-03-24 09:22:07 +00001615
Jiyong Park957bcd92020-10-20 18:23:33 +09001616 // partitionDir is the part of the InstallPath that is automatically determined according to the context.
1617 // For example, it is host/<os>-<arch> for host modules, and target/product/<device>/<partition> for device modules.
1618 partitionDir string
1619
Colin Crossb1692a32021-10-25 15:39:01 -07001620 partition string
1621
Jiyong Park957bcd92020-10-20 18:23:33 +09001622 // makePath indicates whether this path is for Soong (false) or Make (true).
1623 makePath bool
Colin Cross70dda7e2019-10-01 22:05:35 -07001624}
1625
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001626// Will panic if called from outside a test environment.
1627func ensureTestOnly() {
Martin Stjernholm32312eb2021-03-27 18:54:49 +00001628 if PrefixInList(os.Args, "-test.") {
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001629 return
1630 }
Martin Stjernholm32312eb2021-03-27 18:54:49 +00001631 panic(fmt.Errorf("Not in test. Command line:\n %s", strings.Join(os.Args, "\n ")))
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001632}
1633
1634func (p InstallPath) RelativeToTop() Path {
1635 ensureTestOnly()
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02001636 p.soongOutDir = OutSoongDir
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001637 return p
1638}
1639
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02001640func (p InstallPath) getSoongOutDir() string {
1641 return p.soongOutDir
Paul Duffin9b478b02019-12-10 13:41:51 +00001642}
1643
Hans MÃ¥nssond3f2bd72020-11-27 12:37:28 +01001644func (p InstallPath) ReplaceExtension(ctx PathContext, ext string) OutputPath {
1645 panic("Not implemented")
1646}
1647
Paul Duffin9b478b02019-12-10 13:41:51 +00001648var _ Path = InstallPath{}
1649var _ WritablePath = InstallPath{}
1650
Colin Cross70dda7e2019-10-01 22:05:35 -07001651func (p InstallPath) writablePath() {}
1652
1653func (p InstallPath) String() string {
Jiyong Park957bcd92020-10-20 18:23:33 +09001654 if p.makePath {
1655 // Make path starts with out/ instead of out/soong.
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02001656 return filepath.Join(p.soongOutDir, "../", p.path)
Jiyong Park957bcd92020-10-20 18:23:33 +09001657 } else {
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02001658 return filepath.Join(p.soongOutDir, p.path)
Jiyong Park957bcd92020-10-20 18:23:33 +09001659 }
1660}
1661
1662// PartitionDir returns the path to the partition where the install path is rooted at. It is
1663// out/soong/target/product/<device>/<partition> for device modules, and out/soong/host/<os>-<arch> for host modules.
1664// The ./soong is dropped if the install path is for Make.
1665func (p InstallPath) PartitionDir() string {
1666 if p.makePath {
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02001667 return filepath.Join(p.soongOutDir, "../", p.partitionDir)
Jiyong Park957bcd92020-10-20 18:23:33 +09001668 } else {
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02001669 return filepath.Join(p.soongOutDir, p.partitionDir)
Jiyong Park957bcd92020-10-20 18:23:33 +09001670 }
Colin Cross70dda7e2019-10-01 22:05:35 -07001671}
1672
1673// Join creates a new InstallPath with paths... joined with the current path. The
1674// provided paths... may not use '..' to escape from the current path.
1675func (p InstallPath) Join(ctx PathContext, paths ...string) InstallPath {
1676 path, err := validatePath(paths...)
1677 if err != nil {
1678 reportPathError(ctx, err)
1679 }
1680 return p.withRel(path)
1681}
1682
1683func (p InstallPath) withRel(rel string) InstallPath {
1684 p.basePath = p.basePath.withRel(rel)
1685 return p
1686}
1687
Colin Crossc68db4b2021-11-11 18:59:15 -08001688// Deprecated: ToMakePath is a noop, PathForModuleInstall always returns Make paths when building
1689// embedded in Make.
Colin Crossff6c33d2019-10-02 16:01:35 -07001690func (p InstallPath) ToMakePath() InstallPath {
Jiyong Park957bcd92020-10-20 18:23:33 +09001691 p.makePath = true
Colin Crossff6c33d2019-10-02 16:01:35 -07001692 return p
Colin Cross70dda7e2019-10-01 22:05:35 -07001693}
1694
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001695// PathForModuleInstall returns a Path representing the install path for the
1696// module appended with paths...
Colin Cross70dda7e2019-10-01 22:05:35 -07001697func PathForModuleInstall(ctx ModuleInstallPathContext, pathComponents ...string) InstallPath {
Spandan Das5d1b9292021-06-03 19:36:41 +00001698 os, arch := osAndArch(ctx)
1699 partition := modulePartition(ctx, os)
1700 return makePathForInstall(ctx, os, arch, partition, ctx.Debug(), pathComponents...)
1701}
1702
Colin Cross1d0eb7a2021-11-03 14:08:20 -07001703// PathForHostDexInstall returns an InstallPath representing the install path for the
1704// module appended with paths...
1705func PathForHostDexInstall(ctx ModuleInstallPathContext, pathComponents ...string) InstallPath {
1706 return makePathForInstall(ctx, ctx.Config().BuildOS, ctx.Config().BuildArch, "", ctx.Debug(), pathComponents...)
1707}
1708
Spandan Das5d1b9292021-06-03 19:36:41 +00001709// PathForModuleInPartitionInstall is similar to PathForModuleInstall but partition is provided by the caller
1710func PathForModuleInPartitionInstall(ctx ModuleInstallPathContext, partition string, pathComponents ...string) InstallPath {
1711 os, arch := osAndArch(ctx)
1712 return makePathForInstall(ctx, os, arch, partition, ctx.Debug(), pathComponents...)
1713}
1714
1715func osAndArch(ctx ModuleInstallPathContext) (OsType, ArchType) {
Colin Cross6e359402020-02-10 15:29:54 -08001716 os := ctx.Os()
Jiyong Park87788b52020-09-01 12:37:45 +09001717 arch := ctx.Arch().ArchType
1718 forceOS, forceArch := ctx.InstallForceOS()
1719 if forceOS != nil {
Colin Cross6e359402020-02-10 15:29:54 -08001720 os = *forceOS
1721 }
Jiyong Park87788b52020-09-01 12:37:45 +09001722 if forceArch != nil {
1723 arch = *forceArch
1724 }
Spandan Das5d1b9292021-06-03 19:36:41 +00001725 return os, arch
1726}
Colin Cross609c49a2020-02-13 13:20:11 -08001727
Spandan Das5d1b9292021-06-03 19:36:41 +00001728func makePathForInstall(ctx ModuleInstallPathContext, os OsType, arch ArchType, partition string, debug bool, pathComponents ...string) InstallPath {
1729 ret := pathForInstall(ctx, os, arch, partition, debug, pathComponents...)
Colin Cross609c49a2020-02-13 13:20:11 -08001730 return ret
1731}
1732
Jiyong Park87788b52020-09-01 12:37:45 +09001733func pathForInstall(ctx PathContext, os OsType, arch ArchType, partition string, debug bool,
Colin Cross609c49a2020-02-13 13:20:11 -08001734 pathComponents ...string) InstallPath {
1735
Jiyong Park957bcd92020-10-20 18:23:33 +09001736 var partionPaths []string
Colin Cross609c49a2020-02-13 13:20:11 -08001737
Colin Cross6e359402020-02-10 15:29:54 -08001738 if os.Class == Device {
Jiyong Park957bcd92020-10-20 18:23:33 +09001739 partionPaths = []string{"target", "product", ctx.Config().DeviceName(), partition}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001740 } else {
Jiyong Park87788b52020-09-01 12:37:45 +09001741 osName := os.String()
Colin Cross528d67e2021-07-23 22:23:07 +00001742 if os == Linux || os == LinuxMusl {
Jiyong Park87788b52020-09-01 12:37:45 +09001743 // instead of linux_glibc
1744 osName = "linux"
Dan Willemsen866b5632017-09-22 12:28:24 -07001745 }
Jiyong Park87788b52020-09-01 12:37:45 +09001746 // SOONG_HOST_OUT is set to out/host/$(HOST_OS)-$(HOST_PREBUILT_ARCH)
1747 // and HOST_PREBUILT_ARCH is forcibly set to x86 even on x86_64 hosts. We don't seem
1748 // to have a plan to fix it (see the comment in build/make/core/envsetup.mk).
1749 // Let's keep using x86 for the existing cases until we have a need to support
1750 // other architectures.
1751 archName := arch.String()
1752 if os.Class == Host && (arch == X86_64 || arch == Common) {
1753 archName = "x86"
1754 }
Jiyong Park957bcd92020-10-20 18:23:33 +09001755 partionPaths = []string{"host", osName + "-" + archName, partition}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001756 }
Colin Cross609c49a2020-02-13 13:20:11 -08001757 if debug {
Jiyong Park957bcd92020-10-20 18:23:33 +09001758 partionPaths = append([]string{"debug"}, partionPaths...)
Dan Willemsen782a2d12015-12-21 14:55:28 -08001759 }
Colin Cross70dda7e2019-10-01 22:05:35 -07001760
Jiyong Park957bcd92020-10-20 18:23:33 +09001761 partionPath, err := validatePath(partionPaths...)
Colin Cross70dda7e2019-10-01 22:05:35 -07001762 if err != nil {
1763 reportPathError(ctx, err)
1764 }
Colin Crossff6c33d2019-10-02 16:01:35 -07001765
Jiyong Park957bcd92020-10-20 18:23:33 +09001766 base := InstallPath{
Paul Duffin74abc5d2021-03-24 09:24:59 +00001767 basePath: basePath{partionPath, ""},
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02001768 soongOutDir: ctx.Config().soongOutDir,
Jiyong Park957bcd92020-10-20 18:23:33 +09001769 partitionDir: partionPath,
Colin Crossb1692a32021-10-25 15:39:01 -07001770 partition: partition,
Colin Crossc68db4b2021-11-11 18:59:15 -08001771 }
1772
1773 if ctx.Config().KatiEnabled() {
1774 base.makePath = true
Jiyong Park957bcd92020-10-20 18:23:33 +09001775 }
Colin Crossff6c33d2019-10-02 16:01:35 -07001776
Jiyong Park957bcd92020-10-20 18:23:33 +09001777 return base.Join(ctx, pathComponents...)
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001778}
1779
Nicolas Geoffray1228e9c2020-02-27 13:45:35 +00001780func pathForNdkOrSdkInstall(ctx PathContext, prefix string, paths []string) InstallPath {
Jiyong Park957bcd92020-10-20 18:23:33 +09001781 base := InstallPath{
Paul Duffin74abc5d2021-03-24 09:24:59 +00001782 basePath: basePath{prefix, ""},
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02001783 soongOutDir: ctx.Config().soongOutDir,
Jiyong Park957bcd92020-10-20 18:23:33 +09001784 partitionDir: prefix,
1785 makePath: false,
Colin Cross70dda7e2019-10-01 22:05:35 -07001786 }
Jiyong Park957bcd92020-10-20 18:23:33 +09001787 return base.Join(ctx, paths...)
Colin Cross70dda7e2019-10-01 22:05:35 -07001788}
1789
Nicolas Geoffray1228e9c2020-02-27 13:45:35 +00001790func PathForNdkInstall(ctx PathContext, paths ...string) InstallPath {
1791 return pathForNdkOrSdkInstall(ctx, "ndk", paths)
1792}
1793
1794func PathForMainlineSdksInstall(ctx PathContext, paths ...string) InstallPath {
1795 return pathForNdkOrSdkInstall(ctx, "mainline-sdks", paths)
1796}
1797
Colin Cross70dda7e2019-10-01 22:05:35 -07001798func InstallPathToOnDevicePath(ctx PathContext, path InstallPath) string {
Colin Crossb1692a32021-10-25 15:39:01 -07001799 rel := Rel(ctx, strings.TrimSuffix(path.PartitionDir(), path.partition), path.String())
Colin Cross43f08db2018-11-12 10:13:39 -08001800 return "/" + rel
1801}
1802
Colin Cross6e359402020-02-10 15:29:54 -08001803func modulePartition(ctx ModuleInstallPathContext, os OsType) string {
Colin Cross43f08db2018-11-12 10:13:39 -08001804 var partition string
Colin Cross6e359402020-02-10 15:29:54 -08001805 if ctx.InstallInTestcases() {
1806 // "testcases" install directory can be used for host or device modules.
Jaewoong Jung0949f312019-09-11 10:25:18 -07001807 partition = "testcases"
Colin Cross6e359402020-02-10 15:29:54 -08001808 } else if os.Class == Device {
1809 if ctx.InstallInData() {
1810 partition = "data"
1811 } else if ctx.InstallInRamdisk() {
1812 if ctx.DeviceConfig().BoardUsesRecoveryAsBoot() {
1813 partition = "recovery/root/first_stage_ramdisk"
1814 } else {
1815 partition = "ramdisk"
1816 }
1817 if !ctx.InstallInRoot() {
1818 partition += "/system"
1819 }
Yifan Hong60e0cfb2020-10-21 15:17:56 -07001820 } else if ctx.InstallInVendorRamdisk() {
Yifan Hong39143a92020-10-26 12:43:12 -07001821 // The module is only available after switching root into
1822 // /first_stage_ramdisk. To expose the module before switching root
1823 // on a device without a dedicated recovery partition, install the
1824 // recovery variant.
Yifan Hongdd8dacc2020-10-21 15:40:17 -07001825 if ctx.DeviceConfig().BoardMoveRecoveryResourcesToVendorBoot() {
Petri Gyntherac229562021-03-02 23:44:02 -08001826 partition = "vendor_ramdisk/first_stage_ramdisk"
Yifan Hongdd8dacc2020-10-21 15:40:17 -07001827 } else {
Petri Gyntherac229562021-03-02 23:44:02 -08001828 partition = "vendor_ramdisk"
Yifan Hongdd8dacc2020-10-21 15:40:17 -07001829 }
1830 if !ctx.InstallInRoot() {
1831 partition += "/system"
1832 }
Inseob Kim08758f02021-04-08 21:13:22 +09001833 } else if ctx.InstallInDebugRamdisk() {
1834 partition = "debug_ramdisk"
Colin Cross6e359402020-02-10 15:29:54 -08001835 } else if ctx.InstallInRecovery() {
1836 if ctx.InstallInRoot() {
1837 partition = "recovery/root"
1838 } else {
1839 // the layout of recovery partion is the same as that of system partition
1840 partition = "recovery/root/system"
1841 }
1842 } else if ctx.SocSpecific() {
1843 partition = ctx.DeviceConfig().VendorPath()
1844 } else if ctx.DeviceSpecific() {
1845 partition = ctx.DeviceConfig().OdmPath()
1846 } else if ctx.ProductSpecific() {
1847 partition = ctx.DeviceConfig().ProductPath()
1848 } else if ctx.SystemExtSpecific() {
1849 partition = ctx.DeviceConfig().SystemExtPath()
1850 } else if ctx.InstallInRoot() {
1851 partition = "root"
Yifan Hong82db7352020-01-21 16:12:26 -08001852 } else {
Colin Cross6e359402020-02-10 15:29:54 -08001853 partition = "system"
Yifan Hong82db7352020-01-21 16:12:26 -08001854 }
Colin Cross6e359402020-02-10 15:29:54 -08001855 if ctx.InstallInSanitizerDir() {
1856 partition = "data/asan/" + partition
Yifan Hong82db7352020-01-21 16:12:26 -08001857 }
Colin Cross43f08db2018-11-12 10:13:39 -08001858 }
1859 return partition
1860}
1861
Colin Cross609c49a2020-02-13 13:20:11 -08001862type InstallPaths []InstallPath
1863
1864// Paths returns the InstallPaths as a Paths
1865func (p InstallPaths) Paths() Paths {
1866 if p == nil {
1867 return nil
1868 }
1869 ret := make(Paths, len(p))
1870 for i, path := range p {
1871 ret[i] = path
1872 }
1873 return ret
1874}
1875
1876// Strings returns the string forms of the install paths.
1877func (p InstallPaths) Strings() []string {
1878 if p == nil {
1879 return nil
1880 }
1881 ret := make([]string, len(p))
1882 for i, path := range p {
1883 ret[i] = path.String()
1884 }
1885 return ret
1886}
1887
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001888// validateSafePath validates a path that we trust (may contain ninja variables).
Dan Willemsen80a7c2a2015-12-21 14:57:11 -08001889// Ensures that each path component does not attempt to leave its component.
Colin Cross1ccfcc32018-02-22 13:54:26 -08001890func validateSafePath(pathComponents ...string) (string, error) {
Jeff Gaston734e3802017-04-10 15:47:24 -07001891 for _, path := range pathComponents {
Dan Willemsen80a7c2a2015-12-21 14:57:11 -08001892 path := filepath.Clean(path)
1893 if path == ".." || strings.HasPrefix(path, "../") || strings.HasPrefix(path, "/") {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001894 return "", fmt.Errorf("Path is outside directory: %s", path)
Dan Willemsen80a7c2a2015-12-21 14:57:11 -08001895 }
1896 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001897 // TODO: filepath.Join isn't necessarily correct with embedded ninja
1898 // variables. '..' may remove the entire ninja variable, even if it
1899 // will be expanded to multiple nested directories.
Colin Cross1ccfcc32018-02-22 13:54:26 -08001900 return filepath.Join(pathComponents...), nil
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001901}
1902
Dan Willemsen80a7c2a2015-12-21 14:57:11 -08001903// validatePath validates that a path does not include ninja variables, and that
1904// each path component does not attempt to leave its component. Returns a joined
1905// version of each path component.
Colin Cross1ccfcc32018-02-22 13:54:26 -08001906func validatePath(pathComponents ...string) (string, error) {
Jeff Gaston734e3802017-04-10 15:47:24 -07001907 for _, path := range pathComponents {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001908 if strings.Contains(path, "$") {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001909 return "", fmt.Errorf("Path contains invalid character($): %s", path)
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001910 }
1911 }
Colin Cross1ccfcc32018-02-22 13:54:26 -08001912 return validateSafePath(pathComponents...)
Colin Cross6e18ca42015-07-14 18:55:36 -07001913}
Colin Cross5b529592017-05-09 13:34:34 -07001914
Colin Cross0875c522017-11-28 17:34:01 -08001915func PathForPhony(ctx PathContext, phony string) WritablePath {
1916 if strings.ContainsAny(phony, "$/") {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001917 ReportPathErrorf(ctx, "Phony target contains invalid character ($ or /): %s", phony)
Colin Cross0875c522017-11-28 17:34:01 -08001918 }
Paul Duffin74abc5d2021-03-24 09:24:59 +00001919 return PhonyPath{basePath{phony, ""}}
Colin Cross0875c522017-11-28 17:34:01 -08001920}
1921
Colin Cross74e3fe42017-12-11 15:51:44 -08001922type PhonyPath struct {
1923 basePath
1924}
1925
1926func (p PhonyPath) writablePath() {}
1927
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02001928func (p PhonyPath) getSoongOutDir() string {
Paul Duffind65c58b2021-03-24 09:22:07 +00001929 // A phone path cannot contain any / so cannot be relative to the build directory.
1930 return ""
Paul Duffin9b478b02019-12-10 13:41:51 +00001931}
1932
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001933func (p PhonyPath) RelativeToTop() Path {
1934 ensureTestOnly()
1935 // A phony path cannot contain any / so does not have a build directory so switching to a new
1936 // build directory has no effect so just return this path.
1937 return p
1938}
1939
Hans MÃ¥nssond3f2bd72020-11-27 12:37:28 +01001940func (p PhonyPath) ReplaceExtension(ctx PathContext, ext string) OutputPath {
1941 panic("Not implemented")
1942}
1943
Colin Cross74e3fe42017-12-11 15:51:44 -08001944var _ Path = PhonyPath{}
1945var _ WritablePath = PhonyPath{}
1946
Colin Cross5b529592017-05-09 13:34:34 -07001947type testPath struct {
1948 basePath
1949}
1950
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001951func (p testPath) RelativeToTop() Path {
1952 ensureTestOnly()
1953 return p
1954}
1955
Colin Cross5b529592017-05-09 13:34:34 -07001956func (p testPath) String() string {
1957 return p.path
1958}
1959
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001960var _ Path = testPath{}
1961
Colin Cross40e33732019-02-15 11:08:35 -08001962// PathForTesting returns a Path constructed from joining the elements of paths with '/'. It should only be used from
1963// within tests.
Colin Cross5b529592017-05-09 13:34:34 -07001964func PathForTesting(paths ...string) Path {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001965 p, err := validateSafePath(paths...)
1966 if err != nil {
1967 panic(err)
1968 }
Colin Cross5b529592017-05-09 13:34:34 -07001969 return testPath{basePath{path: p, rel: p}}
1970}
1971
Colin Cross40e33732019-02-15 11:08:35 -08001972// PathsForTesting returns a Path constructed from each element in strs. It should only be used from within tests.
1973func PathsForTesting(strs ...string) Paths {
Colin Cross5b529592017-05-09 13:34:34 -07001974 p := make(Paths, len(strs))
1975 for i, s := range strs {
1976 p[i] = PathForTesting(s)
1977 }
1978
1979 return p
1980}
Colin Cross43f08db2018-11-12 10:13:39 -08001981
Colin Cross40e33732019-02-15 11:08:35 -08001982type testPathContext struct {
1983 config Config
Colin Cross40e33732019-02-15 11:08:35 -08001984}
1985
Colin Cross40e33732019-02-15 11:08:35 -08001986func (x *testPathContext) Config() Config { return x.config }
1987func (x *testPathContext) AddNinjaFileDeps(...string) {}
1988
1989// PathContextForTesting returns a PathContext that can be used in tests, for example to create an OutputPath with
1990// PathForOutput.
Colin Cross98be1bb2019-12-13 20:41:13 -08001991func PathContextForTesting(config Config) PathContext {
Colin Cross40e33732019-02-15 11:08:35 -08001992 return &testPathContext{
1993 config: config,
Colin Cross40e33732019-02-15 11:08:35 -08001994 }
1995}
1996
Ulya Trafimovichccc8c852020-10-14 11:29:07 +01001997type testModuleInstallPathContext struct {
1998 baseModuleContext
1999
2000 inData bool
2001 inTestcases bool
2002 inSanitizerDir bool
2003 inRamdisk bool
2004 inVendorRamdisk bool
Inseob Kim08758f02021-04-08 21:13:22 +09002005 inDebugRamdisk bool
Ulya Trafimovichccc8c852020-10-14 11:29:07 +01002006 inRecovery bool
2007 inRoot bool
2008 forceOS *OsType
2009 forceArch *ArchType
2010}
2011
2012func (m testModuleInstallPathContext) Config() Config {
2013 return m.baseModuleContext.config
2014}
2015
2016func (testModuleInstallPathContext) AddNinjaFileDeps(deps ...string) {}
2017
2018func (m testModuleInstallPathContext) InstallInData() bool {
2019 return m.inData
2020}
2021
2022func (m testModuleInstallPathContext) InstallInTestcases() bool {
2023 return m.inTestcases
2024}
2025
2026func (m testModuleInstallPathContext) InstallInSanitizerDir() bool {
2027 return m.inSanitizerDir
2028}
2029
2030func (m testModuleInstallPathContext) InstallInRamdisk() bool {
2031 return m.inRamdisk
2032}
2033
2034func (m testModuleInstallPathContext) InstallInVendorRamdisk() bool {
2035 return m.inVendorRamdisk
2036}
2037
Inseob Kim08758f02021-04-08 21:13:22 +09002038func (m testModuleInstallPathContext) InstallInDebugRamdisk() bool {
2039 return m.inDebugRamdisk
2040}
2041
Ulya Trafimovichccc8c852020-10-14 11:29:07 +01002042func (m testModuleInstallPathContext) InstallInRecovery() bool {
2043 return m.inRecovery
2044}
2045
2046func (m testModuleInstallPathContext) InstallInRoot() bool {
2047 return m.inRoot
2048}
2049
Ulya Trafimovichccc8c852020-10-14 11:29:07 +01002050func (m testModuleInstallPathContext) InstallForceOS() (*OsType, *ArchType) {
2051 return m.forceOS, m.forceArch
2052}
2053
2054// Construct a minimal ModuleInstallPathContext for testing. Note that baseModuleContext is
2055// default-initialized, which leaves blueprint.baseModuleContext set to nil, so methods that are
2056// delegated to it will panic.
2057func ModuleInstallPathContextForTesting(config Config) ModuleInstallPathContext {
2058 ctx := &testModuleInstallPathContext{}
2059 ctx.config = config
2060 ctx.os = Android
2061 return ctx
2062}
2063
Colin Cross43f08db2018-11-12 10:13:39 -08002064// Rel performs the same function as filepath.Rel, but reports errors to a PathContext, and reports an error if
2065// targetPath is not inside basePath.
2066func Rel(ctx PathContext, basePath string, targetPath string) string {
2067 rel, isRel := MaybeRel(ctx, basePath, targetPath)
2068 if !isRel {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01002069 ReportPathErrorf(ctx, "path %q is not under path %q", targetPath, basePath)
Colin Cross43f08db2018-11-12 10:13:39 -08002070 return ""
2071 }
2072 return rel
2073}
2074
2075// MaybeRel performs the same function as filepath.Rel, but reports errors to a PathContext, and returns false if
2076// targetPath is not inside basePath.
2077func MaybeRel(ctx PathContext, basePath string, targetPath string) (string, bool) {
Dan Willemsen633c5022019-04-12 11:11:38 -07002078 rel, isRel, err := maybeRelErr(basePath, targetPath)
2079 if err != nil {
2080 reportPathError(ctx, err)
2081 }
2082 return rel, isRel
2083}
2084
2085func maybeRelErr(basePath string, targetPath string) (string, bool, error) {
Colin Cross43f08db2018-11-12 10:13:39 -08002086 // filepath.Rel returns an error if one path is absolute and the other is not, handle that case first.
2087 if filepath.IsAbs(basePath) != filepath.IsAbs(targetPath) {
Dan Willemsen633c5022019-04-12 11:11:38 -07002088 return "", false, nil
Colin Cross43f08db2018-11-12 10:13:39 -08002089 }
2090 rel, err := filepath.Rel(basePath, targetPath)
2091 if err != nil {
Dan Willemsen633c5022019-04-12 11:11:38 -07002092 return "", false, err
Colin Cross43f08db2018-11-12 10:13:39 -08002093 } else if rel == ".." || strings.HasPrefix(rel, "../") || strings.HasPrefix(rel, "/") {
Dan Willemsen633c5022019-04-12 11:11:38 -07002094 return "", false, nil
Colin Cross43f08db2018-11-12 10:13:39 -08002095 }
Dan Willemsen633c5022019-04-12 11:11:38 -07002096 return rel, true, nil
Colin Cross43f08db2018-11-12 10:13:39 -08002097}
Colin Cross988414c2020-01-11 01:11:46 +00002098
2099// Writes a file to the output directory. Attempting to write directly to the output directory
2100// will fail due to the sandbox of the soong_build process.
2101func WriteFileToOutputDir(path WritablePath, data []byte, perm os.FileMode) error {
Colin Crossd6421132021-11-09 12:32:34 -08002102 absPath := absolutePath(path.String())
2103 err := os.MkdirAll(filepath.Dir(absPath), 0777)
2104 if err != nil {
2105 return err
2106 }
2107 return ioutil.WriteFile(absPath, data, perm)
Colin Cross988414c2020-01-11 01:11:46 +00002108}
2109
Liz Kammer2dd9ca42020-11-25 16:06:39 -08002110func RemoveAllOutputDir(path WritablePath) error {
2111 return os.RemoveAll(absolutePath(path.String()))
2112}
2113
2114func CreateOutputDirIfNonexistent(path WritablePath, perm os.FileMode) error {
2115 dir := absolutePath(path.String())
Liz Kammer09f947d2021-05-12 14:51:49 -04002116 return createDirIfNonexistent(dir, perm)
2117}
2118
2119func createDirIfNonexistent(dir string, perm os.FileMode) error {
Liz Kammer2dd9ca42020-11-25 16:06:39 -08002120 if _, err := os.Stat(dir); os.IsNotExist(err) {
2121 return os.MkdirAll(dir, os.ModePerm)
2122 } else {
2123 return err
2124 }
2125}
2126
Jingwen Chen78257e52021-05-21 02:34:24 +00002127// absolutePath is deliberately private so that Soong's Go plugins can't use it to find and
2128// read arbitrary files without going through the methods in the current package that track
2129// dependencies.
Colin Cross988414c2020-01-11 01:11:46 +00002130func absolutePath(path string) string {
2131 if filepath.IsAbs(path) {
2132 return path
2133 }
2134 return filepath.Join(absSrcDir, path)
2135}
Chris Parsons216e10a2020-07-09 17:12:52 -04002136
2137// A DataPath represents the path of a file to be used as data, for example
2138// a test library to be installed alongside a test.
2139// The data file should be installed (copied from `<SrcPath>`) to
2140// `<install_root>/<RelativeInstallPath>/<filename>`, or
2141// `<install_root>/<filename>` if RelativeInstallPath is empty.
2142type DataPath struct {
2143 // The path of the data file that should be copied into the data directory
2144 SrcPath Path
2145 // The install path of the data file, relative to the install root.
2146 RelativeInstallPath string
2147}
Colin Crossdcf71b22021-02-01 13:59:03 -08002148
2149// PathsIfNonNil returns a Paths containing only the non-nil input arguments.
2150func PathsIfNonNil(paths ...Path) Paths {
2151 if len(paths) == 0 {
2152 // Fast path for empty argument list
2153 return nil
2154 } else if len(paths) == 1 {
2155 // Fast path for a single argument
2156 if paths[0] != nil {
2157 return paths
2158 } else {
2159 return nil
2160 }
2161 }
2162 ret := make(Paths, 0, len(paths))
2163 for _, path := range paths {
2164 if path != nil {
2165 ret = append(ret, path)
2166 }
2167 }
2168 if len(ret) == 0 {
2169 return nil
2170 }
2171 return ret
2172}
Chris Wailesb2703ad2021-07-30 13:25:42 -07002173
2174var thirdPartyDirPrefixExceptions = []*regexp.Regexp{
2175 regexp.MustCompile("^vendor/[^/]*google[^/]*/"),
2176 regexp.MustCompile("^hardware/google/"),
2177 regexp.MustCompile("^hardware/interfaces/"),
2178 regexp.MustCompile("^hardware/libhardware[^/]*/"),
2179 regexp.MustCompile("^hardware/ril/"),
2180}
2181
2182func IsThirdPartyPath(path string) bool {
2183 thirdPartyDirPrefixes := []string{"external/", "vendor/", "hardware/"}
2184
2185 if HasAnyPrefix(path, thirdPartyDirPrefixes) {
2186 for _, prefix := range thirdPartyDirPrefixExceptions {
2187 if prefix.MatchString(path) {
2188 return false
2189 }
2190 }
2191 return true
2192 }
2193 return false
2194}
Colin Crossaff21fb2022-01-12 10:57:57 -08002195
2196// PathsDepSet is a thin type-safe wrapper around the generic depSet. It always uses
2197// topological order.
2198type PathsDepSet struct {
2199 depSet
2200}
2201
2202// newPathsDepSet returns an immutable PathsDepSet with the given direct and
2203// transitive contents.
2204func newPathsDepSet(direct Paths, transitive []*PathsDepSet) *PathsDepSet {
2205 return &PathsDepSet{*newDepSet(TOPOLOGICAL, direct, transitive)}
2206}
2207
2208// ToList returns the PathsDepSet flattened to a list in topological order.
2209func (d *PathsDepSet) ToList() Paths {
2210 if d == nil {
2211 return nil
2212 }
2213 return d.depSet.ToList().(Paths)
2214}