blob: a020d8a7fd8630717c75c26e31dcffddbfe68330 [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
Colin Cross5e708052019-08-06 13:59:50 -0700238func pathContextName(ctx PathContext, module blueprint.Module) string {
239 if x, ok := ctx.(interface{ ModuleName(blueprint.Module) string }); ok {
240 return x.ModuleName(module)
241 } else if x, ok := ctx.(interface{ OtherModuleName(blueprint.Module) string }); ok {
242 return x.OtherModuleName(module)
243 }
244 return "unknown"
245}
246
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700247type Path interface {
248 // Returns the path in string form
249 String() string
250
Colin Cross4f6fc9c2016-10-26 10:05:25 -0700251 // Ext returns the extension of the last element of the path
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700252 Ext() string
Colin Cross4f6fc9c2016-10-26 10:05:25 -0700253
254 // Base returns the last element of the path
255 Base() string
Colin Crossfaeb7aa2017-02-01 14:12:44 -0800256
257 // Rel returns the portion of the path relative to the directory it was created from. For
258 // example, Rel on a PathsForModuleSrc would return the path relative to the module source
Colin Cross0db55682017-12-05 15:36:55 -0800259 // directory, and OutputPath.Join("foo").Rel() would return "foo".
Colin Crossfaeb7aa2017-02-01 14:12:44 -0800260 Rel() string
Paul Duffin85d8f0d2021-03-24 10:18:18 +0000261
Colin Cross7707b242024-07-26 12:02:36 -0700262 // WithoutRel returns a new Path with no relative path, i.e. Rel() will return the same value as Base().
263 WithoutRel() Path
264
Paul Duffin85d8f0d2021-03-24 10:18:18 +0000265 // RelativeToTop returns a new path relative to the top, it is provided solely for use in tests.
266 //
267 // It is guaranteed to always return the same type as it is called on, e.g. if called on an
268 // InstallPath then the returned value can be converted to an InstallPath.
269 //
270 // A standard build has the following structure:
271 // ../top/
272 // out/ - make install files go here.
Colin Cross3b1c6842024-07-26 11:52:57 -0700273 // out/soong - this is the outDir passed to NewTestConfig()
Paul Duffin85d8f0d2021-03-24 10:18:18 +0000274 // ... - the source files
275 //
276 // This function converts a path so that it appears relative to the ../top/ directory, i.e.
Colin Cross3b1c6842024-07-26 11:52:57 -0700277 // * Make install paths, which have the pattern "outDir/../<path>" are converted into the top
Paul Duffin85d8f0d2021-03-24 10:18:18 +0000278 // relative path "out/<path>"
Colin Cross3b1c6842024-07-26 11:52:57 -0700279 // * Soong install paths and other writable paths, which have the pattern "outDir/soong/<path>" are
Paul Duffin85d8f0d2021-03-24 10:18:18 +0000280 // converted into the top relative path "out/soong/<path>".
281 // * Source paths are already relative to the top.
282 // * Phony paths are not relative to anything.
283 // * toolDepPath have an absolute but known value in so don't need making relative to anything in
284 // order to test.
285 RelativeToTop() Path
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700286}
287
Paul Duffin85d8f0d2021-03-24 10:18:18 +0000288const (
Colin Cross3b1c6842024-07-26 11:52:57 -0700289 testOutDir = "out"
290 testOutSoongSubDir = "/soong"
291 TestOutSoongDir = testOutDir + testOutSoongSubDir
Paul Duffin85d8f0d2021-03-24 10:18:18 +0000292)
293
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700294// WritablePath is a type of path that can be used as an output for build rules.
295type WritablePath interface {
296 Path
297
Paul Duffin9b478b02019-12-10 13:41:51 +0000298 // return the path to the build directory.
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +0200299 getSoongOutDir() string
Paul Duffin9b478b02019-12-10 13:41:51 +0000300
Jeff Gaston734e3802017-04-10 15:47:24 -0700301 // the writablePath method doesn't directly do anything,
302 // but it allows a struct to distinguish between whether or not it implements the WritablePath interface
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700303 writablePath()
Hans MÃ¥nssond3f2bd72020-11-27 12:37:28 +0100304
305 ReplaceExtension(ctx PathContext, ext string) OutputPath
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700306}
307
308type genPathProvider interface {
Liz Kammera830f3a2020-11-10 10:50:34 -0800309 genPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleGenPath
yangbill6d032dd2024-04-18 03:05:49 +0000310 genPathWithExtAndTrimExt(ctx ModuleOutPathContext, subdir, ext string, trimExt string) ModuleGenPath
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700311}
312type objPathProvider interface {
Liz Kammera830f3a2020-11-10 10:50:34 -0800313 objPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleObjPath
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700314}
315type resPathProvider interface {
Liz Kammera830f3a2020-11-10 10:50:34 -0800316 resPathWithName(ctx ModuleOutPathContext, name string) ModuleResPath
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700317}
318
319// GenPathWithExt derives a new file path in ctx's generated sources directory
320// from the current path, but with the new extension.
Liz Kammera830f3a2020-11-10 10:50:34 -0800321func GenPathWithExt(ctx ModuleOutPathContext, subdir string, p Path, ext string) ModuleGenPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700322 if path, ok := p.(genPathProvider); ok {
Dan Willemsen21ec4902016-11-02 20:43:13 -0700323 return path.genPathWithExt(ctx, subdir, ext)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700324 }
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +0100325 ReportPathErrorf(ctx, "Tried to create generated file from unsupported path: %s(%s)", reflect.TypeOf(p).Name(), p)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700326 return PathForModuleGen(ctx)
327}
328
yangbill6d032dd2024-04-18 03:05:49 +0000329// GenPathWithExtAndTrimExt derives a new file path in ctx's generated sources directory
330// from the current path, but with the new extension and trim the suffix.
331func GenPathWithExtAndTrimExt(ctx ModuleOutPathContext, subdir string, p Path, ext string, trimExt string) ModuleGenPath {
332 if path, ok := p.(genPathProvider); ok {
333 return path.genPathWithExtAndTrimExt(ctx, subdir, ext, trimExt)
334 }
335 ReportPathErrorf(ctx, "Tried to create generated file from unsupported path: %s(%s)", reflect.TypeOf(p).Name(), p)
336 return PathForModuleGen(ctx)
337}
338
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700339// ObjPathWithExt derives a new file path in ctx's object directory from the
340// current path, but with the new extension.
Liz Kammera830f3a2020-11-10 10:50:34 -0800341func ObjPathWithExt(ctx ModuleOutPathContext, subdir string, p Path, ext string) ModuleObjPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700342 if path, ok := p.(objPathProvider); ok {
343 return path.objPathWithExt(ctx, subdir, ext)
344 }
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +0100345 ReportPathErrorf(ctx, "Tried to create object file from unsupported path: %s (%s)", reflect.TypeOf(p).Name(), p)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700346 return PathForModuleObj(ctx)
347}
348
349// ResPathWithName derives a new path in ctx's output resource directory, using
350// the current path to create the directory name, and the `name` argument for
351// the filename.
Liz Kammera830f3a2020-11-10 10:50:34 -0800352func ResPathWithName(ctx ModuleOutPathContext, p Path, name string) ModuleResPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700353 if path, ok := p.(resPathProvider); ok {
354 return path.resPathWithName(ctx, name)
355 }
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +0100356 ReportPathErrorf(ctx, "Tried to create res file from unsupported path: %s (%s)", reflect.TypeOf(p).Name(), p)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700357 return PathForModuleRes(ctx)
358}
359
360// OptionalPath is a container that may or may not contain a valid Path.
361type OptionalPath struct {
Martin Stjernholmc32dd1c2021-09-15 02:39:00 +0100362 path Path // nil if invalid.
363 invalidReason string // Not applicable if path != nil. "" if the reason is unknown.
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700364}
365
Yu Liu467d7c52024-09-18 21:54:44 +0000366type optionalPathGob struct {
367 Path Path
368 InvalidReason string
369}
370
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700371// OptionalPathForPath returns an OptionalPath containing the path.
372func OptionalPathForPath(path Path) OptionalPath {
Martin Stjernholm2fee27f2021-09-16 14:11:12 +0100373 return OptionalPath{path: path}
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700374}
375
Martin Stjernholmc32dd1c2021-09-15 02:39:00 +0100376// InvalidOptionalPath returns an OptionalPath that is invalid with the given reason.
377func InvalidOptionalPath(reason string) OptionalPath {
378
379 return OptionalPath{invalidReason: reason}
380}
381
Yu Liu467d7c52024-09-18 21:54:44 +0000382func (p *OptionalPath) ToGob() *optionalPathGob {
383 return &optionalPathGob{
384 Path: p.path,
385 InvalidReason: p.invalidReason,
386 }
387}
388
389func (p *OptionalPath) FromGob(data *optionalPathGob) {
390 p.path = data.Path
391 p.invalidReason = data.InvalidReason
392}
393
394func (p OptionalPath) GobEncode() ([]byte, error) {
Yu Liu3cadf7d2024-10-24 18:47:06 +0000395 return gobtools.CustomGobEncode[optionalPathGob](&p)
Yu Liu467d7c52024-09-18 21:54:44 +0000396}
397
398func (p *OptionalPath) GobDecode(data []byte) error {
Yu Liu3cadf7d2024-10-24 18:47:06 +0000399 return gobtools.CustomGobDecode[optionalPathGob](data, p)
Yu Liu467d7c52024-09-18 21:54:44 +0000400}
401
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700402// Valid returns whether there is a valid path
403func (p OptionalPath) Valid() bool {
Martin Stjernholm2fee27f2021-09-16 14:11:12 +0100404 return p.path != nil
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700405}
406
407// Path returns the Path embedded in this OptionalPath. You must be sure that
408// there is a valid path, since this method will panic if there is not.
409func (p OptionalPath) Path() Path {
Martin Stjernholm2fee27f2021-09-16 14:11:12 +0100410 if p.path == nil {
Martin Stjernholmc32dd1c2021-09-15 02:39:00 +0100411 msg := "Requesting an invalid path"
412 if p.invalidReason != "" {
413 msg += ": " + p.invalidReason
414 }
415 panic(msg)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700416 }
417 return p.path
418}
419
Martin Stjernholmc32dd1c2021-09-15 02:39:00 +0100420// InvalidReason returns the reason that the optional path is invalid, or "" if it is valid.
421func (p OptionalPath) InvalidReason() string {
422 if p.path != nil {
423 return ""
424 }
425 if p.invalidReason == "" {
426 return "unknown"
427 }
428 return p.invalidReason
429}
430
Paul Duffinef081852021-05-13 11:11:15 +0100431// AsPaths converts the OptionalPath into Paths.
432//
433// It returns nil if this is not valid, or a single length slice containing the Path embedded in
434// this OptionalPath.
435func (p OptionalPath) AsPaths() Paths {
Martin Stjernholm2fee27f2021-09-16 14:11:12 +0100436 if p.path == nil {
Paul Duffinef081852021-05-13 11:11:15 +0100437 return nil
438 }
439 return Paths{p.path}
440}
441
Paul Duffinafdd4062021-03-30 19:44:07 +0100442// RelativeToTop returns an OptionalPath with the path that was embedded having been replaced by the
443// result of calling Path.RelativeToTop on it.
444func (p OptionalPath) RelativeToTop() OptionalPath {
Martin Stjernholm2fee27f2021-09-16 14:11:12 +0100445 if p.path == nil {
Paul Duffina5b81352021-03-28 23:57:19 +0100446 return p
447 }
448 p.path = p.path.RelativeToTop()
449 return p
450}
451
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700452// String returns the string version of the Path, or "" if it isn't valid.
453func (p OptionalPath) String() string {
Martin Stjernholm2fee27f2021-09-16 14:11:12 +0100454 if p.path != nil {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700455 return p.path.String()
456 } else {
457 return ""
Colin Crossf2298272015-05-12 11:36:53 -0700458 }
459}
Colin Cross6e18ca42015-07-14 18:55:36 -0700460
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700461// Paths is a slice of Path objects, with helpers to operate on the collection.
462type Paths []Path
463
Paul Duffin85d8f0d2021-03-24 10:18:18 +0000464// RelativeToTop creates a new Paths containing the result of calling Path.RelativeToTop on each
465// item in this slice.
466func (p Paths) RelativeToTop() Paths {
467 ensureTestOnly()
468 if p == nil {
469 return p
470 }
471 ret := make(Paths, len(p))
472 for i, path := range p {
473 ret[i] = path.RelativeToTop()
474 }
475 return ret
476}
477
Jingwen Chen40fd90a2020-06-15 05:24:19 +0000478func (paths Paths) containsPath(path Path) bool {
479 for _, p := range paths {
480 if p == path {
481 return true
482 }
483 }
484 return false
485}
486
Liz Kammer7aa52882021-02-11 09:16:14 -0500487// PathsForSource returns Paths rooted from SrcDir, *not* rooted from the module's local source
488// directory
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700489func PathsForSource(ctx PathContext, paths []string) Paths {
490 ret := make(Paths, len(paths))
491 for i, path := range paths {
492 ret[i] = PathForSource(ctx, path)
493 }
494 return ret
495}
496
Liz Kammer7aa52882021-02-11 09:16:14 -0500497// ExistentPathsForSources returns a list of Paths rooted from SrcDir, *not* rooted from the
498// module's local source directory, that are found in the tree. If any are not found, they are
499// 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 -0700500func ExistentPathsForSources(ctx PathGlobContext, paths []string) Paths {
Dan Willemsen7b310ee2015-12-18 15:11:17 -0800501 ret := make(Paths, 0, len(paths))
502 for _, path := range paths {
Colin Cross32f38982018-02-22 11:47:25 -0800503 p := ExistentPathForSource(ctx, path)
Dan Willemsen7b310ee2015-12-18 15:11:17 -0800504 if p.Valid() {
505 ret = append(ret, p.Path())
506 }
507 }
508 return ret
509}
510
Liz Kammer620dea62021-04-14 17:36:10 -0400511// PathsForModuleSrc returns a Paths{} containing the resolved references in paths:
Colin Crossd079e0b2022-08-16 10:27:33 -0700512// - filepath, relative to local module directory, resolves as a filepath relative to the local
513// source directory
514// - glob, relative to the local module directory, resolves as filepath(s), relative to the local
515// source directory.
516// - other modules using the ":name{.tag}" syntax. These modules must implement SourceFileProducer
mrziwangd38e63d2024-07-15 13:43:37 -0700517// or set the OutputFilesProvider. These resolve as a filepath to an output filepath or generated
518// source filepath.
Colin Crossd079e0b2022-08-16 10:27:33 -0700519//
Liz Kammer620dea62021-04-14 17:36:10 -0400520// Properties passed as the paths argument must have been annotated with struct tag
Colin Cross41955e82019-05-29 14:40:35 -0700521// `android:"path"` so that dependencies on SourceFileProducer modules will have already been handled by the
Spandan Das950091c2023-07-19 22:26:37 +0000522// pathdeps mutator.
Liz Kammer620dea62021-04-14 17:36:10 -0400523// If a requested module is not found as a dependency:
Colin Crossd079e0b2022-08-16 10:27:33 -0700524// - if ctx.Config().AllowMissingDependencies() is true, this module to be marked as having
Liz Kammer620dea62021-04-14 17:36:10 -0400525// missing dependencies
Colin Crossd079e0b2022-08-16 10:27:33 -0700526// - otherwise, a ModuleError is thrown.
Liz Kammera830f3a2020-11-10 10:50:34 -0800527func PathsForModuleSrc(ctx ModuleMissingDepsPathContext, paths []string) Paths {
Colin Cross8a497952019-03-05 22:25:09 -0800528 return PathsForModuleSrcExcludes(ctx, paths, nil)
529}
530
Liz Kammer619be462022-01-28 15:13:39 -0500531type SourceInput struct {
532 Context ModuleMissingDepsPathContext
533 Paths []string
534 ExcludePaths []string
535 IncludeDirs bool
536}
537
Liz Kammer620dea62021-04-14 17:36:10 -0400538// PathsForModuleSrcExcludes returns a Paths{} containing the resolved references in paths, minus
539// those listed in excludes. Elements of paths and excludes are resolved as:
Colin Crossd079e0b2022-08-16 10:27:33 -0700540// - filepath, relative to local module directory, resolves as a filepath relative to the local
541// source directory
542// - glob, relative to the local module directory, resolves as filepath(s), relative to the local
543// source directory. Not valid in excludes.
544// - other modules using the ":name{.tag}" syntax. These modules must implement SourceFileProducer
mrziwangd38e63d2024-07-15 13:43:37 -0700545// or set the OutputFilesProvider. These resolve as a filepath to an output filepath or generated
546// source filepath.
Colin Crossd079e0b2022-08-16 10:27:33 -0700547//
Liz Kammer620dea62021-04-14 17:36:10 -0400548// excluding the items (similarly resolved
549// Properties passed as the paths argument must have been annotated with struct tag
550// `android:"path"` so that dependencies on SourceFileProducer modules will have already been handled by the
Spandan Das950091c2023-07-19 22:26:37 +0000551// pathdeps mutator.
Liz Kammer620dea62021-04-14 17:36:10 -0400552// If a requested module is not found as a dependency:
Colin Crossd079e0b2022-08-16 10:27:33 -0700553// - if ctx.Config().AllowMissingDependencies() is true, this module to be marked as having
Liz Kammer620dea62021-04-14 17:36:10 -0400554// missing dependencies
Colin Crossd079e0b2022-08-16 10:27:33 -0700555// - otherwise, a ModuleError is thrown.
Liz Kammera830f3a2020-11-10 10:50:34 -0800556func PathsForModuleSrcExcludes(ctx ModuleMissingDepsPathContext, paths, excludes []string) Paths {
Liz Kammer619be462022-01-28 15:13:39 -0500557 return PathsRelativeToModuleSourceDir(SourceInput{
558 Context: ctx,
559 Paths: paths,
560 ExcludePaths: excludes,
561 IncludeDirs: true,
562 })
563}
564
565func PathsRelativeToModuleSourceDir(input SourceInput) Paths {
566 ret, missingDeps := PathsAndMissingDepsRelativeToModuleSourceDir(input)
567 if input.Context.Config().AllowMissingDependencies() {
568 input.Context.AddMissingDependencies(missingDeps)
Colin Crossba71a3f2019-03-18 12:12:48 -0700569 } else {
570 for _, m := range missingDeps {
Liz Kammer619be462022-01-28 15:13:39 -0500571 input.Context.ModuleErrorf(`missing dependency on %q, is the property annotated with android:"path"?`, m)
Colin Crossba71a3f2019-03-18 12:12:48 -0700572 }
573 }
574 return ret
575}
576
Inseob Kim93036a52024-10-25 17:02:21 +0900577type directoryPath struct {
578 basePath
579}
580
581func (d *directoryPath) String() string {
582 return d.basePath.String()
583}
584
585func (d *directoryPath) base() basePath {
586 return d.basePath
587}
588
589// DirectoryPath represents a source path for directories. Incompatible with Path by design.
590type DirectoryPath interface {
591 String() string
592 base() basePath
593}
594
595var _ DirectoryPath = (*directoryPath)(nil)
596
597type DirectoryPaths []DirectoryPath
598
Inseob Kim76e19852024-10-10 17:57:22 +0900599// DirectoryPathsForModuleSrcExcludes returns a Paths{} containing the resolved references in
600// directory paths. Elements of paths are resolved as:
601// - filepath, relative to local module directory, resolves as a filepath relative to the local
602// source directory
603// - other modules using the ":name" syntax. These modules must implement DirProvider.
Inseob Kim93036a52024-10-25 17:02:21 +0900604func DirectoryPathsForModuleSrc(ctx ModuleMissingDepsPathContext, paths []string) DirectoryPaths {
605 var ret DirectoryPaths
Inseob Kim76e19852024-10-10 17:57:22 +0900606
607 for _, path := range paths {
608 if m, t := SrcIsModuleWithTag(path); m != "" {
Yu Liud3228ac2024-11-08 23:11:47 +0000609 module := GetModuleProxyFromPathDep(ctx, m, t)
Inseob Kim76e19852024-10-10 17:57:22 +0900610 if module == nil {
611 ctx.ModuleErrorf(`missing dependency on %q, is the property annotated with android:"path"?`, m)
612 continue
613 }
614 if t != "" {
615 ctx.ModuleErrorf("DirProvider dependency %q does not support the tag %q", module, t)
616 continue
617 }
618 mctx, ok := ctx.(OtherModuleProviderContext)
619 if !ok {
620 panic(fmt.Errorf("%s is not an OtherModuleProviderContext", ctx))
621 }
Yu Liud3228ac2024-11-08 23:11:47 +0000622 if dirProvider, ok := OtherModuleProvider(mctx, *module, DirProvider); ok {
Inseob Kim76e19852024-10-10 17:57:22 +0900623 ret = append(ret, dirProvider.Dirs...)
624 } else {
625 ReportPathErrorf(ctx, "module %q does not implement DirProvider", module)
626 }
627 } else {
628 p := pathForModuleSrc(ctx, path)
629 if isDir, err := ctx.Config().fs.IsDir(p.String()); err != nil {
630 ReportPathErrorf(ctx, "%s: %s", p, err.Error())
631 } else if !isDir {
632 ReportPathErrorf(ctx, "module directory path %q is not a directory", p)
633 } else {
Inseob Kim93036a52024-10-25 17:02:21 +0900634 ret = append(ret, &directoryPath{basePath{path: p.path, rel: p.rel}})
Inseob Kim76e19852024-10-10 17:57:22 +0900635 }
636 }
637 }
638
Inseob Kim93036a52024-10-25 17:02:21 +0900639 seen := make(map[DirectoryPath]bool, len(ret))
Inseob Kim76e19852024-10-10 17:57:22 +0900640 for _, path := range ret {
641 if seen[path] {
642 ReportPathErrorf(ctx, "duplicated path %q", path)
643 }
644 seen[path] = true
645 }
646 return ret
647}
648
Ulya Trafimovich4d2eeed2019-11-08 10:54:21 +0000649// OutputPaths is a slice of OutputPath objects, with helpers to operate on the collection.
650type OutputPaths []OutputPath
651
652// Paths returns the OutputPaths as a Paths
653func (p OutputPaths) Paths() Paths {
654 if p == nil {
655 return nil
656 }
657 ret := make(Paths, len(p))
658 for i, path := range p {
659 ret[i] = path
660 }
661 return ret
662}
663
664// Strings returns the string forms of the writable paths.
665func (p OutputPaths) Strings() []string {
666 if p == nil {
667 return nil
668 }
669 ret := make([]string, len(p))
670 for i, path := range p {
671 ret[i] = path.String()
672 }
673 return ret
674}
675
Liz Kammera830f3a2020-11-10 10:50:34 -0800676// Expands Paths to a SourceFileProducer or OutputFileProducer module dependency referenced via ":name" or ":name{.tag}" syntax.
677// If the dependency is not found, a missingErrorDependency is returned.
678// If the module dependency is not a SourceFileProducer or OutputFileProducer, appropriate errors will be returned.
679func getPathsFromModuleDep(ctx ModuleWithDepsPathContext, path, moduleName, tag string) (Paths, error) {
Yu Liud3228ac2024-11-08 23:11:47 +0000680 module := GetModuleProxyFromPathDep(ctx, moduleName, tag)
Liz Kammera830f3a2020-11-10 10:50:34 -0800681 if module == nil {
682 return nil, missingDependencyError{[]string{moduleName}}
683 }
Yu Liub5275322024-11-13 18:40:43 +0000684 if !OtherModuleProviderOrDefault(ctx, *module, CommonModuleInfoKey).Enabled {
Colin Crossfa65cee2021-03-22 17:05:59 -0700685 return nil, missingDependencyError{[]string{moduleName}}
686 }
Yu Liud3228ac2024-11-08 23:11:47 +0000687
688 outputFiles, err := outputFilesForModule(ctx, *module, tag)
mrziwange6c85812024-05-22 14:36:09 -0700689 if outputFiles != nil && err == nil {
690 return outputFiles, nil
Liz Kammera830f3a2020-11-10 10:50:34 -0800691 } else {
mrziwange6c85812024-05-22 14:36:09 -0700692 return nil, err
Liz Kammera830f3a2020-11-10 10:50:34 -0800693 }
694}
695
Yu Liud3228ac2024-11-08 23:11:47 +0000696// GetModuleProxyFromPathDep will return the module that was added as a dependency automatically for
Paul Duffind5cf92e2021-07-09 17:38:55 +0100697// properties tagged with `android:"path"` or manually using ExtractSourceDeps or
698// ExtractSourcesDeps.
699//
700// The moduleName and tag supplied to this should be the values returned from SrcIsModuleWithTag.
701// Or, if no tag is expected then the moduleName should be the value returned by SrcIsModule and
702// the tag must be "".
703//
704// If tag is "" then the returned module will be the dependency that was added for ":moduleName".
705// Otherwise, it is the dependency that was added for ":moduleName{tag}".
Yu Liud3228ac2024-11-08 23:11:47 +0000706func GetModuleProxyFromPathDep(ctx ModuleWithDepsPathContext, moduleName, tag string) *ModuleProxy {
707 var found *ModuleProxy
708 // The sourceOrOutputDepTag uniquely identifies the module dependency as it contains both the
709 // module name and the tag. Dependencies added automatically for properties tagged with
710 // `android:"path"` are deduped so are guaranteed to be unique. It is possible for duplicate
711 // dependencies to be added manually using ExtractSourcesDeps or ExtractSourceDeps but even then
712 // it will always be the case that the dependencies will be identical, i.e. the same tag and same
713 // moduleName referring to the same dependency module.
714 //
715 // It does not matter whether the moduleName is a fully qualified name or if the module
716 // dependency is a prebuilt module. All that matters is the same information is supplied to
717 // create the tag here as was supplied to create the tag when the dependency was added so that
718 // this finds the matching dependency module.
719 expectedTag := sourceOrOutputDepTag(moduleName, tag)
720 ctx.VisitDirectDepsProxyWithTag(expectedTag, func(module ModuleProxy) {
721 found = &module
722 })
723 return found
724}
725
726// Deprecated: use GetModuleProxyFromPathDep
Paul Duffind5cf92e2021-07-09 17:38:55 +0100727func GetModuleFromPathDep(ctx ModuleWithDepsPathContext, moduleName, tag string) blueprint.Module {
Paul Duffin40131a32021-07-09 17:10:35 +0100728 var found blueprint.Module
729 // The sourceOrOutputDepTag uniquely identifies the module dependency as it contains both the
730 // module name and the tag. Dependencies added automatically for properties tagged with
731 // `android:"path"` are deduped so are guaranteed to be unique. It is possible for duplicate
732 // dependencies to be added manually using ExtractSourcesDeps or ExtractSourceDeps but even then
733 // it will always be the case that the dependencies will be identical, i.e. the same tag and same
734 // moduleName referring to the same dependency module.
735 //
736 // It does not matter whether the moduleName is a fully qualified name or if the module
737 // dependency is a prebuilt module. All that matters is the same information is supplied to
738 // create the tag here as was supplied to create the tag when the dependency was added so that
739 // this finds the matching dependency module.
740 expectedTag := sourceOrOutputDepTag(moduleName, tag)
Colin Cross648daea2024-09-12 14:35:29 -0700741 ctx.VisitDirectDeps(func(module Module) {
Paul Duffin40131a32021-07-09 17:10:35 +0100742 depTag := ctx.OtherModuleDependencyTag(module)
743 if depTag == expectedTag {
744 found = module
745 }
746 })
747 return found
Paul Duffind5cf92e2021-07-09 17:38:55 +0100748}
749
Liz Kammer620dea62021-04-14 17:36:10 -0400750// PathsAndMissingDepsForModuleSrcExcludes returns a Paths{} containing the resolved references in
751// paths, minus those listed in excludes. Elements of paths and excludes are resolved as:
Colin Crossd079e0b2022-08-16 10:27:33 -0700752// - filepath, relative to local module directory, resolves as a filepath relative to the local
753// source directory
754// - glob, relative to the local module directory, resolves as filepath(s), relative to the local
755// source directory. Not valid in excludes.
756// - other modules using the ":name{.tag}" syntax. These modules must implement SourceFileProducer
mrziwangd38e63d2024-07-15 13:43:37 -0700757// or set the OutputFilesProvider. These resolve as a filepath to an output filepath or generated
758// source filepath.
Colin Crossd079e0b2022-08-16 10:27:33 -0700759//
Liz Kammer620dea62021-04-14 17:36:10 -0400760// and a list of the module names of missing module dependencies are returned as the second return.
761// Properties passed as the paths argument must have been annotated with struct tag
Colin Cross41955e82019-05-29 14:40:35 -0700762// `android:"path"` so that dependencies on SourceFileProducer modules will have already been handled by the
Spandan Das950091c2023-07-19 22:26:37 +0000763// pathdeps mutator.
Liz Kammer619be462022-01-28 15:13:39 -0500764func PathsAndMissingDepsForModuleSrcExcludes(ctx ModuleMissingDepsPathContext, paths, excludes []string) (Paths, []string) {
765 return PathsAndMissingDepsRelativeToModuleSourceDir(SourceInput{
766 Context: ctx,
767 Paths: paths,
768 ExcludePaths: excludes,
769 IncludeDirs: true,
770 })
771}
772
773func PathsAndMissingDepsRelativeToModuleSourceDir(input SourceInput) (Paths, []string) {
774 prefix := pathForModuleSrc(input.Context).String()
Colin Cross8a497952019-03-05 22:25:09 -0800775
776 var expandedExcludes []string
Liz Kammer619be462022-01-28 15:13:39 -0500777 if input.ExcludePaths != nil {
778 expandedExcludes = make([]string, 0, len(input.ExcludePaths))
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700779 }
Colin Cross8a497952019-03-05 22:25:09 -0800780
Colin Crossba71a3f2019-03-18 12:12:48 -0700781 var missingExcludeDeps []string
Liz Kammer619be462022-01-28 15:13:39 -0500782 for _, e := range input.ExcludePaths {
Colin Cross41955e82019-05-29 14:40:35 -0700783 if m, t := SrcIsModuleWithTag(e); m != "" {
Liz Kammer619be462022-01-28 15:13:39 -0500784 modulePaths, err := getPathsFromModuleDep(input.Context, e, m, t)
Liz Kammera830f3a2020-11-10 10:50:34 -0800785 if m, ok := err.(missingDependencyError); ok {
786 missingExcludeDeps = append(missingExcludeDeps, m.missingDeps...)
787 } else if err != nil {
Liz Kammer619be462022-01-28 15:13:39 -0500788 reportPathError(input.Context, err)
Colin Cross8a497952019-03-05 22:25:09 -0800789 } else {
Liz Kammera830f3a2020-11-10 10:50:34 -0800790 expandedExcludes = append(expandedExcludes, modulePaths.Strings()...)
Colin Cross8a497952019-03-05 22:25:09 -0800791 }
792 } else {
793 expandedExcludes = append(expandedExcludes, filepath.Join(prefix, e))
794 }
795 }
796
Liz Kammer619be462022-01-28 15:13:39 -0500797 if input.Paths == nil {
Colin Crossba71a3f2019-03-18 12:12:48 -0700798 return nil, missingExcludeDeps
Colin Cross8a497952019-03-05 22:25:09 -0800799 }
800
Colin Crossba71a3f2019-03-18 12:12:48 -0700801 var missingDeps []string
802
Liz Kammer619be462022-01-28 15:13:39 -0500803 expandedSrcFiles := make(Paths, 0, len(input.Paths))
804 for _, s := range input.Paths {
805 srcFiles, err := expandOneSrcPath(sourcePathInput{
806 context: input.Context,
807 path: s,
808 expandedExcludes: expandedExcludes,
809 includeDirs: input.IncludeDirs,
810 })
Colin Cross8a497952019-03-05 22:25:09 -0800811 if depErr, ok := err.(missingDependencyError); ok {
Colin Crossba71a3f2019-03-18 12:12:48 -0700812 missingDeps = append(missingDeps, depErr.missingDeps...)
Colin Cross8a497952019-03-05 22:25:09 -0800813 } else if err != nil {
Liz Kammer619be462022-01-28 15:13:39 -0500814 reportPathError(input.Context, err)
Colin Cross8a497952019-03-05 22:25:09 -0800815 }
816 expandedSrcFiles = append(expandedSrcFiles, srcFiles...)
817 }
Colin Crossba71a3f2019-03-18 12:12:48 -0700818
Jihoon Kang0e3a5352024-04-12 00:45:50 +0000819 // TODO: b/334169722 - Replace with an error instead of implicitly removing duplicates.
820 return FirstUniquePaths(expandedSrcFiles), append(missingDeps, missingExcludeDeps...)
Colin Cross8a497952019-03-05 22:25:09 -0800821}
822
823type missingDependencyError struct {
824 missingDeps []string
825}
826
827func (e missingDependencyError) Error() string {
828 return "missing dependencies: " + strings.Join(e.missingDeps, ", ")
829}
830
Liz Kammer619be462022-01-28 15:13:39 -0500831type sourcePathInput struct {
832 context ModuleWithDepsPathContext
833 path string
834 expandedExcludes []string
835 includeDirs bool
836}
837
Liz Kammera830f3a2020-11-10 10:50:34 -0800838// Expands one path string to Paths rooted from the module's local source
839// directory, excluding those listed in the expandedExcludes.
840// Expands globs, references to SourceFileProducer or OutputFileProducer modules using the ":name" and ":name{.tag}" syntax.
Liz Kammer619be462022-01-28 15:13:39 -0500841func expandOneSrcPath(input sourcePathInput) (Paths, error) {
Jooyung Han7607dd32020-07-05 10:23:14 +0900842 excludePaths := func(paths Paths) Paths {
Liz Kammer619be462022-01-28 15:13:39 -0500843 if len(input.expandedExcludes) == 0 {
Jooyung Han7607dd32020-07-05 10:23:14 +0900844 return paths
845 }
846 remainder := make(Paths, 0, len(paths))
847 for _, p := range paths {
Liz Kammer619be462022-01-28 15:13:39 -0500848 if !InList(p.String(), input.expandedExcludes) {
Jooyung Han7607dd32020-07-05 10:23:14 +0900849 remainder = append(remainder, p)
850 }
851 }
852 return remainder
853 }
Liz Kammer619be462022-01-28 15:13:39 -0500854 if m, t := SrcIsModuleWithTag(input.path); m != "" {
855 modulePaths, err := getPathsFromModuleDep(input.context, input.path, m, t)
Liz Kammera830f3a2020-11-10 10:50:34 -0800856 if err != nil {
857 return nil, err
Colin Cross8a497952019-03-05 22:25:09 -0800858 } else {
Liz Kammera830f3a2020-11-10 10:50:34 -0800859 return excludePaths(modulePaths), nil
Colin Cross8a497952019-03-05 22:25:09 -0800860 }
Colin Cross8a497952019-03-05 22:25:09 -0800861 } else {
Liz Kammer619be462022-01-28 15:13:39 -0500862 p := pathForModuleSrc(input.context, input.path)
863 if pathtools.IsGlob(input.path) {
864 paths := GlobFiles(input.context, p.String(), input.expandedExcludes)
865 return PathsWithModuleSrcSubDir(input.context, paths, ""), nil
866 } else {
867 if exists, _, err := input.context.Config().fs.Exists(p.String()); err != nil {
868 ReportPathErrorf(input.context, "%s: %s", p, err.Error())
869 } else if !exists && !input.context.Config().TestAllowNonExistentPaths {
870 ReportPathErrorf(input.context, "module source path %q does not exist", p)
871 } else if !input.includeDirs {
872 if isDir, err := input.context.Config().fs.IsDir(p.String()); exists && err != nil {
873 ReportPathErrorf(input.context, "%s: %s", p, err.Error())
874 } else if isDir {
875 ReportPathErrorf(input.context, "module source path %q is a directory", p)
876 }
877 }
Colin Cross8a497952019-03-05 22:25:09 -0800878
Liz Kammer619be462022-01-28 15:13:39 -0500879 if InList(p.String(), input.expandedExcludes) {
880 return nil, nil
881 }
882 return Paths{p}, nil
Colin Cross8a497952019-03-05 22:25:09 -0800883 }
Colin Cross8a497952019-03-05 22:25:09 -0800884 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700885}
886
887// pathsForModuleSrcFromFullPath returns Paths rooted from the module's local
888// source directory, but strip the local source directory from the beginning of
Dan Willemsen540a78c2018-02-26 21:50:08 -0800889// each string. If incDirs is false, strip paths with a trailing '/' from the list.
Colin Crossfe4bc362018-09-12 10:02:13 -0700890// It intended for use in globs that only list files that exist, so it allows '$' in
891// filenames.
Liz Kammera830f3a2020-11-10 10:50:34 -0800892func pathsForModuleSrcFromFullPath(ctx EarlyModulePathContext, paths []string, incDirs bool) Paths {
Lukacs T. Berkif7e36d82021-08-16 17:05:09 +0200893 prefix := ctx.ModuleDir() + "/"
Colin Cross0f37af02017-09-27 17:42:05 -0700894 if prefix == "./" {
895 prefix = ""
896 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700897 ret := make(Paths, 0, len(paths))
898 for _, p := range paths {
Dan Willemsen540a78c2018-02-26 21:50:08 -0800899 if !incDirs && strings.HasSuffix(p, "/") {
900 continue
901 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700902 path := filepath.Clean(p)
903 if !strings.HasPrefix(path, prefix) {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +0100904 ReportPathErrorf(ctx, "Path %q is not in module source directory %q", p, prefix)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700905 continue
906 }
Colin Crosse3924e12018-08-15 20:18:53 -0700907
Colin Crossfe4bc362018-09-12 10:02:13 -0700908 srcPath, err := safePathForSource(ctx, ctx.ModuleDir(), path[len(prefix):])
Colin Crosse3924e12018-08-15 20:18:53 -0700909 if err != nil {
910 reportPathError(ctx, err)
911 continue
912 }
913
Colin Cross07e51612019-03-05 12:46:40 -0800914 srcPath.basePath.rel = srcPath.path
Colin Crosse3924e12018-08-15 20:18:53 -0700915
Colin Cross07e51612019-03-05 12:46:40 -0800916 ret = append(ret, srcPath)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700917 }
918 return ret
919}
920
Liz Kammera830f3a2020-11-10 10:50:34 -0800921// PathsWithOptionalDefaultForModuleSrc returns Paths rooted from the module's local source
922// directory. If input is nil, use the default if it exists. If input is empty, returns nil.
923func PathsWithOptionalDefaultForModuleSrc(ctx ModuleMissingDepsPathContext, input []string, def string) Paths {
Colin Cross0ddae7f2019-02-07 15:30:01 -0800924 if input != nil {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700925 return PathsForModuleSrc(ctx, input)
926 }
927 // Use Glob so that if the default doesn't exist, a dependency is added so that when it
928 // is created, we're run again.
Lukacs T. Berkif7e36d82021-08-16 17:05:09 +0200929 path := filepath.Join(ctx.ModuleDir(), def)
Liz Kammera830f3a2020-11-10 10:50:34 -0800930 return Glob(ctx, path, nil)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700931}
932
933// Strings returns the Paths in string form
934func (p Paths) Strings() []string {
935 if p == nil {
936 return nil
937 }
938 ret := make([]string, len(p))
939 for i, path := range p {
940 ret[i] = path.String()
941 }
942 return ret
943}
944
Colin Crossc0efd1d2020-07-03 11:56:24 -0700945func CopyOfPaths(paths Paths) Paths {
946 return append(Paths(nil), paths...)
947}
948
Colin Crossb6715442017-10-24 11:13:31 -0700949// FirstUniquePaths returns all unique elements of a Paths, keeping the first copy of each. It
950// modifies the Paths slice contents in place, and returns a subslice of the original slice.
Dan Willemsenfe92c962017-08-29 12:28:37 -0700951func FirstUniquePaths(list Paths) Paths {
Colin Cross27027c72020-02-28 15:34:17 -0800952 // 128 was chosen based on BenchmarkFirstUniquePaths results.
953 if len(list) > 128 {
954 return firstUniquePathsMap(list)
955 }
956 return firstUniquePathsList(list)
957}
958
Colin Crossc0efd1d2020-07-03 11:56:24 -0700959// SortedUniquePaths returns all unique elements of a Paths in sorted order. It modifies the
960// Paths slice contents in place, and returns a subslice of the original slice.
Jiyong Park33c77362020-05-29 22:00:16 +0900961func SortedUniquePaths(list Paths) Paths {
962 unique := FirstUniquePaths(list)
963 sort.Slice(unique, func(i, j int) bool {
964 return unique[i].String() < unique[j].String()
965 })
966 return unique
967}
968
Colin Cross27027c72020-02-28 15:34:17 -0800969func firstUniquePathsList(list Paths) Paths {
Dan Willemsenfe92c962017-08-29 12:28:37 -0700970 k := 0
971outer:
972 for i := 0; i < len(list); i++ {
973 for j := 0; j < k; j++ {
974 if list[i] == list[j] {
975 continue outer
976 }
977 }
978 list[k] = list[i]
979 k++
980 }
981 return list[:k]
982}
983
Colin Cross27027c72020-02-28 15:34:17 -0800984func firstUniquePathsMap(list Paths) Paths {
985 k := 0
986 seen := make(map[Path]bool, len(list))
987 for i := 0; i < len(list); i++ {
988 if seen[list[i]] {
989 continue
990 }
991 seen[list[i]] = true
992 list[k] = list[i]
993 k++
994 }
995 return list[:k]
996}
997
Colin Cross5d583952020-11-24 16:21:24 -0800998// FirstUniqueInstallPaths returns all unique elements of an InstallPaths, keeping the first copy of each. It
999// modifies the InstallPaths slice contents in place, and returns a subslice of the original slice.
1000func FirstUniqueInstallPaths(list InstallPaths) InstallPaths {
1001 // 128 was chosen based on BenchmarkFirstUniquePaths results.
1002 if len(list) > 128 {
1003 return firstUniqueInstallPathsMap(list)
1004 }
1005 return firstUniqueInstallPathsList(list)
1006}
1007
1008func firstUniqueInstallPathsList(list InstallPaths) InstallPaths {
1009 k := 0
1010outer:
1011 for i := 0; i < len(list); i++ {
1012 for j := 0; j < k; j++ {
1013 if list[i] == list[j] {
1014 continue outer
1015 }
1016 }
1017 list[k] = list[i]
1018 k++
1019 }
1020 return list[:k]
1021}
1022
1023func firstUniqueInstallPathsMap(list InstallPaths) InstallPaths {
1024 k := 0
1025 seen := make(map[InstallPath]bool, len(list))
1026 for i := 0; i < len(list); i++ {
1027 if seen[list[i]] {
1028 continue
1029 }
1030 seen[list[i]] = true
1031 list[k] = list[i]
1032 k++
1033 }
1034 return list[:k]
1035}
1036
Colin Crossb6715442017-10-24 11:13:31 -07001037// LastUniquePaths returns all unique elements of a Paths, keeping the last copy of each. It
1038// modifies the Paths slice contents in place, and returns a subslice of the original slice.
1039func LastUniquePaths(list Paths) Paths {
1040 totalSkip := 0
1041 for i := len(list) - 1; i >= totalSkip; i-- {
1042 skip := 0
1043 for j := i - 1; j >= totalSkip; j-- {
1044 if list[i] == list[j] {
1045 skip++
1046 } else {
1047 list[j+skip] = list[j]
1048 }
1049 }
1050 totalSkip += skip
1051 }
1052 return list[totalSkip:]
1053}
1054
Colin Crossa140bb02018-04-17 10:52:26 -07001055// ReversePaths returns a copy of a Paths in reverse order.
1056func ReversePaths(list Paths) Paths {
1057 if list == nil {
1058 return nil
1059 }
1060 ret := make(Paths, len(list))
1061 for i := range list {
1062 ret[i] = list[len(list)-1-i]
1063 }
1064 return ret
1065}
1066
Jeff Gaston294356f2017-09-27 17:05:30 -07001067func indexPathList(s Path, list []Path) int {
1068 for i, l := range list {
1069 if l == s {
1070 return i
1071 }
1072 }
1073
1074 return -1
1075}
1076
1077func inPathList(p Path, list []Path) bool {
1078 return indexPathList(p, list) != -1
1079}
1080
1081func FilterPathList(list []Path, filter []Path) (remainder []Path, filtered []Path) {
Paul Duffin57b9e1d2019-12-13 00:03:35 +00001082 return FilterPathListPredicate(list, func(p Path) bool { return inPathList(p, filter) })
1083}
1084
1085func FilterPathListPredicate(list []Path, predicate func(Path) bool) (remainder []Path, filtered []Path) {
Jeff Gaston294356f2017-09-27 17:05:30 -07001086 for _, l := range list {
Paul Duffin57b9e1d2019-12-13 00:03:35 +00001087 if predicate(l) {
Jeff Gaston294356f2017-09-27 17:05:30 -07001088 filtered = append(filtered, l)
1089 } else {
1090 remainder = append(remainder, l)
1091 }
1092 }
1093
1094 return
1095}
1096
Colin Cross93e85952017-08-15 13:34:18 -07001097// HasExt returns true of any of the paths have extension ext, otherwise false
1098func (p Paths) HasExt(ext string) bool {
1099 for _, path := range p {
1100 if path.Ext() == ext {
1101 return true
1102 }
1103 }
1104
1105 return false
1106}
1107
1108// FilterByExt returns the subset of the paths that have extension ext
1109func (p Paths) FilterByExt(ext string) Paths {
1110 ret := make(Paths, 0, len(p))
1111 for _, path := range p {
1112 if path.Ext() == ext {
1113 ret = append(ret, path)
1114 }
1115 }
1116 return ret
1117}
1118
1119// FilterOutByExt returns the subset of the paths that do not have extension ext
1120func (p Paths) FilterOutByExt(ext string) Paths {
1121 ret := make(Paths, 0, len(p))
1122 for _, path := range p {
1123 if path.Ext() != ext {
1124 ret = append(ret, path)
1125 }
1126 }
1127 return ret
1128}
1129
Colin Cross5e6cfbe2017-11-03 15:20:35 -07001130// DirectorySortedPaths is a slice of paths that are sorted such that all files in a directory
1131// (including subdirectories) are in a contiguous subslice of the list, and can be found in
1132// O(log(N)) time using a binary search on the directory prefix.
1133type DirectorySortedPaths Paths
1134
1135func PathsToDirectorySortedPaths(paths Paths) DirectorySortedPaths {
1136 ret := append(DirectorySortedPaths(nil), paths...)
1137 sort.Slice(ret, func(i, j int) bool {
1138 return ret[i].String() < ret[j].String()
1139 })
1140 return ret
1141}
1142
1143// PathsInDirectory returns a subslice of the DirectorySortedPaths as a Paths that contains all entries
1144// that are in the specified directory and its subdirectories.
1145func (p DirectorySortedPaths) PathsInDirectory(dir string) Paths {
1146 prefix := filepath.Clean(dir) + "/"
1147 start := sort.Search(len(p), func(i int) bool {
1148 return prefix < p[i].String()
1149 })
1150
1151 ret := p[start:]
1152
1153 end := sort.Search(len(ret), func(i int) bool {
1154 return !strings.HasPrefix(ret[i].String(), prefix)
1155 })
1156
1157 ret = ret[:end]
1158
1159 return Paths(ret)
1160}
1161
Alex Humesky29e3bbe2020-11-20 21:30:13 -05001162// WritablePaths is a slice of WritablePath, used for multiple outputs.
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001163type WritablePaths []WritablePath
1164
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001165// RelativeToTop creates a new WritablePaths containing the result of calling Path.RelativeToTop on
1166// each item in this slice.
1167func (p WritablePaths) RelativeToTop() WritablePaths {
1168 ensureTestOnly()
1169 if p == nil {
1170 return p
1171 }
1172 ret := make(WritablePaths, len(p))
1173 for i, path := range p {
1174 ret[i] = path.RelativeToTop().(WritablePath)
1175 }
1176 return ret
1177}
1178
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001179// Strings returns the string forms of the writable paths.
1180func (p WritablePaths) Strings() []string {
1181 if p == nil {
1182 return nil
1183 }
1184 ret := make([]string, len(p))
1185 for i, path := range p {
1186 ret[i] = path.String()
1187 }
1188 return ret
1189}
1190
Colin Cross3bc7ffa2017-11-22 16:19:37 -08001191// Paths returns the WritablePaths as a Paths
1192func (p WritablePaths) Paths() Paths {
1193 if p == nil {
1194 return nil
1195 }
1196 ret := make(Paths, len(p))
1197 for i, path := range p {
1198 ret[i] = path
1199 }
1200 return ret
1201}
1202
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001203type basePath struct {
Paul Duffin74abc5d2021-03-24 09:24:59 +00001204 path string
1205 rel string
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001206}
1207
Yu Liu467d7c52024-09-18 21:54:44 +00001208type basePathGob struct {
1209 Path string
1210 Rel string
1211}
Yu Liufa297642024-06-11 00:13:02 +00001212
Yu Liu467d7c52024-09-18 21:54:44 +00001213func (p *basePath) ToGob() *basePathGob {
1214 return &basePathGob{
1215 Path: p.path,
1216 Rel: p.rel,
1217 }
1218}
1219
1220func (p *basePath) FromGob(data *basePathGob) {
1221 p.path = data.Path
1222 p.rel = data.Rel
1223}
1224
1225func (p basePath) GobEncode() ([]byte, error) {
Yu Liu3cadf7d2024-10-24 18:47:06 +00001226 return gobtools.CustomGobEncode[basePathGob](&p)
Yu Liufa297642024-06-11 00:13:02 +00001227}
1228
1229func (p *basePath) GobDecode(data []byte) error {
Yu Liu3cadf7d2024-10-24 18:47:06 +00001230 return gobtools.CustomGobDecode[basePathGob](data, p)
Yu Liufa297642024-06-11 00:13:02 +00001231}
1232
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001233func (p basePath) Ext() string {
1234 return filepath.Ext(p.path)
1235}
1236
Colin Cross4f6fc9c2016-10-26 10:05:25 -07001237func (p basePath) Base() string {
1238 return filepath.Base(p.path)
1239}
1240
Colin Crossfaeb7aa2017-02-01 14:12:44 -08001241func (p basePath) Rel() string {
1242 if p.rel != "" {
1243 return p.rel
1244 }
1245 return p.path
1246}
1247
Colin Cross0875c522017-11-28 17:34:01 -08001248func (p basePath) String() string {
1249 return p.path
1250}
1251
Colin Cross0db55682017-12-05 15:36:55 -08001252func (p basePath) withRel(rel string) basePath {
1253 p.path = filepath.Join(p.path, rel)
1254 p.rel = rel
1255 return p
1256}
1257
Colin Cross7707b242024-07-26 12:02:36 -07001258func (p basePath) withoutRel() basePath {
1259 p.rel = filepath.Base(p.path)
1260 return p
1261}
1262
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001263// SourcePath is a Path representing a file path rooted from SrcDir
1264type SourcePath struct {
1265 basePath
1266}
1267
1268var _ Path = SourcePath{}
1269
Colin Cross0db55682017-12-05 15:36:55 -08001270func (p SourcePath) withRel(rel string) SourcePath {
1271 p.basePath = p.basePath.withRel(rel)
1272 return p
1273}
1274
Colin Crossbd73d0d2024-07-26 12:00:33 -07001275func (p SourcePath) RelativeToTop() Path {
1276 ensureTestOnly()
1277 return p
1278}
1279
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001280// safePathForSource is for paths that we expect are safe -- only for use by go
1281// code that is embedding ninja variables in paths
Colin Crossfe4bc362018-09-12 10:02:13 -07001282func safePathForSource(ctx PathContext, pathComponents ...string) (SourcePath, error) {
1283 p, err := validateSafePath(pathComponents...)
Cole Faust483d1f72023-01-09 14:35:27 -08001284 ret := SourcePath{basePath{p, ""}}
Colin Crossfe4bc362018-09-12 10:02:13 -07001285 if err != nil {
1286 return ret, err
1287 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001288
Colin Cross7b3dcc32019-01-24 13:14:39 -08001289 // absolute path already checked by validateSafePath
Inseob Kim5eb7ee92022-04-27 10:30:34 +09001290 // special-case api surface gen files for now
1291 if strings.HasPrefix(ret.String(), ctx.Config().soongOutDir) && !strings.Contains(ret.String(), ctx.Config().soongOutDir+"/.export") {
Mikhail Naganovab1f5182019-02-08 13:17:55 -08001292 return ret, fmt.Errorf("source path %q is in output", ret.String())
Colin Cross6e18ca42015-07-14 18:55:36 -07001293 }
1294
Colin Crossfe4bc362018-09-12 10:02:13 -07001295 return ret, err
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001296}
1297
Colin Cross192e97a2018-02-22 14:21:02 -08001298// pathForSource creates a SourcePath from pathComponents, but does not check that it exists.
1299func pathForSource(ctx PathContext, pathComponents ...string) (SourcePath, error) {
Colin Crossc48c1432018-02-23 07:09:01 +00001300 p, err := validatePath(pathComponents...)
Cole Faust483d1f72023-01-09 14:35:27 -08001301 ret := SourcePath{basePath{p, ""}}
Colin Cross94a32102018-02-22 14:21:02 -08001302 if err != nil {
Colin Cross192e97a2018-02-22 14:21:02 -08001303 return ret, err
Colin Cross94a32102018-02-22 14:21:02 -08001304 }
1305
Colin Cross7b3dcc32019-01-24 13:14:39 -08001306 // absolute path already checked by validatePath
Inseob Kim5eb7ee92022-04-27 10:30:34 +09001307 // special-case for now
1308 if strings.HasPrefix(ret.String(), ctx.Config().soongOutDir) && !strings.Contains(ret.String(), ctx.Config().soongOutDir+"/.export") {
Mikhail Naganovab1f5182019-02-08 13:17:55 -08001309 return ret, fmt.Errorf("source path %q is in output", ret.String())
Colin Crossc48c1432018-02-23 07:09:01 +00001310 }
1311
Colin Cross192e97a2018-02-22 14:21:02 -08001312 return ret, nil
1313}
1314
1315// existsWithDependencies returns true if the path exists, and adds appropriate dependencies to rerun if the
1316// path does not exist.
Colin Cross662d6142022-11-03 20:38:01 -07001317func existsWithDependencies(ctx PathGlobContext, path SourcePath) (exists bool, err error) {
Colin Cross192e97a2018-02-22 14:21:02 -08001318 var files []string
1319
Colin Cross662d6142022-11-03 20:38:01 -07001320 // Use glob to produce proper dependencies, even though we only want
1321 // a single file.
1322 files, err = ctx.GlobWithDeps(path.String(), nil)
Colin Cross192e97a2018-02-22 14:21:02 -08001323
1324 if err != nil {
1325 return false, fmt.Errorf("glob: %s", err.Error())
1326 }
1327
1328 return len(files) > 0, nil
1329}
1330
1331// PathForSource joins the provided path components and validates that the result
1332// neither escapes the source dir nor is in the out dir.
1333// On error, it will return a usable, but invalid SourcePath, and report a ModuleError.
1334func PathForSource(ctx PathContext, pathComponents ...string) SourcePath {
1335 path, err := pathForSource(ctx, pathComponents...)
1336 if err != nil {
1337 reportPathError(ctx, err)
1338 }
1339
Colin Crosse3924e12018-08-15 20:18:53 -07001340 if pathtools.IsGlob(path.String()) {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001341 ReportPathErrorf(ctx, "path may not contain a glob: %s", path.String())
Colin Crosse3924e12018-08-15 20:18:53 -07001342 }
1343
Liz Kammera830f3a2020-11-10 10:50:34 -08001344 if modCtx, ok := ctx.(ModuleMissingDepsPathContext); ok && ctx.Config().AllowMissingDependencies() {
Colin Cross662d6142022-11-03 20:38:01 -07001345 exists, err := existsWithDependencies(modCtx, path)
Colin Cross192e97a2018-02-22 14:21:02 -08001346 if err != nil {
1347 reportPathError(ctx, err)
1348 }
1349 if !exists {
1350 modCtx.AddMissingDependencies([]string{path.String()})
1351 }
Colin Cross988414c2020-01-11 01:11:46 +00001352 } else if exists, _, err := ctx.Config().fs.Exists(path.String()); err != nil {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001353 ReportPathErrorf(ctx, "%s: %s", path, err.Error())
Pedro Loureiro5d190cc2021-02-15 15:41:33 +00001354 } else if !exists && !ctx.Config().TestAllowNonExistentPaths {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001355 ReportPathErrorf(ctx, "source path %q does not exist", path)
Colin Cross192e97a2018-02-22 14:21:02 -08001356 }
1357 return path
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001358}
1359
Cole Faustbc65a3f2023-08-01 16:38:55 +00001360// PathForArbitraryOutput creates a path for the given components. Unlike PathForOutput,
1361// the path is relative to the root of the output folder, not the out/soong folder.
Cole Faustaddc0dd2024-12-16 16:19:17 -08001362func PathForArbitraryOutput(ctx PathContext, pathComponents ...string) WritablePath {
Colin Cross3b1c6842024-07-26 11:52:57 -07001363 path, err := validatePath(pathComponents...)
Cole Faustbc65a3f2023-08-01 16:38:55 +00001364 if err != nil {
1365 reportPathError(ctx, err)
1366 }
Colin Cross3b1c6842024-07-26 11:52:57 -07001367 fullPath := filepath.Join(ctx.Config().OutDir(), path)
1368 path = fullPath[len(fullPath)-len(path):]
1369 return OutputPath{basePath{path, ""}, ctx.Config().OutDir(), fullPath}
Cole Faustbc65a3f2023-08-01 16:38:55 +00001370}
1371
Spandan Dasc6c10fa2022-10-21 21:52:13 +00001372// MaybeExistentPathForSource joins the provided path components and validates that the result
1373// neither escapes the source dir nor is in the out dir.
1374// It does not validate whether the path exists.
1375func MaybeExistentPathForSource(ctx PathContext, pathComponents ...string) SourcePath {
1376 path, err := pathForSource(ctx, pathComponents...)
1377 if err != nil {
1378 reportPathError(ctx, err)
1379 }
1380
1381 if pathtools.IsGlob(path.String()) {
1382 ReportPathErrorf(ctx, "path may not contain a glob: %s", path.String())
1383 }
1384 return path
1385}
1386
Liz Kammer7aa52882021-02-11 09:16:14 -05001387// ExistentPathForSource returns an OptionalPath with the SourcePath, rooted from SrcDir, *not*
1388// rooted from the module's local source directory, if the path exists, or an empty OptionalPath if
1389// it doesn't exist. Dependencies are added so that the ninja file will be regenerated if the state
1390// of the path changes.
Colin Cross662d6142022-11-03 20:38:01 -07001391func ExistentPathForSource(ctx PathGlobContext, pathComponents ...string) OptionalPath {
Colin Cross192e97a2018-02-22 14:21:02 -08001392 path, err := pathForSource(ctx, pathComponents...)
Colin Cross1ccfcc32018-02-22 13:54:26 -08001393 if err != nil {
1394 reportPathError(ctx, err)
Martin Stjernholmc32dd1c2021-09-15 02:39:00 +01001395 // No need to put the error message into the returned path since it has been reported already.
Colin Cross1ccfcc32018-02-22 13:54:26 -08001396 return OptionalPath{}
1397 }
Colin Crossc48c1432018-02-23 07:09:01 +00001398
Colin Crosse3924e12018-08-15 20:18:53 -07001399 if pathtools.IsGlob(path.String()) {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001400 ReportPathErrorf(ctx, "path may not contain a glob: %s", path.String())
Colin Crosse3924e12018-08-15 20:18:53 -07001401 return OptionalPath{}
1402 }
1403
Colin Cross192e97a2018-02-22 14:21:02 -08001404 exists, err := existsWithDependencies(ctx, path)
Colin Crossc48c1432018-02-23 07:09:01 +00001405 if err != nil {
1406 reportPathError(ctx, err)
1407 return OptionalPath{}
1408 }
Colin Cross192e97a2018-02-22 14:21:02 -08001409 if !exists {
Martin Stjernholmc32dd1c2021-09-15 02:39:00 +01001410 return InvalidOptionalPath(path.String() + " does not exist")
Colin Crossc48c1432018-02-23 07:09:01 +00001411 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001412 return OptionalPathForPath(path)
1413}
1414
1415func (p SourcePath) String() string {
Cole Faust483d1f72023-01-09 14:35:27 -08001416 if p.path == "" {
1417 return "."
1418 }
1419 return p.path
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001420}
1421
Colin Cross7707b242024-07-26 12:02:36 -07001422func (p SourcePath) WithoutRel() Path {
1423 p.basePath = p.basePath.withoutRel()
1424 return p
1425}
1426
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001427// Join creates a new SourcePath with paths... joined with the current path. The
1428// provided paths... may not use '..' to escape from the current path.
1429func (p SourcePath) Join(ctx PathContext, paths ...string) SourcePath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001430 path, err := validatePath(paths...)
1431 if err != nil {
1432 reportPathError(ctx, err)
1433 }
Colin Cross0db55682017-12-05 15:36:55 -08001434 return p.withRel(path)
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001435}
1436
Colin Cross2fafa3e2019-03-05 12:39:51 -08001437// join is like Join but does less path validation.
1438func (p SourcePath) join(ctx PathContext, paths ...string) SourcePath {
1439 path, err := validateSafePath(paths...)
1440 if err != nil {
1441 reportPathError(ctx, err)
1442 }
1443 return p.withRel(path)
1444}
1445
Colin Cross70dda7e2019-10-01 22:05:35 -07001446// OutputPath is a Path representing an intermediates file path rooted from the build directory
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001447type OutputPath struct {
1448 basePath
Paul Duffind65c58b2021-03-24 09:22:07 +00001449
Colin Cross3b1c6842024-07-26 11:52:57 -07001450 // The base out directory for this path, either Config.SoongOutDir() or Config.OutDir()
1451 outDir string
Paul Duffind65c58b2021-03-24 09:22:07 +00001452
Colin Crossd63c9a72020-01-29 16:52:50 -08001453 fullPath string
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001454}
1455
Yu Liu467d7c52024-09-18 21:54:44 +00001456type outputPathGob struct {
Yu Liu5246a7e2024-10-09 20:04:52 +00001457 BasePath basePath
Yu Liu467d7c52024-09-18 21:54:44 +00001458 OutDir string
1459 FullPath string
1460}
Yu Liufa297642024-06-11 00:13:02 +00001461
Yu Liu467d7c52024-09-18 21:54:44 +00001462func (p *OutputPath) ToGob() *outputPathGob {
1463 return &outputPathGob{
Yu Liu5246a7e2024-10-09 20:04:52 +00001464 BasePath: p.basePath,
Yu Liu467d7c52024-09-18 21:54:44 +00001465 OutDir: p.outDir,
1466 FullPath: p.fullPath,
1467 }
1468}
1469
1470func (p *OutputPath) FromGob(data *outputPathGob) {
Yu Liu5246a7e2024-10-09 20:04:52 +00001471 p.basePath = data.BasePath
Yu Liu467d7c52024-09-18 21:54:44 +00001472 p.outDir = data.OutDir
1473 p.fullPath = data.FullPath
1474}
1475
1476func (p OutputPath) GobEncode() ([]byte, error) {
Yu Liu3cadf7d2024-10-24 18:47:06 +00001477 return gobtools.CustomGobEncode[outputPathGob](&p)
Yu Liufa297642024-06-11 00:13:02 +00001478}
1479
1480func (p *OutputPath) GobDecode(data []byte) error {
Yu Liu3cadf7d2024-10-24 18:47:06 +00001481 return gobtools.CustomGobDecode[outputPathGob](data, p)
Yu Liufa297642024-06-11 00:13:02 +00001482}
1483
Colin Cross702e0f82017-10-18 17:27:54 -07001484func (p OutputPath) withRel(rel string) OutputPath {
Colin Cross0db55682017-12-05 15:36:55 -08001485 p.basePath = p.basePath.withRel(rel)
Colin Crossd63c9a72020-01-29 16:52:50 -08001486 p.fullPath = filepath.Join(p.fullPath, rel)
Colin Cross702e0f82017-10-18 17:27:54 -07001487 return p
1488}
1489
Colin Cross7707b242024-07-26 12:02:36 -07001490func (p OutputPath) WithoutRel() Path {
1491 p.basePath = p.basePath.withoutRel()
Colin Cross3063b782018-08-15 11:19:12 -07001492 return p
1493}
1494
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02001495func (p OutputPath) getSoongOutDir() string {
Colin Cross3b1c6842024-07-26 11:52:57 -07001496 return p.outDir
Paul Duffin9b478b02019-12-10 13:41:51 +00001497}
1498
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001499func (p OutputPath) RelativeToTop() Path {
1500 return p.outputPathRelativeToTop()
1501}
1502
1503func (p OutputPath) outputPathRelativeToTop() OutputPath {
Colin Cross3b1c6842024-07-26 11:52:57 -07001504 p.fullPath = StringPathRelativeToTop(p.outDir, p.fullPath)
1505 if strings.HasSuffix(p.outDir, testOutSoongSubDir) {
1506 p.outDir = TestOutSoongDir
1507 } else {
1508 // Handle the PathForArbitraryOutput case
1509 p.outDir = testOutDir
1510 }
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001511 return p
1512}
1513
Paul Duffin0267d492021-02-02 10:05:52 +00001514func (p OutputPath) objPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleObjPath {
1515 return PathForModuleObj(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
1516}
1517
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001518var _ Path = OutputPath{}
Paul Duffin9b478b02019-12-10 13:41:51 +00001519var _ WritablePath = OutputPath{}
Paul Duffin0267d492021-02-02 10:05:52 +00001520var _ objPathProvider = OutputPath{}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001521
Chris Parsons8f232a22020-06-23 17:37:05 -04001522// toolDepPath is a Path representing a dependency of the build tool.
1523type toolDepPath struct {
1524 basePath
1525}
1526
Colin Cross7707b242024-07-26 12:02:36 -07001527func (t toolDepPath) WithoutRel() Path {
1528 t.basePath = t.basePath.withoutRel()
1529 return t
1530}
1531
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001532func (t toolDepPath) RelativeToTop() Path {
1533 ensureTestOnly()
1534 return t
1535}
1536
Chris Parsons8f232a22020-06-23 17:37:05 -04001537var _ Path = toolDepPath{}
1538
1539// pathForBuildToolDep returns a toolDepPath representing the given path string.
1540// There is no validation for the path, as it is "trusted": It may fail
1541// normal validation checks. For example, it may be an absolute path.
1542// Only use this function to construct paths for dependencies of the build
1543// tool invocation.
1544func pathForBuildToolDep(ctx PathContext, path string) toolDepPath {
Paul Duffin74abc5d2021-03-24 09:24:59 +00001545 return toolDepPath{basePath{path, ""}}
Chris Parsons8f232a22020-06-23 17:37:05 -04001546}
1547
Jeff Gaston734e3802017-04-10 15:47:24 -07001548// PathForOutput joins the provided paths and returns an OutputPath that is
1549// validated to not escape the build dir.
1550// On error, it will return a usable, but invalid OutputPath, and report a ModuleError.
1551func PathForOutput(ctx PathContext, pathComponents ...string) OutputPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001552 path, err := validatePath(pathComponents...)
1553 if err != nil {
1554 reportPathError(ctx, err)
1555 }
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02001556 fullPath := filepath.Join(ctx.Config().soongOutDir, path)
Colin Crossd63c9a72020-01-29 16:52:50 -08001557 path = fullPath[len(fullPath)-len(path):]
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02001558 return OutputPath{basePath{path, ""}, ctx.Config().soongOutDir, fullPath}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001559}
1560
Colin Cross3b1c6842024-07-26 11:52:57 -07001561// PathsForOutput returns Paths rooted from outDir
Colin Cross40e33732019-02-15 11:08:35 -08001562func PathsForOutput(ctx PathContext, paths []string) WritablePaths {
1563 ret := make(WritablePaths, len(paths))
1564 for i, path := range paths {
1565 ret[i] = PathForOutput(ctx, path)
1566 }
1567 return ret
1568}
1569
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001570func (p OutputPath) writablePath() {}
1571
1572func (p OutputPath) String() string {
Colin Crossd63c9a72020-01-29 16:52:50 -08001573 return p.fullPath
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001574}
1575
1576// Join creates a new OutputPath with paths... joined with the current path. The
1577// provided paths... may not use '..' to escape from the current path.
1578func (p OutputPath) Join(ctx PathContext, paths ...string) OutputPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001579 path, err := validatePath(paths...)
1580 if err != nil {
1581 reportPathError(ctx, err)
1582 }
Colin Cross0db55682017-12-05 15:36:55 -08001583 return p.withRel(path)
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001584}
1585
Colin Cross8854a5a2019-02-11 14:14:16 -08001586// ReplaceExtension creates a new OutputPath with the extension replaced with ext.
1587func (p OutputPath) ReplaceExtension(ctx PathContext, ext string) OutputPath {
1588 if strings.Contains(ext, "/") {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001589 ReportPathErrorf(ctx, "extension %q cannot contain /", ext)
Colin Cross8854a5a2019-02-11 14:14:16 -08001590 }
1591 ret := PathForOutput(ctx, pathtools.ReplaceExtension(p.path, ext))
Colin Cross2cdd5df2019-02-25 10:25:24 -08001592 ret.rel = pathtools.ReplaceExtension(p.rel, ext)
Colin Cross8854a5a2019-02-11 14:14:16 -08001593 return ret
1594}
1595
Colin Cross40e33732019-02-15 11:08:35 -08001596// InSameDir creates a new OutputPath from the directory of the current OutputPath joined with the elements in paths.
1597func (p OutputPath) InSameDir(ctx PathContext, paths ...string) OutputPath {
1598 path, err := validatePath(paths...)
1599 if err != nil {
1600 reportPathError(ctx, err)
1601 }
1602
1603 ret := PathForOutput(ctx, filepath.Dir(p.path), path)
Colin Cross2cdd5df2019-02-25 10:25:24 -08001604 ret.rel = filepath.Join(filepath.Dir(p.rel), path)
Colin Cross40e33732019-02-15 11:08:35 -08001605 return ret
1606}
1607
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001608// PathForIntermediates returns an OutputPath representing the top-level
1609// intermediates directory.
1610func PathForIntermediates(ctx PathContext, paths ...string) OutputPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001611 path, err := validatePath(paths...)
1612 if err != nil {
1613 reportPathError(ctx, err)
1614 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001615 return PathForOutput(ctx, ".intermediates", path)
1616}
1617
Colin Cross07e51612019-03-05 12:46:40 -08001618var _ genPathProvider = SourcePath{}
1619var _ objPathProvider = SourcePath{}
1620var _ resPathProvider = SourcePath{}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001621
Colin Cross07e51612019-03-05 12:46:40 -08001622// PathForModuleSrc returns a Path representing the paths... under the
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001623// module's local source directory.
Liz Kammera830f3a2020-11-10 10:50:34 -08001624func PathForModuleSrc(ctx ModuleMissingDepsPathContext, pathComponents ...string) Path {
Paul Duffin407501b2021-07-09 16:56:35 +01001625 // Just join the components textually just to make sure that it does not corrupt a fully qualified
1626 // module reference, e.g. if the pathComponents is "://other:foo" then using filepath.Join() or
1627 // validatePath() will corrupt it, e.g. replace "//" with "/". If the path is not a module
1628 // reference then it will be validated by expandOneSrcPath anyway when it calls expandOneSrcPath.
1629 p := strings.Join(pathComponents, string(filepath.Separator))
Liz Kammer619be462022-01-28 15:13:39 -05001630 paths, err := expandOneSrcPath(sourcePathInput{context: ctx, path: p, includeDirs: true})
Colin Cross8a497952019-03-05 22:25:09 -08001631 if err != nil {
1632 if depErr, ok := err.(missingDependencyError); ok {
1633 if ctx.Config().AllowMissingDependencies() {
1634 ctx.AddMissingDependencies(depErr.missingDeps)
1635 } else {
1636 ctx.ModuleErrorf(`%s, is the property annotated with android:"path"?`, depErr.Error())
1637 }
1638 } else {
1639 reportPathError(ctx, err)
1640 }
1641 return nil
1642 } else if len(paths) == 0 {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001643 ReportPathErrorf(ctx, "%q produced no files, expected exactly one", p)
Colin Cross8a497952019-03-05 22:25:09 -08001644 return nil
1645 } else if len(paths) > 1 {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001646 ReportPathErrorf(ctx, "%q produced %d files, expected exactly one", p, len(paths))
Colin Cross8a497952019-03-05 22:25:09 -08001647 }
1648 return paths[0]
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001649}
1650
Liz Kammera830f3a2020-11-10 10:50:34 -08001651func pathForModuleSrc(ctx EarlyModulePathContext, paths ...string) SourcePath {
Colin Cross07e51612019-03-05 12:46:40 -08001652 p, err := validatePath(paths...)
1653 if err != nil {
1654 reportPathError(ctx, err)
1655 }
1656
1657 path, err := pathForSource(ctx, ctx.ModuleDir(), p)
1658 if err != nil {
1659 reportPathError(ctx, err)
1660 }
1661
1662 path.basePath.rel = p
1663
1664 return path
1665}
1666
Colin Cross2fafa3e2019-03-05 12:39:51 -08001667// PathsWithModuleSrcSubDir takes a list of Paths and returns a new list of Paths where Rel() on each path
1668// will return the path relative to subDir in the module's source directory. If any input paths are not located
1669// inside subDir then a path error will be reported.
Liz Kammera830f3a2020-11-10 10:50:34 -08001670func PathsWithModuleSrcSubDir(ctx EarlyModulePathContext, paths Paths, subDir string) Paths {
Colin Cross2fafa3e2019-03-05 12:39:51 -08001671 paths = append(Paths(nil), paths...)
Colin Cross07e51612019-03-05 12:46:40 -08001672 subDirFullPath := pathForModuleSrc(ctx, subDir)
Colin Cross2fafa3e2019-03-05 12:39:51 -08001673 for i, path := range paths {
1674 rel := Rel(ctx, subDirFullPath.String(), path.String())
1675 paths[i] = subDirFullPath.join(ctx, rel)
1676 }
1677 return paths
1678}
1679
1680// PathWithModuleSrcSubDir takes a Path and returns a Path where Rel() will return the path relative to subDir in the
1681// 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 -08001682func PathWithModuleSrcSubDir(ctx EarlyModulePathContext, path Path, subDir string) Path {
Colin Cross07e51612019-03-05 12:46:40 -08001683 subDirFullPath := pathForModuleSrc(ctx, subDir)
Colin Cross2fafa3e2019-03-05 12:39:51 -08001684 rel := Rel(ctx, subDirFullPath.String(), path.String())
1685 return subDirFullPath.Join(ctx, rel)
1686}
1687
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001688// OptionalPathForModuleSrc returns an OptionalPath. The OptionalPath contains a
1689// valid path if p is non-nil.
Liz Kammera830f3a2020-11-10 10:50:34 -08001690func OptionalPathForModuleSrc(ctx ModuleMissingDepsPathContext, p *string) OptionalPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001691 if p == nil {
1692 return OptionalPath{}
1693 }
1694 return OptionalPathForPath(PathForModuleSrc(ctx, *p))
1695}
1696
Liz Kammera830f3a2020-11-10 10:50:34 -08001697func (p SourcePath) genPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleGenPath {
Colin Cross7fc17db2017-02-01 14:07:55 -08001698 return PathForModuleGen(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001699}
1700
yangbill6d032dd2024-04-18 03:05:49 +00001701func (p SourcePath) genPathWithExtAndTrimExt(ctx ModuleOutPathContext, subdir, ext string, trimExt string) ModuleGenPath {
1702 // If Trim_extension being set, force append Output_extension without replace original extension.
1703 if trimExt != "" {
1704 if ext != "" {
1705 return PathForModuleGen(ctx, subdir, strings.TrimSuffix(p.path, trimExt)+"."+ext)
1706 }
1707 return PathForModuleGen(ctx, subdir, strings.TrimSuffix(p.path, trimExt))
1708 }
1709 return PathForModuleGen(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
1710}
1711
Liz Kammera830f3a2020-11-10 10:50:34 -08001712func (p SourcePath) objPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleObjPath {
Colin Cross7fc17db2017-02-01 14:07:55 -08001713 return PathForModuleObj(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001714}
1715
Liz Kammera830f3a2020-11-10 10:50:34 -08001716func (p SourcePath) resPathWithName(ctx ModuleOutPathContext, name string) ModuleResPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001717 // TODO: Use full directory if the new ctx is not the current ctx?
1718 return PathForModuleRes(ctx, p.path, name)
1719}
1720
1721// ModuleOutPath is a Path representing a module's output directory.
1722type ModuleOutPath struct {
1723 OutputPath
1724}
1725
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001726func (p ModuleOutPath) RelativeToTop() Path {
1727 p.OutputPath = p.outputPathRelativeToTop()
1728 return p
1729}
1730
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001731var _ Path = ModuleOutPath{}
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001732var _ WritablePath = ModuleOutPath{}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001733
Liz Kammera830f3a2020-11-10 10:50:34 -08001734func (p ModuleOutPath) objPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleObjPath {
Pete Bentleyfcf55bf2019-08-16 20:14:32 +01001735 return PathForModuleObj(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
1736}
1737
Liz Kammera830f3a2020-11-10 10:50:34 -08001738// ModuleOutPathContext Subset of ModuleContext functions necessary for output path methods.
1739type ModuleOutPathContext interface {
1740 PathContext
1741
1742 ModuleName() string
1743 ModuleDir() string
1744 ModuleSubDir() string
1745}
1746
1747func pathForModuleOut(ctx ModuleOutPathContext) OutputPath {
Inseob Kimb7e9f5f2024-06-25 17:39:52 +09001748 return PathForOutput(ctx, ".intermediates", ctx.ModuleDir(), ctx.ModuleName(), ctx.ModuleSubDir())
Colin Cross702e0f82017-10-18 17:27:54 -07001749}
1750
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001751// PathForModuleOut returns a Path representing the paths... under the module's
1752// output directory.
Liz Kammera830f3a2020-11-10 10:50:34 -08001753func PathForModuleOut(ctx ModuleOutPathContext, paths ...string) ModuleOutPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001754 p, err := validatePath(paths...)
1755 if err != nil {
1756 reportPathError(ctx, err)
1757 }
Colin Cross702e0f82017-10-18 17:27:54 -07001758 return ModuleOutPath{
Liz Kammera830f3a2020-11-10 10:50:34 -08001759 OutputPath: pathForModuleOut(ctx).withRel(p),
Colin Cross702e0f82017-10-18 17:27:54 -07001760 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001761}
1762
1763// ModuleGenPath is a Path representing the 'gen' directory in a module's output
1764// directory. Mainly used for generated sources.
1765type ModuleGenPath struct {
1766 ModuleOutPath
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001767}
1768
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001769func (p ModuleGenPath) RelativeToTop() Path {
1770 p.OutputPath = p.outputPathRelativeToTop()
1771 return p
1772}
1773
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001774var _ Path = ModuleGenPath{}
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001775var _ WritablePath = ModuleGenPath{}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001776var _ genPathProvider = ModuleGenPath{}
1777var _ objPathProvider = ModuleGenPath{}
1778
1779// PathForModuleGen returns a Path representing the paths... under the module's
1780// `gen' directory.
Liz Kammera830f3a2020-11-10 10:50:34 -08001781func PathForModuleGen(ctx ModuleOutPathContext, paths ...string) ModuleGenPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001782 p, err := validatePath(paths...)
1783 if err != nil {
1784 reportPathError(ctx, err)
1785 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001786 return ModuleGenPath{
Colin Cross702e0f82017-10-18 17:27:54 -07001787 ModuleOutPath: ModuleOutPath{
Liz Kammera830f3a2020-11-10 10:50:34 -08001788 OutputPath: pathForModuleOut(ctx).withRel("gen").withRel(p),
Colin Cross702e0f82017-10-18 17:27:54 -07001789 },
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001790 }
1791}
1792
Liz Kammera830f3a2020-11-10 10:50:34 -08001793func (p ModuleGenPath) genPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleGenPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001794 // TODO: make a different path for local vs remote generated files?
Dan Willemsen21ec4902016-11-02 20:43:13 -07001795 return PathForModuleGen(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001796}
1797
yangbill6d032dd2024-04-18 03:05:49 +00001798func (p ModuleGenPath) genPathWithExtAndTrimExt(ctx ModuleOutPathContext, subdir, ext string, trimExt string) ModuleGenPath {
1799 // If Trim_extension being set, force append Output_extension without replace original extension.
1800 if trimExt != "" {
1801 if ext != "" {
1802 return PathForModuleGen(ctx, subdir, strings.TrimSuffix(p.path, trimExt)+"."+ext)
1803 }
1804 return PathForModuleGen(ctx, subdir, strings.TrimSuffix(p.path, trimExt))
1805 }
1806 return PathForModuleGen(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
1807}
1808
Liz Kammera830f3a2020-11-10 10:50:34 -08001809func (p ModuleGenPath) objPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleObjPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001810 return PathForModuleObj(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
1811}
1812
1813// ModuleObjPath is a Path representing the 'obj' directory in a module's output
1814// directory. Used for compiled objects.
1815type ModuleObjPath struct {
1816 ModuleOutPath
1817}
1818
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001819func (p ModuleObjPath) RelativeToTop() Path {
1820 p.OutputPath = p.outputPathRelativeToTop()
1821 return p
1822}
1823
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001824var _ Path = ModuleObjPath{}
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001825var _ WritablePath = ModuleObjPath{}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001826
1827// PathForModuleObj returns a Path representing the paths... under the module's
1828// 'obj' directory.
Liz Kammera830f3a2020-11-10 10:50:34 -08001829func PathForModuleObj(ctx ModuleOutPathContext, pathComponents ...string) ModuleObjPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001830 p, err := validatePath(pathComponents...)
1831 if err != nil {
1832 reportPathError(ctx, err)
1833 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001834 return ModuleObjPath{PathForModuleOut(ctx, "obj", p)}
1835}
1836
1837// ModuleResPath is a a Path representing the 'res' directory in a module's
1838// output directory.
1839type ModuleResPath struct {
1840 ModuleOutPath
1841}
1842
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001843func (p ModuleResPath) RelativeToTop() Path {
1844 p.OutputPath = p.outputPathRelativeToTop()
1845 return p
1846}
1847
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001848var _ Path = ModuleResPath{}
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001849var _ WritablePath = ModuleResPath{}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001850
1851// PathForModuleRes returns a Path representing the paths... under the module's
1852// 'res' directory.
Liz Kammera830f3a2020-11-10 10:50:34 -08001853func PathForModuleRes(ctx ModuleOutPathContext, pathComponents ...string) ModuleResPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001854 p, err := validatePath(pathComponents...)
1855 if err != nil {
1856 reportPathError(ctx, err)
1857 }
1858
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001859 return ModuleResPath{PathForModuleOut(ctx, "res", p)}
1860}
1861
Colin Cross70dda7e2019-10-01 22:05:35 -07001862// InstallPath is a Path representing a installed file path rooted from the build directory
1863type InstallPath struct {
1864 basePath
Colin Crossff6c33d2019-10-02 16:01:35 -07001865
Lukacs T. Berkib078ade2021-08-31 10:42:08 +02001866 // The soong build directory, i.e. Config.SoongOutDir()
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02001867 soongOutDir string
Paul Duffind65c58b2021-03-24 09:22:07 +00001868
Jiyong Park957bcd92020-10-20 18:23:33 +09001869 // partitionDir is the part of the InstallPath that is automatically determined according to the context.
1870 // For example, it is host/<os>-<arch> for host modules, and target/product/<device>/<partition> for device modules.
1871 partitionDir string
1872
Colin Crossb1692a32021-10-25 15:39:01 -07001873 partition string
1874
Jiyong Park957bcd92020-10-20 18:23:33 +09001875 // makePath indicates whether this path is for Soong (false) or Make (true).
1876 makePath bool
Colin Crossc0e42d52024-02-01 16:42:36 -08001877
1878 fullPath string
Colin Cross70dda7e2019-10-01 22:05:35 -07001879}
1880
Yu Liu467d7c52024-09-18 21:54:44 +00001881type installPathGob struct {
Yu Liu5246a7e2024-10-09 20:04:52 +00001882 BasePath basePath
Yu Liu467d7c52024-09-18 21:54:44 +00001883 SoongOutDir string
1884 PartitionDir string
1885 Partition string
1886 MakePath bool
1887 FullPath string
1888}
Yu Liu26a716d2024-08-30 23:40:32 +00001889
Yu Liu467d7c52024-09-18 21:54:44 +00001890func (p *InstallPath) ToGob() *installPathGob {
1891 return &installPathGob{
Yu Liu5246a7e2024-10-09 20:04:52 +00001892 BasePath: p.basePath,
Yu Liu467d7c52024-09-18 21:54:44 +00001893 SoongOutDir: p.soongOutDir,
1894 PartitionDir: p.partitionDir,
1895 Partition: p.partition,
1896 MakePath: p.makePath,
1897 FullPath: p.fullPath,
1898 }
1899}
1900
1901func (p *InstallPath) FromGob(data *installPathGob) {
Yu Liu5246a7e2024-10-09 20:04:52 +00001902 p.basePath = data.BasePath
Yu Liu467d7c52024-09-18 21:54:44 +00001903 p.soongOutDir = data.SoongOutDir
1904 p.partitionDir = data.PartitionDir
1905 p.partition = data.Partition
1906 p.makePath = data.MakePath
1907 p.fullPath = data.FullPath
1908}
1909
1910func (p InstallPath) GobEncode() ([]byte, error) {
Yu Liu3cadf7d2024-10-24 18:47:06 +00001911 return gobtools.CustomGobEncode[installPathGob](&p)
Yu Liu26a716d2024-08-30 23:40:32 +00001912}
1913
1914func (p *InstallPath) GobDecode(data []byte) error {
Yu Liu3cadf7d2024-10-24 18:47:06 +00001915 return gobtools.CustomGobDecode[installPathGob](data, p)
Yu Liu26a716d2024-08-30 23:40:32 +00001916}
1917
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001918// Will panic if called from outside a test environment.
1919func ensureTestOnly() {
Martin Stjernholm32312eb2021-03-27 18:54:49 +00001920 if PrefixInList(os.Args, "-test.") {
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001921 return
1922 }
Martin Stjernholm32312eb2021-03-27 18:54:49 +00001923 panic(fmt.Errorf("Not in test. Command line:\n %s", strings.Join(os.Args, "\n ")))
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001924}
1925
1926func (p InstallPath) RelativeToTop() Path {
1927 ensureTestOnly()
Colin Crossc0e42d52024-02-01 16:42:36 -08001928 if p.makePath {
Colin Cross3b1c6842024-07-26 11:52:57 -07001929 p.soongOutDir = testOutDir
Colin Crossc0e42d52024-02-01 16:42:36 -08001930 } else {
Colin Cross3b1c6842024-07-26 11:52:57 -07001931 p.soongOutDir = TestOutSoongDir
Colin Crossc0e42d52024-02-01 16:42:36 -08001932 }
1933 p.fullPath = filepath.Join(p.soongOutDir, p.path)
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001934 return p
1935}
1936
Colin Cross7707b242024-07-26 12:02:36 -07001937func (p InstallPath) WithoutRel() Path {
1938 p.basePath = p.basePath.withoutRel()
1939 return p
1940}
1941
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02001942func (p InstallPath) getSoongOutDir() string {
1943 return p.soongOutDir
Paul Duffin9b478b02019-12-10 13:41:51 +00001944}
1945
Hans MÃ¥nssond3f2bd72020-11-27 12:37:28 +01001946func (p InstallPath) ReplaceExtension(ctx PathContext, ext string) OutputPath {
1947 panic("Not implemented")
1948}
1949
Paul Duffin9b478b02019-12-10 13:41:51 +00001950var _ Path = InstallPath{}
1951var _ WritablePath = InstallPath{}
1952
Colin Cross70dda7e2019-10-01 22:05:35 -07001953func (p InstallPath) writablePath() {}
1954
1955func (p InstallPath) String() string {
Colin Crossc0e42d52024-02-01 16:42:36 -08001956 return p.fullPath
Jiyong Park957bcd92020-10-20 18:23:33 +09001957}
1958
1959// PartitionDir returns the path to the partition where the install path is rooted at. It is
1960// out/soong/target/product/<device>/<partition> for device modules, and out/soong/host/<os>-<arch> for host modules.
1961// The ./soong is dropped if the install path is for Make.
1962func (p InstallPath) PartitionDir() string {
1963 if p.makePath {
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02001964 return filepath.Join(p.soongOutDir, "../", p.partitionDir)
Jiyong Park957bcd92020-10-20 18:23:33 +09001965 } else {
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02001966 return filepath.Join(p.soongOutDir, p.partitionDir)
Jiyong Park957bcd92020-10-20 18:23:33 +09001967 }
Colin Cross70dda7e2019-10-01 22:05:35 -07001968}
1969
Jihoon Kangf78a8902022-09-01 22:47:07 +00001970func (p InstallPath) Partition() string {
1971 return p.partition
1972}
1973
Colin Cross70dda7e2019-10-01 22:05:35 -07001974// Join creates a new InstallPath with paths... joined with the current path. The
1975// provided paths... may not use '..' to escape from the current path.
1976func (p InstallPath) Join(ctx PathContext, paths ...string) InstallPath {
1977 path, err := validatePath(paths...)
1978 if err != nil {
1979 reportPathError(ctx, err)
1980 }
1981 return p.withRel(path)
1982}
1983
1984func (p InstallPath) withRel(rel string) InstallPath {
1985 p.basePath = p.basePath.withRel(rel)
Colin Crossc0e42d52024-02-01 16:42:36 -08001986 p.fullPath = filepath.Join(p.fullPath, rel)
Colin Cross70dda7e2019-10-01 22:05:35 -07001987 return p
1988}
1989
Colin Crossc68db4b2021-11-11 18:59:15 -08001990// Deprecated: ToMakePath is a noop, PathForModuleInstall always returns Make paths when building
1991// embedded in Make.
Colin Crossff6c33d2019-10-02 16:01:35 -07001992func (p InstallPath) ToMakePath() InstallPath {
Jiyong Park957bcd92020-10-20 18:23:33 +09001993 p.makePath = true
Colin Crossff6c33d2019-10-02 16:01:35 -07001994 return p
Colin Cross70dda7e2019-10-01 22:05:35 -07001995}
1996
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001997// PathForModuleInstall returns a Path representing the install path for the
1998// module appended with paths...
Colin Cross70dda7e2019-10-01 22:05:35 -07001999func PathForModuleInstall(ctx ModuleInstallPathContext, pathComponents ...string) InstallPath {
Spandan Das5d1b9292021-06-03 19:36:41 +00002000 os, arch := osAndArch(ctx)
Cole Faust11edf552023-10-13 11:32:14 -07002001 partition := modulePartition(ctx, os.Class == Device)
Cole Faust3b703f32023-10-16 13:30:51 -07002002 return pathForInstall(ctx, os, arch, partition, pathComponents...)
Spandan Das5d1b9292021-06-03 19:36:41 +00002003}
2004
Colin Cross1d0eb7a2021-11-03 14:08:20 -07002005// PathForHostDexInstall returns an InstallPath representing the install path for the
2006// module appended with paths...
2007func PathForHostDexInstall(ctx ModuleInstallPathContext, pathComponents ...string) InstallPath {
Cole Faust3b703f32023-10-16 13:30:51 -07002008 return pathForInstall(ctx, ctx.Config().BuildOS, ctx.Config().BuildArch, "", pathComponents...)
Colin Cross1d0eb7a2021-11-03 14:08:20 -07002009}
2010
Spandan Das5d1b9292021-06-03 19:36:41 +00002011// PathForModuleInPartitionInstall is similar to PathForModuleInstall but partition is provided by the caller
2012func PathForModuleInPartitionInstall(ctx ModuleInstallPathContext, partition string, pathComponents ...string) InstallPath {
2013 os, arch := osAndArch(ctx)
Cole Faust3b703f32023-10-16 13:30:51 -07002014 return pathForInstall(ctx, os, arch, partition, pathComponents...)
Spandan Das5d1b9292021-06-03 19:36:41 +00002015}
2016
2017func osAndArch(ctx ModuleInstallPathContext) (OsType, ArchType) {
Colin Cross6e359402020-02-10 15:29:54 -08002018 os := ctx.Os()
Jiyong Park87788b52020-09-01 12:37:45 +09002019 arch := ctx.Arch().ArchType
2020 forceOS, forceArch := ctx.InstallForceOS()
2021 if forceOS != nil {
Colin Cross6e359402020-02-10 15:29:54 -08002022 os = *forceOS
2023 }
Jiyong Park87788b52020-09-01 12:37:45 +09002024 if forceArch != nil {
2025 arch = *forceArch
2026 }
Spandan Das5d1b9292021-06-03 19:36:41 +00002027 return os, arch
2028}
Colin Cross609c49a2020-02-13 13:20:11 -08002029
Colin Crossc0e42d52024-02-01 16:42:36 -08002030func pathForPartitionInstallDir(ctx PathContext, partition, partitionPath string, makePath bool) InstallPath {
2031 fullPath := ctx.Config().SoongOutDir()
2032 if makePath {
2033 // Make path starts with out/ instead of out/soong.
2034 fullPath = filepath.Join(fullPath, "../", partitionPath)
2035 } else {
2036 fullPath = filepath.Join(fullPath, partitionPath)
2037 }
2038
2039 return InstallPath{
2040 basePath: basePath{partitionPath, ""},
2041 soongOutDir: ctx.Config().soongOutDir,
2042 partitionDir: partitionPath,
2043 partition: partition,
2044 makePath: makePath,
2045 fullPath: fullPath,
2046 }
2047}
2048
Cole Faust3b703f32023-10-16 13:30:51 -07002049func pathForInstall(ctx PathContext, os OsType, arch ArchType, partition string,
Colin Cross609c49a2020-02-13 13:20:11 -08002050 pathComponents ...string) InstallPath {
2051
Jiyong Park97859152023-02-14 17:05:48 +09002052 var partitionPaths []string
Colin Cross609c49a2020-02-13 13:20:11 -08002053
Colin Cross6e359402020-02-10 15:29:54 -08002054 if os.Class == Device {
Jiyong Park97859152023-02-14 17:05:48 +09002055 partitionPaths = []string{"target", "product", ctx.Config().DeviceName(), partition}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07002056 } else {
Jiyong Park87788b52020-09-01 12:37:45 +09002057 osName := os.String()
Colin Crossa9b2aac2022-06-15 17:25:51 -07002058 if os == Linux {
Jiyong Park87788b52020-09-01 12:37:45 +09002059 // instead of linux_glibc
2060 osName = "linux"
Dan Willemsen866b5632017-09-22 12:28:24 -07002061 }
Colin Crossa9b2aac2022-06-15 17:25:51 -07002062 if os == LinuxMusl && ctx.Config().UseHostMusl() {
2063 // When using musl instead of glibc, use "linux" instead of "linux_musl". When cross
2064 // compiling we will still use "linux_musl".
2065 osName = "linux"
2066 }
2067
Jiyong Park87788b52020-09-01 12:37:45 +09002068 // SOONG_HOST_OUT is set to out/host/$(HOST_OS)-$(HOST_PREBUILT_ARCH)
2069 // and HOST_PREBUILT_ARCH is forcibly set to x86 even on x86_64 hosts. We don't seem
2070 // to have a plan to fix it (see the comment in build/make/core/envsetup.mk).
2071 // Let's keep using x86 for the existing cases until we have a need to support
2072 // other architectures.
2073 archName := arch.String()
2074 if os.Class == Host && (arch == X86_64 || arch == Common) {
2075 archName = "x86"
2076 }
Jiyong Park97859152023-02-14 17:05:48 +09002077 partitionPaths = []string{"host", osName + "-" + archName, partition}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07002078 }
Colin Cross70dda7e2019-10-01 22:05:35 -07002079
Jiyong Park97859152023-02-14 17:05:48 +09002080 partitionPath, err := validatePath(partitionPaths...)
Colin Cross70dda7e2019-10-01 22:05:35 -07002081 if err != nil {
2082 reportPathError(ctx, err)
2083 }
Colin Crossff6c33d2019-10-02 16:01:35 -07002084
Cole Faust6b7075f2024-12-17 10:42:42 -08002085 base := pathForPartitionInstallDir(ctx, partition, partitionPath, true)
Jiyong Park957bcd92020-10-20 18:23:33 +09002086 return base.Join(ctx, pathComponents...)
Dan Willemsen34cc69e2015-09-23 15:26:20 -07002087}
2088
Spandan Dasf280b232024-04-04 21:25:51 +00002089func PathForNdkInstall(ctx PathContext, paths ...string) OutputPath {
2090 return PathForOutput(ctx, append([]string{"ndk"}, paths...)...)
Nicolas Geoffray1228e9c2020-02-27 13:45:35 +00002091}
2092
2093func PathForMainlineSdksInstall(ctx PathContext, paths ...string) InstallPath {
Spandan Dasf280b232024-04-04 21:25:51 +00002094 base := pathForPartitionInstallDir(ctx, "", "mainline-sdks", false)
2095 return base.Join(ctx, paths...)
Nicolas Geoffray1228e9c2020-02-27 13:45:35 +00002096}
2097
Weijia Heaa37c162024-11-06 19:46:03 +00002098func PathForSuiteInstall(ctx PathContext, suite string, pathComponents ...string) InstallPath {
2099 return pathForPartitionInstallDir(ctx, "test_suites", "test_suites", false).Join(ctx, suite).Join(ctx, pathComponents...)
2100}
2101
Colin Cross70dda7e2019-10-01 22:05:35 -07002102func InstallPathToOnDevicePath(ctx PathContext, path InstallPath) string {
Colin Crossb1692a32021-10-25 15:39:01 -07002103 rel := Rel(ctx, strings.TrimSuffix(path.PartitionDir(), path.partition), path.String())
Colin Cross43f08db2018-11-12 10:13:39 -08002104 return "/" + rel
2105}
2106
Cole Faust11edf552023-10-13 11:32:14 -07002107func modulePartition(ctx ModuleInstallPathContext, device bool) string {
Colin Cross43f08db2018-11-12 10:13:39 -08002108 var partition string
Colin Cross6e359402020-02-10 15:29:54 -08002109 if ctx.InstallInTestcases() {
2110 // "testcases" install directory can be used for host or device modules.
Jaewoong Jung0949f312019-09-11 10:25:18 -07002111 partition = "testcases"
Cole Faust11edf552023-10-13 11:32:14 -07002112 } else if device {
Colin Cross6e359402020-02-10 15:29:54 -08002113 if ctx.InstallInData() {
2114 partition = "data"
2115 } else if ctx.InstallInRamdisk() {
2116 if ctx.DeviceConfig().BoardUsesRecoveryAsBoot() {
2117 partition = "recovery/root/first_stage_ramdisk"
2118 } else {
2119 partition = "ramdisk"
2120 }
2121 if !ctx.InstallInRoot() {
2122 partition += "/system"
2123 }
Yifan Hong60e0cfb2020-10-21 15:17:56 -07002124 } else if ctx.InstallInVendorRamdisk() {
Yifan Hong39143a92020-10-26 12:43:12 -07002125 // The module is only available after switching root into
2126 // /first_stage_ramdisk. To expose the module before switching root
2127 // on a device without a dedicated recovery partition, install the
2128 // recovery variant.
Yifan Hongdd8dacc2020-10-21 15:40:17 -07002129 if ctx.DeviceConfig().BoardMoveRecoveryResourcesToVendorBoot() {
Petri Gyntherac229562021-03-02 23:44:02 -08002130 partition = "vendor_ramdisk/first_stage_ramdisk"
Yifan Hongdd8dacc2020-10-21 15:40:17 -07002131 } else {
Petri Gyntherac229562021-03-02 23:44:02 -08002132 partition = "vendor_ramdisk"
Yifan Hongdd8dacc2020-10-21 15:40:17 -07002133 }
2134 if !ctx.InstallInRoot() {
2135 partition += "/system"
2136 }
Inseob Kim08758f02021-04-08 21:13:22 +09002137 } else if ctx.InstallInDebugRamdisk() {
2138 partition = "debug_ramdisk"
Colin Cross6e359402020-02-10 15:29:54 -08002139 } else if ctx.InstallInRecovery() {
2140 if ctx.InstallInRoot() {
2141 partition = "recovery/root"
2142 } else {
2143 // the layout of recovery partion is the same as that of system partition
2144 partition = "recovery/root/system"
2145 }
Colin Crossea30d852023-11-29 16:00:16 -08002146 } else if ctx.SocSpecific() || ctx.InstallInVendor() {
Colin Cross6e359402020-02-10 15:29:54 -08002147 partition = ctx.DeviceConfig().VendorPath()
Colin Crossea30d852023-11-29 16:00:16 -08002148 } else if ctx.DeviceSpecific() || ctx.InstallInOdm() {
Colin Cross6e359402020-02-10 15:29:54 -08002149 partition = ctx.DeviceConfig().OdmPath()
Colin Crossea30d852023-11-29 16:00:16 -08002150 } else if ctx.ProductSpecific() || ctx.InstallInProduct() {
Colin Cross6e359402020-02-10 15:29:54 -08002151 partition = ctx.DeviceConfig().ProductPath()
2152 } else if ctx.SystemExtSpecific() {
2153 partition = ctx.DeviceConfig().SystemExtPath()
2154 } else if ctx.InstallInRoot() {
2155 partition = "root"
Spandan Das27ff7672024-11-06 19:23:57 +00002156 } else if ctx.InstallInSystemDlkm() {
2157 partition = ctx.DeviceConfig().SystemDlkmPath()
2158 } else if ctx.InstallInVendorDlkm() {
2159 partition = ctx.DeviceConfig().VendorDlkmPath()
2160 } else if ctx.InstallInOdmDlkm() {
2161 partition = ctx.DeviceConfig().OdmDlkmPath()
Yifan Hong82db7352020-01-21 16:12:26 -08002162 } else {
Colin Cross6e359402020-02-10 15:29:54 -08002163 partition = "system"
Yifan Hong82db7352020-01-21 16:12:26 -08002164 }
Colin Cross6e359402020-02-10 15:29:54 -08002165 if ctx.InstallInSanitizerDir() {
2166 partition = "data/asan/" + partition
Yifan Hong82db7352020-01-21 16:12:26 -08002167 }
Colin Cross43f08db2018-11-12 10:13:39 -08002168 }
2169 return partition
2170}
2171
Colin Cross609c49a2020-02-13 13:20:11 -08002172type InstallPaths []InstallPath
2173
2174// Paths returns the InstallPaths as a Paths
2175func (p InstallPaths) Paths() Paths {
2176 if p == nil {
2177 return nil
2178 }
2179 ret := make(Paths, len(p))
2180 for i, path := range p {
2181 ret[i] = path
2182 }
2183 return ret
2184}
2185
2186// Strings returns the string forms of the install paths.
2187func (p InstallPaths) Strings() []string {
2188 if p == nil {
2189 return nil
2190 }
2191 ret := make([]string, len(p))
2192 for i, path := range p {
2193 ret[i] = path.String()
2194 }
2195 return ret
2196}
2197
Jingwen Chen24d0c562023-02-07 09:29:36 +00002198// validatePathInternal ensures that a path does not leave its component, and
2199// optionally doesn't contain Ninja variables.
2200func validatePathInternal(allowNinjaVariables bool, pathComponents ...string) (string, error) {
Colin Crossbf9ed3f2023-10-24 14:17:03 -07002201 initialEmpty := 0
2202 finalEmpty := 0
2203 for i, path := range pathComponents {
Jingwen Chen24d0c562023-02-07 09:29:36 +00002204 if !allowNinjaVariables && strings.Contains(path, "$") {
2205 return "", fmt.Errorf("Path contains invalid character($): %s", path)
2206 }
2207
Dan Willemsen80a7c2a2015-12-21 14:57:11 -08002208 path := filepath.Clean(path)
2209 if path == ".." || strings.HasPrefix(path, "../") || strings.HasPrefix(path, "/") {
Colin Cross1ccfcc32018-02-22 13:54:26 -08002210 return "", fmt.Errorf("Path is outside directory: %s", path)
Dan Willemsen80a7c2a2015-12-21 14:57:11 -08002211 }
Colin Crossbf9ed3f2023-10-24 14:17:03 -07002212
2213 if i == initialEmpty && pathComponents[i] == "" {
2214 initialEmpty++
2215 }
2216 if i == finalEmpty && pathComponents[len(pathComponents)-1-i] == "" {
2217 finalEmpty++
2218 }
Dan Willemsen80a7c2a2015-12-21 14:57:11 -08002219 }
Colin Crossbf9ed3f2023-10-24 14:17:03 -07002220 // Optimization: filepath.Join("foo", "") returns a newly allocated copy
2221 // of "foo", while filepath.Join("foo") does not. Strip out any empty
2222 // path components.
2223 if initialEmpty == len(pathComponents) {
2224 return "", nil
2225 }
2226 nonEmptyPathComponents := pathComponents[initialEmpty : len(pathComponents)-finalEmpty]
Dan Willemsen34cc69e2015-09-23 15:26:20 -07002227 // TODO: filepath.Join isn't necessarily correct with embedded ninja
2228 // variables. '..' may remove the entire ninja variable, even if it
2229 // will be expanded to multiple nested directories.
Colin Crossbf9ed3f2023-10-24 14:17:03 -07002230 return filepath.Join(nonEmptyPathComponents...), nil
Dan Willemsen34cc69e2015-09-23 15:26:20 -07002231}
2232
Jingwen Chen24d0c562023-02-07 09:29:36 +00002233// validateSafePath validates a path that we trust (may contain ninja
2234// variables). Ensures that each path component does not attempt to leave its
2235// component. Returns a joined version of each path component.
2236func validateSafePath(pathComponents ...string) (string, error) {
2237 return validatePathInternal(true, pathComponents...)
2238}
2239
Dan Willemsen80a7c2a2015-12-21 14:57:11 -08002240// validatePath validates that a path does not include ninja variables, and that
2241// each path component does not attempt to leave its component. Returns a joined
2242// version of each path component.
Colin Cross1ccfcc32018-02-22 13:54:26 -08002243func validatePath(pathComponents ...string) (string, error) {
Jingwen Chen24d0c562023-02-07 09:29:36 +00002244 return validatePathInternal(false, pathComponents...)
Colin Cross6e18ca42015-07-14 18:55:36 -07002245}
Colin Cross5b529592017-05-09 13:34:34 -07002246
Colin Cross0875c522017-11-28 17:34:01 -08002247func PathForPhony(ctx PathContext, phony string) WritablePath {
2248 if strings.ContainsAny(phony, "$/") {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01002249 ReportPathErrorf(ctx, "Phony target contains invalid character ($ or /): %s", phony)
Colin Cross0875c522017-11-28 17:34:01 -08002250 }
Paul Duffin74abc5d2021-03-24 09:24:59 +00002251 return PhonyPath{basePath{phony, ""}}
Colin Cross0875c522017-11-28 17:34:01 -08002252}
2253
Colin Cross74e3fe42017-12-11 15:51:44 -08002254type PhonyPath struct {
2255 basePath
2256}
2257
2258func (p PhonyPath) writablePath() {}
2259
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02002260func (p PhonyPath) getSoongOutDir() string {
Paul Duffind65c58b2021-03-24 09:22:07 +00002261 // A phone path cannot contain any / so cannot be relative to the build directory.
2262 return ""
Paul Duffin9b478b02019-12-10 13:41:51 +00002263}
2264
Paul Duffin85d8f0d2021-03-24 10:18:18 +00002265func (p PhonyPath) RelativeToTop() Path {
2266 ensureTestOnly()
2267 // A phony path cannot contain any / so does not have a build directory so switching to a new
2268 // build directory has no effect so just return this path.
2269 return p
2270}
2271
Colin Cross7707b242024-07-26 12:02:36 -07002272func (p PhonyPath) WithoutRel() Path {
2273 p.basePath = p.basePath.withoutRel()
2274 return p
2275}
2276
Hans MÃ¥nssond3f2bd72020-11-27 12:37:28 +01002277func (p PhonyPath) ReplaceExtension(ctx PathContext, ext string) OutputPath {
2278 panic("Not implemented")
2279}
2280
Colin Cross74e3fe42017-12-11 15:51:44 -08002281var _ Path = PhonyPath{}
2282var _ WritablePath = PhonyPath{}
2283
Colin Cross5b529592017-05-09 13:34:34 -07002284type testPath struct {
2285 basePath
2286}
2287
Paul Duffin85d8f0d2021-03-24 10:18:18 +00002288func (p testPath) RelativeToTop() Path {
2289 ensureTestOnly()
2290 return p
2291}
2292
Colin Cross7707b242024-07-26 12:02:36 -07002293func (p testPath) WithoutRel() Path {
2294 p.basePath = p.basePath.withoutRel()
2295 return p
2296}
2297
Colin Cross5b529592017-05-09 13:34:34 -07002298func (p testPath) String() string {
2299 return p.path
2300}
2301
Paul Duffin85d8f0d2021-03-24 10:18:18 +00002302var _ Path = testPath{}
2303
Colin Cross40e33732019-02-15 11:08:35 -08002304// PathForTesting returns a Path constructed from joining the elements of paths with '/'. It should only be used from
2305// within tests.
Colin Cross5b529592017-05-09 13:34:34 -07002306func PathForTesting(paths ...string) Path {
Colin Cross1ccfcc32018-02-22 13:54:26 -08002307 p, err := validateSafePath(paths...)
2308 if err != nil {
2309 panic(err)
2310 }
Colin Cross5b529592017-05-09 13:34:34 -07002311 return testPath{basePath{path: p, rel: p}}
2312}
2313
Sam Delmerico2351eac2022-05-24 17:10:02 +00002314func PathForTestingWithRel(path, rel string) Path {
2315 p, err := validateSafePath(path, rel)
2316 if err != nil {
2317 panic(err)
2318 }
2319 r, err := validatePath(rel)
2320 if err != nil {
2321 panic(err)
2322 }
2323 return testPath{basePath{path: p, rel: r}}
2324}
2325
Colin Cross40e33732019-02-15 11:08:35 -08002326// PathsForTesting returns a Path constructed from each element in strs. It should only be used from within tests.
2327func PathsForTesting(strs ...string) Paths {
Colin Cross5b529592017-05-09 13:34:34 -07002328 p := make(Paths, len(strs))
2329 for i, s := range strs {
2330 p[i] = PathForTesting(s)
2331 }
2332
2333 return p
2334}
Colin Cross43f08db2018-11-12 10:13:39 -08002335
Colin Cross40e33732019-02-15 11:08:35 -08002336type testPathContext struct {
2337 config Config
Colin Cross40e33732019-02-15 11:08:35 -08002338}
2339
Colin Cross40e33732019-02-15 11:08:35 -08002340func (x *testPathContext) Config() Config { return x.config }
2341func (x *testPathContext) AddNinjaFileDeps(...string) {}
2342
2343// PathContextForTesting returns a PathContext that can be used in tests, for example to create an OutputPath with
2344// PathForOutput.
Colin Cross98be1bb2019-12-13 20:41:13 -08002345func PathContextForTesting(config Config) PathContext {
Colin Cross40e33732019-02-15 11:08:35 -08002346 return &testPathContext{
2347 config: config,
Colin Cross40e33732019-02-15 11:08:35 -08002348 }
2349}
2350
Ulya Trafimovichccc8c852020-10-14 11:29:07 +01002351type testModuleInstallPathContext struct {
2352 baseModuleContext
2353
2354 inData bool
2355 inTestcases bool
2356 inSanitizerDir bool
2357 inRamdisk bool
2358 inVendorRamdisk bool
Inseob Kim08758f02021-04-08 21:13:22 +09002359 inDebugRamdisk bool
Ulya Trafimovichccc8c852020-10-14 11:29:07 +01002360 inRecovery bool
2361 inRoot bool
Colin Crossea30d852023-11-29 16:00:16 -08002362 inOdm bool
2363 inProduct bool
2364 inVendor bool
Spandan Das27ff7672024-11-06 19:23:57 +00002365 inSystemDlkm bool
2366 inVendorDlkm bool
2367 inOdmDlkm bool
Ulya Trafimovichccc8c852020-10-14 11:29:07 +01002368 forceOS *OsType
2369 forceArch *ArchType
2370}
2371
2372func (m testModuleInstallPathContext) Config() Config {
2373 return m.baseModuleContext.config
2374}
2375
2376func (testModuleInstallPathContext) AddNinjaFileDeps(deps ...string) {}
2377
2378func (m testModuleInstallPathContext) InstallInData() bool {
2379 return m.inData
2380}
2381
2382func (m testModuleInstallPathContext) InstallInTestcases() bool {
2383 return m.inTestcases
2384}
2385
2386func (m testModuleInstallPathContext) InstallInSanitizerDir() bool {
2387 return m.inSanitizerDir
2388}
2389
2390func (m testModuleInstallPathContext) InstallInRamdisk() bool {
2391 return m.inRamdisk
2392}
2393
2394func (m testModuleInstallPathContext) InstallInVendorRamdisk() bool {
2395 return m.inVendorRamdisk
2396}
2397
Inseob Kim08758f02021-04-08 21:13:22 +09002398func (m testModuleInstallPathContext) InstallInDebugRamdisk() bool {
2399 return m.inDebugRamdisk
2400}
2401
Ulya Trafimovichccc8c852020-10-14 11:29:07 +01002402func (m testModuleInstallPathContext) InstallInRecovery() bool {
2403 return m.inRecovery
2404}
2405
2406func (m testModuleInstallPathContext) InstallInRoot() bool {
2407 return m.inRoot
2408}
2409
Colin Crossea30d852023-11-29 16:00:16 -08002410func (m testModuleInstallPathContext) InstallInOdm() bool {
2411 return m.inOdm
2412}
2413
2414func (m testModuleInstallPathContext) InstallInProduct() bool {
2415 return m.inProduct
2416}
2417
2418func (m testModuleInstallPathContext) InstallInVendor() bool {
2419 return m.inVendor
2420}
2421
Spandan Das27ff7672024-11-06 19:23:57 +00002422func (m testModuleInstallPathContext) InstallInSystemDlkm() bool {
2423 return m.inSystemDlkm
2424}
2425
2426func (m testModuleInstallPathContext) InstallInVendorDlkm() bool {
2427 return m.inVendorDlkm
2428}
2429
2430func (m testModuleInstallPathContext) InstallInOdmDlkm() bool {
2431 return m.inOdmDlkm
2432}
2433
Ulya Trafimovichccc8c852020-10-14 11:29:07 +01002434func (m testModuleInstallPathContext) InstallForceOS() (*OsType, *ArchType) {
2435 return m.forceOS, m.forceArch
2436}
2437
2438// Construct a minimal ModuleInstallPathContext for testing. Note that baseModuleContext is
2439// default-initialized, which leaves blueprint.baseModuleContext set to nil, so methods that are
2440// delegated to it will panic.
2441func ModuleInstallPathContextForTesting(config Config) ModuleInstallPathContext {
2442 ctx := &testModuleInstallPathContext{}
2443 ctx.config = config
2444 ctx.os = Android
2445 return ctx
2446}
2447
Colin Cross43f08db2018-11-12 10:13:39 -08002448// Rel performs the same function as filepath.Rel, but reports errors to a PathContext, and reports an error if
2449// targetPath is not inside basePath.
2450func Rel(ctx PathContext, basePath string, targetPath string) string {
2451 rel, isRel := MaybeRel(ctx, basePath, targetPath)
2452 if !isRel {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01002453 ReportPathErrorf(ctx, "path %q is not under path %q", targetPath, basePath)
Colin Cross43f08db2018-11-12 10:13:39 -08002454 return ""
2455 }
2456 return rel
2457}
2458
2459// MaybeRel performs the same function as filepath.Rel, but reports errors to a PathContext, and returns false if
2460// targetPath is not inside basePath.
2461func MaybeRel(ctx PathContext, basePath string, targetPath string) (string, bool) {
Dan Willemsen633c5022019-04-12 11:11:38 -07002462 rel, isRel, err := maybeRelErr(basePath, targetPath)
2463 if err != nil {
2464 reportPathError(ctx, err)
2465 }
2466 return rel, isRel
2467}
2468
2469func maybeRelErr(basePath string, targetPath string) (string, bool, error) {
Colin Cross43f08db2018-11-12 10:13:39 -08002470 // filepath.Rel returns an error if one path is absolute and the other is not, handle that case first.
2471 if filepath.IsAbs(basePath) != filepath.IsAbs(targetPath) {
Dan Willemsen633c5022019-04-12 11:11:38 -07002472 return "", false, nil
Colin Cross43f08db2018-11-12 10:13:39 -08002473 }
2474 rel, err := filepath.Rel(basePath, targetPath)
2475 if err != nil {
Dan Willemsen633c5022019-04-12 11:11:38 -07002476 return "", false, err
Colin Cross43f08db2018-11-12 10:13:39 -08002477 } else if rel == ".." || strings.HasPrefix(rel, "../") || strings.HasPrefix(rel, "/") {
Dan Willemsen633c5022019-04-12 11:11:38 -07002478 return "", false, nil
Colin Cross43f08db2018-11-12 10:13:39 -08002479 }
Dan Willemsen633c5022019-04-12 11:11:38 -07002480 return rel, true, nil
Colin Cross43f08db2018-11-12 10:13:39 -08002481}
Colin Cross988414c2020-01-11 01:11:46 +00002482
2483// Writes a file to the output directory. Attempting to write directly to the output directory
2484// will fail due to the sandbox of the soong_build process.
Chris Parsons1a12d032023-02-06 22:37:41 -05002485// Only writes the file if the file doesn't exist or if it has different contents, to prevent
2486// updating the timestamp if no changes would be made. (This is better for incremental
2487// performance.)
Colin Cross988414c2020-01-11 01:11:46 +00002488func WriteFileToOutputDir(path WritablePath, data []byte, perm os.FileMode) error {
Colin Crossd6421132021-11-09 12:32:34 -08002489 absPath := absolutePath(path.String())
2490 err := os.MkdirAll(filepath.Dir(absPath), 0777)
2491 if err != nil {
2492 return err
2493 }
Chris Parsons1a12d032023-02-06 22:37:41 -05002494 return pathtools.WriteFileIfChanged(absPath, data, perm)
Colin Cross988414c2020-01-11 01:11:46 +00002495}
2496
Liz Kammer2dd9ca42020-11-25 16:06:39 -08002497func RemoveAllOutputDir(path WritablePath) error {
2498 return os.RemoveAll(absolutePath(path.String()))
2499}
2500
2501func CreateOutputDirIfNonexistent(path WritablePath, perm os.FileMode) error {
2502 dir := absolutePath(path.String())
Liz Kammer09f947d2021-05-12 14:51:49 -04002503 return createDirIfNonexistent(dir, perm)
2504}
2505
2506func createDirIfNonexistent(dir string, perm os.FileMode) error {
Liz Kammer2dd9ca42020-11-25 16:06:39 -08002507 if _, err := os.Stat(dir); os.IsNotExist(err) {
2508 return os.MkdirAll(dir, os.ModePerm)
2509 } else {
2510 return err
2511 }
2512}
2513
Jingwen Chen78257e52021-05-21 02:34:24 +00002514// absolutePath is deliberately private so that Soong's Go plugins can't use it to find and
2515// read arbitrary files without going through the methods in the current package that track
2516// dependencies.
Colin Cross988414c2020-01-11 01:11:46 +00002517func absolutePath(path string) string {
2518 if filepath.IsAbs(path) {
2519 return path
2520 }
2521 return filepath.Join(absSrcDir, path)
2522}
Chris Parsons216e10a2020-07-09 17:12:52 -04002523
2524// A DataPath represents the path of a file to be used as data, for example
2525// a test library to be installed alongside a test.
2526// The data file should be installed (copied from `<SrcPath>`) to
2527// `<install_root>/<RelativeInstallPath>/<filename>`, or
2528// `<install_root>/<filename>` if RelativeInstallPath is empty.
2529type DataPath struct {
2530 // The path of the data file that should be copied into the data directory
2531 SrcPath Path
2532 // The install path of the data file, relative to the install root.
2533 RelativeInstallPath string
Colin Cross5c1d5fb2023-11-15 12:39:40 -08002534 // If WithoutRel is true, use SrcPath.Base() instead of SrcPath.Rel() as the filename.
2535 WithoutRel bool
Chris Parsons216e10a2020-07-09 17:12:52 -04002536}
Colin Crossdcf71b22021-02-01 13:59:03 -08002537
Colin Crossd442a0e2023-11-16 11:19:26 -08002538func (d *DataPath) ToRelativeInstallPath() string {
2539 relPath := d.SrcPath.Rel()
Colin Cross5c1d5fb2023-11-15 12:39:40 -08002540 if d.WithoutRel {
2541 relPath = d.SrcPath.Base()
2542 }
Colin Crossd442a0e2023-11-16 11:19:26 -08002543 if d.RelativeInstallPath != "" {
2544 relPath = filepath.Join(d.RelativeInstallPath, relPath)
2545 }
2546 return relPath
2547}
2548
Colin Crossdcf71b22021-02-01 13:59:03 -08002549// PathsIfNonNil returns a Paths containing only the non-nil input arguments.
2550func PathsIfNonNil(paths ...Path) Paths {
2551 if len(paths) == 0 {
2552 // Fast path for empty argument list
2553 return nil
2554 } else if len(paths) == 1 {
2555 // Fast path for a single argument
2556 if paths[0] != nil {
2557 return paths
2558 } else {
2559 return nil
2560 }
2561 }
2562 ret := make(Paths, 0, len(paths))
2563 for _, path := range paths {
2564 if path != nil {
2565 ret = append(ret, path)
2566 }
2567 }
2568 if len(ret) == 0 {
2569 return nil
2570 }
2571 return ret
2572}
Chris Wailesb2703ad2021-07-30 13:25:42 -07002573
2574var thirdPartyDirPrefixExceptions = []*regexp.Regexp{
2575 regexp.MustCompile("^vendor/[^/]*google[^/]*/"),
2576 regexp.MustCompile("^hardware/google/"),
2577 regexp.MustCompile("^hardware/interfaces/"),
2578 regexp.MustCompile("^hardware/libhardware[^/]*/"),
2579 regexp.MustCompile("^hardware/ril/"),
2580}
2581
2582func IsThirdPartyPath(path string) bool {
2583 thirdPartyDirPrefixes := []string{"external/", "vendor/", "hardware/"}
2584
2585 if HasAnyPrefix(path, thirdPartyDirPrefixes) {
2586 for _, prefix := range thirdPartyDirPrefixExceptions {
2587 if prefix.MatchString(path) {
2588 return false
2589 }
2590 }
2591 return true
2592 }
2593 return false
2594}
Jihoon Kangf27c3a52024-11-12 21:27:09 +00002595
2596// ToRelativeSourcePath converts absolute source path to the path relative to the source root.
2597// This throws an error if the input path is outside of the source root and cannot be converted
2598// to the relative path.
2599// This should be rarely used given that the source path is relative in Soong.
2600func ToRelativeSourcePath(ctx PathContext, path string) string {
2601 ret := path
2602 if filepath.IsAbs(path) {
2603 relPath, err := filepath.Rel(absSrcDir, path)
2604 if err != nil || strings.HasPrefix(relPath, "..") {
2605 ReportPathErrorf(ctx, "%s is outside of the source root", path)
2606 }
2607 ret = relPath
2608 }
2609 return ret
2610}