blob: f7fcd35ff9198edbfba8ec52104cfff1a5b2aa8e [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 Liuef9e63e2025-03-04 19:01:28 +0000686 if !OtherModuleProviderOrDefault(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)
1262 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
1317// existsWithDependencies returns true if the path exists, and adds appropriate dependencies to rerun if the
1318// path does not exist.
Colin Cross662d6142022-11-03 20:38:01 -07001319func existsWithDependencies(ctx PathGlobContext, path SourcePath) (exists bool, err error) {
Colin Cross192e97a2018-02-22 14:21:02 -08001320 var files []string
1321
Colin Cross662d6142022-11-03 20:38:01 -07001322 // Use glob to produce proper dependencies, even though we only want
1323 // a single file.
1324 files, err = ctx.GlobWithDeps(path.String(), nil)
Colin Cross192e97a2018-02-22 14:21:02 -08001325
1326 if err != nil {
1327 return false, fmt.Errorf("glob: %s", err.Error())
1328 }
1329
1330 return len(files) > 0, nil
1331}
1332
1333// PathForSource joins the provided path components and validates that the result
1334// neither escapes the source dir nor is in the out dir.
1335// On error, it will return a usable, but invalid SourcePath, and report a ModuleError.
1336func PathForSource(ctx PathContext, pathComponents ...string) SourcePath {
1337 path, err := pathForSource(ctx, pathComponents...)
1338 if err != nil {
1339 reportPathError(ctx, err)
1340 }
1341
Colin Crosse3924e12018-08-15 20:18:53 -07001342 if pathtools.IsGlob(path.String()) {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001343 ReportPathErrorf(ctx, "path may not contain a glob: %s", path.String())
Colin Crosse3924e12018-08-15 20:18:53 -07001344 }
1345
Liz Kammera830f3a2020-11-10 10:50:34 -08001346 if modCtx, ok := ctx.(ModuleMissingDepsPathContext); ok && ctx.Config().AllowMissingDependencies() {
Colin Cross662d6142022-11-03 20:38:01 -07001347 exists, err := existsWithDependencies(modCtx, path)
Colin Cross192e97a2018-02-22 14:21:02 -08001348 if err != nil {
1349 reportPathError(ctx, err)
1350 }
1351 if !exists {
1352 modCtx.AddMissingDependencies([]string{path.String()})
1353 }
Colin Cross988414c2020-01-11 01:11:46 +00001354 } else if exists, _, err := ctx.Config().fs.Exists(path.String()); err != nil {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001355 ReportPathErrorf(ctx, "%s: %s", path, err.Error())
Pedro Loureiro5d190cc2021-02-15 15:41:33 +00001356 } else if !exists && !ctx.Config().TestAllowNonExistentPaths {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001357 ReportPathErrorf(ctx, "source path %q does not exist", path)
Colin Cross192e97a2018-02-22 14:21:02 -08001358 }
1359 return path
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001360}
1361
Cole Faustbc65a3f2023-08-01 16:38:55 +00001362// PathForArbitraryOutput creates a path for the given components. Unlike PathForOutput,
1363// the path is relative to the root of the output folder, not the out/soong folder.
Cole Faustaddc0dd2024-12-16 16:19:17 -08001364func PathForArbitraryOutput(ctx PathContext, pathComponents ...string) WritablePath {
Colin Cross3b1c6842024-07-26 11:52:57 -07001365 path, err := validatePath(pathComponents...)
Cole Faustbc65a3f2023-08-01 16:38:55 +00001366 if err != nil {
1367 reportPathError(ctx, err)
1368 }
Colin Cross3b1c6842024-07-26 11:52:57 -07001369 fullPath := filepath.Join(ctx.Config().OutDir(), path)
1370 path = fullPath[len(fullPath)-len(path):]
1371 return OutputPath{basePath{path, ""}, ctx.Config().OutDir(), fullPath}
Cole Faustbc65a3f2023-08-01 16:38:55 +00001372}
1373
Spandan Dasc6c10fa2022-10-21 21:52:13 +00001374// MaybeExistentPathForSource joins the provided path components and validates that the result
1375// neither escapes the source dir nor is in the out dir.
1376// It does not validate whether the path exists.
1377func MaybeExistentPathForSource(ctx PathContext, pathComponents ...string) SourcePath {
1378 path, err := pathForSource(ctx, pathComponents...)
1379 if err != nil {
1380 reportPathError(ctx, err)
1381 }
1382
1383 if pathtools.IsGlob(path.String()) {
1384 ReportPathErrorf(ctx, "path may not contain a glob: %s", path.String())
1385 }
1386 return path
1387}
1388
Liz Kammer7aa52882021-02-11 09:16:14 -05001389// ExistentPathForSource returns an OptionalPath with the SourcePath, rooted from SrcDir, *not*
1390// rooted from the module's local source directory, if the path exists, or an empty OptionalPath if
1391// it doesn't exist. Dependencies are added so that the ninja file will be regenerated if the state
1392// of the path changes.
Colin Cross662d6142022-11-03 20:38:01 -07001393func ExistentPathForSource(ctx PathGlobContext, pathComponents ...string) OptionalPath {
Colin Cross192e97a2018-02-22 14:21:02 -08001394 path, err := pathForSource(ctx, pathComponents...)
Colin Cross1ccfcc32018-02-22 13:54:26 -08001395 if err != nil {
1396 reportPathError(ctx, err)
Martin Stjernholmc32dd1c2021-09-15 02:39:00 +01001397 // No need to put the error message into the returned path since it has been reported already.
Colin Cross1ccfcc32018-02-22 13:54:26 -08001398 return OptionalPath{}
1399 }
Colin Crossc48c1432018-02-23 07:09:01 +00001400
Colin Crosse3924e12018-08-15 20:18:53 -07001401 if pathtools.IsGlob(path.String()) {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001402 ReportPathErrorf(ctx, "path may not contain a glob: %s", path.String())
Colin Crosse3924e12018-08-15 20:18:53 -07001403 return OptionalPath{}
1404 }
1405
Colin Cross192e97a2018-02-22 14:21:02 -08001406 exists, err := existsWithDependencies(ctx, path)
Colin Crossc48c1432018-02-23 07:09:01 +00001407 if err != nil {
1408 reportPathError(ctx, err)
1409 return OptionalPath{}
1410 }
Colin Cross192e97a2018-02-22 14:21:02 -08001411 if !exists {
Martin Stjernholmc32dd1c2021-09-15 02:39:00 +01001412 return InvalidOptionalPath(path.String() + " does not exist")
Colin Crossc48c1432018-02-23 07:09:01 +00001413 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001414 return OptionalPathForPath(path)
1415}
1416
1417func (p SourcePath) String() string {
Cole Faust483d1f72023-01-09 14:35:27 -08001418 if p.path == "" {
1419 return "."
1420 }
1421 return p.path
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001422}
1423
Colin Cross7707b242024-07-26 12:02:36 -07001424func (p SourcePath) WithoutRel() Path {
1425 p.basePath = p.basePath.withoutRel()
1426 return p
1427}
1428
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001429// Join creates a new SourcePath with paths... joined with the current path. The
1430// provided paths... may not use '..' to escape from the current path.
1431func (p SourcePath) Join(ctx PathContext, paths ...string) SourcePath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001432 path, err := validatePath(paths...)
1433 if err != nil {
1434 reportPathError(ctx, err)
1435 }
Colin Cross0db55682017-12-05 15:36:55 -08001436 return p.withRel(path)
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001437}
1438
Colin Cross2fafa3e2019-03-05 12:39:51 -08001439// join is like Join but does less path validation.
1440func (p SourcePath) join(ctx PathContext, paths ...string) SourcePath {
1441 path, err := validateSafePath(paths...)
1442 if err != nil {
1443 reportPathError(ctx, err)
1444 }
1445 return p.withRel(path)
1446}
1447
Colin Cross70dda7e2019-10-01 22:05:35 -07001448// OutputPath is a Path representing an intermediates file path rooted from the build directory
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001449type OutputPath struct {
1450 basePath
Paul Duffind65c58b2021-03-24 09:22:07 +00001451
Colin Cross3b1c6842024-07-26 11:52:57 -07001452 // The base out directory for this path, either Config.SoongOutDir() or Config.OutDir()
1453 outDir string
Paul Duffind65c58b2021-03-24 09:22:07 +00001454
Colin Crossd63c9a72020-01-29 16:52:50 -08001455 fullPath string
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001456}
1457
Yu Liu467d7c52024-09-18 21:54:44 +00001458type outputPathGob struct {
Yu Liu5246a7e2024-10-09 20:04:52 +00001459 BasePath basePath
Yu Liu467d7c52024-09-18 21:54:44 +00001460 OutDir string
1461 FullPath string
1462}
Yu Liufa297642024-06-11 00:13:02 +00001463
Yu Liu467d7c52024-09-18 21:54:44 +00001464func (p *OutputPath) ToGob() *outputPathGob {
1465 return &outputPathGob{
Yu Liu5246a7e2024-10-09 20:04:52 +00001466 BasePath: p.basePath,
Yu Liu467d7c52024-09-18 21:54:44 +00001467 OutDir: p.outDir,
1468 FullPath: p.fullPath,
1469 }
1470}
1471
1472func (p *OutputPath) FromGob(data *outputPathGob) {
Yu Liu5246a7e2024-10-09 20:04:52 +00001473 p.basePath = data.BasePath
Yu Liu467d7c52024-09-18 21:54:44 +00001474 p.outDir = data.OutDir
1475 p.fullPath = data.FullPath
1476}
1477
1478func (p OutputPath) GobEncode() ([]byte, error) {
Yu Liu3cadf7d2024-10-24 18:47:06 +00001479 return gobtools.CustomGobEncode[outputPathGob](&p)
Yu Liufa297642024-06-11 00:13:02 +00001480}
1481
1482func (p *OutputPath) GobDecode(data []byte) error {
Yu Liu3cadf7d2024-10-24 18:47:06 +00001483 return gobtools.CustomGobDecode[outputPathGob](data, p)
Yu Liufa297642024-06-11 00:13:02 +00001484}
1485
Colin Cross702e0f82017-10-18 17:27:54 -07001486func (p OutputPath) withRel(rel string) OutputPath {
Colin Cross0db55682017-12-05 15:36:55 -08001487 p.basePath = p.basePath.withRel(rel)
Colin Crossd63c9a72020-01-29 16:52:50 -08001488 p.fullPath = filepath.Join(p.fullPath, rel)
Colin Cross702e0f82017-10-18 17:27:54 -07001489 return p
1490}
1491
Colin Cross7707b242024-07-26 12:02:36 -07001492func (p OutputPath) WithoutRel() Path {
1493 p.basePath = p.basePath.withoutRel()
Colin Cross3063b782018-08-15 11:19:12 -07001494 return p
1495}
1496
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02001497func (p OutputPath) getSoongOutDir() string {
Colin Cross3b1c6842024-07-26 11:52:57 -07001498 return p.outDir
Paul Duffin9b478b02019-12-10 13:41:51 +00001499}
1500
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001501func (p OutputPath) RelativeToTop() Path {
1502 return p.outputPathRelativeToTop()
1503}
1504
1505func (p OutputPath) outputPathRelativeToTop() OutputPath {
Colin Cross3b1c6842024-07-26 11:52:57 -07001506 p.fullPath = StringPathRelativeToTop(p.outDir, p.fullPath)
1507 if strings.HasSuffix(p.outDir, testOutSoongSubDir) {
1508 p.outDir = TestOutSoongDir
1509 } else {
1510 // Handle the PathForArbitraryOutput case
1511 p.outDir = testOutDir
1512 }
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001513 return p
1514}
1515
Paul Duffin0267d492021-02-02 10:05:52 +00001516func (p OutputPath) objPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleObjPath {
1517 return PathForModuleObj(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
1518}
1519
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001520var _ Path = OutputPath{}
Paul Duffin9b478b02019-12-10 13:41:51 +00001521var _ WritablePath = OutputPath{}
Paul Duffin0267d492021-02-02 10:05:52 +00001522var _ objPathProvider = OutputPath{}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001523
Chris Parsons8f232a22020-06-23 17:37:05 -04001524// toolDepPath is a Path representing a dependency of the build tool.
1525type toolDepPath struct {
1526 basePath
1527}
1528
Colin Cross7707b242024-07-26 12:02:36 -07001529func (t toolDepPath) WithoutRel() Path {
1530 t.basePath = t.basePath.withoutRel()
1531 return t
1532}
1533
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001534func (t toolDepPath) RelativeToTop() Path {
1535 ensureTestOnly()
1536 return t
1537}
1538
Chris Parsons8f232a22020-06-23 17:37:05 -04001539var _ Path = toolDepPath{}
1540
1541// pathForBuildToolDep returns a toolDepPath representing the given path string.
1542// There is no validation for the path, as it is "trusted": It may fail
1543// normal validation checks. For example, it may be an absolute path.
1544// Only use this function to construct paths for dependencies of the build
1545// tool invocation.
1546func pathForBuildToolDep(ctx PathContext, path string) toolDepPath {
Paul Duffin74abc5d2021-03-24 09:24:59 +00001547 return toolDepPath{basePath{path, ""}}
Chris Parsons8f232a22020-06-23 17:37:05 -04001548}
1549
Jeff Gaston734e3802017-04-10 15:47:24 -07001550// PathForOutput joins the provided paths and returns an OutputPath that is
1551// validated to not escape the build dir.
1552// On error, it will return a usable, but invalid OutputPath, and report a ModuleError.
1553func PathForOutput(ctx PathContext, pathComponents ...string) OutputPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001554 path, err := validatePath(pathComponents...)
1555 if err != nil {
1556 reportPathError(ctx, err)
1557 }
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02001558 fullPath := filepath.Join(ctx.Config().soongOutDir, path)
Colin Crossd63c9a72020-01-29 16:52:50 -08001559 path = fullPath[len(fullPath)-len(path):]
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02001560 return OutputPath{basePath{path, ""}, ctx.Config().soongOutDir, fullPath}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001561}
1562
Colin Cross3b1c6842024-07-26 11:52:57 -07001563// PathsForOutput returns Paths rooted from outDir
Colin Cross40e33732019-02-15 11:08:35 -08001564func PathsForOutput(ctx PathContext, paths []string) WritablePaths {
1565 ret := make(WritablePaths, len(paths))
1566 for i, path := range paths {
1567 ret[i] = PathForOutput(ctx, path)
1568 }
1569 return ret
1570}
1571
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001572func (p OutputPath) writablePath() {}
1573
1574func (p OutputPath) String() string {
Colin Crossd63c9a72020-01-29 16:52:50 -08001575 return p.fullPath
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001576}
1577
1578// Join creates a new OutputPath with paths... joined with the current path. The
1579// provided paths... may not use '..' to escape from the current path.
1580func (p OutputPath) Join(ctx PathContext, paths ...string) OutputPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001581 path, err := validatePath(paths...)
1582 if err != nil {
1583 reportPathError(ctx, err)
1584 }
Colin Cross0db55682017-12-05 15:36:55 -08001585 return p.withRel(path)
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001586}
1587
Colin Cross8854a5a2019-02-11 14:14:16 -08001588// ReplaceExtension creates a new OutputPath with the extension replaced with ext.
1589func (p OutputPath) ReplaceExtension(ctx PathContext, ext string) OutputPath {
1590 if strings.Contains(ext, "/") {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001591 ReportPathErrorf(ctx, "extension %q cannot contain /", ext)
Colin Cross8854a5a2019-02-11 14:14:16 -08001592 }
1593 ret := PathForOutput(ctx, pathtools.ReplaceExtension(p.path, ext))
Colin Cross2cdd5df2019-02-25 10:25:24 -08001594 ret.rel = pathtools.ReplaceExtension(p.rel, ext)
Colin Cross8854a5a2019-02-11 14:14:16 -08001595 return ret
1596}
1597
Colin Cross40e33732019-02-15 11:08:35 -08001598// InSameDir creates a new OutputPath from the directory of the current OutputPath joined with the elements in paths.
1599func (p OutputPath) InSameDir(ctx PathContext, paths ...string) OutputPath {
1600 path, err := validatePath(paths...)
1601 if err != nil {
1602 reportPathError(ctx, err)
1603 }
1604
1605 ret := PathForOutput(ctx, filepath.Dir(p.path), path)
Colin Cross2cdd5df2019-02-25 10:25:24 -08001606 ret.rel = filepath.Join(filepath.Dir(p.rel), path)
Colin Cross40e33732019-02-15 11:08:35 -08001607 return ret
1608}
1609
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001610// PathForIntermediates returns an OutputPath representing the top-level
1611// intermediates directory.
1612func PathForIntermediates(ctx PathContext, paths ...string) OutputPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001613 path, err := validatePath(paths...)
1614 if err != nil {
1615 reportPathError(ctx, err)
1616 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001617 return PathForOutput(ctx, ".intermediates", path)
1618}
1619
Colin Cross07e51612019-03-05 12:46:40 -08001620var _ genPathProvider = SourcePath{}
1621var _ objPathProvider = SourcePath{}
1622var _ resPathProvider = SourcePath{}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001623
Colin Cross07e51612019-03-05 12:46:40 -08001624// PathForModuleSrc returns a Path representing the paths... under the
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001625// module's local source directory.
Liz Kammera830f3a2020-11-10 10:50:34 -08001626func PathForModuleSrc(ctx ModuleMissingDepsPathContext, pathComponents ...string) Path {
Paul Duffin407501b2021-07-09 16:56:35 +01001627 // Just join the components textually just to make sure that it does not corrupt a fully qualified
1628 // module reference, e.g. if the pathComponents is "://other:foo" then using filepath.Join() or
1629 // validatePath() will corrupt it, e.g. replace "//" with "/". If the path is not a module
1630 // reference then it will be validated by expandOneSrcPath anyway when it calls expandOneSrcPath.
1631 p := strings.Join(pathComponents, string(filepath.Separator))
Liz Kammer619be462022-01-28 15:13:39 -05001632 paths, err := expandOneSrcPath(sourcePathInput{context: ctx, path: p, includeDirs: true})
Colin Cross8a497952019-03-05 22:25:09 -08001633 if err != nil {
1634 if depErr, ok := err.(missingDependencyError); ok {
1635 if ctx.Config().AllowMissingDependencies() {
1636 ctx.AddMissingDependencies(depErr.missingDeps)
1637 } else {
1638 ctx.ModuleErrorf(`%s, is the property annotated with android:"path"?`, depErr.Error())
1639 }
1640 } else {
1641 reportPathError(ctx, err)
1642 }
1643 return nil
1644 } else if len(paths) == 0 {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001645 ReportPathErrorf(ctx, "%q produced no files, expected exactly one", p)
Colin Cross8a497952019-03-05 22:25:09 -08001646 return nil
1647 } else if len(paths) > 1 {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001648 ReportPathErrorf(ctx, "%q produced %d files, expected exactly one", p, len(paths))
Colin Cross8a497952019-03-05 22:25:09 -08001649 }
1650 return paths[0]
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001651}
1652
Liz Kammera830f3a2020-11-10 10:50:34 -08001653func pathForModuleSrc(ctx EarlyModulePathContext, paths ...string) SourcePath {
Colin Cross07e51612019-03-05 12:46:40 -08001654 p, err := validatePath(paths...)
1655 if err != nil {
1656 reportPathError(ctx, err)
1657 }
1658
1659 path, err := pathForSource(ctx, ctx.ModuleDir(), p)
1660 if err != nil {
1661 reportPathError(ctx, err)
1662 }
1663
1664 path.basePath.rel = p
1665
1666 return path
1667}
1668
Colin Cross2fafa3e2019-03-05 12:39:51 -08001669// PathsWithModuleSrcSubDir takes a list of Paths and returns a new list of Paths where Rel() on each path
1670// will return the path relative to subDir in the module's source directory. If any input paths are not located
1671// inside subDir then a path error will be reported.
Liz Kammera830f3a2020-11-10 10:50:34 -08001672func PathsWithModuleSrcSubDir(ctx EarlyModulePathContext, paths Paths, subDir string) Paths {
Colin Cross2fafa3e2019-03-05 12:39:51 -08001673 paths = append(Paths(nil), paths...)
Colin Cross07e51612019-03-05 12:46:40 -08001674 subDirFullPath := pathForModuleSrc(ctx, subDir)
Colin Cross2fafa3e2019-03-05 12:39:51 -08001675 for i, path := range paths {
1676 rel := Rel(ctx, subDirFullPath.String(), path.String())
1677 paths[i] = subDirFullPath.join(ctx, rel)
1678 }
1679 return paths
1680}
1681
1682// PathWithModuleSrcSubDir takes a Path and returns a Path where Rel() will return the path relative to subDir in the
1683// 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 -08001684func PathWithModuleSrcSubDir(ctx EarlyModulePathContext, path Path, subDir string) Path {
Colin Cross07e51612019-03-05 12:46:40 -08001685 subDirFullPath := pathForModuleSrc(ctx, subDir)
Colin Cross2fafa3e2019-03-05 12:39:51 -08001686 rel := Rel(ctx, subDirFullPath.String(), path.String())
1687 return subDirFullPath.Join(ctx, rel)
1688}
1689
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001690// OptionalPathForModuleSrc returns an OptionalPath. The OptionalPath contains a
1691// valid path if p is non-nil.
Liz Kammera830f3a2020-11-10 10:50:34 -08001692func OptionalPathForModuleSrc(ctx ModuleMissingDepsPathContext, p *string) OptionalPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001693 if p == nil {
1694 return OptionalPath{}
1695 }
1696 return OptionalPathForPath(PathForModuleSrc(ctx, *p))
1697}
1698
Liz Kammera830f3a2020-11-10 10:50:34 -08001699func (p SourcePath) genPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleGenPath {
Colin Cross7fc17db2017-02-01 14:07:55 -08001700 return PathForModuleGen(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001701}
1702
yangbill6d032dd2024-04-18 03:05:49 +00001703func (p SourcePath) genPathWithExtAndTrimExt(ctx ModuleOutPathContext, subdir, ext string, trimExt string) ModuleGenPath {
1704 // If Trim_extension being set, force append Output_extension without replace original extension.
1705 if trimExt != "" {
1706 if ext != "" {
1707 return PathForModuleGen(ctx, subdir, strings.TrimSuffix(p.path, trimExt)+"."+ext)
1708 }
1709 return PathForModuleGen(ctx, subdir, strings.TrimSuffix(p.path, trimExt))
1710 }
1711 return PathForModuleGen(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
1712}
1713
Liz Kammera830f3a2020-11-10 10:50:34 -08001714func (p SourcePath) objPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleObjPath {
Colin Cross7fc17db2017-02-01 14:07:55 -08001715 return PathForModuleObj(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001716}
1717
Liz Kammera830f3a2020-11-10 10:50:34 -08001718func (p SourcePath) resPathWithName(ctx ModuleOutPathContext, name string) ModuleResPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001719 // TODO: Use full directory if the new ctx is not the current ctx?
1720 return PathForModuleRes(ctx, p.path, name)
1721}
1722
1723// ModuleOutPath is a Path representing a module's output directory.
1724type ModuleOutPath struct {
1725 OutputPath
1726}
1727
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001728func (p ModuleOutPath) RelativeToTop() Path {
1729 p.OutputPath = p.outputPathRelativeToTop()
1730 return p
1731}
1732
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001733var _ Path = ModuleOutPath{}
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001734var _ WritablePath = ModuleOutPath{}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001735
Liz Kammera830f3a2020-11-10 10:50:34 -08001736func (p ModuleOutPath) objPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleObjPath {
Pete Bentleyfcf55bf2019-08-16 20:14:32 +01001737 return PathForModuleObj(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
1738}
1739
Liz Kammera830f3a2020-11-10 10:50:34 -08001740// ModuleOutPathContext Subset of ModuleContext functions necessary for output path methods.
1741type ModuleOutPathContext interface {
1742 PathContext
1743
1744 ModuleName() string
1745 ModuleDir() string
1746 ModuleSubDir() string
1747}
1748
1749func pathForModuleOut(ctx ModuleOutPathContext) OutputPath {
Inseob Kimb7e9f5f2024-06-25 17:39:52 +09001750 return PathForOutput(ctx, ".intermediates", ctx.ModuleDir(), ctx.ModuleName(), ctx.ModuleSubDir())
Colin Cross702e0f82017-10-18 17:27:54 -07001751}
1752
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001753// PathForModuleOut returns a Path representing the paths... under the module's
1754// output directory.
Liz Kammera830f3a2020-11-10 10:50:34 -08001755func PathForModuleOut(ctx ModuleOutPathContext, paths ...string) ModuleOutPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001756 p, err := validatePath(paths...)
1757 if err != nil {
1758 reportPathError(ctx, err)
1759 }
Colin Cross702e0f82017-10-18 17:27:54 -07001760 return ModuleOutPath{
Liz Kammera830f3a2020-11-10 10:50:34 -08001761 OutputPath: pathForModuleOut(ctx).withRel(p),
Colin Cross702e0f82017-10-18 17:27:54 -07001762 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001763}
1764
1765// ModuleGenPath is a Path representing the 'gen' directory in a module's output
1766// directory. Mainly used for generated sources.
1767type ModuleGenPath struct {
1768 ModuleOutPath
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001769}
1770
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001771func (p ModuleGenPath) RelativeToTop() Path {
1772 p.OutputPath = p.outputPathRelativeToTop()
1773 return p
1774}
1775
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001776var _ Path = ModuleGenPath{}
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001777var _ WritablePath = ModuleGenPath{}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001778var _ genPathProvider = ModuleGenPath{}
1779var _ objPathProvider = ModuleGenPath{}
1780
1781// PathForModuleGen returns a Path representing the paths... under the module's
1782// `gen' directory.
Liz Kammera830f3a2020-11-10 10:50:34 -08001783func PathForModuleGen(ctx ModuleOutPathContext, paths ...string) ModuleGenPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001784 p, err := validatePath(paths...)
1785 if err != nil {
1786 reportPathError(ctx, err)
1787 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001788 return ModuleGenPath{
Colin Cross702e0f82017-10-18 17:27:54 -07001789 ModuleOutPath: ModuleOutPath{
Liz Kammera830f3a2020-11-10 10:50:34 -08001790 OutputPath: pathForModuleOut(ctx).withRel("gen").withRel(p),
Colin Cross702e0f82017-10-18 17:27:54 -07001791 },
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001792 }
1793}
1794
Liz Kammera830f3a2020-11-10 10:50:34 -08001795func (p ModuleGenPath) genPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleGenPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001796 // TODO: make a different path for local vs remote generated files?
Dan Willemsen21ec4902016-11-02 20:43:13 -07001797 return PathForModuleGen(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001798}
1799
yangbill6d032dd2024-04-18 03:05:49 +00001800func (p ModuleGenPath) genPathWithExtAndTrimExt(ctx ModuleOutPathContext, subdir, ext string, trimExt string) ModuleGenPath {
1801 // If Trim_extension being set, force append Output_extension without replace original extension.
1802 if trimExt != "" {
1803 if ext != "" {
1804 return PathForModuleGen(ctx, subdir, strings.TrimSuffix(p.path, trimExt)+"."+ext)
1805 }
1806 return PathForModuleGen(ctx, subdir, strings.TrimSuffix(p.path, trimExt))
1807 }
1808 return PathForModuleGen(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
1809}
1810
Liz Kammera830f3a2020-11-10 10:50:34 -08001811func (p ModuleGenPath) objPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleObjPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001812 return PathForModuleObj(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
1813}
1814
1815// ModuleObjPath is a Path representing the 'obj' directory in a module's output
1816// directory. Used for compiled objects.
1817type ModuleObjPath struct {
1818 ModuleOutPath
1819}
1820
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001821func (p ModuleObjPath) RelativeToTop() Path {
1822 p.OutputPath = p.outputPathRelativeToTop()
1823 return p
1824}
1825
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001826var _ Path = ModuleObjPath{}
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001827var _ WritablePath = ModuleObjPath{}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001828
1829// PathForModuleObj returns a Path representing the paths... under the module's
1830// 'obj' directory.
Liz Kammera830f3a2020-11-10 10:50:34 -08001831func PathForModuleObj(ctx ModuleOutPathContext, pathComponents ...string) ModuleObjPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001832 p, err := validatePath(pathComponents...)
1833 if err != nil {
1834 reportPathError(ctx, err)
1835 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001836 return ModuleObjPath{PathForModuleOut(ctx, "obj", p)}
1837}
1838
1839// ModuleResPath is a a Path representing the 'res' directory in a module's
1840// output directory.
1841type ModuleResPath struct {
1842 ModuleOutPath
1843}
1844
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001845func (p ModuleResPath) RelativeToTop() Path {
1846 p.OutputPath = p.outputPathRelativeToTop()
1847 return p
1848}
1849
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001850var _ Path = ModuleResPath{}
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001851var _ WritablePath = ModuleResPath{}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001852
1853// PathForModuleRes returns a Path representing the paths... under the module's
1854// 'res' directory.
Liz Kammera830f3a2020-11-10 10:50:34 -08001855func PathForModuleRes(ctx ModuleOutPathContext, pathComponents ...string) ModuleResPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001856 p, err := validatePath(pathComponents...)
1857 if err != nil {
1858 reportPathError(ctx, err)
1859 }
1860
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001861 return ModuleResPath{PathForModuleOut(ctx, "res", p)}
1862}
1863
Colin Cross70dda7e2019-10-01 22:05:35 -07001864// InstallPath is a Path representing a installed file path rooted from the build directory
1865type InstallPath struct {
1866 basePath
Colin Crossff6c33d2019-10-02 16:01:35 -07001867
Lukacs T. Berkib078ade2021-08-31 10:42:08 +02001868 // The soong build directory, i.e. Config.SoongOutDir()
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02001869 soongOutDir string
Paul Duffind65c58b2021-03-24 09:22:07 +00001870
Jiyong Park957bcd92020-10-20 18:23:33 +09001871 // partitionDir is the part of the InstallPath that is automatically determined according to the context.
1872 // For example, it is host/<os>-<arch> for host modules, and target/product/<device>/<partition> for device modules.
1873 partitionDir string
1874
Colin Crossb1692a32021-10-25 15:39:01 -07001875 partition string
1876
Jiyong Park957bcd92020-10-20 18:23:33 +09001877 // makePath indicates whether this path is for Soong (false) or Make (true).
1878 makePath bool
Colin Crossc0e42d52024-02-01 16:42:36 -08001879
1880 fullPath string
Colin Cross70dda7e2019-10-01 22:05:35 -07001881}
1882
Yu Liu467d7c52024-09-18 21:54:44 +00001883type installPathGob struct {
Yu Liu5246a7e2024-10-09 20:04:52 +00001884 BasePath basePath
Yu Liu467d7c52024-09-18 21:54:44 +00001885 SoongOutDir string
1886 PartitionDir string
1887 Partition string
1888 MakePath bool
1889 FullPath string
1890}
Yu Liu26a716d2024-08-30 23:40:32 +00001891
Yu Liu467d7c52024-09-18 21:54:44 +00001892func (p *InstallPath) ToGob() *installPathGob {
1893 return &installPathGob{
Yu Liu5246a7e2024-10-09 20:04:52 +00001894 BasePath: p.basePath,
Yu Liu467d7c52024-09-18 21:54:44 +00001895 SoongOutDir: p.soongOutDir,
1896 PartitionDir: p.partitionDir,
1897 Partition: p.partition,
1898 MakePath: p.makePath,
1899 FullPath: p.fullPath,
1900 }
1901}
1902
1903func (p *InstallPath) FromGob(data *installPathGob) {
Yu Liu5246a7e2024-10-09 20:04:52 +00001904 p.basePath = data.BasePath
Yu Liu467d7c52024-09-18 21:54:44 +00001905 p.soongOutDir = data.SoongOutDir
1906 p.partitionDir = data.PartitionDir
1907 p.partition = data.Partition
1908 p.makePath = data.MakePath
1909 p.fullPath = data.FullPath
1910}
1911
1912func (p InstallPath) GobEncode() ([]byte, error) {
Yu Liu3cadf7d2024-10-24 18:47:06 +00001913 return gobtools.CustomGobEncode[installPathGob](&p)
Yu Liu26a716d2024-08-30 23:40:32 +00001914}
1915
1916func (p *InstallPath) GobDecode(data []byte) error {
Yu Liu3cadf7d2024-10-24 18:47:06 +00001917 return gobtools.CustomGobDecode[installPathGob](data, p)
Yu Liu26a716d2024-08-30 23:40:32 +00001918}
1919
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001920// Will panic if called from outside a test environment.
1921func ensureTestOnly() {
Martin Stjernholm32312eb2021-03-27 18:54:49 +00001922 if PrefixInList(os.Args, "-test.") {
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001923 return
1924 }
Martin Stjernholm32312eb2021-03-27 18:54:49 +00001925 panic(fmt.Errorf("Not in test. Command line:\n %s", strings.Join(os.Args, "\n ")))
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001926}
1927
1928func (p InstallPath) RelativeToTop() Path {
1929 ensureTestOnly()
Colin Crossc0e42d52024-02-01 16:42:36 -08001930 if p.makePath {
Colin Cross3b1c6842024-07-26 11:52:57 -07001931 p.soongOutDir = testOutDir
Colin Crossc0e42d52024-02-01 16:42:36 -08001932 } else {
Colin Cross3b1c6842024-07-26 11:52:57 -07001933 p.soongOutDir = TestOutSoongDir
Colin Crossc0e42d52024-02-01 16:42:36 -08001934 }
1935 p.fullPath = filepath.Join(p.soongOutDir, p.path)
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001936 return p
1937}
1938
Colin Cross7707b242024-07-26 12:02:36 -07001939func (p InstallPath) WithoutRel() Path {
1940 p.basePath = p.basePath.withoutRel()
1941 return p
1942}
1943
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02001944func (p InstallPath) getSoongOutDir() string {
1945 return p.soongOutDir
Paul Duffin9b478b02019-12-10 13:41:51 +00001946}
1947
Hans MÃ¥nssond3f2bd72020-11-27 12:37:28 +01001948func (p InstallPath) ReplaceExtension(ctx PathContext, ext string) OutputPath {
1949 panic("Not implemented")
1950}
1951
Paul Duffin9b478b02019-12-10 13:41:51 +00001952var _ Path = InstallPath{}
1953var _ WritablePath = InstallPath{}
1954
Colin Cross70dda7e2019-10-01 22:05:35 -07001955func (p InstallPath) writablePath() {}
1956
1957func (p InstallPath) String() string {
Colin Crossc0e42d52024-02-01 16:42:36 -08001958 return p.fullPath
Jiyong Park957bcd92020-10-20 18:23:33 +09001959}
1960
1961// PartitionDir returns the path to the partition where the install path is rooted at. It is
1962// out/soong/target/product/<device>/<partition> for device modules, and out/soong/host/<os>-<arch> for host modules.
1963// The ./soong is dropped if the install path is for Make.
1964func (p InstallPath) PartitionDir() string {
1965 if p.makePath {
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02001966 return filepath.Join(p.soongOutDir, "../", p.partitionDir)
Jiyong Park957bcd92020-10-20 18:23:33 +09001967 } else {
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02001968 return filepath.Join(p.soongOutDir, p.partitionDir)
Jiyong Park957bcd92020-10-20 18:23:33 +09001969 }
Colin Cross70dda7e2019-10-01 22:05:35 -07001970}
1971
Jihoon Kangf78a8902022-09-01 22:47:07 +00001972func (p InstallPath) Partition() string {
1973 return p.partition
1974}
1975
Colin Cross70dda7e2019-10-01 22:05:35 -07001976// Join creates a new InstallPath with paths... joined with the current path. The
1977// provided paths... may not use '..' to escape from the current path.
1978func (p InstallPath) Join(ctx PathContext, paths ...string) InstallPath {
1979 path, err := validatePath(paths...)
1980 if err != nil {
1981 reportPathError(ctx, err)
1982 }
1983 return p.withRel(path)
1984}
1985
1986func (p InstallPath) withRel(rel string) InstallPath {
1987 p.basePath = p.basePath.withRel(rel)
Colin Crossc0e42d52024-02-01 16:42:36 -08001988 p.fullPath = filepath.Join(p.fullPath, rel)
Colin Cross70dda7e2019-10-01 22:05:35 -07001989 return p
1990}
1991
Colin Crossc68db4b2021-11-11 18:59:15 -08001992// Deprecated: ToMakePath is a noop, PathForModuleInstall always returns Make paths when building
1993// embedded in Make.
Colin Crossff6c33d2019-10-02 16:01:35 -07001994func (p InstallPath) ToMakePath() InstallPath {
Jiyong Park957bcd92020-10-20 18:23:33 +09001995 p.makePath = true
Colin Crossff6c33d2019-10-02 16:01:35 -07001996 return p
Colin Cross70dda7e2019-10-01 22:05:35 -07001997}
1998
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001999// PathForModuleInstall returns a Path representing the install path for the
2000// module appended with paths...
Colin Cross70dda7e2019-10-01 22:05:35 -07002001func PathForModuleInstall(ctx ModuleInstallPathContext, pathComponents ...string) InstallPath {
Spandan Das5d1b9292021-06-03 19:36:41 +00002002 os, arch := osAndArch(ctx)
Cole Faust11edf552023-10-13 11:32:14 -07002003 partition := modulePartition(ctx, os.Class == Device)
Cole Faust3b703f32023-10-16 13:30:51 -07002004 return pathForInstall(ctx, os, arch, partition, pathComponents...)
Spandan Das5d1b9292021-06-03 19:36:41 +00002005}
2006
Colin Cross1d0eb7a2021-11-03 14:08:20 -07002007// PathForHostDexInstall returns an InstallPath representing the install path for the
2008// module appended with paths...
2009func PathForHostDexInstall(ctx ModuleInstallPathContext, pathComponents ...string) InstallPath {
Cole Faust3b703f32023-10-16 13:30:51 -07002010 return pathForInstall(ctx, ctx.Config().BuildOS, ctx.Config().BuildArch, "", pathComponents...)
Colin Cross1d0eb7a2021-11-03 14:08:20 -07002011}
2012
Spandan Das5d1b9292021-06-03 19:36:41 +00002013// PathForModuleInPartitionInstall is similar to PathForModuleInstall but partition is provided by the caller
2014func PathForModuleInPartitionInstall(ctx ModuleInstallPathContext, partition string, pathComponents ...string) InstallPath {
2015 os, arch := osAndArch(ctx)
Cole Faust3b703f32023-10-16 13:30:51 -07002016 return pathForInstall(ctx, os, arch, partition, pathComponents...)
Spandan Das5d1b9292021-06-03 19:36:41 +00002017}
2018
2019func osAndArch(ctx ModuleInstallPathContext) (OsType, ArchType) {
Colin Cross6e359402020-02-10 15:29:54 -08002020 os := ctx.Os()
Jiyong Park87788b52020-09-01 12:37:45 +09002021 arch := ctx.Arch().ArchType
2022 forceOS, forceArch := ctx.InstallForceOS()
2023 if forceOS != nil {
Colin Cross6e359402020-02-10 15:29:54 -08002024 os = *forceOS
2025 }
Jiyong Park87788b52020-09-01 12:37:45 +09002026 if forceArch != nil {
2027 arch = *forceArch
2028 }
Spandan Das5d1b9292021-06-03 19:36:41 +00002029 return os, arch
2030}
Colin Cross609c49a2020-02-13 13:20:11 -08002031
Colin Crossc0e42d52024-02-01 16:42:36 -08002032func pathForPartitionInstallDir(ctx PathContext, partition, partitionPath string, makePath bool) InstallPath {
2033 fullPath := ctx.Config().SoongOutDir()
2034 if makePath {
2035 // Make path starts with out/ instead of out/soong.
2036 fullPath = filepath.Join(fullPath, "../", partitionPath)
2037 } else {
2038 fullPath = filepath.Join(fullPath, partitionPath)
2039 }
2040
2041 return InstallPath{
2042 basePath: basePath{partitionPath, ""},
2043 soongOutDir: ctx.Config().soongOutDir,
2044 partitionDir: partitionPath,
2045 partition: partition,
2046 makePath: makePath,
2047 fullPath: fullPath,
2048 }
2049}
2050
Cole Faust3b703f32023-10-16 13:30:51 -07002051func pathForInstall(ctx PathContext, os OsType, arch ArchType, partition string,
Colin Cross609c49a2020-02-13 13:20:11 -08002052 pathComponents ...string) InstallPath {
2053
Jiyong Park97859152023-02-14 17:05:48 +09002054 var partitionPaths []string
Colin Cross609c49a2020-02-13 13:20:11 -08002055
Colin Cross6e359402020-02-10 15:29:54 -08002056 if os.Class == Device {
Jiyong Park97859152023-02-14 17:05:48 +09002057 partitionPaths = []string{"target", "product", ctx.Config().DeviceName(), partition}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07002058 } else {
Jiyong Park87788b52020-09-01 12:37:45 +09002059 osName := os.String()
Colin Crossa9b2aac2022-06-15 17:25:51 -07002060 if os == Linux {
Jiyong Park87788b52020-09-01 12:37:45 +09002061 // instead of linux_glibc
2062 osName = "linux"
Dan Willemsen866b5632017-09-22 12:28:24 -07002063 }
Colin Crossa9b2aac2022-06-15 17:25:51 -07002064 if os == LinuxMusl && ctx.Config().UseHostMusl() {
2065 // When using musl instead of glibc, use "linux" instead of "linux_musl". When cross
2066 // compiling we will still use "linux_musl".
2067 osName = "linux"
2068 }
2069
Jiyong Park87788b52020-09-01 12:37:45 +09002070 // SOONG_HOST_OUT is set to out/host/$(HOST_OS)-$(HOST_PREBUILT_ARCH)
2071 // and HOST_PREBUILT_ARCH is forcibly set to x86 even on x86_64 hosts. We don't seem
2072 // to have a plan to fix it (see the comment in build/make/core/envsetup.mk).
2073 // Let's keep using x86 for the existing cases until we have a need to support
2074 // other architectures.
2075 archName := arch.String()
2076 if os.Class == Host && (arch == X86_64 || arch == Common) {
2077 archName = "x86"
2078 }
Jiyong Park97859152023-02-14 17:05:48 +09002079 partitionPaths = []string{"host", osName + "-" + archName, partition}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07002080 }
Colin Cross70dda7e2019-10-01 22:05:35 -07002081
Jiyong Park97859152023-02-14 17:05:48 +09002082 partitionPath, err := validatePath(partitionPaths...)
Colin Cross70dda7e2019-10-01 22:05:35 -07002083 if err != nil {
2084 reportPathError(ctx, err)
2085 }
Colin Crossff6c33d2019-10-02 16:01:35 -07002086
Cole Faust6b7075f2024-12-17 10:42:42 -08002087 base := pathForPartitionInstallDir(ctx, partition, partitionPath, true)
Jiyong Park957bcd92020-10-20 18:23:33 +09002088 return base.Join(ctx, pathComponents...)
Dan Willemsen34cc69e2015-09-23 15:26:20 -07002089}
2090
Spandan Dasf280b232024-04-04 21:25:51 +00002091func PathForNdkInstall(ctx PathContext, paths ...string) OutputPath {
2092 return PathForOutput(ctx, append([]string{"ndk"}, paths...)...)
Nicolas Geoffray1228e9c2020-02-27 13:45:35 +00002093}
2094
2095func PathForMainlineSdksInstall(ctx PathContext, paths ...string) InstallPath {
Spandan Dasf280b232024-04-04 21:25:51 +00002096 base := pathForPartitionInstallDir(ctx, "", "mainline-sdks", false)
2097 return base.Join(ctx, paths...)
Nicolas Geoffray1228e9c2020-02-27 13:45:35 +00002098}
2099
Weijia Heaa37c162024-11-06 19:46:03 +00002100func PathForSuiteInstall(ctx PathContext, suite string, pathComponents ...string) InstallPath {
2101 return pathForPartitionInstallDir(ctx, "test_suites", "test_suites", false).Join(ctx, suite).Join(ctx, pathComponents...)
2102}
2103
Colin Cross70dda7e2019-10-01 22:05:35 -07002104func InstallPathToOnDevicePath(ctx PathContext, path InstallPath) string {
Colin Crossb1692a32021-10-25 15:39:01 -07002105 rel := Rel(ctx, strings.TrimSuffix(path.PartitionDir(), path.partition), path.String())
Colin Cross43f08db2018-11-12 10:13:39 -08002106 return "/" + rel
2107}
2108
Cole Faust11edf552023-10-13 11:32:14 -07002109func modulePartition(ctx ModuleInstallPathContext, device bool) string {
Colin Cross43f08db2018-11-12 10:13:39 -08002110 var partition string
Colin Cross6e359402020-02-10 15:29:54 -08002111 if ctx.InstallInTestcases() {
2112 // "testcases" install directory can be used for host or device modules.
Jaewoong Jung0949f312019-09-11 10:25:18 -07002113 partition = "testcases"
Cole Faust11edf552023-10-13 11:32:14 -07002114 } else if device {
Colin Cross6e359402020-02-10 15:29:54 -08002115 if ctx.InstallInData() {
2116 partition = "data"
2117 } else if ctx.InstallInRamdisk() {
2118 if ctx.DeviceConfig().BoardUsesRecoveryAsBoot() {
2119 partition = "recovery/root/first_stage_ramdisk"
2120 } else {
2121 partition = "ramdisk"
2122 }
2123 if !ctx.InstallInRoot() {
2124 partition += "/system"
2125 }
Yifan Hong60e0cfb2020-10-21 15:17:56 -07002126 } else if ctx.InstallInVendorRamdisk() {
Yifan Hong39143a92020-10-26 12:43:12 -07002127 // The module is only available after switching root into
2128 // /first_stage_ramdisk. To expose the module before switching root
2129 // on a device without a dedicated recovery partition, install the
2130 // recovery variant.
Yifan Hongdd8dacc2020-10-21 15:40:17 -07002131 if ctx.DeviceConfig().BoardMoveRecoveryResourcesToVendorBoot() {
Petri Gyntherac229562021-03-02 23:44:02 -08002132 partition = "vendor_ramdisk/first_stage_ramdisk"
Yifan Hongdd8dacc2020-10-21 15:40:17 -07002133 } else {
Petri Gyntherac229562021-03-02 23:44:02 -08002134 partition = "vendor_ramdisk"
Yifan Hongdd8dacc2020-10-21 15:40:17 -07002135 }
2136 if !ctx.InstallInRoot() {
2137 partition += "/system"
2138 }
Inseob Kim08758f02021-04-08 21:13:22 +09002139 } else if ctx.InstallInDebugRamdisk() {
2140 partition = "debug_ramdisk"
Colin Cross6e359402020-02-10 15:29:54 -08002141 } else if ctx.InstallInRecovery() {
2142 if ctx.InstallInRoot() {
2143 partition = "recovery/root"
2144 } else {
2145 // the layout of recovery partion is the same as that of system partition
2146 partition = "recovery/root/system"
2147 }
Colin Crossea30d852023-11-29 16:00:16 -08002148 } else if ctx.SocSpecific() || ctx.InstallInVendor() {
Colin Cross6e359402020-02-10 15:29:54 -08002149 partition = ctx.DeviceConfig().VendorPath()
Colin Crossea30d852023-11-29 16:00:16 -08002150 } else if ctx.DeviceSpecific() || ctx.InstallInOdm() {
Colin Cross6e359402020-02-10 15:29:54 -08002151 partition = ctx.DeviceConfig().OdmPath()
Colin Crossea30d852023-11-29 16:00:16 -08002152 } else if ctx.ProductSpecific() || ctx.InstallInProduct() {
Colin Cross6e359402020-02-10 15:29:54 -08002153 partition = ctx.DeviceConfig().ProductPath()
2154 } else if ctx.SystemExtSpecific() {
2155 partition = ctx.DeviceConfig().SystemExtPath()
2156 } else if ctx.InstallInRoot() {
2157 partition = "root"
Spandan Das27ff7672024-11-06 19:23:57 +00002158 } else if ctx.InstallInSystemDlkm() {
2159 partition = ctx.DeviceConfig().SystemDlkmPath()
2160 } else if ctx.InstallInVendorDlkm() {
2161 partition = ctx.DeviceConfig().VendorDlkmPath()
2162 } else if ctx.InstallInOdmDlkm() {
2163 partition = ctx.DeviceConfig().OdmDlkmPath()
Yifan Hong82db7352020-01-21 16:12:26 -08002164 } else {
Colin Cross6e359402020-02-10 15:29:54 -08002165 partition = "system"
Yifan Hong82db7352020-01-21 16:12:26 -08002166 }
Colin Cross6e359402020-02-10 15:29:54 -08002167 if ctx.InstallInSanitizerDir() {
2168 partition = "data/asan/" + partition
Yifan Hong82db7352020-01-21 16:12:26 -08002169 }
Colin Cross43f08db2018-11-12 10:13:39 -08002170 }
2171 return partition
2172}
2173
Colin Cross609c49a2020-02-13 13:20:11 -08002174type InstallPaths []InstallPath
2175
2176// Paths returns the InstallPaths as a Paths
2177func (p InstallPaths) Paths() Paths {
2178 if p == nil {
2179 return nil
2180 }
2181 ret := make(Paths, len(p))
2182 for i, path := range p {
2183 ret[i] = path
2184 }
2185 return ret
2186}
2187
2188// Strings returns the string forms of the install paths.
2189func (p InstallPaths) Strings() []string {
2190 if p == nil {
2191 return nil
2192 }
2193 ret := make([]string, len(p))
2194 for i, path := range p {
2195 ret[i] = path.String()
2196 }
2197 return ret
2198}
2199
Jingwen Chen24d0c562023-02-07 09:29:36 +00002200// validatePathInternal ensures that a path does not leave its component, and
2201// optionally doesn't contain Ninja variables.
2202func validatePathInternal(allowNinjaVariables bool, pathComponents ...string) (string, error) {
Colin Crossbf9ed3f2023-10-24 14:17:03 -07002203 initialEmpty := 0
2204 finalEmpty := 0
2205 for i, path := range pathComponents {
Jingwen Chen24d0c562023-02-07 09:29:36 +00002206 if !allowNinjaVariables && strings.Contains(path, "$") {
2207 return "", fmt.Errorf("Path contains invalid character($): %s", path)
2208 }
2209
Dan Willemsen80a7c2a2015-12-21 14:57:11 -08002210 path := filepath.Clean(path)
2211 if path == ".." || strings.HasPrefix(path, "../") || strings.HasPrefix(path, "/") {
Colin Cross1ccfcc32018-02-22 13:54:26 -08002212 return "", fmt.Errorf("Path is outside directory: %s", path)
Dan Willemsen80a7c2a2015-12-21 14:57:11 -08002213 }
Colin Crossbf9ed3f2023-10-24 14:17:03 -07002214
2215 if i == initialEmpty && pathComponents[i] == "" {
2216 initialEmpty++
2217 }
2218 if i == finalEmpty && pathComponents[len(pathComponents)-1-i] == "" {
2219 finalEmpty++
2220 }
Dan Willemsen80a7c2a2015-12-21 14:57:11 -08002221 }
Colin Crossbf9ed3f2023-10-24 14:17:03 -07002222 // Optimization: filepath.Join("foo", "") returns a newly allocated copy
2223 // of "foo", while filepath.Join("foo") does not. Strip out any empty
2224 // path components.
2225 if initialEmpty == len(pathComponents) {
2226 return "", nil
2227 }
2228 nonEmptyPathComponents := pathComponents[initialEmpty : len(pathComponents)-finalEmpty]
Dan Willemsen34cc69e2015-09-23 15:26:20 -07002229 // TODO: filepath.Join isn't necessarily correct with embedded ninja
2230 // variables. '..' may remove the entire ninja variable, even if it
2231 // will be expanded to multiple nested directories.
Colin Crossbf9ed3f2023-10-24 14:17:03 -07002232 return filepath.Join(nonEmptyPathComponents...), nil
Dan Willemsen34cc69e2015-09-23 15:26:20 -07002233}
2234
Jingwen Chen24d0c562023-02-07 09:29:36 +00002235// validateSafePath validates a path that we trust (may contain ninja
2236// variables). Ensures that each path component does not attempt to leave its
2237// component. Returns a joined version of each path component.
2238func validateSafePath(pathComponents ...string) (string, error) {
2239 return validatePathInternal(true, pathComponents...)
2240}
2241
Dan Willemsen80a7c2a2015-12-21 14:57:11 -08002242// validatePath validates that a path does not include ninja variables, and that
2243// each path component does not attempt to leave its component. Returns a joined
2244// version of each path component.
Colin Cross1ccfcc32018-02-22 13:54:26 -08002245func validatePath(pathComponents ...string) (string, error) {
Jingwen Chen24d0c562023-02-07 09:29:36 +00002246 return validatePathInternal(false, pathComponents...)
Colin Cross6e18ca42015-07-14 18:55:36 -07002247}
Colin Cross5b529592017-05-09 13:34:34 -07002248
Colin Cross0875c522017-11-28 17:34:01 -08002249func PathForPhony(ctx PathContext, phony string) WritablePath {
2250 if strings.ContainsAny(phony, "$/") {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01002251 ReportPathErrorf(ctx, "Phony target contains invalid character ($ or /): %s", phony)
Colin Cross0875c522017-11-28 17:34:01 -08002252 }
Paul Duffin74abc5d2021-03-24 09:24:59 +00002253 return PhonyPath{basePath{phony, ""}}
Colin Cross0875c522017-11-28 17:34:01 -08002254}
2255
Colin Cross74e3fe42017-12-11 15:51:44 -08002256type PhonyPath struct {
2257 basePath
2258}
2259
2260func (p PhonyPath) writablePath() {}
2261
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02002262func (p PhonyPath) getSoongOutDir() string {
Paul Duffind65c58b2021-03-24 09:22:07 +00002263 // A phone path cannot contain any / so cannot be relative to the build directory.
2264 return ""
Paul Duffin9b478b02019-12-10 13:41:51 +00002265}
2266
Paul Duffin85d8f0d2021-03-24 10:18:18 +00002267func (p PhonyPath) RelativeToTop() Path {
2268 ensureTestOnly()
2269 // A phony path cannot contain any / so does not have a build directory so switching to a new
2270 // build directory has no effect so just return this path.
2271 return p
2272}
2273
Colin Cross7707b242024-07-26 12:02:36 -07002274func (p PhonyPath) WithoutRel() Path {
2275 p.basePath = p.basePath.withoutRel()
2276 return p
2277}
2278
Hans MÃ¥nssond3f2bd72020-11-27 12:37:28 +01002279func (p PhonyPath) ReplaceExtension(ctx PathContext, ext string) OutputPath {
2280 panic("Not implemented")
2281}
2282
Colin Cross74e3fe42017-12-11 15:51:44 -08002283var _ Path = PhonyPath{}
2284var _ WritablePath = PhonyPath{}
2285
Colin Cross5b529592017-05-09 13:34:34 -07002286type testPath struct {
2287 basePath
2288}
2289
Paul Duffin85d8f0d2021-03-24 10:18:18 +00002290func (p testPath) RelativeToTop() Path {
2291 ensureTestOnly()
2292 return p
2293}
2294
Colin Cross7707b242024-07-26 12:02:36 -07002295func (p testPath) WithoutRel() Path {
2296 p.basePath = p.basePath.withoutRel()
2297 return p
2298}
2299
Colin Cross5b529592017-05-09 13:34:34 -07002300func (p testPath) String() string {
2301 return p.path
2302}
2303
Paul Duffin85d8f0d2021-03-24 10:18:18 +00002304var _ Path = testPath{}
2305
Colin Cross40e33732019-02-15 11:08:35 -08002306// PathForTesting returns a Path constructed from joining the elements of paths with '/'. It should only be used from
2307// within tests.
Colin Cross5b529592017-05-09 13:34:34 -07002308func PathForTesting(paths ...string) Path {
Colin Cross1ccfcc32018-02-22 13:54:26 -08002309 p, err := validateSafePath(paths...)
2310 if err != nil {
2311 panic(err)
2312 }
Colin Cross5b529592017-05-09 13:34:34 -07002313 return testPath{basePath{path: p, rel: p}}
2314}
2315
Sam Delmerico2351eac2022-05-24 17:10:02 +00002316func PathForTestingWithRel(path, rel string) Path {
2317 p, err := validateSafePath(path, rel)
2318 if err != nil {
2319 panic(err)
2320 }
2321 r, err := validatePath(rel)
2322 if err != nil {
2323 panic(err)
2324 }
2325 return testPath{basePath{path: p, rel: r}}
2326}
2327
Colin Cross40e33732019-02-15 11:08:35 -08002328// PathsForTesting returns a Path constructed from each element in strs. It should only be used from within tests.
2329func PathsForTesting(strs ...string) Paths {
Colin Cross5b529592017-05-09 13:34:34 -07002330 p := make(Paths, len(strs))
2331 for i, s := range strs {
2332 p[i] = PathForTesting(s)
2333 }
2334
2335 return p
2336}
Colin Cross43f08db2018-11-12 10:13:39 -08002337
Colin Cross40e33732019-02-15 11:08:35 -08002338type testPathContext struct {
2339 config Config
Colin Cross40e33732019-02-15 11:08:35 -08002340}
2341
Colin Cross40e33732019-02-15 11:08:35 -08002342func (x *testPathContext) Config() Config { return x.config }
2343func (x *testPathContext) AddNinjaFileDeps(...string) {}
2344
2345// PathContextForTesting returns a PathContext that can be used in tests, for example to create an OutputPath with
2346// PathForOutput.
Colin Cross98be1bb2019-12-13 20:41:13 -08002347func PathContextForTesting(config Config) PathContext {
Colin Cross40e33732019-02-15 11:08:35 -08002348 return &testPathContext{
2349 config: config,
Colin Cross40e33732019-02-15 11:08:35 -08002350 }
2351}
2352
Ulya Trafimovichccc8c852020-10-14 11:29:07 +01002353type testModuleInstallPathContext struct {
2354 baseModuleContext
2355
2356 inData bool
2357 inTestcases bool
2358 inSanitizerDir bool
2359 inRamdisk bool
2360 inVendorRamdisk bool
Inseob Kim08758f02021-04-08 21:13:22 +09002361 inDebugRamdisk bool
Ulya Trafimovichccc8c852020-10-14 11:29:07 +01002362 inRecovery bool
2363 inRoot bool
Colin Crossea30d852023-11-29 16:00:16 -08002364 inOdm bool
2365 inProduct bool
2366 inVendor bool
Spandan Das27ff7672024-11-06 19:23:57 +00002367 inSystemDlkm bool
2368 inVendorDlkm bool
2369 inOdmDlkm bool
Ulya Trafimovichccc8c852020-10-14 11:29:07 +01002370 forceOS *OsType
2371 forceArch *ArchType
2372}
2373
2374func (m testModuleInstallPathContext) Config() Config {
2375 return m.baseModuleContext.config
2376}
2377
2378func (testModuleInstallPathContext) AddNinjaFileDeps(deps ...string) {}
2379
2380func (m testModuleInstallPathContext) InstallInData() bool {
2381 return m.inData
2382}
2383
2384func (m testModuleInstallPathContext) InstallInTestcases() bool {
2385 return m.inTestcases
2386}
2387
2388func (m testModuleInstallPathContext) InstallInSanitizerDir() bool {
2389 return m.inSanitizerDir
2390}
2391
2392func (m testModuleInstallPathContext) InstallInRamdisk() bool {
2393 return m.inRamdisk
2394}
2395
2396func (m testModuleInstallPathContext) InstallInVendorRamdisk() bool {
2397 return m.inVendorRamdisk
2398}
2399
Inseob Kim08758f02021-04-08 21:13:22 +09002400func (m testModuleInstallPathContext) InstallInDebugRamdisk() bool {
2401 return m.inDebugRamdisk
2402}
2403
Ulya Trafimovichccc8c852020-10-14 11:29:07 +01002404func (m testModuleInstallPathContext) InstallInRecovery() bool {
2405 return m.inRecovery
2406}
2407
2408func (m testModuleInstallPathContext) InstallInRoot() bool {
2409 return m.inRoot
2410}
2411
Colin Crossea30d852023-11-29 16:00:16 -08002412func (m testModuleInstallPathContext) InstallInOdm() bool {
2413 return m.inOdm
2414}
2415
2416func (m testModuleInstallPathContext) InstallInProduct() bool {
2417 return m.inProduct
2418}
2419
2420func (m testModuleInstallPathContext) InstallInVendor() bool {
2421 return m.inVendor
2422}
2423
Spandan Das27ff7672024-11-06 19:23:57 +00002424func (m testModuleInstallPathContext) InstallInSystemDlkm() bool {
2425 return m.inSystemDlkm
2426}
2427
2428func (m testModuleInstallPathContext) InstallInVendorDlkm() bool {
2429 return m.inVendorDlkm
2430}
2431
2432func (m testModuleInstallPathContext) InstallInOdmDlkm() bool {
2433 return m.inOdmDlkm
2434}
2435
Ulya Trafimovichccc8c852020-10-14 11:29:07 +01002436func (m testModuleInstallPathContext) InstallForceOS() (*OsType, *ArchType) {
2437 return m.forceOS, m.forceArch
2438}
2439
2440// Construct a minimal ModuleInstallPathContext for testing. Note that baseModuleContext is
2441// default-initialized, which leaves blueprint.baseModuleContext set to nil, so methods that are
2442// delegated to it will panic.
2443func ModuleInstallPathContextForTesting(config Config) ModuleInstallPathContext {
2444 ctx := &testModuleInstallPathContext{}
2445 ctx.config = config
2446 ctx.os = Android
2447 return ctx
2448}
2449
Colin Cross43f08db2018-11-12 10:13:39 -08002450// Rel performs the same function as filepath.Rel, but reports errors to a PathContext, and reports an error if
2451// targetPath is not inside basePath.
2452func Rel(ctx PathContext, basePath string, targetPath string) string {
2453 rel, isRel := MaybeRel(ctx, basePath, targetPath)
2454 if !isRel {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01002455 ReportPathErrorf(ctx, "path %q is not under path %q", targetPath, basePath)
Colin Cross43f08db2018-11-12 10:13:39 -08002456 return ""
2457 }
2458 return rel
2459}
2460
2461// MaybeRel performs the same function as filepath.Rel, but reports errors to a PathContext, and returns false if
2462// targetPath is not inside basePath.
2463func MaybeRel(ctx PathContext, basePath string, targetPath string) (string, bool) {
Dan Willemsen633c5022019-04-12 11:11:38 -07002464 rel, isRel, err := maybeRelErr(basePath, targetPath)
2465 if err != nil {
2466 reportPathError(ctx, err)
2467 }
2468 return rel, isRel
2469}
2470
2471func maybeRelErr(basePath string, targetPath string) (string, bool, error) {
Colin Cross43f08db2018-11-12 10:13:39 -08002472 // filepath.Rel returns an error if one path is absolute and the other is not, handle that case first.
2473 if filepath.IsAbs(basePath) != filepath.IsAbs(targetPath) {
Dan Willemsen633c5022019-04-12 11:11:38 -07002474 return "", false, nil
Colin Cross43f08db2018-11-12 10:13:39 -08002475 }
2476 rel, err := filepath.Rel(basePath, targetPath)
2477 if err != nil {
Dan Willemsen633c5022019-04-12 11:11:38 -07002478 return "", false, err
Colin Cross43f08db2018-11-12 10:13:39 -08002479 } else if rel == ".." || strings.HasPrefix(rel, "../") || strings.HasPrefix(rel, "/") {
Dan Willemsen633c5022019-04-12 11:11:38 -07002480 return "", false, nil
Colin Cross43f08db2018-11-12 10:13:39 -08002481 }
Dan Willemsen633c5022019-04-12 11:11:38 -07002482 return rel, true, nil
Colin Cross43f08db2018-11-12 10:13:39 -08002483}
Colin Cross988414c2020-01-11 01:11:46 +00002484
2485// Writes a file to the output directory. Attempting to write directly to the output directory
2486// will fail due to the sandbox of the soong_build process.
Chris Parsons1a12d032023-02-06 22:37:41 -05002487// Only writes the file if the file doesn't exist or if it has different contents, to prevent
2488// updating the timestamp if no changes would be made. (This is better for incremental
2489// performance.)
Colin Cross988414c2020-01-11 01:11:46 +00002490func WriteFileToOutputDir(path WritablePath, data []byte, perm os.FileMode) error {
Colin Crossd6421132021-11-09 12:32:34 -08002491 absPath := absolutePath(path.String())
2492 err := os.MkdirAll(filepath.Dir(absPath), 0777)
2493 if err != nil {
2494 return err
2495 }
Chris Parsons1a12d032023-02-06 22:37:41 -05002496 return pathtools.WriteFileIfChanged(absPath, data, perm)
Colin Cross988414c2020-01-11 01:11:46 +00002497}
2498
Liz Kammer2dd9ca42020-11-25 16:06:39 -08002499func RemoveAllOutputDir(path WritablePath) error {
2500 return os.RemoveAll(absolutePath(path.String()))
2501}
2502
2503func CreateOutputDirIfNonexistent(path WritablePath, perm os.FileMode) error {
2504 dir := absolutePath(path.String())
Liz Kammer09f947d2021-05-12 14:51:49 -04002505 return createDirIfNonexistent(dir, perm)
2506}
2507
2508func createDirIfNonexistent(dir string, perm os.FileMode) error {
Liz Kammer2dd9ca42020-11-25 16:06:39 -08002509 if _, err := os.Stat(dir); os.IsNotExist(err) {
2510 return os.MkdirAll(dir, os.ModePerm)
2511 } else {
2512 return err
2513 }
2514}
2515
Jingwen Chen78257e52021-05-21 02:34:24 +00002516// absolutePath is deliberately private so that Soong's Go plugins can't use it to find and
2517// read arbitrary files without going through the methods in the current package that track
2518// dependencies.
Colin Cross988414c2020-01-11 01:11:46 +00002519func absolutePath(path string) string {
2520 if filepath.IsAbs(path) {
2521 return path
2522 }
2523 return filepath.Join(absSrcDir, path)
2524}
Chris Parsons216e10a2020-07-09 17:12:52 -04002525
2526// A DataPath represents the path of a file to be used as data, for example
2527// a test library to be installed alongside a test.
2528// The data file should be installed (copied from `<SrcPath>`) to
2529// `<install_root>/<RelativeInstallPath>/<filename>`, or
2530// `<install_root>/<filename>` if RelativeInstallPath is empty.
2531type DataPath struct {
2532 // The path of the data file that should be copied into the data directory
2533 SrcPath Path
2534 // The install path of the data file, relative to the install root.
2535 RelativeInstallPath string
Colin Cross5c1d5fb2023-11-15 12:39:40 -08002536 // If WithoutRel is true, use SrcPath.Base() instead of SrcPath.Rel() as the filename.
2537 WithoutRel bool
Chris Parsons216e10a2020-07-09 17:12:52 -04002538}
Colin Crossdcf71b22021-02-01 13:59:03 -08002539
Colin Crossd442a0e2023-11-16 11:19:26 -08002540func (d *DataPath) ToRelativeInstallPath() string {
2541 relPath := d.SrcPath.Rel()
Colin Cross5c1d5fb2023-11-15 12:39:40 -08002542 if d.WithoutRel {
2543 relPath = d.SrcPath.Base()
2544 }
Colin Crossd442a0e2023-11-16 11:19:26 -08002545 if d.RelativeInstallPath != "" {
2546 relPath = filepath.Join(d.RelativeInstallPath, relPath)
2547 }
2548 return relPath
2549}
2550
Colin Crossdcf71b22021-02-01 13:59:03 -08002551// PathsIfNonNil returns a Paths containing only the non-nil input arguments.
2552func PathsIfNonNil(paths ...Path) Paths {
2553 if len(paths) == 0 {
2554 // Fast path for empty argument list
2555 return nil
2556 } else if len(paths) == 1 {
2557 // Fast path for a single argument
2558 if paths[0] != nil {
2559 return paths
2560 } else {
2561 return nil
2562 }
2563 }
2564 ret := make(Paths, 0, len(paths))
2565 for _, path := range paths {
2566 if path != nil {
2567 ret = append(ret, path)
2568 }
2569 }
2570 if len(ret) == 0 {
2571 return nil
2572 }
2573 return ret
2574}
Chris Wailesb2703ad2021-07-30 13:25:42 -07002575
2576var thirdPartyDirPrefixExceptions = []*regexp.Regexp{
2577 regexp.MustCompile("^vendor/[^/]*google[^/]*/"),
2578 regexp.MustCompile("^hardware/google/"),
2579 regexp.MustCompile("^hardware/interfaces/"),
2580 regexp.MustCompile("^hardware/libhardware[^/]*/"),
2581 regexp.MustCompile("^hardware/ril/"),
2582}
2583
2584func IsThirdPartyPath(path string) bool {
2585 thirdPartyDirPrefixes := []string{"external/", "vendor/", "hardware/"}
2586
2587 if HasAnyPrefix(path, thirdPartyDirPrefixes) {
2588 for _, prefix := range thirdPartyDirPrefixExceptions {
2589 if prefix.MatchString(path) {
2590 return false
2591 }
2592 }
2593 return true
2594 }
2595 return false
2596}
Jihoon Kangf27c3a52024-11-12 21:27:09 +00002597
2598// ToRelativeSourcePath converts absolute source path to the path relative to the source root.
2599// This throws an error if the input path is outside of the source root and cannot be converted
2600// to the relative path.
2601// This should be rarely used given that the source path is relative in Soong.
2602func ToRelativeSourcePath(ctx PathContext, path string) string {
2603 ret := path
2604 if filepath.IsAbs(path) {
2605 relPath, err := filepath.Rel(absSrcDir, path)
2606 if err != nil || strings.HasPrefix(relPath, "..") {
2607 ReportPathErrorf(ctx, "%s is outside of the source root", path)
2608 }
2609 ret = relPath
2610 }
2611 return ret
2612}