blob: 1da98882d33bff3ab08c08fe57a6f0c0d0fa9a25 [file] [log] [blame]
Colin Cross3f40fa42015-01-30 17:27:36 -08001// Copyright 2015 Google Inc. All rights reserved.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
Colin Cross635c3b02016-05-18 15:37:25 -070015package android
Colin Cross3f40fa42015-01-30 17:27:36 -080016
17import (
Colin Cross6e18ca42015-07-14 18:55:36 -070018 "fmt"
Colin Cross988414c2020-01-11 01:11:46 +000019 "os"
Colin Cross6a745c62015-06-16 16:38:10 -070020 "path/filepath"
Dan Willemsen34cc69e2015-09-23 15:26:20 -070021 "reflect"
Chris Wailesb2703ad2021-07-30 13:25:42 -070022 "regexp"
Colin Cross5e6cfbe2017-11-03 15:20:35 -070023 "sort"
Dan Willemsen34cc69e2015-09-23 15:26:20 -070024 "strings"
25
26 "github.com/google/blueprint"
Colin Cross0e446152021-05-03 13:35:32 -070027 "github.com/google/blueprint/bootstrap"
Dan Willemsen34cc69e2015-09-23 15:26:20 -070028 "github.com/google/blueprint/pathtools"
Colin Cross3f40fa42015-01-30 17:27:36 -080029)
30
Colin Cross988414c2020-01-11 01:11:46 +000031var absSrcDir string
32
Dan Willemsen34cc69e2015-09-23 15:26:20 -070033// PathContext is the subset of a (Module|Singleton)Context required by the
34// Path methods.
35type PathContext interface {
Colin Crossaabf6792017-11-29 00:27:14 -080036 Config() Config
Dan Willemsen7b310ee2015-12-18 15:11:17 -080037 AddNinjaFileDeps(deps ...string)
Colin Cross3f40fa42015-01-30 17:27:36 -080038}
39
Colin Cross7f19f372016-11-01 11:10:25 -070040type PathGlobContext interface {
Colin Cross662d6142022-11-03 20:38:01 -070041 PathContext
Colin Cross7f19f372016-11-01 11:10:25 -070042 GlobWithDeps(globPattern string, excludes []string) ([]string, error)
43}
44
Colin Crossaabf6792017-11-29 00:27:14 -080045var _ PathContext = SingletonContext(nil)
46var _ PathContext = ModuleContext(nil)
Dan Willemsen34cc69e2015-09-23 15:26:20 -070047
Ulya Trafimovich8640ab92020-05-11 18:06:15 +010048// "Null" path context is a minimal path context for a given config.
49type NullPathContext struct {
50 config Config
51}
52
53func (NullPathContext) AddNinjaFileDeps(...string) {}
54func (ctx NullPathContext) Config() Config { return ctx.config }
55
Liz Kammera830f3a2020-11-10 10:50:34 -080056// EarlyModulePathContext is a subset of EarlyModuleContext methods required by the
57// Path methods. These path methods can be called before any mutators have run.
58type EarlyModulePathContext interface {
Liz Kammera830f3a2020-11-10 10:50:34 -080059 PathGlobContext
60
61 ModuleDir() string
62 ModuleErrorf(fmt string, args ...interface{})
Cole Fausta963b942024-04-11 17:43:00 -070063 OtherModulePropertyErrorf(module Module, property, fmt string, args ...interface{})
Liz Kammera830f3a2020-11-10 10:50:34 -080064}
65
66var _ EarlyModulePathContext = ModuleContext(nil)
67
68// Glob globs files and directories matching globPattern relative to ModuleDir(),
69// paths in the excludes parameter will be omitted.
70func Glob(ctx EarlyModulePathContext, globPattern string, excludes []string) Paths {
71 ret, err := ctx.GlobWithDeps(globPattern, excludes)
72 if err != nil {
73 ctx.ModuleErrorf("glob: %s", err.Error())
74 }
75 return pathsForModuleSrcFromFullPath(ctx, ret, true)
76}
77
78// GlobFiles globs *only* files (not directories) matching globPattern relative to ModuleDir().
79// Paths in the excludes parameter will be omitted.
80func GlobFiles(ctx EarlyModulePathContext, globPattern string, excludes []string) Paths {
81 ret, err := ctx.GlobWithDeps(globPattern, excludes)
82 if err != nil {
83 ctx.ModuleErrorf("glob: %s", err.Error())
84 }
85 return pathsForModuleSrcFromFullPath(ctx, ret, false)
86}
87
88// ModuleWithDepsPathContext is a subset of *ModuleContext methods required by
89// the Path methods that rely on module dependencies having been resolved.
90type ModuleWithDepsPathContext interface {
91 EarlyModulePathContext
Paul Duffin40131a32021-07-09 17:10:35 +010092 VisitDirectDepsBlueprint(visit func(blueprint.Module))
93 OtherModuleDependencyTag(m blueprint.Module) blueprint.DependencyTag
Liz Kammera830f3a2020-11-10 10:50:34 -080094}
95
96// ModuleMissingDepsPathContext is a subset of *ModuleContext methods required by
97// the Path methods that rely on module dependencies having been resolved and ability to report
98// missing dependency errors.
99type ModuleMissingDepsPathContext interface {
100 ModuleWithDepsPathContext
101 AddMissingDependencies(missingDeps []string)
102}
103
Dan Willemsen00269f22017-07-06 16:59:48 -0700104type ModuleInstallPathContext interface {
Colin Cross0ea8ba82019-06-06 14:33:29 -0700105 BaseModuleContext
Dan Willemsen00269f22017-07-06 16:59:48 -0700106
107 InstallInData() bool
Jaewoong Jung0949f312019-09-11 10:25:18 -0700108 InstallInTestcases() bool
Dan Willemsen00269f22017-07-06 16:59:48 -0700109 InstallInSanitizerDir() bool
Yifan Hong1b3348d2020-01-21 15:53:22 -0800110 InstallInRamdisk() bool
Yifan Hong60e0cfb2020-10-21 15:17:56 -0700111 InstallInVendorRamdisk() bool
Inseob Kim08758f02021-04-08 21:13:22 +0900112 InstallInDebugRamdisk() bool
Jiyong Parkf9332f12018-02-01 00:54:12 +0900113 InstallInRecovery() bool
Colin Cross90ba5f42019-10-02 11:10:58 -0700114 InstallInRoot() bool
Colin Crossea30d852023-11-29 16:00:16 -0800115 InstallInOdm() bool
116 InstallInProduct() bool
117 InstallInVendor() bool
Jiyong Park87788b52020-09-01 12:37:45 +0900118 InstallForceOS() (*OsType, *ArchType)
Dan Willemsen00269f22017-07-06 16:59:48 -0700119}
120
121var _ ModuleInstallPathContext = ModuleContext(nil)
122
Cole Faust11edf552023-10-13 11:32:14 -0700123type baseModuleContextToModuleInstallPathContext struct {
124 BaseModuleContext
125}
126
127func (ctx *baseModuleContextToModuleInstallPathContext) InstallInData() bool {
128 return ctx.Module().InstallInData()
129}
130
131func (ctx *baseModuleContextToModuleInstallPathContext) InstallInTestcases() bool {
132 return ctx.Module().InstallInTestcases()
133}
134
135func (ctx *baseModuleContextToModuleInstallPathContext) InstallInSanitizerDir() bool {
136 return ctx.Module().InstallInSanitizerDir()
137}
138
139func (ctx *baseModuleContextToModuleInstallPathContext) InstallInRamdisk() bool {
140 return ctx.Module().InstallInRamdisk()
141}
142
143func (ctx *baseModuleContextToModuleInstallPathContext) InstallInVendorRamdisk() bool {
144 return ctx.Module().InstallInVendorRamdisk()
145}
146
147func (ctx *baseModuleContextToModuleInstallPathContext) InstallInDebugRamdisk() bool {
148 return ctx.Module().InstallInDebugRamdisk()
149}
150
151func (ctx *baseModuleContextToModuleInstallPathContext) InstallInRecovery() bool {
152 return ctx.Module().InstallInRecovery()
153}
154
155func (ctx *baseModuleContextToModuleInstallPathContext) InstallInRoot() bool {
156 return ctx.Module().InstallInRoot()
157}
158
Colin Crossea30d852023-11-29 16:00:16 -0800159func (ctx *baseModuleContextToModuleInstallPathContext) InstallInOdm() bool {
160 return ctx.Module().InstallInOdm()
161}
162
163func (ctx *baseModuleContextToModuleInstallPathContext) InstallInProduct() bool {
164 return ctx.Module().InstallInProduct()
165}
166
167func (ctx *baseModuleContextToModuleInstallPathContext) InstallInVendor() bool {
168 return ctx.Module().InstallInVendor()
169}
170
Cole Faust11edf552023-10-13 11:32:14 -0700171func (ctx *baseModuleContextToModuleInstallPathContext) InstallForceOS() (*OsType, *ArchType) {
172 return ctx.Module().InstallForceOS()
173}
174
175var _ ModuleInstallPathContext = (*baseModuleContextToModuleInstallPathContext)(nil)
176
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700177// errorfContext is the interface containing the Errorf method matching the
178// Errorf method in blueprint.SingletonContext.
179type errorfContext interface {
180 Errorf(format string, args ...interface{})
Colin Cross3f40fa42015-01-30 17:27:36 -0800181}
182
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700183var _ errorfContext = blueprint.SingletonContext(nil)
184
Spandan Das59a4a2b2024-01-09 21:35:56 +0000185// ModuleErrorfContext is the interface containing the ModuleErrorf method matching
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700186// the ModuleErrorf method in blueprint.ModuleContext.
Spandan Das59a4a2b2024-01-09 21:35:56 +0000187type ModuleErrorfContext interface {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700188 ModuleErrorf(format string, args ...interface{})
Colin Cross3f40fa42015-01-30 17:27:36 -0800189}
190
Spandan Das59a4a2b2024-01-09 21:35:56 +0000191var _ ModuleErrorfContext = blueprint.ModuleContext(nil)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700192
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700193// reportPathError will register an error with the attached context. It
194// attempts ctx.ModuleErrorf for a better error message first, then falls
195// back to ctx.Errorf.
Colin Cross1ccfcc32018-02-22 13:54:26 -0800196func reportPathError(ctx PathContext, err error) {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +0100197 ReportPathErrorf(ctx, "%s", err.Error())
Colin Cross1ccfcc32018-02-22 13:54:26 -0800198}
199
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +0100200// ReportPathErrorf will register an error with the attached context. It
Colin Cross1ccfcc32018-02-22 13:54:26 -0800201// attempts ctx.ModuleErrorf for a better error message first, then falls
202// back to ctx.Errorf.
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +0100203func ReportPathErrorf(ctx PathContext, format string, args ...interface{}) {
Spandan Das59a4a2b2024-01-09 21:35:56 +0000204 if mctx, ok := ctx.(ModuleErrorfContext); ok {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700205 mctx.ModuleErrorf(format, args...)
206 } else if ectx, ok := ctx.(errorfContext); ok {
207 ectx.Errorf(format, args...)
208 } else {
209 panic(fmt.Sprintf(format, args...))
Colin Crossf2298272015-05-12 11:36:53 -0700210 }
211}
212
Colin Cross5e708052019-08-06 13:59:50 -0700213func pathContextName(ctx PathContext, module blueprint.Module) string {
214 if x, ok := ctx.(interface{ ModuleName(blueprint.Module) string }); ok {
215 return x.ModuleName(module)
216 } else if x, ok := ctx.(interface{ OtherModuleName(blueprint.Module) string }); ok {
217 return x.OtherModuleName(module)
218 }
219 return "unknown"
220}
221
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700222type Path interface {
223 // Returns the path in string form
224 String() string
225
Colin Cross4f6fc9c2016-10-26 10:05:25 -0700226 // Ext returns the extension of the last element of the path
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700227 Ext() string
Colin Cross4f6fc9c2016-10-26 10:05:25 -0700228
229 // Base returns the last element of the path
230 Base() string
Colin Crossfaeb7aa2017-02-01 14:12:44 -0800231
232 // Rel returns the portion of the path relative to the directory it was created from. For
233 // example, Rel on a PathsForModuleSrc would return the path relative to the module source
Colin Cross0db55682017-12-05 15:36:55 -0800234 // directory, and OutputPath.Join("foo").Rel() would return "foo".
Colin Crossfaeb7aa2017-02-01 14:12:44 -0800235 Rel() string
Paul Duffin85d8f0d2021-03-24 10:18:18 +0000236
237 // RelativeToTop returns a new path relative to the top, it is provided solely for use in tests.
238 //
239 // It is guaranteed to always return the same type as it is called on, e.g. if called on an
240 // InstallPath then the returned value can be converted to an InstallPath.
241 //
242 // A standard build has the following structure:
243 // ../top/
244 // out/ - make install files go here.
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +0200245 // out/soong - this is the soongOutDir passed to NewTestConfig()
Paul Duffin85d8f0d2021-03-24 10:18:18 +0000246 // ... - the source files
247 //
248 // This function converts a path so that it appears relative to the ../top/ directory, i.e.
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +0200249 // * Make install paths, which have the pattern "soongOutDir/../<path>" are converted into the top
Paul Duffin85d8f0d2021-03-24 10:18:18 +0000250 // relative path "out/<path>"
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +0200251 // * Soong install paths and other writable paths, which have the pattern "soongOutDir/<path>" are
Paul Duffin85d8f0d2021-03-24 10:18:18 +0000252 // converted into the top relative path "out/soong/<path>".
253 // * Source paths are already relative to the top.
254 // * Phony paths are not relative to anything.
255 // * toolDepPath have an absolute but known value in so don't need making relative to anything in
256 // order to test.
257 RelativeToTop() Path
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700258}
259
Paul Duffin85d8f0d2021-03-24 10:18:18 +0000260const (
261 OutDir = "out"
262 OutSoongDir = OutDir + "/soong"
263)
264
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700265// WritablePath is a type of path that can be used as an output for build rules.
266type WritablePath interface {
267 Path
268
Paul Duffin9b478b02019-12-10 13:41:51 +0000269 // return the path to the build directory.
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +0200270 getSoongOutDir() string
Paul Duffin9b478b02019-12-10 13:41:51 +0000271
Jeff Gaston734e3802017-04-10 15:47:24 -0700272 // the writablePath method doesn't directly do anything,
273 // but it allows a struct to distinguish between whether or not it implements the WritablePath interface
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700274 writablePath()
Hans MÃ¥nssond3f2bd72020-11-27 12:37:28 +0100275
276 ReplaceExtension(ctx PathContext, ext string) OutputPath
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700277}
278
279type genPathProvider interface {
Liz Kammera830f3a2020-11-10 10:50:34 -0800280 genPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleGenPath
yangbill6d032dd2024-04-18 03:05:49 +0000281 genPathWithExtAndTrimExt(ctx ModuleOutPathContext, subdir, ext string, trimExt string) ModuleGenPath
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700282}
283type objPathProvider interface {
Liz Kammera830f3a2020-11-10 10:50:34 -0800284 objPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleObjPath
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700285}
286type resPathProvider interface {
Liz Kammera830f3a2020-11-10 10:50:34 -0800287 resPathWithName(ctx ModuleOutPathContext, name string) ModuleResPath
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700288}
289
290// GenPathWithExt derives a new file path in ctx's generated sources directory
291// from the current path, but with the new extension.
Liz Kammera830f3a2020-11-10 10:50:34 -0800292func GenPathWithExt(ctx ModuleOutPathContext, subdir string, p Path, ext string) ModuleGenPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700293 if path, ok := p.(genPathProvider); ok {
Dan Willemsen21ec4902016-11-02 20:43:13 -0700294 return path.genPathWithExt(ctx, subdir, ext)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700295 }
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +0100296 ReportPathErrorf(ctx, "Tried to create generated file from unsupported path: %s(%s)", reflect.TypeOf(p).Name(), p)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700297 return PathForModuleGen(ctx)
298}
299
yangbill6d032dd2024-04-18 03:05:49 +0000300// GenPathWithExtAndTrimExt derives a new file path in ctx's generated sources directory
301// from the current path, but with the new extension and trim the suffix.
302func GenPathWithExtAndTrimExt(ctx ModuleOutPathContext, subdir string, p Path, ext string, trimExt string) ModuleGenPath {
303 if path, ok := p.(genPathProvider); ok {
304 return path.genPathWithExtAndTrimExt(ctx, subdir, ext, trimExt)
305 }
306 ReportPathErrorf(ctx, "Tried to create generated file from unsupported path: %s(%s)", reflect.TypeOf(p).Name(), p)
307 return PathForModuleGen(ctx)
308}
309
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700310// ObjPathWithExt derives a new file path in ctx's object directory from the
311// current path, but with the new extension.
Liz Kammera830f3a2020-11-10 10:50:34 -0800312func ObjPathWithExt(ctx ModuleOutPathContext, subdir string, p Path, ext string) ModuleObjPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700313 if path, ok := p.(objPathProvider); ok {
314 return path.objPathWithExt(ctx, subdir, ext)
315 }
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +0100316 ReportPathErrorf(ctx, "Tried to create object file from unsupported path: %s (%s)", reflect.TypeOf(p).Name(), p)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700317 return PathForModuleObj(ctx)
318}
319
320// ResPathWithName derives a new path in ctx's output resource directory, using
321// the current path to create the directory name, and the `name` argument for
322// the filename.
Liz Kammera830f3a2020-11-10 10:50:34 -0800323func ResPathWithName(ctx ModuleOutPathContext, p Path, name string) ModuleResPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700324 if path, ok := p.(resPathProvider); ok {
325 return path.resPathWithName(ctx, name)
326 }
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +0100327 ReportPathErrorf(ctx, "Tried to create res file from unsupported path: %s (%s)", reflect.TypeOf(p).Name(), p)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700328 return PathForModuleRes(ctx)
329}
330
331// OptionalPath is a container that may or may not contain a valid Path.
332type OptionalPath struct {
Martin Stjernholmc32dd1c2021-09-15 02:39:00 +0100333 path Path // nil if invalid.
334 invalidReason string // Not applicable if path != nil. "" if the reason is unknown.
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700335}
336
337// OptionalPathForPath returns an OptionalPath containing the path.
338func OptionalPathForPath(path Path) OptionalPath {
Martin Stjernholm2fee27f2021-09-16 14:11:12 +0100339 return OptionalPath{path: path}
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700340}
341
Martin Stjernholmc32dd1c2021-09-15 02:39:00 +0100342// InvalidOptionalPath returns an OptionalPath that is invalid with the given reason.
343func InvalidOptionalPath(reason string) OptionalPath {
344
345 return OptionalPath{invalidReason: reason}
346}
347
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700348// Valid returns whether there is a valid path
349func (p OptionalPath) Valid() bool {
Martin Stjernholm2fee27f2021-09-16 14:11:12 +0100350 return p.path != nil
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700351}
352
353// Path returns the Path embedded in this OptionalPath. You must be sure that
354// there is a valid path, since this method will panic if there is not.
355func (p OptionalPath) Path() Path {
Martin Stjernholm2fee27f2021-09-16 14:11:12 +0100356 if p.path == nil {
Martin Stjernholmc32dd1c2021-09-15 02:39:00 +0100357 msg := "Requesting an invalid path"
358 if p.invalidReason != "" {
359 msg += ": " + p.invalidReason
360 }
361 panic(msg)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700362 }
363 return p.path
364}
365
Martin Stjernholmc32dd1c2021-09-15 02:39:00 +0100366// InvalidReason returns the reason that the optional path is invalid, or "" if it is valid.
367func (p OptionalPath) InvalidReason() string {
368 if p.path != nil {
369 return ""
370 }
371 if p.invalidReason == "" {
372 return "unknown"
373 }
374 return p.invalidReason
375}
376
Paul Duffinef081852021-05-13 11:11:15 +0100377// AsPaths converts the OptionalPath into Paths.
378//
379// It returns nil if this is not valid, or a single length slice containing the Path embedded in
380// this OptionalPath.
381func (p OptionalPath) AsPaths() Paths {
Martin Stjernholm2fee27f2021-09-16 14:11:12 +0100382 if p.path == nil {
Paul Duffinef081852021-05-13 11:11:15 +0100383 return nil
384 }
385 return Paths{p.path}
386}
387
Paul Duffinafdd4062021-03-30 19:44:07 +0100388// RelativeToTop returns an OptionalPath with the path that was embedded having been replaced by the
389// result of calling Path.RelativeToTop on it.
390func (p OptionalPath) RelativeToTop() OptionalPath {
Martin Stjernholm2fee27f2021-09-16 14:11:12 +0100391 if p.path == nil {
Paul Duffina5b81352021-03-28 23:57:19 +0100392 return p
393 }
394 p.path = p.path.RelativeToTop()
395 return p
396}
397
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700398// String returns the string version of the Path, or "" if it isn't valid.
399func (p OptionalPath) String() string {
Martin Stjernholm2fee27f2021-09-16 14:11:12 +0100400 if p.path != nil {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700401 return p.path.String()
402 } else {
403 return ""
Colin Crossf2298272015-05-12 11:36:53 -0700404 }
405}
Colin Cross6e18ca42015-07-14 18:55:36 -0700406
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700407// Paths is a slice of Path objects, with helpers to operate on the collection.
408type Paths []Path
409
Paul Duffin85d8f0d2021-03-24 10:18:18 +0000410// RelativeToTop creates a new Paths containing the result of calling Path.RelativeToTop on each
411// item in this slice.
412func (p Paths) RelativeToTop() Paths {
413 ensureTestOnly()
414 if p == nil {
415 return p
416 }
417 ret := make(Paths, len(p))
418 for i, path := range p {
419 ret[i] = path.RelativeToTop()
420 }
421 return ret
422}
423
Jingwen Chen40fd90a2020-06-15 05:24:19 +0000424func (paths Paths) containsPath(path Path) bool {
425 for _, p := range paths {
426 if p == path {
427 return true
428 }
429 }
430 return false
431}
432
Liz Kammer7aa52882021-02-11 09:16:14 -0500433// PathsForSource returns Paths rooted from SrcDir, *not* rooted from the module's local source
434// directory
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700435func PathsForSource(ctx PathContext, paths []string) Paths {
436 ret := make(Paths, len(paths))
437 for i, path := range paths {
438 ret[i] = PathForSource(ctx, path)
439 }
440 return ret
441}
442
Liz Kammer7aa52882021-02-11 09:16:14 -0500443// ExistentPathsForSources returns a list of Paths rooted from SrcDir, *not* rooted from the
444// module's local source directory, that are found in the tree. If any are not found, they are
445// omitted from the list, and dependencies are added so that we're re-run when they are added.
Colin Cross662d6142022-11-03 20:38:01 -0700446func ExistentPathsForSources(ctx PathGlobContext, paths []string) Paths {
Dan Willemsen7b310ee2015-12-18 15:11:17 -0800447 ret := make(Paths, 0, len(paths))
448 for _, path := range paths {
Colin Cross32f38982018-02-22 11:47:25 -0800449 p := ExistentPathForSource(ctx, path)
Dan Willemsen7b310ee2015-12-18 15:11:17 -0800450 if p.Valid() {
451 ret = append(ret, p.Path())
452 }
453 }
454 return ret
455}
456
Liz Kammer620dea62021-04-14 17:36:10 -0400457// PathsForModuleSrc returns a Paths{} containing the resolved references in paths:
Colin Crossd079e0b2022-08-16 10:27:33 -0700458// - filepath, relative to local module directory, resolves as a filepath relative to the local
459// source directory
460// - glob, relative to the local module directory, resolves as filepath(s), relative to the local
461// source directory.
462// - other modules using the ":name{.tag}" syntax. These modules must implement SourceFileProducer
463// or OutputFileProducer. These resolve as a filepath to an output filepath or generated source
464// filepath.
465//
Liz Kammer620dea62021-04-14 17:36:10 -0400466// Properties passed as the paths argument must have been annotated with struct tag
Colin Cross41955e82019-05-29 14:40:35 -0700467// `android:"path"` so that dependencies on SourceFileProducer modules will have already been handled by the
Spandan Das950091c2023-07-19 22:26:37 +0000468// pathdeps mutator.
Liz Kammer620dea62021-04-14 17:36:10 -0400469// If a requested module is not found as a dependency:
Colin Crossd079e0b2022-08-16 10:27:33 -0700470// - if ctx.Config().AllowMissingDependencies() is true, this module to be marked as having
Liz Kammer620dea62021-04-14 17:36:10 -0400471// missing dependencies
Colin Crossd079e0b2022-08-16 10:27:33 -0700472// - otherwise, a ModuleError is thrown.
Liz Kammera830f3a2020-11-10 10:50:34 -0800473func PathsForModuleSrc(ctx ModuleMissingDepsPathContext, paths []string) Paths {
Colin Cross8a497952019-03-05 22:25:09 -0800474 return PathsForModuleSrcExcludes(ctx, paths, nil)
475}
476
Liz Kammer619be462022-01-28 15:13:39 -0500477type SourceInput struct {
478 Context ModuleMissingDepsPathContext
479 Paths []string
480 ExcludePaths []string
481 IncludeDirs bool
482}
483
Liz Kammer620dea62021-04-14 17:36:10 -0400484// PathsForModuleSrcExcludes returns a Paths{} containing the resolved references in paths, minus
485// those listed in excludes. Elements of paths and excludes are resolved as:
Colin Crossd079e0b2022-08-16 10:27:33 -0700486// - filepath, relative to local module directory, resolves as a filepath relative to the local
487// source directory
488// - glob, relative to the local module directory, resolves as filepath(s), relative to the local
489// source directory. Not valid in excludes.
490// - other modules using the ":name{.tag}" syntax. These modules must implement SourceFileProducer
491// or OutputFileProducer. These resolve as a filepath to an output filepath or generated source
492// filepath.
493//
Liz Kammer620dea62021-04-14 17:36:10 -0400494// excluding the items (similarly resolved
495// Properties passed as the paths argument must have been annotated with struct tag
496// `android:"path"` so that dependencies on SourceFileProducer modules will have already been handled by the
Spandan Das950091c2023-07-19 22:26:37 +0000497// pathdeps mutator.
Liz Kammer620dea62021-04-14 17:36:10 -0400498// If a requested module is not found as a dependency:
Colin Crossd079e0b2022-08-16 10:27:33 -0700499// - if ctx.Config().AllowMissingDependencies() is true, this module to be marked as having
Liz Kammer620dea62021-04-14 17:36:10 -0400500// missing dependencies
Colin Crossd079e0b2022-08-16 10:27:33 -0700501// - otherwise, a ModuleError is thrown.
Liz Kammera830f3a2020-11-10 10:50:34 -0800502func PathsForModuleSrcExcludes(ctx ModuleMissingDepsPathContext, paths, excludes []string) Paths {
Liz Kammer619be462022-01-28 15:13:39 -0500503 return PathsRelativeToModuleSourceDir(SourceInput{
504 Context: ctx,
505 Paths: paths,
506 ExcludePaths: excludes,
507 IncludeDirs: true,
508 })
509}
510
511func PathsRelativeToModuleSourceDir(input SourceInput) Paths {
512 ret, missingDeps := PathsAndMissingDepsRelativeToModuleSourceDir(input)
513 if input.Context.Config().AllowMissingDependencies() {
514 input.Context.AddMissingDependencies(missingDeps)
Colin Crossba71a3f2019-03-18 12:12:48 -0700515 } else {
516 for _, m := range missingDeps {
Liz Kammer619be462022-01-28 15:13:39 -0500517 input.Context.ModuleErrorf(`missing dependency on %q, is the property annotated with android:"path"?`, m)
Colin Crossba71a3f2019-03-18 12:12:48 -0700518 }
519 }
520 return ret
521}
522
Ulya Trafimovich4d2eeed2019-11-08 10:54:21 +0000523// OutputPaths is a slice of OutputPath objects, with helpers to operate on the collection.
524type OutputPaths []OutputPath
525
526// Paths returns the OutputPaths as a Paths
527func (p OutputPaths) Paths() Paths {
528 if p == nil {
529 return nil
530 }
531 ret := make(Paths, len(p))
532 for i, path := range p {
533 ret[i] = path
534 }
535 return ret
536}
537
538// Strings returns the string forms of the writable paths.
539func (p OutputPaths) Strings() []string {
540 if p == nil {
541 return nil
542 }
543 ret := make([]string, len(p))
544 for i, path := range p {
545 ret[i] = path.String()
546 }
547 return ret
548}
549
Colin Crossa44551f2021-10-25 15:36:21 -0700550// PathForGoBinary returns the path to the installed location of a bootstrap_go_binary module.
551func PathForGoBinary(ctx PathContext, goBinary bootstrap.GoBinaryTool) Path {
Cole Faust3b703f32023-10-16 13:30:51 -0700552 goBinaryInstallDir := pathForInstall(ctx, ctx.Config().BuildOS, ctx.Config().BuildArch, "bin")
Colin Crossa44551f2021-10-25 15:36:21 -0700553 rel := Rel(ctx, goBinaryInstallDir.String(), goBinary.InstallPath())
554 return goBinaryInstallDir.Join(ctx, rel)
555}
556
Liz Kammera830f3a2020-11-10 10:50:34 -0800557// Expands Paths to a SourceFileProducer or OutputFileProducer module dependency referenced via ":name" or ":name{.tag}" syntax.
558// If the dependency is not found, a missingErrorDependency is returned.
559// If the module dependency is not a SourceFileProducer or OutputFileProducer, appropriate errors will be returned.
560func getPathsFromModuleDep(ctx ModuleWithDepsPathContext, path, moduleName, tag string) (Paths, error) {
Paul Duffind5cf92e2021-07-09 17:38:55 +0100561 module := GetModuleFromPathDep(ctx, moduleName, tag)
Liz Kammera830f3a2020-11-10 10:50:34 -0800562 if module == nil {
563 return nil, missingDependencyError{[]string{moduleName}}
564 }
Cole Fausta963b942024-04-11 17:43:00 -0700565 if aModule, ok := module.(Module); ok && !aModule.Enabled(ctx) {
Colin Crossfa65cee2021-03-22 17:05:59 -0700566 return nil, missingDependencyError{[]string{moduleName}}
567 }
mrziwange6c85812024-05-22 14:36:09 -0700568 if goBinary, ok := module.(bootstrap.GoBinaryTool); ok && tag == "" {
Colin Crossa44551f2021-10-25 15:36:21 -0700569 goBinaryPath := PathForGoBinary(ctx, goBinary)
570 return Paths{goBinaryPath}, nil
mrziwange6c85812024-05-22 14:36:09 -0700571 }
572 outputFiles, err := outputFilesForModule(ctx, module, tag)
573 if outputFiles != nil && err == nil {
574 return outputFiles, nil
Liz Kammera830f3a2020-11-10 10:50:34 -0800575 } else {
mrziwange6c85812024-05-22 14:36:09 -0700576 return nil, err
Liz Kammera830f3a2020-11-10 10:50:34 -0800577 }
578}
579
Paul Duffind5cf92e2021-07-09 17:38:55 +0100580// GetModuleFromPathDep will return the module that was added as a dependency automatically for
581// properties tagged with `android:"path"` or manually using ExtractSourceDeps or
582// ExtractSourcesDeps.
583//
584// The moduleName and tag supplied to this should be the values returned from SrcIsModuleWithTag.
585// Or, if no tag is expected then the moduleName should be the value returned by SrcIsModule and
586// the tag must be "".
587//
588// If tag is "" then the returned module will be the dependency that was added for ":moduleName".
589// Otherwise, it is the dependency that was added for ":moduleName{tag}".
Paul Duffind5cf92e2021-07-09 17:38:55 +0100590func GetModuleFromPathDep(ctx ModuleWithDepsPathContext, moduleName, tag string) blueprint.Module {
Paul Duffin40131a32021-07-09 17:10:35 +0100591 var found blueprint.Module
592 // The sourceOrOutputDepTag uniquely identifies the module dependency as it contains both the
593 // module name and the tag. Dependencies added automatically for properties tagged with
594 // `android:"path"` are deduped so are guaranteed to be unique. It is possible for duplicate
595 // dependencies to be added manually using ExtractSourcesDeps or ExtractSourceDeps but even then
596 // it will always be the case that the dependencies will be identical, i.e. the same tag and same
597 // moduleName referring to the same dependency module.
598 //
599 // It does not matter whether the moduleName is a fully qualified name or if the module
600 // dependency is a prebuilt module. All that matters is the same information is supplied to
601 // create the tag here as was supplied to create the tag when the dependency was added so that
602 // this finds the matching dependency module.
603 expectedTag := sourceOrOutputDepTag(moduleName, tag)
604 ctx.VisitDirectDepsBlueprint(func(module blueprint.Module) {
605 depTag := ctx.OtherModuleDependencyTag(module)
606 if depTag == expectedTag {
607 found = module
608 }
609 })
610 return found
Paul Duffind5cf92e2021-07-09 17:38:55 +0100611}
612
Liz Kammer620dea62021-04-14 17:36:10 -0400613// PathsAndMissingDepsForModuleSrcExcludes returns a Paths{} containing the resolved references in
614// paths, minus those listed in excludes. Elements of paths and excludes are resolved as:
Colin Crossd079e0b2022-08-16 10:27:33 -0700615// - filepath, relative to local module directory, resolves as a filepath relative to the local
616// source directory
617// - glob, relative to the local module directory, resolves as filepath(s), relative to the local
618// source directory. Not valid in excludes.
619// - other modules using the ":name{.tag}" syntax. These modules must implement SourceFileProducer
620// or OutputFileProducer. These resolve as a filepath to an output filepath or generated source
621// filepath.
622//
Liz Kammer620dea62021-04-14 17:36:10 -0400623// and a list of the module names of missing module dependencies are returned as the second return.
624// Properties passed as the paths argument must have been annotated with struct tag
Colin Cross41955e82019-05-29 14:40:35 -0700625// `android:"path"` so that dependencies on SourceFileProducer modules will have already been handled by the
Spandan Das950091c2023-07-19 22:26:37 +0000626// pathdeps mutator.
Liz Kammer619be462022-01-28 15:13:39 -0500627func PathsAndMissingDepsForModuleSrcExcludes(ctx ModuleMissingDepsPathContext, paths, excludes []string) (Paths, []string) {
628 return PathsAndMissingDepsRelativeToModuleSourceDir(SourceInput{
629 Context: ctx,
630 Paths: paths,
631 ExcludePaths: excludes,
632 IncludeDirs: true,
633 })
634}
635
636func PathsAndMissingDepsRelativeToModuleSourceDir(input SourceInput) (Paths, []string) {
637 prefix := pathForModuleSrc(input.Context).String()
Colin Cross8a497952019-03-05 22:25:09 -0800638
639 var expandedExcludes []string
Liz Kammer619be462022-01-28 15:13:39 -0500640 if input.ExcludePaths != nil {
641 expandedExcludes = make([]string, 0, len(input.ExcludePaths))
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700642 }
Colin Cross8a497952019-03-05 22:25:09 -0800643
Colin Crossba71a3f2019-03-18 12:12:48 -0700644 var missingExcludeDeps []string
Liz Kammer619be462022-01-28 15:13:39 -0500645 for _, e := range input.ExcludePaths {
Colin Cross41955e82019-05-29 14:40:35 -0700646 if m, t := SrcIsModuleWithTag(e); m != "" {
Liz Kammer619be462022-01-28 15:13:39 -0500647 modulePaths, err := getPathsFromModuleDep(input.Context, e, m, t)
Liz Kammera830f3a2020-11-10 10:50:34 -0800648 if m, ok := err.(missingDependencyError); ok {
649 missingExcludeDeps = append(missingExcludeDeps, m.missingDeps...)
650 } else if err != nil {
Liz Kammer619be462022-01-28 15:13:39 -0500651 reportPathError(input.Context, err)
Colin Cross8a497952019-03-05 22:25:09 -0800652 } else {
Liz Kammera830f3a2020-11-10 10:50:34 -0800653 expandedExcludes = append(expandedExcludes, modulePaths.Strings()...)
Colin Cross8a497952019-03-05 22:25:09 -0800654 }
655 } else {
656 expandedExcludes = append(expandedExcludes, filepath.Join(prefix, e))
657 }
658 }
659
Liz Kammer619be462022-01-28 15:13:39 -0500660 if input.Paths == nil {
Colin Crossba71a3f2019-03-18 12:12:48 -0700661 return nil, missingExcludeDeps
Colin Cross8a497952019-03-05 22:25:09 -0800662 }
663
Colin Crossba71a3f2019-03-18 12:12:48 -0700664 var missingDeps []string
665
Liz Kammer619be462022-01-28 15:13:39 -0500666 expandedSrcFiles := make(Paths, 0, len(input.Paths))
667 for _, s := range input.Paths {
668 srcFiles, err := expandOneSrcPath(sourcePathInput{
669 context: input.Context,
670 path: s,
671 expandedExcludes: expandedExcludes,
672 includeDirs: input.IncludeDirs,
673 })
Colin Cross8a497952019-03-05 22:25:09 -0800674 if depErr, ok := err.(missingDependencyError); ok {
Colin Crossba71a3f2019-03-18 12:12:48 -0700675 missingDeps = append(missingDeps, depErr.missingDeps...)
Colin Cross8a497952019-03-05 22:25:09 -0800676 } else if err != nil {
Liz Kammer619be462022-01-28 15:13:39 -0500677 reportPathError(input.Context, err)
Colin Cross8a497952019-03-05 22:25:09 -0800678 }
679 expandedSrcFiles = append(expandedSrcFiles, srcFiles...)
680 }
Colin Crossba71a3f2019-03-18 12:12:48 -0700681
Jihoon Kang0e3a5352024-04-12 00:45:50 +0000682 // TODO: b/334169722 - Replace with an error instead of implicitly removing duplicates.
683 return FirstUniquePaths(expandedSrcFiles), append(missingDeps, missingExcludeDeps...)
Colin Cross8a497952019-03-05 22:25:09 -0800684}
685
686type missingDependencyError struct {
687 missingDeps []string
688}
689
690func (e missingDependencyError) Error() string {
691 return "missing dependencies: " + strings.Join(e.missingDeps, ", ")
692}
693
Liz Kammer619be462022-01-28 15:13:39 -0500694type sourcePathInput struct {
695 context ModuleWithDepsPathContext
696 path string
697 expandedExcludes []string
698 includeDirs bool
699}
700
Liz Kammera830f3a2020-11-10 10:50:34 -0800701// Expands one path string to Paths rooted from the module's local source
702// directory, excluding those listed in the expandedExcludes.
703// Expands globs, references to SourceFileProducer or OutputFileProducer modules using the ":name" and ":name{.tag}" syntax.
Liz Kammer619be462022-01-28 15:13:39 -0500704func expandOneSrcPath(input sourcePathInput) (Paths, error) {
Jooyung Han7607dd32020-07-05 10:23:14 +0900705 excludePaths := func(paths Paths) Paths {
Liz Kammer619be462022-01-28 15:13:39 -0500706 if len(input.expandedExcludes) == 0 {
Jooyung Han7607dd32020-07-05 10:23:14 +0900707 return paths
708 }
709 remainder := make(Paths, 0, len(paths))
710 for _, p := range paths {
Liz Kammer619be462022-01-28 15:13:39 -0500711 if !InList(p.String(), input.expandedExcludes) {
Jooyung Han7607dd32020-07-05 10:23:14 +0900712 remainder = append(remainder, p)
713 }
714 }
715 return remainder
716 }
Liz Kammer619be462022-01-28 15:13:39 -0500717 if m, t := SrcIsModuleWithTag(input.path); m != "" {
718 modulePaths, err := getPathsFromModuleDep(input.context, input.path, m, t)
Liz Kammera830f3a2020-11-10 10:50:34 -0800719 if err != nil {
720 return nil, err
Colin Cross8a497952019-03-05 22:25:09 -0800721 } else {
Liz Kammera830f3a2020-11-10 10:50:34 -0800722 return excludePaths(modulePaths), nil
Colin Cross8a497952019-03-05 22:25:09 -0800723 }
Colin Cross8a497952019-03-05 22:25:09 -0800724 } else {
Liz Kammer619be462022-01-28 15:13:39 -0500725 p := pathForModuleSrc(input.context, input.path)
726 if pathtools.IsGlob(input.path) {
727 paths := GlobFiles(input.context, p.String(), input.expandedExcludes)
728 return PathsWithModuleSrcSubDir(input.context, paths, ""), nil
729 } else {
730 if exists, _, err := input.context.Config().fs.Exists(p.String()); err != nil {
731 ReportPathErrorf(input.context, "%s: %s", p, err.Error())
732 } else if !exists && !input.context.Config().TestAllowNonExistentPaths {
733 ReportPathErrorf(input.context, "module source path %q does not exist", p)
734 } else if !input.includeDirs {
735 if isDir, err := input.context.Config().fs.IsDir(p.String()); exists && err != nil {
736 ReportPathErrorf(input.context, "%s: %s", p, err.Error())
737 } else if isDir {
738 ReportPathErrorf(input.context, "module source path %q is a directory", p)
739 }
740 }
Colin Cross8a497952019-03-05 22:25:09 -0800741
Liz Kammer619be462022-01-28 15:13:39 -0500742 if InList(p.String(), input.expandedExcludes) {
743 return nil, nil
744 }
745 return Paths{p}, nil
Colin Cross8a497952019-03-05 22:25:09 -0800746 }
Colin Cross8a497952019-03-05 22:25:09 -0800747 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700748}
749
750// pathsForModuleSrcFromFullPath returns Paths rooted from the module's local
751// source directory, but strip the local source directory from the beginning of
Dan Willemsen540a78c2018-02-26 21:50:08 -0800752// each string. If incDirs is false, strip paths with a trailing '/' from the list.
Colin Crossfe4bc362018-09-12 10:02:13 -0700753// It intended for use in globs that only list files that exist, so it allows '$' in
754// filenames.
Liz Kammera830f3a2020-11-10 10:50:34 -0800755func pathsForModuleSrcFromFullPath(ctx EarlyModulePathContext, paths []string, incDirs bool) Paths {
Lukacs T. Berkif7e36d82021-08-16 17:05:09 +0200756 prefix := ctx.ModuleDir() + "/"
Colin Cross0f37af02017-09-27 17:42:05 -0700757 if prefix == "./" {
758 prefix = ""
759 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700760 ret := make(Paths, 0, len(paths))
761 for _, p := range paths {
Dan Willemsen540a78c2018-02-26 21:50:08 -0800762 if !incDirs && strings.HasSuffix(p, "/") {
763 continue
764 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700765 path := filepath.Clean(p)
766 if !strings.HasPrefix(path, prefix) {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +0100767 ReportPathErrorf(ctx, "Path %q is not in module source directory %q", p, prefix)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700768 continue
769 }
Colin Crosse3924e12018-08-15 20:18:53 -0700770
Colin Crossfe4bc362018-09-12 10:02:13 -0700771 srcPath, err := safePathForSource(ctx, ctx.ModuleDir(), path[len(prefix):])
Colin Crosse3924e12018-08-15 20:18:53 -0700772 if err != nil {
773 reportPathError(ctx, err)
774 continue
775 }
776
Colin Cross07e51612019-03-05 12:46:40 -0800777 srcPath.basePath.rel = srcPath.path
Colin Crosse3924e12018-08-15 20:18:53 -0700778
Colin Cross07e51612019-03-05 12:46:40 -0800779 ret = append(ret, srcPath)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700780 }
781 return ret
782}
783
Liz Kammera830f3a2020-11-10 10:50:34 -0800784// PathsWithOptionalDefaultForModuleSrc returns Paths rooted from the module's local source
785// directory. If input is nil, use the default if it exists. If input is empty, returns nil.
786func PathsWithOptionalDefaultForModuleSrc(ctx ModuleMissingDepsPathContext, input []string, def string) Paths {
Colin Cross0ddae7f2019-02-07 15:30:01 -0800787 if input != nil {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700788 return PathsForModuleSrc(ctx, input)
789 }
790 // Use Glob so that if the default doesn't exist, a dependency is added so that when it
791 // is created, we're run again.
Lukacs T. Berkif7e36d82021-08-16 17:05:09 +0200792 path := filepath.Join(ctx.ModuleDir(), def)
Liz Kammera830f3a2020-11-10 10:50:34 -0800793 return Glob(ctx, path, nil)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700794}
795
796// Strings returns the Paths in string form
797func (p Paths) Strings() []string {
798 if p == nil {
799 return nil
800 }
801 ret := make([]string, len(p))
802 for i, path := range p {
803 ret[i] = path.String()
804 }
805 return ret
806}
807
Colin Crossc0efd1d2020-07-03 11:56:24 -0700808func CopyOfPaths(paths Paths) Paths {
809 return append(Paths(nil), paths...)
810}
811
Colin Crossb6715442017-10-24 11:13:31 -0700812// FirstUniquePaths returns all unique elements of a Paths, keeping the first copy of each. It
813// modifies the Paths slice contents in place, and returns a subslice of the original slice.
Dan Willemsenfe92c962017-08-29 12:28:37 -0700814func FirstUniquePaths(list Paths) Paths {
Colin Cross27027c72020-02-28 15:34:17 -0800815 // 128 was chosen based on BenchmarkFirstUniquePaths results.
816 if len(list) > 128 {
817 return firstUniquePathsMap(list)
818 }
819 return firstUniquePathsList(list)
820}
821
Colin Crossc0efd1d2020-07-03 11:56:24 -0700822// SortedUniquePaths returns all unique elements of a Paths in sorted order. It modifies the
823// Paths slice contents in place, and returns a subslice of the original slice.
Jiyong Park33c77362020-05-29 22:00:16 +0900824func SortedUniquePaths(list Paths) Paths {
825 unique := FirstUniquePaths(list)
826 sort.Slice(unique, func(i, j int) bool {
827 return unique[i].String() < unique[j].String()
828 })
829 return unique
830}
831
Colin Cross27027c72020-02-28 15:34:17 -0800832func firstUniquePathsList(list Paths) Paths {
Dan Willemsenfe92c962017-08-29 12:28:37 -0700833 k := 0
834outer:
835 for i := 0; i < len(list); i++ {
836 for j := 0; j < k; j++ {
837 if list[i] == list[j] {
838 continue outer
839 }
840 }
841 list[k] = list[i]
842 k++
843 }
844 return list[:k]
845}
846
Colin Cross27027c72020-02-28 15:34:17 -0800847func firstUniquePathsMap(list Paths) Paths {
848 k := 0
849 seen := make(map[Path]bool, len(list))
850 for i := 0; i < len(list); i++ {
851 if seen[list[i]] {
852 continue
853 }
854 seen[list[i]] = true
855 list[k] = list[i]
856 k++
857 }
858 return list[:k]
859}
860
Colin Cross5d583952020-11-24 16:21:24 -0800861// FirstUniqueInstallPaths returns all unique elements of an InstallPaths, keeping the first copy of each. It
862// modifies the InstallPaths slice contents in place, and returns a subslice of the original slice.
863func FirstUniqueInstallPaths(list InstallPaths) InstallPaths {
864 // 128 was chosen based on BenchmarkFirstUniquePaths results.
865 if len(list) > 128 {
866 return firstUniqueInstallPathsMap(list)
867 }
868 return firstUniqueInstallPathsList(list)
869}
870
871func firstUniqueInstallPathsList(list InstallPaths) InstallPaths {
872 k := 0
873outer:
874 for i := 0; i < len(list); i++ {
875 for j := 0; j < k; j++ {
876 if list[i] == list[j] {
877 continue outer
878 }
879 }
880 list[k] = list[i]
881 k++
882 }
883 return list[:k]
884}
885
886func firstUniqueInstallPathsMap(list InstallPaths) InstallPaths {
887 k := 0
888 seen := make(map[InstallPath]bool, len(list))
889 for i := 0; i < len(list); i++ {
890 if seen[list[i]] {
891 continue
892 }
893 seen[list[i]] = true
894 list[k] = list[i]
895 k++
896 }
897 return list[:k]
898}
899
Colin Crossb6715442017-10-24 11:13:31 -0700900// LastUniquePaths returns all unique elements of a Paths, keeping the last copy of each. It
901// modifies the Paths slice contents in place, and returns a subslice of the original slice.
902func LastUniquePaths(list Paths) Paths {
903 totalSkip := 0
904 for i := len(list) - 1; i >= totalSkip; i-- {
905 skip := 0
906 for j := i - 1; j >= totalSkip; j-- {
907 if list[i] == list[j] {
908 skip++
909 } else {
910 list[j+skip] = list[j]
911 }
912 }
913 totalSkip += skip
914 }
915 return list[totalSkip:]
916}
917
Colin Crossa140bb02018-04-17 10:52:26 -0700918// ReversePaths returns a copy of a Paths in reverse order.
919func ReversePaths(list Paths) Paths {
920 if list == nil {
921 return nil
922 }
923 ret := make(Paths, len(list))
924 for i := range list {
925 ret[i] = list[len(list)-1-i]
926 }
927 return ret
928}
929
Jeff Gaston294356f2017-09-27 17:05:30 -0700930func indexPathList(s Path, list []Path) int {
931 for i, l := range list {
932 if l == s {
933 return i
934 }
935 }
936
937 return -1
938}
939
940func inPathList(p Path, list []Path) bool {
941 return indexPathList(p, list) != -1
942}
943
944func FilterPathList(list []Path, filter []Path) (remainder []Path, filtered []Path) {
Paul Duffin57b9e1d2019-12-13 00:03:35 +0000945 return FilterPathListPredicate(list, func(p Path) bool { return inPathList(p, filter) })
946}
947
948func FilterPathListPredicate(list []Path, predicate func(Path) bool) (remainder []Path, filtered []Path) {
Jeff Gaston294356f2017-09-27 17:05:30 -0700949 for _, l := range list {
Paul Duffin57b9e1d2019-12-13 00:03:35 +0000950 if predicate(l) {
Jeff Gaston294356f2017-09-27 17:05:30 -0700951 filtered = append(filtered, l)
952 } else {
953 remainder = append(remainder, l)
954 }
955 }
956
957 return
958}
959
Colin Cross93e85952017-08-15 13:34:18 -0700960// HasExt returns true of any of the paths have extension ext, otherwise false
961func (p Paths) HasExt(ext string) bool {
962 for _, path := range p {
963 if path.Ext() == ext {
964 return true
965 }
966 }
967
968 return false
969}
970
971// FilterByExt returns the subset of the paths that have extension ext
972func (p Paths) FilterByExt(ext string) Paths {
973 ret := make(Paths, 0, len(p))
974 for _, path := range p {
975 if path.Ext() == ext {
976 ret = append(ret, path)
977 }
978 }
979 return ret
980}
981
982// FilterOutByExt returns the subset of the paths that do not have extension ext
983func (p Paths) FilterOutByExt(ext string) Paths {
984 ret := make(Paths, 0, len(p))
985 for _, path := range p {
986 if path.Ext() != ext {
987 ret = append(ret, path)
988 }
989 }
990 return ret
991}
992
Colin Cross5e6cfbe2017-11-03 15:20:35 -0700993// DirectorySortedPaths is a slice of paths that are sorted such that all files in a directory
994// (including subdirectories) are in a contiguous subslice of the list, and can be found in
995// O(log(N)) time using a binary search on the directory prefix.
996type DirectorySortedPaths Paths
997
998func PathsToDirectorySortedPaths(paths Paths) DirectorySortedPaths {
999 ret := append(DirectorySortedPaths(nil), paths...)
1000 sort.Slice(ret, func(i, j int) bool {
1001 return ret[i].String() < ret[j].String()
1002 })
1003 return ret
1004}
1005
1006// PathsInDirectory returns a subslice of the DirectorySortedPaths as a Paths that contains all entries
1007// that are in the specified directory and its subdirectories.
1008func (p DirectorySortedPaths) PathsInDirectory(dir string) Paths {
1009 prefix := filepath.Clean(dir) + "/"
1010 start := sort.Search(len(p), func(i int) bool {
1011 return prefix < p[i].String()
1012 })
1013
1014 ret := p[start:]
1015
1016 end := sort.Search(len(ret), func(i int) bool {
1017 return !strings.HasPrefix(ret[i].String(), prefix)
1018 })
1019
1020 ret = ret[:end]
1021
1022 return Paths(ret)
1023}
1024
Alex Humesky29e3bbe2020-11-20 21:30:13 -05001025// WritablePaths is a slice of WritablePath, used for multiple outputs.
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001026type WritablePaths []WritablePath
1027
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001028// RelativeToTop creates a new WritablePaths containing the result of calling Path.RelativeToTop on
1029// each item in this slice.
1030func (p WritablePaths) RelativeToTop() WritablePaths {
1031 ensureTestOnly()
1032 if p == nil {
1033 return p
1034 }
1035 ret := make(WritablePaths, len(p))
1036 for i, path := range p {
1037 ret[i] = path.RelativeToTop().(WritablePath)
1038 }
1039 return ret
1040}
1041
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001042// Strings returns the string forms of the writable paths.
1043func (p WritablePaths) Strings() []string {
1044 if p == nil {
1045 return nil
1046 }
1047 ret := make([]string, len(p))
1048 for i, path := range p {
1049 ret[i] = path.String()
1050 }
1051 return ret
1052}
1053
Colin Cross3bc7ffa2017-11-22 16:19:37 -08001054// Paths returns the WritablePaths as a Paths
1055func (p WritablePaths) Paths() Paths {
1056 if p == nil {
1057 return nil
1058 }
1059 ret := make(Paths, len(p))
1060 for i, path := range p {
1061 ret[i] = path
1062 }
1063 return ret
1064}
1065
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001066type basePath struct {
Paul Duffin74abc5d2021-03-24 09:24:59 +00001067 path string
1068 rel string
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001069}
1070
1071func (p basePath) Ext() string {
1072 return filepath.Ext(p.path)
1073}
1074
Colin Cross4f6fc9c2016-10-26 10:05:25 -07001075func (p basePath) Base() string {
1076 return filepath.Base(p.path)
1077}
1078
Colin Crossfaeb7aa2017-02-01 14:12:44 -08001079func (p basePath) Rel() string {
1080 if p.rel != "" {
1081 return p.rel
1082 }
1083 return p.path
1084}
1085
Colin Cross0875c522017-11-28 17:34:01 -08001086func (p basePath) String() string {
1087 return p.path
1088}
1089
Colin Cross0db55682017-12-05 15:36:55 -08001090func (p basePath) withRel(rel string) basePath {
1091 p.path = filepath.Join(p.path, rel)
1092 p.rel = rel
1093 return p
1094}
1095
Cole Faustbc65a3f2023-08-01 16:38:55 +00001096func (p basePath) RelativeToTop() Path {
1097 ensureTestOnly()
1098 return p
1099}
1100
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001101// SourcePath is a Path representing a file path rooted from SrcDir
1102type SourcePath struct {
1103 basePath
1104}
1105
1106var _ Path = SourcePath{}
1107
Colin Cross0db55682017-12-05 15:36:55 -08001108func (p SourcePath) withRel(rel string) SourcePath {
1109 p.basePath = p.basePath.withRel(rel)
1110 return p
1111}
1112
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001113// safePathForSource is for paths that we expect are safe -- only for use by go
1114// code that is embedding ninja variables in paths
Colin Crossfe4bc362018-09-12 10:02:13 -07001115func safePathForSource(ctx PathContext, pathComponents ...string) (SourcePath, error) {
1116 p, err := validateSafePath(pathComponents...)
Cole Faust483d1f72023-01-09 14:35:27 -08001117 ret := SourcePath{basePath{p, ""}}
Colin Crossfe4bc362018-09-12 10:02:13 -07001118 if err != nil {
1119 return ret, err
1120 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001121
Colin Cross7b3dcc32019-01-24 13:14:39 -08001122 // absolute path already checked by validateSafePath
Inseob Kim5eb7ee92022-04-27 10:30:34 +09001123 // special-case api surface gen files for now
1124 if strings.HasPrefix(ret.String(), ctx.Config().soongOutDir) && !strings.Contains(ret.String(), ctx.Config().soongOutDir+"/.export") {
Mikhail Naganovab1f5182019-02-08 13:17:55 -08001125 return ret, fmt.Errorf("source path %q is in output", ret.String())
Colin Cross6e18ca42015-07-14 18:55:36 -07001126 }
1127
Colin Crossfe4bc362018-09-12 10:02:13 -07001128 return ret, err
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001129}
1130
Colin Cross192e97a2018-02-22 14:21:02 -08001131// pathForSource creates a SourcePath from pathComponents, but does not check that it exists.
1132func pathForSource(ctx PathContext, pathComponents ...string) (SourcePath, error) {
Colin Crossc48c1432018-02-23 07:09:01 +00001133 p, err := validatePath(pathComponents...)
Cole Faust483d1f72023-01-09 14:35:27 -08001134 ret := SourcePath{basePath{p, ""}}
Colin Cross94a32102018-02-22 14:21:02 -08001135 if err != nil {
Colin Cross192e97a2018-02-22 14:21:02 -08001136 return ret, err
Colin Cross94a32102018-02-22 14:21:02 -08001137 }
1138
Colin Cross7b3dcc32019-01-24 13:14:39 -08001139 // absolute path already checked by validatePath
Inseob Kim5eb7ee92022-04-27 10:30:34 +09001140 // special-case for now
1141 if strings.HasPrefix(ret.String(), ctx.Config().soongOutDir) && !strings.Contains(ret.String(), ctx.Config().soongOutDir+"/.export") {
Mikhail Naganovab1f5182019-02-08 13:17:55 -08001142 return ret, fmt.Errorf("source path %q is in output", ret.String())
Colin Crossc48c1432018-02-23 07:09:01 +00001143 }
1144
Colin Cross192e97a2018-02-22 14:21:02 -08001145 return ret, nil
1146}
1147
Sam Mortimerefd02782019-09-05 15:16:13 -07001148// pathForSourceRelaxed creates a SourcePath from pathComponents, but does not check that it exists.
1149// It differs from pathForSource in that the path is allowed to exist outside of the PathContext.
1150func pathForSourceRelaxed(ctx PathContext, pathComponents ...string) (SourcePath, error) {
1151 p := filepath.Join(pathComponents...)
1152 ret := SourcePath{basePath{p, ""}}
1153
1154 abs, err := filepath.Abs(ret.String())
1155 if err != nil {
1156 return ret, err
1157 }
1158 buildroot, err := filepath.Abs(ctx.Config().outDir)
1159 if err != nil {
1160 return ret, err
1161 }
1162 if strings.HasPrefix(abs, buildroot) {
1163 return ret, fmt.Errorf("source path %s is in output", abs)
1164 }
1165
1166 if pathtools.IsGlob(ret.String()) {
1167 return ret, fmt.Errorf("path may not contain a glob: %s", ret.String())
1168 }
1169
1170 return ret, nil
1171}
1172
Colin Cross192e97a2018-02-22 14:21:02 -08001173// existsWithDependencies returns true if the path exists, and adds appropriate dependencies to rerun if the
1174// path does not exist.
Colin Cross662d6142022-11-03 20:38:01 -07001175func existsWithDependencies(ctx PathGlobContext, path SourcePath) (exists bool, err error) {
Colin Cross192e97a2018-02-22 14:21:02 -08001176 var files []string
1177
Colin Cross662d6142022-11-03 20:38:01 -07001178 // Use glob to produce proper dependencies, even though we only want
1179 // a single file.
1180 files, err = ctx.GlobWithDeps(path.String(), nil)
Colin Cross192e97a2018-02-22 14:21:02 -08001181
1182 if err != nil {
1183 return false, fmt.Errorf("glob: %s", err.Error())
1184 }
1185
1186 return len(files) > 0, nil
1187}
1188
1189// PathForSource joins the provided path components and validates that the result
1190// neither escapes the source dir nor is in the out dir.
1191// On error, it will return a usable, but invalid SourcePath, and report a ModuleError.
1192func PathForSource(ctx PathContext, pathComponents ...string) SourcePath {
1193 path, err := pathForSource(ctx, pathComponents...)
1194 if err != nil {
1195 reportPathError(ctx, err)
1196 }
1197
Colin Crosse3924e12018-08-15 20:18:53 -07001198 if pathtools.IsGlob(path.String()) {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001199 ReportPathErrorf(ctx, "path may not contain a glob: %s", path.String())
Colin Crosse3924e12018-08-15 20:18:53 -07001200 }
1201
Liz Kammera830f3a2020-11-10 10:50:34 -08001202 if modCtx, ok := ctx.(ModuleMissingDepsPathContext); ok && ctx.Config().AllowMissingDependencies() {
Colin Cross662d6142022-11-03 20:38:01 -07001203 exists, err := existsWithDependencies(modCtx, path)
Colin Cross192e97a2018-02-22 14:21:02 -08001204 if err != nil {
1205 reportPathError(ctx, err)
1206 }
1207 if !exists {
1208 modCtx.AddMissingDependencies([]string{path.String()})
1209 }
Colin Cross988414c2020-01-11 01:11:46 +00001210 } else if exists, _, err := ctx.Config().fs.Exists(path.String()); err != nil {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001211 ReportPathErrorf(ctx, "%s: %s", path, err.Error())
Pedro Loureiro5d190cc2021-02-15 15:41:33 +00001212 } else if !exists && !ctx.Config().TestAllowNonExistentPaths {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001213 ReportPathErrorf(ctx, "source path %q does not exist", path)
Colin Cross192e97a2018-02-22 14:21:02 -08001214 }
1215 return path
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001216}
1217
Cole Faustbc65a3f2023-08-01 16:38:55 +00001218// PathForArbitraryOutput creates a path for the given components. Unlike PathForOutput,
1219// the path is relative to the root of the output folder, not the out/soong folder.
1220func PathForArbitraryOutput(ctx PathContext, pathComponents ...string) Path {
1221 p, err := validatePath(pathComponents...)
1222 if err != nil {
1223 reportPathError(ctx, err)
1224 }
1225 return basePath{path: filepath.Join(ctx.Config().OutDir(), p)}
1226}
1227
Spandan Dasc6c10fa2022-10-21 21:52:13 +00001228// MaybeExistentPathForSource joins the provided path components and validates that the result
1229// neither escapes the source dir nor is in the out dir.
1230// It does not validate whether the path exists.
1231func MaybeExistentPathForSource(ctx PathContext, pathComponents ...string) SourcePath {
1232 path, err := pathForSource(ctx, pathComponents...)
1233 if err != nil {
1234 reportPathError(ctx, err)
1235 }
1236
1237 if pathtools.IsGlob(path.String()) {
1238 ReportPathErrorf(ctx, "path may not contain a glob: %s", path.String())
1239 }
1240 return path
1241}
1242
Sam Mortimerefd02782019-09-05 15:16:13 -07001243// PathForSourceRelaxed joins the provided path components. Unlike PathForSource,
1244// the result is allowed to exist outside of the source dir.
1245// On error, it will return a usable, but invalid SourcePath, and report a ModuleError.
1246func PathForSourceRelaxed(ctx PathContext, pathComponents ...string) SourcePath {
1247 path, err := pathForSourceRelaxed(ctx, pathComponents...)
1248 if err != nil {
1249 reportPathError(ctx, err)
1250 }
1251
1252 if modCtx, ok := ctx.(ModuleMissingDepsPathContext); ok && ctx.Config().AllowMissingDependencies() {
1253 exists, err := existsWithDependencies(modCtx, path)
1254 if err != nil {
1255 reportPathError(ctx, err)
1256 }
1257 if !exists {
1258 modCtx.AddMissingDependencies([]string{path.String()})
1259 }
1260 } else if exists, _, err := ctx.Config().fs.Exists(path.String()); err != nil {
1261 ReportPathErrorf(ctx, "%s: %s", path, err.Error())
1262 } else if !exists {
1263 ReportPathErrorf(ctx, "source path %s does not exist", path)
1264 }
1265 return path
1266}
1267
Liz Kammer7aa52882021-02-11 09:16:14 -05001268// ExistentPathForSource returns an OptionalPath with the SourcePath, rooted from SrcDir, *not*
1269// rooted from the module's local source directory, if the path exists, or an empty OptionalPath if
1270// it doesn't exist. Dependencies are added so that the ninja file will be regenerated if the state
1271// of the path changes.
Colin Cross662d6142022-11-03 20:38:01 -07001272func ExistentPathForSource(ctx PathGlobContext, pathComponents ...string) OptionalPath {
Colin Cross192e97a2018-02-22 14:21:02 -08001273 path, err := pathForSource(ctx, pathComponents...)
Colin Cross1ccfcc32018-02-22 13:54:26 -08001274 if err != nil {
1275 reportPathError(ctx, err)
Martin Stjernholmc32dd1c2021-09-15 02:39:00 +01001276 // No need to put the error message into the returned path since it has been reported already.
Colin Cross1ccfcc32018-02-22 13:54:26 -08001277 return OptionalPath{}
1278 }
Colin Crossc48c1432018-02-23 07:09:01 +00001279
Colin Crosse3924e12018-08-15 20:18:53 -07001280 if pathtools.IsGlob(path.String()) {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001281 ReportPathErrorf(ctx, "path may not contain a glob: %s", path.String())
Colin Crosse3924e12018-08-15 20:18:53 -07001282 return OptionalPath{}
1283 }
1284
Colin Cross192e97a2018-02-22 14:21:02 -08001285 exists, err := existsWithDependencies(ctx, path)
Colin Crossc48c1432018-02-23 07:09:01 +00001286 if err != nil {
1287 reportPathError(ctx, err)
1288 return OptionalPath{}
1289 }
Colin Cross192e97a2018-02-22 14:21:02 -08001290 if !exists {
Martin Stjernholmc32dd1c2021-09-15 02:39:00 +01001291 return InvalidOptionalPath(path.String() + " does not exist")
Colin Crossc48c1432018-02-23 07:09:01 +00001292 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001293 return OptionalPathForPath(path)
1294}
1295
1296func (p SourcePath) String() string {
Cole Faust483d1f72023-01-09 14:35:27 -08001297 if p.path == "" {
1298 return "."
1299 }
1300 return p.path
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001301}
1302
1303// Join creates a new SourcePath with paths... joined with the current path. The
1304// provided paths... may not use '..' to escape from the current path.
1305func (p SourcePath) Join(ctx PathContext, paths ...string) SourcePath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001306 path, err := validatePath(paths...)
1307 if err != nil {
1308 reportPathError(ctx, err)
1309 }
Colin Cross0db55682017-12-05 15:36:55 -08001310 return p.withRel(path)
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001311}
1312
Colin Cross2fafa3e2019-03-05 12:39:51 -08001313// join is like Join but does less path validation.
1314func (p SourcePath) join(ctx PathContext, paths ...string) SourcePath {
1315 path, err := validateSafePath(paths...)
1316 if err != nil {
1317 reportPathError(ctx, err)
1318 }
1319 return p.withRel(path)
1320}
1321
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001322// OverlayPath returns the overlay for `path' if it exists. This assumes that the
1323// SourcePath is the path to a resource overlay directory.
Liz Kammera830f3a2020-11-10 10:50:34 -08001324func (p SourcePath) OverlayPath(ctx ModuleMissingDepsPathContext, path Path) OptionalPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001325 var relDir string
Colin Cross07e51612019-03-05 12:46:40 -08001326 if srcPath, ok := path.(SourcePath); ok {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001327 relDir = srcPath.path
1328 } else {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001329 ReportPathErrorf(ctx, "Cannot find relative path for %s(%s)", reflect.TypeOf(path).Name(), path)
Martin Stjernholmc32dd1c2021-09-15 02:39:00 +01001330 // No need to put the error message into the returned path since it has been reported already.
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001331 return OptionalPath{}
1332 }
Cole Faust483d1f72023-01-09 14:35:27 -08001333 dir := filepath.Join(p.path, relDir)
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001334 // Use Glob so that we are run again if the directory is added.
Colin Cross7f19f372016-11-01 11:10:25 -07001335 if pathtools.IsGlob(dir) {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001336 ReportPathErrorf(ctx, "Path may not contain a glob: %s", dir)
Dan Willemsen7b310ee2015-12-18 15:11:17 -08001337 }
Colin Cross461b4452018-02-23 09:22:42 -08001338 paths, err := ctx.GlobWithDeps(dir, nil)
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001339 if err != nil {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001340 ReportPathErrorf(ctx, "glob: %s", err.Error())
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001341 return OptionalPath{}
1342 }
1343 if len(paths) == 0 {
Martin Stjernholmc32dd1c2021-09-15 02:39:00 +01001344 return InvalidOptionalPath(dir + " does not exist")
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001345 }
Cole Faust483d1f72023-01-09 14:35:27 -08001346 return OptionalPathForPath(PathForSource(ctx, paths[0]))
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001347}
1348
Colin Cross70dda7e2019-10-01 22:05:35 -07001349// OutputPath is a Path representing an intermediates file path rooted from the build directory
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001350type OutputPath struct {
1351 basePath
Paul Duffind65c58b2021-03-24 09:22:07 +00001352
Lukacs T. Berkib078ade2021-08-31 10:42:08 +02001353 // The soong build directory, i.e. Config.SoongOutDir()
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02001354 soongOutDir string
Paul Duffind65c58b2021-03-24 09:22:07 +00001355
Colin Crossd63c9a72020-01-29 16:52:50 -08001356 fullPath string
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001357}
1358
Colin Cross702e0f82017-10-18 17:27:54 -07001359func (p OutputPath) withRel(rel string) OutputPath {
Colin Cross0db55682017-12-05 15:36:55 -08001360 p.basePath = p.basePath.withRel(rel)
Colin Crossd63c9a72020-01-29 16:52:50 -08001361 p.fullPath = filepath.Join(p.fullPath, rel)
Colin Cross702e0f82017-10-18 17:27:54 -07001362 return p
1363}
1364
Colin Cross3063b782018-08-15 11:19:12 -07001365func (p OutputPath) WithoutRel() OutputPath {
1366 p.basePath.rel = filepath.Base(p.basePath.path)
1367 return p
1368}
1369
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02001370func (p OutputPath) getSoongOutDir() string {
1371 return p.soongOutDir
Paul Duffin9b478b02019-12-10 13:41:51 +00001372}
1373
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001374func (p OutputPath) RelativeToTop() Path {
1375 return p.outputPathRelativeToTop()
1376}
1377
1378func (p OutputPath) outputPathRelativeToTop() OutputPath {
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02001379 p.fullPath = StringPathRelativeToTop(p.soongOutDir, p.fullPath)
1380 p.soongOutDir = OutSoongDir
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001381 return p
1382}
1383
Paul Duffin0267d492021-02-02 10:05:52 +00001384func (p OutputPath) objPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleObjPath {
1385 return PathForModuleObj(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
1386}
1387
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001388var _ Path = OutputPath{}
Paul Duffin9b478b02019-12-10 13:41:51 +00001389var _ WritablePath = OutputPath{}
Paul Duffin0267d492021-02-02 10:05:52 +00001390var _ objPathProvider = OutputPath{}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001391
Chris Parsons8f232a22020-06-23 17:37:05 -04001392// toolDepPath is a Path representing a dependency of the build tool.
1393type toolDepPath struct {
1394 basePath
1395}
1396
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001397func (t toolDepPath) RelativeToTop() Path {
1398 ensureTestOnly()
1399 return t
1400}
1401
Chris Parsons8f232a22020-06-23 17:37:05 -04001402var _ Path = toolDepPath{}
1403
1404// pathForBuildToolDep returns a toolDepPath representing the given path string.
1405// There is no validation for the path, as it is "trusted": It may fail
1406// normal validation checks. For example, it may be an absolute path.
1407// Only use this function to construct paths for dependencies of the build
1408// tool invocation.
1409func pathForBuildToolDep(ctx PathContext, path string) toolDepPath {
Paul Duffin74abc5d2021-03-24 09:24:59 +00001410 return toolDepPath{basePath{path, ""}}
Chris Parsons8f232a22020-06-23 17:37:05 -04001411}
1412
Jeff Gaston734e3802017-04-10 15:47:24 -07001413// PathForOutput joins the provided paths and returns an OutputPath that is
1414// validated to not escape the build dir.
1415// On error, it will return a usable, but invalid OutputPath, and report a ModuleError.
1416func PathForOutput(ctx PathContext, pathComponents ...string) OutputPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001417 path, err := validatePath(pathComponents...)
1418 if err != nil {
1419 reportPathError(ctx, err)
1420 }
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02001421 fullPath := filepath.Join(ctx.Config().soongOutDir, path)
Colin Crossd63c9a72020-01-29 16:52:50 -08001422 path = fullPath[len(fullPath)-len(path):]
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02001423 return OutputPath{basePath{path, ""}, ctx.Config().soongOutDir, fullPath}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001424}
1425
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02001426// PathsForOutput returns Paths rooted from soongOutDir
Colin Cross40e33732019-02-15 11:08:35 -08001427func PathsForOutput(ctx PathContext, paths []string) WritablePaths {
1428 ret := make(WritablePaths, len(paths))
1429 for i, path := range paths {
1430 ret[i] = PathForOutput(ctx, path)
1431 }
1432 return ret
1433}
1434
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001435func (p OutputPath) writablePath() {}
1436
1437func (p OutputPath) String() string {
Colin Crossd63c9a72020-01-29 16:52:50 -08001438 return p.fullPath
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001439}
1440
1441// Join creates a new OutputPath with paths... joined with the current path. The
1442// provided paths... may not use '..' to escape from the current path.
1443func (p OutputPath) Join(ctx PathContext, paths ...string) OutputPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001444 path, err := validatePath(paths...)
1445 if err != nil {
1446 reportPathError(ctx, err)
1447 }
Colin Cross0db55682017-12-05 15:36:55 -08001448 return p.withRel(path)
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001449}
1450
Colin Cross8854a5a2019-02-11 14:14:16 -08001451// ReplaceExtension creates a new OutputPath with the extension replaced with ext.
1452func (p OutputPath) ReplaceExtension(ctx PathContext, ext string) OutputPath {
1453 if strings.Contains(ext, "/") {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001454 ReportPathErrorf(ctx, "extension %q cannot contain /", ext)
Colin Cross8854a5a2019-02-11 14:14:16 -08001455 }
1456 ret := PathForOutput(ctx, pathtools.ReplaceExtension(p.path, ext))
Colin Cross2cdd5df2019-02-25 10:25:24 -08001457 ret.rel = pathtools.ReplaceExtension(p.rel, ext)
Colin Cross8854a5a2019-02-11 14:14:16 -08001458 return ret
1459}
1460
Colin Cross40e33732019-02-15 11:08:35 -08001461// InSameDir creates a new OutputPath from the directory of the current OutputPath joined with the elements in paths.
1462func (p OutputPath) InSameDir(ctx PathContext, paths ...string) OutputPath {
1463 path, err := validatePath(paths...)
1464 if err != nil {
1465 reportPathError(ctx, err)
1466 }
1467
1468 ret := PathForOutput(ctx, filepath.Dir(p.path), path)
Colin Cross2cdd5df2019-02-25 10:25:24 -08001469 ret.rel = filepath.Join(filepath.Dir(p.rel), path)
Colin Cross40e33732019-02-15 11:08:35 -08001470 return ret
1471}
1472
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001473// PathForIntermediates returns an OutputPath representing the top-level
1474// intermediates directory.
1475func PathForIntermediates(ctx PathContext, paths ...string) OutputPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001476 path, err := validatePath(paths...)
1477 if err != nil {
1478 reportPathError(ctx, err)
1479 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001480 return PathForOutput(ctx, ".intermediates", path)
1481}
1482
Colin Cross07e51612019-03-05 12:46:40 -08001483var _ genPathProvider = SourcePath{}
1484var _ objPathProvider = SourcePath{}
1485var _ resPathProvider = SourcePath{}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001486
Colin Cross07e51612019-03-05 12:46:40 -08001487// PathForModuleSrc returns a Path representing the paths... under the
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001488// module's local source directory.
Liz Kammera830f3a2020-11-10 10:50:34 -08001489func PathForModuleSrc(ctx ModuleMissingDepsPathContext, pathComponents ...string) Path {
Paul Duffin407501b2021-07-09 16:56:35 +01001490 // Just join the components textually just to make sure that it does not corrupt a fully qualified
1491 // module reference, e.g. if the pathComponents is "://other:foo" then using filepath.Join() or
1492 // validatePath() will corrupt it, e.g. replace "//" with "/". If the path is not a module
1493 // reference then it will be validated by expandOneSrcPath anyway when it calls expandOneSrcPath.
1494 p := strings.Join(pathComponents, string(filepath.Separator))
Liz Kammer619be462022-01-28 15:13:39 -05001495 paths, err := expandOneSrcPath(sourcePathInput{context: ctx, path: p, includeDirs: true})
Colin Cross8a497952019-03-05 22:25:09 -08001496 if err != nil {
1497 if depErr, ok := err.(missingDependencyError); ok {
1498 if ctx.Config().AllowMissingDependencies() {
1499 ctx.AddMissingDependencies(depErr.missingDeps)
1500 } else {
1501 ctx.ModuleErrorf(`%s, is the property annotated with android:"path"?`, depErr.Error())
1502 }
1503 } else {
1504 reportPathError(ctx, err)
1505 }
1506 return nil
1507 } else if len(paths) == 0 {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001508 ReportPathErrorf(ctx, "%q produced no files, expected exactly one", p)
Colin Cross8a497952019-03-05 22:25:09 -08001509 return nil
1510 } else if len(paths) > 1 {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001511 ReportPathErrorf(ctx, "%q produced %d files, expected exactly one", p, len(paths))
Colin Cross8a497952019-03-05 22:25:09 -08001512 }
1513 return paths[0]
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001514}
1515
Liz Kammera830f3a2020-11-10 10:50:34 -08001516func pathForModuleSrc(ctx EarlyModulePathContext, paths ...string) SourcePath {
Colin Cross07e51612019-03-05 12:46:40 -08001517 p, err := validatePath(paths...)
1518 if err != nil {
1519 reportPathError(ctx, err)
1520 }
1521
1522 path, err := pathForSource(ctx, ctx.ModuleDir(), p)
1523 if err != nil {
1524 reportPathError(ctx, err)
1525 }
1526
1527 path.basePath.rel = p
1528
1529 return path
1530}
1531
Colin Cross2fafa3e2019-03-05 12:39:51 -08001532// PathsWithModuleSrcSubDir takes a list of Paths and returns a new list of Paths where Rel() on each path
1533// will return the path relative to subDir in the module's source directory. If any input paths are not located
1534// inside subDir then a path error will be reported.
Liz Kammera830f3a2020-11-10 10:50:34 -08001535func PathsWithModuleSrcSubDir(ctx EarlyModulePathContext, paths Paths, subDir string) Paths {
Colin Cross2fafa3e2019-03-05 12:39:51 -08001536 paths = append(Paths(nil), paths...)
Colin Cross07e51612019-03-05 12:46:40 -08001537 subDirFullPath := pathForModuleSrc(ctx, subDir)
Colin Cross2fafa3e2019-03-05 12:39:51 -08001538 for i, path := range paths {
1539 rel := Rel(ctx, subDirFullPath.String(), path.String())
1540 paths[i] = subDirFullPath.join(ctx, rel)
1541 }
1542 return paths
1543}
1544
1545// PathWithModuleSrcSubDir takes a Path and returns a Path where Rel() will return the path relative to subDir in the
1546// 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 -08001547func PathWithModuleSrcSubDir(ctx EarlyModulePathContext, path Path, subDir string) Path {
Colin Cross07e51612019-03-05 12:46:40 -08001548 subDirFullPath := pathForModuleSrc(ctx, subDir)
Colin Cross2fafa3e2019-03-05 12:39:51 -08001549 rel := Rel(ctx, subDirFullPath.String(), path.String())
1550 return subDirFullPath.Join(ctx, rel)
1551}
1552
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001553// OptionalPathForModuleSrc returns an OptionalPath. The OptionalPath contains a
1554// valid path if p is non-nil.
Liz Kammera830f3a2020-11-10 10:50:34 -08001555func OptionalPathForModuleSrc(ctx ModuleMissingDepsPathContext, p *string) OptionalPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001556 if p == nil {
1557 return OptionalPath{}
1558 }
1559 return OptionalPathForPath(PathForModuleSrc(ctx, *p))
1560}
1561
Liz Kammera830f3a2020-11-10 10:50:34 -08001562func (p SourcePath) genPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleGenPath {
Colin Cross7fc17db2017-02-01 14:07:55 -08001563 return PathForModuleGen(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001564}
1565
yangbill6d032dd2024-04-18 03:05:49 +00001566func (p SourcePath) genPathWithExtAndTrimExt(ctx ModuleOutPathContext, subdir, ext string, trimExt string) ModuleGenPath {
1567 // If Trim_extension being set, force append Output_extension without replace original extension.
1568 if trimExt != "" {
1569 if ext != "" {
1570 return PathForModuleGen(ctx, subdir, strings.TrimSuffix(p.path, trimExt)+"."+ext)
1571 }
1572 return PathForModuleGen(ctx, subdir, strings.TrimSuffix(p.path, trimExt))
1573 }
1574 return PathForModuleGen(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
1575}
1576
Liz Kammera830f3a2020-11-10 10:50:34 -08001577func (p SourcePath) objPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleObjPath {
Colin Cross7fc17db2017-02-01 14:07:55 -08001578 return PathForModuleObj(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001579}
1580
Liz Kammera830f3a2020-11-10 10:50:34 -08001581func (p SourcePath) resPathWithName(ctx ModuleOutPathContext, name string) ModuleResPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001582 // TODO: Use full directory if the new ctx is not the current ctx?
1583 return PathForModuleRes(ctx, p.path, name)
1584}
1585
1586// ModuleOutPath is a Path representing a module's output directory.
1587type ModuleOutPath struct {
1588 OutputPath
1589}
1590
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001591func (p ModuleOutPath) RelativeToTop() Path {
1592 p.OutputPath = p.outputPathRelativeToTop()
1593 return p
1594}
1595
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001596var _ Path = ModuleOutPath{}
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001597var _ WritablePath = ModuleOutPath{}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001598
Liz Kammera830f3a2020-11-10 10:50:34 -08001599func (p ModuleOutPath) objPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleObjPath {
Pete Bentleyfcf55bf2019-08-16 20:14:32 +01001600 return PathForModuleObj(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
1601}
1602
Liz Kammera830f3a2020-11-10 10:50:34 -08001603// ModuleOutPathContext Subset of ModuleContext functions necessary for output path methods.
1604type ModuleOutPathContext interface {
1605 PathContext
1606
1607 ModuleName() string
1608 ModuleDir() string
1609 ModuleSubDir() string
Inseob Kim8ff69de2023-06-16 14:19:33 +09001610 SoongConfigTraceHash() string
Liz Kammera830f3a2020-11-10 10:50:34 -08001611}
1612
1613func pathForModuleOut(ctx ModuleOutPathContext) OutputPath {
Inseob Kim8ff69de2023-06-16 14:19:33 +09001614 return PathForOutput(ctx, ".intermediates", ctx.ModuleDir(), ctx.ModuleName(), ctx.ModuleSubDir(), ctx.SoongConfigTraceHash())
Colin Cross702e0f82017-10-18 17:27:54 -07001615}
1616
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001617// PathForModuleOut returns a Path representing the paths... under the module's
1618// output directory.
Liz Kammera830f3a2020-11-10 10:50:34 -08001619func PathForModuleOut(ctx ModuleOutPathContext, paths ...string) ModuleOutPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001620 p, err := validatePath(paths...)
1621 if err != nil {
1622 reportPathError(ctx, err)
1623 }
Colin Cross702e0f82017-10-18 17:27:54 -07001624 return ModuleOutPath{
Liz Kammera830f3a2020-11-10 10:50:34 -08001625 OutputPath: pathForModuleOut(ctx).withRel(p),
Colin Cross702e0f82017-10-18 17:27:54 -07001626 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001627}
1628
1629// ModuleGenPath is a Path representing the 'gen' directory in a module's output
1630// directory. Mainly used for generated sources.
1631type ModuleGenPath struct {
1632 ModuleOutPath
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001633}
1634
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001635func (p ModuleGenPath) RelativeToTop() Path {
1636 p.OutputPath = p.outputPathRelativeToTop()
1637 return p
1638}
1639
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001640var _ Path = ModuleGenPath{}
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001641var _ WritablePath = ModuleGenPath{}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001642var _ genPathProvider = ModuleGenPath{}
1643var _ objPathProvider = ModuleGenPath{}
1644
1645// PathForModuleGen returns a Path representing the paths... under the module's
1646// `gen' directory.
Liz Kammera830f3a2020-11-10 10:50:34 -08001647func PathForModuleGen(ctx ModuleOutPathContext, paths ...string) ModuleGenPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001648 p, err := validatePath(paths...)
1649 if err != nil {
1650 reportPathError(ctx, err)
1651 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001652 return ModuleGenPath{
Colin Cross702e0f82017-10-18 17:27:54 -07001653 ModuleOutPath: ModuleOutPath{
Liz Kammera830f3a2020-11-10 10:50:34 -08001654 OutputPath: pathForModuleOut(ctx).withRel("gen").withRel(p),
Colin Cross702e0f82017-10-18 17:27:54 -07001655 },
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001656 }
1657}
1658
Liz Kammera830f3a2020-11-10 10:50:34 -08001659func (p ModuleGenPath) genPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleGenPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001660 // TODO: make a different path for local vs remote generated files?
Dan Willemsen21ec4902016-11-02 20:43:13 -07001661 return PathForModuleGen(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001662}
1663
yangbill6d032dd2024-04-18 03:05:49 +00001664func (p ModuleGenPath) genPathWithExtAndTrimExt(ctx ModuleOutPathContext, subdir, ext string, trimExt string) ModuleGenPath {
1665 // If Trim_extension being set, force append Output_extension without replace original extension.
1666 if trimExt != "" {
1667 if ext != "" {
1668 return PathForModuleGen(ctx, subdir, strings.TrimSuffix(p.path, trimExt)+"."+ext)
1669 }
1670 return PathForModuleGen(ctx, subdir, strings.TrimSuffix(p.path, trimExt))
1671 }
1672 return PathForModuleGen(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
1673}
1674
Liz Kammera830f3a2020-11-10 10:50:34 -08001675func (p ModuleGenPath) objPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleObjPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001676 return PathForModuleObj(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
1677}
1678
1679// ModuleObjPath is a Path representing the 'obj' directory in a module's output
1680// directory. Used for compiled objects.
1681type ModuleObjPath struct {
1682 ModuleOutPath
1683}
1684
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001685func (p ModuleObjPath) RelativeToTop() Path {
1686 p.OutputPath = p.outputPathRelativeToTop()
1687 return p
1688}
1689
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001690var _ Path = ModuleObjPath{}
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001691var _ WritablePath = ModuleObjPath{}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001692
1693// PathForModuleObj returns a Path representing the paths... under the module's
1694// 'obj' directory.
Liz Kammera830f3a2020-11-10 10:50:34 -08001695func PathForModuleObj(ctx ModuleOutPathContext, pathComponents ...string) ModuleObjPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001696 p, err := validatePath(pathComponents...)
1697 if err != nil {
1698 reportPathError(ctx, err)
1699 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001700 return ModuleObjPath{PathForModuleOut(ctx, "obj", p)}
1701}
1702
1703// ModuleResPath is a a Path representing the 'res' directory in a module's
1704// output directory.
1705type ModuleResPath struct {
1706 ModuleOutPath
1707}
1708
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001709func (p ModuleResPath) RelativeToTop() Path {
1710 p.OutputPath = p.outputPathRelativeToTop()
1711 return p
1712}
1713
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001714var _ Path = ModuleResPath{}
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001715var _ WritablePath = ModuleResPath{}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001716
1717// PathForModuleRes returns a Path representing the paths... under the module's
1718// 'res' directory.
Liz Kammera830f3a2020-11-10 10:50:34 -08001719func PathForModuleRes(ctx ModuleOutPathContext, pathComponents ...string) ModuleResPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001720 p, err := validatePath(pathComponents...)
1721 if err != nil {
1722 reportPathError(ctx, err)
1723 }
1724
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001725 return ModuleResPath{PathForModuleOut(ctx, "res", p)}
1726}
1727
Colin Cross70dda7e2019-10-01 22:05:35 -07001728// InstallPath is a Path representing a installed file path rooted from the build directory
1729type InstallPath struct {
1730 basePath
Colin Crossff6c33d2019-10-02 16:01:35 -07001731
Lukacs T. Berkib078ade2021-08-31 10:42:08 +02001732 // The soong build directory, i.e. Config.SoongOutDir()
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02001733 soongOutDir string
Paul Duffind65c58b2021-03-24 09:22:07 +00001734
Jiyong Park957bcd92020-10-20 18:23:33 +09001735 // partitionDir is the part of the InstallPath that is automatically determined according to the context.
1736 // For example, it is host/<os>-<arch> for host modules, and target/product/<device>/<partition> for device modules.
1737 partitionDir string
1738
Colin Crossb1692a32021-10-25 15:39:01 -07001739 partition string
1740
Jiyong Park957bcd92020-10-20 18:23:33 +09001741 // makePath indicates whether this path is for Soong (false) or Make (true).
1742 makePath bool
Colin Crossc0e42d52024-02-01 16:42:36 -08001743
1744 fullPath string
Colin Cross70dda7e2019-10-01 22:05:35 -07001745}
1746
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001747// Will panic if called from outside a test environment.
1748func ensureTestOnly() {
Martin Stjernholm32312eb2021-03-27 18:54:49 +00001749 if PrefixInList(os.Args, "-test.") {
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001750 return
1751 }
Martin Stjernholm32312eb2021-03-27 18:54:49 +00001752 panic(fmt.Errorf("Not in test. Command line:\n %s", strings.Join(os.Args, "\n ")))
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001753}
1754
1755func (p InstallPath) RelativeToTop() Path {
1756 ensureTestOnly()
Colin Crossc0e42d52024-02-01 16:42:36 -08001757 if p.makePath {
1758 p.soongOutDir = OutDir
1759 } else {
1760 p.soongOutDir = OutSoongDir
1761 }
1762 p.fullPath = filepath.Join(p.soongOutDir, p.path)
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001763 return p
1764}
1765
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02001766func (p InstallPath) getSoongOutDir() string {
1767 return p.soongOutDir
Paul Duffin9b478b02019-12-10 13:41:51 +00001768}
1769
Hans MÃ¥nssond3f2bd72020-11-27 12:37:28 +01001770func (p InstallPath) ReplaceExtension(ctx PathContext, ext string) OutputPath {
1771 panic("Not implemented")
1772}
1773
Paul Duffin9b478b02019-12-10 13:41:51 +00001774var _ Path = InstallPath{}
1775var _ WritablePath = InstallPath{}
1776
Colin Cross70dda7e2019-10-01 22:05:35 -07001777func (p InstallPath) writablePath() {}
1778
1779func (p InstallPath) String() string {
Colin Crossc0e42d52024-02-01 16:42:36 -08001780 return p.fullPath
Jiyong Park957bcd92020-10-20 18:23:33 +09001781}
1782
1783// PartitionDir returns the path to the partition where the install path is rooted at. It is
1784// out/soong/target/product/<device>/<partition> for device modules, and out/soong/host/<os>-<arch> for host modules.
1785// The ./soong is dropped if the install path is for Make.
1786func (p InstallPath) PartitionDir() string {
1787 if p.makePath {
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02001788 return filepath.Join(p.soongOutDir, "../", p.partitionDir)
Jiyong Park957bcd92020-10-20 18:23:33 +09001789 } else {
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02001790 return filepath.Join(p.soongOutDir, p.partitionDir)
Jiyong Park957bcd92020-10-20 18:23:33 +09001791 }
Colin Cross70dda7e2019-10-01 22:05:35 -07001792}
1793
Jihoon Kangf78a8902022-09-01 22:47:07 +00001794func (p InstallPath) Partition() string {
1795 return p.partition
1796}
1797
Colin Cross70dda7e2019-10-01 22:05:35 -07001798// Join creates a new InstallPath with paths... joined with the current path. The
1799// provided paths... may not use '..' to escape from the current path.
1800func (p InstallPath) Join(ctx PathContext, paths ...string) InstallPath {
1801 path, err := validatePath(paths...)
1802 if err != nil {
1803 reportPathError(ctx, err)
1804 }
1805 return p.withRel(path)
1806}
1807
1808func (p InstallPath) withRel(rel string) InstallPath {
1809 p.basePath = p.basePath.withRel(rel)
Colin Crossc0e42d52024-02-01 16:42:36 -08001810 p.fullPath = filepath.Join(p.fullPath, rel)
Colin Cross70dda7e2019-10-01 22:05:35 -07001811 return p
1812}
1813
Colin Crossc68db4b2021-11-11 18:59:15 -08001814// Deprecated: ToMakePath is a noop, PathForModuleInstall always returns Make paths when building
1815// embedded in Make.
Colin Crossff6c33d2019-10-02 16:01:35 -07001816func (p InstallPath) ToMakePath() InstallPath {
Jiyong Park957bcd92020-10-20 18:23:33 +09001817 p.makePath = true
Colin Crossff6c33d2019-10-02 16:01:35 -07001818 return p
Colin Cross70dda7e2019-10-01 22:05:35 -07001819}
1820
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001821// PathForModuleInstall returns a Path representing the install path for the
1822// module appended with paths...
Colin Cross70dda7e2019-10-01 22:05:35 -07001823func PathForModuleInstall(ctx ModuleInstallPathContext, pathComponents ...string) InstallPath {
Spandan Das5d1b9292021-06-03 19:36:41 +00001824 os, arch := osAndArch(ctx)
Cole Faust11edf552023-10-13 11:32:14 -07001825 partition := modulePartition(ctx, os.Class == Device)
Cole Faust3b703f32023-10-16 13:30:51 -07001826 return pathForInstall(ctx, os, arch, partition, pathComponents...)
Spandan Das5d1b9292021-06-03 19:36:41 +00001827}
1828
Colin Cross1d0eb7a2021-11-03 14:08:20 -07001829// PathForHostDexInstall returns an InstallPath representing the install path for the
1830// module appended with paths...
1831func PathForHostDexInstall(ctx ModuleInstallPathContext, pathComponents ...string) InstallPath {
Cole Faust3b703f32023-10-16 13:30:51 -07001832 return pathForInstall(ctx, ctx.Config().BuildOS, ctx.Config().BuildArch, "", pathComponents...)
Colin Cross1d0eb7a2021-11-03 14:08:20 -07001833}
1834
Spandan Das5d1b9292021-06-03 19:36:41 +00001835// PathForModuleInPartitionInstall is similar to PathForModuleInstall but partition is provided by the caller
1836func PathForModuleInPartitionInstall(ctx ModuleInstallPathContext, partition string, pathComponents ...string) InstallPath {
1837 os, arch := osAndArch(ctx)
Cole Faust3b703f32023-10-16 13:30:51 -07001838 return pathForInstall(ctx, os, arch, partition, pathComponents...)
Spandan Das5d1b9292021-06-03 19:36:41 +00001839}
1840
1841func osAndArch(ctx ModuleInstallPathContext) (OsType, ArchType) {
Colin Cross6e359402020-02-10 15:29:54 -08001842 os := ctx.Os()
Jiyong Park87788b52020-09-01 12:37:45 +09001843 arch := ctx.Arch().ArchType
1844 forceOS, forceArch := ctx.InstallForceOS()
1845 if forceOS != nil {
Colin Cross6e359402020-02-10 15:29:54 -08001846 os = *forceOS
1847 }
Jiyong Park87788b52020-09-01 12:37:45 +09001848 if forceArch != nil {
1849 arch = *forceArch
1850 }
Spandan Das5d1b9292021-06-03 19:36:41 +00001851 return os, arch
1852}
Colin Cross609c49a2020-02-13 13:20:11 -08001853
Colin Crossc0e42d52024-02-01 16:42:36 -08001854func pathForPartitionInstallDir(ctx PathContext, partition, partitionPath string, makePath bool) InstallPath {
1855 fullPath := ctx.Config().SoongOutDir()
1856 if makePath {
1857 // Make path starts with out/ instead of out/soong.
1858 fullPath = filepath.Join(fullPath, "../", partitionPath)
1859 } else {
1860 fullPath = filepath.Join(fullPath, partitionPath)
1861 }
1862
1863 return InstallPath{
1864 basePath: basePath{partitionPath, ""},
1865 soongOutDir: ctx.Config().soongOutDir,
1866 partitionDir: partitionPath,
1867 partition: partition,
1868 makePath: makePath,
1869 fullPath: fullPath,
1870 }
1871}
1872
Cole Faust3b703f32023-10-16 13:30:51 -07001873func pathForInstall(ctx PathContext, os OsType, arch ArchType, partition string,
Colin Cross609c49a2020-02-13 13:20:11 -08001874 pathComponents ...string) InstallPath {
1875
Jiyong Park97859152023-02-14 17:05:48 +09001876 var partitionPaths []string
Colin Cross609c49a2020-02-13 13:20:11 -08001877
Colin Cross6e359402020-02-10 15:29:54 -08001878 if os.Class == Device {
Jiyong Park97859152023-02-14 17:05:48 +09001879 partitionPaths = []string{"target", "product", ctx.Config().DeviceName(), partition}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001880 } else {
Jiyong Park87788b52020-09-01 12:37:45 +09001881 osName := os.String()
Colin Crossa9b2aac2022-06-15 17:25:51 -07001882 if os == Linux {
Jiyong Park87788b52020-09-01 12:37:45 +09001883 // instead of linux_glibc
1884 osName = "linux"
Dan Willemsen866b5632017-09-22 12:28:24 -07001885 }
Colin Crossa9b2aac2022-06-15 17:25:51 -07001886 if os == LinuxMusl && ctx.Config().UseHostMusl() {
1887 // When using musl instead of glibc, use "linux" instead of "linux_musl". When cross
1888 // compiling we will still use "linux_musl".
1889 osName = "linux"
1890 }
1891
Jiyong Park87788b52020-09-01 12:37:45 +09001892 // SOONG_HOST_OUT is set to out/host/$(HOST_OS)-$(HOST_PREBUILT_ARCH)
1893 // and HOST_PREBUILT_ARCH is forcibly set to x86 even on x86_64 hosts. We don't seem
1894 // to have a plan to fix it (see the comment in build/make/core/envsetup.mk).
1895 // Let's keep using x86 for the existing cases until we have a need to support
1896 // other architectures.
1897 archName := arch.String()
1898 if os.Class == Host && (arch == X86_64 || arch == Common) {
1899 archName = "x86"
1900 }
Jiyong Park97859152023-02-14 17:05:48 +09001901 partitionPaths = []string{"host", osName + "-" + archName, partition}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001902 }
Colin Cross70dda7e2019-10-01 22:05:35 -07001903
Jiyong Park97859152023-02-14 17:05:48 +09001904 partitionPath, err := validatePath(partitionPaths...)
Colin Cross70dda7e2019-10-01 22:05:35 -07001905 if err != nil {
1906 reportPathError(ctx, err)
1907 }
Colin Crossff6c33d2019-10-02 16:01:35 -07001908
Colin Crossc0e42d52024-02-01 16:42:36 -08001909 base := pathForPartitionInstallDir(ctx, partition, partitionPath, ctx.Config().KatiEnabled())
Jiyong Park957bcd92020-10-20 18:23:33 +09001910 return base.Join(ctx, pathComponents...)
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001911}
1912
Spandan Dasf280b232024-04-04 21:25:51 +00001913func PathForNdkInstall(ctx PathContext, paths ...string) OutputPath {
1914 return PathForOutput(ctx, append([]string{"ndk"}, paths...)...)
Nicolas Geoffray1228e9c2020-02-27 13:45:35 +00001915}
1916
1917func PathForMainlineSdksInstall(ctx PathContext, paths ...string) InstallPath {
Spandan Dasf280b232024-04-04 21:25:51 +00001918 base := pathForPartitionInstallDir(ctx, "", "mainline-sdks", false)
1919 return base.Join(ctx, paths...)
Nicolas Geoffray1228e9c2020-02-27 13:45:35 +00001920}
1921
Colin Cross70dda7e2019-10-01 22:05:35 -07001922func InstallPathToOnDevicePath(ctx PathContext, path InstallPath) string {
Colin Crossb1692a32021-10-25 15:39:01 -07001923 rel := Rel(ctx, strings.TrimSuffix(path.PartitionDir(), path.partition), path.String())
Colin Cross43f08db2018-11-12 10:13:39 -08001924 return "/" + rel
1925}
1926
Cole Faust11edf552023-10-13 11:32:14 -07001927func modulePartition(ctx ModuleInstallPathContext, device bool) string {
Colin Cross43f08db2018-11-12 10:13:39 -08001928 var partition string
Colin Cross6e359402020-02-10 15:29:54 -08001929 if ctx.InstallInTestcases() {
1930 // "testcases" install directory can be used for host or device modules.
Jaewoong Jung0949f312019-09-11 10:25:18 -07001931 partition = "testcases"
Cole Faust11edf552023-10-13 11:32:14 -07001932 } else if device {
Colin Cross6e359402020-02-10 15:29:54 -08001933 if ctx.InstallInData() {
1934 partition = "data"
1935 } else if ctx.InstallInRamdisk() {
1936 if ctx.DeviceConfig().BoardUsesRecoveryAsBoot() {
1937 partition = "recovery/root/first_stage_ramdisk"
1938 } else {
1939 partition = "ramdisk"
1940 }
1941 if !ctx.InstallInRoot() {
1942 partition += "/system"
1943 }
Yifan Hong60e0cfb2020-10-21 15:17:56 -07001944 } else if ctx.InstallInVendorRamdisk() {
Yifan Hong39143a92020-10-26 12:43:12 -07001945 // The module is only available after switching root into
1946 // /first_stage_ramdisk. To expose the module before switching root
1947 // on a device without a dedicated recovery partition, install the
1948 // recovery variant.
Yifan Hongdd8dacc2020-10-21 15:40:17 -07001949 if ctx.DeviceConfig().BoardMoveRecoveryResourcesToVendorBoot() {
Petri Gyntherac229562021-03-02 23:44:02 -08001950 partition = "vendor_ramdisk/first_stage_ramdisk"
Yifan Hongdd8dacc2020-10-21 15:40:17 -07001951 } else {
Petri Gyntherac229562021-03-02 23:44:02 -08001952 partition = "vendor_ramdisk"
Yifan Hongdd8dacc2020-10-21 15:40:17 -07001953 }
1954 if !ctx.InstallInRoot() {
1955 partition += "/system"
1956 }
Inseob Kim08758f02021-04-08 21:13:22 +09001957 } else if ctx.InstallInDebugRamdisk() {
1958 partition = "debug_ramdisk"
Colin Cross6e359402020-02-10 15:29:54 -08001959 } else if ctx.InstallInRecovery() {
1960 if ctx.InstallInRoot() {
1961 partition = "recovery/root"
1962 } else {
1963 // the layout of recovery partion is the same as that of system partition
1964 partition = "recovery/root/system"
1965 }
Colin Crossea30d852023-11-29 16:00:16 -08001966 } else if ctx.SocSpecific() || ctx.InstallInVendor() {
Colin Cross6e359402020-02-10 15:29:54 -08001967 partition = ctx.DeviceConfig().VendorPath()
Colin Crossea30d852023-11-29 16:00:16 -08001968 } else if ctx.DeviceSpecific() || ctx.InstallInOdm() {
Colin Cross6e359402020-02-10 15:29:54 -08001969 partition = ctx.DeviceConfig().OdmPath()
Colin Crossea30d852023-11-29 16:00:16 -08001970 } else if ctx.ProductSpecific() || ctx.InstallInProduct() {
Colin Cross6e359402020-02-10 15:29:54 -08001971 partition = ctx.DeviceConfig().ProductPath()
1972 } else if ctx.SystemExtSpecific() {
1973 partition = ctx.DeviceConfig().SystemExtPath()
1974 } else if ctx.InstallInRoot() {
1975 partition = "root"
Yifan Hong82db7352020-01-21 16:12:26 -08001976 } else {
Colin Cross6e359402020-02-10 15:29:54 -08001977 partition = "system"
Yifan Hong82db7352020-01-21 16:12:26 -08001978 }
Colin Cross6e359402020-02-10 15:29:54 -08001979 if ctx.InstallInSanitizerDir() {
1980 partition = "data/asan/" + partition
Yifan Hong82db7352020-01-21 16:12:26 -08001981 }
Colin Cross43f08db2018-11-12 10:13:39 -08001982 }
1983 return partition
1984}
1985
Colin Cross609c49a2020-02-13 13:20:11 -08001986type InstallPaths []InstallPath
1987
1988// Paths returns the InstallPaths as a Paths
1989func (p InstallPaths) Paths() Paths {
1990 if p == nil {
1991 return nil
1992 }
1993 ret := make(Paths, len(p))
1994 for i, path := range p {
1995 ret[i] = path
1996 }
1997 return ret
1998}
1999
2000// Strings returns the string forms of the install paths.
2001func (p InstallPaths) Strings() []string {
2002 if p == nil {
2003 return nil
2004 }
2005 ret := make([]string, len(p))
2006 for i, path := range p {
2007 ret[i] = path.String()
2008 }
2009 return ret
2010}
2011
Jingwen Chen24d0c562023-02-07 09:29:36 +00002012// validatePathInternal ensures that a path does not leave its component, and
2013// optionally doesn't contain Ninja variables.
2014func validatePathInternal(allowNinjaVariables bool, pathComponents ...string) (string, error) {
Colin Crossbf9ed3f2023-10-24 14:17:03 -07002015 initialEmpty := 0
2016 finalEmpty := 0
2017 for i, path := range pathComponents {
Jingwen Chen24d0c562023-02-07 09:29:36 +00002018 if !allowNinjaVariables && strings.Contains(path, "$") {
2019 return "", fmt.Errorf("Path contains invalid character($): %s", path)
2020 }
2021
Dan Willemsen80a7c2a2015-12-21 14:57:11 -08002022 path := filepath.Clean(path)
maxwen479f5b02024-03-20 14:41:25 +01002023 if path == ".." || strings.HasPrefix(path, "../") || i != initialEmpty && strings.HasPrefix(path, "/") {
Colin Cross1ccfcc32018-02-22 13:54:26 -08002024 return "", fmt.Errorf("Path is outside directory: %s", path)
Dan Willemsen80a7c2a2015-12-21 14:57:11 -08002025 }
Colin Crossbf9ed3f2023-10-24 14:17:03 -07002026
2027 if i == initialEmpty && pathComponents[i] == "" {
2028 initialEmpty++
2029 }
2030 if i == finalEmpty && pathComponents[len(pathComponents)-1-i] == "" {
2031 finalEmpty++
2032 }
Dan Willemsen80a7c2a2015-12-21 14:57:11 -08002033 }
Colin Crossbf9ed3f2023-10-24 14:17:03 -07002034 // Optimization: filepath.Join("foo", "") returns a newly allocated copy
2035 // of "foo", while filepath.Join("foo") does not. Strip out any empty
2036 // path components.
2037 if initialEmpty == len(pathComponents) {
2038 return "", nil
2039 }
2040 nonEmptyPathComponents := pathComponents[initialEmpty : len(pathComponents)-finalEmpty]
Dan Willemsen34cc69e2015-09-23 15:26:20 -07002041 // TODO: filepath.Join isn't necessarily correct with embedded ninja
2042 // variables. '..' may remove the entire ninja variable, even if it
2043 // will be expanded to multiple nested directories.
Colin Crossbf9ed3f2023-10-24 14:17:03 -07002044 return filepath.Join(nonEmptyPathComponents...), nil
Dan Willemsen34cc69e2015-09-23 15:26:20 -07002045}
2046
Jingwen Chen24d0c562023-02-07 09:29:36 +00002047// validateSafePath validates a path that we trust (may contain ninja
2048// variables). Ensures that each path component does not attempt to leave its
2049// component. Returns a joined version of each path component.
2050func validateSafePath(pathComponents ...string) (string, error) {
2051 return validatePathInternal(true, pathComponents...)
2052}
2053
Dan Willemsen80a7c2a2015-12-21 14:57:11 -08002054// validatePath validates that a path does not include ninja variables, and that
2055// each path component does not attempt to leave its component. Returns a joined
2056// version of each path component.
Colin Cross1ccfcc32018-02-22 13:54:26 -08002057func validatePath(pathComponents ...string) (string, error) {
Jingwen Chen24d0c562023-02-07 09:29:36 +00002058 return validatePathInternal(false, pathComponents...)
Colin Cross6e18ca42015-07-14 18:55:36 -07002059}
Colin Cross5b529592017-05-09 13:34:34 -07002060
Colin Cross0875c522017-11-28 17:34:01 -08002061func PathForPhony(ctx PathContext, phony string) WritablePath {
2062 if strings.ContainsAny(phony, "$/") {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01002063 ReportPathErrorf(ctx, "Phony target contains invalid character ($ or /): %s", phony)
Colin Cross0875c522017-11-28 17:34:01 -08002064 }
Paul Duffin74abc5d2021-03-24 09:24:59 +00002065 return PhonyPath{basePath{phony, ""}}
Colin Cross0875c522017-11-28 17:34:01 -08002066}
2067
Colin Cross74e3fe42017-12-11 15:51:44 -08002068type PhonyPath struct {
2069 basePath
2070}
2071
2072func (p PhonyPath) writablePath() {}
2073
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02002074func (p PhonyPath) getSoongOutDir() string {
Paul Duffind65c58b2021-03-24 09:22:07 +00002075 // A phone path cannot contain any / so cannot be relative to the build directory.
2076 return ""
Paul Duffin9b478b02019-12-10 13:41:51 +00002077}
2078
Paul Duffin85d8f0d2021-03-24 10:18:18 +00002079func (p PhonyPath) RelativeToTop() Path {
2080 ensureTestOnly()
2081 // A phony path cannot contain any / so does not have a build directory so switching to a new
2082 // build directory has no effect so just return this path.
2083 return p
2084}
2085
Hans MÃ¥nssond3f2bd72020-11-27 12:37:28 +01002086func (p PhonyPath) ReplaceExtension(ctx PathContext, ext string) OutputPath {
2087 panic("Not implemented")
2088}
2089
Colin Cross74e3fe42017-12-11 15:51:44 -08002090var _ Path = PhonyPath{}
2091var _ WritablePath = PhonyPath{}
2092
Colin Cross5b529592017-05-09 13:34:34 -07002093type testPath struct {
2094 basePath
2095}
2096
Paul Duffin85d8f0d2021-03-24 10:18:18 +00002097func (p testPath) RelativeToTop() Path {
2098 ensureTestOnly()
2099 return p
2100}
2101
Colin Cross5b529592017-05-09 13:34:34 -07002102func (p testPath) String() string {
2103 return p.path
2104}
2105
Paul Duffin85d8f0d2021-03-24 10:18:18 +00002106var _ Path = testPath{}
2107
Colin Cross40e33732019-02-15 11:08:35 -08002108// PathForTesting returns a Path constructed from joining the elements of paths with '/'. It should only be used from
2109// within tests.
Colin Cross5b529592017-05-09 13:34:34 -07002110func PathForTesting(paths ...string) Path {
Colin Cross1ccfcc32018-02-22 13:54:26 -08002111 p, err := validateSafePath(paths...)
2112 if err != nil {
2113 panic(err)
2114 }
Colin Cross5b529592017-05-09 13:34:34 -07002115 return testPath{basePath{path: p, rel: p}}
2116}
2117
Sam Delmerico2351eac2022-05-24 17:10:02 +00002118func PathForTestingWithRel(path, rel string) Path {
2119 p, err := validateSafePath(path, rel)
2120 if err != nil {
2121 panic(err)
2122 }
2123 r, err := validatePath(rel)
2124 if err != nil {
2125 panic(err)
2126 }
2127 return testPath{basePath{path: p, rel: r}}
2128}
2129
Colin Cross40e33732019-02-15 11:08:35 -08002130// PathsForTesting returns a Path constructed from each element in strs. It should only be used from within tests.
2131func PathsForTesting(strs ...string) Paths {
Colin Cross5b529592017-05-09 13:34:34 -07002132 p := make(Paths, len(strs))
2133 for i, s := range strs {
2134 p[i] = PathForTesting(s)
2135 }
2136
2137 return p
2138}
Colin Cross43f08db2018-11-12 10:13:39 -08002139
Colin Cross40e33732019-02-15 11:08:35 -08002140type testPathContext struct {
2141 config Config
Colin Cross40e33732019-02-15 11:08:35 -08002142}
2143
Colin Cross40e33732019-02-15 11:08:35 -08002144func (x *testPathContext) Config() Config { return x.config }
2145func (x *testPathContext) AddNinjaFileDeps(...string) {}
2146
2147// PathContextForTesting returns a PathContext that can be used in tests, for example to create an OutputPath with
2148// PathForOutput.
Colin Cross98be1bb2019-12-13 20:41:13 -08002149func PathContextForTesting(config Config) PathContext {
Colin Cross40e33732019-02-15 11:08:35 -08002150 return &testPathContext{
2151 config: config,
Colin Cross40e33732019-02-15 11:08:35 -08002152 }
2153}
2154
Ulya Trafimovichccc8c852020-10-14 11:29:07 +01002155type testModuleInstallPathContext struct {
2156 baseModuleContext
2157
2158 inData bool
2159 inTestcases bool
2160 inSanitizerDir bool
2161 inRamdisk bool
2162 inVendorRamdisk bool
Inseob Kim08758f02021-04-08 21:13:22 +09002163 inDebugRamdisk bool
Ulya Trafimovichccc8c852020-10-14 11:29:07 +01002164 inRecovery bool
2165 inRoot bool
Colin Crossea30d852023-11-29 16:00:16 -08002166 inOdm bool
2167 inProduct bool
2168 inVendor bool
Ulya Trafimovichccc8c852020-10-14 11:29:07 +01002169 forceOS *OsType
2170 forceArch *ArchType
2171}
2172
2173func (m testModuleInstallPathContext) Config() Config {
2174 return m.baseModuleContext.config
2175}
2176
2177func (testModuleInstallPathContext) AddNinjaFileDeps(deps ...string) {}
2178
2179func (m testModuleInstallPathContext) InstallInData() bool {
2180 return m.inData
2181}
2182
2183func (m testModuleInstallPathContext) InstallInTestcases() bool {
2184 return m.inTestcases
2185}
2186
2187func (m testModuleInstallPathContext) InstallInSanitizerDir() bool {
2188 return m.inSanitizerDir
2189}
2190
2191func (m testModuleInstallPathContext) InstallInRamdisk() bool {
2192 return m.inRamdisk
2193}
2194
2195func (m testModuleInstallPathContext) InstallInVendorRamdisk() bool {
2196 return m.inVendorRamdisk
2197}
2198
Inseob Kim08758f02021-04-08 21:13:22 +09002199func (m testModuleInstallPathContext) InstallInDebugRamdisk() bool {
2200 return m.inDebugRamdisk
2201}
2202
Ulya Trafimovichccc8c852020-10-14 11:29:07 +01002203func (m testModuleInstallPathContext) InstallInRecovery() bool {
2204 return m.inRecovery
2205}
2206
2207func (m testModuleInstallPathContext) InstallInRoot() bool {
2208 return m.inRoot
2209}
2210
Colin Crossea30d852023-11-29 16:00:16 -08002211func (m testModuleInstallPathContext) InstallInOdm() bool {
2212 return m.inOdm
2213}
2214
2215func (m testModuleInstallPathContext) InstallInProduct() bool {
2216 return m.inProduct
2217}
2218
2219func (m testModuleInstallPathContext) InstallInVendor() bool {
2220 return m.inVendor
2221}
2222
Ulya Trafimovichccc8c852020-10-14 11:29:07 +01002223func (m testModuleInstallPathContext) InstallForceOS() (*OsType, *ArchType) {
2224 return m.forceOS, m.forceArch
2225}
2226
2227// Construct a minimal ModuleInstallPathContext for testing. Note that baseModuleContext is
2228// default-initialized, which leaves blueprint.baseModuleContext set to nil, so methods that are
2229// delegated to it will panic.
2230func ModuleInstallPathContextForTesting(config Config) ModuleInstallPathContext {
2231 ctx := &testModuleInstallPathContext{}
2232 ctx.config = config
2233 ctx.os = Android
2234 return ctx
2235}
2236
Colin Cross43f08db2018-11-12 10:13:39 -08002237// Rel performs the same function as filepath.Rel, but reports errors to a PathContext, and reports an error if
2238// targetPath is not inside basePath.
2239func Rel(ctx PathContext, basePath string, targetPath string) string {
2240 rel, isRel := MaybeRel(ctx, basePath, targetPath)
2241 if !isRel {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01002242 ReportPathErrorf(ctx, "path %q is not under path %q", targetPath, basePath)
Colin Cross43f08db2018-11-12 10:13:39 -08002243 return ""
2244 }
2245 return rel
2246}
2247
2248// MaybeRel performs the same function as filepath.Rel, but reports errors to a PathContext, and returns false if
2249// targetPath is not inside basePath.
2250func MaybeRel(ctx PathContext, basePath string, targetPath string) (string, bool) {
Dan Willemsen633c5022019-04-12 11:11:38 -07002251 rel, isRel, err := maybeRelErr(basePath, targetPath)
2252 if err != nil {
2253 reportPathError(ctx, err)
2254 }
2255 return rel, isRel
2256}
2257
2258func maybeRelErr(basePath string, targetPath string) (string, bool, error) {
Colin Cross43f08db2018-11-12 10:13:39 -08002259 // filepath.Rel returns an error if one path is absolute and the other is not, handle that case first.
2260 if filepath.IsAbs(basePath) != filepath.IsAbs(targetPath) {
Dan Willemsen633c5022019-04-12 11:11:38 -07002261 return "", false, nil
Colin Cross43f08db2018-11-12 10:13:39 -08002262 }
2263 rel, err := filepath.Rel(basePath, targetPath)
2264 if err != nil {
Dan Willemsen633c5022019-04-12 11:11:38 -07002265 return "", false, err
Colin Cross43f08db2018-11-12 10:13:39 -08002266 } else if rel == ".." || strings.HasPrefix(rel, "../") || strings.HasPrefix(rel, "/") {
Dan Willemsen633c5022019-04-12 11:11:38 -07002267 return "", false, nil
Colin Cross43f08db2018-11-12 10:13:39 -08002268 }
Dan Willemsen633c5022019-04-12 11:11:38 -07002269 return rel, true, nil
Colin Cross43f08db2018-11-12 10:13:39 -08002270}
Colin Cross988414c2020-01-11 01:11:46 +00002271
2272// Writes a file to the output directory. Attempting to write directly to the output directory
2273// will fail due to the sandbox of the soong_build process.
Chris Parsons1a12d032023-02-06 22:37:41 -05002274// Only writes the file if the file doesn't exist or if it has different contents, to prevent
2275// updating the timestamp if no changes would be made. (This is better for incremental
2276// performance.)
Colin Cross988414c2020-01-11 01:11:46 +00002277func WriteFileToOutputDir(path WritablePath, data []byte, perm os.FileMode) error {
Colin Crossd6421132021-11-09 12:32:34 -08002278 absPath := absolutePath(path.String())
2279 err := os.MkdirAll(filepath.Dir(absPath), 0777)
2280 if err != nil {
2281 return err
2282 }
Chris Parsons1a12d032023-02-06 22:37:41 -05002283 return pathtools.WriteFileIfChanged(absPath, data, perm)
Colin Cross988414c2020-01-11 01:11:46 +00002284}
2285
Liz Kammer2dd9ca42020-11-25 16:06:39 -08002286func RemoveAllOutputDir(path WritablePath) error {
2287 return os.RemoveAll(absolutePath(path.String()))
2288}
2289
2290func CreateOutputDirIfNonexistent(path WritablePath, perm os.FileMode) error {
2291 dir := absolutePath(path.String())
Liz Kammer09f947d2021-05-12 14:51:49 -04002292 return createDirIfNonexistent(dir, perm)
2293}
2294
2295func createDirIfNonexistent(dir string, perm os.FileMode) error {
Liz Kammer2dd9ca42020-11-25 16:06:39 -08002296 if _, err := os.Stat(dir); os.IsNotExist(err) {
2297 return os.MkdirAll(dir, os.ModePerm)
2298 } else {
2299 return err
2300 }
2301}
2302
Jingwen Chen78257e52021-05-21 02:34:24 +00002303// absolutePath is deliberately private so that Soong's Go plugins can't use it to find and
2304// read arbitrary files without going through the methods in the current package that track
2305// dependencies.
Colin Cross988414c2020-01-11 01:11:46 +00002306func absolutePath(path string) string {
2307 if filepath.IsAbs(path) {
2308 return path
2309 }
2310 return filepath.Join(absSrcDir, path)
2311}
Chris Parsons216e10a2020-07-09 17:12:52 -04002312
2313// A DataPath represents the path of a file to be used as data, for example
2314// a test library to be installed alongside a test.
2315// The data file should be installed (copied from `<SrcPath>`) to
2316// `<install_root>/<RelativeInstallPath>/<filename>`, or
2317// `<install_root>/<filename>` if RelativeInstallPath is empty.
2318type DataPath struct {
2319 // The path of the data file that should be copied into the data directory
2320 SrcPath Path
2321 // The install path of the data file, relative to the install root.
2322 RelativeInstallPath string
Colin Cross5c1d5fb2023-11-15 12:39:40 -08002323 // If WithoutRel is true, use SrcPath.Base() instead of SrcPath.Rel() as the filename.
2324 WithoutRel bool
Chris Parsons216e10a2020-07-09 17:12:52 -04002325}
Colin Crossdcf71b22021-02-01 13:59:03 -08002326
Colin Crossd442a0e2023-11-16 11:19:26 -08002327func (d *DataPath) ToRelativeInstallPath() string {
2328 relPath := d.SrcPath.Rel()
Colin Cross5c1d5fb2023-11-15 12:39:40 -08002329 if d.WithoutRel {
2330 relPath = d.SrcPath.Base()
2331 }
Colin Crossd442a0e2023-11-16 11:19:26 -08002332 if d.RelativeInstallPath != "" {
2333 relPath = filepath.Join(d.RelativeInstallPath, relPath)
2334 }
2335 return relPath
2336}
2337
Colin Crossdcf71b22021-02-01 13:59:03 -08002338// PathsIfNonNil returns a Paths containing only the non-nil input arguments.
2339func PathsIfNonNil(paths ...Path) Paths {
2340 if len(paths) == 0 {
2341 // Fast path for empty argument list
2342 return nil
2343 } else if len(paths) == 1 {
2344 // Fast path for a single argument
2345 if paths[0] != nil {
2346 return paths
2347 } else {
2348 return nil
2349 }
2350 }
2351 ret := make(Paths, 0, len(paths))
2352 for _, path := range paths {
2353 if path != nil {
2354 ret = append(ret, path)
2355 }
2356 }
2357 if len(ret) == 0 {
2358 return nil
2359 }
2360 return ret
2361}
Chris Wailesb2703ad2021-07-30 13:25:42 -07002362
2363var thirdPartyDirPrefixExceptions = []*regexp.Regexp{
2364 regexp.MustCompile("^vendor/[^/]*google[^/]*/"),
2365 regexp.MustCompile("^hardware/google/"),
2366 regexp.MustCompile("^hardware/interfaces/"),
2367 regexp.MustCompile("^hardware/libhardware[^/]*/"),
2368 regexp.MustCompile("^hardware/ril/"),
2369}
2370
2371func IsThirdPartyPath(path string) bool {
2372 thirdPartyDirPrefixes := []string{"external/", "vendor/", "hardware/"}
2373
2374 if HasAnyPrefix(path, thirdPartyDirPrefixes) {
2375 for _, prefix := range thirdPartyDirPrefixExceptions {
2376 if prefix.MatchString(path) {
2377 return false
2378 }
2379 }
2380 return true
2381 }
2382 return false
2383}