blob: 8f066cc0804d8767de6dba7142cf582c118e65b2 [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 Liud3228ac2024-11-08 23:11:47 +0000678 if !OtherModuleProviderOrDefault(ctx, *module, CommonPropertiesProviderKey).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)
1254 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
1309// existsWithDependencies returns true if the path exists, and adds appropriate dependencies to rerun if the
1310// path does not exist.
Colin Cross662d6142022-11-03 20:38:01 -07001311func existsWithDependencies(ctx PathGlobContext, path SourcePath) (exists bool, err error) {
Colin Cross192e97a2018-02-22 14:21:02 -08001312 var files []string
1313
Colin Cross662d6142022-11-03 20:38:01 -07001314 // Use glob to produce proper dependencies, even though we only want
1315 // a single file.
1316 files, err = ctx.GlobWithDeps(path.String(), nil)
Colin Cross192e97a2018-02-22 14:21:02 -08001317
1318 if err != nil {
1319 return false, fmt.Errorf("glob: %s", err.Error())
1320 }
1321
1322 return len(files) > 0, nil
1323}
1324
1325// PathForSource joins the provided path components and validates that the result
1326// neither escapes the source dir nor is in the out dir.
1327// On error, it will return a usable, but invalid SourcePath, and report a ModuleError.
1328func PathForSource(ctx PathContext, pathComponents ...string) SourcePath {
1329 path, err := pathForSource(ctx, pathComponents...)
1330 if err != nil {
1331 reportPathError(ctx, err)
1332 }
1333
Colin Crosse3924e12018-08-15 20:18:53 -07001334 if pathtools.IsGlob(path.String()) {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001335 ReportPathErrorf(ctx, "path may not contain a glob: %s", path.String())
Colin Crosse3924e12018-08-15 20:18:53 -07001336 }
1337
Liz Kammera830f3a2020-11-10 10:50:34 -08001338 if modCtx, ok := ctx.(ModuleMissingDepsPathContext); ok && ctx.Config().AllowMissingDependencies() {
Colin Cross662d6142022-11-03 20:38:01 -07001339 exists, err := existsWithDependencies(modCtx, path)
Colin Cross192e97a2018-02-22 14:21:02 -08001340 if err != nil {
1341 reportPathError(ctx, err)
1342 }
1343 if !exists {
1344 modCtx.AddMissingDependencies([]string{path.String()})
1345 }
Colin Cross988414c2020-01-11 01:11:46 +00001346 } else if exists, _, err := ctx.Config().fs.Exists(path.String()); err != nil {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001347 ReportPathErrorf(ctx, "%s: %s", path, err.Error())
Pedro Loureiro5d190cc2021-02-15 15:41:33 +00001348 } else if !exists && !ctx.Config().TestAllowNonExistentPaths {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001349 ReportPathErrorf(ctx, "source path %q does not exist", path)
Colin Cross192e97a2018-02-22 14:21:02 -08001350 }
1351 return path
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001352}
1353
Cole Faustbc65a3f2023-08-01 16:38:55 +00001354// PathForArbitraryOutput creates a path for the given components. Unlike PathForOutput,
1355// the path is relative to the root of the output folder, not the out/soong folder.
1356func PathForArbitraryOutput(ctx PathContext, pathComponents ...string) Path {
Colin Cross3b1c6842024-07-26 11:52:57 -07001357 path, err := validatePath(pathComponents...)
Cole Faustbc65a3f2023-08-01 16:38:55 +00001358 if err != nil {
1359 reportPathError(ctx, err)
1360 }
Colin Cross3b1c6842024-07-26 11:52:57 -07001361 fullPath := filepath.Join(ctx.Config().OutDir(), path)
1362 path = fullPath[len(fullPath)-len(path):]
1363 return OutputPath{basePath{path, ""}, ctx.Config().OutDir(), fullPath}
Cole Faustbc65a3f2023-08-01 16:38:55 +00001364}
1365
Spandan Dasc6c10fa2022-10-21 21:52:13 +00001366// MaybeExistentPathForSource joins the provided path components and validates that the result
1367// neither escapes the source dir nor is in the out dir.
1368// It does not validate whether the path exists.
1369func MaybeExistentPathForSource(ctx PathContext, pathComponents ...string) SourcePath {
1370 path, err := pathForSource(ctx, pathComponents...)
1371 if err != nil {
1372 reportPathError(ctx, err)
1373 }
1374
1375 if pathtools.IsGlob(path.String()) {
1376 ReportPathErrorf(ctx, "path may not contain a glob: %s", path.String())
1377 }
1378 return path
1379}
1380
Liz Kammer7aa52882021-02-11 09:16:14 -05001381// ExistentPathForSource returns an OptionalPath with the SourcePath, rooted from SrcDir, *not*
1382// rooted from the module's local source directory, if the path exists, or an empty OptionalPath if
1383// it doesn't exist. Dependencies are added so that the ninja file will be regenerated if the state
1384// of the path changes.
Colin Cross662d6142022-11-03 20:38:01 -07001385func ExistentPathForSource(ctx PathGlobContext, pathComponents ...string) OptionalPath {
Colin Cross192e97a2018-02-22 14:21:02 -08001386 path, err := pathForSource(ctx, pathComponents...)
Colin Cross1ccfcc32018-02-22 13:54:26 -08001387 if err != nil {
1388 reportPathError(ctx, err)
Martin Stjernholmc32dd1c2021-09-15 02:39:00 +01001389 // No need to put the error message into the returned path since it has been reported already.
Colin Cross1ccfcc32018-02-22 13:54:26 -08001390 return OptionalPath{}
1391 }
Colin Crossc48c1432018-02-23 07:09:01 +00001392
Colin Crosse3924e12018-08-15 20:18:53 -07001393 if pathtools.IsGlob(path.String()) {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001394 ReportPathErrorf(ctx, "path may not contain a glob: %s", path.String())
Colin Crosse3924e12018-08-15 20:18:53 -07001395 return OptionalPath{}
1396 }
1397
Colin Cross192e97a2018-02-22 14:21:02 -08001398 exists, err := existsWithDependencies(ctx, path)
Colin Crossc48c1432018-02-23 07:09:01 +00001399 if err != nil {
1400 reportPathError(ctx, err)
1401 return OptionalPath{}
1402 }
Colin Cross192e97a2018-02-22 14:21:02 -08001403 if !exists {
Martin Stjernholmc32dd1c2021-09-15 02:39:00 +01001404 return InvalidOptionalPath(path.String() + " does not exist")
Colin Crossc48c1432018-02-23 07:09:01 +00001405 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001406 return OptionalPathForPath(path)
1407}
1408
1409func (p SourcePath) String() string {
Cole Faust483d1f72023-01-09 14:35:27 -08001410 if p.path == "" {
1411 return "."
1412 }
1413 return p.path
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001414}
1415
Colin Cross7707b242024-07-26 12:02:36 -07001416func (p SourcePath) WithoutRel() Path {
1417 p.basePath = p.basePath.withoutRel()
1418 return p
1419}
1420
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001421// Join creates a new SourcePath with paths... joined with the current path. The
1422// provided paths... may not use '..' to escape from the current path.
1423func (p SourcePath) Join(ctx PathContext, paths ...string) SourcePath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001424 path, err := validatePath(paths...)
1425 if err != nil {
1426 reportPathError(ctx, err)
1427 }
Colin Cross0db55682017-12-05 15:36:55 -08001428 return p.withRel(path)
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001429}
1430
Colin Cross2fafa3e2019-03-05 12:39:51 -08001431// join is like Join but does less path validation.
1432func (p SourcePath) join(ctx PathContext, paths ...string) SourcePath {
1433 path, err := validateSafePath(paths...)
1434 if err != nil {
1435 reportPathError(ctx, err)
1436 }
1437 return p.withRel(path)
1438}
1439
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001440// OverlayPath returns the overlay for `path' if it exists. This assumes that the
1441// SourcePath is the path to a resource overlay directory.
Liz Kammera830f3a2020-11-10 10:50:34 -08001442func (p SourcePath) OverlayPath(ctx ModuleMissingDepsPathContext, path Path) OptionalPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001443 var relDir string
Colin Cross07e51612019-03-05 12:46:40 -08001444 if srcPath, ok := path.(SourcePath); ok {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001445 relDir = srcPath.path
1446 } else {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001447 ReportPathErrorf(ctx, "Cannot find relative path for %s(%s)", reflect.TypeOf(path).Name(), path)
Martin Stjernholmc32dd1c2021-09-15 02:39:00 +01001448 // No need to put the error message into the returned path since it has been reported already.
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001449 return OptionalPath{}
1450 }
Cole Faust483d1f72023-01-09 14:35:27 -08001451 dir := filepath.Join(p.path, relDir)
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001452 // Use Glob so that we are run again if the directory is added.
Colin Cross7f19f372016-11-01 11:10:25 -07001453 if pathtools.IsGlob(dir) {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001454 ReportPathErrorf(ctx, "Path may not contain a glob: %s", dir)
Dan Willemsen7b310ee2015-12-18 15:11:17 -08001455 }
Colin Cross461b4452018-02-23 09:22:42 -08001456 paths, err := ctx.GlobWithDeps(dir, nil)
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001457 if err != nil {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001458 ReportPathErrorf(ctx, "glob: %s", err.Error())
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001459 return OptionalPath{}
1460 }
1461 if len(paths) == 0 {
Martin Stjernholmc32dd1c2021-09-15 02:39:00 +01001462 return InvalidOptionalPath(dir + " does not exist")
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001463 }
Cole Faust483d1f72023-01-09 14:35:27 -08001464 return OptionalPathForPath(PathForSource(ctx, paths[0]))
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001465}
1466
Colin Cross70dda7e2019-10-01 22:05:35 -07001467// OutputPath is a Path representing an intermediates file path rooted from the build directory
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001468type OutputPath struct {
1469 basePath
Paul Duffind65c58b2021-03-24 09:22:07 +00001470
Colin Cross3b1c6842024-07-26 11:52:57 -07001471 // The base out directory for this path, either Config.SoongOutDir() or Config.OutDir()
1472 outDir string
Paul Duffind65c58b2021-03-24 09:22:07 +00001473
Colin Crossd63c9a72020-01-29 16:52:50 -08001474 fullPath string
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001475}
1476
Yu Liu467d7c52024-09-18 21:54:44 +00001477type outputPathGob struct {
Yu Liu5246a7e2024-10-09 20:04:52 +00001478 BasePath basePath
Yu Liu467d7c52024-09-18 21:54:44 +00001479 OutDir string
1480 FullPath string
1481}
Yu Liufa297642024-06-11 00:13:02 +00001482
Yu Liu467d7c52024-09-18 21:54:44 +00001483func (p *OutputPath) ToGob() *outputPathGob {
1484 return &outputPathGob{
Yu Liu5246a7e2024-10-09 20:04:52 +00001485 BasePath: p.basePath,
Yu Liu467d7c52024-09-18 21:54:44 +00001486 OutDir: p.outDir,
1487 FullPath: p.fullPath,
1488 }
1489}
1490
1491func (p *OutputPath) FromGob(data *outputPathGob) {
Yu Liu5246a7e2024-10-09 20:04:52 +00001492 p.basePath = data.BasePath
Yu Liu467d7c52024-09-18 21:54:44 +00001493 p.outDir = data.OutDir
1494 p.fullPath = data.FullPath
1495}
1496
1497func (p OutputPath) GobEncode() ([]byte, error) {
Yu Liu3cadf7d2024-10-24 18:47:06 +00001498 return gobtools.CustomGobEncode[outputPathGob](&p)
Yu Liufa297642024-06-11 00:13:02 +00001499}
1500
1501func (p *OutputPath) GobDecode(data []byte) error {
Yu Liu3cadf7d2024-10-24 18:47:06 +00001502 return gobtools.CustomGobDecode[outputPathGob](data, p)
Yu Liufa297642024-06-11 00:13:02 +00001503}
1504
Colin Cross702e0f82017-10-18 17:27:54 -07001505func (p OutputPath) withRel(rel string) OutputPath {
Colin Cross0db55682017-12-05 15:36:55 -08001506 p.basePath = p.basePath.withRel(rel)
Colin Crossd63c9a72020-01-29 16:52:50 -08001507 p.fullPath = filepath.Join(p.fullPath, rel)
Colin Cross702e0f82017-10-18 17:27:54 -07001508 return p
1509}
1510
Colin Cross7707b242024-07-26 12:02:36 -07001511func (p OutputPath) WithoutRel() Path {
1512 p.basePath = p.basePath.withoutRel()
Colin Cross3063b782018-08-15 11:19:12 -07001513 return p
1514}
1515
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02001516func (p OutputPath) getSoongOutDir() string {
Colin Cross3b1c6842024-07-26 11:52:57 -07001517 return p.outDir
Paul Duffin9b478b02019-12-10 13:41:51 +00001518}
1519
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001520func (p OutputPath) RelativeToTop() Path {
1521 return p.outputPathRelativeToTop()
1522}
1523
1524func (p OutputPath) outputPathRelativeToTop() OutputPath {
Colin Cross3b1c6842024-07-26 11:52:57 -07001525 p.fullPath = StringPathRelativeToTop(p.outDir, p.fullPath)
1526 if strings.HasSuffix(p.outDir, testOutSoongSubDir) {
1527 p.outDir = TestOutSoongDir
1528 } else {
1529 // Handle the PathForArbitraryOutput case
1530 p.outDir = testOutDir
1531 }
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001532 return p
1533}
1534
Paul Duffin0267d492021-02-02 10:05:52 +00001535func (p OutputPath) objPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleObjPath {
1536 return PathForModuleObj(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
1537}
1538
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001539var _ Path = OutputPath{}
Paul Duffin9b478b02019-12-10 13:41:51 +00001540var _ WritablePath = OutputPath{}
Paul Duffin0267d492021-02-02 10:05:52 +00001541var _ objPathProvider = OutputPath{}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001542
Chris Parsons8f232a22020-06-23 17:37:05 -04001543// toolDepPath is a Path representing a dependency of the build tool.
1544type toolDepPath struct {
1545 basePath
1546}
1547
Colin Cross7707b242024-07-26 12:02:36 -07001548func (t toolDepPath) WithoutRel() Path {
1549 t.basePath = t.basePath.withoutRel()
1550 return t
1551}
1552
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001553func (t toolDepPath) RelativeToTop() Path {
1554 ensureTestOnly()
1555 return t
1556}
1557
Chris Parsons8f232a22020-06-23 17:37:05 -04001558var _ Path = toolDepPath{}
1559
1560// pathForBuildToolDep returns a toolDepPath representing the given path string.
1561// There is no validation for the path, as it is "trusted": It may fail
1562// normal validation checks. For example, it may be an absolute path.
1563// Only use this function to construct paths for dependencies of the build
1564// tool invocation.
1565func pathForBuildToolDep(ctx PathContext, path string) toolDepPath {
Paul Duffin74abc5d2021-03-24 09:24:59 +00001566 return toolDepPath{basePath{path, ""}}
Chris Parsons8f232a22020-06-23 17:37:05 -04001567}
1568
Jeff Gaston734e3802017-04-10 15:47:24 -07001569// PathForOutput joins the provided paths and returns an OutputPath that is
1570// validated to not escape the build dir.
1571// On error, it will return a usable, but invalid OutputPath, and report a ModuleError.
1572func PathForOutput(ctx PathContext, pathComponents ...string) OutputPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001573 path, err := validatePath(pathComponents...)
1574 if err != nil {
1575 reportPathError(ctx, err)
1576 }
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02001577 fullPath := filepath.Join(ctx.Config().soongOutDir, path)
Colin Crossd63c9a72020-01-29 16:52:50 -08001578 path = fullPath[len(fullPath)-len(path):]
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02001579 return OutputPath{basePath{path, ""}, ctx.Config().soongOutDir, fullPath}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001580}
1581
Colin Cross3b1c6842024-07-26 11:52:57 -07001582// PathsForOutput returns Paths rooted from outDir
Colin Cross40e33732019-02-15 11:08:35 -08001583func PathsForOutput(ctx PathContext, paths []string) WritablePaths {
1584 ret := make(WritablePaths, len(paths))
1585 for i, path := range paths {
1586 ret[i] = PathForOutput(ctx, path)
1587 }
1588 return ret
1589}
1590
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001591func (p OutputPath) writablePath() {}
1592
1593func (p OutputPath) String() string {
Colin Crossd63c9a72020-01-29 16:52:50 -08001594 return p.fullPath
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001595}
1596
1597// Join creates a new OutputPath with paths... joined with the current path. The
1598// provided paths... may not use '..' to escape from the current path.
1599func (p OutputPath) Join(ctx PathContext, paths ...string) OutputPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001600 path, err := validatePath(paths...)
1601 if err != nil {
1602 reportPathError(ctx, err)
1603 }
Colin Cross0db55682017-12-05 15:36:55 -08001604 return p.withRel(path)
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001605}
1606
Colin Cross8854a5a2019-02-11 14:14:16 -08001607// ReplaceExtension creates a new OutputPath with the extension replaced with ext.
1608func (p OutputPath) ReplaceExtension(ctx PathContext, ext string) OutputPath {
1609 if strings.Contains(ext, "/") {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001610 ReportPathErrorf(ctx, "extension %q cannot contain /", ext)
Colin Cross8854a5a2019-02-11 14:14:16 -08001611 }
1612 ret := PathForOutput(ctx, pathtools.ReplaceExtension(p.path, ext))
Colin Cross2cdd5df2019-02-25 10:25:24 -08001613 ret.rel = pathtools.ReplaceExtension(p.rel, ext)
Colin Cross8854a5a2019-02-11 14:14:16 -08001614 return ret
1615}
1616
Colin Cross40e33732019-02-15 11:08:35 -08001617// InSameDir creates a new OutputPath from the directory of the current OutputPath joined with the elements in paths.
1618func (p OutputPath) InSameDir(ctx PathContext, paths ...string) OutputPath {
1619 path, err := validatePath(paths...)
1620 if err != nil {
1621 reportPathError(ctx, err)
1622 }
1623
1624 ret := PathForOutput(ctx, filepath.Dir(p.path), path)
Colin Cross2cdd5df2019-02-25 10:25:24 -08001625 ret.rel = filepath.Join(filepath.Dir(p.rel), path)
Colin Cross40e33732019-02-15 11:08:35 -08001626 return ret
1627}
1628
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001629// PathForIntermediates returns an OutputPath representing the top-level
1630// intermediates directory.
1631func PathForIntermediates(ctx PathContext, paths ...string) OutputPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001632 path, err := validatePath(paths...)
1633 if err != nil {
1634 reportPathError(ctx, err)
1635 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001636 return PathForOutput(ctx, ".intermediates", path)
1637}
1638
Colin Cross07e51612019-03-05 12:46:40 -08001639var _ genPathProvider = SourcePath{}
1640var _ objPathProvider = SourcePath{}
1641var _ resPathProvider = SourcePath{}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001642
Colin Cross07e51612019-03-05 12:46:40 -08001643// PathForModuleSrc returns a Path representing the paths... under the
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001644// module's local source directory.
Liz Kammera830f3a2020-11-10 10:50:34 -08001645func PathForModuleSrc(ctx ModuleMissingDepsPathContext, pathComponents ...string) Path {
Paul Duffin407501b2021-07-09 16:56:35 +01001646 // Just join the components textually just to make sure that it does not corrupt a fully qualified
1647 // module reference, e.g. if the pathComponents is "://other:foo" then using filepath.Join() or
1648 // validatePath() will corrupt it, e.g. replace "//" with "/". If the path is not a module
1649 // reference then it will be validated by expandOneSrcPath anyway when it calls expandOneSrcPath.
1650 p := strings.Join(pathComponents, string(filepath.Separator))
Liz Kammer619be462022-01-28 15:13:39 -05001651 paths, err := expandOneSrcPath(sourcePathInput{context: ctx, path: p, includeDirs: true})
Colin Cross8a497952019-03-05 22:25:09 -08001652 if err != nil {
1653 if depErr, ok := err.(missingDependencyError); ok {
1654 if ctx.Config().AllowMissingDependencies() {
1655 ctx.AddMissingDependencies(depErr.missingDeps)
1656 } else {
1657 ctx.ModuleErrorf(`%s, is the property annotated with android:"path"?`, depErr.Error())
1658 }
1659 } else {
1660 reportPathError(ctx, err)
1661 }
1662 return nil
1663 } else if len(paths) == 0 {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001664 ReportPathErrorf(ctx, "%q produced no files, expected exactly one", p)
Colin Cross8a497952019-03-05 22:25:09 -08001665 return nil
1666 } else if len(paths) > 1 {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001667 ReportPathErrorf(ctx, "%q produced %d files, expected exactly one", p, len(paths))
Colin Cross8a497952019-03-05 22:25:09 -08001668 }
1669 return paths[0]
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001670}
1671
Liz Kammera830f3a2020-11-10 10:50:34 -08001672func pathForModuleSrc(ctx EarlyModulePathContext, paths ...string) SourcePath {
Colin Cross07e51612019-03-05 12:46:40 -08001673 p, err := validatePath(paths...)
1674 if err != nil {
1675 reportPathError(ctx, err)
1676 }
1677
1678 path, err := pathForSource(ctx, ctx.ModuleDir(), p)
1679 if err != nil {
1680 reportPathError(ctx, err)
1681 }
1682
1683 path.basePath.rel = p
1684
1685 return path
1686}
1687
Colin Cross2fafa3e2019-03-05 12:39:51 -08001688// PathsWithModuleSrcSubDir takes a list of Paths and returns a new list of Paths where Rel() on each path
1689// will return the path relative to subDir in the module's source directory. If any input paths are not located
1690// inside subDir then a path error will be reported.
Liz Kammera830f3a2020-11-10 10:50:34 -08001691func PathsWithModuleSrcSubDir(ctx EarlyModulePathContext, paths Paths, subDir string) Paths {
Colin Cross2fafa3e2019-03-05 12:39:51 -08001692 paths = append(Paths(nil), paths...)
Colin Cross07e51612019-03-05 12:46:40 -08001693 subDirFullPath := pathForModuleSrc(ctx, subDir)
Colin Cross2fafa3e2019-03-05 12:39:51 -08001694 for i, path := range paths {
1695 rel := Rel(ctx, subDirFullPath.String(), path.String())
1696 paths[i] = subDirFullPath.join(ctx, rel)
1697 }
1698 return paths
1699}
1700
1701// PathWithModuleSrcSubDir takes a Path and returns a Path where Rel() will return the path relative to subDir in the
1702// 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 -08001703func PathWithModuleSrcSubDir(ctx EarlyModulePathContext, path Path, subDir string) Path {
Colin Cross07e51612019-03-05 12:46:40 -08001704 subDirFullPath := pathForModuleSrc(ctx, subDir)
Colin Cross2fafa3e2019-03-05 12:39:51 -08001705 rel := Rel(ctx, subDirFullPath.String(), path.String())
1706 return subDirFullPath.Join(ctx, rel)
1707}
1708
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001709// OptionalPathForModuleSrc returns an OptionalPath. The OptionalPath contains a
1710// valid path if p is non-nil.
Liz Kammera830f3a2020-11-10 10:50:34 -08001711func OptionalPathForModuleSrc(ctx ModuleMissingDepsPathContext, p *string) OptionalPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001712 if p == nil {
1713 return OptionalPath{}
1714 }
1715 return OptionalPathForPath(PathForModuleSrc(ctx, *p))
1716}
1717
Liz Kammera830f3a2020-11-10 10:50:34 -08001718func (p SourcePath) genPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleGenPath {
Colin Cross7fc17db2017-02-01 14:07:55 -08001719 return PathForModuleGen(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001720}
1721
yangbill6d032dd2024-04-18 03:05:49 +00001722func (p SourcePath) genPathWithExtAndTrimExt(ctx ModuleOutPathContext, subdir, ext string, trimExt string) ModuleGenPath {
1723 // If Trim_extension being set, force append Output_extension without replace original extension.
1724 if trimExt != "" {
1725 if ext != "" {
1726 return PathForModuleGen(ctx, subdir, strings.TrimSuffix(p.path, trimExt)+"."+ext)
1727 }
1728 return PathForModuleGen(ctx, subdir, strings.TrimSuffix(p.path, trimExt))
1729 }
1730 return PathForModuleGen(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
1731}
1732
Liz Kammera830f3a2020-11-10 10:50:34 -08001733func (p SourcePath) objPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleObjPath {
Colin Cross7fc17db2017-02-01 14:07:55 -08001734 return PathForModuleObj(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001735}
1736
Liz Kammera830f3a2020-11-10 10:50:34 -08001737func (p SourcePath) resPathWithName(ctx ModuleOutPathContext, name string) ModuleResPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001738 // TODO: Use full directory if the new ctx is not the current ctx?
1739 return PathForModuleRes(ctx, p.path, name)
1740}
1741
1742// ModuleOutPath is a Path representing a module's output directory.
1743type ModuleOutPath struct {
1744 OutputPath
1745}
1746
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001747func (p ModuleOutPath) RelativeToTop() Path {
1748 p.OutputPath = p.outputPathRelativeToTop()
1749 return p
1750}
1751
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001752var _ Path = ModuleOutPath{}
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001753var _ WritablePath = ModuleOutPath{}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001754
Liz Kammera830f3a2020-11-10 10:50:34 -08001755func (p ModuleOutPath) objPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleObjPath {
Pete Bentleyfcf55bf2019-08-16 20:14:32 +01001756 return PathForModuleObj(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
1757}
1758
Liz Kammera830f3a2020-11-10 10:50:34 -08001759// ModuleOutPathContext Subset of ModuleContext functions necessary for output path methods.
1760type ModuleOutPathContext interface {
1761 PathContext
1762
1763 ModuleName() string
1764 ModuleDir() string
1765 ModuleSubDir() string
1766}
1767
1768func pathForModuleOut(ctx ModuleOutPathContext) OutputPath {
Inseob Kimb7e9f5f2024-06-25 17:39:52 +09001769 return PathForOutput(ctx, ".intermediates", ctx.ModuleDir(), ctx.ModuleName(), ctx.ModuleSubDir())
Colin Cross702e0f82017-10-18 17:27:54 -07001770}
1771
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001772// PathForModuleOut returns a Path representing the paths... under the module's
1773// output directory.
Liz Kammera830f3a2020-11-10 10:50:34 -08001774func PathForModuleOut(ctx ModuleOutPathContext, paths ...string) ModuleOutPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001775 p, err := validatePath(paths...)
1776 if err != nil {
1777 reportPathError(ctx, err)
1778 }
Colin Cross702e0f82017-10-18 17:27:54 -07001779 return ModuleOutPath{
Liz Kammera830f3a2020-11-10 10:50:34 -08001780 OutputPath: pathForModuleOut(ctx).withRel(p),
Colin Cross702e0f82017-10-18 17:27:54 -07001781 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001782}
1783
1784// ModuleGenPath is a Path representing the 'gen' directory in a module's output
1785// directory. Mainly used for generated sources.
1786type ModuleGenPath struct {
1787 ModuleOutPath
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001788}
1789
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001790func (p ModuleGenPath) RelativeToTop() Path {
1791 p.OutputPath = p.outputPathRelativeToTop()
1792 return p
1793}
1794
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001795var _ Path = ModuleGenPath{}
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001796var _ WritablePath = ModuleGenPath{}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001797var _ genPathProvider = ModuleGenPath{}
1798var _ objPathProvider = ModuleGenPath{}
1799
1800// PathForModuleGen returns a Path representing the paths... under the module's
1801// `gen' directory.
Liz Kammera830f3a2020-11-10 10:50:34 -08001802func PathForModuleGen(ctx ModuleOutPathContext, paths ...string) ModuleGenPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001803 p, err := validatePath(paths...)
1804 if err != nil {
1805 reportPathError(ctx, err)
1806 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001807 return ModuleGenPath{
Colin Cross702e0f82017-10-18 17:27:54 -07001808 ModuleOutPath: ModuleOutPath{
Liz Kammera830f3a2020-11-10 10:50:34 -08001809 OutputPath: pathForModuleOut(ctx).withRel("gen").withRel(p),
Colin Cross702e0f82017-10-18 17:27:54 -07001810 },
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001811 }
1812}
1813
Liz Kammera830f3a2020-11-10 10:50:34 -08001814func (p ModuleGenPath) genPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleGenPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001815 // TODO: make a different path for local vs remote generated files?
Dan Willemsen21ec4902016-11-02 20:43:13 -07001816 return PathForModuleGen(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001817}
1818
yangbill6d032dd2024-04-18 03:05:49 +00001819func (p ModuleGenPath) genPathWithExtAndTrimExt(ctx ModuleOutPathContext, subdir, ext string, trimExt string) ModuleGenPath {
1820 // If Trim_extension being set, force append Output_extension without replace original extension.
1821 if trimExt != "" {
1822 if ext != "" {
1823 return PathForModuleGen(ctx, subdir, strings.TrimSuffix(p.path, trimExt)+"."+ext)
1824 }
1825 return PathForModuleGen(ctx, subdir, strings.TrimSuffix(p.path, trimExt))
1826 }
1827 return PathForModuleGen(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
1828}
1829
Liz Kammera830f3a2020-11-10 10:50:34 -08001830func (p ModuleGenPath) objPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleObjPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001831 return PathForModuleObj(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
1832}
1833
1834// ModuleObjPath is a Path representing the 'obj' directory in a module's output
1835// directory. Used for compiled objects.
1836type ModuleObjPath struct {
1837 ModuleOutPath
1838}
1839
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001840func (p ModuleObjPath) RelativeToTop() Path {
1841 p.OutputPath = p.outputPathRelativeToTop()
1842 return p
1843}
1844
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001845var _ Path = ModuleObjPath{}
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001846var _ WritablePath = ModuleObjPath{}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001847
1848// PathForModuleObj returns a Path representing the paths... under the module's
1849// 'obj' directory.
Liz Kammera830f3a2020-11-10 10:50:34 -08001850func PathForModuleObj(ctx ModuleOutPathContext, pathComponents ...string) ModuleObjPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001851 p, err := validatePath(pathComponents...)
1852 if err != nil {
1853 reportPathError(ctx, err)
1854 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001855 return ModuleObjPath{PathForModuleOut(ctx, "obj", p)}
1856}
1857
1858// ModuleResPath is a a Path representing the 'res' directory in a module's
1859// output directory.
1860type ModuleResPath struct {
1861 ModuleOutPath
1862}
1863
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001864func (p ModuleResPath) RelativeToTop() Path {
1865 p.OutputPath = p.outputPathRelativeToTop()
1866 return p
1867}
1868
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001869var _ Path = ModuleResPath{}
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001870var _ WritablePath = ModuleResPath{}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001871
1872// PathForModuleRes returns a Path representing the paths... under the module's
1873// 'res' directory.
Liz Kammera830f3a2020-11-10 10:50:34 -08001874func PathForModuleRes(ctx ModuleOutPathContext, pathComponents ...string) ModuleResPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001875 p, err := validatePath(pathComponents...)
1876 if err != nil {
1877 reportPathError(ctx, err)
1878 }
1879
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001880 return ModuleResPath{PathForModuleOut(ctx, "res", p)}
1881}
1882
Colin Cross70dda7e2019-10-01 22:05:35 -07001883// InstallPath is a Path representing a installed file path rooted from the build directory
1884type InstallPath struct {
1885 basePath
Colin Crossff6c33d2019-10-02 16:01:35 -07001886
Lukacs T. Berkib078ade2021-08-31 10:42:08 +02001887 // The soong build directory, i.e. Config.SoongOutDir()
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02001888 soongOutDir string
Paul Duffind65c58b2021-03-24 09:22:07 +00001889
Jiyong Park957bcd92020-10-20 18:23:33 +09001890 // partitionDir is the part of the InstallPath that is automatically determined according to the context.
1891 // For example, it is host/<os>-<arch> for host modules, and target/product/<device>/<partition> for device modules.
1892 partitionDir string
1893
Colin Crossb1692a32021-10-25 15:39:01 -07001894 partition string
1895
Jiyong Park957bcd92020-10-20 18:23:33 +09001896 // makePath indicates whether this path is for Soong (false) or Make (true).
1897 makePath bool
Colin Crossc0e42d52024-02-01 16:42:36 -08001898
1899 fullPath string
Colin Cross70dda7e2019-10-01 22:05:35 -07001900}
1901
Yu Liu467d7c52024-09-18 21:54:44 +00001902type installPathGob struct {
Yu Liu5246a7e2024-10-09 20:04:52 +00001903 BasePath basePath
Yu Liu467d7c52024-09-18 21:54:44 +00001904 SoongOutDir string
1905 PartitionDir string
1906 Partition string
1907 MakePath bool
1908 FullPath string
1909}
Yu Liu26a716d2024-08-30 23:40:32 +00001910
Yu Liu467d7c52024-09-18 21:54:44 +00001911func (p *InstallPath) ToGob() *installPathGob {
1912 return &installPathGob{
Yu Liu5246a7e2024-10-09 20:04:52 +00001913 BasePath: p.basePath,
Yu Liu467d7c52024-09-18 21:54:44 +00001914 SoongOutDir: p.soongOutDir,
1915 PartitionDir: p.partitionDir,
1916 Partition: p.partition,
1917 MakePath: p.makePath,
1918 FullPath: p.fullPath,
1919 }
1920}
1921
1922func (p *InstallPath) FromGob(data *installPathGob) {
Yu Liu5246a7e2024-10-09 20:04:52 +00001923 p.basePath = data.BasePath
Yu Liu467d7c52024-09-18 21:54:44 +00001924 p.soongOutDir = data.SoongOutDir
1925 p.partitionDir = data.PartitionDir
1926 p.partition = data.Partition
1927 p.makePath = data.MakePath
1928 p.fullPath = data.FullPath
1929}
1930
1931func (p InstallPath) GobEncode() ([]byte, error) {
Yu Liu3cadf7d2024-10-24 18:47:06 +00001932 return gobtools.CustomGobEncode[installPathGob](&p)
Yu Liu26a716d2024-08-30 23:40:32 +00001933}
1934
1935func (p *InstallPath) GobDecode(data []byte) error {
Yu Liu3cadf7d2024-10-24 18:47:06 +00001936 return gobtools.CustomGobDecode[installPathGob](data, p)
Yu Liu26a716d2024-08-30 23:40:32 +00001937}
1938
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001939// Will panic if called from outside a test environment.
1940func ensureTestOnly() {
Martin Stjernholm32312eb2021-03-27 18:54:49 +00001941 if PrefixInList(os.Args, "-test.") {
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001942 return
1943 }
Martin Stjernholm32312eb2021-03-27 18:54:49 +00001944 panic(fmt.Errorf("Not in test. Command line:\n %s", strings.Join(os.Args, "\n ")))
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001945}
1946
1947func (p InstallPath) RelativeToTop() Path {
1948 ensureTestOnly()
Colin Crossc0e42d52024-02-01 16:42:36 -08001949 if p.makePath {
Colin Cross3b1c6842024-07-26 11:52:57 -07001950 p.soongOutDir = testOutDir
Colin Crossc0e42d52024-02-01 16:42:36 -08001951 } else {
Colin Cross3b1c6842024-07-26 11:52:57 -07001952 p.soongOutDir = TestOutSoongDir
Colin Crossc0e42d52024-02-01 16:42:36 -08001953 }
1954 p.fullPath = filepath.Join(p.soongOutDir, p.path)
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001955 return p
1956}
1957
Colin Cross7707b242024-07-26 12:02:36 -07001958func (p InstallPath) WithoutRel() Path {
1959 p.basePath = p.basePath.withoutRel()
1960 return p
1961}
1962
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02001963func (p InstallPath) getSoongOutDir() string {
1964 return p.soongOutDir
Paul Duffin9b478b02019-12-10 13:41:51 +00001965}
1966
Hans MÃ¥nssond3f2bd72020-11-27 12:37:28 +01001967func (p InstallPath) ReplaceExtension(ctx PathContext, ext string) OutputPath {
1968 panic("Not implemented")
1969}
1970
Paul Duffin9b478b02019-12-10 13:41:51 +00001971var _ Path = InstallPath{}
1972var _ WritablePath = InstallPath{}
1973
Colin Cross70dda7e2019-10-01 22:05:35 -07001974func (p InstallPath) writablePath() {}
1975
1976func (p InstallPath) String() string {
Colin Crossc0e42d52024-02-01 16:42:36 -08001977 return p.fullPath
Jiyong Park957bcd92020-10-20 18:23:33 +09001978}
1979
1980// PartitionDir returns the path to the partition where the install path is rooted at. It is
1981// out/soong/target/product/<device>/<partition> for device modules, and out/soong/host/<os>-<arch> for host modules.
1982// The ./soong is dropped if the install path is for Make.
1983func (p InstallPath) PartitionDir() string {
1984 if p.makePath {
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02001985 return filepath.Join(p.soongOutDir, "../", p.partitionDir)
Jiyong Park957bcd92020-10-20 18:23:33 +09001986 } else {
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02001987 return filepath.Join(p.soongOutDir, p.partitionDir)
Jiyong Park957bcd92020-10-20 18:23:33 +09001988 }
Colin Cross70dda7e2019-10-01 22:05:35 -07001989}
1990
Jihoon Kangf78a8902022-09-01 22:47:07 +00001991func (p InstallPath) Partition() string {
1992 return p.partition
1993}
1994
Colin Cross70dda7e2019-10-01 22:05:35 -07001995// Join creates a new InstallPath with paths... joined with the current path. The
1996// provided paths... may not use '..' to escape from the current path.
1997func (p InstallPath) Join(ctx PathContext, paths ...string) InstallPath {
1998 path, err := validatePath(paths...)
1999 if err != nil {
2000 reportPathError(ctx, err)
2001 }
2002 return p.withRel(path)
2003}
2004
2005func (p InstallPath) withRel(rel string) InstallPath {
2006 p.basePath = p.basePath.withRel(rel)
Colin Crossc0e42d52024-02-01 16:42:36 -08002007 p.fullPath = filepath.Join(p.fullPath, rel)
Colin Cross70dda7e2019-10-01 22:05:35 -07002008 return p
2009}
2010
Colin Crossc68db4b2021-11-11 18:59:15 -08002011// Deprecated: ToMakePath is a noop, PathForModuleInstall always returns Make paths when building
2012// embedded in Make.
Colin Crossff6c33d2019-10-02 16:01:35 -07002013func (p InstallPath) ToMakePath() InstallPath {
Jiyong Park957bcd92020-10-20 18:23:33 +09002014 p.makePath = true
Colin Crossff6c33d2019-10-02 16:01:35 -07002015 return p
Colin Cross70dda7e2019-10-01 22:05:35 -07002016}
2017
Dan Willemsen34cc69e2015-09-23 15:26:20 -07002018// PathForModuleInstall returns a Path representing the install path for the
2019// module appended with paths...
Colin Cross70dda7e2019-10-01 22:05:35 -07002020func PathForModuleInstall(ctx ModuleInstallPathContext, pathComponents ...string) InstallPath {
Spandan Das5d1b9292021-06-03 19:36:41 +00002021 os, arch := osAndArch(ctx)
Cole Faust11edf552023-10-13 11:32:14 -07002022 partition := modulePartition(ctx, os.Class == Device)
Cole Faust3b703f32023-10-16 13:30:51 -07002023 return pathForInstall(ctx, os, arch, partition, pathComponents...)
Spandan Das5d1b9292021-06-03 19:36:41 +00002024}
2025
Colin Cross1d0eb7a2021-11-03 14:08:20 -07002026// PathForHostDexInstall returns an InstallPath representing the install path for the
2027// module appended with paths...
2028func PathForHostDexInstall(ctx ModuleInstallPathContext, pathComponents ...string) InstallPath {
Cole Faust3b703f32023-10-16 13:30:51 -07002029 return pathForInstall(ctx, ctx.Config().BuildOS, ctx.Config().BuildArch, "", pathComponents...)
Colin Cross1d0eb7a2021-11-03 14:08:20 -07002030}
2031
Spandan Das5d1b9292021-06-03 19:36:41 +00002032// PathForModuleInPartitionInstall is similar to PathForModuleInstall but partition is provided by the caller
2033func PathForModuleInPartitionInstall(ctx ModuleInstallPathContext, partition string, pathComponents ...string) InstallPath {
2034 os, arch := osAndArch(ctx)
Cole Faust3b703f32023-10-16 13:30:51 -07002035 return pathForInstall(ctx, os, arch, partition, pathComponents...)
Spandan Das5d1b9292021-06-03 19:36:41 +00002036}
2037
2038func osAndArch(ctx ModuleInstallPathContext) (OsType, ArchType) {
Colin Cross6e359402020-02-10 15:29:54 -08002039 os := ctx.Os()
Jiyong Park87788b52020-09-01 12:37:45 +09002040 arch := ctx.Arch().ArchType
2041 forceOS, forceArch := ctx.InstallForceOS()
2042 if forceOS != nil {
Colin Cross6e359402020-02-10 15:29:54 -08002043 os = *forceOS
2044 }
Jiyong Park87788b52020-09-01 12:37:45 +09002045 if forceArch != nil {
2046 arch = *forceArch
2047 }
Spandan Das5d1b9292021-06-03 19:36:41 +00002048 return os, arch
2049}
Colin Cross609c49a2020-02-13 13:20:11 -08002050
Colin Crossc0e42d52024-02-01 16:42:36 -08002051func pathForPartitionInstallDir(ctx PathContext, partition, partitionPath string, makePath bool) InstallPath {
2052 fullPath := ctx.Config().SoongOutDir()
2053 if makePath {
2054 // Make path starts with out/ instead of out/soong.
2055 fullPath = filepath.Join(fullPath, "../", partitionPath)
2056 } else {
2057 fullPath = filepath.Join(fullPath, partitionPath)
2058 }
2059
2060 return InstallPath{
2061 basePath: basePath{partitionPath, ""},
2062 soongOutDir: ctx.Config().soongOutDir,
2063 partitionDir: partitionPath,
2064 partition: partition,
2065 makePath: makePath,
2066 fullPath: fullPath,
2067 }
2068}
2069
Cole Faust3b703f32023-10-16 13:30:51 -07002070func pathForInstall(ctx PathContext, os OsType, arch ArchType, partition string,
Colin Cross609c49a2020-02-13 13:20:11 -08002071 pathComponents ...string) InstallPath {
2072
Jiyong Park97859152023-02-14 17:05:48 +09002073 var partitionPaths []string
Colin Cross609c49a2020-02-13 13:20:11 -08002074
Colin Cross6e359402020-02-10 15:29:54 -08002075 if os.Class == Device {
Jiyong Park97859152023-02-14 17:05:48 +09002076 partitionPaths = []string{"target", "product", ctx.Config().DeviceName(), partition}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07002077 } else {
Jiyong Park87788b52020-09-01 12:37:45 +09002078 osName := os.String()
Colin Crossa9b2aac2022-06-15 17:25:51 -07002079 if os == Linux {
Jiyong Park87788b52020-09-01 12:37:45 +09002080 // instead of linux_glibc
2081 osName = "linux"
Dan Willemsen866b5632017-09-22 12:28:24 -07002082 }
Colin Crossa9b2aac2022-06-15 17:25:51 -07002083 if os == LinuxMusl && ctx.Config().UseHostMusl() {
2084 // When using musl instead of glibc, use "linux" instead of "linux_musl". When cross
2085 // compiling we will still use "linux_musl".
2086 osName = "linux"
2087 }
2088
Jiyong Park87788b52020-09-01 12:37:45 +09002089 // SOONG_HOST_OUT is set to out/host/$(HOST_OS)-$(HOST_PREBUILT_ARCH)
2090 // and HOST_PREBUILT_ARCH is forcibly set to x86 even on x86_64 hosts. We don't seem
2091 // to have a plan to fix it (see the comment in build/make/core/envsetup.mk).
2092 // Let's keep using x86 for the existing cases until we have a need to support
2093 // other architectures.
2094 archName := arch.String()
2095 if os.Class == Host && (arch == X86_64 || arch == Common) {
2096 archName = "x86"
2097 }
Jiyong Park97859152023-02-14 17:05:48 +09002098 partitionPaths = []string{"host", osName + "-" + archName, partition}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07002099 }
Colin Cross70dda7e2019-10-01 22:05:35 -07002100
Jiyong Park97859152023-02-14 17:05:48 +09002101 partitionPath, err := validatePath(partitionPaths...)
Colin Cross70dda7e2019-10-01 22:05:35 -07002102 if err != nil {
2103 reportPathError(ctx, err)
2104 }
Colin Crossff6c33d2019-10-02 16:01:35 -07002105
Colin Crossc0e42d52024-02-01 16:42:36 -08002106 base := pathForPartitionInstallDir(ctx, partition, partitionPath, ctx.Config().KatiEnabled())
Jiyong Park957bcd92020-10-20 18:23:33 +09002107 return base.Join(ctx, pathComponents...)
Dan Willemsen34cc69e2015-09-23 15:26:20 -07002108}
2109
Spandan Dasf280b232024-04-04 21:25:51 +00002110func PathForNdkInstall(ctx PathContext, paths ...string) OutputPath {
2111 return PathForOutput(ctx, append([]string{"ndk"}, paths...)...)
Nicolas Geoffray1228e9c2020-02-27 13:45:35 +00002112}
2113
2114func PathForMainlineSdksInstall(ctx PathContext, paths ...string) InstallPath {
Spandan Dasf280b232024-04-04 21:25:51 +00002115 base := pathForPartitionInstallDir(ctx, "", "mainline-sdks", false)
2116 return base.Join(ctx, paths...)
Nicolas Geoffray1228e9c2020-02-27 13:45:35 +00002117}
2118
Weijia Heaa37c162024-11-06 19:46:03 +00002119func PathForSuiteInstall(ctx PathContext, suite string, pathComponents ...string) InstallPath {
2120 return pathForPartitionInstallDir(ctx, "test_suites", "test_suites", false).Join(ctx, suite).Join(ctx, pathComponents...)
2121}
2122
Colin Cross70dda7e2019-10-01 22:05:35 -07002123func InstallPathToOnDevicePath(ctx PathContext, path InstallPath) string {
Colin Crossb1692a32021-10-25 15:39:01 -07002124 rel := Rel(ctx, strings.TrimSuffix(path.PartitionDir(), path.partition), path.String())
Colin Cross43f08db2018-11-12 10:13:39 -08002125 return "/" + rel
2126}
2127
Cole Faust11edf552023-10-13 11:32:14 -07002128func modulePartition(ctx ModuleInstallPathContext, device bool) string {
Colin Cross43f08db2018-11-12 10:13:39 -08002129 var partition string
Colin Cross6e359402020-02-10 15:29:54 -08002130 if ctx.InstallInTestcases() {
2131 // "testcases" install directory can be used for host or device modules.
Jaewoong Jung0949f312019-09-11 10:25:18 -07002132 partition = "testcases"
Cole Faust11edf552023-10-13 11:32:14 -07002133 } else if device {
Colin Cross6e359402020-02-10 15:29:54 -08002134 if ctx.InstallInData() {
2135 partition = "data"
2136 } else if ctx.InstallInRamdisk() {
2137 if ctx.DeviceConfig().BoardUsesRecoveryAsBoot() {
2138 partition = "recovery/root/first_stage_ramdisk"
2139 } else {
2140 partition = "ramdisk"
2141 }
2142 if !ctx.InstallInRoot() {
2143 partition += "/system"
2144 }
Yifan Hong60e0cfb2020-10-21 15:17:56 -07002145 } else if ctx.InstallInVendorRamdisk() {
Yifan Hong39143a92020-10-26 12:43:12 -07002146 // The module is only available after switching root into
2147 // /first_stage_ramdisk. To expose the module before switching root
2148 // on a device without a dedicated recovery partition, install the
2149 // recovery variant.
Yifan Hongdd8dacc2020-10-21 15:40:17 -07002150 if ctx.DeviceConfig().BoardMoveRecoveryResourcesToVendorBoot() {
Petri Gyntherac229562021-03-02 23:44:02 -08002151 partition = "vendor_ramdisk/first_stage_ramdisk"
Yifan Hongdd8dacc2020-10-21 15:40:17 -07002152 } else {
Petri Gyntherac229562021-03-02 23:44:02 -08002153 partition = "vendor_ramdisk"
Yifan Hongdd8dacc2020-10-21 15:40:17 -07002154 }
2155 if !ctx.InstallInRoot() {
2156 partition += "/system"
2157 }
Inseob Kim08758f02021-04-08 21:13:22 +09002158 } else if ctx.InstallInDebugRamdisk() {
2159 partition = "debug_ramdisk"
Colin Cross6e359402020-02-10 15:29:54 -08002160 } else if ctx.InstallInRecovery() {
2161 if ctx.InstallInRoot() {
2162 partition = "recovery/root"
2163 } else {
2164 // the layout of recovery partion is the same as that of system partition
2165 partition = "recovery/root/system"
2166 }
Colin Crossea30d852023-11-29 16:00:16 -08002167 } else if ctx.SocSpecific() || ctx.InstallInVendor() {
Colin Cross6e359402020-02-10 15:29:54 -08002168 partition = ctx.DeviceConfig().VendorPath()
Colin Crossea30d852023-11-29 16:00:16 -08002169 } else if ctx.DeviceSpecific() || ctx.InstallInOdm() {
Colin Cross6e359402020-02-10 15:29:54 -08002170 partition = ctx.DeviceConfig().OdmPath()
Colin Crossea30d852023-11-29 16:00:16 -08002171 } else if ctx.ProductSpecific() || ctx.InstallInProduct() {
Colin Cross6e359402020-02-10 15:29:54 -08002172 partition = ctx.DeviceConfig().ProductPath()
2173 } else if ctx.SystemExtSpecific() {
2174 partition = ctx.DeviceConfig().SystemExtPath()
2175 } else if ctx.InstallInRoot() {
2176 partition = "root"
Spandan Das27ff7672024-11-06 19:23:57 +00002177 } else if ctx.InstallInSystemDlkm() {
2178 partition = ctx.DeviceConfig().SystemDlkmPath()
2179 } else if ctx.InstallInVendorDlkm() {
2180 partition = ctx.DeviceConfig().VendorDlkmPath()
2181 } else if ctx.InstallInOdmDlkm() {
2182 partition = ctx.DeviceConfig().OdmDlkmPath()
Yifan Hong82db7352020-01-21 16:12:26 -08002183 } else {
Colin Cross6e359402020-02-10 15:29:54 -08002184 partition = "system"
Yifan Hong82db7352020-01-21 16:12:26 -08002185 }
Colin Cross6e359402020-02-10 15:29:54 -08002186 if ctx.InstallInSanitizerDir() {
2187 partition = "data/asan/" + partition
Yifan Hong82db7352020-01-21 16:12:26 -08002188 }
Colin Cross43f08db2018-11-12 10:13:39 -08002189 }
2190 return partition
2191}
2192
Colin Cross609c49a2020-02-13 13:20:11 -08002193type InstallPaths []InstallPath
2194
2195// Paths returns the InstallPaths as a Paths
2196func (p InstallPaths) Paths() Paths {
2197 if p == nil {
2198 return nil
2199 }
2200 ret := make(Paths, len(p))
2201 for i, path := range p {
2202 ret[i] = path
2203 }
2204 return ret
2205}
2206
2207// Strings returns the string forms of the install paths.
2208func (p InstallPaths) Strings() []string {
2209 if p == nil {
2210 return nil
2211 }
2212 ret := make([]string, len(p))
2213 for i, path := range p {
2214 ret[i] = path.String()
2215 }
2216 return ret
2217}
2218
Jingwen Chen24d0c562023-02-07 09:29:36 +00002219// validatePathInternal ensures that a path does not leave its component, and
2220// optionally doesn't contain Ninja variables.
2221func validatePathInternal(allowNinjaVariables bool, pathComponents ...string) (string, error) {
Colin Crossbf9ed3f2023-10-24 14:17:03 -07002222 initialEmpty := 0
2223 finalEmpty := 0
2224 for i, path := range pathComponents {
Jingwen Chen24d0c562023-02-07 09:29:36 +00002225 if !allowNinjaVariables && strings.Contains(path, "$") {
2226 return "", fmt.Errorf("Path contains invalid character($): %s", path)
2227 }
2228
Dan Willemsen80a7c2a2015-12-21 14:57:11 -08002229 path := filepath.Clean(path)
2230 if path == ".." || strings.HasPrefix(path, "../") || strings.HasPrefix(path, "/") {
Colin Cross1ccfcc32018-02-22 13:54:26 -08002231 return "", fmt.Errorf("Path is outside directory: %s", path)
Dan Willemsen80a7c2a2015-12-21 14:57:11 -08002232 }
Colin Crossbf9ed3f2023-10-24 14:17:03 -07002233
2234 if i == initialEmpty && pathComponents[i] == "" {
2235 initialEmpty++
2236 }
2237 if i == finalEmpty && pathComponents[len(pathComponents)-1-i] == "" {
2238 finalEmpty++
2239 }
Dan Willemsen80a7c2a2015-12-21 14:57:11 -08002240 }
Colin Crossbf9ed3f2023-10-24 14:17:03 -07002241 // Optimization: filepath.Join("foo", "") returns a newly allocated copy
2242 // of "foo", while filepath.Join("foo") does not. Strip out any empty
2243 // path components.
2244 if initialEmpty == len(pathComponents) {
2245 return "", nil
2246 }
2247 nonEmptyPathComponents := pathComponents[initialEmpty : len(pathComponents)-finalEmpty]
Dan Willemsen34cc69e2015-09-23 15:26:20 -07002248 // TODO: filepath.Join isn't necessarily correct with embedded ninja
2249 // variables. '..' may remove the entire ninja variable, even if it
2250 // will be expanded to multiple nested directories.
Colin Crossbf9ed3f2023-10-24 14:17:03 -07002251 return filepath.Join(nonEmptyPathComponents...), nil
Dan Willemsen34cc69e2015-09-23 15:26:20 -07002252}
2253
Jingwen Chen24d0c562023-02-07 09:29:36 +00002254// validateSafePath validates a path that we trust (may contain ninja
2255// variables). Ensures that each path component does not attempt to leave its
2256// component. Returns a joined version of each path component.
2257func validateSafePath(pathComponents ...string) (string, error) {
2258 return validatePathInternal(true, pathComponents...)
2259}
2260
Dan Willemsen80a7c2a2015-12-21 14:57:11 -08002261// validatePath validates that a path does not include ninja variables, and that
2262// each path component does not attempt to leave its component. Returns a joined
2263// version of each path component.
Colin Cross1ccfcc32018-02-22 13:54:26 -08002264func validatePath(pathComponents ...string) (string, error) {
Jingwen Chen24d0c562023-02-07 09:29:36 +00002265 return validatePathInternal(false, pathComponents...)
Colin Cross6e18ca42015-07-14 18:55:36 -07002266}
Colin Cross5b529592017-05-09 13:34:34 -07002267
Colin Cross0875c522017-11-28 17:34:01 -08002268func PathForPhony(ctx PathContext, phony string) WritablePath {
2269 if strings.ContainsAny(phony, "$/") {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01002270 ReportPathErrorf(ctx, "Phony target contains invalid character ($ or /): %s", phony)
Colin Cross0875c522017-11-28 17:34:01 -08002271 }
Paul Duffin74abc5d2021-03-24 09:24:59 +00002272 return PhonyPath{basePath{phony, ""}}
Colin Cross0875c522017-11-28 17:34:01 -08002273}
2274
Colin Cross74e3fe42017-12-11 15:51:44 -08002275type PhonyPath struct {
2276 basePath
2277}
2278
2279func (p PhonyPath) writablePath() {}
2280
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02002281func (p PhonyPath) getSoongOutDir() string {
Paul Duffind65c58b2021-03-24 09:22:07 +00002282 // A phone path cannot contain any / so cannot be relative to the build directory.
2283 return ""
Paul Duffin9b478b02019-12-10 13:41:51 +00002284}
2285
Paul Duffin85d8f0d2021-03-24 10:18:18 +00002286func (p PhonyPath) RelativeToTop() Path {
2287 ensureTestOnly()
2288 // A phony path cannot contain any / so does not have a build directory so switching to a new
2289 // build directory has no effect so just return this path.
2290 return p
2291}
2292
Colin Cross7707b242024-07-26 12:02:36 -07002293func (p PhonyPath) WithoutRel() Path {
2294 p.basePath = p.basePath.withoutRel()
2295 return p
2296}
2297
Hans MÃ¥nssond3f2bd72020-11-27 12:37:28 +01002298func (p PhonyPath) ReplaceExtension(ctx PathContext, ext string) OutputPath {
2299 panic("Not implemented")
2300}
2301
Colin Cross74e3fe42017-12-11 15:51:44 -08002302var _ Path = PhonyPath{}
2303var _ WritablePath = PhonyPath{}
2304
Colin Cross5b529592017-05-09 13:34:34 -07002305type testPath struct {
2306 basePath
2307}
2308
Paul Duffin85d8f0d2021-03-24 10:18:18 +00002309func (p testPath) RelativeToTop() Path {
2310 ensureTestOnly()
2311 return p
2312}
2313
Colin Cross7707b242024-07-26 12:02:36 -07002314func (p testPath) WithoutRel() Path {
2315 p.basePath = p.basePath.withoutRel()
2316 return p
2317}
2318
Colin Cross5b529592017-05-09 13:34:34 -07002319func (p testPath) String() string {
2320 return p.path
2321}
2322
Paul Duffin85d8f0d2021-03-24 10:18:18 +00002323var _ Path = testPath{}
2324
Colin Cross40e33732019-02-15 11:08:35 -08002325// PathForTesting returns a Path constructed from joining the elements of paths with '/'. It should only be used from
2326// within tests.
Colin Cross5b529592017-05-09 13:34:34 -07002327func PathForTesting(paths ...string) Path {
Colin Cross1ccfcc32018-02-22 13:54:26 -08002328 p, err := validateSafePath(paths...)
2329 if err != nil {
2330 panic(err)
2331 }
Colin Cross5b529592017-05-09 13:34:34 -07002332 return testPath{basePath{path: p, rel: p}}
2333}
2334
Sam Delmerico2351eac2022-05-24 17:10:02 +00002335func PathForTestingWithRel(path, rel string) Path {
2336 p, err := validateSafePath(path, rel)
2337 if err != nil {
2338 panic(err)
2339 }
2340 r, err := validatePath(rel)
2341 if err != nil {
2342 panic(err)
2343 }
2344 return testPath{basePath{path: p, rel: r}}
2345}
2346
Colin Cross40e33732019-02-15 11:08:35 -08002347// PathsForTesting returns a Path constructed from each element in strs. It should only be used from within tests.
2348func PathsForTesting(strs ...string) Paths {
Colin Cross5b529592017-05-09 13:34:34 -07002349 p := make(Paths, len(strs))
2350 for i, s := range strs {
2351 p[i] = PathForTesting(s)
2352 }
2353
2354 return p
2355}
Colin Cross43f08db2018-11-12 10:13:39 -08002356
Colin Cross40e33732019-02-15 11:08:35 -08002357type testPathContext struct {
2358 config Config
Colin Cross40e33732019-02-15 11:08:35 -08002359}
2360
Colin Cross40e33732019-02-15 11:08:35 -08002361func (x *testPathContext) Config() Config { return x.config }
2362func (x *testPathContext) AddNinjaFileDeps(...string) {}
2363
2364// PathContextForTesting returns a PathContext that can be used in tests, for example to create an OutputPath with
2365// PathForOutput.
Colin Cross98be1bb2019-12-13 20:41:13 -08002366func PathContextForTesting(config Config) PathContext {
Colin Cross40e33732019-02-15 11:08:35 -08002367 return &testPathContext{
2368 config: config,
Colin Cross40e33732019-02-15 11:08:35 -08002369 }
2370}
2371
Ulya Trafimovichccc8c852020-10-14 11:29:07 +01002372type testModuleInstallPathContext struct {
2373 baseModuleContext
2374
2375 inData bool
2376 inTestcases bool
2377 inSanitizerDir bool
2378 inRamdisk bool
2379 inVendorRamdisk bool
Inseob Kim08758f02021-04-08 21:13:22 +09002380 inDebugRamdisk bool
Ulya Trafimovichccc8c852020-10-14 11:29:07 +01002381 inRecovery bool
2382 inRoot bool
Colin Crossea30d852023-11-29 16:00:16 -08002383 inOdm bool
2384 inProduct bool
2385 inVendor bool
Spandan Das27ff7672024-11-06 19:23:57 +00002386 inSystemDlkm bool
2387 inVendorDlkm bool
2388 inOdmDlkm bool
Ulya Trafimovichccc8c852020-10-14 11:29:07 +01002389 forceOS *OsType
2390 forceArch *ArchType
2391}
2392
2393func (m testModuleInstallPathContext) Config() Config {
2394 return m.baseModuleContext.config
2395}
2396
2397func (testModuleInstallPathContext) AddNinjaFileDeps(deps ...string) {}
2398
2399func (m testModuleInstallPathContext) InstallInData() bool {
2400 return m.inData
2401}
2402
2403func (m testModuleInstallPathContext) InstallInTestcases() bool {
2404 return m.inTestcases
2405}
2406
2407func (m testModuleInstallPathContext) InstallInSanitizerDir() bool {
2408 return m.inSanitizerDir
2409}
2410
2411func (m testModuleInstallPathContext) InstallInRamdisk() bool {
2412 return m.inRamdisk
2413}
2414
2415func (m testModuleInstallPathContext) InstallInVendorRamdisk() bool {
2416 return m.inVendorRamdisk
2417}
2418
Inseob Kim08758f02021-04-08 21:13:22 +09002419func (m testModuleInstallPathContext) InstallInDebugRamdisk() bool {
2420 return m.inDebugRamdisk
2421}
2422
Ulya Trafimovichccc8c852020-10-14 11:29:07 +01002423func (m testModuleInstallPathContext) InstallInRecovery() bool {
2424 return m.inRecovery
2425}
2426
2427func (m testModuleInstallPathContext) InstallInRoot() bool {
2428 return m.inRoot
2429}
2430
Colin Crossea30d852023-11-29 16:00:16 -08002431func (m testModuleInstallPathContext) InstallInOdm() bool {
2432 return m.inOdm
2433}
2434
2435func (m testModuleInstallPathContext) InstallInProduct() bool {
2436 return m.inProduct
2437}
2438
2439func (m testModuleInstallPathContext) InstallInVendor() bool {
2440 return m.inVendor
2441}
2442
Spandan Das27ff7672024-11-06 19:23:57 +00002443func (m testModuleInstallPathContext) InstallInSystemDlkm() bool {
2444 return m.inSystemDlkm
2445}
2446
2447func (m testModuleInstallPathContext) InstallInVendorDlkm() bool {
2448 return m.inVendorDlkm
2449}
2450
2451func (m testModuleInstallPathContext) InstallInOdmDlkm() bool {
2452 return m.inOdmDlkm
2453}
2454
Ulya Trafimovichccc8c852020-10-14 11:29:07 +01002455func (m testModuleInstallPathContext) InstallForceOS() (*OsType, *ArchType) {
2456 return m.forceOS, m.forceArch
2457}
2458
2459// Construct a minimal ModuleInstallPathContext for testing. Note that baseModuleContext is
2460// default-initialized, which leaves blueprint.baseModuleContext set to nil, so methods that are
2461// delegated to it will panic.
2462func ModuleInstallPathContextForTesting(config Config) ModuleInstallPathContext {
2463 ctx := &testModuleInstallPathContext{}
2464 ctx.config = config
2465 ctx.os = Android
2466 return ctx
2467}
2468
Colin Cross43f08db2018-11-12 10:13:39 -08002469// Rel performs the same function as filepath.Rel, but reports errors to a PathContext, and reports an error if
2470// targetPath is not inside basePath.
2471func Rel(ctx PathContext, basePath string, targetPath string) string {
2472 rel, isRel := MaybeRel(ctx, basePath, targetPath)
2473 if !isRel {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01002474 ReportPathErrorf(ctx, "path %q is not under path %q", targetPath, basePath)
Colin Cross43f08db2018-11-12 10:13:39 -08002475 return ""
2476 }
2477 return rel
2478}
2479
2480// MaybeRel performs the same function as filepath.Rel, but reports errors to a PathContext, and returns false if
2481// targetPath is not inside basePath.
2482func MaybeRel(ctx PathContext, basePath string, targetPath string) (string, bool) {
Dan Willemsen633c5022019-04-12 11:11:38 -07002483 rel, isRel, err := maybeRelErr(basePath, targetPath)
2484 if err != nil {
2485 reportPathError(ctx, err)
2486 }
2487 return rel, isRel
2488}
2489
2490func maybeRelErr(basePath string, targetPath string) (string, bool, error) {
Colin Cross43f08db2018-11-12 10:13:39 -08002491 // filepath.Rel returns an error if one path is absolute and the other is not, handle that case first.
2492 if filepath.IsAbs(basePath) != filepath.IsAbs(targetPath) {
Dan Willemsen633c5022019-04-12 11:11:38 -07002493 return "", false, nil
Colin Cross43f08db2018-11-12 10:13:39 -08002494 }
2495 rel, err := filepath.Rel(basePath, targetPath)
2496 if err != nil {
Dan Willemsen633c5022019-04-12 11:11:38 -07002497 return "", false, err
Colin Cross43f08db2018-11-12 10:13:39 -08002498 } else if rel == ".." || strings.HasPrefix(rel, "../") || strings.HasPrefix(rel, "/") {
Dan Willemsen633c5022019-04-12 11:11:38 -07002499 return "", false, nil
Colin Cross43f08db2018-11-12 10:13:39 -08002500 }
Dan Willemsen633c5022019-04-12 11:11:38 -07002501 return rel, true, nil
Colin Cross43f08db2018-11-12 10:13:39 -08002502}
Colin Cross988414c2020-01-11 01:11:46 +00002503
2504// Writes a file to the output directory. Attempting to write directly to the output directory
2505// will fail due to the sandbox of the soong_build process.
Chris Parsons1a12d032023-02-06 22:37:41 -05002506// Only writes the file if the file doesn't exist or if it has different contents, to prevent
2507// updating the timestamp if no changes would be made. (This is better for incremental
2508// performance.)
Colin Cross988414c2020-01-11 01:11:46 +00002509func WriteFileToOutputDir(path WritablePath, data []byte, perm os.FileMode) error {
Colin Crossd6421132021-11-09 12:32:34 -08002510 absPath := absolutePath(path.String())
2511 err := os.MkdirAll(filepath.Dir(absPath), 0777)
2512 if err != nil {
2513 return err
2514 }
Chris Parsons1a12d032023-02-06 22:37:41 -05002515 return pathtools.WriteFileIfChanged(absPath, data, perm)
Colin Cross988414c2020-01-11 01:11:46 +00002516}
2517
Liz Kammer2dd9ca42020-11-25 16:06:39 -08002518func RemoveAllOutputDir(path WritablePath) error {
2519 return os.RemoveAll(absolutePath(path.String()))
2520}
2521
2522func CreateOutputDirIfNonexistent(path WritablePath, perm os.FileMode) error {
2523 dir := absolutePath(path.String())
Liz Kammer09f947d2021-05-12 14:51:49 -04002524 return createDirIfNonexistent(dir, perm)
2525}
2526
2527func createDirIfNonexistent(dir string, perm os.FileMode) error {
Liz Kammer2dd9ca42020-11-25 16:06:39 -08002528 if _, err := os.Stat(dir); os.IsNotExist(err) {
2529 return os.MkdirAll(dir, os.ModePerm)
2530 } else {
2531 return err
2532 }
2533}
2534
Jingwen Chen78257e52021-05-21 02:34:24 +00002535// absolutePath is deliberately private so that Soong's Go plugins can't use it to find and
2536// read arbitrary files without going through the methods in the current package that track
2537// dependencies.
Colin Cross988414c2020-01-11 01:11:46 +00002538func absolutePath(path string) string {
2539 if filepath.IsAbs(path) {
2540 return path
2541 }
2542 return filepath.Join(absSrcDir, path)
2543}
Chris Parsons216e10a2020-07-09 17:12:52 -04002544
2545// A DataPath represents the path of a file to be used as data, for example
2546// a test library to be installed alongside a test.
2547// The data file should be installed (copied from `<SrcPath>`) to
2548// `<install_root>/<RelativeInstallPath>/<filename>`, or
2549// `<install_root>/<filename>` if RelativeInstallPath is empty.
2550type DataPath struct {
2551 // The path of the data file that should be copied into the data directory
2552 SrcPath Path
2553 // The install path of the data file, relative to the install root.
2554 RelativeInstallPath string
Colin Cross5c1d5fb2023-11-15 12:39:40 -08002555 // If WithoutRel is true, use SrcPath.Base() instead of SrcPath.Rel() as the filename.
2556 WithoutRel bool
Chris Parsons216e10a2020-07-09 17:12:52 -04002557}
Colin Crossdcf71b22021-02-01 13:59:03 -08002558
Colin Crossd442a0e2023-11-16 11:19:26 -08002559func (d *DataPath) ToRelativeInstallPath() string {
2560 relPath := d.SrcPath.Rel()
Colin Cross5c1d5fb2023-11-15 12:39:40 -08002561 if d.WithoutRel {
2562 relPath = d.SrcPath.Base()
2563 }
Colin Crossd442a0e2023-11-16 11:19:26 -08002564 if d.RelativeInstallPath != "" {
2565 relPath = filepath.Join(d.RelativeInstallPath, relPath)
2566 }
2567 return relPath
2568}
2569
Colin Crossdcf71b22021-02-01 13:59:03 -08002570// PathsIfNonNil returns a Paths containing only the non-nil input arguments.
2571func PathsIfNonNil(paths ...Path) Paths {
2572 if len(paths) == 0 {
2573 // Fast path for empty argument list
2574 return nil
2575 } else if len(paths) == 1 {
2576 // Fast path for a single argument
2577 if paths[0] != nil {
2578 return paths
2579 } else {
2580 return nil
2581 }
2582 }
2583 ret := make(Paths, 0, len(paths))
2584 for _, path := range paths {
2585 if path != nil {
2586 ret = append(ret, path)
2587 }
2588 }
2589 if len(ret) == 0 {
2590 return nil
2591 }
2592 return ret
2593}
Chris Wailesb2703ad2021-07-30 13:25:42 -07002594
2595var thirdPartyDirPrefixExceptions = []*regexp.Regexp{
2596 regexp.MustCompile("^vendor/[^/]*google[^/]*/"),
2597 regexp.MustCompile("^hardware/google/"),
2598 regexp.MustCompile("^hardware/interfaces/"),
2599 regexp.MustCompile("^hardware/libhardware[^/]*/"),
2600 regexp.MustCompile("^hardware/ril/"),
2601}
2602
2603func IsThirdPartyPath(path string) bool {
2604 thirdPartyDirPrefixes := []string{"external/", "vendor/", "hardware/"}
2605
2606 if HasAnyPrefix(path, thirdPartyDirPrefixes) {
2607 for _, prefix := range thirdPartyDirPrefixExceptions {
2608 if prefix.MatchString(path) {
2609 return false
2610 }
2611 }
2612 return true
2613 }
2614 return false
2615}
Jihoon Kangf27c3a52024-11-12 21:27:09 +00002616
2617// ToRelativeSourcePath converts absolute source path to the path relative to the source root.
2618// This throws an error if the input path is outside of the source root and cannot be converted
2619// to the relative path.
2620// This should be rarely used given that the source path is relative in Soong.
2621func ToRelativeSourcePath(ctx PathContext, path string) string {
2622 ret := path
2623 if filepath.IsAbs(path) {
2624 relPath, err := filepath.Rel(absSrcDir, path)
2625 if err != nil || strings.HasPrefix(relPath, "..") {
2626 ReportPathErrorf(ctx, "%s is outside of the source root", path)
2627 }
2628 ret = relPath
2629 }
2630 return ret
2631}