blob: a254717d0f1dcb8f2d4a685ef63214381dc02dbf [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"
Yu Liu3cadf7d2024-10-24 18:47:06 +000027 "github.com/google/blueprint/gobtools"
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
Cole Faust55b56fe2024-08-23 12:06:11 -070092 OtherModuleProviderContext
Colin Cross648daea2024-09-12 14:35:29 -070093 VisitDirectDeps(visit func(Module))
Yu Liud3228ac2024-11-08 23:11:47 +000094 VisitDirectDepsProxy(visit func(ModuleProxy))
95 VisitDirectDepsProxyWithTag(tag blueprint.DependencyTag, visit func(ModuleProxy))
Paul Duffin40131a32021-07-09 17:10:35 +010096 OtherModuleDependencyTag(m blueprint.Module) blueprint.DependencyTag
Cole Faust4e2bf9f2024-09-11 13:26:20 -070097 HasMutatorFinished(mutatorName string) bool
Liz Kammera830f3a2020-11-10 10:50:34 -080098}
99
100// ModuleMissingDepsPathContext is a subset of *ModuleContext methods required by
101// the Path methods that rely on module dependencies having been resolved and ability to report
102// missing dependency errors.
103type ModuleMissingDepsPathContext interface {
104 ModuleWithDepsPathContext
105 AddMissingDependencies(missingDeps []string)
106}
107
Dan Willemsen00269f22017-07-06 16:59:48 -0700108type ModuleInstallPathContext interface {
Colin Cross0ea8ba82019-06-06 14:33:29 -0700109 BaseModuleContext
Dan Willemsen00269f22017-07-06 16:59:48 -0700110
111 InstallInData() bool
Jaewoong Jung0949f312019-09-11 10:25:18 -0700112 InstallInTestcases() bool
Dan Willemsen00269f22017-07-06 16:59:48 -0700113 InstallInSanitizerDir() bool
Yifan Hong1b3348d2020-01-21 15:53:22 -0800114 InstallInRamdisk() bool
Yifan Hong60e0cfb2020-10-21 15:17:56 -0700115 InstallInVendorRamdisk() bool
Inseob Kim08758f02021-04-08 21:13:22 +0900116 InstallInDebugRamdisk() bool
Jiyong Parkf9332f12018-02-01 00:54:12 +0900117 InstallInRecovery() bool
Colin Cross90ba5f42019-10-02 11:10:58 -0700118 InstallInRoot() bool
Colin Crossea30d852023-11-29 16:00:16 -0800119 InstallInOdm() bool
120 InstallInProduct() bool
121 InstallInVendor() bool
Spandan Das27ff7672024-11-06 19:23:57 +0000122 InstallInSystemDlkm() bool
123 InstallInVendorDlkm() bool
124 InstallInOdmDlkm() bool
Jiyong Park87788b52020-09-01 12:37:45 +0900125 InstallForceOS() (*OsType, *ArchType)
Dan Willemsen00269f22017-07-06 16:59:48 -0700126}
127
128var _ ModuleInstallPathContext = ModuleContext(nil)
129
Cole Faust11edf552023-10-13 11:32:14 -0700130type baseModuleContextToModuleInstallPathContext struct {
131 BaseModuleContext
132}
133
134func (ctx *baseModuleContextToModuleInstallPathContext) InstallInData() bool {
135 return ctx.Module().InstallInData()
136}
137
138func (ctx *baseModuleContextToModuleInstallPathContext) InstallInTestcases() bool {
139 return ctx.Module().InstallInTestcases()
140}
141
142func (ctx *baseModuleContextToModuleInstallPathContext) InstallInSanitizerDir() bool {
143 return ctx.Module().InstallInSanitizerDir()
144}
145
146func (ctx *baseModuleContextToModuleInstallPathContext) InstallInRamdisk() bool {
147 return ctx.Module().InstallInRamdisk()
148}
149
150func (ctx *baseModuleContextToModuleInstallPathContext) InstallInVendorRamdisk() bool {
151 return ctx.Module().InstallInVendorRamdisk()
152}
153
154func (ctx *baseModuleContextToModuleInstallPathContext) InstallInDebugRamdisk() bool {
155 return ctx.Module().InstallInDebugRamdisk()
156}
157
158func (ctx *baseModuleContextToModuleInstallPathContext) InstallInRecovery() bool {
159 return ctx.Module().InstallInRecovery()
160}
161
162func (ctx *baseModuleContextToModuleInstallPathContext) InstallInRoot() bool {
163 return ctx.Module().InstallInRoot()
164}
165
Colin Crossea30d852023-11-29 16:00:16 -0800166func (ctx *baseModuleContextToModuleInstallPathContext) InstallInOdm() bool {
167 return ctx.Module().InstallInOdm()
168}
169
170func (ctx *baseModuleContextToModuleInstallPathContext) InstallInProduct() bool {
171 return ctx.Module().InstallInProduct()
172}
173
174func (ctx *baseModuleContextToModuleInstallPathContext) InstallInVendor() bool {
175 return ctx.Module().InstallInVendor()
176}
177
Spandan Das27ff7672024-11-06 19:23:57 +0000178func (ctx *baseModuleContextToModuleInstallPathContext) InstallInSystemDlkm() bool {
179 return ctx.Module().InstallInSystemDlkm()
180}
181
182func (ctx *baseModuleContextToModuleInstallPathContext) InstallInVendorDlkm() bool {
183 return ctx.Module().InstallInVendorDlkm()
184}
185
186func (ctx *baseModuleContextToModuleInstallPathContext) InstallInOdmDlkm() bool {
187 return ctx.Module().InstallInOdmDlkm()
188}
189
Cole Faust11edf552023-10-13 11:32:14 -0700190func (ctx *baseModuleContextToModuleInstallPathContext) InstallForceOS() (*OsType, *ArchType) {
191 return ctx.Module().InstallForceOS()
192}
193
194var _ ModuleInstallPathContext = (*baseModuleContextToModuleInstallPathContext)(nil)
195
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700196// errorfContext is the interface containing the Errorf method matching the
197// Errorf method in blueprint.SingletonContext.
198type errorfContext interface {
199 Errorf(format string, args ...interface{})
Colin Cross3f40fa42015-01-30 17:27:36 -0800200}
201
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700202var _ errorfContext = blueprint.SingletonContext(nil)
203
Spandan Das59a4a2b2024-01-09 21:35:56 +0000204// ModuleErrorfContext is the interface containing the ModuleErrorf method matching
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700205// the ModuleErrorf method in blueprint.ModuleContext.
Spandan Das59a4a2b2024-01-09 21:35:56 +0000206type ModuleErrorfContext interface {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700207 ModuleErrorf(format string, args ...interface{})
Colin Cross3f40fa42015-01-30 17:27:36 -0800208}
209
Spandan Das59a4a2b2024-01-09 21:35:56 +0000210var _ ModuleErrorfContext = blueprint.ModuleContext(nil)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700211
Colin Cross92ac46d2025-02-26 19:25:23 -0800212type AddMissingDependenciesContext interface {
213 AddMissingDependencies([]string)
214}
215
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700216// reportPathError will register an error with the attached context. It
217// attempts ctx.ModuleErrorf for a better error message first, then falls
218// back to ctx.Errorf.
Colin Cross1ccfcc32018-02-22 13:54:26 -0800219func reportPathError(ctx PathContext, err error) {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +0100220 ReportPathErrorf(ctx, "%s", err.Error())
Colin Cross1ccfcc32018-02-22 13:54:26 -0800221}
222
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +0100223// ReportPathErrorf will register an error with the attached context. It
Colin Cross1ccfcc32018-02-22 13:54:26 -0800224// attempts ctx.ModuleErrorf for a better error message first, then falls
225// back to ctx.Errorf.
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +0100226func ReportPathErrorf(ctx PathContext, format string, args ...interface{}) {
Colin Cross92ac46d2025-02-26 19:25:23 -0800227 if mctx, ok := ctx.(AddMissingDependenciesContext); ok && ctx.Config().AllowMissingDependencies() {
228 mctx.AddMissingDependencies([]string{fmt.Sprintf(format, args...)})
229 } else if mctx, ok := ctx.(ModuleErrorfContext); ok {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700230 mctx.ModuleErrorf(format, args...)
231 } else if ectx, ok := ctx.(errorfContext); ok {
232 ectx.Errorf(format, args...)
233 } else {
234 panic(fmt.Sprintf(format, args...))
Colin Crossf2298272015-05-12 11:36:53 -0700235 }
236}
237
Yu Liu2a815b62025-02-21 20:46:25 +0000238// TODO(b/397766191): Change the signature to take ModuleProxy
239// Please only access the module's internal data through providers.
Colin Cross5e708052019-08-06 13:59:50 -0700240func pathContextName(ctx PathContext, module blueprint.Module) string {
241 if x, ok := ctx.(interface{ ModuleName(blueprint.Module) string }); ok {
242 return x.ModuleName(module)
243 } else if x, ok := ctx.(interface{ OtherModuleName(blueprint.Module) string }); ok {
244 return x.OtherModuleName(module)
245 }
246 return "unknown"
247}
248
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700249type Path interface {
250 // Returns the path in string form
251 String() string
252
Colin Cross4f6fc9c2016-10-26 10:05:25 -0700253 // Ext returns the extension of the last element of the path
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700254 Ext() string
Colin Cross4f6fc9c2016-10-26 10:05:25 -0700255
256 // Base returns the last element of the path
257 Base() string
Colin Crossfaeb7aa2017-02-01 14:12:44 -0800258
259 // Rel returns the portion of the path relative to the directory it was created from. For
260 // example, Rel on a PathsForModuleSrc would return the path relative to the module source
Colin Cross0db55682017-12-05 15:36:55 -0800261 // directory, and OutputPath.Join("foo").Rel() would return "foo".
Colin Crossfaeb7aa2017-02-01 14:12:44 -0800262 Rel() string
Paul Duffin85d8f0d2021-03-24 10:18:18 +0000263
Colin Cross7707b242024-07-26 12:02:36 -0700264 // WithoutRel returns a new Path with no relative path, i.e. Rel() will return the same value as Base().
265 WithoutRel() Path
266
Paul Duffin85d8f0d2021-03-24 10:18:18 +0000267 // RelativeToTop returns a new path relative to the top, it is provided solely for use in tests.
268 //
269 // It is guaranteed to always return the same type as it is called on, e.g. if called on an
270 // InstallPath then the returned value can be converted to an InstallPath.
271 //
272 // A standard build has the following structure:
273 // ../top/
274 // out/ - make install files go here.
Colin Cross3b1c6842024-07-26 11:52:57 -0700275 // out/soong - this is the outDir passed to NewTestConfig()
Paul Duffin85d8f0d2021-03-24 10:18:18 +0000276 // ... - the source files
277 //
278 // This function converts a path so that it appears relative to the ../top/ directory, i.e.
Colin Cross3b1c6842024-07-26 11:52:57 -0700279 // * Make install paths, which have the pattern "outDir/../<path>" are converted into the top
Paul Duffin85d8f0d2021-03-24 10:18:18 +0000280 // relative path "out/<path>"
Colin Cross3b1c6842024-07-26 11:52:57 -0700281 // * Soong install paths and other writable paths, which have the pattern "outDir/soong/<path>" are
Paul Duffin85d8f0d2021-03-24 10:18:18 +0000282 // converted into the top relative path "out/soong/<path>".
283 // * Source paths are already relative to the top.
284 // * Phony paths are not relative to anything.
285 // * toolDepPath have an absolute but known value in so don't need making relative to anything in
286 // order to test.
287 RelativeToTop() Path
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700288}
289
Paul Duffin85d8f0d2021-03-24 10:18:18 +0000290const (
Colin Cross3b1c6842024-07-26 11:52:57 -0700291 testOutDir = "out"
292 testOutSoongSubDir = "/soong"
293 TestOutSoongDir = testOutDir + testOutSoongSubDir
Paul Duffin85d8f0d2021-03-24 10:18:18 +0000294)
295
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700296// WritablePath is a type of path that can be used as an output for build rules.
297type WritablePath interface {
298 Path
299
Paul Duffin9b478b02019-12-10 13:41:51 +0000300 // return the path to the build directory.
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +0200301 getSoongOutDir() string
Paul Duffin9b478b02019-12-10 13:41:51 +0000302
Jeff Gaston734e3802017-04-10 15:47:24 -0700303 // the writablePath method doesn't directly do anything,
304 // but it allows a struct to distinguish between whether or not it implements the WritablePath interface
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700305 writablePath()
Hans MÃ¥nssond3f2bd72020-11-27 12:37:28 +0100306
307 ReplaceExtension(ctx PathContext, ext string) OutputPath
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700308}
309
310type genPathProvider interface {
Liz Kammera830f3a2020-11-10 10:50:34 -0800311 genPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleGenPath
yangbill6d032dd2024-04-18 03:05:49 +0000312 genPathWithExtAndTrimExt(ctx ModuleOutPathContext, subdir, ext string, trimExt string) ModuleGenPath
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700313}
314type objPathProvider interface {
Liz Kammera830f3a2020-11-10 10:50:34 -0800315 objPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleObjPath
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700316}
317type resPathProvider interface {
Liz Kammera830f3a2020-11-10 10:50:34 -0800318 resPathWithName(ctx ModuleOutPathContext, name string) ModuleResPath
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700319}
320
321// GenPathWithExt derives a new file path in ctx's generated sources directory
322// from the current path, but with the new extension.
Liz Kammera830f3a2020-11-10 10:50:34 -0800323func GenPathWithExt(ctx ModuleOutPathContext, subdir string, p Path, ext string) ModuleGenPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700324 if path, ok := p.(genPathProvider); ok {
Dan Willemsen21ec4902016-11-02 20:43:13 -0700325 return path.genPathWithExt(ctx, subdir, ext)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700326 }
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +0100327 ReportPathErrorf(ctx, "Tried to create generated file from unsupported path: %s(%s)", reflect.TypeOf(p).Name(), p)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700328 return PathForModuleGen(ctx)
329}
330
yangbill6d032dd2024-04-18 03:05:49 +0000331// GenPathWithExtAndTrimExt derives a new file path in ctx's generated sources directory
332// from the current path, but with the new extension and trim the suffix.
333func GenPathWithExtAndTrimExt(ctx ModuleOutPathContext, subdir string, p Path, ext string, trimExt string) ModuleGenPath {
334 if path, ok := p.(genPathProvider); ok {
335 return path.genPathWithExtAndTrimExt(ctx, subdir, ext, trimExt)
336 }
337 ReportPathErrorf(ctx, "Tried to create generated file from unsupported path: %s(%s)", reflect.TypeOf(p).Name(), p)
338 return PathForModuleGen(ctx)
339}
340
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700341// ObjPathWithExt derives a new file path in ctx's object directory from the
342// current path, but with the new extension.
Liz Kammera830f3a2020-11-10 10:50:34 -0800343func ObjPathWithExt(ctx ModuleOutPathContext, subdir string, p Path, ext string) ModuleObjPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700344 if path, ok := p.(objPathProvider); ok {
345 return path.objPathWithExt(ctx, subdir, ext)
346 }
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +0100347 ReportPathErrorf(ctx, "Tried to create object file from unsupported path: %s (%s)", reflect.TypeOf(p).Name(), p)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700348 return PathForModuleObj(ctx)
349}
350
351// ResPathWithName derives a new path in ctx's output resource directory, using
352// the current path to create the directory name, and the `name` argument for
353// the filename.
Liz Kammera830f3a2020-11-10 10:50:34 -0800354func ResPathWithName(ctx ModuleOutPathContext, p Path, name string) ModuleResPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700355 if path, ok := p.(resPathProvider); ok {
356 return path.resPathWithName(ctx, name)
357 }
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +0100358 ReportPathErrorf(ctx, "Tried to create res file from unsupported path: %s (%s)", reflect.TypeOf(p).Name(), p)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700359 return PathForModuleRes(ctx)
360}
361
362// OptionalPath is a container that may or may not contain a valid Path.
363type OptionalPath struct {
Martin Stjernholmc32dd1c2021-09-15 02:39:00 +0100364 path Path // nil if invalid.
365 invalidReason string // Not applicable if path != nil. "" if the reason is unknown.
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700366}
367
Yu Liu467d7c52024-09-18 21:54:44 +0000368type optionalPathGob struct {
369 Path Path
370 InvalidReason string
371}
372
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700373// OptionalPathForPath returns an OptionalPath containing the path.
374func OptionalPathForPath(path Path) OptionalPath {
Martin Stjernholm2fee27f2021-09-16 14:11:12 +0100375 return OptionalPath{path: path}
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700376}
377
Martin Stjernholmc32dd1c2021-09-15 02:39:00 +0100378// InvalidOptionalPath returns an OptionalPath that is invalid with the given reason.
379func InvalidOptionalPath(reason string) OptionalPath {
380
381 return OptionalPath{invalidReason: reason}
382}
383
Yu Liu467d7c52024-09-18 21:54:44 +0000384func (p *OptionalPath) ToGob() *optionalPathGob {
385 return &optionalPathGob{
386 Path: p.path,
387 InvalidReason: p.invalidReason,
388 }
389}
390
391func (p *OptionalPath) FromGob(data *optionalPathGob) {
392 p.path = data.Path
393 p.invalidReason = data.InvalidReason
394}
395
396func (p OptionalPath) GobEncode() ([]byte, error) {
Yu Liu3cadf7d2024-10-24 18:47:06 +0000397 return gobtools.CustomGobEncode[optionalPathGob](&p)
Yu Liu467d7c52024-09-18 21:54:44 +0000398}
399
400func (p *OptionalPath) GobDecode(data []byte) error {
Yu Liu3cadf7d2024-10-24 18:47:06 +0000401 return gobtools.CustomGobDecode[optionalPathGob](data, p)
Yu Liu467d7c52024-09-18 21:54:44 +0000402}
403
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700404// Valid returns whether there is a valid path
405func (p OptionalPath) Valid() bool {
Martin Stjernholm2fee27f2021-09-16 14:11:12 +0100406 return p.path != nil
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700407}
408
409// Path returns the Path embedded in this OptionalPath. You must be sure that
410// there is a valid path, since this method will panic if there is not.
411func (p OptionalPath) Path() Path {
Martin Stjernholm2fee27f2021-09-16 14:11:12 +0100412 if p.path == nil {
Martin Stjernholmc32dd1c2021-09-15 02:39:00 +0100413 msg := "Requesting an invalid path"
414 if p.invalidReason != "" {
415 msg += ": " + p.invalidReason
416 }
417 panic(msg)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700418 }
419 return p.path
420}
421
Martin Stjernholmc32dd1c2021-09-15 02:39:00 +0100422// InvalidReason returns the reason that the optional path is invalid, or "" if it is valid.
423func (p OptionalPath) InvalidReason() string {
424 if p.path != nil {
425 return ""
426 }
427 if p.invalidReason == "" {
428 return "unknown"
429 }
430 return p.invalidReason
431}
432
Paul Duffinef081852021-05-13 11:11:15 +0100433// AsPaths converts the OptionalPath into Paths.
434//
435// It returns nil if this is not valid, or a single length slice containing the Path embedded in
436// this OptionalPath.
437func (p OptionalPath) AsPaths() Paths {
Martin Stjernholm2fee27f2021-09-16 14:11:12 +0100438 if p.path == nil {
Paul Duffinef081852021-05-13 11:11:15 +0100439 return nil
440 }
441 return Paths{p.path}
442}
443
Paul Duffinafdd4062021-03-30 19:44:07 +0100444// RelativeToTop returns an OptionalPath with the path that was embedded having been replaced by the
445// result of calling Path.RelativeToTop on it.
446func (p OptionalPath) RelativeToTop() OptionalPath {
Martin Stjernholm2fee27f2021-09-16 14:11:12 +0100447 if p.path == nil {
Paul Duffina5b81352021-03-28 23:57:19 +0100448 return p
449 }
450 p.path = p.path.RelativeToTop()
451 return p
452}
453
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700454// String returns the string version of the Path, or "" if it isn't valid.
455func (p OptionalPath) String() string {
Martin Stjernholm2fee27f2021-09-16 14:11:12 +0100456 if p.path != nil {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700457 return p.path.String()
458 } else {
459 return ""
Colin Crossf2298272015-05-12 11:36:53 -0700460 }
461}
Colin Cross6e18ca42015-07-14 18:55:36 -0700462
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700463// Paths is a slice of Path objects, with helpers to operate on the collection.
464type Paths []Path
465
Paul Duffin85d8f0d2021-03-24 10:18:18 +0000466// RelativeToTop creates a new Paths containing the result of calling Path.RelativeToTop on each
467// item in this slice.
468func (p Paths) RelativeToTop() Paths {
469 ensureTestOnly()
470 if p == nil {
471 return p
472 }
473 ret := make(Paths, len(p))
474 for i, path := range p {
475 ret[i] = path.RelativeToTop()
476 }
477 return ret
478}
479
Jingwen Chen40fd90a2020-06-15 05:24:19 +0000480func (paths Paths) containsPath(path Path) bool {
481 for _, p := range paths {
482 if p == path {
483 return true
484 }
485 }
486 return false
487}
488
Liz Kammer7aa52882021-02-11 09:16:14 -0500489// PathsForSource returns Paths rooted from SrcDir, *not* rooted from the module's local source
490// directory
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700491func PathsForSource(ctx PathContext, paths []string) Paths {
492 ret := make(Paths, len(paths))
493 for i, path := range paths {
494 ret[i] = PathForSource(ctx, path)
495 }
496 return ret
497}
498
Liz Kammer7aa52882021-02-11 09:16:14 -0500499// ExistentPathsForSources returns a list of Paths rooted from SrcDir, *not* rooted from the
500// module's local source directory, that are found in the tree. If any are not found, they are
501// 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 -0700502func ExistentPathsForSources(ctx PathGlobContext, paths []string) Paths {
Dan Willemsen7b310ee2015-12-18 15:11:17 -0800503 ret := make(Paths, 0, len(paths))
504 for _, path := range paths {
Colin Cross32f38982018-02-22 11:47:25 -0800505 p := ExistentPathForSource(ctx, path)
Dan Willemsen7b310ee2015-12-18 15:11:17 -0800506 if p.Valid() {
507 ret = append(ret, p.Path())
508 }
509 }
510 return ret
511}
512
Liz Kammer620dea62021-04-14 17:36:10 -0400513// PathsForModuleSrc returns a Paths{} containing the resolved references in paths:
Colin Crossd079e0b2022-08-16 10:27:33 -0700514// - filepath, relative to local module directory, resolves as a filepath relative to the local
515// source directory
516// - glob, relative to the local module directory, resolves as filepath(s), relative to the local
517// source directory.
518// - other modules using the ":name{.tag}" syntax. These modules must implement SourceFileProducer
mrziwangd38e63d2024-07-15 13:43:37 -0700519// or set the OutputFilesProvider. These resolve as a filepath to an output filepath or generated
520// source filepath.
Colin Crossd079e0b2022-08-16 10:27:33 -0700521//
Liz Kammer620dea62021-04-14 17:36:10 -0400522// Properties passed as the paths argument must have been annotated with struct tag
Colin Cross41955e82019-05-29 14:40:35 -0700523// `android:"path"` so that dependencies on SourceFileProducer modules will have already been handled by the
Spandan Das950091c2023-07-19 22:26:37 +0000524// pathdeps mutator.
Liz Kammer620dea62021-04-14 17:36:10 -0400525// If a requested module is not found as a dependency:
Colin Crossd079e0b2022-08-16 10:27:33 -0700526// - if ctx.Config().AllowMissingDependencies() is true, this module to be marked as having
Liz Kammer620dea62021-04-14 17:36:10 -0400527// missing dependencies
Colin Crossd079e0b2022-08-16 10:27:33 -0700528// - otherwise, a ModuleError is thrown.
Liz Kammera830f3a2020-11-10 10:50:34 -0800529func PathsForModuleSrc(ctx ModuleMissingDepsPathContext, paths []string) Paths {
Colin Cross8a497952019-03-05 22:25:09 -0800530 return PathsForModuleSrcExcludes(ctx, paths, nil)
531}
532
Liz Kammer619be462022-01-28 15:13:39 -0500533type SourceInput struct {
534 Context ModuleMissingDepsPathContext
535 Paths []string
536 ExcludePaths []string
537 IncludeDirs bool
538}
539
Liz Kammer620dea62021-04-14 17:36:10 -0400540// PathsForModuleSrcExcludes returns a Paths{} containing the resolved references in paths, minus
541// those listed in excludes. Elements of paths and excludes are resolved as:
Colin Crossd079e0b2022-08-16 10:27:33 -0700542// - filepath, relative to local module directory, resolves as a filepath relative to the local
543// source directory
544// - glob, relative to the local module directory, resolves as filepath(s), relative to the local
545// source directory. Not valid in excludes.
546// - other modules using the ":name{.tag}" syntax. These modules must implement SourceFileProducer
mrziwangd38e63d2024-07-15 13:43:37 -0700547// or set the OutputFilesProvider. These resolve as a filepath to an output filepath or generated
548// source filepath.
Colin Crossd079e0b2022-08-16 10:27:33 -0700549//
Liz Kammer620dea62021-04-14 17:36:10 -0400550// excluding the items (similarly resolved
551// Properties passed as the paths argument must have been annotated with struct tag
552// `android:"path"` so that dependencies on SourceFileProducer modules will have already been handled by the
Spandan Das950091c2023-07-19 22:26:37 +0000553// pathdeps mutator.
Liz Kammer620dea62021-04-14 17:36:10 -0400554// If a requested module is not found as a dependency:
Colin Crossd079e0b2022-08-16 10:27:33 -0700555// - if ctx.Config().AllowMissingDependencies() is true, this module to be marked as having
Liz Kammer620dea62021-04-14 17:36:10 -0400556// missing dependencies
Colin Crossd079e0b2022-08-16 10:27:33 -0700557// - otherwise, a ModuleError is thrown.
Liz Kammera830f3a2020-11-10 10:50:34 -0800558func PathsForModuleSrcExcludes(ctx ModuleMissingDepsPathContext, paths, excludes []string) Paths {
Liz Kammer619be462022-01-28 15:13:39 -0500559 return PathsRelativeToModuleSourceDir(SourceInput{
560 Context: ctx,
561 Paths: paths,
562 ExcludePaths: excludes,
563 IncludeDirs: true,
564 })
565}
566
567func PathsRelativeToModuleSourceDir(input SourceInput) Paths {
568 ret, missingDeps := PathsAndMissingDepsRelativeToModuleSourceDir(input)
569 if input.Context.Config().AllowMissingDependencies() {
570 input.Context.AddMissingDependencies(missingDeps)
Colin Crossba71a3f2019-03-18 12:12:48 -0700571 } else {
572 for _, m := range missingDeps {
Liz Kammer619be462022-01-28 15:13:39 -0500573 input.Context.ModuleErrorf(`missing dependency on %q, is the property annotated with android:"path"?`, m)
Colin Crossba71a3f2019-03-18 12:12:48 -0700574 }
575 }
576 return ret
577}
578
Inseob Kim93036a52024-10-25 17:02:21 +0900579type directoryPath struct {
580 basePath
581}
582
583func (d *directoryPath) String() string {
584 return d.basePath.String()
585}
586
587func (d *directoryPath) base() basePath {
588 return d.basePath
589}
590
591// DirectoryPath represents a source path for directories. Incompatible with Path by design.
592type DirectoryPath interface {
593 String() string
594 base() basePath
595}
596
597var _ DirectoryPath = (*directoryPath)(nil)
598
599type DirectoryPaths []DirectoryPath
600
Inseob Kim76e19852024-10-10 17:57:22 +0900601// DirectoryPathsForModuleSrcExcludes returns a Paths{} containing the resolved references in
602// directory paths. Elements of paths are resolved as:
603// - filepath, relative to local module directory, resolves as a filepath relative to the local
604// source directory
605// - other modules using the ":name" syntax. These modules must implement DirProvider.
Inseob Kim93036a52024-10-25 17:02:21 +0900606func DirectoryPathsForModuleSrc(ctx ModuleMissingDepsPathContext, paths []string) DirectoryPaths {
607 var ret DirectoryPaths
Inseob Kim76e19852024-10-10 17:57:22 +0900608
609 for _, path := range paths {
610 if m, t := SrcIsModuleWithTag(path); m != "" {
Yu Liud3228ac2024-11-08 23:11:47 +0000611 module := GetModuleProxyFromPathDep(ctx, m, t)
Inseob Kim76e19852024-10-10 17:57:22 +0900612 if module == nil {
613 ctx.ModuleErrorf(`missing dependency on %q, is the property annotated with android:"path"?`, m)
614 continue
615 }
616 if t != "" {
617 ctx.ModuleErrorf("DirProvider dependency %q does not support the tag %q", module, t)
618 continue
619 }
620 mctx, ok := ctx.(OtherModuleProviderContext)
621 if !ok {
622 panic(fmt.Errorf("%s is not an OtherModuleProviderContext", ctx))
623 }
Yu Liud3228ac2024-11-08 23:11:47 +0000624 if dirProvider, ok := OtherModuleProvider(mctx, *module, DirProvider); ok {
Inseob Kim76e19852024-10-10 17:57:22 +0900625 ret = append(ret, dirProvider.Dirs...)
626 } else {
627 ReportPathErrorf(ctx, "module %q does not implement DirProvider", module)
628 }
629 } else {
630 p := pathForModuleSrc(ctx, path)
631 if isDir, err := ctx.Config().fs.IsDir(p.String()); err != nil {
632 ReportPathErrorf(ctx, "%s: %s", p, err.Error())
633 } else if !isDir {
634 ReportPathErrorf(ctx, "module directory path %q is not a directory", p)
635 } else {
Inseob Kim93036a52024-10-25 17:02:21 +0900636 ret = append(ret, &directoryPath{basePath{path: p.path, rel: p.rel}})
Inseob Kim76e19852024-10-10 17:57:22 +0900637 }
638 }
639 }
640
Inseob Kim93036a52024-10-25 17:02:21 +0900641 seen := make(map[DirectoryPath]bool, len(ret))
Inseob Kim76e19852024-10-10 17:57:22 +0900642 for _, path := range ret {
643 if seen[path] {
644 ReportPathErrorf(ctx, "duplicated path %q", path)
645 }
646 seen[path] = true
647 }
648 return ret
649}
650
Ulya Trafimovich4d2eeed2019-11-08 10:54:21 +0000651// OutputPaths is a slice of OutputPath objects, with helpers to operate on the collection.
652type OutputPaths []OutputPath
653
654// Paths returns the OutputPaths as a Paths
655func (p OutputPaths) Paths() Paths {
656 if p == nil {
657 return nil
658 }
659 ret := make(Paths, len(p))
660 for i, path := range p {
661 ret[i] = path
662 }
663 return ret
664}
665
666// Strings returns the string forms of the writable paths.
667func (p OutputPaths) Strings() []string {
668 if p == nil {
669 return nil
670 }
671 ret := make([]string, len(p))
672 for i, path := range p {
673 ret[i] = path.String()
674 }
675 return ret
676}
677
Liz Kammera830f3a2020-11-10 10:50:34 -0800678// Expands Paths to a SourceFileProducer or OutputFileProducer module dependency referenced via ":name" or ":name{.tag}" syntax.
679// If the dependency is not found, a missingErrorDependency is returned.
680// If the module dependency is not a SourceFileProducer or OutputFileProducer, appropriate errors will be returned.
681func getPathsFromModuleDep(ctx ModuleWithDepsPathContext, path, moduleName, tag string) (Paths, error) {
Yu Liud3228ac2024-11-08 23:11:47 +0000682 module := GetModuleProxyFromPathDep(ctx, moduleName, tag)
Liz Kammera830f3a2020-11-10 10:50:34 -0800683 if module == nil {
684 return nil, missingDependencyError{[]string{moduleName}}
685 }
Yu Liuf22120f2025-03-13 18:36:35 +0000686 if !OtherModulePointerProviderOrDefault(ctx, *module, CommonModuleInfoProvider).Enabled {
Colin Crossfa65cee2021-03-22 17:05:59 -0700687 return nil, missingDependencyError{[]string{moduleName}}
688 }
Yu Liud3228ac2024-11-08 23:11:47 +0000689
690 outputFiles, err := outputFilesForModule(ctx, *module, tag)
mrziwange6c85812024-05-22 14:36:09 -0700691 if outputFiles != nil && err == nil {
692 return outputFiles, nil
Liz Kammera830f3a2020-11-10 10:50:34 -0800693 } else {
mrziwange6c85812024-05-22 14:36:09 -0700694 return nil, err
Liz Kammera830f3a2020-11-10 10:50:34 -0800695 }
696}
697
Yu Liud3228ac2024-11-08 23:11:47 +0000698// GetModuleProxyFromPathDep will return the module that was added as a dependency automatically for
Paul Duffind5cf92e2021-07-09 17:38:55 +0100699// properties tagged with `android:"path"` or manually using ExtractSourceDeps or
700// ExtractSourcesDeps.
701//
702// The moduleName and tag supplied to this should be the values returned from SrcIsModuleWithTag.
703// Or, if no tag is expected then the moduleName should be the value returned by SrcIsModule and
704// the tag must be "".
705//
706// If tag is "" then the returned module will be the dependency that was added for ":moduleName".
707// Otherwise, it is the dependency that was added for ":moduleName{tag}".
Yu Liud3228ac2024-11-08 23:11:47 +0000708func GetModuleProxyFromPathDep(ctx ModuleWithDepsPathContext, moduleName, tag string) *ModuleProxy {
709 var found *ModuleProxy
710 // The sourceOrOutputDepTag uniquely identifies the module dependency as it contains both the
711 // module name and the tag. Dependencies added automatically for properties tagged with
712 // `android:"path"` are deduped so are guaranteed to be unique. It is possible for duplicate
713 // dependencies to be added manually using ExtractSourcesDeps or ExtractSourceDeps but even then
714 // it will always be the case that the dependencies will be identical, i.e. the same tag and same
715 // moduleName referring to the same dependency module.
716 //
717 // It does not matter whether the moduleName is a fully qualified name or if the module
718 // dependency is a prebuilt module. All that matters is the same information is supplied to
719 // create the tag here as was supplied to create the tag when the dependency was added so that
720 // this finds the matching dependency module.
721 expectedTag := sourceOrOutputDepTag(moduleName, tag)
722 ctx.VisitDirectDepsProxyWithTag(expectedTag, func(module ModuleProxy) {
723 found = &module
724 })
725 return found
726}
727
728// Deprecated: use GetModuleProxyFromPathDep
Paul Duffind5cf92e2021-07-09 17:38:55 +0100729func GetModuleFromPathDep(ctx ModuleWithDepsPathContext, moduleName, tag string) blueprint.Module {
Paul Duffin40131a32021-07-09 17:10:35 +0100730 var found blueprint.Module
731 // The sourceOrOutputDepTag uniquely identifies the module dependency as it contains both the
732 // module name and the tag. Dependencies added automatically for properties tagged with
733 // `android:"path"` are deduped so are guaranteed to be unique. It is possible for duplicate
734 // dependencies to be added manually using ExtractSourcesDeps or ExtractSourceDeps but even then
735 // it will always be the case that the dependencies will be identical, i.e. the same tag and same
736 // moduleName referring to the same dependency module.
737 //
738 // It does not matter whether the moduleName is a fully qualified name or if the module
739 // dependency is a prebuilt module. All that matters is the same information is supplied to
740 // create the tag here as was supplied to create the tag when the dependency was added so that
741 // this finds the matching dependency module.
742 expectedTag := sourceOrOutputDepTag(moduleName, tag)
Colin Cross648daea2024-09-12 14:35:29 -0700743 ctx.VisitDirectDeps(func(module Module) {
Paul Duffin40131a32021-07-09 17:10:35 +0100744 depTag := ctx.OtherModuleDependencyTag(module)
745 if depTag == expectedTag {
746 found = module
747 }
748 })
749 return found
Paul Duffind5cf92e2021-07-09 17:38:55 +0100750}
751
Liz Kammer620dea62021-04-14 17:36:10 -0400752// PathsAndMissingDepsForModuleSrcExcludes returns a Paths{} containing the resolved references in
753// paths, minus those listed in excludes. Elements of paths and excludes are resolved as:
Colin Crossd079e0b2022-08-16 10:27:33 -0700754// - filepath, relative to local module directory, resolves as a filepath relative to the local
755// source directory
756// - glob, relative to the local module directory, resolves as filepath(s), relative to the local
757// source directory. Not valid in excludes.
758// - other modules using the ":name{.tag}" syntax. These modules must implement SourceFileProducer
mrziwangd38e63d2024-07-15 13:43:37 -0700759// or set the OutputFilesProvider. These resolve as a filepath to an output filepath or generated
760// source filepath.
Colin Crossd079e0b2022-08-16 10:27:33 -0700761//
Liz Kammer620dea62021-04-14 17:36:10 -0400762// and a list of the module names of missing module dependencies are returned as the second return.
763// Properties passed as the paths argument must have been annotated with struct tag
Colin Cross41955e82019-05-29 14:40:35 -0700764// `android:"path"` so that dependencies on SourceFileProducer modules will have already been handled by the
Spandan Das950091c2023-07-19 22:26:37 +0000765// pathdeps mutator.
Liz Kammer619be462022-01-28 15:13:39 -0500766func PathsAndMissingDepsForModuleSrcExcludes(ctx ModuleMissingDepsPathContext, paths, excludes []string) (Paths, []string) {
767 return PathsAndMissingDepsRelativeToModuleSourceDir(SourceInput{
768 Context: ctx,
769 Paths: paths,
770 ExcludePaths: excludes,
771 IncludeDirs: true,
772 })
773}
774
775func PathsAndMissingDepsRelativeToModuleSourceDir(input SourceInput) (Paths, []string) {
776 prefix := pathForModuleSrc(input.Context).String()
Colin Cross8a497952019-03-05 22:25:09 -0800777
778 var expandedExcludes []string
Liz Kammer619be462022-01-28 15:13:39 -0500779 if input.ExcludePaths != nil {
780 expandedExcludes = make([]string, 0, len(input.ExcludePaths))
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700781 }
Colin Cross8a497952019-03-05 22:25:09 -0800782
Colin Crossba71a3f2019-03-18 12:12:48 -0700783 var missingExcludeDeps []string
Liz Kammer619be462022-01-28 15:13:39 -0500784 for _, e := range input.ExcludePaths {
Colin Cross41955e82019-05-29 14:40:35 -0700785 if m, t := SrcIsModuleWithTag(e); m != "" {
Liz Kammer619be462022-01-28 15:13:39 -0500786 modulePaths, err := getPathsFromModuleDep(input.Context, e, m, t)
Liz Kammera830f3a2020-11-10 10:50:34 -0800787 if m, ok := err.(missingDependencyError); ok {
788 missingExcludeDeps = append(missingExcludeDeps, m.missingDeps...)
789 } else if err != nil {
Liz Kammer619be462022-01-28 15:13:39 -0500790 reportPathError(input.Context, err)
Colin Cross8a497952019-03-05 22:25:09 -0800791 } else {
Liz Kammera830f3a2020-11-10 10:50:34 -0800792 expandedExcludes = append(expandedExcludes, modulePaths.Strings()...)
Colin Cross8a497952019-03-05 22:25:09 -0800793 }
794 } else {
795 expandedExcludes = append(expandedExcludes, filepath.Join(prefix, e))
796 }
797 }
798
Liz Kammer619be462022-01-28 15:13:39 -0500799 if input.Paths == nil {
Colin Crossba71a3f2019-03-18 12:12:48 -0700800 return nil, missingExcludeDeps
Colin Cross8a497952019-03-05 22:25:09 -0800801 }
802
Colin Crossba71a3f2019-03-18 12:12:48 -0700803 var missingDeps []string
804
Liz Kammer619be462022-01-28 15:13:39 -0500805 expandedSrcFiles := make(Paths, 0, len(input.Paths))
806 for _, s := range input.Paths {
807 srcFiles, err := expandOneSrcPath(sourcePathInput{
808 context: input.Context,
809 path: s,
810 expandedExcludes: expandedExcludes,
811 includeDirs: input.IncludeDirs,
812 })
Colin Cross8a497952019-03-05 22:25:09 -0800813 if depErr, ok := err.(missingDependencyError); ok {
Colin Crossba71a3f2019-03-18 12:12:48 -0700814 missingDeps = append(missingDeps, depErr.missingDeps...)
Colin Cross8a497952019-03-05 22:25:09 -0800815 } else if err != nil {
Liz Kammer619be462022-01-28 15:13:39 -0500816 reportPathError(input.Context, err)
Colin Cross8a497952019-03-05 22:25:09 -0800817 }
818 expandedSrcFiles = append(expandedSrcFiles, srcFiles...)
819 }
Colin Crossba71a3f2019-03-18 12:12:48 -0700820
Jihoon Kang0e3a5352024-04-12 00:45:50 +0000821 // TODO: b/334169722 - Replace with an error instead of implicitly removing duplicates.
822 return FirstUniquePaths(expandedSrcFiles), append(missingDeps, missingExcludeDeps...)
Colin Cross8a497952019-03-05 22:25:09 -0800823}
824
825type missingDependencyError struct {
826 missingDeps []string
827}
828
829func (e missingDependencyError) Error() string {
830 return "missing dependencies: " + strings.Join(e.missingDeps, ", ")
831}
832
Liz Kammer619be462022-01-28 15:13:39 -0500833type sourcePathInput struct {
834 context ModuleWithDepsPathContext
835 path string
836 expandedExcludes []string
837 includeDirs bool
838}
839
Liz Kammera830f3a2020-11-10 10:50:34 -0800840// Expands one path string to Paths rooted from the module's local source
841// directory, excluding those listed in the expandedExcludes.
842// Expands globs, references to SourceFileProducer or OutputFileProducer modules using the ":name" and ":name{.tag}" syntax.
Liz Kammer619be462022-01-28 15:13:39 -0500843func expandOneSrcPath(input sourcePathInput) (Paths, error) {
Jooyung Han7607dd32020-07-05 10:23:14 +0900844 excludePaths := func(paths Paths) Paths {
Liz Kammer619be462022-01-28 15:13:39 -0500845 if len(input.expandedExcludes) == 0 {
Jooyung Han7607dd32020-07-05 10:23:14 +0900846 return paths
847 }
848 remainder := make(Paths, 0, len(paths))
849 for _, p := range paths {
Liz Kammer619be462022-01-28 15:13:39 -0500850 if !InList(p.String(), input.expandedExcludes) {
Jooyung Han7607dd32020-07-05 10:23:14 +0900851 remainder = append(remainder, p)
852 }
853 }
854 return remainder
855 }
Liz Kammer619be462022-01-28 15:13:39 -0500856 if m, t := SrcIsModuleWithTag(input.path); m != "" {
857 modulePaths, err := getPathsFromModuleDep(input.context, input.path, m, t)
Liz Kammera830f3a2020-11-10 10:50:34 -0800858 if err != nil {
859 return nil, err
Colin Cross8a497952019-03-05 22:25:09 -0800860 } else {
Liz Kammera830f3a2020-11-10 10:50:34 -0800861 return excludePaths(modulePaths), nil
Colin Cross8a497952019-03-05 22:25:09 -0800862 }
Colin Cross8a497952019-03-05 22:25:09 -0800863 } else {
Liz Kammer619be462022-01-28 15:13:39 -0500864 p := pathForModuleSrc(input.context, input.path)
865 if pathtools.IsGlob(input.path) {
866 paths := GlobFiles(input.context, p.String(), input.expandedExcludes)
867 return PathsWithModuleSrcSubDir(input.context, paths, ""), nil
868 } else {
869 if exists, _, err := input.context.Config().fs.Exists(p.String()); err != nil {
870 ReportPathErrorf(input.context, "%s: %s", p, err.Error())
871 } else if !exists && !input.context.Config().TestAllowNonExistentPaths {
872 ReportPathErrorf(input.context, "module source path %q does not exist", p)
873 } else if !input.includeDirs {
874 if isDir, err := input.context.Config().fs.IsDir(p.String()); exists && err != nil {
875 ReportPathErrorf(input.context, "%s: %s", p, err.Error())
876 } else if isDir {
877 ReportPathErrorf(input.context, "module source path %q is a directory", p)
878 }
879 }
Colin Cross8a497952019-03-05 22:25:09 -0800880
Liz Kammer619be462022-01-28 15:13:39 -0500881 if InList(p.String(), input.expandedExcludes) {
882 return nil, nil
883 }
884 return Paths{p}, nil
Colin Cross8a497952019-03-05 22:25:09 -0800885 }
Colin Cross8a497952019-03-05 22:25:09 -0800886 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700887}
888
889// pathsForModuleSrcFromFullPath returns Paths rooted from the module's local
890// source directory, but strip the local source directory from the beginning of
Dan Willemsen540a78c2018-02-26 21:50:08 -0800891// each string. If incDirs is false, strip paths with a trailing '/' from the list.
Colin Crossfe4bc362018-09-12 10:02:13 -0700892// It intended for use in globs that only list files that exist, so it allows '$' in
893// filenames.
Liz Kammera830f3a2020-11-10 10:50:34 -0800894func pathsForModuleSrcFromFullPath(ctx EarlyModulePathContext, paths []string, incDirs bool) Paths {
Lukacs T. Berkif7e36d82021-08-16 17:05:09 +0200895 prefix := ctx.ModuleDir() + "/"
Colin Cross0f37af02017-09-27 17:42:05 -0700896 if prefix == "./" {
897 prefix = ""
898 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700899 ret := make(Paths, 0, len(paths))
900 for _, p := range paths {
Dan Willemsen540a78c2018-02-26 21:50:08 -0800901 if !incDirs && strings.HasSuffix(p, "/") {
902 continue
903 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700904 path := filepath.Clean(p)
905 if !strings.HasPrefix(path, prefix) {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +0100906 ReportPathErrorf(ctx, "Path %q is not in module source directory %q", p, prefix)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700907 continue
908 }
Colin Crosse3924e12018-08-15 20:18:53 -0700909
Colin Crossfe4bc362018-09-12 10:02:13 -0700910 srcPath, err := safePathForSource(ctx, ctx.ModuleDir(), path[len(prefix):])
Colin Crosse3924e12018-08-15 20:18:53 -0700911 if err != nil {
912 reportPathError(ctx, err)
913 continue
914 }
915
Colin Cross07e51612019-03-05 12:46:40 -0800916 srcPath.basePath.rel = srcPath.path
Colin Crosse3924e12018-08-15 20:18:53 -0700917
Colin Cross07e51612019-03-05 12:46:40 -0800918 ret = append(ret, srcPath)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700919 }
920 return ret
921}
922
Liz Kammera830f3a2020-11-10 10:50:34 -0800923// PathsWithOptionalDefaultForModuleSrc returns Paths rooted from the module's local source
924// directory. If input is nil, use the default if it exists. If input is empty, returns nil.
925func PathsWithOptionalDefaultForModuleSrc(ctx ModuleMissingDepsPathContext, input []string, def string) Paths {
Colin Cross0ddae7f2019-02-07 15:30:01 -0800926 if input != nil {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700927 return PathsForModuleSrc(ctx, input)
928 }
929 // Use Glob so that if the default doesn't exist, a dependency is added so that when it
930 // is created, we're run again.
Lukacs T. Berkif7e36d82021-08-16 17:05:09 +0200931 path := filepath.Join(ctx.ModuleDir(), def)
Liz Kammera830f3a2020-11-10 10:50:34 -0800932 return Glob(ctx, path, nil)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700933}
934
935// Strings returns the Paths in string form
936func (p Paths) Strings() []string {
937 if p == nil {
938 return nil
939 }
940 ret := make([]string, len(p))
941 for i, path := range p {
942 ret[i] = path.String()
943 }
944 return ret
945}
946
Colin Crossc0efd1d2020-07-03 11:56:24 -0700947func CopyOfPaths(paths Paths) Paths {
948 return append(Paths(nil), paths...)
949}
950
Colin Crossb6715442017-10-24 11:13:31 -0700951// FirstUniquePaths returns all unique elements of a Paths, keeping the first copy of each. It
952// modifies the Paths slice contents in place, and returns a subslice of the original slice.
Dan Willemsenfe92c962017-08-29 12:28:37 -0700953func FirstUniquePaths(list Paths) Paths {
Colin Cross27027c72020-02-28 15:34:17 -0800954 // 128 was chosen based on BenchmarkFirstUniquePaths results.
955 if len(list) > 128 {
956 return firstUniquePathsMap(list)
957 }
958 return firstUniquePathsList(list)
959}
960
Colin Crossc0efd1d2020-07-03 11:56:24 -0700961// SortedUniquePaths returns all unique elements of a Paths in sorted order. It modifies the
962// Paths slice contents in place, and returns a subslice of the original slice.
Jiyong Park33c77362020-05-29 22:00:16 +0900963func SortedUniquePaths(list Paths) Paths {
964 unique := FirstUniquePaths(list)
965 sort.Slice(unique, func(i, j int) bool {
966 return unique[i].String() < unique[j].String()
967 })
968 return unique
969}
970
Colin Cross27027c72020-02-28 15:34:17 -0800971func firstUniquePathsList(list Paths) Paths {
Dan Willemsenfe92c962017-08-29 12:28:37 -0700972 k := 0
973outer:
974 for i := 0; i < len(list); i++ {
975 for j := 0; j < k; j++ {
976 if list[i] == list[j] {
977 continue outer
978 }
979 }
980 list[k] = list[i]
981 k++
982 }
983 return list[:k]
984}
985
Colin Cross27027c72020-02-28 15:34:17 -0800986func firstUniquePathsMap(list Paths) Paths {
987 k := 0
988 seen := make(map[Path]bool, len(list))
989 for i := 0; i < len(list); i++ {
990 if seen[list[i]] {
991 continue
992 }
993 seen[list[i]] = true
994 list[k] = list[i]
995 k++
996 }
997 return list[:k]
998}
999
Colin Cross5d583952020-11-24 16:21:24 -08001000// FirstUniqueInstallPaths returns all unique elements of an InstallPaths, keeping the first copy of each. It
1001// modifies the InstallPaths slice contents in place, and returns a subslice of the original slice.
1002func FirstUniqueInstallPaths(list InstallPaths) InstallPaths {
1003 // 128 was chosen based on BenchmarkFirstUniquePaths results.
1004 if len(list) > 128 {
1005 return firstUniqueInstallPathsMap(list)
1006 }
1007 return firstUniqueInstallPathsList(list)
1008}
1009
1010func firstUniqueInstallPathsList(list InstallPaths) InstallPaths {
1011 k := 0
1012outer:
1013 for i := 0; i < len(list); i++ {
1014 for j := 0; j < k; j++ {
1015 if list[i] == list[j] {
1016 continue outer
1017 }
1018 }
1019 list[k] = list[i]
1020 k++
1021 }
1022 return list[:k]
1023}
1024
1025func firstUniqueInstallPathsMap(list InstallPaths) InstallPaths {
1026 k := 0
1027 seen := make(map[InstallPath]bool, len(list))
1028 for i := 0; i < len(list); i++ {
1029 if seen[list[i]] {
1030 continue
1031 }
1032 seen[list[i]] = true
1033 list[k] = list[i]
1034 k++
1035 }
1036 return list[:k]
1037}
1038
Colin Crossb6715442017-10-24 11:13:31 -07001039// LastUniquePaths returns all unique elements of a Paths, keeping the last copy of each. It
1040// modifies the Paths slice contents in place, and returns a subslice of the original slice.
1041func LastUniquePaths(list Paths) Paths {
1042 totalSkip := 0
1043 for i := len(list) - 1; i >= totalSkip; i-- {
1044 skip := 0
1045 for j := i - 1; j >= totalSkip; j-- {
1046 if list[i] == list[j] {
1047 skip++
1048 } else {
1049 list[j+skip] = list[j]
1050 }
1051 }
1052 totalSkip += skip
1053 }
1054 return list[totalSkip:]
1055}
1056
Colin Crossa140bb02018-04-17 10:52:26 -07001057// ReversePaths returns a copy of a Paths in reverse order.
1058func ReversePaths(list Paths) Paths {
1059 if list == nil {
1060 return nil
1061 }
1062 ret := make(Paths, len(list))
1063 for i := range list {
1064 ret[i] = list[len(list)-1-i]
1065 }
1066 return ret
1067}
1068
Jeff Gaston294356f2017-09-27 17:05:30 -07001069func indexPathList(s Path, list []Path) int {
1070 for i, l := range list {
1071 if l == s {
1072 return i
1073 }
1074 }
1075
1076 return -1
1077}
1078
1079func inPathList(p Path, list []Path) bool {
1080 return indexPathList(p, list) != -1
1081}
1082
1083func FilterPathList(list []Path, filter []Path) (remainder []Path, filtered []Path) {
Paul Duffin57b9e1d2019-12-13 00:03:35 +00001084 return FilterPathListPredicate(list, func(p Path) bool { return inPathList(p, filter) })
1085}
1086
1087func FilterPathListPredicate(list []Path, predicate func(Path) bool) (remainder []Path, filtered []Path) {
Jeff Gaston294356f2017-09-27 17:05:30 -07001088 for _, l := range list {
Paul Duffin57b9e1d2019-12-13 00:03:35 +00001089 if predicate(l) {
Jeff Gaston294356f2017-09-27 17:05:30 -07001090 filtered = append(filtered, l)
1091 } else {
1092 remainder = append(remainder, l)
1093 }
1094 }
1095
1096 return
1097}
1098
Colin Cross93e85952017-08-15 13:34:18 -07001099// HasExt returns true of any of the paths have extension ext, otherwise false
1100func (p Paths) HasExt(ext string) bool {
1101 for _, path := range p {
1102 if path.Ext() == ext {
1103 return true
1104 }
1105 }
1106
1107 return false
1108}
1109
1110// FilterByExt returns the subset of the paths that have extension ext
1111func (p Paths) FilterByExt(ext string) Paths {
1112 ret := make(Paths, 0, len(p))
1113 for _, path := range p {
1114 if path.Ext() == ext {
1115 ret = append(ret, path)
1116 }
1117 }
1118 return ret
1119}
1120
1121// FilterOutByExt returns the subset of the paths that do not have extension ext
1122func (p Paths) FilterOutByExt(ext string) Paths {
1123 ret := make(Paths, 0, len(p))
1124 for _, path := range p {
1125 if path.Ext() != ext {
1126 ret = append(ret, path)
1127 }
1128 }
1129 return ret
1130}
1131
Colin Cross5e6cfbe2017-11-03 15:20:35 -07001132// DirectorySortedPaths is a slice of paths that are sorted such that all files in a directory
1133// (including subdirectories) are in a contiguous subslice of the list, and can be found in
1134// O(log(N)) time using a binary search on the directory prefix.
1135type DirectorySortedPaths Paths
1136
1137func PathsToDirectorySortedPaths(paths Paths) DirectorySortedPaths {
1138 ret := append(DirectorySortedPaths(nil), paths...)
1139 sort.Slice(ret, func(i, j int) bool {
1140 return ret[i].String() < ret[j].String()
1141 })
1142 return ret
1143}
1144
1145// PathsInDirectory returns a subslice of the DirectorySortedPaths as a Paths that contains all entries
1146// that are in the specified directory and its subdirectories.
1147func (p DirectorySortedPaths) PathsInDirectory(dir string) Paths {
1148 prefix := filepath.Clean(dir) + "/"
1149 start := sort.Search(len(p), func(i int) bool {
1150 return prefix < p[i].String()
1151 })
1152
1153 ret := p[start:]
1154
1155 end := sort.Search(len(ret), func(i int) bool {
1156 return !strings.HasPrefix(ret[i].String(), prefix)
1157 })
1158
1159 ret = ret[:end]
1160
1161 return Paths(ret)
1162}
1163
Alex Humesky29e3bbe2020-11-20 21:30:13 -05001164// WritablePaths is a slice of WritablePath, used for multiple outputs.
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001165type WritablePaths []WritablePath
1166
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001167// RelativeToTop creates a new WritablePaths containing the result of calling Path.RelativeToTop on
1168// each item in this slice.
1169func (p WritablePaths) RelativeToTop() WritablePaths {
1170 ensureTestOnly()
1171 if p == nil {
1172 return p
1173 }
1174 ret := make(WritablePaths, len(p))
1175 for i, path := range p {
1176 ret[i] = path.RelativeToTop().(WritablePath)
1177 }
1178 return ret
1179}
1180
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001181// Strings returns the string forms of the writable paths.
1182func (p WritablePaths) Strings() []string {
1183 if p == nil {
1184 return nil
1185 }
1186 ret := make([]string, len(p))
1187 for i, path := range p {
1188 ret[i] = path.String()
1189 }
1190 return ret
1191}
1192
Colin Cross3bc7ffa2017-11-22 16:19:37 -08001193// Paths returns the WritablePaths as a Paths
1194func (p WritablePaths) Paths() Paths {
1195 if p == nil {
1196 return nil
1197 }
1198 ret := make(Paths, len(p))
1199 for i, path := range p {
1200 ret[i] = path
1201 }
1202 return ret
1203}
1204
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001205type basePath struct {
Paul Duffin74abc5d2021-03-24 09:24:59 +00001206 path string
1207 rel string
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001208}
1209
Yu Liu467d7c52024-09-18 21:54:44 +00001210type basePathGob struct {
1211 Path string
1212 Rel string
1213}
Yu Liufa297642024-06-11 00:13:02 +00001214
Yu Liu467d7c52024-09-18 21:54:44 +00001215func (p *basePath) ToGob() *basePathGob {
1216 return &basePathGob{
1217 Path: p.path,
1218 Rel: p.rel,
1219 }
1220}
1221
1222func (p *basePath) FromGob(data *basePathGob) {
1223 p.path = data.Path
1224 p.rel = data.Rel
1225}
1226
1227func (p basePath) GobEncode() ([]byte, error) {
Yu Liu3cadf7d2024-10-24 18:47:06 +00001228 return gobtools.CustomGobEncode[basePathGob](&p)
Yu Liufa297642024-06-11 00:13:02 +00001229}
1230
1231func (p *basePath) GobDecode(data []byte) error {
Yu Liu3cadf7d2024-10-24 18:47:06 +00001232 return gobtools.CustomGobDecode[basePathGob](data, p)
Yu Liufa297642024-06-11 00:13:02 +00001233}
1234
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001235func (p basePath) Ext() string {
1236 return filepath.Ext(p.path)
1237}
1238
Colin Cross4f6fc9c2016-10-26 10:05:25 -07001239func (p basePath) Base() string {
1240 return filepath.Base(p.path)
1241}
1242
Colin Crossfaeb7aa2017-02-01 14:12:44 -08001243func (p basePath) Rel() string {
1244 if p.rel != "" {
1245 return p.rel
1246 }
1247 return p.path
1248}
1249
Colin Cross0875c522017-11-28 17:34:01 -08001250func (p basePath) String() string {
1251 return p.path
1252}
1253
Colin Cross0db55682017-12-05 15:36:55 -08001254func (p basePath) withRel(rel string) basePath {
1255 p.path = filepath.Join(p.path, rel)
1256 p.rel = rel
1257 return p
1258}
1259
Colin Cross7707b242024-07-26 12:02:36 -07001260func (p basePath) withoutRel() basePath {
1261 p.rel = filepath.Base(p.path)
Cole Faustbc65a3f2023-08-01 16:38:55 +00001262 return p
1263}
1264
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001265// SourcePath is a Path representing a file path rooted from SrcDir
1266type SourcePath struct {
1267 basePath
1268}
1269
1270var _ Path = SourcePath{}
1271
Colin Cross0db55682017-12-05 15:36:55 -08001272func (p SourcePath) withRel(rel string) SourcePath {
1273 p.basePath = p.basePath.withRel(rel)
1274 return p
1275}
1276
Colin Crossbd73d0d2024-07-26 12:00:33 -07001277func (p SourcePath) RelativeToTop() Path {
1278 ensureTestOnly()
1279 return p
1280}
1281
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001282// safePathForSource is for paths that we expect are safe -- only for use by go
1283// code that is embedding ninja variables in paths
Colin Crossfe4bc362018-09-12 10:02:13 -07001284func safePathForSource(ctx PathContext, pathComponents ...string) (SourcePath, error) {
1285 p, err := validateSafePath(pathComponents...)
Cole Faust483d1f72023-01-09 14:35:27 -08001286 ret := SourcePath{basePath{p, ""}}
Colin Crossfe4bc362018-09-12 10:02:13 -07001287 if err != nil {
1288 return ret, err
1289 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001290
Colin Cross7b3dcc32019-01-24 13:14:39 -08001291 // absolute path already checked by validateSafePath
Inseob Kim5eb7ee92022-04-27 10:30:34 +09001292 // special-case api surface gen files for now
1293 if strings.HasPrefix(ret.String(), ctx.Config().soongOutDir) && !strings.Contains(ret.String(), ctx.Config().soongOutDir+"/.export") {
Mikhail Naganovab1f5182019-02-08 13:17:55 -08001294 return ret, fmt.Errorf("source path %q is in output", ret.String())
Colin Cross6e18ca42015-07-14 18:55:36 -07001295 }
1296
Colin Crossfe4bc362018-09-12 10:02:13 -07001297 return ret, err
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001298}
1299
Colin Cross192e97a2018-02-22 14:21:02 -08001300// pathForSource creates a SourcePath from pathComponents, but does not check that it exists.
1301func pathForSource(ctx PathContext, pathComponents ...string) (SourcePath, error) {
Colin Crossc48c1432018-02-23 07:09:01 +00001302 p, err := validatePath(pathComponents...)
Cole Faust483d1f72023-01-09 14:35:27 -08001303 ret := SourcePath{basePath{p, ""}}
Colin Cross94a32102018-02-22 14:21:02 -08001304 if err != nil {
Colin Cross192e97a2018-02-22 14:21:02 -08001305 return ret, err
Colin Cross94a32102018-02-22 14:21:02 -08001306 }
1307
Colin Cross7b3dcc32019-01-24 13:14:39 -08001308 // absolute path already checked by validatePath
Inseob Kim5eb7ee92022-04-27 10:30:34 +09001309 // special-case for now
1310 if strings.HasPrefix(ret.String(), ctx.Config().soongOutDir) && !strings.Contains(ret.String(), ctx.Config().soongOutDir+"/.export") {
Mikhail Naganovab1f5182019-02-08 13:17:55 -08001311 return ret, fmt.Errorf("source path %q is in output", ret.String())
Colin Crossc48c1432018-02-23 07:09:01 +00001312 }
1313
Colin Cross192e97a2018-02-22 14:21:02 -08001314 return ret, nil
1315}
1316
Sam Mortimerefd02782019-09-05 15:16:13 -07001317// pathForSourceRelaxed creates a SourcePath from pathComponents, but does not check that it exists.
1318// It differs from pathForSource in that the path is allowed to exist outside of the PathContext.
1319func pathForSourceRelaxed(ctx PathContext, pathComponents ...string) (SourcePath, error) {
1320 p := filepath.Join(pathComponents...)
1321 ret := SourcePath{basePath{p, ""}}
1322
1323 abs, err := filepath.Abs(ret.String())
1324 if err != nil {
1325 return ret, err
1326 }
1327 buildroot, err := filepath.Abs(ctx.Config().outDir)
1328 if err != nil {
1329 return ret, err
1330 }
1331 if strings.HasPrefix(abs, buildroot) {
1332 return ret, fmt.Errorf("source path %s is in output", abs)
1333 }
1334
1335 if pathtools.IsGlob(ret.String()) {
1336 return ret, fmt.Errorf("path may not contain a glob: %s", ret.String())
1337 }
1338
1339 return ret, nil
1340}
1341
Colin Cross192e97a2018-02-22 14:21:02 -08001342// existsWithDependencies returns true if the path exists, and adds appropriate dependencies to rerun if the
1343// path does not exist.
Colin Cross662d6142022-11-03 20:38:01 -07001344func existsWithDependencies(ctx PathGlobContext, path SourcePath) (exists bool, err error) {
Colin Cross192e97a2018-02-22 14:21:02 -08001345 var files []string
1346
Colin Cross662d6142022-11-03 20:38:01 -07001347 // Use glob to produce proper dependencies, even though we only want
1348 // a single file.
1349 files, err = ctx.GlobWithDeps(path.String(), nil)
Colin Cross192e97a2018-02-22 14:21:02 -08001350
1351 if err != nil {
1352 return false, fmt.Errorf("glob: %s", err.Error())
1353 }
1354
1355 return len(files) > 0, nil
1356}
1357
1358// PathForSource joins the provided path components and validates that the result
1359// neither escapes the source dir nor is in the out dir.
1360// On error, it will return a usable, but invalid SourcePath, and report a ModuleError.
1361func PathForSource(ctx PathContext, pathComponents ...string) SourcePath {
1362 path, err := pathForSource(ctx, pathComponents...)
1363 if err != nil {
1364 reportPathError(ctx, err)
1365 }
1366
Colin Crosse3924e12018-08-15 20:18:53 -07001367 if pathtools.IsGlob(path.String()) {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001368 ReportPathErrorf(ctx, "path may not contain a glob: %s", path.String())
Colin Crosse3924e12018-08-15 20:18:53 -07001369 }
1370
Liz Kammera830f3a2020-11-10 10:50:34 -08001371 if modCtx, ok := ctx.(ModuleMissingDepsPathContext); ok && ctx.Config().AllowMissingDependencies() {
Colin Cross662d6142022-11-03 20:38:01 -07001372 exists, err := existsWithDependencies(modCtx, path)
Colin Cross192e97a2018-02-22 14:21:02 -08001373 if err != nil {
1374 reportPathError(ctx, err)
1375 }
1376 if !exists {
1377 modCtx.AddMissingDependencies([]string{path.String()})
1378 }
Colin Cross988414c2020-01-11 01:11:46 +00001379 } else if exists, _, err := ctx.Config().fs.Exists(path.String()); err != nil {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001380 ReportPathErrorf(ctx, "%s: %s", path, err.Error())
Pedro Loureiro5d190cc2021-02-15 15:41:33 +00001381 } else if !exists && !ctx.Config().TestAllowNonExistentPaths {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001382 ReportPathErrorf(ctx, "source path %q does not exist", path)
Colin Cross192e97a2018-02-22 14:21:02 -08001383 }
1384 return path
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001385}
1386
Cole Faustbc65a3f2023-08-01 16:38:55 +00001387// PathForArbitraryOutput creates a path for the given components. Unlike PathForOutput,
1388// the path is relative to the root of the output folder, not the out/soong folder.
Cole Faustaddc0dd2024-12-16 16:19:17 -08001389func PathForArbitraryOutput(ctx PathContext, pathComponents ...string) WritablePath {
Colin Cross3b1c6842024-07-26 11:52:57 -07001390 path, err := validatePath(pathComponents...)
Cole Faustbc65a3f2023-08-01 16:38:55 +00001391 if err != nil {
1392 reportPathError(ctx, err)
1393 }
Colin Cross3b1c6842024-07-26 11:52:57 -07001394 fullPath := filepath.Join(ctx.Config().OutDir(), path)
1395 path = fullPath[len(fullPath)-len(path):]
1396 return OutputPath{basePath{path, ""}, ctx.Config().OutDir(), fullPath}
Cole Faustbc65a3f2023-08-01 16:38:55 +00001397}
1398
Spandan Dasc6c10fa2022-10-21 21:52:13 +00001399// MaybeExistentPathForSource joins the provided path components and validates that the result
1400// neither escapes the source dir nor is in the out dir.
1401// It does not validate whether the path exists.
1402func MaybeExistentPathForSource(ctx PathContext, pathComponents ...string) SourcePath {
1403 path, err := pathForSource(ctx, pathComponents...)
1404 if err != nil {
1405 reportPathError(ctx, err)
1406 }
1407
1408 if pathtools.IsGlob(path.String()) {
1409 ReportPathErrorf(ctx, "path may not contain a glob: %s", path.String())
1410 }
1411 return path
1412}
1413
Sam Mortimerefd02782019-09-05 15:16:13 -07001414// PathForSourceRelaxed joins the provided path components. Unlike PathForSource,
1415// the result is allowed to exist outside of the source dir.
1416// On error, it will return a usable, but invalid SourcePath, and report a ModuleError.
1417func PathForSourceRelaxed(ctx PathContext, pathComponents ...string) SourcePath {
1418 path, err := pathForSourceRelaxed(ctx, pathComponents...)
1419 if err != nil {
1420 reportPathError(ctx, err)
1421 }
1422
1423 if modCtx, ok := ctx.(ModuleMissingDepsPathContext); ok && ctx.Config().AllowMissingDependencies() {
1424 exists, err := existsWithDependencies(modCtx, path)
1425 if err != nil {
1426 reportPathError(ctx, err)
1427 }
1428 if !exists {
1429 modCtx.AddMissingDependencies([]string{path.String()})
1430 }
1431 } else if exists, _, err := ctx.Config().fs.Exists(path.String()); err != nil {
1432 ReportPathErrorf(ctx, "%s: %s", path, err.Error())
1433 } else if !exists {
1434 ReportPathErrorf(ctx, "source path %s does not exist", path)
1435 }
1436 return path
1437}
1438
Liz Kammer7aa52882021-02-11 09:16:14 -05001439// ExistentPathForSource returns an OptionalPath with the SourcePath, rooted from SrcDir, *not*
1440// rooted from the module's local source directory, if the path exists, or an empty OptionalPath if
1441// it doesn't exist. Dependencies are added so that the ninja file will be regenerated if the state
1442// of the path changes.
Colin Cross662d6142022-11-03 20:38:01 -07001443func ExistentPathForSource(ctx PathGlobContext, pathComponents ...string) OptionalPath {
Colin Cross192e97a2018-02-22 14:21:02 -08001444 path, err := pathForSource(ctx, pathComponents...)
Colin Cross1ccfcc32018-02-22 13:54:26 -08001445 if err != nil {
1446 reportPathError(ctx, err)
Martin Stjernholmc32dd1c2021-09-15 02:39:00 +01001447 // No need to put the error message into the returned path since it has been reported already.
Colin Cross1ccfcc32018-02-22 13:54:26 -08001448 return OptionalPath{}
1449 }
Colin Crossc48c1432018-02-23 07:09:01 +00001450
Colin Crosse3924e12018-08-15 20:18:53 -07001451 if pathtools.IsGlob(path.String()) {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001452 ReportPathErrorf(ctx, "path may not contain a glob: %s", path.String())
Colin Crosse3924e12018-08-15 20:18:53 -07001453 return OptionalPath{}
1454 }
1455
Colin Cross192e97a2018-02-22 14:21:02 -08001456 exists, err := existsWithDependencies(ctx, path)
Colin Crossc48c1432018-02-23 07:09:01 +00001457 if err != nil {
1458 reportPathError(ctx, err)
1459 return OptionalPath{}
1460 }
Colin Cross192e97a2018-02-22 14:21:02 -08001461 if !exists {
Martin Stjernholmc32dd1c2021-09-15 02:39:00 +01001462 return InvalidOptionalPath(path.String() + " does not exist")
Colin Crossc48c1432018-02-23 07:09:01 +00001463 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001464 return OptionalPathForPath(path)
1465}
1466
1467func (p SourcePath) String() string {
Cole Faust483d1f72023-01-09 14:35:27 -08001468 if p.path == "" {
1469 return "."
1470 }
1471 return p.path
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001472}
1473
Colin Cross7707b242024-07-26 12:02:36 -07001474func (p SourcePath) WithoutRel() Path {
1475 p.basePath = p.basePath.withoutRel()
1476 return p
1477}
1478
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001479// Join creates a new SourcePath with paths... joined with the current path. The
1480// provided paths... may not use '..' to escape from the current path.
1481func (p SourcePath) Join(ctx PathContext, paths ...string) SourcePath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001482 path, err := validatePath(paths...)
1483 if err != nil {
1484 reportPathError(ctx, err)
1485 }
Colin Cross0db55682017-12-05 15:36:55 -08001486 return p.withRel(path)
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001487}
1488
Colin Cross2fafa3e2019-03-05 12:39:51 -08001489// join is like Join but does less path validation.
1490func (p SourcePath) join(ctx PathContext, paths ...string) SourcePath {
1491 path, err := validateSafePath(paths...)
1492 if err != nil {
1493 reportPathError(ctx, err)
1494 }
1495 return p.withRel(path)
1496}
1497
Colin Cross70dda7e2019-10-01 22:05:35 -07001498// OutputPath is a Path representing an intermediates file path rooted from the build directory
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001499type OutputPath struct {
1500 basePath
Paul Duffind65c58b2021-03-24 09:22:07 +00001501
Colin Cross3b1c6842024-07-26 11:52:57 -07001502 // The base out directory for this path, either Config.SoongOutDir() or Config.OutDir()
1503 outDir string
Paul Duffind65c58b2021-03-24 09:22:07 +00001504
Colin Crossd63c9a72020-01-29 16:52:50 -08001505 fullPath string
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001506}
1507
Yu Liu467d7c52024-09-18 21:54:44 +00001508type outputPathGob struct {
Yu Liu5246a7e2024-10-09 20:04:52 +00001509 BasePath basePath
Yu Liu467d7c52024-09-18 21:54:44 +00001510 OutDir string
1511 FullPath string
1512}
Yu Liufa297642024-06-11 00:13:02 +00001513
Yu Liu467d7c52024-09-18 21:54:44 +00001514func (p *OutputPath) ToGob() *outputPathGob {
1515 return &outputPathGob{
Yu Liu5246a7e2024-10-09 20:04:52 +00001516 BasePath: p.basePath,
Yu Liu467d7c52024-09-18 21:54:44 +00001517 OutDir: p.outDir,
1518 FullPath: p.fullPath,
1519 }
1520}
1521
1522func (p *OutputPath) FromGob(data *outputPathGob) {
Yu Liu5246a7e2024-10-09 20:04:52 +00001523 p.basePath = data.BasePath
Yu Liu467d7c52024-09-18 21:54:44 +00001524 p.outDir = data.OutDir
1525 p.fullPath = data.FullPath
1526}
1527
1528func (p OutputPath) GobEncode() ([]byte, error) {
Yu Liu3cadf7d2024-10-24 18:47:06 +00001529 return gobtools.CustomGobEncode[outputPathGob](&p)
Yu Liufa297642024-06-11 00:13:02 +00001530}
1531
1532func (p *OutputPath) GobDecode(data []byte) error {
Yu Liu3cadf7d2024-10-24 18:47:06 +00001533 return gobtools.CustomGobDecode[outputPathGob](data, p)
Yu Liufa297642024-06-11 00:13:02 +00001534}
1535
Colin Cross702e0f82017-10-18 17:27:54 -07001536func (p OutputPath) withRel(rel string) OutputPath {
Colin Cross0db55682017-12-05 15:36:55 -08001537 p.basePath = p.basePath.withRel(rel)
Colin Crossd63c9a72020-01-29 16:52:50 -08001538 p.fullPath = filepath.Join(p.fullPath, rel)
Colin Cross702e0f82017-10-18 17:27:54 -07001539 return p
1540}
1541
Colin Cross7707b242024-07-26 12:02:36 -07001542func (p OutputPath) WithoutRel() Path {
1543 p.basePath = p.basePath.withoutRel()
Colin Cross3063b782018-08-15 11:19:12 -07001544 return p
1545}
1546
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02001547func (p OutputPath) getSoongOutDir() string {
Colin Cross3b1c6842024-07-26 11:52:57 -07001548 return p.outDir
Paul Duffin9b478b02019-12-10 13:41:51 +00001549}
1550
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001551func (p OutputPath) RelativeToTop() Path {
1552 return p.outputPathRelativeToTop()
1553}
1554
1555func (p OutputPath) outputPathRelativeToTop() OutputPath {
Colin Cross3b1c6842024-07-26 11:52:57 -07001556 p.fullPath = StringPathRelativeToTop(p.outDir, p.fullPath)
1557 if strings.HasSuffix(p.outDir, testOutSoongSubDir) {
1558 p.outDir = TestOutSoongDir
1559 } else {
1560 // Handle the PathForArbitraryOutput case
1561 p.outDir = testOutDir
1562 }
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001563 return p
1564}
1565
Paul Duffin0267d492021-02-02 10:05:52 +00001566func (p OutputPath) objPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleObjPath {
1567 return PathForModuleObj(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
1568}
1569
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001570var _ Path = OutputPath{}
Paul Duffin9b478b02019-12-10 13:41:51 +00001571var _ WritablePath = OutputPath{}
Paul Duffin0267d492021-02-02 10:05:52 +00001572var _ objPathProvider = OutputPath{}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001573
Chris Parsons8f232a22020-06-23 17:37:05 -04001574// toolDepPath is a Path representing a dependency of the build tool.
1575type toolDepPath struct {
1576 basePath
1577}
1578
Colin Cross7707b242024-07-26 12:02:36 -07001579func (t toolDepPath) WithoutRel() Path {
1580 t.basePath = t.basePath.withoutRel()
1581 return t
1582}
1583
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001584func (t toolDepPath) RelativeToTop() Path {
1585 ensureTestOnly()
1586 return t
1587}
1588
Chris Parsons8f232a22020-06-23 17:37:05 -04001589var _ Path = toolDepPath{}
1590
1591// pathForBuildToolDep returns a toolDepPath representing the given path string.
1592// There is no validation for the path, as it is "trusted": It may fail
1593// normal validation checks. For example, it may be an absolute path.
1594// Only use this function to construct paths for dependencies of the build
1595// tool invocation.
1596func pathForBuildToolDep(ctx PathContext, path string) toolDepPath {
Paul Duffin74abc5d2021-03-24 09:24:59 +00001597 return toolDepPath{basePath{path, ""}}
Chris Parsons8f232a22020-06-23 17:37:05 -04001598}
1599
Jeff Gaston734e3802017-04-10 15:47:24 -07001600// PathForOutput joins the provided paths and returns an OutputPath that is
1601// validated to not escape the build dir.
1602// On error, it will return a usable, but invalid OutputPath, and report a ModuleError.
1603func PathForOutput(ctx PathContext, pathComponents ...string) OutputPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001604 path, err := validatePath(pathComponents...)
1605 if err != nil {
1606 reportPathError(ctx, err)
1607 }
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02001608 fullPath := filepath.Join(ctx.Config().soongOutDir, path)
Colin Crossd63c9a72020-01-29 16:52:50 -08001609 path = fullPath[len(fullPath)-len(path):]
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02001610 return OutputPath{basePath{path, ""}, ctx.Config().soongOutDir, fullPath}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001611}
1612
Colin Cross3b1c6842024-07-26 11:52:57 -07001613// PathsForOutput returns Paths rooted from outDir
Colin Cross40e33732019-02-15 11:08:35 -08001614func PathsForOutput(ctx PathContext, paths []string) WritablePaths {
1615 ret := make(WritablePaths, len(paths))
1616 for i, path := range paths {
1617 ret[i] = PathForOutput(ctx, path)
1618 }
1619 return ret
1620}
1621
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001622func (p OutputPath) writablePath() {}
1623
1624func (p OutputPath) String() string {
Colin Crossd63c9a72020-01-29 16:52:50 -08001625 return p.fullPath
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001626}
1627
1628// Join creates a new OutputPath with paths... joined with the current path. The
1629// provided paths... may not use '..' to escape from the current path.
1630func (p OutputPath) Join(ctx PathContext, paths ...string) OutputPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001631 path, err := validatePath(paths...)
1632 if err != nil {
1633 reportPathError(ctx, err)
1634 }
Colin Cross0db55682017-12-05 15:36:55 -08001635 return p.withRel(path)
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001636}
1637
Colin Cross8854a5a2019-02-11 14:14:16 -08001638// ReplaceExtension creates a new OutputPath with the extension replaced with ext.
1639func (p OutputPath) ReplaceExtension(ctx PathContext, ext string) OutputPath {
1640 if strings.Contains(ext, "/") {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001641 ReportPathErrorf(ctx, "extension %q cannot contain /", ext)
Colin Cross8854a5a2019-02-11 14:14:16 -08001642 }
1643 ret := PathForOutput(ctx, pathtools.ReplaceExtension(p.path, ext))
Colin Cross2cdd5df2019-02-25 10:25:24 -08001644 ret.rel = pathtools.ReplaceExtension(p.rel, ext)
Colin Cross8854a5a2019-02-11 14:14:16 -08001645 return ret
1646}
1647
Colin Cross40e33732019-02-15 11:08:35 -08001648// InSameDir creates a new OutputPath from the directory of the current OutputPath joined with the elements in paths.
1649func (p OutputPath) InSameDir(ctx PathContext, paths ...string) OutputPath {
1650 path, err := validatePath(paths...)
1651 if err != nil {
1652 reportPathError(ctx, err)
1653 }
1654
1655 ret := PathForOutput(ctx, filepath.Dir(p.path), path)
Colin Cross2cdd5df2019-02-25 10:25:24 -08001656 ret.rel = filepath.Join(filepath.Dir(p.rel), path)
Colin Cross40e33732019-02-15 11:08:35 -08001657 return ret
1658}
1659
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001660// PathForIntermediates returns an OutputPath representing the top-level
1661// intermediates directory.
1662func PathForIntermediates(ctx PathContext, paths ...string) OutputPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001663 path, err := validatePath(paths...)
1664 if err != nil {
1665 reportPathError(ctx, err)
1666 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001667 return PathForOutput(ctx, ".intermediates", path)
1668}
1669
Colin Cross07e51612019-03-05 12:46:40 -08001670var _ genPathProvider = SourcePath{}
1671var _ objPathProvider = SourcePath{}
1672var _ resPathProvider = SourcePath{}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001673
Colin Cross07e51612019-03-05 12:46:40 -08001674// PathForModuleSrc returns a Path representing the paths... under the
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001675// module's local source directory.
Liz Kammera830f3a2020-11-10 10:50:34 -08001676func PathForModuleSrc(ctx ModuleMissingDepsPathContext, pathComponents ...string) Path {
Paul Duffin407501b2021-07-09 16:56:35 +01001677 // Just join the components textually just to make sure that it does not corrupt a fully qualified
1678 // module reference, e.g. if the pathComponents is "://other:foo" then using filepath.Join() or
1679 // validatePath() will corrupt it, e.g. replace "//" with "/". If the path is not a module
1680 // reference then it will be validated by expandOneSrcPath anyway when it calls expandOneSrcPath.
1681 p := strings.Join(pathComponents, string(filepath.Separator))
Liz Kammer619be462022-01-28 15:13:39 -05001682 paths, err := expandOneSrcPath(sourcePathInput{context: ctx, path: p, includeDirs: true})
Colin Cross8a497952019-03-05 22:25:09 -08001683 if err != nil {
1684 if depErr, ok := err.(missingDependencyError); ok {
1685 if ctx.Config().AllowMissingDependencies() {
1686 ctx.AddMissingDependencies(depErr.missingDeps)
1687 } else {
1688 ctx.ModuleErrorf(`%s, is the property annotated with android:"path"?`, depErr.Error())
1689 }
1690 } else {
1691 reportPathError(ctx, err)
1692 }
1693 return nil
1694 } else if len(paths) == 0 {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001695 ReportPathErrorf(ctx, "%q produced no files, expected exactly one", p)
Colin Cross8a497952019-03-05 22:25:09 -08001696 return nil
1697 } else if len(paths) > 1 {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001698 ReportPathErrorf(ctx, "%q produced %d files, expected exactly one", p, len(paths))
Colin Cross8a497952019-03-05 22:25:09 -08001699 }
1700 return paths[0]
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001701}
1702
Liz Kammera830f3a2020-11-10 10:50:34 -08001703func pathForModuleSrc(ctx EarlyModulePathContext, paths ...string) SourcePath {
Colin Cross07e51612019-03-05 12:46:40 -08001704 p, err := validatePath(paths...)
1705 if err != nil {
1706 reportPathError(ctx, err)
1707 }
1708
1709 path, err := pathForSource(ctx, ctx.ModuleDir(), p)
1710 if err != nil {
1711 reportPathError(ctx, err)
1712 }
1713
1714 path.basePath.rel = p
1715
1716 return path
1717}
1718
Colin Cross2fafa3e2019-03-05 12:39:51 -08001719// PathsWithModuleSrcSubDir takes a list of Paths and returns a new list of Paths where Rel() on each path
1720// will return the path relative to subDir in the module's source directory. If any input paths are not located
1721// inside subDir then a path error will be reported.
Liz Kammera830f3a2020-11-10 10:50:34 -08001722func PathsWithModuleSrcSubDir(ctx EarlyModulePathContext, paths Paths, subDir string) Paths {
Colin Cross2fafa3e2019-03-05 12:39:51 -08001723 paths = append(Paths(nil), paths...)
Colin Cross07e51612019-03-05 12:46:40 -08001724 subDirFullPath := pathForModuleSrc(ctx, subDir)
Colin Cross2fafa3e2019-03-05 12:39:51 -08001725 for i, path := range paths {
1726 rel := Rel(ctx, subDirFullPath.String(), path.String())
1727 paths[i] = subDirFullPath.join(ctx, rel)
1728 }
1729 return paths
1730}
1731
1732// PathWithModuleSrcSubDir takes a Path and returns a Path where Rel() will return the path relative to subDir in the
1733// 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 -08001734func PathWithModuleSrcSubDir(ctx EarlyModulePathContext, path Path, subDir string) Path {
Colin Cross07e51612019-03-05 12:46:40 -08001735 subDirFullPath := pathForModuleSrc(ctx, subDir)
Colin Cross2fafa3e2019-03-05 12:39:51 -08001736 rel := Rel(ctx, subDirFullPath.String(), path.String())
1737 return subDirFullPath.Join(ctx, rel)
1738}
1739
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001740// OptionalPathForModuleSrc returns an OptionalPath. The OptionalPath contains a
1741// valid path if p is non-nil.
Liz Kammera830f3a2020-11-10 10:50:34 -08001742func OptionalPathForModuleSrc(ctx ModuleMissingDepsPathContext, p *string) OptionalPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001743 if p == nil {
1744 return OptionalPath{}
1745 }
1746 return OptionalPathForPath(PathForModuleSrc(ctx, *p))
1747}
1748
Liz Kammera830f3a2020-11-10 10:50:34 -08001749func (p SourcePath) genPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleGenPath {
Colin Cross7fc17db2017-02-01 14:07:55 -08001750 return PathForModuleGen(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001751}
1752
yangbill6d032dd2024-04-18 03:05:49 +00001753func (p SourcePath) genPathWithExtAndTrimExt(ctx ModuleOutPathContext, subdir, ext string, trimExt string) ModuleGenPath {
1754 // If Trim_extension being set, force append Output_extension without replace original extension.
1755 if trimExt != "" {
1756 if ext != "" {
1757 return PathForModuleGen(ctx, subdir, strings.TrimSuffix(p.path, trimExt)+"."+ext)
1758 }
1759 return PathForModuleGen(ctx, subdir, strings.TrimSuffix(p.path, trimExt))
1760 }
1761 return PathForModuleGen(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
1762}
1763
Liz Kammera830f3a2020-11-10 10:50:34 -08001764func (p SourcePath) objPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleObjPath {
Colin Cross7fc17db2017-02-01 14:07:55 -08001765 return PathForModuleObj(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001766}
1767
Liz Kammera830f3a2020-11-10 10:50:34 -08001768func (p SourcePath) resPathWithName(ctx ModuleOutPathContext, name string) ModuleResPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001769 // TODO: Use full directory if the new ctx is not the current ctx?
1770 return PathForModuleRes(ctx, p.path, name)
1771}
1772
1773// ModuleOutPath is a Path representing a module's output directory.
1774type ModuleOutPath struct {
1775 OutputPath
1776}
1777
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001778func (p ModuleOutPath) RelativeToTop() Path {
1779 p.OutputPath = p.outputPathRelativeToTop()
1780 return p
1781}
1782
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001783var _ Path = ModuleOutPath{}
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001784var _ WritablePath = ModuleOutPath{}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001785
Liz Kammera830f3a2020-11-10 10:50:34 -08001786func (p ModuleOutPath) objPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleObjPath {
Pete Bentleyfcf55bf2019-08-16 20:14:32 +01001787 return PathForModuleObj(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
1788}
1789
Liz Kammera830f3a2020-11-10 10:50:34 -08001790// ModuleOutPathContext Subset of ModuleContext functions necessary for output path methods.
1791type ModuleOutPathContext interface {
1792 PathContext
1793
1794 ModuleName() string
1795 ModuleDir() string
1796 ModuleSubDir() string
1797}
1798
1799func pathForModuleOut(ctx ModuleOutPathContext) OutputPath {
Inseob Kimb7e9f5f2024-06-25 17:39:52 +09001800 return PathForOutput(ctx, ".intermediates", ctx.ModuleDir(), ctx.ModuleName(), ctx.ModuleSubDir())
Colin Cross702e0f82017-10-18 17:27:54 -07001801}
1802
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001803// PathForModuleOut returns a Path representing the paths... under the module's
1804// output directory.
Liz Kammera830f3a2020-11-10 10:50:34 -08001805func PathForModuleOut(ctx ModuleOutPathContext, paths ...string) ModuleOutPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001806 p, err := validatePath(paths...)
1807 if err != nil {
1808 reportPathError(ctx, err)
1809 }
Colin Cross702e0f82017-10-18 17:27:54 -07001810 return ModuleOutPath{
Liz Kammera830f3a2020-11-10 10:50:34 -08001811 OutputPath: pathForModuleOut(ctx).withRel(p),
Colin Cross702e0f82017-10-18 17:27:54 -07001812 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001813}
1814
1815// ModuleGenPath is a Path representing the 'gen' directory in a module's output
1816// directory. Mainly used for generated sources.
1817type ModuleGenPath struct {
1818 ModuleOutPath
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001819}
1820
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001821func (p ModuleGenPath) RelativeToTop() Path {
1822 p.OutputPath = p.outputPathRelativeToTop()
1823 return p
1824}
1825
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001826var _ Path = ModuleGenPath{}
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001827var _ WritablePath = ModuleGenPath{}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001828var _ genPathProvider = ModuleGenPath{}
1829var _ objPathProvider = ModuleGenPath{}
1830
1831// PathForModuleGen returns a Path representing the paths... under the module's
1832// `gen' directory.
Liz Kammera830f3a2020-11-10 10:50:34 -08001833func PathForModuleGen(ctx ModuleOutPathContext, paths ...string) ModuleGenPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001834 p, err := validatePath(paths...)
1835 if err != nil {
1836 reportPathError(ctx, err)
1837 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001838 return ModuleGenPath{
Colin Cross702e0f82017-10-18 17:27:54 -07001839 ModuleOutPath: ModuleOutPath{
Liz Kammera830f3a2020-11-10 10:50:34 -08001840 OutputPath: pathForModuleOut(ctx).withRel("gen").withRel(p),
Colin Cross702e0f82017-10-18 17:27:54 -07001841 },
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001842 }
1843}
1844
Liz Kammera830f3a2020-11-10 10:50:34 -08001845func (p ModuleGenPath) genPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleGenPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001846 // TODO: make a different path for local vs remote generated files?
Dan Willemsen21ec4902016-11-02 20:43:13 -07001847 return PathForModuleGen(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001848}
1849
yangbill6d032dd2024-04-18 03:05:49 +00001850func (p ModuleGenPath) genPathWithExtAndTrimExt(ctx ModuleOutPathContext, subdir, ext string, trimExt string) ModuleGenPath {
1851 // If Trim_extension being set, force append Output_extension without replace original extension.
1852 if trimExt != "" {
1853 if ext != "" {
1854 return PathForModuleGen(ctx, subdir, strings.TrimSuffix(p.path, trimExt)+"."+ext)
1855 }
1856 return PathForModuleGen(ctx, subdir, strings.TrimSuffix(p.path, trimExt))
1857 }
1858 return PathForModuleGen(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
1859}
1860
Liz Kammera830f3a2020-11-10 10:50:34 -08001861func (p ModuleGenPath) objPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleObjPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001862 return PathForModuleObj(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
1863}
1864
1865// ModuleObjPath is a Path representing the 'obj' directory in a module's output
1866// directory. Used for compiled objects.
1867type ModuleObjPath struct {
1868 ModuleOutPath
1869}
1870
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001871func (p ModuleObjPath) RelativeToTop() Path {
1872 p.OutputPath = p.outputPathRelativeToTop()
1873 return p
1874}
1875
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001876var _ Path = ModuleObjPath{}
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001877var _ WritablePath = ModuleObjPath{}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001878
1879// PathForModuleObj returns a Path representing the paths... under the module's
1880// 'obj' directory.
Liz Kammera830f3a2020-11-10 10:50:34 -08001881func PathForModuleObj(ctx ModuleOutPathContext, pathComponents ...string) ModuleObjPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001882 p, err := validatePath(pathComponents...)
1883 if err != nil {
1884 reportPathError(ctx, err)
1885 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001886 return ModuleObjPath{PathForModuleOut(ctx, "obj", p)}
1887}
1888
1889// ModuleResPath is a a Path representing the 'res' directory in a module's
1890// output directory.
1891type ModuleResPath struct {
1892 ModuleOutPath
1893}
1894
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001895func (p ModuleResPath) RelativeToTop() Path {
1896 p.OutputPath = p.outputPathRelativeToTop()
1897 return p
1898}
1899
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001900var _ Path = ModuleResPath{}
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001901var _ WritablePath = ModuleResPath{}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001902
1903// PathForModuleRes returns a Path representing the paths... under the module's
1904// 'res' directory.
Liz Kammera830f3a2020-11-10 10:50:34 -08001905func PathForModuleRes(ctx ModuleOutPathContext, pathComponents ...string) ModuleResPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001906 p, err := validatePath(pathComponents...)
1907 if err != nil {
1908 reportPathError(ctx, err)
1909 }
1910
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001911 return ModuleResPath{PathForModuleOut(ctx, "res", p)}
1912}
1913
Colin Cross70dda7e2019-10-01 22:05:35 -07001914// InstallPath is a Path representing a installed file path rooted from the build directory
1915type InstallPath struct {
1916 basePath
Colin Crossff6c33d2019-10-02 16:01:35 -07001917
Lukacs T. Berkib078ade2021-08-31 10:42:08 +02001918 // The soong build directory, i.e. Config.SoongOutDir()
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02001919 soongOutDir string
Paul Duffind65c58b2021-03-24 09:22:07 +00001920
Jiyong Park957bcd92020-10-20 18:23:33 +09001921 // partitionDir is the part of the InstallPath that is automatically determined according to the context.
1922 // For example, it is host/<os>-<arch> for host modules, and target/product/<device>/<partition> for device modules.
1923 partitionDir string
1924
Colin Crossb1692a32021-10-25 15:39:01 -07001925 partition string
1926
Jiyong Park957bcd92020-10-20 18:23:33 +09001927 // makePath indicates whether this path is for Soong (false) or Make (true).
1928 makePath bool
Colin Crossc0e42d52024-02-01 16:42:36 -08001929
1930 fullPath string
Colin Cross70dda7e2019-10-01 22:05:35 -07001931}
1932
Yu Liu467d7c52024-09-18 21:54:44 +00001933type installPathGob struct {
Yu Liu5246a7e2024-10-09 20:04:52 +00001934 BasePath basePath
Yu Liu467d7c52024-09-18 21:54:44 +00001935 SoongOutDir string
1936 PartitionDir string
1937 Partition string
1938 MakePath bool
1939 FullPath string
1940}
Yu Liu26a716d2024-08-30 23:40:32 +00001941
Yu Liu467d7c52024-09-18 21:54:44 +00001942func (p *InstallPath) ToGob() *installPathGob {
1943 return &installPathGob{
Yu Liu5246a7e2024-10-09 20:04:52 +00001944 BasePath: p.basePath,
Yu Liu467d7c52024-09-18 21:54:44 +00001945 SoongOutDir: p.soongOutDir,
1946 PartitionDir: p.partitionDir,
1947 Partition: p.partition,
1948 MakePath: p.makePath,
1949 FullPath: p.fullPath,
1950 }
1951}
1952
1953func (p *InstallPath) FromGob(data *installPathGob) {
Yu Liu5246a7e2024-10-09 20:04:52 +00001954 p.basePath = data.BasePath
Yu Liu467d7c52024-09-18 21:54:44 +00001955 p.soongOutDir = data.SoongOutDir
1956 p.partitionDir = data.PartitionDir
1957 p.partition = data.Partition
1958 p.makePath = data.MakePath
1959 p.fullPath = data.FullPath
1960}
1961
1962func (p InstallPath) GobEncode() ([]byte, error) {
Yu Liu3cadf7d2024-10-24 18:47:06 +00001963 return gobtools.CustomGobEncode[installPathGob](&p)
Yu Liu26a716d2024-08-30 23:40:32 +00001964}
1965
1966func (p *InstallPath) GobDecode(data []byte) error {
Yu Liu3cadf7d2024-10-24 18:47:06 +00001967 return gobtools.CustomGobDecode[installPathGob](data, p)
Yu Liu26a716d2024-08-30 23:40:32 +00001968}
1969
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001970// Will panic if called from outside a test environment.
1971func ensureTestOnly() {
Martin Stjernholm32312eb2021-03-27 18:54:49 +00001972 if PrefixInList(os.Args, "-test.") {
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001973 return
1974 }
Martin Stjernholm32312eb2021-03-27 18:54:49 +00001975 panic(fmt.Errorf("Not in test. Command line:\n %s", strings.Join(os.Args, "\n ")))
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001976}
1977
1978func (p InstallPath) RelativeToTop() Path {
1979 ensureTestOnly()
Colin Crossc0e42d52024-02-01 16:42:36 -08001980 if p.makePath {
Colin Cross3b1c6842024-07-26 11:52:57 -07001981 p.soongOutDir = testOutDir
Colin Crossc0e42d52024-02-01 16:42:36 -08001982 } else {
Colin Cross3b1c6842024-07-26 11:52:57 -07001983 p.soongOutDir = TestOutSoongDir
Colin Crossc0e42d52024-02-01 16:42:36 -08001984 }
1985 p.fullPath = filepath.Join(p.soongOutDir, p.path)
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001986 return p
1987}
1988
Colin Cross7707b242024-07-26 12:02:36 -07001989func (p InstallPath) WithoutRel() Path {
1990 p.basePath = p.basePath.withoutRel()
1991 return p
1992}
1993
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02001994func (p InstallPath) getSoongOutDir() string {
1995 return p.soongOutDir
Paul Duffin9b478b02019-12-10 13:41:51 +00001996}
1997
Hans MÃ¥nssond3f2bd72020-11-27 12:37:28 +01001998func (p InstallPath) ReplaceExtension(ctx PathContext, ext string) OutputPath {
1999 panic("Not implemented")
2000}
2001
Paul Duffin9b478b02019-12-10 13:41:51 +00002002var _ Path = InstallPath{}
2003var _ WritablePath = InstallPath{}
2004
Colin Cross70dda7e2019-10-01 22:05:35 -07002005func (p InstallPath) writablePath() {}
2006
2007func (p InstallPath) String() string {
Colin Crossc0e42d52024-02-01 16:42:36 -08002008 return p.fullPath
Jiyong Park957bcd92020-10-20 18:23:33 +09002009}
2010
2011// PartitionDir returns the path to the partition where the install path is rooted at. It is
2012// out/soong/target/product/<device>/<partition> for device modules, and out/soong/host/<os>-<arch> for host modules.
2013// The ./soong is dropped if the install path is for Make.
2014func (p InstallPath) PartitionDir() string {
2015 if p.makePath {
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02002016 return filepath.Join(p.soongOutDir, "../", p.partitionDir)
Jiyong Park957bcd92020-10-20 18:23:33 +09002017 } else {
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02002018 return filepath.Join(p.soongOutDir, p.partitionDir)
Jiyong Park957bcd92020-10-20 18:23:33 +09002019 }
Colin Cross70dda7e2019-10-01 22:05:35 -07002020}
2021
Jihoon Kangf78a8902022-09-01 22:47:07 +00002022func (p InstallPath) Partition() string {
2023 return p.partition
2024}
2025
Colin Cross70dda7e2019-10-01 22:05:35 -07002026// Join creates a new InstallPath with paths... joined with the current path. The
2027// provided paths... may not use '..' to escape from the current path.
2028func (p InstallPath) Join(ctx PathContext, paths ...string) InstallPath {
2029 path, err := validatePath(paths...)
2030 if err != nil {
2031 reportPathError(ctx, err)
2032 }
2033 return p.withRel(path)
2034}
2035
2036func (p InstallPath) withRel(rel string) InstallPath {
2037 p.basePath = p.basePath.withRel(rel)
Colin Crossc0e42d52024-02-01 16:42:36 -08002038 p.fullPath = filepath.Join(p.fullPath, rel)
Colin Cross70dda7e2019-10-01 22:05:35 -07002039 return p
2040}
2041
Colin Crossc68db4b2021-11-11 18:59:15 -08002042// Deprecated: ToMakePath is a noop, PathForModuleInstall always returns Make paths when building
2043// embedded in Make.
Colin Crossff6c33d2019-10-02 16:01:35 -07002044func (p InstallPath) ToMakePath() InstallPath {
Jiyong Park957bcd92020-10-20 18:23:33 +09002045 p.makePath = true
Colin Crossff6c33d2019-10-02 16:01:35 -07002046 return p
Colin Cross70dda7e2019-10-01 22:05:35 -07002047}
2048
Dan Willemsen34cc69e2015-09-23 15:26:20 -07002049// PathForModuleInstall returns a Path representing the install path for the
2050// module appended with paths...
Colin Cross70dda7e2019-10-01 22:05:35 -07002051func PathForModuleInstall(ctx ModuleInstallPathContext, pathComponents ...string) InstallPath {
Spandan Das5d1b9292021-06-03 19:36:41 +00002052 os, arch := osAndArch(ctx)
Cole Faust11edf552023-10-13 11:32:14 -07002053 partition := modulePartition(ctx, os.Class == Device)
Cole Faust3b703f32023-10-16 13:30:51 -07002054 return pathForInstall(ctx, os, arch, partition, pathComponents...)
Spandan Das5d1b9292021-06-03 19:36:41 +00002055}
2056
Colin Cross1d0eb7a2021-11-03 14:08:20 -07002057// PathForHostDexInstall returns an InstallPath representing the install path for the
2058// module appended with paths...
2059func PathForHostDexInstall(ctx ModuleInstallPathContext, pathComponents ...string) InstallPath {
Cole Faust3b703f32023-10-16 13:30:51 -07002060 return pathForInstall(ctx, ctx.Config().BuildOS, ctx.Config().BuildArch, "", pathComponents...)
Colin Cross1d0eb7a2021-11-03 14:08:20 -07002061}
2062
Spandan Das5d1b9292021-06-03 19:36:41 +00002063// PathForModuleInPartitionInstall is similar to PathForModuleInstall but partition is provided by the caller
2064func PathForModuleInPartitionInstall(ctx ModuleInstallPathContext, partition string, pathComponents ...string) InstallPath {
2065 os, arch := osAndArch(ctx)
Cole Faust3b703f32023-10-16 13:30:51 -07002066 return pathForInstall(ctx, os, arch, partition, pathComponents...)
Spandan Das5d1b9292021-06-03 19:36:41 +00002067}
2068
2069func osAndArch(ctx ModuleInstallPathContext) (OsType, ArchType) {
Colin Cross6e359402020-02-10 15:29:54 -08002070 os := ctx.Os()
Jiyong Park87788b52020-09-01 12:37:45 +09002071 arch := ctx.Arch().ArchType
2072 forceOS, forceArch := ctx.InstallForceOS()
2073 if forceOS != nil {
Colin Cross6e359402020-02-10 15:29:54 -08002074 os = *forceOS
2075 }
Jiyong Park87788b52020-09-01 12:37:45 +09002076 if forceArch != nil {
2077 arch = *forceArch
2078 }
Spandan Das5d1b9292021-06-03 19:36:41 +00002079 return os, arch
2080}
Colin Cross609c49a2020-02-13 13:20:11 -08002081
Colin Crossc0e42d52024-02-01 16:42:36 -08002082func pathForPartitionInstallDir(ctx PathContext, partition, partitionPath string, makePath bool) InstallPath {
2083 fullPath := ctx.Config().SoongOutDir()
2084 if makePath {
2085 // Make path starts with out/ instead of out/soong.
2086 fullPath = filepath.Join(fullPath, "../", partitionPath)
2087 } else {
2088 fullPath = filepath.Join(fullPath, partitionPath)
2089 }
2090
2091 return InstallPath{
2092 basePath: basePath{partitionPath, ""},
2093 soongOutDir: ctx.Config().soongOutDir,
2094 partitionDir: partitionPath,
2095 partition: partition,
2096 makePath: makePath,
2097 fullPath: fullPath,
2098 }
2099}
2100
Cole Faust3b703f32023-10-16 13:30:51 -07002101func pathForInstall(ctx PathContext, os OsType, arch ArchType, partition string,
Colin Cross609c49a2020-02-13 13:20:11 -08002102 pathComponents ...string) InstallPath {
2103
Jiyong Park97859152023-02-14 17:05:48 +09002104 var partitionPaths []string
Colin Cross609c49a2020-02-13 13:20:11 -08002105
Colin Cross6e359402020-02-10 15:29:54 -08002106 if os.Class == Device {
Justin Yunbe6f81d2024-12-17 21:15:59 +09002107 partitionPaths = []string{"target", "product", *ctx.Config().deviceNameToInstall, partition}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07002108 } else {
Jiyong Park87788b52020-09-01 12:37:45 +09002109 osName := os.String()
Colin Crossa9b2aac2022-06-15 17:25:51 -07002110 if os == Linux {
Jiyong Park87788b52020-09-01 12:37:45 +09002111 // instead of linux_glibc
2112 osName = "linux"
Dan Willemsen866b5632017-09-22 12:28:24 -07002113 }
Colin Crossa9b2aac2022-06-15 17:25:51 -07002114 if os == LinuxMusl && ctx.Config().UseHostMusl() {
2115 // When using musl instead of glibc, use "linux" instead of "linux_musl". When cross
2116 // compiling we will still use "linux_musl".
2117 osName = "linux"
2118 }
2119
Jiyong Park87788b52020-09-01 12:37:45 +09002120 // SOONG_HOST_OUT is set to out/host/$(HOST_OS)-$(HOST_PREBUILT_ARCH)
2121 // and HOST_PREBUILT_ARCH is forcibly set to x86 even on x86_64 hosts. We don't seem
2122 // to have a plan to fix it (see the comment in build/make/core/envsetup.mk).
2123 // Let's keep using x86 for the existing cases until we have a need to support
2124 // other architectures.
2125 archName := arch.String()
2126 if os.Class == Host && (arch == X86_64 || arch == Common) {
2127 archName = "x86"
2128 }
Jiyong Park97859152023-02-14 17:05:48 +09002129 partitionPaths = []string{"host", osName + "-" + archName, partition}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07002130 }
Colin Cross70dda7e2019-10-01 22:05:35 -07002131
Jiyong Park97859152023-02-14 17:05:48 +09002132 partitionPath, err := validatePath(partitionPaths...)
Colin Cross70dda7e2019-10-01 22:05:35 -07002133 if err != nil {
2134 reportPathError(ctx, err)
2135 }
Colin Crossff6c33d2019-10-02 16:01:35 -07002136
Cole Faust6b7075f2024-12-17 10:42:42 -08002137 base := pathForPartitionInstallDir(ctx, partition, partitionPath, true)
Jiyong Park957bcd92020-10-20 18:23:33 +09002138 return base.Join(ctx, pathComponents...)
Dan Willemsen34cc69e2015-09-23 15:26:20 -07002139}
2140
Spandan Dasf280b232024-04-04 21:25:51 +00002141func PathForNdkInstall(ctx PathContext, paths ...string) OutputPath {
2142 return PathForOutput(ctx, append([]string{"ndk"}, paths...)...)
Nicolas Geoffray1228e9c2020-02-27 13:45:35 +00002143}
2144
2145func PathForMainlineSdksInstall(ctx PathContext, paths ...string) InstallPath {
Spandan Dasf280b232024-04-04 21:25:51 +00002146 base := pathForPartitionInstallDir(ctx, "", "mainline-sdks", false)
2147 return base.Join(ctx, paths...)
Nicolas Geoffray1228e9c2020-02-27 13:45:35 +00002148}
2149
Weijia Heaa37c162024-11-06 19:46:03 +00002150func PathForSuiteInstall(ctx PathContext, suite string, pathComponents ...string) InstallPath {
2151 return pathForPartitionInstallDir(ctx, "test_suites", "test_suites", false).Join(ctx, suite).Join(ctx, pathComponents...)
2152}
2153
Colin Cross70dda7e2019-10-01 22:05:35 -07002154func InstallPathToOnDevicePath(ctx PathContext, path InstallPath) string {
Colin Crossb1692a32021-10-25 15:39:01 -07002155 rel := Rel(ctx, strings.TrimSuffix(path.PartitionDir(), path.partition), path.String())
Colin Cross43f08db2018-11-12 10:13:39 -08002156 return "/" + rel
2157}
2158
Cole Faust11edf552023-10-13 11:32:14 -07002159func modulePartition(ctx ModuleInstallPathContext, device bool) string {
Colin Cross43f08db2018-11-12 10:13:39 -08002160 var partition string
Colin Cross6e359402020-02-10 15:29:54 -08002161 if ctx.InstallInTestcases() {
2162 // "testcases" install directory can be used for host or device modules.
Jaewoong Jung0949f312019-09-11 10:25:18 -07002163 partition = "testcases"
Cole Faust11edf552023-10-13 11:32:14 -07002164 } else if device {
Colin Cross6e359402020-02-10 15:29:54 -08002165 if ctx.InstallInData() {
2166 partition = "data"
2167 } else if ctx.InstallInRamdisk() {
2168 if ctx.DeviceConfig().BoardUsesRecoveryAsBoot() {
2169 partition = "recovery/root/first_stage_ramdisk"
2170 } else {
2171 partition = "ramdisk"
2172 }
2173 if !ctx.InstallInRoot() {
2174 partition += "/system"
2175 }
Yifan Hong60e0cfb2020-10-21 15:17:56 -07002176 } else if ctx.InstallInVendorRamdisk() {
Yifan Hong39143a92020-10-26 12:43:12 -07002177 // The module is only available after switching root into
2178 // /first_stage_ramdisk. To expose the module before switching root
2179 // on a device without a dedicated recovery partition, install the
2180 // recovery variant.
Yifan Hongdd8dacc2020-10-21 15:40:17 -07002181 if ctx.DeviceConfig().BoardMoveRecoveryResourcesToVendorBoot() {
Petri Gyntherac229562021-03-02 23:44:02 -08002182 partition = "vendor_ramdisk/first_stage_ramdisk"
Yifan Hongdd8dacc2020-10-21 15:40:17 -07002183 } else {
Petri Gyntherac229562021-03-02 23:44:02 -08002184 partition = "vendor_ramdisk"
Yifan Hongdd8dacc2020-10-21 15:40:17 -07002185 }
2186 if !ctx.InstallInRoot() {
2187 partition += "/system"
2188 }
Inseob Kim08758f02021-04-08 21:13:22 +09002189 } else if ctx.InstallInDebugRamdisk() {
2190 partition = "debug_ramdisk"
Colin Cross6e359402020-02-10 15:29:54 -08002191 } else if ctx.InstallInRecovery() {
2192 if ctx.InstallInRoot() {
2193 partition = "recovery/root"
2194 } else {
2195 // the layout of recovery partion is the same as that of system partition
2196 partition = "recovery/root/system"
2197 }
Colin Crossea30d852023-11-29 16:00:16 -08002198 } else if ctx.SocSpecific() || ctx.InstallInVendor() {
Colin Cross6e359402020-02-10 15:29:54 -08002199 partition = ctx.DeviceConfig().VendorPath()
Colin Crossea30d852023-11-29 16:00:16 -08002200 } else if ctx.DeviceSpecific() || ctx.InstallInOdm() {
Colin Cross6e359402020-02-10 15:29:54 -08002201 partition = ctx.DeviceConfig().OdmPath()
Colin Crossea30d852023-11-29 16:00:16 -08002202 } else if ctx.ProductSpecific() || ctx.InstallInProduct() {
Colin Cross6e359402020-02-10 15:29:54 -08002203 partition = ctx.DeviceConfig().ProductPath()
2204 } else if ctx.SystemExtSpecific() {
2205 partition = ctx.DeviceConfig().SystemExtPath()
2206 } else if ctx.InstallInRoot() {
2207 partition = "root"
Spandan Das27ff7672024-11-06 19:23:57 +00002208 } else if ctx.InstallInSystemDlkm() {
2209 partition = ctx.DeviceConfig().SystemDlkmPath()
2210 } else if ctx.InstallInVendorDlkm() {
2211 partition = ctx.DeviceConfig().VendorDlkmPath()
2212 } else if ctx.InstallInOdmDlkm() {
2213 partition = ctx.DeviceConfig().OdmDlkmPath()
Yifan Hong82db7352020-01-21 16:12:26 -08002214 } else {
Colin Cross6e359402020-02-10 15:29:54 -08002215 partition = "system"
Yifan Hong82db7352020-01-21 16:12:26 -08002216 }
Colin Cross6e359402020-02-10 15:29:54 -08002217 if ctx.InstallInSanitizerDir() {
2218 partition = "data/asan/" + partition
Yifan Hong82db7352020-01-21 16:12:26 -08002219 }
Colin Cross43f08db2018-11-12 10:13:39 -08002220 }
2221 return partition
2222}
2223
Colin Cross609c49a2020-02-13 13:20:11 -08002224type InstallPaths []InstallPath
2225
2226// Paths returns the InstallPaths as a Paths
2227func (p InstallPaths) Paths() Paths {
2228 if p == nil {
2229 return nil
2230 }
2231 ret := make(Paths, len(p))
2232 for i, path := range p {
2233 ret[i] = path
2234 }
2235 return ret
2236}
2237
2238// Strings returns the string forms of the install paths.
2239func (p InstallPaths) Strings() []string {
2240 if p == nil {
2241 return nil
2242 }
2243 ret := make([]string, len(p))
2244 for i, path := range p {
2245 ret[i] = path.String()
2246 }
2247 return ret
2248}
2249
Jingwen Chen24d0c562023-02-07 09:29:36 +00002250// validatePathInternal ensures that a path does not leave its component, and
2251// optionally doesn't contain Ninja variables.
2252func validatePathInternal(allowNinjaVariables bool, pathComponents ...string) (string, error) {
Colin Crossbf9ed3f2023-10-24 14:17:03 -07002253 initialEmpty := 0
2254 finalEmpty := 0
2255 for i, path := range pathComponents {
Jingwen Chen24d0c562023-02-07 09:29:36 +00002256 if !allowNinjaVariables && strings.Contains(path, "$") {
2257 return "", fmt.Errorf("Path contains invalid character($): %s", path)
2258 }
2259
Dan Willemsen80a7c2a2015-12-21 14:57:11 -08002260 path := filepath.Clean(path)
maxwen479f5b02024-03-20 14:41:25 +01002261 if path == ".." || strings.HasPrefix(path, "../") || i != initialEmpty && strings.HasPrefix(path, "/") {
Colin Cross1ccfcc32018-02-22 13:54:26 -08002262 return "", fmt.Errorf("Path is outside directory: %s", path)
Dan Willemsen80a7c2a2015-12-21 14:57:11 -08002263 }
Colin Crossbf9ed3f2023-10-24 14:17:03 -07002264
2265 if i == initialEmpty && pathComponents[i] == "" {
2266 initialEmpty++
2267 }
2268 if i == finalEmpty && pathComponents[len(pathComponents)-1-i] == "" {
2269 finalEmpty++
2270 }
Dan Willemsen80a7c2a2015-12-21 14:57:11 -08002271 }
Colin Crossbf9ed3f2023-10-24 14:17:03 -07002272 // Optimization: filepath.Join("foo", "") returns a newly allocated copy
2273 // of "foo", while filepath.Join("foo") does not. Strip out any empty
2274 // path components.
2275 if initialEmpty == len(pathComponents) {
2276 return "", nil
2277 }
2278 nonEmptyPathComponents := pathComponents[initialEmpty : len(pathComponents)-finalEmpty]
Dan Willemsen34cc69e2015-09-23 15:26:20 -07002279 // TODO: filepath.Join isn't necessarily correct with embedded ninja
2280 // variables. '..' may remove the entire ninja variable, even if it
2281 // will be expanded to multiple nested directories.
Colin Crossbf9ed3f2023-10-24 14:17:03 -07002282 return filepath.Join(nonEmptyPathComponents...), nil
Dan Willemsen34cc69e2015-09-23 15:26:20 -07002283}
2284
Jingwen Chen24d0c562023-02-07 09:29:36 +00002285// validateSafePath validates a path that we trust (may contain ninja
2286// variables). Ensures that each path component does not attempt to leave its
2287// component. Returns a joined version of each path component.
2288func validateSafePath(pathComponents ...string) (string, error) {
2289 return validatePathInternal(true, pathComponents...)
2290}
2291
Dan Willemsen80a7c2a2015-12-21 14:57:11 -08002292// validatePath validates that a path does not include ninja variables, and that
2293// each path component does not attempt to leave its component. Returns a joined
2294// version of each path component.
Colin Cross1ccfcc32018-02-22 13:54:26 -08002295func validatePath(pathComponents ...string) (string, error) {
Jingwen Chen24d0c562023-02-07 09:29:36 +00002296 return validatePathInternal(false, pathComponents...)
Colin Cross6e18ca42015-07-14 18:55:36 -07002297}
Colin Cross5b529592017-05-09 13:34:34 -07002298
Colin Cross0875c522017-11-28 17:34:01 -08002299func PathForPhony(ctx PathContext, phony string) WritablePath {
2300 if strings.ContainsAny(phony, "$/") {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01002301 ReportPathErrorf(ctx, "Phony target contains invalid character ($ or /): %s", phony)
Colin Cross0875c522017-11-28 17:34:01 -08002302 }
Paul Duffin74abc5d2021-03-24 09:24:59 +00002303 return PhonyPath{basePath{phony, ""}}
Colin Cross0875c522017-11-28 17:34:01 -08002304}
2305
Colin Cross74e3fe42017-12-11 15:51:44 -08002306type PhonyPath struct {
2307 basePath
2308}
2309
2310func (p PhonyPath) writablePath() {}
2311
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02002312func (p PhonyPath) getSoongOutDir() string {
Paul Duffind65c58b2021-03-24 09:22:07 +00002313 // A phone path cannot contain any / so cannot be relative to the build directory.
2314 return ""
Paul Duffin9b478b02019-12-10 13:41:51 +00002315}
2316
Paul Duffin85d8f0d2021-03-24 10:18:18 +00002317func (p PhonyPath) RelativeToTop() Path {
2318 ensureTestOnly()
2319 // A phony path cannot contain any / so does not have a build directory so switching to a new
2320 // build directory has no effect so just return this path.
2321 return p
2322}
2323
Colin Cross7707b242024-07-26 12:02:36 -07002324func (p PhonyPath) WithoutRel() Path {
2325 p.basePath = p.basePath.withoutRel()
2326 return p
2327}
2328
Hans MÃ¥nssond3f2bd72020-11-27 12:37:28 +01002329func (p PhonyPath) ReplaceExtension(ctx PathContext, ext string) OutputPath {
2330 panic("Not implemented")
2331}
2332
Colin Cross74e3fe42017-12-11 15:51:44 -08002333var _ Path = PhonyPath{}
2334var _ WritablePath = PhonyPath{}
2335
Colin Cross5b529592017-05-09 13:34:34 -07002336type testPath struct {
2337 basePath
2338}
2339
Paul Duffin85d8f0d2021-03-24 10:18:18 +00002340func (p testPath) RelativeToTop() Path {
2341 ensureTestOnly()
2342 return p
2343}
2344
Colin Cross7707b242024-07-26 12:02:36 -07002345func (p testPath) WithoutRel() Path {
2346 p.basePath = p.basePath.withoutRel()
2347 return p
2348}
2349
Colin Cross5b529592017-05-09 13:34:34 -07002350func (p testPath) String() string {
2351 return p.path
2352}
2353
Paul Duffin85d8f0d2021-03-24 10:18:18 +00002354var _ Path = testPath{}
2355
Colin Cross40e33732019-02-15 11:08:35 -08002356// PathForTesting returns a Path constructed from joining the elements of paths with '/'. It should only be used from
2357// within tests.
Colin Cross5b529592017-05-09 13:34:34 -07002358func PathForTesting(paths ...string) Path {
Colin Cross1ccfcc32018-02-22 13:54:26 -08002359 p, err := validateSafePath(paths...)
2360 if err != nil {
2361 panic(err)
2362 }
Colin Cross5b529592017-05-09 13:34:34 -07002363 return testPath{basePath{path: p, rel: p}}
2364}
2365
Sam Delmerico2351eac2022-05-24 17:10:02 +00002366func PathForTestingWithRel(path, rel string) Path {
2367 p, err := validateSafePath(path, rel)
2368 if err != nil {
2369 panic(err)
2370 }
2371 r, err := validatePath(rel)
2372 if err != nil {
2373 panic(err)
2374 }
2375 return testPath{basePath{path: p, rel: r}}
2376}
2377
Colin Cross40e33732019-02-15 11:08:35 -08002378// PathsForTesting returns a Path constructed from each element in strs. It should only be used from within tests.
2379func PathsForTesting(strs ...string) Paths {
Colin Cross5b529592017-05-09 13:34:34 -07002380 p := make(Paths, len(strs))
2381 for i, s := range strs {
2382 p[i] = PathForTesting(s)
2383 }
2384
2385 return p
2386}
Colin Cross43f08db2018-11-12 10:13:39 -08002387
Colin Cross40e33732019-02-15 11:08:35 -08002388type testPathContext struct {
2389 config Config
Colin Cross40e33732019-02-15 11:08:35 -08002390}
2391
Colin Cross40e33732019-02-15 11:08:35 -08002392func (x *testPathContext) Config() Config { return x.config }
2393func (x *testPathContext) AddNinjaFileDeps(...string) {}
2394
2395// PathContextForTesting returns a PathContext that can be used in tests, for example to create an OutputPath with
2396// PathForOutput.
Colin Cross98be1bb2019-12-13 20:41:13 -08002397func PathContextForTesting(config Config) PathContext {
Colin Cross40e33732019-02-15 11:08:35 -08002398 return &testPathContext{
2399 config: config,
Colin Cross40e33732019-02-15 11:08:35 -08002400 }
2401}
2402
Ulya Trafimovichccc8c852020-10-14 11:29:07 +01002403type testModuleInstallPathContext struct {
2404 baseModuleContext
2405
2406 inData bool
2407 inTestcases bool
2408 inSanitizerDir bool
2409 inRamdisk bool
2410 inVendorRamdisk bool
Inseob Kim08758f02021-04-08 21:13:22 +09002411 inDebugRamdisk bool
Ulya Trafimovichccc8c852020-10-14 11:29:07 +01002412 inRecovery bool
2413 inRoot bool
Colin Crossea30d852023-11-29 16:00:16 -08002414 inOdm bool
2415 inProduct bool
2416 inVendor bool
Spandan Das27ff7672024-11-06 19:23:57 +00002417 inSystemDlkm bool
2418 inVendorDlkm bool
2419 inOdmDlkm bool
Ulya Trafimovichccc8c852020-10-14 11:29:07 +01002420 forceOS *OsType
2421 forceArch *ArchType
2422}
2423
2424func (m testModuleInstallPathContext) Config() Config {
2425 return m.baseModuleContext.config
2426}
2427
2428func (testModuleInstallPathContext) AddNinjaFileDeps(deps ...string) {}
2429
2430func (m testModuleInstallPathContext) InstallInData() bool {
2431 return m.inData
2432}
2433
2434func (m testModuleInstallPathContext) InstallInTestcases() bool {
2435 return m.inTestcases
2436}
2437
2438func (m testModuleInstallPathContext) InstallInSanitizerDir() bool {
2439 return m.inSanitizerDir
2440}
2441
2442func (m testModuleInstallPathContext) InstallInRamdisk() bool {
2443 return m.inRamdisk
2444}
2445
2446func (m testModuleInstallPathContext) InstallInVendorRamdisk() bool {
2447 return m.inVendorRamdisk
2448}
2449
Inseob Kim08758f02021-04-08 21:13:22 +09002450func (m testModuleInstallPathContext) InstallInDebugRamdisk() bool {
2451 return m.inDebugRamdisk
2452}
2453
Ulya Trafimovichccc8c852020-10-14 11:29:07 +01002454func (m testModuleInstallPathContext) InstallInRecovery() bool {
2455 return m.inRecovery
2456}
2457
2458func (m testModuleInstallPathContext) InstallInRoot() bool {
2459 return m.inRoot
2460}
2461
Colin Crossea30d852023-11-29 16:00:16 -08002462func (m testModuleInstallPathContext) InstallInOdm() bool {
2463 return m.inOdm
2464}
2465
2466func (m testModuleInstallPathContext) InstallInProduct() bool {
2467 return m.inProduct
2468}
2469
2470func (m testModuleInstallPathContext) InstallInVendor() bool {
2471 return m.inVendor
2472}
2473
Spandan Das27ff7672024-11-06 19:23:57 +00002474func (m testModuleInstallPathContext) InstallInSystemDlkm() bool {
2475 return m.inSystemDlkm
2476}
2477
2478func (m testModuleInstallPathContext) InstallInVendorDlkm() bool {
2479 return m.inVendorDlkm
2480}
2481
2482func (m testModuleInstallPathContext) InstallInOdmDlkm() bool {
2483 return m.inOdmDlkm
2484}
2485
Ulya Trafimovichccc8c852020-10-14 11:29:07 +01002486func (m testModuleInstallPathContext) InstallForceOS() (*OsType, *ArchType) {
2487 return m.forceOS, m.forceArch
2488}
2489
2490// Construct a minimal ModuleInstallPathContext for testing. Note that baseModuleContext is
2491// default-initialized, which leaves blueprint.baseModuleContext set to nil, so methods that are
2492// delegated to it will panic.
2493func ModuleInstallPathContextForTesting(config Config) ModuleInstallPathContext {
2494 ctx := &testModuleInstallPathContext{}
2495 ctx.config = config
2496 ctx.os = Android
2497 return ctx
2498}
2499
Colin Cross43f08db2018-11-12 10:13:39 -08002500// Rel performs the same function as filepath.Rel, but reports errors to a PathContext, and reports an error if
2501// targetPath is not inside basePath.
2502func Rel(ctx PathContext, basePath string, targetPath string) string {
2503 rel, isRel := MaybeRel(ctx, basePath, targetPath)
2504 if !isRel {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01002505 ReportPathErrorf(ctx, "path %q is not under path %q", targetPath, basePath)
Colin Cross43f08db2018-11-12 10:13:39 -08002506 return ""
2507 }
2508 return rel
2509}
2510
2511// MaybeRel performs the same function as filepath.Rel, but reports errors to a PathContext, and returns false if
2512// targetPath is not inside basePath.
2513func MaybeRel(ctx PathContext, basePath string, targetPath string) (string, bool) {
Dan Willemsen633c5022019-04-12 11:11:38 -07002514 rel, isRel, err := maybeRelErr(basePath, targetPath)
2515 if err != nil {
2516 reportPathError(ctx, err)
2517 }
2518 return rel, isRel
2519}
2520
2521func maybeRelErr(basePath string, targetPath string) (string, bool, error) {
Colin Cross43f08db2018-11-12 10:13:39 -08002522 // filepath.Rel returns an error if one path is absolute and the other is not, handle that case first.
2523 if filepath.IsAbs(basePath) != filepath.IsAbs(targetPath) {
Dan Willemsen633c5022019-04-12 11:11:38 -07002524 return "", false, nil
Colin Cross43f08db2018-11-12 10:13:39 -08002525 }
2526 rel, err := filepath.Rel(basePath, targetPath)
2527 if err != nil {
Dan Willemsen633c5022019-04-12 11:11:38 -07002528 return "", false, err
Colin Cross43f08db2018-11-12 10:13:39 -08002529 } else if rel == ".." || strings.HasPrefix(rel, "../") || strings.HasPrefix(rel, "/") {
Dan Willemsen633c5022019-04-12 11:11:38 -07002530 return "", false, nil
Colin Cross43f08db2018-11-12 10:13:39 -08002531 }
Dan Willemsen633c5022019-04-12 11:11:38 -07002532 return rel, true, nil
Colin Cross43f08db2018-11-12 10:13:39 -08002533}
Colin Cross988414c2020-01-11 01:11:46 +00002534
2535// Writes a file to the output directory. Attempting to write directly to the output directory
2536// will fail due to the sandbox of the soong_build process.
Chris Parsons1a12d032023-02-06 22:37:41 -05002537// Only writes the file if the file doesn't exist or if it has different contents, to prevent
2538// updating the timestamp if no changes would be made. (This is better for incremental
2539// performance.)
Colin Cross988414c2020-01-11 01:11:46 +00002540func WriteFileToOutputDir(path WritablePath, data []byte, perm os.FileMode) error {
Colin Crossd6421132021-11-09 12:32:34 -08002541 absPath := absolutePath(path.String())
2542 err := os.MkdirAll(filepath.Dir(absPath), 0777)
2543 if err != nil {
2544 return err
2545 }
Chris Parsons1a12d032023-02-06 22:37:41 -05002546 return pathtools.WriteFileIfChanged(absPath, data, perm)
Colin Cross988414c2020-01-11 01:11:46 +00002547}
2548
Liz Kammer2dd9ca42020-11-25 16:06:39 -08002549func RemoveAllOutputDir(path WritablePath) error {
2550 return os.RemoveAll(absolutePath(path.String()))
2551}
2552
2553func CreateOutputDirIfNonexistent(path WritablePath, perm os.FileMode) error {
2554 dir := absolutePath(path.String())
Liz Kammer09f947d2021-05-12 14:51:49 -04002555 return createDirIfNonexistent(dir, perm)
2556}
2557
2558func createDirIfNonexistent(dir string, perm os.FileMode) error {
Liz Kammer2dd9ca42020-11-25 16:06:39 -08002559 if _, err := os.Stat(dir); os.IsNotExist(err) {
2560 return os.MkdirAll(dir, os.ModePerm)
2561 } else {
2562 return err
2563 }
2564}
2565
Jingwen Chen78257e52021-05-21 02:34:24 +00002566// absolutePath is deliberately private so that Soong's Go plugins can't use it to find and
2567// read arbitrary files without going through the methods in the current package that track
2568// dependencies.
Colin Cross988414c2020-01-11 01:11:46 +00002569func absolutePath(path string) string {
2570 if filepath.IsAbs(path) {
2571 return path
2572 }
2573 return filepath.Join(absSrcDir, path)
2574}
Chris Parsons216e10a2020-07-09 17:12:52 -04002575
2576// A DataPath represents the path of a file to be used as data, for example
2577// a test library to be installed alongside a test.
2578// The data file should be installed (copied from `<SrcPath>`) to
2579// `<install_root>/<RelativeInstallPath>/<filename>`, or
2580// `<install_root>/<filename>` if RelativeInstallPath is empty.
2581type DataPath struct {
2582 // The path of the data file that should be copied into the data directory
2583 SrcPath Path
2584 // The install path of the data file, relative to the install root.
2585 RelativeInstallPath string
Colin Cross5c1d5fb2023-11-15 12:39:40 -08002586 // If WithoutRel is true, use SrcPath.Base() instead of SrcPath.Rel() as the filename.
2587 WithoutRel bool
Chris Parsons216e10a2020-07-09 17:12:52 -04002588}
Colin Crossdcf71b22021-02-01 13:59:03 -08002589
Colin Crossd442a0e2023-11-16 11:19:26 -08002590func (d *DataPath) ToRelativeInstallPath() string {
2591 relPath := d.SrcPath.Rel()
Colin Cross5c1d5fb2023-11-15 12:39:40 -08002592 if d.WithoutRel {
2593 relPath = d.SrcPath.Base()
2594 }
Colin Crossd442a0e2023-11-16 11:19:26 -08002595 if d.RelativeInstallPath != "" {
2596 relPath = filepath.Join(d.RelativeInstallPath, relPath)
2597 }
2598 return relPath
2599}
2600
Colin Crossdcf71b22021-02-01 13:59:03 -08002601// PathsIfNonNil returns a Paths containing only the non-nil input arguments.
2602func PathsIfNonNil(paths ...Path) Paths {
2603 if len(paths) == 0 {
2604 // Fast path for empty argument list
2605 return nil
2606 } else if len(paths) == 1 {
2607 // Fast path for a single argument
2608 if paths[0] != nil {
2609 return paths
2610 } else {
2611 return nil
2612 }
2613 }
2614 ret := make(Paths, 0, len(paths))
2615 for _, path := range paths {
2616 if path != nil {
2617 ret = append(ret, path)
2618 }
2619 }
2620 if len(ret) == 0 {
2621 return nil
2622 }
2623 return ret
2624}
Chris Wailesb2703ad2021-07-30 13:25:42 -07002625
2626var thirdPartyDirPrefixExceptions = []*regexp.Regexp{
2627 regexp.MustCompile("^vendor/[^/]*google[^/]*/"),
2628 regexp.MustCompile("^hardware/google/"),
2629 regexp.MustCompile("^hardware/interfaces/"),
2630 regexp.MustCompile("^hardware/libhardware[^/]*/"),
2631 regexp.MustCompile("^hardware/ril/"),
2632}
2633
2634func IsThirdPartyPath(path string) bool {
2635 thirdPartyDirPrefixes := []string{"external/", "vendor/", "hardware/"}
2636
2637 if HasAnyPrefix(path, thirdPartyDirPrefixes) {
2638 for _, prefix := range thirdPartyDirPrefixExceptions {
2639 if prefix.MatchString(path) {
2640 return false
2641 }
2642 }
2643 return true
2644 }
2645 return false
2646}
Jihoon Kangf27c3a52024-11-12 21:27:09 +00002647
2648// ToRelativeSourcePath converts absolute source path to the path relative to the source root.
2649// This throws an error if the input path is outside of the source root and cannot be converted
2650// to the relative path.
2651// This should be rarely used given that the source path is relative in Soong.
2652func ToRelativeSourcePath(ctx PathContext, path string) string {
2653 ret := path
2654 if filepath.IsAbs(path) {
2655 relPath, err := filepath.Rel(absSrcDir, path)
2656 if err != nil || strings.HasPrefix(relPath, "..") {
2657 ReportPathErrorf(ctx, "%s is outside of the source root", path)
2658 }
2659 ret = relPath
2660 }
2661 return ret
2662}