blob: bbf10d15d91447047da76b62ff82cfac16c67be1 [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
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700212// reportPathError will register an error with the attached context. It
213// attempts ctx.ModuleErrorf for a better error message first, then falls
214// back to ctx.Errorf.
Colin Cross1ccfcc32018-02-22 13:54:26 -0800215func reportPathError(ctx PathContext, err error) {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +0100216 ReportPathErrorf(ctx, "%s", err.Error())
Colin Cross1ccfcc32018-02-22 13:54:26 -0800217}
218
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +0100219// ReportPathErrorf will register an error with the attached context. It
Colin Cross1ccfcc32018-02-22 13:54:26 -0800220// attempts ctx.ModuleErrorf for a better error message first, then falls
221// back to ctx.Errorf.
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +0100222func ReportPathErrorf(ctx PathContext, format string, args ...interface{}) {
Spandan Das59a4a2b2024-01-09 21:35:56 +0000223 if mctx, ok := ctx.(ModuleErrorfContext); ok {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700224 mctx.ModuleErrorf(format, args...)
225 } else if ectx, ok := ctx.(errorfContext); ok {
226 ectx.Errorf(format, args...)
227 } else {
228 panic(fmt.Sprintf(format, args...))
Colin Crossf2298272015-05-12 11:36:53 -0700229 }
230}
231
Colin Cross5e708052019-08-06 13:59:50 -0700232func pathContextName(ctx PathContext, module blueprint.Module) string {
233 if x, ok := ctx.(interface{ ModuleName(blueprint.Module) string }); ok {
234 return x.ModuleName(module)
235 } else if x, ok := ctx.(interface{ OtherModuleName(blueprint.Module) string }); ok {
236 return x.OtherModuleName(module)
237 }
238 return "unknown"
239}
240
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700241type Path interface {
242 // Returns the path in string form
243 String() string
244
Colin Cross4f6fc9c2016-10-26 10:05:25 -0700245 // Ext returns the extension of the last element of the path
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700246 Ext() string
Colin Cross4f6fc9c2016-10-26 10:05:25 -0700247
248 // Base returns the last element of the path
249 Base() string
Colin Crossfaeb7aa2017-02-01 14:12:44 -0800250
251 // Rel returns the portion of the path relative to the directory it was created from. For
252 // example, Rel on a PathsForModuleSrc would return the path relative to the module source
Colin Cross0db55682017-12-05 15:36:55 -0800253 // directory, and OutputPath.Join("foo").Rel() would return "foo".
Colin Crossfaeb7aa2017-02-01 14:12:44 -0800254 Rel() string
Paul Duffin85d8f0d2021-03-24 10:18:18 +0000255
Colin Cross7707b242024-07-26 12:02:36 -0700256 // WithoutRel returns a new Path with no relative path, i.e. Rel() will return the same value as Base().
257 WithoutRel() Path
258
Paul Duffin85d8f0d2021-03-24 10:18:18 +0000259 // RelativeToTop returns a new path relative to the top, it is provided solely for use in tests.
260 //
261 // It is guaranteed to always return the same type as it is called on, e.g. if called on an
262 // InstallPath then the returned value can be converted to an InstallPath.
263 //
264 // A standard build has the following structure:
265 // ../top/
266 // out/ - make install files go here.
Colin Cross3b1c6842024-07-26 11:52:57 -0700267 // out/soong - this is the outDir passed to NewTestConfig()
Paul Duffin85d8f0d2021-03-24 10:18:18 +0000268 // ... - the source files
269 //
270 // This function converts a path so that it appears relative to the ../top/ directory, i.e.
Colin Cross3b1c6842024-07-26 11:52:57 -0700271 // * Make install paths, which have the pattern "outDir/../<path>" are converted into the top
Paul Duffin85d8f0d2021-03-24 10:18:18 +0000272 // relative path "out/<path>"
Colin Cross3b1c6842024-07-26 11:52:57 -0700273 // * Soong install paths and other writable paths, which have the pattern "outDir/soong/<path>" are
Paul Duffin85d8f0d2021-03-24 10:18:18 +0000274 // converted into the top relative path "out/soong/<path>".
275 // * Source paths are already relative to the top.
276 // * Phony paths are not relative to anything.
277 // * toolDepPath have an absolute but known value in so don't need making relative to anything in
278 // order to test.
279 RelativeToTop() Path
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700280}
281
Paul Duffin85d8f0d2021-03-24 10:18:18 +0000282const (
Colin Cross3b1c6842024-07-26 11:52:57 -0700283 testOutDir = "out"
284 testOutSoongSubDir = "/soong"
285 TestOutSoongDir = testOutDir + testOutSoongSubDir
Paul Duffin85d8f0d2021-03-24 10:18:18 +0000286)
287
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700288// WritablePath is a type of path that can be used as an output for build rules.
289type WritablePath interface {
290 Path
291
Paul Duffin9b478b02019-12-10 13:41:51 +0000292 // return the path to the build directory.
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +0200293 getSoongOutDir() string
Paul Duffin9b478b02019-12-10 13:41:51 +0000294
Jeff Gaston734e3802017-04-10 15:47:24 -0700295 // the writablePath method doesn't directly do anything,
296 // but it allows a struct to distinguish between whether or not it implements the WritablePath interface
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700297 writablePath()
Hans MÃ¥nssond3f2bd72020-11-27 12:37:28 +0100298
299 ReplaceExtension(ctx PathContext, ext string) OutputPath
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700300}
301
302type genPathProvider interface {
Liz Kammera830f3a2020-11-10 10:50:34 -0800303 genPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleGenPath
yangbill6d032dd2024-04-18 03:05:49 +0000304 genPathWithExtAndTrimExt(ctx ModuleOutPathContext, subdir, ext string, trimExt string) ModuleGenPath
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700305}
306type objPathProvider interface {
Liz Kammera830f3a2020-11-10 10:50:34 -0800307 objPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleObjPath
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700308}
309type resPathProvider interface {
Liz Kammera830f3a2020-11-10 10:50:34 -0800310 resPathWithName(ctx ModuleOutPathContext, name string) ModuleResPath
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700311}
312
313// GenPathWithExt derives a new file path in ctx's generated sources directory
314// from the current path, but with the new extension.
Liz Kammera830f3a2020-11-10 10:50:34 -0800315func GenPathWithExt(ctx ModuleOutPathContext, subdir string, p Path, ext string) ModuleGenPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700316 if path, ok := p.(genPathProvider); ok {
Dan Willemsen21ec4902016-11-02 20:43:13 -0700317 return path.genPathWithExt(ctx, subdir, ext)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700318 }
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +0100319 ReportPathErrorf(ctx, "Tried to create generated file from unsupported path: %s(%s)", reflect.TypeOf(p).Name(), p)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700320 return PathForModuleGen(ctx)
321}
322
yangbill6d032dd2024-04-18 03:05:49 +0000323// GenPathWithExtAndTrimExt derives a new file path in ctx's generated sources directory
324// from the current path, but with the new extension and trim the suffix.
325func GenPathWithExtAndTrimExt(ctx ModuleOutPathContext, subdir string, p Path, ext string, trimExt string) ModuleGenPath {
326 if path, ok := p.(genPathProvider); ok {
327 return path.genPathWithExtAndTrimExt(ctx, subdir, ext, trimExt)
328 }
329 ReportPathErrorf(ctx, "Tried to create generated file from unsupported path: %s(%s)", reflect.TypeOf(p).Name(), p)
330 return PathForModuleGen(ctx)
331}
332
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700333// ObjPathWithExt derives a new file path in ctx's object directory from the
334// current path, but with the new extension.
Liz Kammera830f3a2020-11-10 10:50:34 -0800335func ObjPathWithExt(ctx ModuleOutPathContext, subdir string, p Path, ext string) ModuleObjPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700336 if path, ok := p.(objPathProvider); ok {
337 return path.objPathWithExt(ctx, subdir, ext)
338 }
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +0100339 ReportPathErrorf(ctx, "Tried to create object file from unsupported path: %s (%s)", reflect.TypeOf(p).Name(), p)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700340 return PathForModuleObj(ctx)
341}
342
343// ResPathWithName derives a new path in ctx's output resource directory, using
344// the current path to create the directory name, and the `name` argument for
345// the filename.
Liz Kammera830f3a2020-11-10 10:50:34 -0800346func ResPathWithName(ctx ModuleOutPathContext, p Path, name string) ModuleResPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700347 if path, ok := p.(resPathProvider); ok {
348 return path.resPathWithName(ctx, name)
349 }
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +0100350 ReportPathErrorf(ctx, "Tried to create res file from unsupported path: %s (%s)", reflect.TypeOf(p).Name(), p)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700351 return PathForModuleRes(ctx)
352}
353
354// OptionalPath is a container that may or may not contain a valid Path.
355type OptionalPath struct {
Martin Stjernholmc32dd1c2021-09-15 02:39:00 +0100356 path Path // nil if invalid.
357 invalidReason string // Not applicable if path != nil. "" if the reason is unknown.
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700358}
359
Yu Liu467d7c52024-09-18 21:54:44 +0000360type optionalPathGob struct {
361 Path Path
362 InvalidReason string
363}
364
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700365// OptionalPathForPath returns an OptionalPath containing the path.
366func OptionalPathForPath(path Path) OptionalPath {
Martin Stjernholm2fee27f2021-09-16 14:11:12 +0100367 return OptionalPath{path: path}
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700368}
369
Martin Stjernholmc32dd1c2021-09-15 02:39:00 +0100370// InvalidOptionalPath returns an OptionalPath that is invalid with the given reason.
371func InvalidOptionalPath(reason string) OptionalPath {
372
373 return OptionalPath{invalidReason: reason}
374}
375
Yu Liu467d7c52024-09-18 21:54:44 +0000376func (p *OptionalPath) ToGob() *optionalPathGob {
377 return &optionalPathGob{
378 Path: p.path,
379 InvalidReason: p.invalidReason,
380 }
381}
382
383func (p *OptionalPath) FromGob(data *optionalPathGob) {
384 p.path = data.Path
385 p.invalidReason = data.InvalidReason
386}
387
388func (p OptionalPath) GobEncode() ([]byte, error) {
Yu Liu3cadf7d2024-10-24 18:47:06 +0000389 return gobtools.CustomGobEncode[optionalPathGob](&p)
Yu Liu467d7c52024-09-18 21:54:44 +0000390}
391
392func (p *OptionalPath) GobDecode(data []byte) error {
Yu Liu3cadf7d2024-10-24 18:47:06 +0000393 return gobtools.CustomGobDecode[optionalPathGob](data, p)
Yu Liu467d7c52024-09-18 21:54:44 +0000394}
395
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700396// Valid returns whether there is a valid path
397func (p OptionalPath) Valid() bool {
Martin Stjernholm2fee27f2021-09-16 14:11:12 +0100398 return p.path != nil
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700399}
400
401// Path returns the Path embedded in this OptionalPath. You must be sure that
402// there is a valid path, since this method will panic if there is not.
403func (p OptionalPath) Path() Path {
Martin Stjernholm2fee27f2021-09-16 14:11:12 +0100404 if p.path == nil {
Martin Stjernholmc32dd1c2021-09-15 02:39:00 +0100405 msg := "Requesting an invalid path"
406 if p.invalidReason != "" {
407 msg += ": " + p.invalidReason
408 }
409 panic(msg)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700410 }
411 return p.path
412}
413
Martin Stjernholmc32dd1c2021-09-15 02:39:00 +0100414// InvalidReason returns the reason that the optional path is invalid, or "" if it is valid.
415func (p OptionalPath) InvalidReason() string {
416 if p.path != nil {
417 return ""
418 }
419 if p.invalidReason == "" {
420 return "unknown"
421 }
422 return p.invalidReason
423}
424
Paul Duffinef081852021-05-13 11:11:15 +0100425// AsPaths converts the OptionalPath into Paths.
426//
427// It returns nil if this is not valid, or a single length slice containing the Path embedded in
428// this OptionalPath.
429func (p OptionalPath) AsPaths() Paths {
Martin Stjernholm2fee27f2021-09-16 14:11:12 +0100430 if p.path == nil {
Paul Duffinef081852021-05-13 11:11:15 +0100431 return nil
432 }
433 return Paths{p.path}
434}
435
Paul Duffinafdd4062021-03-30 19:44:07 +0100436// RelativeToTop returns an OptionalPath with the path that was embedded having been replaced by the
437// result of calling Path.RelativeToTop on it.
438func (p OptionalPath) RelativeToTop() OptionalPath {
Martin Stjernholm2fee27f2021-09-16 14:11:12 +0100439 if p.path == nil {
Paul Duffina5b81352021-03-28 23:57:19 +0100440 return p
441 }
442 p.path = p.path.RelativeToTop()
443 return p
444}
445
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700446// String returns the string version of the Path, or "" if it isn't valid.
447func (p OptionalPath) String() string {
Martin Stjernholm2fee27f2021-09-16 14:11:12 +0100448 if p.path != nil {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700449 return p.path.String()
450 } else {
451 return ""
Colin Crossf2298272015-05-12 11:36:53 -0700452 }
453}
Colin Cross6e18ca42015-07-14 18:55:36 -0700454
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700455// Paths is a slice of Path objects, with helpers to operate on the collection.
456type Paths []Path
457
Paul Duffin85d8f0d2021-03-24 10:18:18 +0000458// RelativeToTop creates a new Paths containing the result of calling Path.RelativeToTop on each
459// item in this slice.
460func (p Paths) RelativeToTop() Paths {
461 ensureTestOnly()
462 if p == nil {
463 return p
464 }
465 ret := make(Paths, len(p))
466 for i, path := range p {
467 ret[i] = path.RelativeToTop()
468 }
469 return ret
470}
471
Jingwen Chen40fd90a2020-06-15 05:24:19 +0000472func (paths Paths) containsPath(path Path) bool {
473 for _, p := range paths {
474 if p == path {
475 return true
476 }
477 }
478 return false
479}
480
Liz Kammer7aa52882021-02-11 09:16:14 -0500481// PathsForSource returns Paths rooted from SrcDir, *not* rooted from the module's local source
482// directory
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700483func PathsForSource(ctx PathContext, paths []string) Paths {
484 ret := make(Paths, len(paths))
485 for i, path := range paths {
486 ret[i] = PathForSource(ctx, path)
487 }
488 return ret
489}
490
Liz Kammer7aa52882021-02-11 09:16:14 -0500491// ExistentPathsForSources returns a list of Paths rooted from SrcDir, *not* rooted from the
492// module's local source directory, that are found in the tree. If any are not found, they are
493// 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 -0700494func ExistentPathsForSources(ctx PathGlobContext, paths []string) Paths {
Dan Willemsen7b310ee2015-12-18 15:11:17 -0800495 ret := make(Paths, 0, len(paths))
496 for _, path := range paths {
Colin Cross32f38982018-02-22 11:47:25 -0800497 p := ExistentPathForSource(ctx, path)
Dan Willemsen7b310ee2015-12-18 15:11:17 -0800498 if p.Valid() {
499 ret = append(ret, p.Path())
500 }
501 }
502 return ret
503}
504
Liz Kammer620dea62021-04-14 17:36:10 -0400505// PathsForModuleSrc returns a Paths{} containing the resolved references in paths:
Colin Crossd079e0b2022-08-16 10:27:33 -0700506// - filepath, relative to local module directory, resolves as a filepath relative to the local
507// source directory
508// - glob, relative to the local module directory, resolves as filepath(s), relative to the local
509// source directory.
510// - other modules using the ":name{.tag}" syntax. These modules must implement SourceFileProducer
mrziwangd38e63d2024-07-15 13:43:37 -0700511// or set the OutputFilesProvider. These resolve as a filepath to an output filepath or generated
512// source filepath.
Colin Crossd079e0b2022-08-16 10:27:33 -0700513//
Liz Kammer620dea62021-04-14 17:36:10 -0400514// Properties passed as the paths argument must have been annotated with struct tag
Colin Cross41955e82019-05-29 14:40:35 -0700515// `android:"path"` so that dependencies on SourceFileProducer modules will have already been handled by the
Spandan Das950091c2023-07-19 22:26:37 +0000516// pathdeps mutator.
Liz Kammer620dea62021-04-14 17:36:10 -0400517// If a requested module is not found as a dependency:
Colin Crossd079e0b2022-08-16 10:27:33 -0700518// - if ctx.Config().AllowMissingDependencies() is true, this module to be marked as having
Liz Kammer620dea62021-04-14 17:36:10 -0400519// missing dependencies
Colin Crossd079e0b2022-08-16 10:27:33 -0700520// - otherwise, a ModuleError is thrown.
Liz Kammera830f3a2020-11-10 10:50:34 -0800521func PathsForModuleSrc(ctx ModuleMissingDepsPathContext, paths []string) Paths {
Colin Cross8a497952019-03-05 22:25:09 -0800522 return PathsForModuleSrcExcludes(ctx, paths, nil)
523}
524
Liz Kammer619be462022-01-28 15:13:39 -0500525type SourceInput struct {
526 Context ModuleMissingDepsPathContext
527 Paths []string
528 ExcludePaths []string
529 IncludeDirs bool
530}
531
Liz Kammer620dea62021-04-14 17:36:10 -0400532// PathsForModuleSrcExcludes returns a Paths{} containing the resolved references in paths, minus
533// those listed in excludes. Elements of paths and excludes are resolved as:
Colin Crossd079e0b2022-08-16 10:27:33 -0700534// - filepath, relative to local module directory, resolves as a filepath relative to the local
535// source directory
536// - glob, relative to the local module directory, resolves as filepath(s), relative to the local
537// source directory. Not valid in excludes.
538// - other modules using the ":name{.tag}" syntax. These modules must implement SourceFileProducer
mrziwangd38e63d2024-07-15 13:43:37 -0700539// or set the OutputFilesProvider. These resolve as a filepath to an output filepath or generated
540// source filepath.
Colin Crossd079e0b2022-08-16 10:27:33 -0700541//
Liz Kammer620dea62021-04-14 17:36:10 -0400542// excluding the items (similarly resolved
543// Properties passed as the paths argument must have been annotated with struct tag
544// `android:"path"` so that dependencies on SourceFileProducer modules will have already been handled by the
Spandan Das950091c2023-07-19 22:26:37 +0000545// pathdeps mutator.
Liz Kammer620dea62021-04-14 17:36:10 -0400546// If a requested module is not found as a dependency:
Colin Crossd079e0b2022-08-16 10:27:33 -0700547// - if ctx.Config().AllowMissingDependencies() is true, this module to be marked as having
Liz Kammer620dea62021-04-14 17:36:10 -0400548// missing dependencies
Colin Crossd079e0b2022-08-16 10:27:33 -0700549// - otherwise, a ModuleError is thrown.
Liz Kammera830f3a2020-11-10 10:50:34 -0800550func PathsForModuleSrcExcludes(ctx ModuleMissingDepsPathContext, paths, excludes []string) Paths {
Liz Kammer619be462022-01-28 15:13:39 -0500551 return PathsRelativeToModuleSourceDir(SourceInput{
552 Context: ctx,
553 Paths: paths,
554 ExcludePaths: excludes,
555 IncludeDirs: true,
556 })
557}
558
559func PathsRelativeToModuleSourceDir(input SourceInput) Paths {
560 ret, missingDeps := PathsAndMissingDepsRelativeToModuleSourceDir(input)
561 if input.Context.Config().AllowMissingDependencies() {
562 input.Context.AddMissingDependencies(missingDeps)
Colin Crossba71a3f2019-03-18 12:12:48 -0700563 } else {
564 for _, m := range missingDeps {
Liz Kammer619be462022-01-28 15:13:39 -0500565 input.Context.ModuleErrorf(`missing dependency on %q, is the property annotated with android:"path"?`, m)
Colin Crossba71a3f2019-03-18 12:12:48 -0700566 }
567 }
568 return ret
569}
570
Inseob Kim93036a52024-10-25 17:02:21 +0900571type directoryPath struct {
572 basePath
573}
574
575func (d *directoryPath) String() string {
576 return d.basePath.String()
577}
578
579func (d *directoryPath) base() basePath {
580 return d.basePath
581}
582
583// DirectoryPath represents a source path for directories. Incompatible with Path by design.
584type DirectoryPath interface {
585 String() string
586 base() basePath
587}
588
589var _ DirectoryPath = (*directoryPath)(nil)
590
591type DirectoryPaths []DirectoryPath
592
Inseob Kim76e19852024-10-10 17:57:22 +0900593// DirectoryPathsForModuleSrcExcludes returns a Paths{} containing the resolved references in
594// directory paths. Elements of paths are resolved as:
595// - filepath, relative to local module directory, resolves as a filepath relative to the local
596// source directory
597// - other modules using the ":name" syntax. These modules must implement DirProvider.
Inseob Kim93036a52024-10-25 17:02:21 +0900598func DirectoryPathsForModuleSrc(ctx ModuleMissingDepsPathContext, paths []string) DirectoryPaths {
599 var ret DirectoryPaths
Inseob Kim76e19852024-10-10 17:57:22 +0900600
601 for _, path := range paths {
602 if m, t := SrcIsModuleWithTag(path); m != "" {
Yu Liud3228ac2024-11-08 23:11:47 +0000603 module := GetModuleProxyFromPathDep(ctx, m, t)
Inseob Kim76e19852024-10-10 17:57:22 +0900604 if module == nil {
605 ctx.ModuleErrorf(`missing dependency on %q, is the property annotated with android:"path"?`, m)
606 continue
607 }
608 if t != "" {
609 ctx.ModuleErrorf("DirProvider dependency %q does not support the tag %q", module, t)
610 continue
611 }
612 mctx, ok := ctx.(OtherModuleProviderContext)
613 if !ok {
614 panic(fmt.Errorf("%s is not an OtherModuleProviderContext", ctx))
615 }
Yu Liud3228ac2024-11-08 23:11:47 +0000616 if dirProvider, ok := OtherModuleProvider(mctx, *module, DirProvider); ok {
Inseob Kim76e19852024-10-10 17:57:22 +0900617 ret = append(ret, dirProvider.Dirs...)
618 } else {
619 ReportPathErrorf(ctx, "module %q does not implement DirProvider", module)
620 }
621 } else {
622 p := pathForModuleSrc(ctx, path)
623 if isDir, err := ctx.Config().fs.IsDir(p.String()); err != nil {
624 ReportPathErrorf(ctx, "%s: %s", p, err.Error())
625 } else if !isDir {
626 ReportPathErrorf(ctx, "module directory path %q is not a directory", p)
627 } else {
Inseob Kim93036a52024-10-25 17:02:21 +0900628 ret = append(ret, &directoryPath{basePath{path: p.path, rel: p.rel}})
Inseob Kim76e19852024-10-10 17:57:22 +0900629 }
630 }
631 }
632
Inseob Kim93036a52024-10-25 17:02:21 +0900633 seen := make(map[DirectoryPath]bool, len(ret))
Inseob Kim76e19852024-10-10 17:57:22 +0900634 for _, path := range ret {
635 if seen[path] {
636 ReportPathErrorf(ctx, "duplicated path %q", path)
637 }
638 seen[path] = true
639 }
640 return ret
641}
642
Ulya Trafimovich4d2eeed2019-11-08 10:54:21 +0000643// OutputPaths is a slice of OutputPath objects, with helpers to operate on the collection.
644type OutputPaths []OutputPath
645
646// Paths returns the OutputPaths as a Paths
647func (p OutputPaths) Paths() Paths {
648 if p == nil {
649 return nil
650 }
651 ret := make(Paths, len(p))
652 for i, path := range p {
653 ret[i] = path
654 }
655 return ret
656}
657
658// Strings returns the string forms of the writable paths.
659func (p OutputPaths) Strings() []string {
660 if p == nil {
661 return nil
662 }
663 ret := make([]string, len(p))
664 for i, path := range p {
665 ret[i] = path.String()
666 }
667 return ret
668}
669
Liz Kammera830f3a2020-11-10 10:50:34 -0800670// Expands Paths to a SourceFileProducer or OutputFileProducer module dependency referenced via ":name" or ":name{.tag}" syntax.
671// If the dependency is not found, a missingErrorDependency is returned.
672// If the module dependency is not a SourceFileProducer or OutputFileProducer, appropriate errors will be returned.
673func getPathsFromModuleDep(ctx ModuleWithDepsPathContext, path, moduleName, tag string) (Paths, error) {
Yu Liud3228ac2024-11-08 23:11:47 +0000674 module := GetModuleProxyFromPathDep(ctx, moduleName, tag)
Liz Kammera830f3a2020-11-10 10:50:34 -0800675 if module == nil {
676 return nil, missingDependencyError{[]string{moduleName}}
677 }
Yu Liub5275322024-11-13 18:40:43 +0000678 if !OtherModuleProviderOrDefault(ctx, *module, CommonModuleInfoKey).Enabled {
Colin Crossfa65cee2021-03-22 17:05:59 -0700679 return nil, missingDependencyError{[]string{moduleName}}
680 }
Yu Liud3228ac2024-11-08 23:11:47 +0000681
682 outputFiles, err := outputFilesForModule(ctx, *module, tag)
mrziwange6c85812024-05-22 14:36:09 -0700683 if outputFiles != nil && err == nil {
684 return outputFiles, nil
Liz Kammera830f3a2020-11-10 10:50:34 -0800685 } else {
mrziwange6c85812024-05-22 14:36:09 -0700686 return nil, err
Liz Kammera830f3a2020-11-10 10:50:34 -0800687 }
688}
689
Yu Liud3228ac2024-11-08 23:11:47 +0000690// GetModuleProxyFromPathDep will return the module that was added as a dependency automatically for
Paul Duffind5cf92e2021-07-09 17:38:55 +0100691// properties tagged with `android:"path"` or manually using ExtractSourceDeps or
692// ExtractSourcesDeps.
693//
694// The moduleName and tag supplied to this should be the values returned from SrcIsModuleWithTag.
695// Or, if no tag is expected then the moduleName should be the value returned by SrcIsModule and
696// the tag must be "".
697//
698// If tag is "" then the returned module will be the dependency that was added for ":moduleName".
699// Otherwise, it is the dependency that was added for ":moduleName{tag}".
Yu Liud3228ac2024-11-08 23:11:47 +0000700func GetModuleProxyFromPathDep(ctx ModuleWithDepsPathContext, moduleName, tag string) *ModuleProxy {
701 var found *ModuleProxy
702 // The sourceOrOutputDepTag uniquely identifies the module dependency as it contains both the
703 // module name and the tag. Dependencies added automatically for properties tagged with
704 // `android:"path"` are deduped so are guaranteed to be unique. It is possible for duplicate
705 // dependencies to be added manually using ExtractSourcesDeps or ExtractSourceDeps but even then
706 // it will always be the case that the dependencies will be identical, i.e. the same tag and same
707 // moduleName referring to the same dependency module.
708 //
709 // It does not matter whether the moduleName is a fully qualified name or if the module
710 // dependency is a prebuilt module. All that matters is the same information is supplied to
711 // create the tag here as was supplied to create the tag when the dependency was added so that
712 // this finds the matching dependency module.
713 expectedTag := sourceOrOutputDepTag(moduleName, tag)
714 ctx.VisitDirectDepsProxyWithTag(expectedTag, func(module ModuleProxy) {
715 found = &module
716 })
717 return found
718}
719
720// Deprecated: use GetModuleProxyFromPathDep
Paul Duffind5cf92e2021-07-09 17:38:55 +0100721func GetModuleFromPathDep(ctx ModuleWithDepsPathContext, moduleName, tag string) blueprint.Module {
Paul Duffin40131a32021-07-09 17:10:35 +0100722 var found blueprint.Module
723 // The sourceOrOutputDepTag uniquely identifies the module dependency as it contains both the
724 // module name and the tag. Dependencies added automatically for properties tagged with
725 // `android:"path"` are deduped so are guaranteed to be unique. It is possible for duplicate
726 // dependencies to be added manually using ExtractSourcesDeps or ExtractSourceDeps but even then
727 // it will always be the case that the dependencies will be identical, i.e. the same tag and same
728 // moduleName referring to the same dependency module.
729 //
730 // It does not matter whether the moduleName is a fully qualified name or if the module
731 // dependency is a prebuilt module. All that matters is the same information is supplied to
732 // create the tag here as was supplied to create the tag when the dependency was added so that
733 // this finds the matching dependency module.
734 expectedTag := sourceOrOutputDepTag(moduleName, tag)
Colin Cross648daea2024-09-12 14:35:29 -0700735 ctx.VisitDirectDeps(func(module Module) {
Paul Duffin40131a32021-07-09 17:10:35 +0100736 depTag := ctx.OtherModuleDependencyTag(module)
737 if depTag == expectedTag {
738 found = module
739 }
740 })
741 return found
Paul Duffind5cf92e2021-07-09 17:38:55 +0100742}
743
Liz Kammer620dea62021-04-14 17:36:10 -0400744// PathsAndMissingDepsForModuleSrcExcludes returns a Paths{} containing the resolved references in
745// paths, minus those listed in excludes. Elements of paths and excludes are resolved as:
Colin Crossd079e0b2022-08-16 10:27:33 -0700746// - filepath, relative to local module directory, resolves as a filepath relative to the local
747// source directory
748// - glob, relative to the local module directory, resolves as filepath(s), relative to the local
749// source directory. Not valid in excludes.
750// - other modules using the ":name{.tag}" syntax. These modules must implement SourceFileProducer
mrziwangd38e63d2024-07-15 13:43:37 -0700751// or set the OutputFilesProvider. These resolve as a filepath to an output filepath or generated
752// source filepath.
Colin Crossd079e0b2022-08-16 10:27:33 -0700753//
Liz Kammer620dea62021-04-14 17:36:10 -0400754// and a list of the module names of missing module dependencies are returned as the second return.
755// Properties passed as the paths argument must have been annotated with struct tag
Colin Cross41955e82019-05-29 14:40:35 -0700756// `android:"path"` so that dependencies on SourceFileProducer modules will have already been handled by the
Spandan Das950091c2023-07-19 22:26:37 +0000757// pathdeps mutator.
Liz Kammer619be462022-01-28 15:13:39 -0500758func PathsAndMissingDepsForModuleSrcExcludes(ctx ModuleMissingDepsPathContext, paths, excludes []string) (Paths, []string) {
759 return PathsAndMissingDepsRelativeToModuleSourceDir(SourceInput{
760 Context: ctx,
761 Paths: paths,
762 ExcludePaths: excludes,
763 IncludeDirs: true,
764 })
765}
766
767func PathsAndMissingDepsRelativeToModuleSourceDir(input SourceInput) (Paths, []string) {
768 prefix := pathForModuleSrc(input.Context).String()
Colin Cross8a497952019-03-05 22:25:09 -0800769
770 var expandedExcludes []string
Liz Kammer619be462022-01-28 15:13:39 -0500771 if input.ExcludePaths != nil {
772 expandedExcludes = make([]string, 0, len(input.ExcludePaths))
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700773 }
Colin Cross8a497952019-03-05 22:25:09 -0800774
Colin Crossba71a3f2019-03-18 12:12:48 -0700775 var missingExcludeDeps []string
Liz Kammer619be462022-01-28 15:13:39 -0500776 for _, e := range input.ExcludePaths {
Colin Cross41955e82019-05-29 14:40:35 -0700777 if m, t := SrcIsModuleWithTag(e); m != "" {
Liz Kammer619be462022-01-28 15:13:39 -0500778 modulePaths, err := getPathsFromModuleDep(input.Context, e, m, t)
Liz Kammera830f3a2020-11-10 10:50:34 -0800779 if m, ok := err.(missingDependencyError); ok {
780 missingExcludeDeps = append(missingExcludeDeps, m.missingDeps...)
781 } else if err != nil {
Liz Kammer619be462022-01-28 15:13:39 -0500782 reportPathError(input.Context, err)
Colin Cross8a497952019-03-05 22:25:09 -0800783 } else {
Liz Kammera830f3a2020-11-10 10:50:34 -0800784 expandedExcludes = append(expandedExcludes, modulePaths.Strings()...)
Colin Cross8a497952019-03-05 22:25:09 -0800785 }
786 } else {
787 expandedExcludes = append(expandedExcludes, filepath.Join(prefix, e))
788 }
789 }
790
Liz Kammer619be462022-01-28 15:13:39 -0500791 if input.Paths == nil {
Colin Crossba71a3f2019-03-18 12:12:48 -0700792 return nil, missingExcludeDeps
Colin Cross8a497952019-03-05 22:25:09 -0800793 }
794
Colin Crossba71a3f2019-03-18 12:12:48 -0700795 var missingDeps []string
796
Liz Kammer619be462022-01-28 15:13:39 -0500797 expandedSrcFiles := make(Paths, 0, len(input.Paths))
798 for _, s := range input.Paths {
799 srcFiles, err := expandOneSrcPath(sourcePathInput{
800 context: input.Context,
801 path: s,
802 expandedExcludes: expandedExcludes,
803 includeDirs: input.IncludeDirs,
804 })
Colin Cross8a497952019-03-05 22:25:09 -0800805 if depErr, ok := err.(missingDependencyError); ok {
Colin Crossba71a3f2019-03-18 12:12:48 -0700806 missingDeps = append(missingDeps, depErr.missingDeps...)
Colin Cross8a497952019-03-05 22:25:09 -0800807 } else if err != nil {
Liz Kammer619be462022-01-28 15:13:39 -0500808 reportPathError(input.Context, err)
Colin Cross8a497952019-03-05 22:25:09 -0800809 }
810 expandedSrcFiles = append(expandedSrcFiles, srcFiles...)
811 }
Colin Crossba71a3f2019-03-18 12:12:48 -0700812
Jihoon Kang0e3a5352024-04-12 00:45:50 +0000813 // TODO: b/334169722 - Replace with an error instead of implicitly removing duplicates.
814 return FirstUniquePaths(expandedSrcFiles), append(missingDeps, missingExcludeDeps...)
Colin Cross8a497952019-03-05 22:25:09 -0800815}
816
817type missingDependencyError struct {
818 missingDeps []string
819}
820
821func (e missingDependencyError) Error() string {
822 return "missing dependencies: " + strings.Join(e.missingDeps, ", ")
823}
824
Liz Kammer619be462022-01-28 15:13:39 -0500825type sourcePathInput struct {
826 context ModuleWithDepsPathContext
827 path string
828 expandedExcludes []string
829 includeDirs bool
830}
831
Liz Kammera830f3a2020-11-10 10:50:34 -0800832// Expands one path string to Paths rooted from the module's local source
833// directory, excluding those listed in the expandedExcludes.
834// Expands globs, references to SourceFileProducer or OutputFileProducer modules using the ":name" and ":name{.tag}" syntax.
Liz Kammer619be462022-01-28 15:13:39 -0500835func expandOneSrcPath(input sourcePathInput) (Paths, error) {
Jooyung Han7607dd32020-07-05 10:23:14 +0900836 excludePaths := func(paths Paths) Paths {
Liz Kammer619be462022-01-28 15:13:39 -0500837 if len(input.expandedExcludes) == 0 {
Jooyung Han7607dd32020-07-05 10:23:14 +0900838 return paths
839 }
840 remainder := make(Paths, 0, len(paths))
841 for _, p := range paths {
Liz Kammer619be462022-01-28 15:13:39 -0500842 if !InList(p.String(), input.expandedExcludes) {
Jooyung Han7607dd32020-07-05 10:23:14 +0900843 remainder = append(remainder, p)
844 }
845 }
846 return remainder
847 }
Liz Kammer619be462022-01-28 15:13:39 -0500848 if m, t := SrcIsModuleWithTag(input.path); m != "" {
849 modulePaths, err := getPathsFromModuleDep(input.context, input.path, m, t)
Liz Kammera830f3a2020-11-10 10:50:34 -0800850 if err != nil {
851 return nil, err
Colin Cross8a497952019-03-05 22:25:09 -0800852 } else {
Liz Kammera830f3a2020-11-10 10:50:34 -0800853 return excludePaths(modulePaths), nil
Colin Cross8a497952019-03-05 22:25:09 -0800854 }
Colin Cross8a497952019-03-05 22:25:09 -0800855 } else {
Liz Kammer619be462022-01-28 15:13:39 -0500856 p := pathForModuleSrc(input.context, input.path)
857 if pathtools.IsGlob(input.path) {
858 paths := GlobFiles(input.context, p.String(), input.expandedExcludes)
859 return PathsWithModuleSrcSubDir(input.context, paths, ""), nil
860 } else {
861 if exists, _, err := input.context.Config().fs.Exists(p.String()); err != nil {
862 ReportPathErrorf(input.context, "%s: %s", p, err.Error())
863 } else if !exists && !input.context.Config().TestAllowNonExistentPaths {
864 ReportPathErrorf(input.context, "module source path %q does not exist", p)
865 } else if !input.includeDirs {
866 if isDir, err := input.context.Config().fs.IsDir(p.String()); exists && err != nil {
867 ReportPathErrorf(input.context, "%s: %s", p, err.Error())
868 } else if isDir {
869 ReportPathErrorf(input.context, "module source path %q is a directory", p)
870 }
871 }
Colin Cross8a497952019-03-05 22:25:09 -0800872
Liz Kammer619be462022-01-28 15:13:39 -0500873 if InList(p.String(), input.expandedExcludes) {
874 return nil, nil
875 }
876 return Paths{p}, nil
Colin Cross8a497952019-03-05 22:25:09 -0800877 }
Colin Cross8a497952019-03-05 22:25:09 -0800878 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700879}
880
881// pathsForModuleSrcFromFullPath returns Paths rooted from the module's local
882// source directory, but strip the local source directory from the beginning of
Dan Willemsen540a78c2018-02-26 21:50:08 -0800883// each string. If incDirs is false, strip paths with a trailing '/' from the list.
Colin Crossfe4bc362018-09-12 10:02:13 -0700884// It intended for use in globs that only list files that exist, so it allows '$' in
885// filenames.
Liz Kammera830f3a2020-11-10 10:50:34 -0800886func pathsForModuleSrcFromFullPath(ctx EarlyModulePathContext, paths []string, incDirs bool) Paths {
Lukacs T. Berkif7e36d82021-08-16 17:05:09 +0200887 prefix := ctx.ModuleDir() + "/"
Colin Cross0f37af02017-09-27 17:42:05 -0700888 if prefix == "./" {
889 prefix = ""
890 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700891 ret := make(Paths, 0, len(paths))
892 for _, p := range paths {
Dan Willemsen540a78c2018-02-26 21:50:08 -0800893 if !incDirs && strings.HasSuffix(p, "/") {
894 continue
895 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700896 path := filepath.Clean(p)
897 if !strings.HasPrefix(path, prefix) {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +0100898 ReportPathErrorf(ctx, "Path %q is not in module source directory %q", p, prefix)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700899 continue
900 }
Colin Crosse3924e12018-08-15 20:18:53 -0700901
Colin Crossfe4bc362018-09-12 10:02:13 -0700902 srcPath, err := safePathForSource(ctx, ctx.ModuleDir(), path[len(prefix):])
Colin Crosse3924e12018-08-15 20:18:53 -0700903 if err != nil {
904 reportPathError(ctx, err)
905 continue
906 }
907
Colin Cross07e51612019-03-05 12:46:40 -0800908 srcPath.basePath.rel = srcPath.path
Colin Crosse3924e12018-08-15 20:18:53 -0700909
Colin Cross07e51612019-03-05 12:46:40 -0800910 ret = append(ret, srcPath)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700911 }
912 return ret
913}
914
Liz Kammera830f3a2020-11-10 10:50:34 -0800915// PathsWithOptionalDefaultForModuleSrc returns Paths rooted from the module's local source
916// directory. If input is nil, use the default if it exists. If input is empty, returns nil.
917func PathsWithOptionalDefaultForModuleSrc(ctx ModuleMissingDepsPathContext, input []string, def string) Paths {
Colin Cross0ddae7f2019-02-07 15:30:01 -0800918 if input != nil {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700919 return PathsForModuleSrc(ctx, input)
920 }
921 // Use Glob so that if the default doesn't exist, a dependency is added so that when it
922 // is created, we're run again.
Lukacs T. Berkif7e36d82021-08-16 17:05:09 +0200923 path := filepath.Join(ctx.ModuleDir(), def)
Liz Kammera830f3a2020-11-10 10:50:34 -0800924 return Glob(ctx, path, nil)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700925}
926
927// Strings returns the Paths in string form
928func (p Paths) Strings() []string {
929 if p == nil {
930 return nil
931 }
932 ret := make([]string, len(p))
933 for i, path := range p {
934 ret[i] = path.String()
935 }
936 return ret
937}
938
Colin Crossc0efd1d2020-07-03 11:56:24 -0700939func CopyOfPaths(paths Paths) Paths {
940 return append(Paths(nil), paths...)
941}
942
Colin Crossb6715442017-10-24 11:13:31 -0700943// FirstUniquePaths returns all unique elements of a Paths, keeping the first copy of each. It
944// modifies the Paths slice contents in place, and returns a subslice of the original slice.
Dan Willemsenfe92c962017-08-29 12:28:37 -0700945func FirstUniquePaths(list Paths) Paths {
Colin Cross27027c72020-02-28 15:34:17 -0800946 // 128 was chosen based on BenchmarkFirstUniquePaths results.
947 if len(list) > 128 {
948 return firstUniquePathsMap(list)
949 }
950 return firstUniquePathsList(list)
951}
952
Colin Crossc0efd1d2020-07-03 11:56:24 -0700953// SortedUniquePaths returns all unique elements of a Paths in sorted order. It modifies the
954// Paths slice contents in place, and returns a subslice of the original slice.
Jiyong Park33c77362020-05-29 22:00:16 +0900955func SortedUniquePaths(list Paths) Paths {
956 unique := FirstUniquePaths(list)
957 sort.Slice(unique, func(i, j int) bool {
958 return unique[i].String() < unique[j].String()
959 })
960 return unique
961}
962
Colin Cross27027c72020-02-28 15:34:17 -0800963func firstUniquePathsList(list Paths) Paths {
Dan Willemsenfe92c962017-08-29 12:28:37 -0700964 k := 0
965outer:
966 for i := 0; i < len(list); i++ {
967 for j := 0; j < k; j++ {
968 if list[i] == list[j] {
969 continue outer
970 }
971 }
972 list[k] = list[i]
973 k++
974 }
975 return list[:k]
976}
977
Colin Cross27027c72020-02-28 15:34:17 -0800978func firstUniquePathsMap(list Paths) Paths {
979 k := 0
980 seen := make(map[Path]bool, len(list))
981 for i := 0; i < len(list); i++ {
982 if seen[list[i]] {
983 continue
984 }
985 seen[list[i]] = true
986 list[k] = list[i]
987 k++
988 }
989 return list[:k]
990}
991
Colin Cross5d583952020-11-24 16:21:24 -0800992// FirstUniqueInstallPaths returns all unique elements of an InstallPaths, keeping the first copy of each. It
993// modifies the InstallPaths slice contents in place, and returns a subslice of the original slice.
994func FirstUniqueInstallPaths(list InstallPaths) InstallPaths {
995 // 128 was chosen based on BenchmarkFirstUniquePaths results.
996 if len(list) > 128 {
997 return firstUniqueInstallPathsMap(list)
998 }
999 return firstUniqueInstallPathsList(list)
1000}
1001
1002func firstUniqueInstallPathsList(list InstallPaths) InstallPaths {
1003 k := 0
1004outer:
1005 for i := 0; i < len(list); i++ {
1006 for j := 0; j < k; j++ {
1007 if list[i] == list[j] {
1008 continue outer
1009 }
1010 }
1011 list[k] = list[i]
1012 k++
1013 }
1014 return list[:k]
1015}
1016
1017func firstUniqueInstallPathsMap(list InstallPaths) InstallPaths {
1018 k := 0
1019 seen := make(map[InstallPath]bool, len(list))
1020 for i := 0; i < len(list); i++ {
1021 if seen[list[i]] {
1022 continue
1023 }
1024 seen[list[i]] = true
1025 list[k] = list[i]
1026 k++
1027 }
1028 return list[:k]
1029}
1030
Colin Crossb6715442017-10-24 11:13:31 -07001031// LastUniquePaths returns all unique elements of a Paths, keeping the last copy of each. It
1032// modifies the Paths slice contents in place, and returns a subslice of the original slice.
1033func LastUniquePaths(list Paths) Paths {
1034 totalSkip := 0
1035 for i := len(list) - 1; i >= totalSkip; i-- {
1036 skip := 0
1037 for j := i - 1; j >= totalSkip; j-- {
1038 if list[i] == list[j] {
1039 skip++
1040 } else {
1041 list[j+skip] = list[j]
1042 }
1043 }
1044 totalSkip += skip
1045 }
1046 return list[totalSkip:]
1047}
1048
Colin Crossa140bb02018-04-17 10:52:26 -07001049// ReversePaths returns a copy of a Paths in reverse order.
1050func ReversePaths(list Paths) Paths {
1051 if list == nil {
1052 return nil
1053 }
1054 ret := make(Paths, len(list))
1055 for i := range list {
1056 ret[i] = list[len(list)-1-i]
1057 }
1058 return ret
1059}
1060
Jeff Gaston294356f2017-09-27 17:05:30 -07001061func indexPathList(s Path, list []Path) int {
1062 for i, l := range list {
1063 if l == s {
1064 return i
1065 }
1066 }
1067
1068 return -1
1069}
1070
1071func inPathList(p Path, list []Path) bool {
1072 return indexPathList(p, list) != -1
1073}
1074
1075func FilterPathList(list []Path, filter []Path) (remainder []Path, filtered []Path) {
Paul Duffin57b9e1d2019-12-13 00:03:35 +00001076 return FilterPathListPredicate(list, func(p Path) bool { return inPathList(p, filter) })
1077}
1078
1079func FilterPathListPredicate(list []Path, predicate func(Path) bool) (remainder []Path, filtered []Path) {
Jeff Gaston294356f2017-09-27 17:05:30 -07001080 for _, l := range list {
Paul Duffin57b9e1d2019-12-13 00:03:35 +00001081 if predicate(l) {
Jeff Gaston294356f2017-09-27 17:05:30 -07001082 filtered = append(filtered, l)
1083 } else {
1084 remainder = append(remainder, l)
1085 }
1086 }
1087
1088 return
1089}
1090
Colin Cross93e85952017-08-15 13:34:18 -07001091// HasExt returns true of any of the paths have extension ext, otherwise false
1092func (p Paths) HasExt(ext string) bool {
1093 for _, path := range p {
1094 if path.Ext() == ext {
1095 return true
1096 }
1097 }
1098
1099 return false
1100}
1101
1102// FilterByExt returns the subset of the paths that have extension ext
1103func (p Paths) FilterByExt(ext string) Paths {
1104 ret := make(Paths, 0, len(p))
1105 for _, path := range p {
1106 if path.Ext() == ext {
1107 ret = append(ret, path)
1108 }
1109 }
1110 return ret
1111}
1112
1113// FilterOutByExt returns the subset of the paths that do not have extension ext
1114func (p Paths) FilterOutByExt(ext string) Paths {
1115 ret := make(Paths, 0, len(p))
1116 for _, path := range p {
1117 if path.Ext() != ext {
1118 ret = append(ret, path)
1119 }
1120 }
1121 return ret
1122}
1123
Colin Cross5e6cfbe2017-11-03 15:20:35 -07001124// DirectorySortedPaths is a slice of paths that are sorted such that all files in a directory
1125// (including subdirectories) are in a contiguous subslice of the list, and can be found in
1126// O(log(N)) time using a binary search on the directory prefix.
1127type DirectorySortedPaths Paths
1128
1129func PathsToDirectorySortedPaths(paths Paths) DirectorySortedPaths {
1130 ret := append(DirectorySortedPaths(nil), paths...)
1131 sort.Slice(ret, func(i, j int) bool {
1132 return ret[i].String() < ret[j].String()
1133 })
1134 return ret
1135}
1136
1137// PathsInDirectory returns a subslice of the DirectorySortedPaths as a Paths that contains all entries
1138// that are in the specified directory and its subdirectories.
1139func (p DirectorySortedPaths) PathsInDirectory(dir string) Paths {
1140 prefix := filepath.Clean(dir) + "/"
1141 start := sort.Search(len(p), func(i int) bool {
1142 return prefix < p[i].String()
1143 })
1144
1145 ret := p[start:]
1146
1147 end := sort.Search(len(ret), func(i int) bool {
1148 return !strings.HasPrefix(ret[i].String(), prefix)
1149 })
1150
1151 ret = ret[:end]
1152
1153 return Paths(ret)
1154}
1155
Alex Humesky29e3bbe2020-11-20 21:30:13 -05001156// WritablePaths is a slice of WritablePath, used for multiple outputs.
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001157type WritablePaths []WritablePath
1158
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001159// RelativeToTop creates a new WritablePaths containing the result of calling Path.RelativeToTop on
1160// each item in this slice.
1161func (p WritablePaths) RelativeToTop() WritablePaths {
1162 ensureTestOnly()
1163 if p == nil {
1164 return p
1165 }
1166 ret := make(WritablePaths, len(p))
1167 for i, path := range p {
1168 ret[i] = path.RelativeToTop().(WritablePath)
1169 }
1170 return ret
1171}
1172
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001173// Strings returns the string forms of the writable paths.
1174func (p WritablePaths) Strings() []string {
1175 if p == nil {
1176 return nil
1177 }
1178 ret := make([]string, len(p))
1179 for i, path := range p {
1180 ret[i] = path.String()
1181 }
1182 return ret
1183}
1184
Colin Cross3bc7ffa2017-11-22 16:19:37 -08001185// Paths returns the WritablePaths as a Paths
1186func (p WritablePaths) Paths() Paths {
1187 if p == nil {
1188 return nil
1189 }
1190 ret := make(Paths, len(p))
1191 for i, path := range p {
1192 ret[i] = path
1193 }
1194 return ret
1195}
1196
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001197type basePath struct {
Paul Duffin74abc5d2021-03-24 09:24:59 +00001198 path string
1199 rel string
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001200}
1201
Yu Liu467d7c52024-09-18 21:54:44 +00001202type basePathGob struct {
1203 Path string
1204 Rel string
1205}
Yu Liufa297642024-06-11 00:13:02 +00001206
Yu Liu467d7c52024-09-18 21:54:44 +00001207func (p *basePath) ToGob() *basePathGob {
1208 return &basePathGob{
1209 Path: p.path,
1210 Rel: p.rel,
1211 }
1212}
1213
1214func (p *basePath) FromGob(data *basePathGob) {
1215 p.path = data.Path
1216 p.rel = data.Rel
1217}
1218
1219func (p basePath) GobEncode() ([]byte, error) {
Yu Liu3cadf7d2024-10-24 18:47:06 +00001220 return gobtools.CustomGobEncode[basePathGob](&p)
Yu Liufa297642024-06-11 00:13:02 +00001221}
1222
1223func (p *basePath) GobDecode(data []byte) error {
Yu Liu3cadf7d2024-10-24 18:47:06 +00001224 return gobtools.CustomGobDecode[basePathGob](data, p)
Yu Liufa297642024-06-11 00:13:02 +00001225}
1226
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001227func (p basePath) Ext() string {
1228 return filepath.Ext(p.path)
1229}
1230
Colin Cross4f6fc9c2016-10-26 10:05:25 -07001231func (p basePath) Base() string {
1232 return filepath.Base(p.path)
1233}
1234
Colin Crossfaeb7aa2017-02-01 14:12:44 -08001235func (p basePath) Rel() string {
1236 if p.rel != "" {
1237 return p.rel
1238 }
1239 return p.path
1240}
1241
Colin Cross0875c522017-11-28 17:34:01 -08001242func (p basePath) String() string {
1243 return p.path
1244}
1245
Colin Cross0db55682017-12-05 15:36:55 -08001246func (p basePath) withRel(rel string) basePath {
1247 p.path = filepath.Join(p.path, rel)
1248 p.rel = rel
1249 return p
1250}
1251
Colin Cross7707b242024-07-26 12:02:36 -07001252func (p basePath) withoutRel() basePath {
1253 p.rel = filepath.Base(p.path)
Cole Faustbc65a3f2023-08-01 16:38:55 +00001254 return p
1255}
1256
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001257// SourcePath is a Path representing a file path rooted from SrcDir
1258type SourcePath struct {
1259 basePath
1260}
1261
1262var _ Path = SourcePath{}
1263
Colin Cross0db55682017-12-05 15:36:55 -08001264func (p SourcePath) withRel(rel string) SourcePath {
1265 p.basePath = p.basePath.withRel(rel)
1266 return p
1267}
1268
Colin Crossbd73d0d2024-07-26 12:00:33 -07001269func (p SourcePath) RelativeToTop() Path {
1270 ensureTestOnly()
1271 return p
1272}
1273
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001274// safePathForSource is for paths that we expect are safe -- only for use by go
1275// code that is embedding ninja variables in paths
Colin Crossfe4bc362018-09-12 10:02:13 -07001276func safePathForSource(ctx PathContext, pathComponents ...string) (SourcePath, error) {
1277 p, err := validateSafePath(pathComponents...)
Cole Faust483d1f72023-01-09 14:35:27 -08001278 ret := SourcePath{basePath{p, ""}}
Colin Crossfe4bc362018-09-12 10:02:13 -07001279 if err != nil {
1280 return ret, err
1281 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001282
Colin Cross7b3dcc32019-01-24 13:14:39 -08001283 // absolute path already checked by validateSafePath
Inseob Kim5eb7ee92022-04-27 10:30:34 +09001284 // special-case api surface gen files for now
1285 if strings.HasPrefix(ret.String(), ctx.Config().soongOutDir) && !strings.Contains(ret.String(), ctx.Config().soongOutDir+"/.export") {
Mikhail Naganovab1f5182019-02-08 13:17:55 -08001286 return ret, fmt.Errorf("source path %q is in output", ret.String())
Colin Cross6e18ca42015-07-14 18:55:36 -07001287 }
1288
Colin Crossfe4bc362018-09-12 10:02:13 -07001289 return ret, err
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001290}
1291
Colin Cross192e97a2018-02-22 14:21:02 -08001292// pathForSource creates a SourcePath from pathComponents, but does not check that it exists.
1293func pathForSource(ctx PathContext, pathComponents ...string) (SourcePath, error) {
Colin Crossc48c1432018-02-23 07:09:01 +00001294 p, err := validatePath(pathComponents...)
Cole Faust483d1f72023-01-09 14:35:27 -08001295 ret := SourcePath{basePath{p, ""}}
Colin Cross94a32102018-02-22 14:21:02 -08001296 if err != nil {
Colin Cross192e97a2018-02-22 14:21:02 -08001297 return ret, err
Colin Cross94a32102018-02-22 14:21:02 -08001298 }
1299
Colin Cross7b3dcc32019-01-24 13:14:39 -08001300 // absolute path already checked by validatePath
Inseob Kim5eb7ee92022-04-27 10:30:34 +09001301 // special-case for now
1302 if strings.HasPrefix(ret.String(), ctx.Config().soongOutDir) && !strings.Contains(ret.String(), ctx.Config().soongOutDir+"/.export") {
Mikhail Naganovab1f5182019-02-08 13:17:55 -08001303 return ret, fmt.Errorf("source path %q is in output", ret.String())
Colin Crossc48c1432018-02-23 07:09:01 +00001304 }
1305
Colin Cross192e97a2018-02-22 14:21:02 -08001306 return ret, nil
1307}
1308
Sam Mortimerefd02782019-09-05 15:16:13 -07001309// pathForSourceRelaxed creates a SourcePath from pathComponents, but does not check that it exists.
1310// It differs from pathForSource in that the path is allowed to exist outside of the PathContext.
1311func pathForSourceRelaxed(ctx PathContext, pathComponents ...string) (SourcePath, error) {
1312 p := filepath.Join(pathComponents...)
1313 ret := SourcePath{basePath{p, ""}}
1314
1315 abs, err := filepath.Abs(ret.String())
1316 if err != nil {
1317 return ret, err
1318 }
1319 buildroot, err := filepath.Abs(ctx.Config().outDir)
1320 if err != nil {
1321 return ret, err
1322 }
1323 if strings.HasPrefix(abs, buildroot) {
1324 return ret, fmt.Errorf("source path %s is in output", abs)
1325 }
1326
1327 if pathtools.IsGlob(ret.String()) {
1328 return ret, fmt.Errorf("path may not contain a glob: %s", ret.String())
1329 }
1330
1331 return ret, nil
1332}
1333
Colin Cross192e97a2018-02-22 14:21:02 -08001334// existsWithDependencies returns true if the path exists, and adds appropriate dependencies to rerun if the
1335// path does not exist.
Colin Cross662d6142022-11-03 20:38:01 -07001336func existsWithDependencies(ctx PathGlobContext, path SourcePath) (exists bool, err error) {
Colin Cross192e97a2018-02-22 14:21:02 -08001337 var files []string
1338
Colin Cross662d6142022-11-03 20:38:01 -07001339 // Use glob to produce proper dependencies, even though we only want
1340 // a single file.
1341 files, err = ctx.GlobWithDeps(path.String(), nil)
Colin Cross192e97a2018-02-22 14:21:02 -08001342
1343 if err != nil {
1344 return false, fmt.Errorf("glob: %s", err.Error())
1345 }
1346
1347 return len(files) > 0, nil
1348}
1349
1350// PathForSource joins the provided path components and validates that the result
1351// neither escapes the source dir nor is in the out dir.
1352// On error, it will return a usable, but invalid SourcePath, and report a ModuleError.
1353func PathForSource(ctx PathContext, pathComponents ...string) SourcePath {
1354 path, err := pathForSource(ctx, pathComponents...)
1355 if err != nil {
1356 reportPathError(ctx, err)
1357 }
1358
Colin Crosse3924e12018-08-15 20:18:53 -07001359 if pathtools.IsGlob(path.String()) {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001360 ReportPathErrorf(ctx, "path may not contain a glob: %s", path.String())
Colin Crosse3924e12018-08-15 20:18:53 -07001361 }
1362
Liz Kammera830f3a2020-11-10 10:50:34 -08001363 if modCtx, ok := ctx.(ModuleMissingDepsPathContext); ok && ctx.Config().AllowMissingDependencies() {
Colin Cross662d6142022-11-03 20:38:01 -07001364 exists, err := existsWithDependencies(modCtx, path)
Colin Cross192e97a2018-02-22 14:21:02 -08001365 if err != nil {
1366 reportPathError(ctx, err)
1367 }
1368 if !exists {
1369 modCtx.AddMissingDependencies([]string{path.String()})
1370 }
Colin Cross988414c2020-01-11 01:11:46 +00001371 } else if exists, _, err := ctx.Config().fs.Exists(path.String()); err != nil {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001372 ReportPathErrorf(ctx, "%s: %s", path, err.Error())
Pedro Loureiro5d190cc2021-02-15 15:41:33 +00001373 } else if !exists && !ctx.Config().TestAllowNonExistentPaths {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001374 ReportPathErrorf(ctx, "source path %q does not exist", path)
Colin Cross192e97a2018-02-22 14:21:02 -08001375 }
1376 return path
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001377}
1378
Cole Faustbc65a3f2023-08-01 16:38:55 +00001379// PathForArbitraryOutput creates a path for the given components. Unlike PathForOutput,
1380// the path is relative to the root of the output folder, not the out/soong folder.
1381func PathForArbitraryOutput(ctx PathContext, pathComponents ...string) Path {
Colin Cross3b1c6842024-07-26 11:52:57 -07001382 path, err := validatePath(pathComponents...)
Cole Faustbc65a3f2023-08-01 16:38:55 +00001383 if err != nil {
1384 reportPathError(ctx, err)
1385 }
Colin Cross3b1c6842024-07-26 11:52:57 -07001386 fullPath := filepath.Join(ctx.Config().OutDir(), path)
1387 path = fullPath[len(fullPath)-len(path):]
1388 return OutputPath{basePath{path, ""}, ctx.Config().OutDir(), fullPath}
Cole Faustbc65a3f2023-08-01 16:38:55 +00001389}
1390
Spandan Dasc6c10fa2022-10-21 21:52:13 +00001391// MaybeExistentPathForSource joins the provided path components and validates that the result
1392// neither escapes the source dir nor is in the out dir.
1393// It does not validate whether the path exists.
1394func MaybeExistentPathForSource(ctx PathContext, pathComponents ...string) SourcePath {
1395 path, err := pathForSource(ctx, pathComponents...)
1396 if err != nil {
1397 reportPathError(ctx, err)
1398 }
1399
1400 if pathtools.IsGlob(path.String()) {
1401 ReportPathErrorf(ctx, "path may not contain a glob: %s", path.String())
1402 }
1403 return path
1404}
1405
Sam Mortimerefd02782019-09-05 15:16:13 -07001406// PathForSourceRelaxed joins the provided path components. Unlike PathForSource,
1407// the result is allowed to exist outside of the source dir.
1408// On error, it will return a usable, but invalid SourcePath, and report a ModuleError.
1409func PathForSourceRelaxed(ctx PathContext, pathComponents ...string) SourcePath {
1410 path, err := pathForSourceRelaxed(ctx, pathComponents...)
1411 if err != nil {
1412 reportPathError(ctx, err)
1413 }
1414
1415 if modCtx, ok := ctx.(ModuleMissingDepsPathContext); ok && ctx.Config().AllowMissingDependencies() {
1416 exists, err := existsWithDependencies(modCtx, path)
1417 if err != nil {
1418 reportPathError(ctx, err)
1419 }
1420 if !exists {
1421 modCtx.AddMissingDependencies([]string{path.String()})
1422 }
1423 } else if exists, _, err := ctx.Config().fs.Exists(path.String()); err != nil {
1424 ReportPathErrorf(ctx, "%s: %s", path, err.Error())
1425 } else if !exists {
1426 ReportPathErrorf(ctx, "source path %s does not exist", path)
1427 }
1428 return path
1429}
1430
Liz Kammer7aa52882021-02-11 09:16:14 -05001431// ExistentPathForSource returns an OptionalPath with the SourcePath, rooted from SrcDir, *not*
1432// rooted from the module's local source directory, if the path exists, or an empty OptionalPath if
1433// it doesn't exist. Dependencies are added so that the ninja file will be regenerated if the state
1434// of the path changes.
Colin Cross662d6142022-11-03 20:38:01 -07001435func ExistentPathForSource(ctx PathGlobContext, pathComponents ...string) OptionalPath {
Colin Cross192e97a2018-02-22 14:21:02 -08001436 path, err := pathForSource(ctx, pathComponents...)
Colin Cross1ccfcc32018-02-22 13:54:26 -08001437 if err != nil {
1438 reportPathError(ctx, err)
Martin Stjernholmc32dd1c2021-09-15 02:39:00 +01001439 // No need to put the error message into the returned path since it has been reported already.
Colin Cross1ccfcc32018-02-22 13:54:26 -08001440 return OptionalPath{}
1441 }
Colin Crossc48c1432018-02-23 07:09:01 +00001442
Colin Crosse3924e12018-08-15 20:18:53 -07001443 if pathtools.IsGlob(path.String()) {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001444 ReportPathErrorf(ctx, "path may not contain a glob: %s", path.String())
Colin Crosse3924e12018-08-15 20:18:53 -07001445 return OptionalPath{}
1446 }
1447
Colin Cross192e97a2018-02-22 14:21:02 -08001448 exists, err := existsWithDependencies(ctx, path)
Colin Crossc48c1432018-02-23 07:09:01 +00001449 if err != nil {
1450 reportPathError(ctx, err)
1451 return OptionalPath{}
1452 }
Colin Cross192e97a2018-02-22 14:21:02 -08001453 if !exists {
Martin Stjernholmc32dd1c2021-09-15 02:39:00 +01001454 return InvalidOptionalPath(path.String() + " does not exist")
Colin Crossc48c1432018-02-23 07:09:01 +00001455 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001456 return OptionalPathForPath(path)
1457}
1458
1459func (p SourcePath) String() string {
Cole Faust483d1f72023-01-09 14:35:27 -08001460 if p.path == "" {
1461 return "."
1462 }
1463 return p.path
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001464}
1465
Colin Cross7707b242024-07-26 12:02:36 -07001466func (p SourcePath) WithoutRel() Path {
1467 p.basePath = p.basePath.withoutRel()
1468 return p
1469}
1470
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001471// Join creates a new SourcePath with paths... joined with the current path. The
1472// provided paths... may not use '..' to escape from the current path.
1473func (p SourcePath) Join(ctx PathContext, paths ...string) SourcePath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001474 path, err := validatePath(paths...)
1475 if err != nil {
1476 reportPathError(ctx, err)
1477 }
Colin Cross0db55682017-12-05 15:36:55 -08001478 return p.withRel(path)
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001479}
1480
Colin Cross2fafa3e2019-03-05 12:39:51 -08001481// join is like Join but does less path validation.
1482func (p SourcePath) join(ctx PathContext, paths ...string) SourcePath {
1483 path, err := validateSafePath(paths...)
1484 if err != nil {
1485 reportPathError(ctx, err)
1486 }
1487 return p.withRel(path)
1488}
1489
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001490// OverlayPath returns the overlay for `path' if it exists. This assumes that the
1491// SourcePath is the path to a resource overlay directory.
Liz Kammera830f3a2020-11-10 10:50:34 -08001492func (p SourcePath) OverlayPath(ctx ModuleMissingDepsPathContext, path Path) OptionalPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001493 var relDir string
Colin Cross07e51612019-03-05 12:46:40 -08001494 if srcPath, ok := path.(SourcePath); ok {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001495 relDir = srcPath.path
1496 } else {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001497 ReportPathErrorf(ctx, "Cannot find relative path for %s(%s)", reflect.TypeOf(path).Name(), path)
Martin Stjernholmc32dd1c2021-09-15 02:39:00 +01001498 // No need to put the error message into the returned path since it has been reported already.
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001499 return OptionalPath{}
1500 }
Cole Faust483d1f72023-01-09 14:35:27 -08001501 dir := filepath.Join(p.path, relDir)
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001502 // Use Glob so that we are run again if the directory is added.
Colin Cross7f19f372016-11-01 11:10:25 -07001503 if pathtools.IsGlob(dir) {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001504 ReportPathErrorf(ctx, "Path may not contain a glob: %s", dir)
Dan Willemsen7b310ee2015-12-18 15:11:17 -08001505 }
Colin Cross461b4452018-02-23 09:22:42 -08001506 paths, err := ctx.GlobWithDeps(dir, nil)
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001507 if err != nil {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001508 ReportPathErrorf(ctx, "glob: %s", err.Error())
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001509 return OptionalPath{}
1510 }
1511 if len(paths) == 0 {
Martin Stjernholmc32dd1c2021-09-15 02:39:00 +01001512 return InvalidOptionalPath(dir + " does not exist")
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001513 }
Cole Faust483d1f72023-01-09 14:35:27 -08001514 return OptionalPathForPath(PathForSource(ctx, paths[0]))
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001515}
1516
Colin Cross70dda7e2019-10-01 22:05:35 -07001517// OutputPath is a Path representing an intermediates file path rooted from the build directory
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001518type OutputPath struct {
1519 basePath
Paul Duffind65c58b2021-03-24 09:22:07 +00001520
Colin Cross3b1c6842024-07-26 11:52:57 -07001521 // The base out directory for this path, either Config.SoongOutDir() or Config.OutDir()
1522 outDir string
Paul Duffind65c58b2021-03-24 09:22:07 +00001523
Colin Crossd63c9a72020-01-29 16:52:50 -08001524 fullPath string
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001525}
1526
Yu Liu467d7c52024-09-18 21:54:44 +00001527type outputPathGob struct {
Yu Liu5246a7e2024-10-09 20:04:52 +00001528 BasePath basePath
Yu Liu467d7c52024-09-18 21:54:44 +00001529 OutDir string
1530 FullPath string
1531}
Yu Liufa297642024-06-11 00:13:02 +00001532
Yu Liu467d7c52024-09-18 21:54:44 +00001533func (p *OutputPath) ToGob() *outputPathGob {
1534 return &outputPathGob{
Yu Liu5246a7e2024-10-09 20:04:52 +00001535 BasePath: p.basePath,
Yu Liu467d7c52024-09-18 21:54:44 +00001536 OutDir: p.outDir,
1537 FullPath: p.fullPath,
1538 }
1539}
1540
1541func (p *OutputPath) FromGob(data *outputPathGob) {
Yu Liu5246a7e2024-10-09 20:04:52 +00001542 p.basePath = data.BasePath
Yu Liu467d7c52024-09-18 21:54:44 +00001543 p.outDir = data.OutDir
1544 p.fullPath = data.FullPath
1545}
1546
1547func (p OutputPath) GobEncode() ([]byte, error) {
Yu Liu3cadf7d2024-10-24 18:47:06 +00001548 return gobtools.CustomGobEncode[outputPathGob](&p)
Yu Liufa297642024-06-11 00:13:02 +00001549}
1550
1551func (p *OutputPath) GobDecode(data []byte) error {
Yu Liu3cadf7d2024-10-24 18:47:06 +00001552 return gobtools.CustomGobDecode[outputPathGob](data, p)
Yu Liufa297642024-06-11 00:13:02 +00001553}
1554
Colin Cross702e0f82017-10-18 17:27:54 -07001555func (p OutputPath) withRel(rel string) OutputPath {
Colin Cross0db55682017-12-05 15:36:55 -08001556 p.basePath = p.basePath.withRel(rel)
Colin Crossd63c9a72020-01-29 16:52:50 -08001557 p.fullPath = filepath.Join(p.fullPath, rel)
Colin Cross702e0f82017-10-18 17:27:54 -07001558 return p
1559}
1560
Colin Cross7707b242024-07-26 12:02:36 -07001561func (p OutputPath) WithoutRel() Path {
1562 p.basePath = p.basePath.withoutRel()
Colin Cross3063b782018-08-15 11:19:12 -07001563 return p
1564}
1565
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02001566func (p OutputPath) getSoongOutDir() string {
Colin Cross3b1c6842024-07-26 11:52:57 -07001567 return p.outDir
Paul Duffin9b478b02019-12-10 13:41:51 +00001568}
1569
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001570func (p OutputPath) RelativeToTop() Path {
1571 return p.outputPathRelativeToTop()
1572}
1573
1574func (p OutputPath) outputPathRelativeToTop() OutputPath {
Colin Cross3b1c6842024-07-26 11:52:57 -07001575 p.fullPath = StringPathRelativeToTop(p.outDir, p.fullPath)
1576 if strings.HasSuffix(p.outDir, testOutSoongSubDir) {
1577 p.outDir = TestOutSoongDir
1578 } else {
1579 // Handle the PathForArbitraryOutput case
1580 p.outDir = testOutDir
1581 }
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001582 return p
1583}
1584
Paul Duffin0267d492021-02-02 10:05:52 +00001585func (p OutputPath) objPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleObjPath {
1586 return PathForModuleObj(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
1587}
1588
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001589var _ Path = OutputPath{}
Paul Duffin9b478b02019-12-10 13:41:51 +00001590var _ WritablePath = OutputPath{}
Paul Duffin0267d492021-02-02 10:05:52 +00001591var _ objPathProvider = OutputPath{}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001592
Chris Parsons8f232a22020-06-23 17:37:05 -04001593// toolDepPath is a Path representing a dependency of the build tool.
1594type toolDepPath struct {
1595 basePath
1596}
1597
Colin Cross7707b242024-07-26 12:02:36 -07001598func (t toolDepPath) WithoutRel() Path {
1599 t.basePath = t.basePath.withoutRel()
1600 return t
1601}
1602
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001603func (t toolDepPath) RelativeToTop() Path {
1604 ensureTestOnly()
1605 return t
1606}
1607
Chris Parsons8f232a22020-06-23 17:37:05 -04001608var _ Path = toolDepPath{}
1609
1610// pathForBuildToolDep returns a toolDepPath representing the given path string.
1611// There is no validation for the path, as it is "trusted": It may fail
1612// normal validation checks. For example, it may be an absolute path.
1613// Only use this function to construct paths for dependencies of the build
1614// tool invocation.
1615func pathForBuildToolDep(ctx PathContext, path string) toolDepPath {
Paul Duffin74abc5d2021-03-24 09:24:59 +00001616 return toolDepPath{basePath{path, ""}}
Chris Parsons8f232a22020-06-23 17:37:05 -04001617}
1618
Jeff Gaston734e3802017-04-10 15:47:24 -07001619// PathForOutput joins the provided paths and returns an OutputPath that is
1620// validated to not escape the build dir.
1621// On error, it will return a usable, but invalid OutputPath, and report a ModuleError.
1622func PathForOutput(ctx PathContext, pathComponents ...string) OutputPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001623 path, err := validatePath(pathComponents...)
1624 if err != nil {
1625 reportPathError(ctx, err)
1626 }
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02001627 fullPath := filepath.Join(ctx.Config().soongOutDir, path)
Colin Crossd63c9a72020-01-29 16:52:50 -08001628 path = fullPath[len(fullPath)-len(path):]
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02001629 return OutputPath{basePath{path, ""}, ctx.Config().soongOutDir, fullPath}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001630}
1631
Colin Cross3b1c6842024-07-26 11:52:57 -07001632// PathsForOutput returns Paths rooted from outDir
Colin Cross40e33732019-02-15 11:08:35 -08001633func PathsForOutput(ctx PathContext, paths []string) WritablePaths {
1634 ret := make(WritablePaths, len(paths))
1635 for i, path := range paths {
1636 ret[i] = PathForOutput(ctx, path)
1637 }
1638 return ret
1639}
1640
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001641func (p OutputPath) writablePath() {}
1642
1643func (p OutputPath) String() string {
Colin Crossd63c9a72020-01-29 16:52:50 -08001644 return p.fullPath
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001645}
1646
1647// Join creates a new OutputPath with paths... joined with the current path. The
1648// provided paths... may not use '..' to escape from the current path.
1649func (p OutputPath) Join(ctx PathContext, paths ...string) OutputPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001650 path, err := validatePath(paths...)
1651 if err != nil {
1652 reportPathError(ctx, err)
1653 }
Colin Cross0db55682017-12-05 15:36:55 -08001654 return p.withRel(path)
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001655}
1656
Colin Cross8854a5a2019-02-11 14:14:16 -08001657// ReplaceExtension creates a new OutputPath with the extension replaced with ext.
1658func (p OutputPath) ReplaceExtension(ctx PathContext, ext string) OutputPath {
1659 if strings.Contains(ext, "/") {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001660 ReportPathErrorf(ctx, "extension %q cannot contain /", ext)
Colin Cross8854a5a2019-02-11 14:14:16 -08001661 }
1662 ret := PathForOutput(ctx, pathtools.ReplaceExtension(p.path, ext))
Colin Cross2cdd5df2019-02-25 10:25:24 -08001663 ret.rel = pathtools.ReplaceExtension(p.rel, ext)
Colin Cross8854a5a2019-02-11 14:14:16 -08001664 return ret
1665}
1666
Colin Cross40e33732019-02-15 11:08:35 -08001667// InSameDir creates a new OutputPath from the directory of the current OutputPath joined with the elements in paths.
1668func (p OutputPath) InSameDir(ctx PathContext, paths ...string) OutputPath {
1669 path, err := validatePath(paths...)
1670 if err != nil {
1671 reportPathError(ctx, err)
1672 }
1673
1674 ret := PathForOutput(ctx, filepath.Dir(p.path), path)
Colin Cross2cdd5df2019-02-25 10:25:24 -08001675 ret.rel = filepath.Join(filepath.Dir(p.rel), path)
Colin Cross40e33732019-02-15 11:08:35 -08001676 return ret
1677}
1678
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001679// PathForIntermediates returns an OutputPath representing the top-level
1680// intermediates directory.
1681func PathForIntermediates(ctx PathContext, paths ...string) OutputPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001682 path, err := validatePath(paths...)
1683 if err != nil {
1684 reportPathError(ctx, err)
1685 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001686 return PathForOutput(ctx, ".intermediates", path)
1687}
1688
Colin Cross07e51612019-03-05 12:46:40 -08001689var _ genPathProvider = SourcePath{}
1690var _ objPathProvider = SourcePath{}
1691var _ resPathProvider = SourcePath{}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001692
Colin Cross07e51612019-03-05 12:46:40 -08001693// PathForModuleSrc returns a Path representing the paths... under the
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001694// module's local source directory.
Liz Kammera830f3a2020-11-10 10:50:34 -08001695func PathForModuleSrc(ctx ModuleMissingDepsPathContext, pathComponents ...string) Path {
Paul Duffin407501b2021-07-09 16:56:35 +01001696 // Just join the components textually just to make sure that it does not corrupt a fully qualified
1697 // module reference, e.g. if the pathComponents is "://other:foo" then using filepath.Join() or
1698 // validatePath() will corrupt it, e.g. replace "//" with "/". If the path is not a module
1699 // reference then it will be validated by expandOneSrcPath anyway when it calls expandOneSrcPath.
1700 p := strings.Join(pathComponents, string(filepath.Separator))
Liz Kammer619be462022-01-28 15:13:39 -05001701 paths, err := expandOneSrcPath(sourcePathInput{context: ctx, path: p, includeDirs: true})
Colin Cross8a497952019-03-05 22:25:09 -08001702 if err != nil {
1703 if depErr, ok := err.(missingDependencyError); ok {
1704 if ctx.Config().AllowMissingDependencies() {
1705 ctx.AddMissingDependencies(depErr.missingDeps)
1706 } else {
1707 ctx.ModuleErrorf(`%s, is the property annotated with android:"path"?`, depErr.Error())
1708 }
1709 } else {
1710 reportPathError(ctx, err)
1711 }
1712 return nil
1713 } else if len(paths) == 0 {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001714 ReportPathErrorf(ctx, "%q produced no files, expected exactly one", p)
Colin Cross8a497952019-03-05 22:25:09 -08001715 return nil
1716 } else if len(paths) > 1 {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001717 ReportPathErrorf(ctx, "%q produced %d files, expected exactly one", p, len(paths))
Colin Cross8a497952019-03-05 22:25:09 -08001718 }
1719 return paths[0]
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001720}
1721
Liz Kammera830f3a2020-11-10 10:50:34 -08001722func pathForModuleSrc(ctx EarlyModulePathContext, paths ...string) SourcePath {
Colin Cross07e51612019-03-05 12:46:40 -08001723 p, err := validatePath(paths...)
1724 if err != nil {
1725 reportPathError(ctx, err)
1726 }
1727
1728 path, err := pathForSource(ctx, ctx.ModuleDir(), p)
1729 if err != nil {
1730 reportPathError(ctx, err)
1731 }
1732
1733 path.basePath.rel = p
1734
1735 return path
1736}
1737
Colin Cross2fafa3e2019-03-05 12:39:51 -08001738// PathsWithModuleSrcSubDir takes a list of Paths and returns a new list of Paths where Rel() on each path
1739// will return the path relative to subDir in the module's source directory. If any input paths are not located
1740// inside subDir then a path error will be reported.
Liz Kammera830f3a2020-11-10 10:50:34 -08001741func PathsWithModuleSrcSubDir(ctx EarlyModulePathContext, paths Paths, subDir string) Paths {
Colin Cross2fafa3e2019-03-05 12:39:51 -08001742 paths = append(Paths(nil), paths...)
Colin Cross07e51612019-03-05 12:46:40 -08001743 subDirFullPath := pathForModuleSrc(ctx, subDir)
Colin Cross2fafa3e2019-03-05 12:39:51 -08001744 for i, path := range paths {
1745 rel := Rel(ctx, subDirFullPath.String(), path.String())
1746 paths[i] = subDirFullPath.join(ctx, rel)
1747 }
1748 return paths
1749}
1750
1751// PathWithModuleSrcSubDir takes a Path and returns a Path where Rel() will return the path relative to subDir in the
1752// 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 -08001753func PathWithModuleSrcSubDir(ctx EarlyModulePathContext, path Path, subDir string) Path {
Colin Cross07e51612019-03-05 12:46:40 -08001754 subDirFullPath := pathForModuleSrc(ctx, subDir)
Colin Cross2fafa3e2019-03-05 12:39:51 -08001755 rel := Rel(ctx, subDirFullPath.String(), path.String())
1756 return subDirFullPath.Join(ctx, rel)
1757}
1758
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001759// OptionalPathForModuleSrc returns an OptionalPath. The OptionalPath contains a
1760// valid path if p is non-nil.
Liz Kammera830f3a2020-11-10 10:50:34 -08001761func OptionalPathForModuleSrc(ctx ModuleMissingDepsPathContext, p *string) OptionalPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001762 if p == nil {
1763 return OptionalPath{}
1764 }
1765 return OptionalPathForPath(PathForModuleSrc(ctx, *p))
1766}
1767
Liz Kammera830f3a2020-11-10 10:50:34 -08001768func (p SourcePath) genPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleGenPath {
Colin Cross7fc17db2017-02-01 14:07:55 -08001769 return PathForModuleGen(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001770}
1771
yangbill6d032dd2024-04-18 03:05:49 +00001772func (p SourcePath) genPathWithExtAndTrimExt(ctx ModuleOutPathContext, subdir, ext string, trimExt string) ModuleGenPath {
1773 // If Trim_extension being set, force append Output_extension without replace original extension.
1774 if trimExt != "" {
1775 if ext != "" {
1776 return PathForModuleGen(ctx, subdir, strings.TrimSuffix(p.path, trimExt)+"."+ext)
1777 }
1778 return PathForModuleGen(ctx, subdir, strings.TrimSuffix(p.path, trimExt))
1779 }
1780 return PathForModuleGen(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
1781}
1782
Liz Kammera830f3a2020-11-10 10:50:34 -08001783func (p SourcePath) objPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleObjPath {
Colin Cross7fc17db2017-02-01 14:07:55 -08001784 return PathForModuleObj(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001785}
1786
Liz Kammera830f3a2020-11-10 10:50:34 -08001787func (p SourcePath) resPathWithName(ctx ModuleOutPathContext, name string) ModuleResPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001788 // TODO: Use full directory if the new ctx is not the current ctx?
1789 return PathForModuleRes(ctx, p.path, name)
1790}
1791
1792// ModuleOutPath is a Path representing a module's output directory.
1793type ModuleOutPath struct {
1794 OutputPath
1795}
1796
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001797func (p ModuleOutPath) RelativeToTop() Path {
1798 p.OutputPath = p.outputPathRelativeToTop()
1799 return p
1800}
1801
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001802var _ Path = ModuleOutPath{}
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001803var _ WritablePath = ModuleOutPath{}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001804
Liz Kammera830f3a2020-11-10 10:50:34 -08001805func (p ModuleOutPath) objPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleObjPath {
Pete Bentleyfcf55bf2019-08-16 20:14:32 +01001806 return PathForModuleObj(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
1807}
1808
Liz Kammera830f3a2020-11-10 10:50:34 -08001809// ModuleOutPathContext Subset of ModuleContext functions necessary for output path methods.
1810type ModuleOutPathContext interface {
1811 PathContext
1812
1813 ModuleName() string
1814 ModuleDir() string
1815 ModuleSubDir() string
1816}
1817
1818func pathForModuleOut(ctx ModuleOutPathContext) OutputPath {
Inseob Kimb7e9f5f2024-06-25 17:39:52 +09001819 return PathForOutput(ctx, ".intermediates", ctx.ModuleDir(), ctx.ModuleName(), ctx.ModuleSubDir())
Colin Cross702e0f82017-10-18 17:27:54 -07001820}
1821
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001822// PathForModuleOut returns a Path representing the paths... under the module's
1823// output directory.
Liz Kammera830f3a2020-11-10 10:50:34 -08001824func PathForModuleOut(ctx ModuleOutPathContext, paths ...string) ModuleOutPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001825 p, err := validatePath(paths...)
1826 if err != nil {
1827 reportPathError(ctx, err)
1828 }
Colin Cross702e0f82017-10-18 17:27:54 -07001829 return ModuleOutPath{
Liz Kammera830f3a2020-11-10 10:50:34 -08001830 OutputPath: pathForModuleOut(ctx).withRel(p),
Colin Cross702e0f82017-10-18 17:27:54 -07001831 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001832}
1833
1834// ModuleGenPath is a Path representing the 'gen' directory in a module's output
1835// directory. Mainly used for generated sources.
1836type ModuleGenPath struct {
1837 ModuleOutPath
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001838}
1839
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001840func (p ModuleGenPath) RelativeToTop() Path {
1841 p.OutputPath = p.outputPathRelativeToTop()
1842 return p
1843}
1844
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001845var _ Path = ModuleGenPath{}
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001846var _ WritablePath = ModuleGenPath{}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001847var _ genPathProvider = ModuleGenPath{}
1848var _ objPathProvider = ModuleGenPath{}
1849
1850// PathForModuleGen returns a Path representing the paths... under the module's
1851// `gen' directory.
Liz Kammera830f3a2020-11-10 10:50:34 -08001852func PathForModuleGen(ctx ModuleOutPathContext, paths ...string) ModuleGenPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001853 p, err := validatePath(paths...)
1854 if err != nil {
1855 reportPathError(ctx, err)
1856 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001857 return ModuleGenPath{
Colin Cross702e0f82017-10-18 17:27:54 -07001858 ModuleOutPath: ModuleOutPath{
Liz Kammera830f3a2020-11-10 10:50:34 -08001859 OutputPath: pathForModuleOut(ctx).withRel("gen").withRel(p),
Colin Cross702e0f82017-10-18 17:27:54 -07001860 },
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001861 }
1862}
1863
Liz Kammera830f3a2020-11-10 10:50:34 -08001864func (p ModuleGenPath) genPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleGenPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001865 // TODO: make a different path for local vs remote generated files?
Dan Willemsen21ec4902016-11-02 20:43:13 -07001866 return PathForModuleGen(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001867}
1868
yangbill6d032dd2024-04-18 03:05:49 +00001869func (p ModuleGenPath) genPathWithExtAndTrimExt(ctx ModuleOutPathContext, subdir, ext string, trimExt string) ModuleGenPath {
1870 // If Trim_extension being set, force append Output_extension without replace original extension.
1871 if trimExt != "" {
1872 if ext != "" {
1873 return PathForModuleGen(ctx, subdir, strings.TrimSuffix(p.path, trimExt)+"."+ext)
1874 }
1875 return PathForModuleGen(ctx, subdir, strings.TrimSuffix(p.path, trimExt))
1876 }
1877 return PathForModuleGen(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
1878}
1879
Liz Kammera830f3a2020-11-10 10:50:34 -08001880func (p ModuleGenPath) objPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleObjPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001881 return PathForModuleObj(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
1882}
1883
1884// ModuleObjPath is a Path representing the 'obj' directory in a module's output
1885// directory. Used for compiled objects.
1886type ModuleObjPath struct {
1887 ModuleOutPath
1888}
1889
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001890func (p ModuleObjPath) RelativeToTop() Path {
1891 p.OutputPath = p.outputPathRelativeToTop()
1892 return p
1893}
1894
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001895var _ Path = ModuleObjPath{}
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001896var _ WritablePath = ModuleObjPath{}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001897
1898// PathForModuleObj returns a Path representing the paths... under the module's
1899// 'obj' directory.
Liz Kammera830f3a2020-11-10 10:50:34 -08001900func PathForModuleObj(ctx ModuleOutPathContext, pathComponents ...string) ModuleObjPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001901 p, err := validatePath(pathComponents...)
1902 if err != nil {
1903 reportPathError(ctx, err)
1904 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001905 return ModuleObjPath{PathForModuleOut(ctx, "obj", p)}
1906}
1907
1908// ModuleResPath is a a Path representing the 'res' directory in a module's
1909// output directory.
1910type ModuleResPath struct {
1911 ModuleOutPath
1912}
1913
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001914func (p ModuleResPath) RelativeToTop() Path {
1915 p.OutputPath = p.outputPathRelativeToTop()
1916 return p
1917}
1918
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001919var _ Path = ModuleResPath{}
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001920var _ WritablePath = ModuleResPath{}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001921
1922// PathForModuleRes returns a Path representing the paths... under the module's
1923// 'res' directory.
Liz Kammera830f3a2020-11-10 10:50:34 -08001924func PathForModuleRes(ctx ModuleOutPathContext, pathComponents ...string) ModuleResPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001925 p, err := validatePath(pathComponents...)
1926 if err != nil {
1927 reportPathError(ctx, err)
1928 }
1929
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001930 return ModuleResPath{PathForModuleOut(ctx, "res", p)}
1931}
1932
Colin Cross70dda7e2019-10-01 22:05:35 -07001933// InstallPath is a Path representing a installed file path rooted from the build directory
1934type InstallPath struct {
1935 basePath
Colin Crossff6c33d2019-10-02 16:01:35 -07001936
Lukacs T. Berkib078ade2021-08-31 10:42:08 +02001937 // The soong build directory, i.e. Config.SoongOutDir()
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02001938 soongOutDir string
Paul Duffind65c58b2021-03-24 09:22:07 +00001939
Jiyong Park957bcd92020-10-20 18:23:33 +09001940 // partitionDir is the part of the InstallPath that is automatically determined according to the context.
1941 // For example, it is host/<os>-<arch> for host modules, and target/product/<device>/<partition> for device modules.
1942 partitionDir string
1943
Colin Crossb1692a32021-10-25 15:39:01 -07001944 partition string
1945
Jiyong Park957bcd92020-10-20 18:23:33 +09001946 // makePath indicates whether this path is for Soong (false) or Make (true).
1947 makePath bool
Colin Crossc0e42d52024-02-01 16:42:36 -08001948
1949 fullPath string
Colin Cross70dda7e2019-10-01 22:05:35 -07001950}
1951
Yu Liu467d7c52024-09-18 21:54:44 +00001952type installPathGob struct {
Yu Liu5246a7e2024-10-09 20:04:52 +00001953 BasePath basePath
Yu Liu467d7c52024-09-18 21:54:44 +00001954 SoongOutDir string
1955 PartitionDir string
1956 Partition string
1957 MakePath bool
1958 FullPath string
1959}
Yu Liu26a716d2024-08-30 23:40:32 +00001960
Yu Liu467d7c52024-09-18 21:54:44 +00001961func (p *InstallPath) ToGob() *installPathGob {
1962 return &installPathGob{
Yu Liu5246a7e2024-10-09 20:04:52 +00001963 BasePath: p.basePath,
Yu Liu467d7c52024-09-18 21:54:44 +00001964 SoongOutDir: p.soongOutDir,
1965 PartitionDir: p.partitionDir,
1966 Partition: p.partition,
1967 MakePath: p.makePath,
1968 FullPath: p.fullPath,
1969 }
1970}
1971
1972func (p *InstallPath) FromGob(data *installPathGob) {
Yu Liu5246a7e2024-10-09 20:04:52 +00001973 p.basePath = data.BasePath
Yu Liu467d7c52024-09-18 21:54:44 +00001974 p.soongOutDir = data.SoongOutDir
1975 p.partitionDir = data.PartitionDir
1976 p.partition = data.Partition
1977 p.makePath = data.MakePath
1978 p.fullPath = data.FullPath
1979}
1980
1981func (p InstallPath) GobEncode() ([]byte, error) {
Yu Liu3cadf7d2024-10-24 18:47:06 +00001982 return gobtools.CustomGobEncode[installPathGob](&p)
Yu Liu26a716d2024-08-30 23:40:32 +00001983}
1984
1985func (p *InstallPath) GobDecode(data []byte) error {
Yu Liu3cadf7d2024-10-24 18:47:06 +00001986 return gobtools.CustomGobDecode[installPathGob](data, p)
Yu Liu26a716d2024-08-30 23:40:32 +00001987}
1988
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001989// Will panic if called from outside a test environment.
1990func ensureTestOnly() {
Martin Stjernholm32312eb2021-03-27 18:54:49 +00001991 if PrefixInList(os.Args, "-test.") {
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001992 return
1993 }
Martin Stjernholm32312eb2021-03-27 18:54:49 +00001994 panic(fmt.Errorf("Not in test. Command line:\n %s", strings.Join(os.Args, "\n ")))
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001995}
1996
1997func (p InstallPath) RelativeToTop() Path {
1998 ensureTestOnly()
Colin Crossc0e42d52024-02-01 16:42:36 -08001999 if p.makePath {
Colin Cross3b1c6842024-07-26 11:52:57 -07002000 p.soongOutDir = testOutDir
Colin Crossc0e42d52024-02-01 16:42:36 -08002001 } else {
Colin Cross3b1c6842024-07-26 11:52:57 -07002002 p.soongOutDir = TestOutSoongDir
Colin Crossc0e42d52024-02-01 16:42:36 -08002003 }
2004 p.fullPath = filepath.Join(p.soongOutDir, p.path)
Paul Duffin85d8f0d2021-03-24 10:18:18 +00002005 return p
2006}
2007
Colin Cross7707b242024-07-26 12:02:36 -07002008func (p InstallPath) WithoutRel() Path {
2009 p.basePath = p.basePath.withoutRel()
2010 return p
2011}
2012
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02002013func (p InstallPath) getSoongOutDir() string {
2014 return p.soongOutDir
Paul Duffin9b478b02019-12-10 13:41:51 +00002015}
2016
Hans MÃ¥nssond3f2bd72020-11-27 12:37:28 +01002017func (p InstallPath) ReplaceExtension(ctx PathContext, ext string) OutputPath {
2018 panic("Not implemented")
2019}
2020
Paul Duffin9b478b02019-12-10 13:41:51 +00002021var _ Path = InstallPath{}
2022var _ WritablePath = InstallPath{}
2023
Colin Cross70dda7e2019-10-01 22:05:35 -07002024func (p InstallPath) writablePath() {}
2025
2026func (p InstallPath) String() string {
Colin Crossc0e42d52024-02-01 16:42:36 -08002027 return p.fullPath
Jiyong Park957bcd92020-10-20 18:23:33 +09002028}
2029
2030// PartitionDir returns the path to the partition where the install path is rooted at. It is
2031// out/soong/target/product/<device>/<partition> for device modules, and out/soong/host/<os>-<arch> for host modules.
2032// The ./soong is dropped if the install path is for Make.
2033func (p InstallPath) PartitionDir() string {
2034 if p.makePath {
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02002035 return filepath.Join(p.soongOutDir, "../", p.partitionDir)
Jiyong Park957bcd92020-10-20 18:23:33 +09002036 } else {
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02002037 return filepath.Join(p.soongOutDir, p.partitionDir)
Jiyong Park957bcd92020-10-20 18:23:33 +09002038 }
Colin Cross70dda7e2019-10-01 22:05:35 -07002039}
2040
Jihoon Kangf78a8902022-09-01 22:47:07 +00002041func (p InstallPath) Partition() string {
2042 return p.partition
2043}
2044
Colin Cross70dda7e2019-10-01 22:05:35 -07002045// Join creates a new InstallPath with paths... joined with the current path. The
2046// provided paths... may not use '..' to escape from the current path.
2047func (p InstallPath) Join(ctx PathContext, paths ...string) InstallPath {
2048 path, err := validatePath(paths...)
2049 if err != nil {
2050 reportPathError(ctx, err)
2051 }
2052 return p.withRel(path)
2053}
2054
2055func (p InstallPath) withRel(rel string) InstallPath {
2056 p.basePath = p.basePath.withRel(rel)
Colin Crossc0e42d52024-02-01 16:42:36 -08002057 p.fullPath = filepath.Join(p.fullPath, rel)
Colin Cross70dda7e2019-10-01 22:05:35 -07002058 return p
2059}
2060
Colin Crossc68db4b2021-11-11 18:59:15 -08002061// Deprecated: ToMakePath is a noop, PathForModuleInstall always returns Make paths when building
2062// embedded in Make.
Colin Crossff6c33d2019-10-02 16:01:35 -07002063func (p InstallPath) ToMakePath() InstallPath {
Jiyong Park957bcd92020-10-20 18:23:33 +09002064 p.makePath = true
Colin Crossff6c33d2019-10-02 16:01:35 -07002065 return p
Colin Cross70dda7e2019-10-01 22:05:35 -07002066}
2067
Dan Willemsen34cc69e2015-09-23 15:26:20 -07002068// PathForModuleInstall returns a Path representing the install path for the
2069// module appended with paths...
Colin Cross70dda7e2019-10-01 22:05:35 -07002070func PathForModuleInstall(ctx ModuleInstallPathContext, pathComponents ...string) InstallPath {
Spandan Das5d1b9292021-06-03 19:36:41 +00002071 os, arch := osAndArch(ctx)
Cole Faust11edf552023-10-13 11:32:14 -07002072 partition := modulePartition(ctx, os.Class == Device)
Cole Faust3b703f32023-10-16 13:30:51 -07002073 return pathForInstall(ctx, os, arch, partition, pathComponents...)
Spandan Das5d1b9292021-06-03 19:36:41 +00002074}
2075
Colin Cross1d0eb7a2021-11-03 14:08:20 -07002076// PathForHostDexInstall returns an InstallPath representing the install path for the
2077// module appended with paths...
2078func PathForHostDexInstall(ctx ModuleInstallPathContext, pathComponents ...string) InstallPath {
Cole Faust3b703f32023-10-16 13:30:51 -07002079 return pathForInstall(ctx, ctx.Config().BuildOS, ctx.Config().BuildArch, "", pathComponents...)
Colin Cross1d0eb7a2021-11-03 14:08:20 -07002080}
2081
Spandan Das5d1b9292021-06-03 19:36:41 +00002082// PathForModuleInPartitionInstall is similar to PathForModuleInstall but partition is provided by the caller
2083func PathForModuleInPartitionInstall(ctx ModuleInstallPathContext, partition string, pathComponents ...string) InstallPath {
2084 os, arch := osAndArch(ctx)
Cole Faust3b703f32023-10-16 13:30:51 -07002085 return pathForInstall(ctx, os, arch, partition, pathComponents...)
Spandan Das5d1b9292021-06-03 19:36:41 +00002086}
2087
2088func osAndArch(ctx ModuleInstallPathContext) (OsType, ArchType) {
Colin Cross6e359402020-02-10 15:29:54 -08002089 os := ctx.Os()
Jiyong Park87788b52020-09-01 12:37:45 +09002090 arch := ctx.Arch().ArchType
2091 forceOS, forceArch := ctx.InstallForceOS()
2092 if forceOS != nil {
Colin Cross6e359402020-02-10 15:29:54 -08002093 os = *forceOS
2094 }
Jiyong Park87788b52020-09-01 12:37:45 +09002095 if forceArch != nil {
2096 arch = *forceArch
2097 }
Spandan Das5d1b9292021-06-03 19:36:41 +00002098 return os, arch
2099}
Colin Cross609c49a2020-02-13 13:20:11 -08002100
Colin Crossc0e42d52024-02-01 16:42:36 -08002101func pathForPartitionInstallDir(ctx PathContext, partition, partitionPath string, makePath bool) InstallPath {
2102 fullPath := ctx.Config().SoongOutDir()
2103 if makePath {
2104 // Make path starts with out/ instead of out/soong.
2105 fullPath = filepath.Join(fullPath, "../", partitionPath)
2106 } else {
2107 fullPath = filepath.Join(fullPath, partitionPath)
2108 }
2109
2110 return InstallPath{
2111 basePath: basePath{partitionPath, ""},
2112 soongOutDir: ctx.Config().soongOutDir,
2113 partitionDir: partitionPath,
2114 partition: partition,
2115 makePath: makePath,
2116 fullPath: fullPath,
2117 }
2118}
2119
Cole Faust3b703f32023-10-16 13:30:51 -07002120func pathForInstall(ctx PathContext, os OsType, arch ArchType, partition string,
Colin Cross609c49a2020-02-13 13:20:11 -08002121 pathComponents ...string) InstallPath {
2122
Jiyong Park97859152023-02-14 17:05:48 +09002123 var partitionPaths []string
Colin Cross609c49a2020-02-13 13:20:11 -08002124
Colin Cross6e359402020-02-10 15:29:54 -08002125 if os.Class == Device {
Jiyong Park97859152023-02-14 17:05:48 +09002126 partitionPaths = []string{"target", "product", ctx.Config().DeviceName(), partition}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07002127 } else {
Jiyong Park87788b52020-09-01 12:37:45 +09002128 osName := os.String()
Colin Crossa9b2aac2022-06-15 17:25:51 -07002129 if os == Linux {
Jiyong Park87788b52020-09-01 12:37:45 +09002130 // instead of linux_glibc
2131 osName = "linux"
Dan Willemsen866b5632017-09-22 12:28:24 -07002132 }
Colin Crossa9b2aac2022-06-15 17:25:51 -07002133 if os == LinuxMusl && ctx.Config().UseHostMusl() {
2134 // When using musl instead of glibc, use "linux" instead of "linux_musl". When cross
2135 // compiling we will still use "linux_musl".
2136 osName = "linux"
2137 }
2138
Jiyong Park87788b52020-09-01 12:37:45 +09002139 // SOONG_HOST_OUT is set to out/host/$(HOST_OS)-$(HOST_PREBUILT_ARCH)
2140 // and HOST_PREBUILT_ARCH is forcibly set to x86 even on x86_64 hosts. We don't seem
2141 // to have a plan to fix it (see the comment in build/make/core/envsetup.mk).
2142 // Let's keep using x86 for the existing cases until we have a need to support
2143 // other architectures.
2144 archName := arch.String()
2145 if os.Class == Host && (arch == X86_64 || arch == Common) {
2146 archName = "x86"
2147 }
Jiyong Park97859152023-02-14 17:05:48 +09002148 partitionPaths = []string{"host", osName + "-" + archName, partition}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07002149 }
Colin Cross70dda7e2019-10-01 22:05:35 -07002150
Jiyong Park97859152023-02-14 17:05:48 +09002151 partitionPath, err := validatePath(partitionPaths...)
Colin Cross70dda7e2019-10-01 22:05:35 -07002152 if err != nil {
2153 reportPathError(ctx, err)
2154 }
Colin Crossff6c33d2019-10-02 16:01:35 -07002155
Colin Crossc0e42d52024-02-01 16:42:36 -08002156 base := pathForPartitionInstallDir(ctx, partition, partitionPath, ctx.Config().KatiEnabled())
Jiyong Park957bcd92020-10-20 18:23:33 +09002157 return base.Join(ctx, pathComponents...)
Dan Willemsen34cc69e2015-09-23 15:26:20 -07002158}
2159
Spandan Dasf280b232024-04-04 21:25:51 +00002160func PathForNdkInstall(ctx PathContext, paths ...string) OutputPath {
2161 return PathForOutput(ctx, append([]string{"ndk"}, paths...)...)
Nicolas Geoffray1228e9c2020-02-27 13:45:35 +00002162}
2163
2164func PathForMainlineSdksInstall(ctx PathContext, paths ...string) InstallPath {
Spandan Dasf280b232024-04-04 21:25:51 +00002165 base := pathForPartitionInstallDir(ctx, "", "mainline-sdks", false)
2166 return base.Join(ctx, paths...)
Nicolas Geoffray1228e9c2020-02-27 13:45:35 +00002167}
2168
Weijia Heaa37c162024-11-06 19:46:03 +00002169func PathForSuiteInstall(ctx PathContext, suite string, pathComponents ...string) InstallPath {
2170 return pathForPartitionInstallDir(ctx, "test_suites", "test_suites", false).Join(ctx, suite).Join(ctx, pathComponents...)
2171}
2172
Colin Cross70dda7e2019-10-01 22:05:35 -07002173func InstallPathToOnDevicePath(ctx PathContext, path InstallPath) string {
Colin Crossb1692a32021-10-25 15:39:01 -07002174 rel := Rel(ctx, strings.TrimSuffix(path.PartitionDir(), path.partition), path.String())
Colin Cross43f08db2018-11-12 10:13:39 -08002175 return "/" + rel
2176}
2177
Cole Faust11edf552023-10-13 11:32:14 -07002178func modulePartition(ctx ModuleInstallPathContext, device bool) string {
Colin Cross43f08db2018-11-12 10:13:39 -08002179 var partition string
Colin Cross6e359402020-02-10 15:29:54 -08002180 if ctx.InstallInTestcases() {
2181 // "testcases" install directory can be used for host or device modules.
Jaewoong Jung0949f312019-09-11 10:25:18 -07002182 partition = "testcases"
Cole Faust11edf552023-10-13 11:32:14 -07002183 } else if device {
Colin Cross6e359402020-02-10 15:29:54 -08002184 if ctx.InstallInData() {
2185 partition = "data"
2186 } else if ctx.InstallInRamdisk() {
2187 if ctx.DeviceConfig().BoardUsesRecoveryAsBoot() {
2188 partition = "recovery/root/first_stage_ramdisk"
2189 } else {
2190 partition = "ramdisk"
2191 }
2192 if !ctx.InstallInRoot() {
2193 partition += "/system"
2194 }
Yifan Hong60e0cfb2020-10-21 15:17:56 -07002195 } else if ctx.InstallInVendorRamdisk() {
Yifan Hong39143a92020-10-26 12:43:12 -07002196 // The module is only available after switching root into
2197 // /first_stage_ramdisk. To expose the module before switching root
2198 // on a device without a dedicated recovery partition, install the
2199 // recovery variant.
Yifan Hongdd8dacc2020-10-21 15:40:17 -07002200 if ctx.DeviceConfig().BoardMoveRecoveryResourcesToVendorBoot() {
Petri Gyntherac229562021-03-02 23:44:02 -08002201 partition = "vendor_ramdisk/first_stage_ramdisk"
Yifan Hongdd8dacc2020-10-21 15:40:17 -07002202 } else {
Petri Gyntherac229562021-03-02 23:44:02 -08002203 partition = "vendor_ramdisk"
Yifan Hongdd8dacc2020-10-21 15:40:17 -07002204 }
2205 if !ctx.InstallInRoot() {
2206 partition += "/system"
2207 }
Inseob Kim08758f02021-04-08 21:13:22 +09002208 } else if ctx.InstallInDebugRamdisk() {
2209 partition = "debug_ramdisk"
Colin Cross6e359402020-02-10 15:29:54 -08002210 } else if ctx.InstallInRecovery() {
2211 if ctx.InstallInRoot() {
2212 partition = "recovery/root"
2213 } else {
2214 // the layout of recovery partion is the same as that of system partition
2215 partition = "recovery/root/system"
2216 }
Colin Crossea30d852023-11-29 16:00:16 -08002217 } else if ctx.SocSpecific() || ctx.InstallInVendor() {
Colin Cross6e359402020-02-10 15:29:54 -08002218 partition = ctx.DeviceConfig().VendorPath()
Colin Crossea30d852023-11-29 16:00:16 -08002219 } else if ctx.DeviceSpecific() || ctx.InstallInOdm() {
Colin Cross6e359402020-02-10 15:29:54 -08002220 partition = ctx.DeviceConfig().OdmPath()
Colin Crossea30d852023-11-29 16:00:16 -08002221 } else if ctx.ProductSpecific() || ctx.InstallInProduct() {
Colin Cross6e359402020-02-10 15:29:54 -08002222 partition = ctx.DeviceConfig().ProductPath()
2223 } else if ctx.SystemExtSpecific() {
2224 partition = ctx.DeviceConfig().SystemExtPath()
2225 } else if ctx.InstallInRoot() {
2226 partition = "root"
Spandan Das27ff7672024-11-06 19:23:57 +00002227 } else if ctx.InstallInSystemDlkm() {
2228 partition = ctx.DeviceConfig().SystemDlkmPath()
2229 } else if ctx.InstallInVendorDlkm() {
2230 partition = ctx.DeviceConfig().VendorDlkmPath()
2231 } else if ctx.InstallInOdmDlkm() {
2232 partition = ctx.DeviceConfig().OdmDlkmPath()
Yifan Hong82db7352020-01-21 16:12:26 -08002233 } else {
Colin Cross6e359402020-02-10 15:29:54 -08002234 partition = "system"
Yifan Hong82db7352020-01-21 16:12:26 -08002235 }
Colin Cross6e359402020-02-10 15:29:54 -08002236 if ctx.InstallInSanitizerDir() {
2237 partition = "data/asan/" + partition
Yifan Hong82db7352020-01-21 16:12:26 -08002238 }
Colin Cross43f08db2018-11-12 10:13:39 -08002239 }
2240 return partition
2241}
2242
Colin Cross609c49a2020-02-13 13:20:11 -08002243type InstallPaths []InstallPath
2244
2245// Paths returns the InstallPaths as a Paths
2246func (p InstallPaths) Paths() Paths {
2247 if p == nil {
2248 return nil
2249 }
2250 ret := make(Paths, len(p))
2251 for i, path := range p {
2252 ret[i] = path
2253 }
2254 return ret
2255}
2256
2257// Strings returns the string forms of the install paths.
2258func (p InstallPaths) Strings() []string {
2259 if p == nil {
2260 return nil
2261 }
2262 ret := make([]string, len(p))
2263 for i, path := range p {
2264 ret[i] = path.String()
2265 }
2266 return ret
2267}
2268
Jingwen Chen24d0c562023-02-07 09:29:36 +00002269// validatePathInternal ensures that a path does not leave its component, and
2270// optionally doesn't contain Ninja variables.
2271func validatePathInternal(allowNinjaVariables bool, pathComponents ...string) (string, error) {
Colin Crossbf9ed3f2023-10-24 14:17:03 -07002272 initialEmpty := 0
2273 finalEmpty := 0
2274 for i, path := range pathComponents {
Jingwen Chen24d0c562023-02-07 09:29:36 +00002275 if !allowNinjaVariables && strings.Contains(path, "$") {
2276 return "", fmt.Errorf("Path contains invalid character($): %s", path)
2277 }
2278
Dan Willemsen80a7c2a2015-12-21 14:57:11 -08002279 path := filepath.Clean(path)
maxwen479f5b02024-03-20 14:41:25 +01002280 if path == ".." || strings.HasPrefix(path, "../") || i != initialEmpty && strings.HasPrefix(path, "/") {
Colin Cross1ccfcc32018-02-22 13:54:26 -08002281 return "", fmt.Errorf("Path is outside directory: %s", path)
Dan Willemsen80a7c2a2015-12-21 14:57:11 -08002282 }
Colin Crossbf9ed3f2023-10-24 14:17:03 -07002283
2284 if i == initialEmpty && pathComponents[i] == "" {
2285 initialEmpty++
2286 }
2287 if i == finalEmpty && pathComponents[len(pathComponents)-1-i] == "" {
2288 finalEmpty++
2289 }
Dan Willemsen80a7c2a2015-12-21 14:57:11 -08002290 }
Colin Crossbf9ed3f2023-10-24 14:17:03 -07002291 // Optimization: filepath.Join("foo", "") returns a newly allocated copy
2292 // of "foo", while filepath.Join("foo") does not. Strip out any empty
2293 // path components.
2294 if initialEmpty == len(pathComponents) {
2295 return "", nil
2296 }
2297 nonEmptyPathComponents := pathComponents[initialEmpty : len(pathComponents)-finalEmpty]
Dan Willemsen34cc69e2015-09-23 15:26:20 -07002298 // TODO: filepath.Join isn't necessarily correct with embedded ninja
2299 // variables. '..' may remove the entire ninja variable, even if it
2300 // will be expanded to multiple nested directories.
Colin Crossbf9ed3f2023-10-24 14:17:03 -07002301 return filepath.Join(nonEmptyPathComponents...), nil
Dan Willemsen34cc69e2015-09-23 15:26:20 -07002302}
2303
Jingwen Chen24d0c562023-02-07 09:29:36 +00002304// validateSafePath validates a path that we trust (may contain ninja
2305// variables). Ensures that each path component does not attempt to leave its
2306// component. Returns a joined version of each path component.
2307func validateSafePath(pathComponents ...string) (string, error) {
2308 return validatePathInternal(true, pathComponents...)
2309}
2310
Dan Willemsen80a7c2a2015-12-21 14:57:11 -08002311// validatePath validates that a path does not include ninja variables, and that
2312// each path component does not attempt to leave its component. Returns a joined
2313// version of each path component.
Colin Cross1ccfcc32018-02-22 13:54:26 -08002314func validatePath(pathComponents ...string) (string, error) {
Jingwen Chen24d0c562023-02-07 09:29:36 +00002315 return validatePathInternal(false, pathComponents...)
Colin Cross6e18ca42015-07-14 18:55:36 -07002316}
Colin Cross5b529592017-05-09 13:34:34 -07002317
Colin Cross0875c522017-11-28 17:34:01 -08002318func PathForPhony(ctx PathContext, phony string) WritablePath {
2319 if strings.ContainsAny(phony, "$/") {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01002320 ReportPathErrorf(ctx, "Phony target contains invalid character ($ or /): %s", phony)
Colin Cross0875c522017-11-28 17:34:01 -08002321 }
Paul Duffin74abc5d2021-03-24 09:24:59 +00002322 return PhonyPath{basePath{phony, ""}}
Colin Cross0875c522017-11-28 17:34:01 -08002323}
2324
Colin Cross74e3fe42017-12-11 15:51:44 -08002325type PhonyPath struct {
2326 basePath
2327}
2328
2329func (p PhonyPath) writablePath() {}
2330
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02002331func (p PhonyPath) getSoongOutDir() string {
Paul Duffind65c58b2021-03-24 09:22:07 +00002332 // A phone path cannot contain any / so cannot be relative to the build directory.
2333 return ""
Paul Duffin9b478b02019-12-10 13:41:51 +00002334}
2335
Paul Duffin85d8f0d2021-03-24 10:18:18 +00002336func (p PhonyPath) RelativeToTop() Path {
2337 ensureTestOnly()
2338 // A phony path cannot contain any / so does not have a build directory so switching to a new
2339 // build directory has no effect so just return this path.
2340 return p
2341}
2342
Colin Cross7707b242024-07-26 12:02:36 -07002343func (p PhonyPath) WithoutRel() Path {
2344 p.basePath = p.basePath.withoutRel()
2345 return p
2346}
2347
Hans MÃ¥nssond3f2bd72020-11-27 12:37:28 +01002348func (p PhonyPath) ReplaceExtension(ctx PathContext, ext string) OutputPath {
2349 panic("Not implemented")
2350}
2351
Colin Cross74e3fe42017-12-11 15:51:44 -08002352var _ Path = PhonyPath{}
2353var _ WritablePath = PhonyPath{}
2354
Colin Cross5b529592017-05-09 13:34:34 -07002355type testPath struct {
2356 basePath
2357}
2358
Paul Duffin85d8f0d2021-03-24 10:18:18 +00002359func (p testPath) RelativeToTop() Path {
2360 ensureTestOnly()
2361 return p
2362}
2363
Colin Cross7707b242024-07-26 12:02:36 -07002364func (p testPath) WithoutRel() Path {
2365 p.basePath = p.basePath.withoutRel()
2366 return p
2367}
2368
Colin Cross5b529592017-05-09 13:34:34 -07002369func (p testPath) String() string {
2370 return p.path
2371}
2372
Paul Duffin85d8f0d2021-03-24 10:18:18 +00002373var _ Path = testPath{}
2374
Colin Cross40e33732019-02-15 11:08:35 -08002375// PathForTesting returns a Path constructed from joining the elements of paths with '/'. It should only be used from
2376// within tests.
Colin Cross5b529592017-05-09 13:34:34 -07002377func PathForTesting(paths ...string) Path {
Colin Cross1ccfcc32018-02-22 13:54:26 -08002378 p, err := validateSafePath(paths...)
2379 if err != nil {
2380 panic(err)
2381 }
Colin Cross5b529592017-05-09 13:34:34 -07002382 return testPath{basePath{path: p, rel: p}}
2383}
2384
Sam Delmerico2351eac2022-05-24 17:10:02 +00002385func PathForTestingWithRel(path, rel string) Path {
2386 p, err := validateSafePath(path, rel)
2387 if err != nil {
2388 panic(err)
2389 }
2390 r, err := validatePath(rel)
2391 if err != nil {
2392 panic(err)
2393 }
2394 return testPath{basePath{path: p, rel: r}}
2395}
2396
Colin Cross40e33732019-02-15 11:08:35 -08002397// PathsForTesting returns a Path constructed from each element in strs. It should only be used from within tests.
2398func PathsForTesting(strs ...string) Paths {
Colin Cross5b529592017-05-09 13:34:34 -07002399 p := make(Paths, len(strs))
2400 for i, s := range strs {
2401 p[i] = PathForTesting(s)
2402 }
2403
2404 return p
2405}
Colin Cross43f08db2018-11-12 10:13:39 -08002406
Colin Cross40e33732019-02-15 11:08:35 -08002407type testPathContext struct {
2408 config Config
Colin Cross40e33732019-02-15 11:08:35 -08002409}
2410
Colin Cross40e33732019-02-15 11:08:35 -08002411func (x *testPathContext) Config() Config { return x.config }
2412func (x *testPathContext) AddNinjaFileDeps(...string) {}
2413
2414// PathContextForTesting returns a PathContext that can be used in tests, for example to create an OutputPath with
2415// PathForOutput.
Colin Cross98be1bb2019-12-13 20:41:13 -08002416func PathContextForTesting(config Config) PathContext {
Colin Cross40e33732019-02-15 11:08:35 -08002417 return &testPathContext{
2418 config: config,
Colin Cross40e33732019-02-15 11:08:35 -08002419 }
2420}
2421
Ulya Trafimovichccc8c852020-10-14 11:29:07 +01002422type testModuleInstallPathContext struct {
2423 baseModuleContext
2424
2425 inData bool
2426 inTestcases bool
2427 inSanitizerDir bool
2428 inRamdisk bool
2429 inVendorRamdisk bool
Inseob Kim08758f02021-04-08 21:13:22 +09002430 inDebugRamdisk bool
Ulya Trafimovichccc8c852020-10-14 11:29:07 +01002431 inRecovery bool
2432 inRoot bool
Colin Crossea30d852023-11-29 16:00:16 -08002433 inOdm bool
2434 inProduct bool
2435 inVendor bool
Spandan Das27ff7672024-11-06 19:23:57 +00002436 inSystemDlkm bool
2437 inVendorDlkm bool
2438 inOdmDlkm bool
Ulya Trafimovichccc8c852020-10-14 11:29:07 +01002439 forceOS *OsType
2440 forceArch *ArchType
2441}
2442
2443func (m testModuleInstallPathContext) Config() Config {
2444 return m.baseModuleContext.config
2445}
2446
2447func (testModuleInstallPathContext) AddNinjaFileDeps(deps ...string) {}
2448
2449func (m testModuleInstallPathContext) InstallInData() bool {
2450 return m.inData
2451}
2452
2453func (m testModuleInstallPathContext) InstallInTestcases() bool {
2454 return m.inTestcases
2455}
2456
2457func (m testModuleInstallPathContext) InstallInSanitizerDir() bool {
2458 return m.inSanitizerDir
2459}
2460
2461func (m testModuleInstallPathContext) InstallInRamdisk() bool {
2462 return m.inRamdisk
2463}
2464
2465func (m testModuleInstallPathContext) InstallInVendorRamdisk() bool {
2466 return m.inVendorRamdisk
2467}
2468
Inseob Kim08758f02021-04-08 21:13:22 +09002469func (m testModuleInstallPathContext) InstallInDebugRamdisk() bool {
2470 return m.inDebugRamdisk
2471}
2472
Ulya Trafimovichccc8c852020-10-14 11:29:07 +01002473func (m testModuleInstallPathContext) InstallInRecovery() bool {
2474 return m.inRecovery
2475}
2476
2477func (m testModuleInstallPathContext) InstallInRoot() bool {
2478 return m.inRoot
2479}
2480
Colin Crossea30d852023-11-29 16:00:16 -08002481func (m testModuleInstallPathContext) InstallInOdm() bool {
2482 return m.inOdm
2483}
2484
2485func (m testModuleInstallPathContext) InstallInProduct() bool {
2486 return m.inProduct
2487}
2488
2489func (m testModuleInstallPathContext) InstallInVendor() bool {
2490 return m.inVendor
2491}
2492
Spandan Das27ff7672024-11-06 19:23:57 +00002493func (m testModuleInstallPathContext) InstallInSystemDlkm() bool {
2494 return m.inSystemDlkm
2495}
2496
2497func (m testModuleInstallPathContext) InstallInVendorDlkm() bool {
2498 return m.inVendorDlkm
2499}
2500
2501func (m testModuleInstallPathContext) InstallInOdmDlkm() bool {
2502 return m.inOdmDlkm
2503}
2504
Ulya Trafimovichccc8c852020-10-14 11:29:07 +01002505func (m testModuleInstallPathContext) InstallForceOS() (*OsType, *ArchType) {
2506 return m.forceOS, m.forceArch
2507}
2508
2509// Construct a minimal ModuleInstallPathContext for testing. Note that baseModuleContext is
2510// default-initialized, which leaves blueprint.baseModuleContext set to nil, so methods that are
2511// delegated to it will panic.
2512func ModuleInstallPathContextForTesting(config Config) ModuleInstallPathContext {
2513 ctx := &testModuleInstallPathContext{}
2514 ctx.config = config
2515 ctx.os = Android
2516 return ctx
2517}
2518
Colin Cross43f08db2018-11-12 10:13:39 -08002519// Rel performs the same function as filepath.Rel, but reports errors to a PathContext, and reports an error if
2520// targetPath is not inside basePath.
2521func Rel(ctx PathContext, basePath string, targetPath string) string {
2522 rel, isRel := MaybeRel(ctx, basePath, targetPath)
2523 if !isRel {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01002524 ReportPathErrorf(ctx, "path %q is not under path %q", targetPath, basePath)
Colin Cross43f08db2018-11-12 10:13:39 -08002525 return ""
2526 }
2527 return rel
2528}
2529
2530// MaybeRel performs the same function as filepath.Rel, but reports errors to a PathContext, and returns false if
2531// targetPath is not inside basePath.
2532func MaybeRel(ctx PathContext, basePath string, targetPath string) (string, bool) {
Dan Willemsen633c5022019-04-12 11:11:38 -07002533 rel, isRel, err := maybeRelErr(basePath, targetPath)
2534 if err != nil {
2535 reportPathError(ctx, err)
2536 }
2537 return rel, isRel
2538}
2539
2540func maybeRelErr(basePath string, targetPath string) (string, bool, error) {
Colin Cross43f08db2018-11-12 10:13:39 -08002541 // filepath.Rel returns an error if one path is absolute and the other is not, handle that case first.
2542 if filepath.IsAbs(basePath) != filepath.IsAbs(targetPath) {
Dan Willemsen633c5022019-04-12 11:11:38 -07002543 return "", false, nil
Colin Cross43f08db2018-11-12 10:13:39 -08002544 }
2545 rel, err := filepath.Rel(basePath, targetPath)
2546 if err != nil {
Dan Willemsen633c5022019-04-12 11:11:38 -07002547 return "", false, err
Colin Cross43f08db2018-11-12 10:13:39 -08002548 } else if rel == ".." || strings.HasPrefix(rel, "../") || strings.HasPrefix(rel, "/") {
Dan Willemsen633c5022019-04-12 11:11:38 -07002549 return "", false, nil
Colin Cross43f08db2018-11-12 10:13:39 -08002550 }
Dan Willemsen633c5022019-04-12 11:11:38 -07002551 return rel, true, nil
Colin Cross43f08db2018-11-12 10:13:39 -08002552}
Colin Cross988414c2020-01-11 01:11:46 +00002553
2554// Writes a file to the output directory. Attempting to write directly to the output directory
2555// will fail due to the sandbox of the soong_build process.
Chris Parsons1a12d032023-02-06 22:37:41 -05002556// Only writes the file if the file doesn't exist or if it has different contents, to prevent
2557// updating the timestamp if no changes would be made. (This is better for incremental
2558// performance.)
Colin Cross988414c2020-01-11 01:11:46 +00002559func WriteFileToOutputDir(path WritablePath, data []byte, perm os.FileMode) error {
Colin Crossd6421132021-11-09 12:32:34 -08002560 absPath := absolutePath(path.String())
2561 err := os.MkdirAll(filepath.Dir(absPath), 0777)
2562 if err != nil {
2563 return err
2564 }
Chris Parsons1a12d032023-02-06 22:37:41 -05002565 return pathtools.WriteFileIfChanged(absPath, data, perm)
Colin Cross988414c2020-01-11 01:11:46 +00002566}
2567
Liz Kammer2dd9ca42020-11-25 16:06:39 -08002568func RemoveAllOutputDir(path WritablePath) error {
2569 return os.RemoveAll(absolutePath(path.String()))
2570}
2571
2572func CreateOutputDirIfNonexistent(path WritablePath, perm os.FileMode) error {
2573 dir := absolutePath(path.String())
Liz Kammer09f947d2021-05-12 14:51:49 -04002574 return createDirIfNonexistent(dir, perm)
2575}
2576
2577func createDirIfNonexistent(dir string, perm os.FileMode) error {
Liz Kammer2dd9ca42020-11-25 16:06:39 -08002578 if _, err := os.Stat(dir); os.IsNotExist(err) {
2579 return os.MkdirAll(dir, os.ModePerm)
2580 } else {
2581 return err
2582 }
2583}
2584
Jingwen Chen78257e52021-05-21 02:34:24 +00002585// absolutePath is deliberately private so that Soong's Go plugins can't use it to find and
2586// read arbitrary files without going through the methods in the current package that track
2587// dependencies.
Colin Cross988414c2020-01-11 01:11:46 +00002588func absolutePath(path string) string {
2589 if filepath.IsAbs(path) {
2590 return path
2591 }
2592 return filepath.Join(absSrcDir, path)
2593}
Chris Parsons216e10a2020-07-09 17:12:52 -04002594
2595// A DataPath represents the path of a file to be used as data, for example
2596// a test library to be installed alongside a test.
2597// The data file should be installed (copied from `<SrcPath>`) to
2598// `<install_root>/<RelativeInstallPath>/<filename>`, or
2599// `<install_root>/<filename>` if RelativeInstallPath is empty.
2600type DataPath struct {
2601 // The path of the data file that should be copied into the data directory
2602 SrcPath Path
2603 // The install path of the data file, relative to the install root.
2604 RelativeInstallPath string
Colin Cross5c1d5fb2023-11-15 12:39:40 -08002605 // If WithoutRel is true, use SrcPath.Base() instead of SrcPath.Rel() as the filename.
2606 WithoutRel bool
Chris Parsons216e10a2020-07-09 17:12:52 -04002607}
Colin Crossdcf71b22021-02-01 13:59:03 -08002608
Colin Crossd442a0e2023-11-16 11:19:26 -08002609func (d *DataPath) ToRelativeInstallPath() string {
2610 relPath := d.SrcPath.Rel()
Colin Cross5c1d5fb2023-11-15 12:39:40 -08002611 if d.WithoutRel {
2612 relPath = d.SrcPath.Base()
2613 }
Colin Crossd442a0e2023-11-16 11:19:26 -08002614 if d.RelativeInstallPath != "" {
2615 relPath = filepath.Join(d.RelativeInstallPath, relPath)
2616 }
2617 return relPath
2618}
2619
Colin Crossdcf71b22021-02-01 13:59:03 -08002620// PathsIfNonNil returns a Paths containing only the non-nil input arguments.
2621func PathsIfNonNil(paths ...Path) Paths {
2622 if len(paths) == 0 {
2623 // Fast path for empty argument list
2624 return nil
2625 } else if len(paths) == 1 {
2626 // Fast path for a single argument
2627 if paths[0] != nil {
2628 return paths
2629 } else {
2630 return nil
2631 }
2632 }
2633 ret := make(Paths, 0, len(paths))
2634 for _, path := range paths {
2635 if path != nil {
2636 ret = append(ret, path)
2637 }
2638 }
2639 if len(ret) == 0 {
2640 return nil
2641 }
2642 return ret
2643}
Chris Wailesb2703ad2021-07-30 13:25:42 -07002644
2645var thirdPartyDirPrefixExceptions = []*regexp.Regexp{
2646 regexp.MustCompile("^vendor/[^/]*google[^/]*/"),
2647 regexp.MustCompile("^hardware/google/"),
2648 regexp.MustCompile("^hardware/interfaces/"),
2649 regexp.MustCompile("^hardware/libhardware[^/]*/"),
2650 regexp.MustCompile("^hardware/ril/"),
2651}
2652
2653func IsThirdPartyPath(path string) bool {
2654 thirdPartyDirPrefixes := []string{"external/", "vendor/", "hardware/"}
2655
2656 if HasAnyPrefix(path, thirdPartyDirPrefixes) {
2657 for _, prefix := range thirdPartyDirPrefixExceptions {
2658 if prefix.MatchString(path) {
2659 return false
2660 }
2661 }
2662 return true
2663 }
2664 return false
2665}
Jihoon Kangf27c3a52024-11-12 21:27:09 +00002666
2667// ToRelativeSourcePath converts absolute source path to the path relative to the source root.
2668// This throws an error if the input path is outside of the source root and cannot be converted
2669// to the relative path.
2670// This should be rarely used given that the source path is relative in Soong.
2671func ToRelativeSourcePath(ctx PathContext, path string) string {
2672 ret := path
2673 if filepath.IsAbs(path) {
2674 relPath, err := filepath.Rel(absSrcDir, path)
2675 if err != nil || strings.HasPrefix(relPath, "..") {
2676 ReportPathErrorf(ctx, "%s is outside of the source root", path)
2677 }
2678 ret = relPath
2679 }
2680 return ret
2681}