blob: 1486ad217566426c26e35887c976fe181948494d [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))
Paul Duffin40131a32021-07-09 17:10:35 +010094 OtherModuleDependencyTag(m blueprint.Module) blueprint.DependencyTag
Cole Faust4e2bf9f2024-09-11 13:26:20 -070095 HasMutatorFinished(mutatorName string) bool
Liz Kammera830f3a2020-11-10 10:50:34 -080096}
97
98// ModuleMissingDepsPathContext is a subset of *ModuleContext methods required by
99// the Path methods that rely on module dependencies having been resolved and ability to report
100// missing dependency errors.
101type ModuleMissingDepsPathContext interface {
102 ModuleWithDepsPathContext
103 AddMissingDependencies(missingDeps []string)
104}
105
Dan Willemsen00269f22017-07-06 16:59:48 -0700106type ModuleInstallPathContext interface {
Colin Cross0ea8ba82019-06-06 14:33:29 -0700107 BaseModuleContext
Dan Willemsen00269f22017-07-06 16:59:48 -0700108
109 InstallInData() bool
Jaewoong Jung0949f312019-09-11 10:25:18 -0700110 InstallInTestcases() bool
Dan Willemsen00269f22017-07-06 16:59:48 -0700111 InstallInSanitizerDir() bool
Yifan Hong1b3348d2020-01-21 15:53:22 -0800112 InstallInRamdisk() bool
Yifan Hong60e0cfb2020-10-21 15:17:56 -0700113 InstallInVendorRamdisk() bool
Inseob Kim08758f02021-04-08 21:13:22 +0900114 InstallInDebugRamdisk() bool
Jiyong Parkf9332f12018-02-01 00:54:12 +0900115 InstallInRecovery() bool
Colin Cross90ba5f42019-10-02 11:10:58 -0700116 InstallInRoot() bool
Colin Crossea30d852023-11-29 16:00:16 -0800117 InstallInOdm() bool
118 InstallInProduct() bool
119 InstallInVendor() bool
Spandan Das27ff7672024-11-06 19:23:57 +0000120 InstallInSystemDlkm() bool
121 InstallInVendorDlkm() bool
122 InstallInOdmDlkm() bool
Jiyong Park87788b52020-09-01 12:37:45 +0900123 InstallForceOS() (*OsType, *ArchType)
Dan Willemsen00269f22017-07-06 16:59:48 -0700124}
125
126var _ ModuleInstallPathContext = ModuleContext(nil)
127
Cole Faust11edf552023-10-13 11:32:14 -0700128type baseModuleContextToModuleInstallPathContext struct {
129 BaseModuleContext
130}
131
132func (ctx *baseModuleContextToModuleInstallPathContext) InstallInData() bool {
133 return ctx.Module().InstallInData()
134}
135
136func (ctx *baseModuleContextToModuleInstallPathContext) InstallInTestcases() bool {
137 return ctx.Module().InstallInTestcases()
138}
139
140func (ctx *baseModuleContextToModuleInstallPathContext) InstallInSanitizerDir() bool {
141 return ctx.Module().InstallInSanitizerDir()
142}
143
144func (ctx *baseModuleContextToModuleInstallPathContext) InstallInRamdisk() bool {
145 return ctx.Module().InstallInRamdisk()
146}
147
148func (ctx *baseModuleContextToModuleInstallPathContext) InstallInVendorRamdisk() bool {
149 return ctx.Module().InstallInVendorRamdisk()
150}
151
152func (ctx *baseModuleContextToModuleInstallPathContext) InstallInDebugRamdisk() bool {
153 return ctx.Module().InstallInDebugRamdisk()
154}
155
156func (ctx *baseModuleContextToModuleInstallPathContext) InstallInRecovery() bool {
157 return ctx.Module().InstallInRecovery()
158}
159
160func (ctx *baseModuleContextToModuleInstallPathContext) InstallInRoot() bool {
161 return ctx.Module().InstallInRoot()
162}
163
Colin Crossea30d852023-11-29 16:00:16 -0800164func (ctx *baseModuleContextToModuleInstallPathContext) InstallInOdm() bool {
165 return ctx.Module().InstallInOdm()
166}
167
168func (ctx *baseModuleContextToModuleInstallPathContext) InstallInProduct() bool {
169 return ctx.Module().InstallInProduct()
170}
171
172func (ctx *baseModuleContextToModuleInstallPathContext) InstallInVendor() bool {
173 return ctx.Module().InstallInVendor()
174}
175
Spandan Das27ff7672024-11-06 19:23:57 +0000176func (ctx *baseModuleContextToModuleInstallPathContext) InstallInSystemDlkm() bool {
177 return ctx.Module().InstallInSystemDlkm()
178}
179
180func (ctx *baseModuleContextToModuleInstallPathContext) InstallInVendorDlkm() bool {
181 return ctx.Module().InstallInVendorDlkm()
182}
183
184func (ctx *baseModuleContextToModuleInstallPathContext) InstallInOdmDlkm() bool {
185 return ctx.Module().InstallInOdmDlkm()
186}
187
Cole Faust11edf552023-10-13 11:32:14 -0700188func (ctx *baseModuleContextToModuleInstallPathContext) InstallForceOS() (*OsType, *ArchType) {
189 return ctx.Module().InstallForceOS()
190}
191
192var _ ModuleInstallPathContext = (*baseModuleContextToModuleInstallPathContext)(nil)
193
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700194// errorfContext is the interface containing the Errorf method matching the
195// Errorf method in blueprint.SingletonContext.
196type errorfContext interface {
197 Errorf(format string, args ...interface{})
Colin Cross3f40fa42015-01-30 17:27:36 -0800198}
199
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700200var _ errorfContext = blueprint.SingletonContext(nil)
201
Spandan Das59a4a2b2024-01-09 21:35:56 +0000202// ModuleErrorfContext is the interface containing the ModuleErrorf method matching
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700203// the ModuleErrorf method in blueprint.ModuleContext.
Spandan Das59a4a2b2024-01-09 21:35:56 +0000204type ModuleErrorfContext interface {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700205 ModuleErrorf(format string, args ...interface{})
Colin Cross3f40fa42015-01-30 17:27:36 -0800206}
207
Spandan Das59a4a2b2024-01-09 21:35:56 +0000208var _ ModuleErrorfContext = blueprint.ModuleContext(nil)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700209
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700210// reportPathError will register an error with the attached context. It
211// attempts ctx.ModuleErrorf for a better error message first, then falls
212// back to ctx.Errorf.
Colin Cross1ccfcc32018-02-22 13:54:26 -0800213func reportPathError(ctx PathContext, err error) {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +0100214 ReportPathErrorf(ctx, "%s", err.Error())
Colin Cross1ccfcc32018-02-22 13:54:26 -0800215}
216
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +0100217// ReportPathErrorf will register an error with the attached context. It
Colin Cross1ccfcc32018-02-22 13:54:26 -0800218// attempts ctx.ModuleErrorf for a better error message first, then falls
219// back to ctx.Errorf.
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +0100220func ReportPathErrorf(ctx PathContext, format string, args ...interface{}) {
Spandan Das59a4a2b2024-01-09 21:35:56 +0000221 if mctx, ok := ctx.(ModuleErrorfContext); ok {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700222 mctx.ModuleErrorf(format, args...)
223 } else if ectx, ok := ctx.(errorfContext); ok {
224 ectx.Errorf(format, args...)
225 } else {
226 panic(fmt.Sprintf(format, args...))
Colin Crossf2298272015-05-12 11:36:53 -0700227 }
228}
229
Colin Cross5e708052019-08-06 13:59:50 -0700230func pathContextName(ctx PathContext, module blueprint.Module) string {
231 if x, ok := ctx.(interface{ ModuleName(blueprint.Module) string }); ok {
232 return x.ModuleName(module)
233 } else if x, ok := ctx.(interface{ OtherModuleName(blueprint.Module) string }); ok {
234 return x.OtherModuleName(module)
235 }
236 return "unknown"
237}
238
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700239type Path interface {
240 // Returns the path in string form
241 String() string
242
Colin Cross4f6fc9c2016-10-26 10:05:25 -0700243 // Ext returns the extension of the last element of the path
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700244 Ext() string
Colin Cross4f6fc9c2016-10-26 10:05:25 -0700245
246 // Base returns the last element of the path
247 Base() string
Colin Crossfaeb7aa2017-02-01 14:12:44 -0800248
249 // Rel returns the portion of the path relative to the directory it was created from. For
250 // example, Rel on a PathsForModuleSrc would return the path relative to the module source
Colin Cross0db55682017-12-05 15:36:55 -0800251 // directory, and OutputPath.Join("foo").Rel() would return "foo".
Colin Crossfaeb7aa2017-02-01 14:12:44 -0800252 Rel() string
Paul Duffin85d8f0d2021-03-24 10:18:18 +0000253
Colin Cross7707b242024-07-26 12:02:36 -0700254 // WithoutRel returns a new Path with no relative path, i.e. Rel() will return the same value as Base().
255 WithoutRel() Path
256
Paul Duffin85d8f0d2021-03-24 10:18:18 +0000257 // RelativeToTop returns a new path relative to the top, it is provided solely for use in tests.
258 //
259 // It is guaranteed to always return the same type as it is called on, e.g. if called on an
260 // InstallPath then the returned value can be converted to an InstallPath.
261 //
262 // A standard build has the following structure:
263 // ../top/
264 // out/ - make install files go here.
Colin Cross3b1c6842024-07-26 11:52:57 -0700265 // out/soong - this is the outDir passed to NewTestConfig()
Paul Duffin85d8f0d2021-03-24 10:18:18 +0000266 // ... - the source files
267 //
268 // This function converts a path so that it appears relative to the ../top/ directory, i.e.
Colin Cross3b1c6842024-07-26 11:52:57 -0700269 // * Make install paths, which have the pattern "outDir/../<path>" are converted into the top
Paul Duffin85d8f0d2021-03-24 10:18:18 +0000270 // relative path "out/<path>"
Colin Cross3b1c6842024-07-26 11:52:57 -0700271 // * Soong install paths and other writable paths, which have the pattern "outDir/soong/<path>" are
Paul Duffin85d8f0d2021-03-24 10:18:18 +0000272 // converted into the top relative path "out/soong/<path>".
273 // * Source paths are already relative to the top.
274 // * Phony paths are not relative to anything.
275 // * toolDepPath have an absolute but known value in so don't need making relative to anything in
276 // order to test.
277 RelativeToTop() Path
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700278}
279
Paul Duffin85d8f0d2021-03-24 10:18:18 +0000280const (
Colin Cross3b1c6842024-07-26 11:52:57 -0700281 testOutDir = "out"
282 testOutSoongSubDir = "/soong"
283 TestOutSoongDir = testOutDir + testOutSoongSubDir
Paul Duffin85d8f0d2021-03-24 10:18:18 +0000284)
285
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700286// WritablePath is a type of path that can be used as an output for build rules.
287type WritablePath interface {
288 Path
289
Paul Duffin9b478b02019-12-10 13:41:51 +0000290 // return the path to the build directory.
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +0200291 getSoongOutDir() string
Paul Duffin9b478b02019-12-10 13:41:51 +0000292
Jeff Gaston734e3802017-04-10 15:47:24 -0700293 // the writablePath method doesn't directly do anything,
294 // but it allows a struct to distinguish between whether or not it implements the WritablePath interface
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700295 writablePath()
Hans MÃ¥nssond3f2bd72020-11-27 12:37:28 +0100296
297 ReplaceExtension(ctx PathContext, ext string) OutputPath
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700298}
299
300type genPathProvider interface {
Liz Kammera830f3a2020-11-10 10:50:34 -0800301 genPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleGenPath
yangbill6d032dd2024-04-18 03:05:49 +0000302 genPathWithExtAndTrimExt(ctx ModuleOutPathContext, subdir, ext string, trimExt string) ModuleGenPath
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700303}
304type objPathProvider interface {
Liz Kammera830f3a2020-11-10 10:50:34 -0800305 objPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleObjPath
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700306}
307type resPathProvider interface {
Liz Kammera830f3a2020-11-10 10:50:34 -0800308 resPathWithName(ctx ModuleOutPathContext, name string) ModuleResPath
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700309}
310
311// GenPathWithExt derives a new file path in ctx's generated sources directory
312// from the current path, but with the new extension.
Liz Kammera830f3a2020-11-10 10:50:34 -0800313func GenPathWithExt(ctx ModuleOutPathContext, subdir string, p Path, ext string) ModuleGenPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700314 if path, ok := p.(genPathProvider); ok {
Dan Willemsen21ec4902016-11-02 20:43:13 -0700315 return path.genPathWithExt(ctx, subdir, ext)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700316 }
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +0100317 ReportPathErrorf(ctx, "Tried to create generated file from unsupported path: %s(%s)", reflect.TypeOf(p).Name(), p)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700318 return PathForModuleGen(ctx)
319}
320
yangbill6d032dd2024-04-18 03:05:49 +0000321// GenPathWithExtAndTrimExt derives a new file path in ctx's generated sources directory
322// from the current path, but with the new extension and trim the suffix.
323func GenPathWithExtAndTrimExt(ctx ModuleOutPathContext, subdir string, p Path, ext string, trimExt string) ModuleGenPath {
324 if path, ok := p.(genPathProvider); ok {
325 return path.genPathWithExtAndTrimExt(ctx, subdir, ext, trimExt)
326 }
327 ReportPathErrorf(ctx, "Tried to create generated file from unsupported path: %s(%s)", reflect.TypeOf(p).Name(), p)
328 return PathForModuleGen(ctx)
329}
330
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700331// ObjPathWithExt derives a new file path in ctx's object directory from the
332// current path, but with the new extension.
Liz Kammera830f3a2020-11-10 10:50:34 -0800333func ObjPathWithExt(ctx ModuleOutPathContext, subdir string, p Path, ext string) ModuleObjPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700334 if path, ok := p.(objPathProvider); ok {
335 return path.objPathWithExt(ctx, subdir, ext)
336 }
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +0100337 ReportPathErrorf(ctx, "Tried to create object file from unsupported path: %s (%s)", reflect.TypeOf(p).Name(), p)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700338 return PathForModuleObj(ctx)
339}
340
341// ResPathWithName derives a new path in ctx's output resource directory, using
342// the current path to create the directory name, and the `name` argument for
343// the filename.
Liz Kammera830f3a2020-11-10 10:50:34 -0800344func ResPathWithName(ctx ModuleOutPathContext, p Path, name string) ModuleResPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700345 if path, ok := p.(resPathProvider); ok {
346 return path.resPathWithName(ctx, name)
347 }
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +0100348 ReportPathErrorf(ctx, "Tried to create res file from unsupported path: %s (%s)", reflect.TypeOf(p).Name(), p)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700349 return PathForModuleRes(ctx)
350}
351
352// OptionalPath is a container that may or may not contain a valid Path.
353type OptionalPath struct {
Martin Stjernholmc32dd1c2021-09-15 02:39:00 +0100354 path Path // nil if invalid.
355 invalidReason string // Not applicable if path != nil. "" if the reason is unknown.
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700356}
357
Yu Liu467d7c52024-09-18 21:54:44 +0000358type optionalPathGob struct {
359 Path Path
360 InvalidReason string
361}
362
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700363// OptionalPathForPath returns an OptionalPath containing the path.
364func OptionalPathForPath(path Path) OptionalPath {
Martin Stjernholm2fee27f2021-09-16 14:11:12 +0100365 return OptionalPath{path: path}
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700366}
367
Martin Stjernholmc32dd1c2021-09-15 02:39:00 +0100368// InvalidOptionalPath returns an OptionalPath that is invalid with the given reason.
369func InvalidOptionalPath(reason string) OptionalPath {
370
371 return OptionalPath{invalidReason: reason}
372}
373
Yu Liu467d7c52024-09-18 21:54:44 +0000374func (p *OptionalPath) ToGob() *optionalPathGob {
375 return &optionalPathGob{
376 Path: p.path,
377 InvalidReason: p.invalidReason,
378 }
379}
380
381func (p *OptionalPath) FromGob(data *optionalPathGob) {
382 p.path = data.Path
383 p.invalidReason = data.InvalidReason
384}
385
386func (p OptionalPath) GobEncode() ([]byte, error) {
Yu Liu3cadf7d2024-10-24 18:47:06 +0000387 return gobtools.CustomGobEncode[optionalPathGob](&p)
Yu Liu467d7c52024-09-18 21:54:44 +0000388}
389
390func (p *OptionalPath) GobDecode(data []byte) error {
Yu Liu3cadf7d2024-10-24 18:47:06 +0000391 return gobtools.CustomGobDecode[optionalPathGob](data, p)
Yu Liu467d7c52024-09-18 21:54:44 +0000392}
393
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700394// Valid returns whether there is a valid path
395func (p OptionalPath) Valid() bool {
Martin Stjernholm2fee27f2021-09-16 14:11:12 +0100396 return p.path != nil
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700397}
398
399// Path returns the Path embedded in this OptionalPath. You must be sure that
400// there is a valid path, since this method will panic if there is not.
401func (p OptionalPath) Path() Path {
Martin Stjernholm2fee27f2021-09-16 14:11:12 +0100402 if p.path == nil {
Martin Stjernholmc32dd1c2021-09-15 02:39:00 +0100403 msg := "Requesting an invalid path"
404 if p.invalidReason != "" {
405 msg += ": " + p.invalidReason
406 }
407 panic(msg)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700408 }
409 return p.path
410}
411
Martin Stjernholmc32dd1c2021-09-15 02:39:00 +0100412// InvalidReason returns the reason that the optional path is invalid, or "" if it is valid.
413func (p OptionalPath) InvalidReason() string {
414 if p.path != nil {
415 return ""
416 }
417 if p.invalidReason == "" {
418 return "unknown"
419 }
420 return p.invalidReason
421}
422
Paul Duffinef081852021-05-13 11:11:15 +0100423// AsPaths converts the OptionalPath into Paths.
424//
425// It returns nil if this is not valid, or a single length slice containing the Path embedded in
426// this OptionalPath.
427func (p OptionalPath) AsPaths() Paths {
Martin Stjernholm2fee27f2021-09-16 14:11:12 +0100428 if p.path == nil {
Paul Duffinef081852021-05-13 11:11:15 +0100429 return nil
430 }
431 return Paths{p.path}
432}
433
Paul Duffinafdd4062021-03-30 19:44:07 +0100434// RelativeToTop returns an OptionalPath with the path that was embedded having been replaced by the
435// result of calling Path.RelativeToTop on it.
436func (p OptionalPath) RelativeToTop() OptionalPath {
Martin Stjernholm2fee27f2021-09-16 14:11:12 +0100437 if p.path == nil {
Paul Duffina5b81352021-03-28 23:57:19 +0100438 return p
439 }
440 p.path = p.path.RelativeToTop()
441 return p
442}
443
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700444// String returns the string version of the Path, or "" if it isn't valid.
445func (p OptionalPath) String() string {
Martin Stjernholm2fee27f2021-09-16 14:11:12 +0100446 if p.path != nil {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700447 return p.path.String()
448 } else {
449 return ""
Colin Crossf2298272015-05-12 11:36:53 -0700450 }
451}
Colin Cross6e18ca42015-07-14 18:55:36 -0700452
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700453// Paths is a slice of Path objects, with helpers to operate on the collection.
454type Paths []Path
455
Paul Duffin85d8f0d2021-03-24 10:18:18 +0000456// RelativeToTop creates a new Paths containing the result of calling Path.RelativeToTop on each
457// item in this slice.
458func (p Paths) RelativeToTop() Paths {
459 ensureTestOnly()
460 if p == nil {
461 return p
462 }
463 ret := make(Paths, len(p))
464 for i, path := range p {
465 ret[i] = path.RelativeToTop()
466 }
467 return ret
468}
469
Jingwen Chen40fd90a2020-06-15 05:24:19 +0000470func (paths Paths) containsPath(path Path) bool {
471 for _, p := range paths {
472 if p == path {
473 return true
474 }
475 }
476 return false
477}
478
Liz Kammer7aa52882021-02-11 09:16:14 -0500479// PathsForSource returns Paths rooted from SrcDir, *not* rooted from the module's local source
480// directory
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700481func PathsForSource(ctx PathContext, paths []string) Paths {
482 ret := make(Paths, len(paths))
483 for i, path := range paths {
484 ret[i] = PathForSource(ctx, path)
485 }
486 return ret
487}
488
Liz Kammer7aa52882021-02-11 09:16:14 -0500489// ExistentPathsForSources returns a list of Paths rooted from SrcDir, *not* rooted from the
490// module's local source directory, that are found in the tree. If any are not found, they are
491// 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 -0700492func ExistentPathsForSources(ctx PathGlobContext, paths []string) Paths {
Dan Willemsen7b310ee2015-12-18 15:11:17 -0800493 ret := make(Paths, 0, len(paths))
494 for _, path := range paths {
Colin Cross32f38982018-02-22 11:47:25 -0800495 p := ExistentPathForSource(ctx, path)
Dan Willemsen7b310ee2015-12-18 15:11:17 -0800496 if p.Valid() {
497 ret = append(ret, p.Path())
498 }
499 }
500 return ret
501}
502
Liz Kammer620dea62021-04-14 17:36:10 -0400503// PathsForModuleSrc returns a Paths{} containing the resolved references in paths:
Colin Crossd079e0b2022-08-16 10:27:33 -0700504// - filepath, relative to local module directory, resolves as a filepath relative to the local
505// source directory
506// - glob, relative to the local module directory, resolves as filepath(s), relative to the local
507// source directory.
508// - other modules using the ":name{.tag}" syntax. These modules must implement SourceFileProducer
mrziwangd38e63d2024-07-15 13:43:37 -0700509// or set the OutputFilesProvider. These resolve as a filepath to an output filepath or generated
510// source filepath.
Colin Crossd079e0b2022-08-16 10:27:33 -0700511//
Liz Kammer620dea62021-04-14 17:36:10 -0400512// Properties passed as the paths argument must have been annotated with struct tag
Colin Cross41955e82019-05-29 14:40:35 -0700513// `android:"path"` so that dependencies on SourceFileProducer modules will have already been handled by the
Spandan Das950091c2023-07-19 22:26:37 +0000514// pathdeps mutator.
Liz Kammer620dea62021-04-14 17:36:10 -0400515// If a requested module is not found as a dependency:
Colin Crossd079e0b2022-08-16 10:27:33 -0700516// - if ctx.Config().AllowMissingDependencies() is true, this module to be marked as having
Liz Kammer620dea62021-04-14 17:36:10 -0400517// missing dependencies
Colin Crossd079e0b2022-08-16 10:27:33 -0700518// - otherwise, a ModuleError is thrown.
Liz Kammera830f3a2020-11-10 10:50:34 -0800519func PathsForModuleSrc(ctx ModuleMissingDepsPathContext, paths []string) Paths {
Colin Cross8a497952019-03-05 22:25:09 -0800520 return PathsForModuleSrcExcludes(ctx, paths, nil)
521}
522
Liz Kammer619be462022-01-28 15:13:39 -0500523type SourceInput struct {
524 Context ModuleMissingDepsPathContext
525 Paths []string
526 ExcludePaths []string
527 IncludeDirs bool
528}
529
Liz Kammer620dea62021-04-14 17:36:10 -0400530// PathsForModuleSrcExcludes returns a Paths{} containing the resolved references in paths, minus
531// those listed in excludes. Elements of paths and excludes are resolved as:
Colin Crossd079e0b2022-08-16 10:27:33 -0700532// - filepath, relative to local module directory, resolves as a filepath relative to the local
533// source directory
534// - glob, relative to the local module directory, resolves as filepath(s), relative to the local
535// source directory. Not valid in excludes.
536// - other modules using the ":name{.tag}" syntax. These modules must implement SourceFileProducer
mrziwangd38e63d2024-07-15 13:43:37 -0700537// or set the OutputFilesProvider. These resolve as a filepath to an output filepath or generated
538// source filepath.
Colin Crossd079e0b2022-08-16 10:27:33 -0700539//
Liz Kammer620dea62021-04-14 17:36:10 -0400540// excluding the items (similarly resolved
541// Properties passed as the paths argument must have been annotated with struct tag
542// `android:"path"` so that dependencies on SourceFileProducer modules will have already been handled by the
Spandan Das950091c2023-07-19 22:26:37 +0000543// pathdeps mutator.
Liz Kammer620dea62021-04-14 17:36:10 -0400544// If a requested module is not found as a dependency:
Colin Crossd079e0b2022-08-16 10:27:33 -0700545// - if ctx.Config().AllowMissingDependencies() is true, this module to be marked as having
Liz Kammer620dea62021-04-14 17:36:10 -0400546// missing dependencies
Colin Crossd079e0b2022-08-16 10:27:33 -0700547// - otherwise, a ModuleError is thrown.
Liz Kammera830f3a2020-11-10 10:50:34 -0800548func PathsForModuleSrcExcludes(ctx ModuleMissingDepsPathContext, paths, excludes []string) Paths {
Liz Kammer619be462022-01-28 15:13:39 -0500549 return PathsRelativeToModuleSourceDir(SourceInput{
550 Context: ctx,
551 Paths: paths,
552 ExcludePaths: excludes,
553 IncludeDirs: true,
554 })
555}
556
557func PathsRelativeToModuleSourceDir(input SourceInput) Paths {
558 ret, missingDeps := PathsAndMissingDepsRelativeToModuleSourceDir(input)
559 if input.Context.Config().AllowMissingDependencies() {
560 input.Context.AddMissingDependencies(missingDeps)
Colin Crossba71a3f2019-03-18 12:12:48 -0700561 } else {
562 for _, m := range missingDeps {
Liz Kammer619be462022-01-28 15:13:39 -0500563 input.Context.ModuleErrorf(`missing dependency on %q, is the property annotated with android:"path"?`, m)
Colin Crossba71a3f2019-03-18 12:12:48 -0700564 }
565 }
566 return ret
567}
568
Inseob Kim93036a52024-10-25 17:02:21 +0900569type directoryPath struct {
570 basePath
571}
572
573func (d *directoryPath) String() string {
574 return d.basePath.String()
575}
576
577func (d *directoryPath) base() basePath {
578 return d.basePath
579}
580
581// DirectoryPath represents a source path for directories. Incompatible with Path by design.
582type DirectoryPath interface {
583 String() string
584 base() basePath
585}
586
587var _ DirectoryPath = (*directoryPath)(nil)
588
589type DirectoryPaths []DirectoryPath
590
Inseob Kim76e19852024-10-10 17:57:22 +0900591// DirectoryPathsForModuleSrcExcludes returns a Paths{} containing the resolved references in
592// directory paths. Elements of paths are resolved as:
593// - filepath, relative to local module directory, resolves as a filepath relative to the local
594// source directory
595// - other modules using the ":name" syntax. These modules must implement DirProvider.
Inseob Kim93036a52024-10-25 17:02:21 +0900596func DirectoryPathsForModuleSrc(ctx ModuleMissingDepsPathContext, paths []string) DirectoryPaths {
597 var ret DirectoryPaths
Inseob Kim76e19852024-10-10 17:57:22 +0900598
599 for _, path := range paths {
600 if m, t := SrcIsModuleWithTag(path); m != "" {
601 module := GetModuleFromPathDep(ctx, m, t)
602 if module == nil {
603 ctx.ModuleErrorf(`missing dependency on %q, is the property annotated with android:"path"?`, m)
604 continue
605 }
606 if t != "" {
607 ctx.ModuleErrorf("DirProvider dependency %q does not support the tag %q", module, t)
608 continue
609 }
610 mctx, ok := ctx.(OtherModuleProviderContext)
611 if !ok {
612 panic(fmt.Errorf("%s is not an OtherModuleProviderContext", ctx))
613 }
614 if dirProvider, ok := OtherModuleProvider(mctx, module, DirProvider); ok {
615 ret = append(ret, dirProvider.Dirs...)
616 } else {
617 ReportPathErrorf(ctx, "module %q does not implement DirProvider", module)
618 }
619 } else {
620 p := pathForModuleSrc(ctx, path)
621 if isDir, err := ctx.Config().fs.IsDir(p.String()); err != nil {
622 ReportPathErrorf(ctx, "%s: %s", p, err.Error())
623 } else if !isDir {
624 ReportPathErrorf(ctx, "module directory path %q is not a directory", p)
625 } else {
Inseob Kim93036a52024-10-25 17:02:21 +0900626 ret = append(ret, &directoryPath{basePath{path: p.path, rel: p.rel}})
Inseob Kim76e19852024-10-10 17:57:22 +0900627 }
628 }
629 }
630
Inseob Kim93036a52024-10-25 17:02:21 +0900631 seen := make(map[DirectoryPath]bool, len(ret))
Inseob Kim76e19852024-10-10 17:57:22 +0900632 for _, path := range ret {
633 if seen[path] {
634 ReportPathErrorf(ctx, "duplicated path %q", path)
635 }
636 seen[path] = true
637 }
638 return ret
639}
640
Ulya Trafimovich4d2eeed2019-11-08 10:54:21 +0000641// OutputPaths is a slice of OutputPath objects, with helpers to operate on the collection.
642type OutputPaths []OutputPath
643
644// Paths returns the OutputPaths as a Paths
645func (p OutputPaths) Paths() Paths {
646 if p == nil {
647 return nil
648 }
649 ret := make(Paths, len(p))
650 for i, path := range p {
651 ret[i] = path
652 }
653 return ret
654}
655
656// Strings returns the string forms of the writable paths.
657func (p OutputPaths) Strings() []string {
658 if p == nil {
659 return nil
660 }
661 ret := make([]string, len(p))
662 for i, path := range p {
663 ret[i] = path.String()
664 }
665 return ret
666}
667
Liz Kammera830f3a2020-11-10 10:50:34 -0800668// Expands Paths to a SourceFileProducer or OutputFileProducer module dependency referenced via ":name" or ":name{.tag}" syntax.
669// If the dependency is not found, a missingErrorDependency is returned.
670// If the module dependency is not a SourceFileProducer or OutputFileProducer, appropriate errors will be returned.
671func getPathsFromModuleDep(ctx ModuleWithDepsPathContext, path, moduleName, tag string) (Paths, error) {
Paul Duffind5cf92e2021-07-09 17:38:55 +0100672 module := GetModuleFromPathDep(ctx, moduleName, tag)
Liz Kammera830f3a2020-11-10 10:50:34 -0800673 if module == nil {
674 return nil, missingDependencyError{[]string{moduleName}}
675 }
Cole Fausta963b942024-04-11 17:43:00 -0700676 if aModule, ok := module.(Module); ok && !aModule.Enabled(ctx) {
Colin Crossfa65cee2021-03-22 17:05:59 -0700677 return nil, missingDependencyError{[]string{moduleName}}
678 }
mrziwange6c85812024-05-22 14:36:09 -0700679 outputFiles, err := outputFilesForModule(ctx, module, tag)
680 if outputFiles != nil && err == nil {
681 return outputFiles, nil
Liz Kammera830f3a2020-11-10 10:50:34 -0800682 } else {
mrziwange6c85812024-05-22 14:36:09 -0700683 return nil, err
Liz Kammera830f3a2020-11-10 10:50:34 -0800684 }
685}
686
Paul Duffind5cf92e2021-07-09 17:38:55 +0100687// GetModuleFromPathDep will return the module that was added as a dependency automatically for
688// properties tagged with `android:"path"` or manually using ExtractSourceDeps or
689// ExtractSourcesDeps.
690//
691// The moduleName and tag supplied to this should be the values returned from SrcIsModuleWithTag.
692// Or, if no tag is expected then the moduleName should be the value returned by SrcIsModule and
693// the tag must be "".
694//
695// If tag is "" then the returned module will be the dependency that was added for ":moduleName".
696// Otherwise, it is the dependency that was added for ":moduleName{tag}".
Paul Duffind5cf92e2021-07-09 17:38:55 +0100697func GetModuleFromPathDep(ctx ModuleWithDepsPathContext, moduleName, tag string) blueprint.Module {
Paul Duffin40131a32021-07-09 17:10:35 +0100698 var found blueprint.Module
699 // The sourceOrOutputDepTag uniquely identifies the module dependency as it contains both the
700 // module name and the tag. Dependencies added automatically for properties tagged with
701 // `android:"path"` are deduped so are guaranteed to be unique. It is possible for duplicate
702 // dependencies to be added manually using ExtractSourcesDeps or ExtractSourceDeps but even then
703 // it will always be the case that the dependencies will be identical, i.e. the same tag and same
704 // moduleName referring to the same dependency module.
705 //
706 // It does not matter whether the moduleName is a fully qualified name or if the module
707 // dependency is a prebuilt module. All that matters is the same information is supplied to
708 // create the tag here as was supplied to create the tag when the dependency was added so that
709 // this finds the matching dependency module.
710 expectedTag := sourceOrOutputDepTag(moduleName, tag)
Colin Cross648daea2024-09-12 14:35:29 -0700711 ctx.VisitDirectDeps(func(module Module) {
Paul Duffin40131a32021-07-09 17:10:35 +0100712 depTag := ctx.OtherModuleDependencyTag(module)
713 if depTag == expectedTag {
714 found = module
715 }
716 })
717 return found
Paul Duffind5cf92e2021-07-09 17:38:55 +0100718}
719
Liz Kammer620dea62021-04-14 17:36:10 -0400720// PathsAndMissingDepsForModuleSrcExcludes returns a Paths{} containing the resolved references in
721// paths, minus those listed in excludes. Elements of paths and excludes are resolved as:
Colin Crossd079e0b2022-08-16 10:27:33 -0700722// - filepath, relative to local module directory, resolves as a filepath relative to the local
723// source directory
724// - glob, relative to the local module directory, resolves as filepath(s), relative to the local
725// source directory. Not valid in excludes.
726// - other modules using the ":name{.tag}" syntax. These modules must implement SourceFileProducer
mrziwangd38e63d2024-07-15 13:43:37 -0700727// or set the OutputFilesProvider. These resolve as a filepath to an output filepath or generated
728// source filepath.
Colin Crossd079e0b2022-08-16 10:27:33 -0700729//
Liz Kammer620dea62021-04-14 17:36:10 -0400730// and a list of the module names of missing module dependencies are returned as the second return.
731// Properties passed as the paths argument must have been annotated with struct tag
Colin Cross41955e82019-05-29 14:40:35 -0700732// `android:"path"` so that dependencies on SourceFileProducer modules will have already been handled by the
Spandan Das950091c2023-07-19 22:26:37 +0000733// pathdeps mutator.
Liz Kammer619be462022-01-28 15:13:39 -0500734func PathsAndMissingDepsForModuleSrcExcludes(ctx ModuleMissingDepsPathContext, paths, excludes []string) (Paths, []string) {
735 return PathsAndMissingDepsRelativeToModuleSourceDir(SourceInput{
736 Context: ctx,
737 Paths: paths,
738 ExcludePaths: excludes,
739 IncludeDirs: true,
740 })
741}
742
743func PathsAndMissingDepsRelativeToModuleSourceDir(input SourceInput) (Paths, []string) {
744 prefix := pathForModuleSrc(input.Context).String()
Colin Cross8a497952019-03-05 22:25:09 -0800745
746 var expandedExcludes []string
Liz Kammer619be462022-01-28 15:13:39 -0500747 if input.ExcludePaths != nil {
748 expandedExcludes = make([]string, 0, len(input.ExcludePaths))
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700749 }
Colin Cross8a497952019-03-05 22:25:09 -0800750
Colin Crossba71a3f2019-03-18 12:12:48 -0700751 var missingExcludeDeps []string
Liz Kammer619be462022-01-28 15:13:39 -0500752 for _, e := range input.ExcludePaths {
Colin Cross41955e82019-05-29 14:40:35 -0700753 if m, t := SrcIsModuleWithTag(e); m != "" {
Liz Kammer619be462022-01-28 15:13:39 -0500754 modulePaths, err := getPathsFromModuleDep(input.Context, e, m, t)
Liz Kammera830f3a2020-11-10 10:50:34 -0800755 if m, ok := err.(missingDependencyError); ok {
756 missingExcludeDeps = append(missingExcludeDeps, m.missingDeps...)
757 } else if err != nil {
Liz Kammer619be462022-01-28 15:13:39 -0500758 reportPathError(input.Context, err)
Colin Cross8a497952019-03-05 22:25:09 -0800759 } else {
Liz Kammera830f3a2020-11-10 10:50:34 -0800760 expandedExcludes = append(expandedExcludes, modulePaths.Strings()...)
Colin Cross8a497952019-03-05 22:25:09 -0800761 }
762 } else {
763 expandedExcludes = append(expandedExcludes, filepath.Join(prefix, e))
764 }
765 }
766
Liz Kammer619be462022-01-28 15:13:39 -0500767 if input.Paths == nil {
Colin Crossba71a3f2019-03-18 12:12:48 -0700768 return nil, missingExcludeDeps
Colin Cross8a497952019-03-05 22:25:09 -0800769 }
770
Colin Crossba71a3f2019-03-18 12:12:48 -0700771 var missingDeps []string
772
Liz Kammer619be462022-01-28 15:13:39 -0500773 expandedSrcFiles := make(Paths, 0, len(input.Paths))
774 for _, s := range input.Paths {
775 srcFiles, err := expandOneSrcPath(sourcePathInput{
776 context: input.Context,
777 path: s,
778 expandedExcludes: expandedExcludes,
779 includeDirs: input.IncludeDirs,
780 })
Colin Cross8a497952019-03-05 22:25:09 -0800781 if depErr, ok := err.(missingDependencyError); ok {
Colin Crossba71a3f2019-03-18 12:12:48 -0700782 missingDeps = append(missingDeps, depErr.missingDeps...)
Colin Cross8a497952019-03-05 22:25:09 -0800783 } else if err != nil {
Liz Kammer619be462022-01-28 15:13:39 -0500784 reportPathError(input.Context, err)
Colin Cross8a497952019-03-05 22:25:09 -0800785 }
786 expandedSrcFiles = append(expandedSrcFiles, srcFiles...)
787 }
Colin Crossba71a3f2019-03-18 12:12:48 -0700788
Jihoon Kang0e3a5352024-04-12 00:45:50 +0000789 // TODO: b/334169722 - Replace with an error instead of implicitly removing duplicates.
790 return FirstUniquePaths(expandedSrcFiles), append(missingDeps, missingExcludeDeps...)
Colin Cross8a497952019-03-05 22:25:09 -0800791}
792
793type missingDependencyError struct {
794 missingDeps []string
795}
796
797func (e missingDependencyError) Error() string {
798 return "missing dependencies: " + strings.Join(e.missingDeps, ", ")
799}
800
Liz Kammer619be462022-01-28 15:13:39 -0500801type sourcePathInput struct {
802 context ModuleWithDepsPathContext
803 path string
804 expandedExcludes []string
805 includeDirs bool
806}
807
Liz Kammera830f3a2020-11-10 10:50:34 -0800808// Expands one path string to Paths rooted from the module's local source
809// directory, excluding those listed in the expandedExcludes.
810// Expands globs, references to SourceFileProducer or OutputFileProducer modules using the ":name" and ":name{.tag}" syntax.
Liz Kammer619be462022-01-28 15:13:39 -0500811func expandOneSrcPath(input sourcePathInput) (Paths, error) {
Jooyung Han7607dd32020-07-05 10:23:14 +0900812 excludePaths := func(paths Paths) Paths {
Liz Kammer619be462022-01-28 15:13:39 -0500813 if len(input.expandedExcludes) == 0 {
Jooyung Han7607dd32020-07-05 10:23:14 +0900814 return paths
815 }
816 remainder := make(Paths, 0, len(paths))
817 for _, p := range paths {
Liz Kammer619be462022-01-28 15:13:39 -0500818 if !InList(p.String(), input.expandedExcludes) {
Jooyung Han7607dd32020-07-05 10:23:14 +0900819 remainder = append(remainder, p)
820 }
821 }
822 return remainder
823 }
Liz Kammer619be462022-01-28 15:13:39 -0500824 if m, t := SrcIsModuleWithTag(input.path); m != "" {
825 modulePaths, err := getPathsFromModuleDep(input.context, input.path, m, t)
Liz Kammera830f3a2020-11-10 10:50:34 -0800826 if err != nil {
827 return nil, err
Colin Cross8a497952019-03-05 22:25:09 -0800828 } else {
Liz Kammera830f3a2020-11-10 10:50:34 -0800829 return excludePaths(modulePaths), nil
Colin Cross8a497952019-03-05 22:25:09 -0800830 }
Colin Cross8a497952019-03-05 22:25:09 -0800831 } else {
Liz Kammer619be462022-01-28 15:13:39 -0500832 p := pathForModuleSrc(input.context, input.path)
833 if pathtools.IsGlob(input.path) {
834 paths := GlobFiles(input.context, p.String(), input.expandedExcludes)
835 return PathsWithModuleSrcSubDir(input.context, paths, ""), nil
836 } else {
837 if exists, _, err := input.context.Config().fs.Exists(p.String()); err != nil {
838 ReportPathErrorf(input.context, "%s: %s", p, err.Error())
839 } else if !exists && !input.context.Config().TestAllowNonExistentPaths {
840 ReportPathErrorf(input.context, "module source path %q does not exist", p)
841 } else if !input.includeDirs {
842 if isDir, err := input.context.Config().fs.IsDir(p.String()); exists && err != nil {
843 ReportPathErrorf(input.context, "%s: %s", p, err.Error())
844 } else if isDir {
845 ReportPathErrorf(input.context, "module source path %q is a directory", p)
846 }
847 }
Colin Cross8a497952019-03-05 22:25:09 -0800848
Liz Kammer619be462022-01-28 15:13:39 -0500849 if InList(p.String(), input.expandedExcludes) {
850 return nil, nil
851 }
852 return Paths{p}, nil
Colin Cross8a497952019-03-05 22:25:09 -0800853 }
Colin Cross8a497952019-03-05 22:25:09 -0800854 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700855}
856
857// pathsForModuleSrcFromFullPath returns Paths rooted from the module's local
858// source directory, but strip the local source directory from the beginning of
Dan Willemsen540a78c2018-02-26 21:50:08 -0800859// each string. If incDirs is false, strip paths with a trailing '/' from the list.
Colin Crossfe4bc362018-09-12 10:02:13 -0700860// It intended for use in globs that only list files that exist, so it allows '$' in
861// filenames.
Liz Kammera830f3a2020-11-10 10:50:34 -0800862func pathsForModuleSrcFromFullPath(ctx EarlyModulePathContext, paths []string, incDirs bool) Paths {
Lukacs T. Berkif7e36d82021-08-16 17:05:09 +0200863 prefix := ctx.ModuleDir() + "/"
Colin Cross0f37af02017-09-27 17:42:05 -0700864 if prefix == "./" {
865 prefix = ""
866 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700867 ret := make(Paths, 0, len(paths))
868 for _, p := range paths {
Dan Willemsen540a78c2018-02-26 21:50:08 -0800869 if !incDirs && strings.HasSuffix(p, "/") {
870 continue
871 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700872 path := filepath.Clean(p)
873 if !strings.HasPrefix(path, prefix) {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +0100874 ReportPathErrorf(ctx, "Path %q is not in module source directory %q", p, prefix)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700875 continue
876 }
Colin Crosse3924e12018-08-15 20:18:53 -0700877
Colin Crossfe4bc362018-09-12 10:02:13 -0700878 srcPath, err := safePathForSource(ctx, ctx.ModuleDir(), path[len(prefix):])
Colin Crosse3924e12018-08-15 20:18:53 -0700879 if err != nil {
880 reportPathError(ctx, err)
881 continue
882 }
883
Colin Cross07e51612019-03-05 12:46:40 -0800884 srcPath.basePath.rel = srcPath.path
Colin Crosse3924e12018-08-15 20:18:53 -0700885
Colin Cross07e51612019-03-05 12:46:40 -0800886 ret = append(ret, srcPath)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700887 }
888 return ret
889}
890
Liz Kammera830f3a2020-11-10 10:50:34 -0800891// PathsWithOptionalDefaultForModuleSrc returns Paths rooted from the module's local source
892// directory. If input is nil, use the default if it exists. If input is empty, returns nil.
893func PathsWithOptionalDefaultForModuleSrc(ctx ModuleMissingDepsPathContext, input []string, def string) Paths {
Colin Cross0ddae7f2019-02-07 15:30:01 -0800894 if input != nil {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700895 return PathsForModuleSrc(ctx, input)
896 }
897 // Use Glob so that if the default doesn't exist, a dependency is added so that when it
898 // is created, we're run again.
Lukacs T. Berkif7e36d82021-08-16 17:05:09 +0200899 path := filepath.Join(ctx.ModuleDir(), def)
Liz Kammera830f3a2020-11-10 10:50:34 -0800900 return Glob(ctx, path, nil)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700901}
902
903// Strings returns the Paths in string form
904func (p Paths) Strings() []string {
905 if p == nil {
906 return nil
907 }
908 ret := make([]string, len(p))
909 for i, path := range p {
910 ret[i] = path.String()
911 }
912 return ret
913}
914
Colin Crossc0efd1d2020-07-03 11:56:24 -0700915func CopyOfPaths(paths Paths) Paths {
916 return append(Paths(nil), paths...)
917}
918
Colin Crossb6715442017-10-24 11:13:31 -0700919// FirstUniquePaths returns all unique elements of a Paths, keeping the first copy of each. It
920// modifies the Paths slice contents in place, and returns a subslice of the original slice.
Dan Willemsenfe92c962017-08-29 12:28:37 -0700921func FirstUniquePaths(list Paths) Paths {
Colin Cross27027c72020-02-28 15:34:17 -0800922 // 128 was chosen based on BenchmarkFirstUniquePaths results.
923 if len(list) > 128 {
924 return firstUniquePathsMap(list)
925 }
926 return firstUniquePathsList(list)
927}
928
Colin Crossc0efd1d2020-07-03 11:56:24 -0700929// SortedUniquePaths returns all unique elements of a Paths in sorted order. It modifies the
930// Paths slice contents in place, and returns a subslice of the original slice.
Jiyong Park33c77362020-05-29 22:00:16 +0900931func SortedUniquePaths(list Paths) Paths {
932 unique := FirstUniquePaths(list)
933 sort.Slice(unique, func(i, j int) bool {
934 return unique[i].String() < unique[j].String()
935 })
936 return unique
937}
938
Colin Cross27027c72020-02-28 15:34:17 -0800939func firstUniquePathsList(list Paths) Paths {
Dan Willemsenfe92c962017-08-29 12:28:37 -0700940 k := 0
941outer:
942 for i := 0; i < len(list); i++ {
943 for j := 0; j < k; j++ {
944 if list[i] == list[j] {
945 continue outer
946 }
947 }
948 list[k] = list[i]
949 k++
950 }
951 return list[:k]
952}
953
Colin Cross27027c72020-02-28 15:34:17 -0800954func firstUniquePathsMap(list Paths) Paths {
955 k := 0
956 seen := make(map[Path]bool, len(list))
957 for i := 0; i < len(list); i++ {
958 if seen[list[i]] {
959 continue
960 }
961 seen[list[i]] = true
962 list[k] = list[i]
963 k++
964 }
965 return list[:k]
966}
967
Colin Cross5d583952020-11-24 16:21:24 -0800968// FirstUniqueInstallPaths returns all unique elements of an InstallPaths, keeping the first copy of each. It
969// modifies the InstallPaths slice contents in place, and returns a subslice of the original slice.
970func FirstUniqueInstallPaths(list InstallPaths) InstallPaths {
971 // 128 was chosen based on BenchmarkFirstUniquePaths results.
972 if len(list) > 128 {
973 return firstUniqueInstallPathsMap(list)
974 }
975 return firstUniqueInstallPathsList(list)
976}
977
978func firstUniqueInstallPathsList(list InstallPaths) InstallPaths {
979 k := 0
980outer:
981 for i := 0; i < len(list); i++ {
982 for j := 0; j < k; j++ {
983 if list[i] == list[j] {
984 continue outer
985 }
986 }
987 list[k] = list[i]
988 k++
989 }
990 return list[:k]
991}
992
993func firstUniqueInstallPathsMap(list InstallPaths) InstallPaths {
994 k := 0
995 seen := make(map[InstallPath]bool, len(list))
996 for i := 0; i < len(list); i++ {
997 if seen[list[i]] {
998 continue
999 }
1000 seen[list[i]] = true
1001 list[k] = list[i]
1002 k++
1003 }
1004 return list[:k]
1005}
1006
Colin Crossb6715442017-10-24 11:13:31 -07001007// LastUniquePaths returns all unique elements of a Paths, keeping the last copy of each. It
1008// modifies the Paths slice contents in place, and returns a subslice of the original slice.
1009func LastUniquePaths(list Paths) Paths {
1010 totalSkip := 0
1011 for i := len(list) - 1; i >= totalSkip; i-- {
1012 skip := 0
1013 for j := i - 1; j >= totalSkip; j-- {
1014 if list[i] == list[j] {
1015 skip++
1016 } else {
1017 list[j+skip] = list[j]
1018 }
1019 }
1020 totalSkip += skip
1021 }
1022 return list[totalSkip:]
1023}
1024
Colin Crossa140bb02018-04-17 10:52:26 -07001025// ReversePaths returns a copy of a Paths in reverse order.
1026func ReversePaths(list Paths) Paths {
1027 if list == nil {
1028 return nil
1029 }
1030 ret := make(Paths, len(list))
1031 for i := range list {
1032 ret[i] = list[len(list)-1-i]
1033 }
1034 return ret
1035}
1036
Jeff Gaston294356f2017-09-27 17:05:30 -07001037func indexPathList(s Path, list []Path) int {
1038 for i, l := range list {
1039 if l == s {
1040 return i
1041 }
1042 }
1043
1044 return -1
1045}
1046
1047func inPathList(p Path, list []Path) bool {
1048 return indexPathList(p, list) != -1
1049}
1050
1051func FilterPathList(list []Path, filter []Path) (remainder []Path, filtered []Path) {
Paul Duffin57b9e1d2019-12-13 00:03:35 +00001052 return FilterPathListPredicate(list, func(p Path) bool { return inPathList(p, filter) })
1053}
1054
1055func FilterPathListPredicate(list []Path, predicate func(Path) bool) (remainder []Path, filtered []Path) {
Jeff Gaston294356f2017-09-27 17:05:30 -07001056 for _, l := range list {
Paul Duffin57b9e1d2019-12-13 00:03:35 +00001057 if predicate(l) {
Jeff Gaston294356f2017-09-27 17:05:30 -07001058 filtered = append(filtered, l)
1059 } else {
1060 remainder = append(remainder, l)
1061 }
1062 }
1063
1064 return
1065}
1066
Colin Cross93e85952017-08-15 13:34:18 -07001067// HasExt returns true of any of the paths have extension ext, otherwise false
1068func (p Paths) HasExt(ext string) bool {
1069 for _, path := range p {
1070 if path.Ext() == ext {
1071 return true
1072 }
1073 }
1074
1075 return false
1076}
1077
1078// FilterByExt returns the subset of the paths that have extension ext
1079func (p Paths) FilterByExt(ext string) Paths {
1080 ret := make(Paths, 0, len(p))
1081 for _, path := range p {
1082 if path.Ext() == ext {
1083 ret = append(ret, path)
1084 }
1085 }
1086 return ret
1087}
1088
1089// FilterOutByExt returns the subset of the paths that do not have extension ext
1090func (p Paths) FilterOutByExt(ext string) Paths {
1091 ret := make(Paths, 0, len(p))
1092 for _, path := range p {
1093 if path.Ext() != ext {
1094 ret = append(ret, path)
1095 }
1096 }
1097 return ret
1098}
1099
Colin Cross5e6cfbe2017-11-03 15:20:35 -07001100// DirectorySortedPaths is a slice of paths that are sorted such that all files in a directory
1101// (including subdirectories) are in a contiguous subslice of the list, and can be found in
1102// O(log(N)) time using a binary search on the directory prefix.
1103type DirectorySortedPaths Paths
1104
1105func PathsToDirectorySortedPaths(paths Paths) DirectorySortedPaths {
1106 ret := append(DirectorySortedPaths(nil), paths...)
1107 sort.Slice(ret, func(i, j int) bool {
1108 return ret[i].String() < ret[j].String()
1109 })
1110 return ret
1111}
1112
1113// PathsInDirectory returns a subslice of the DirectorySortedPaths as a Paths that contains all entries
1114// that are in the specified directory and its subdirectories.
1115func (p DirectorySortedPaths) PathsInDirectory(dir string) Paths {
1116 prefix := filepath.Clean(dir) + "/"
1117 start := sort.Search(len(p), func(i int) bool {
1118 return prefix < p[i].String()
1119 })
1120
1121 ret := p[start:]
1122
1123 end := sort.Search(len(ret), func(i int) bool {
1124 return !strings.HasPrefix(ret[i].String(), prefix)
1125 })
1126
1127 ret = ret[:end]
1128
1129 return Paths(ret)
1130}
1131
Alex Humesky29e3bbe2020-11-20 21:30:13 -05001132// WritablePaths is a slice of WritablePath, used for multiple outputs.
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001133type WritablePaths []WritablePath
1134
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001135// RelativeToTop creates a new WritablePaths containing the result of calling Path.RelativeToTop on
1136// each item in this slice.
1137func (p WritablePaths) RelativeToTop() WritablePaths {
1138 ensureTestOnly()
1139 if p == nil {
1140 return p
1141 }
1142 ret := make(WritablePaths, len(p))
1143 for i, path := range p {
1144 ret[i] = path.RelativeToTop().(WritablePath)
1145 }
1146 return ret
1147}
1148
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001149// Strings returns the string forms of the writable paths.
1150func (p WritablePaths) Strings() []string {
1151 if p == nil {
1152 return nil
1153 }
1154 ret := make([]string, len(p))
1155 for i, path := range p {
1156 ret[i] = path.String()
1157 }
1158 return ret
1159}
1160
Colin Cross3bc7ffa2017-11-22 16:19:37 -08001161// Paths returns the WritablePaths as a Paths
1162func (p WritablePaths) Paths() Paths {
1163 if p == nil {
1164 return nil
1165 }
1166 ret := make(Paths, len(p))
1167 for i, path := range p {
1168 ret[i] = path
1169 }
1170 return ret
1171}
1172
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001173type basePath struct {
Paul Duffin74abc5d2021-03-24 09:24:59 +00001174 path string
1175 rel string
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001176}
1177
Yu Liu467d7c52024-09-18 21:54:44 +00001178type basePathGob struct {
1179 Path string
1180 Rel string
1181}
Yu Liufa297642024-06-11 00:13:02 +00001182
Yu Liu467d7c52024-09-18 21:54:44 +00001183func (p *basePath) ToGob() *basePathGob {
1184 return &basePathGob{
1185 Path: p.path,
1186 Rel: p.rel,
1187 }
1188}
1189
1190func (p *basePath) FromGob(data *basePathGob) {
1191 p.path = data.Path
1192 p.rel = data.Rel
1193}
1194
1195func (p basePath) GobEncode() ([]byte, error) {
Yu Liu3cadf7d2024-10-24 18:47:06 +00001196 return gobtools.CustomGobEncode[basePathGob](&p)
Yu Liufa297642024-06-11 00:13:02 +00001197}
1198
1199func (p *basePath) GobDecode(data []byte) error {
Yu Liu3cadf7d2024-10-24 18:47:06 +00001200 return gobtools.CustomGobDecode[basePathGob](data, p)
Yu Liufa297642024-06-11 00:13:02 +00001201}
1202
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001203func (p basePath) Ext() string {
1204 return filepath.Ext(p.path)
1205}
1206
Colin Cross4f6fc9c2016-10-26 10:05:25 -07001207func (p basePath) Base() string {
1208 return filepath.Base(p.path)
1209}
1210
Colin Crossfaeb7aa2017-02-01 14:12:44 -08001211func (p basePath) Rel() string {
1212 if p.rel != "" {
1213 return p.rel
1214 }
1215 return p.path
1216}
1217
Colin Cross0875c522017-11-28 17:34:01 -08001218func (p basePath) String() string {
1219 return p.path
1220}
1221
Colin Cross0db55682017-12-05 15:36:55 -08001222func (p basePath) withRel(rel string) basePath {
1223 p.path = filepath.Join(p.path, rel)
1224 p.rel = rel
1225 return p
1226}
1227
Colin Cross7707b242024-07-26 12:02:36 -07001228func (p basePath) withoutRel() basePath {
1229 p.rel = filepath.Base(p.path)
1230 return p
1231}
1232
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001233// SourcePath is a Path representing a file path rooted from SrcDir
1234type SourcePath struct {
1235 basePath
1236}
1237
1238var _ Path = SourcePath{}
1239
Colin Cross0db55682017-12-05 15:36:55 -08001240func (p SourcePath) withRel(rel string) SourcePath {
1241 p.basePath = p.basePath.withRel(rel)
1242 return p
1243}
1244
Colin Crossbd73d0d2024-07-26 12:00:33 -07001245func (p SourcePath) RelativeToTop() Path {
1246 ensureTestOnly()
1247 return p
1248}
1249
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001250// safePathForSource is for paths that we expect are safe -- only for use by go
1251// code that is embedding ninja variables in paths
Colin Crossfe4bc362018-09-12 10:02:13 -07001252func safePathForSource(ctx PathContext, pathComponents ...string) (SourcePath, error) {
1253 p, err := validateSafePath(pathComponents...)
Cole Faust483d1f72023-01-09 14:35:27 -08001254 ret := SourcePath{basePath{p, ""}}
Colin Crossfe4bc362018-09-12 10:02:13 -07001255 if err != nil {
1256 return ret, err
1257 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001258
Colin Cross7b3dcc32019-01-24 13:14:39 -08001259 // absolute path already checked by validateSafePath
Inseob Kim5eb7ee92022-04-27 10:30:34 +09001260 // special-case api surface gen files for now
1261 if strings.HasPrefix(ret.String(), ctx.Config().soongOutDir) && !strings.Contains(ret.String(), ctx.Config().soongOutDir+"/.export") {
Mikhail Naganovab1f5182019-02-08 13:17:55 -08001262 return ret, fmt.Errorf("source path %q is in output", ret.String())
Colin Cross6e18ca42015-07-14 18:55:36 -07001263 }
1264
Colin Crossfe4bc362018-09-12 10:02:13 -07001265 return ret, err
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001266}
1267
Colin Cross192e97a2018-02-22 14:21:02 -08001268// pathForSource creates a SourcePath from pathComponents, but does not check that it exists.
1269func pathForSource(ctx PathContext, pathComponents ...string) (SourcePath, error) {
Colin Crossc48c1432018-02-23 07:09:01 +00001270 p, err := validatePath(pathComponents...)
Cole Faust483d1f72023-01-09 14:35:27 -08001271 ret := SourcePath{basePath{p, ""}}
Colin Cross94a32102018-02-22 14:21:02 -08001272 if err != nil {
Colin Cross192e97a2018-02-22 14:21:02 -08001273 return ret, err
Colin Cross94a32102018-02-22 14:21:02 -08001274 }
1275
Colin Cross7b3dcc32019-01-24 13:14:39 -08001276 // absolute path already checked by validatePath
Inseob Kim5eb7ee92022-04-27 10:30:34 +09001277 // special-case for now
1278 if strings.HasPrefix(ret.String(), ctx.Config().soongOutDir) && !strings.Contains(ret.String(), ctx.Config().soongOutDir+"/.export") {
Mikhail Naganovab1f5182019-02-08 13:17:55 -08001279 return ret, fmt.Errorf("source path %q is in output", ret.String())
Colin Crossc48c1432018-02-23 07:09:01 +00001280 }
1281
Colin Cross192e97a2018-02-22 14:21:02 -08001282 return ret, nil
1283}
1284
1285// existsWithDependencies returns true if the path exists, and adds appropriate dependencies to rerun if the
1286// path does not exist.
Colin Cross662d6142022-11-03 20:38:01 -07001287func existsWithDependencies(ctx PathGlobContext, path SourcePath) (exists bool, err error) {
Colin Cross192e97a2018-02-22 14:21:02 -08001288 var files []string
1289
Colin Cross662d6142022-11-03 20:38:01 -07001290 // Use glob to produce proper dependencies, even though we only want
1291 // a single file.
1292 files, err = ctx.GlobWithDeps(path.String(), nil)
Colin Cross192e97a2018-02-22 14:21:02 -08001293
1294 if err != nil {
1295 return false, fmt.Errorf("glob: %s", err.Error())
1296 }
1297
1298 return len(files) > 0, nil
1299}
1300
1301// PathForSource joins the provided path components and validates that the result
1302// neither escapes the source dir nor is in the out dir.
1303// On error, it will return a usable, but invalid SourcePath, and report a ModuleError.
1304func PathForSource(ctx PathContext, pathComponents ...string) SourcePath {
1305 path, err := pathForSource(ctx, pathComponents...)
1306 if err != nil {
1307 reportPathError(ctx, err)
1308 }
1309
Colin Crosse3924e12018-08-15 20:18:53 -07001310 if pathtools.IsGlob(path.String()) {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001311 ReportPathErrorf(ctx, "path may not contain a glob: %s", path.String())
Colin Crosse3924e12018-08-15 20:18:53 -07001312 }
1313
Liz Kammera830f3a2020-11-10 10:50:34 -08001314 if modCtx, ok := ctx.(ModuleMissingDepsPathContext); ok && ctx.Config().AllowMissingDependencies() {
Colin Cross662d6142022-11-03 20:38:01 -07001315 exists, err := existsWithDependencies(modCtx, path)
Colin Cross192e97a2018-02-22 14:21:02 -08001316 if err != nil {
1317 reportPathError(ctx, err)
1318 }
1319 if !exists {
1320 modCtx.AddMissingDependencies([]string{path.String()})
1321 }
Colin Cross988414c2020-01-11 01:11:46 +00001322 } else if exists, _, err := ctx.Config().fs.Exists(path.String()); err != nil {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001323 ReportPathErrorf(ctx, "%s: %s", path, err.Error())
Pedro Loureiro5d190cc2021-02-15 15:41:33 +00001324 } else if !exists && !ctx.Config().TestAllowNonExistentPaths {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001325 ReportPathErrorf(ctx, "source path %q does not exist", path)
Colin Cross192e97a2018-02-22 14:21:02 -08001326 }
1327 return path
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001328}
1329
Cole Faustbc65a3f2023-08-01 16:38:55 +00001330// PathForArbitraryOutput creates a path for the given components. Unlike PathForOutput,
1331// the path is relative to the root of the output folder, not the out/soong folder.
1332func PathForArbitraryOutput(ctx PathContext, pathComponents ...string) Path {
Colin Cross3b1c6842024-07-26 11:52:57 -07001333 path, err := validatePath(pathComponents...)
Cole Faustbc65a3f2023-08-01 16:38:55 +00001334 if err != nil {
1335 reportPathError(ctx, err)
1336 }
Colin Cross3b1c6842024-07-26 11:52:57 -07001337 fullPath := filepath.Join(ctx.Config().OutDir(), path)
1338 path = fullPath[len(fullPath)-len(path):]
1339 return OutputPath{basePath{path, ""}, ctx.Config().OutDir(), fullPath}
Cole Faustbc65a3f2023-08-01 16:38:55 +00001340}
1341
Spandan Dasc6c10fa2022-10-21 21:52:13 +00001342// MaybeExistentPathForSource joins the provided path components and validates that the result
1343// neither escapes the source dir nor is in the out dir.
1344// It does not validate whether the path exists.
1345func MaybeExistentPathForSource(ctx PathContext, pathComponents ...string) SourcePath {
1346 path, err := pathForSource(ctx, pathComponents...)
1347 if err != nil {
1348 reportPathError(ctx, err)
1349 }
1350
1351 if pathtools.IsGlob(path.String()) {
1352 ReportPathErrorf(ctx, "path may not contain a glob: %s", path.String())
1353 }
1354 return path
1355}
1356
Liz Kammer7aa52882021-02-11 09:16:14 -05001357// ExistentPathForSource returns an OptionalPath with the SourcePath, rooted from SrcDir, *not*
1358// rooted from the module's local source directory, if the path exists, or an empty OptionalPath if
1359// it doesn't exist. Dependencies are added so that the ninja file will be regenerated if the state
1360// of the path changes.
Colin Cross662d6142022-11-03 20:38:01 -07001361func ExistentPathForSource(ctx PathGlobContext, pathComponents ...string) OptionalPath {
Colin Cross192e97a2018-02-22 14:21:02 -08001362 path, err := pathForSource(ctx, pathComponents...)
Colin Cross1ccfcc32018-02-22 13:54:26 -08001363 if err != nil {
1364 reportPathError(ctx, err)
Martin Stjernholmc32dd1c2021-09-15 02:39:00 +01001365 // No need to put the error message into the returned path since it has been reported already.
Colin Cross1ccfcc32018-02-22 13:54:26 -08001366 return OptionalPath{}
1367 }
Colin Crossc48c1432018-02-23 07:09:01 +00001368
Colin Crosse3924e12018-08-15 20:18:53 -07001369 if pathtools.IsGlob(path.String()) {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001370 ReportPathErrorf(ctx, "path may not contain a glob: %s", path.String())
Colin Crosse3924e12018-08-15 20:18:53 -07001371 return OptionalPath{}
1372 }
1373
Colin Cross192e97a2018-02-22 14:21:02 -08001374 exists, err := existsWithDependencies(ctx, path)
Colin Crossc48c1432018-02-23 07:09:01 +00001375 if err != nil {
1376 reportPathError(ctx, err)
1377 return OptionalPath{}
1378 }
Colin Cross192e97a2018-02-22 14:21:02 -08001379 if !exists {
Martin Stjernholmc32dd1c2021-09-15 02:39:00 +01001380 return InvalidOptionalPath(path.String() + " does not exist")
Colin Crossc48c1432018-02-23 07:09:01 +00001381 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001382 return OptionalPathForPath(path)
1383}
1384
1385func (p SourcePath) String() string {
Cole Faust483d1f72023-01-09 14:35:27 -08001386 if p.path == "" {
1387 return "."
1388 }
1389 return p.path
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001390}
1391
Colin Cross7707b242024-07-26 12:02:36 -07001392func (p SourcePath) WithoutRel() Path {
1393 p.basePath = p.basePath.withoutRel()
1394 return p
1395}
1396
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001397// Join creates a new SourcePath with paths... joined with the current path. The
1398// provided paths... may not use '..' to escape from the current path.
1399func (p SourcePath) Join(ctx PathContext, paths ...string) SourcePath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001400 path, err := validatePath(paths...)
1401 if err != nil {
1402 reportPathError(ctx, err)
1403 }
Colin Cross0db55682017-12-05 15:36:55 -08001404 return p.withRel(path)
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001405}
1406
Colin Cross2fafa3e2019-03-05 12:39:51 -08001407// join is like Join but does less path validation.
1408func (p SourcePath) join(ctx PathContext, paths ...string) SourcePath {
1409 path, err := validateSafePath(paths...)
1410 if err != nil {
1411 reportPathError(ctx, err)
1412 }
1413 return p.withRel(path)
1414}
1415
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001416// OverlayPath returns the overlay for `path' if it exists. This assumes that the
1417// SourcePath is the path to a resource overlay directory.
Liz Kammera830f3a2020-11-10 10:50:34 -08001418func (p SourcePath) OverlayPath(ctx ModuleMissingDepsPathContext, path Path) OptionalPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001419 var relDir string
Colin Cross07e51612019-03-05 12:46:40 -08001420 if srcPath, ok := path.(SourcePath); ok {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001421 relDir = srcPath.path
1422 } else {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001423 ReportPathErrorf(ctx, "Cannot find relative path for %s(%s)", reflect.TypeOf(path).Name(), path)
Martin Stjernholmc32dd1c2021-09-15 02:39:00 +01001424 // No need to put the error message into the returned path since it has been reported already.
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001425 return OptionalPath{}
1426 }
Cole Faust483d1f72023-01-09 14:35:27 -08001427 dir := filepath.Join(p.path, relDir)
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001428 // Use Glob so that we are run again if the directory is added.
Colin Cross7f19f372016-11-01 11:10:25 -07001429 if pathtools.IsGlob(dir) {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001430 ReportPathErrorf(ctx, "Path may not contain a glob: %s", dir)
Dan Willemsen7b310ee2015-12-18 15:11:17 -08001431 }
Colin Cross461b4452018-02-23 09:22:42 -08001432 paths, err := ctx.GlobWithDeps(dir, nil)
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001433 if err != nil {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001434 ReportPathErrorf(ctx, "glob: %s", err.Error())
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001435 return OptionalPath{}
1436 }
1437 if len(paths) == 0 {
Martin Stjernholmc32dd1c2021-09-15 02:39:00 +01001438 return InvalidOptionalPath(dir + " does not exist")
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001439 }
Cole Faust483d1f72023-01-09 14:35:27 -08001440 return OptionalPathForPath(PathForSource(ctx, paths[0]))
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001441}
1442
Colin Cross70dda7e2019-10-01 22:05:35 -07001443// OutputPath is a Path representing an intermediates file path rooted from the build directory
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001444type OutputPath struct {
1445 basePath
Paul Duffind65c58b2021-03-24 09:22:07 +00001446
Colin Cross3b1c6842024-07-26 11:52:57 -07001447 // The base out directory for this path, either Config.SoongOutDir() or Config.OutDir()
1448 outDir string
Paul Duffind65c58b2021-03-24 09:22:07 +00001449
Colin Crossd63c9a72020-01-29 16:52:50 -08001450 fullPath string
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001451}
1452
Yu Liu467d7c52024-09-18 21:54:44 +00001453type outputPathGob struct {
Yu Liu5246a7e2024-10-09 20:04:52 +00001454 BasePath basePath
Yu Liu467d7c52024-09-18 21:54:44 +00001455 OutDir string
1456 FullPath string
1457}
Yu Liufa297642024-06-11 00:13:02 +00001458
Yu Liu467d7c52024-09-18 21:54:44 +00001459func (p *OutputPath) ToGob() *outputPathGob {
1460 return &outputPathGob{
Yu Liu5246a7e2024-10-09 20:04:52 +00001461 BasePath: p.basePath,
Yu Liu467d7c52024-09-18 21:54:44 +00001462 OutDir: p.outDir,
1463 FullPath: p.fullPath,
1464 }
1465}
1466
1467func (p *OutputPath) FromGob(data *outputPathGob) {
Yu Liu5246a7e2024-10-09 20:04:52 +00001468 p.basePath = data.BasePath
Yu Liu467d7c52024-09-18 21:54:44 +00001469 p.outDir = data.OutDir
1470 p.fullPath = data.FullPath
1471}
1472
1473func (p OutputPath) GobEncode() ([]byte, error) {
Yu Liu3cadf7d2024-10-24 18:47:06 +00001474 return gobtools.CustomGobEncode[outputPathGob](&p)
Yu Liufa297642024-06-11 00:13:02 +00001475}
1476
1477func (p *OutputPath) GobDecode(data []byte) error {
Yu Liu3cadf7d2024-10-24 18:47:06 +00001478 return gobtools.CustomGobDecode[outputPathGob](data, p)
Yu Liufa297642024-06-11 00:13:02 +00001479}
1480
Colin Cross702e0f82017-10-18 17:27:54 -07001481func (p OutputPath) withRel(rel string) OutputPath {
Colin Cross0db55682017-12-05 15:36:55 -08001482 p.basePath = p.basePath.withRel(rel)
Colin Crossd63c9a72020-01-29 16:52:50 -08001483 p.fullPath = filepath.Join(p.fullPath, rel)
Colin Cross702e0f82017-10-18 17:27:54 -07001484 return p
1485}
1486
Colin Cross7707b242024-07-26 12:02:36 -07001487func (p OutputPath) WithoutRel() Path {
1488 p.basePath = p.basePath.withoutRel()
Colin Cross3063b782018-08-15 11:19:12 -07001489 return p
1490}
1491
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02001492func (p OutputPath) getSoongOutDir() string {
Colin Cross3b1c6842024-07-26 11:52:57 -07001493 return p.outDir
Paul Duffin9b478b02019-12-10 13:41:51 +00001494}
1495
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001496func (p OutputPath) RelativeToTop() Path {
1497 return p.outputPathRelativeToTop()
1498}
1499
1500func (p OutputPath) outputPathRelativeToTop() OutputPath {
Colin Cross3b1c6842024-07-26 11:52:57 -07001501 p.fullPath = StringPathRelativeToTop(p.outDir, p.fullPath)
1502 if strings.HasSuffix(p.outDir, testOutSoongSubDir) {
1503 p.outDir = TestOutSoongDir
1504 } else {
1505 // Handle the PathForArbitraryOutput case
1506 p.outDir = testOutDir
1507 }
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001508 return p
1509}
1510
Paul Duffin0267d492021-02-02 10:05:52 +00001511func (p OutputPath) objPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleObjPath {
1512 return PathForModuleObj(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
1513}
1514
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001515var _ Path = OutputPath{}
Paul Duffin9b478b02019-12-10 13:41:51 +00001516var _ WritablePath = OutputPath{}
Paul Duffin0267d492021-02-02 10:05:52 +00001517var _ objPathProvider = OutputPath{}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001518
Chris Parsons8f232a22020-06-23 17:37:05 -04001519// toolDepPath is a Path representing a dependency of the build tool.
1520type toolDepPath struct {
1521 basePath
1522}
1523
Colin Cross7707b242024-07-26 12:02:36 -07001524func (t toolDepPath) WithoutRel() Path {
1525 t.basePath = t.basePath.withoutRel()
1526 return t
1527}
1528
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001529func (t toolDepPath) RelativeToTop() Path {
1530 ensureTestOnly()
1531 return t
1532}
1533
Chris Parsons8f232a22020-06-23 17:37:05 -04001534var _ Path = toolDepPath{}
1535
1536// pathForBuildToolDep returns a toolDepPath representing the given path string.
1537// There is no validation for the path, as it is "trusted": It may fail
1538// normal validation checks. For example, it may be an absolute path.
1539// Only use this function to construct paths for dependencies of the build
1540// tool invocation.
1541func pathForBuildToolDep(ctx PathContext, path string) toolDepPath {
Paul Duffin74abc5d2021-03-24 09:24:59 +00001542 return toolDepPath{basePath{path, ""}}
Chris Parsons8f232a22020-06-23 17:37:05 -04001543}
1544
Jeff Gaston734e3802017-04-10 15:47:24 -07001545// PathForOutput joins the provided paths and returns an OutputPath that is
1546// validated to not escape the build dir.
1547// On error, it will return a usable, but invalid OutputPath, and report a ModuleError.
1548func PathForOutput(ctx PathContext, pathComponents ...string) OutputPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001549 path, err := validatePath(pathComponents...)
1550 if err != nil {
1551 reportPathError(ctx, err)
1552 }
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02001553 fullPath := filepath.Join(ctx.Config().soongOutDir, path)
Colin Crossd63c9a72020-01-29 16:52:50 -08001554 path = fullPath[len(fullPath)-len(path):]
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02001555 return OutputPath{basePath{path, ""}, ctx.Config().soongOutDir, fullPath}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001556}
1557
Colin Cross3b1c6842024-07-26 11:52:57 -07001558// PathsForOutput returns Paths rooted from outDir
Colin Cross40e33732019-02-15 11:08:35 -08001559func PathsForOutput(ctx PathContext, paths []string) WritablePaths {
1560 ret := make(WritablePaths, len(paths))
1561 for i, path := range paths {
1562 ret[i] = PathForOutput(ctx, path)
1563 }
1564 return ret
1565}
1566
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001567func (p OutputPath) writablePath() {}
1568
1569func (p OutputPath) String() string {
Colin Crossd63c9a72020-01-29 16:52:50 -08001570 return p.fullPath
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001571}
1572
1573// Join creates a new OutputPath with paths... joined with the current path. The
1574// provided paths... may not use '..' to escape from the current path.
1575func (p OutputPath) Join(ctx PathContext, paths ...string) OutputPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001576 path, err := validatePath(paths...)
1577 if err != nil {
1578 reportPathError(ctx, err)
1579 }
Colin Cross0db55682017-12-05 15:36:55 -08001580 return p.withRel(path)
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001581}
1582
Colin Cross8854a5a2019-02-11 14:14:16 -08001583// ReplaceExtension creates a new OutputPath with the extension replaced with ext.
1584func (p OutputPath) ReplaceExtension(ctx PathContext, ext string) OutputPath {
1585 if strings.Contains(ext, "/") {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001586 ReportPathErrorf(ctx, "extension %q cannot contain /", ext)
Colin Cross8854a5a2019-02-11 14:14:16 -08001587 }
1588 ret := PathForOutput(ctx, pathtools.ReplaceExtension(p.path, ext))
Colin Cross2cdd5df2019-02-25 10:25:24 -08001589 ret.rel = pathtools.ReplaceExtension(p.rel, ext)
Colin Cross8854a5a2019-02-11 14:14:16 -08001590 return ret
1591}
1592
Colin Cross40e33732019-02-15 11:08:35 -08001593// InSameDir creates a new OutputPath from the directory of the current OutputPath joined with the elements in paths.
1594func (p OutputPath) InSameDir(ctx PathContext, paths ...string) OutputPath {
1595 path, err := validatePath(paths...)
1596 if err != nil {
1597 reportPathError(ctx, err)
1598 }
1599
1600 ret := PathForOutput(ctx, filepath.Dir(p.path), path)
Colin Cross2cdd5df2019-02-25 10:25:24 -08001601 ret.rel = filepath.Join(filepath.Dir(p.rel), path)
Colin Cross40e33732019-02-15 11:08:35 -08001602 return ret
1603}
1604
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001605// PathForIntermediates returns an OutputPath representing the top-level
1606// intermediates directory.
1607func PathForIntermediates(ctx PathContext, paths ...string) OutputPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001608 path, err := validatePath(paths...)
1609 if err != nil {
1610 reportPathError(ctx, err)
1611 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001612 return PathForOutput(ctx, ".intermediates", path)
1613}
1614
Colin Cross07e51612019-03-05 12:46:40 -08001615var _ genPathProvider = SourcePath{}
1616var _ objPathProvider = SourcePath{}
1617var _ resPathProvider = SourcePath{}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001618
Colin Cross07e51612019-03-05 12:46:40 -08001619// PathForModuleSrc returns a Path representing the paths... under the
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001620// module's local source directory.
Liz Kammera830f3a2020-11-10 10:50:34 -08001621func PathForModuleSrc(ctx ModuleMissingDepsPathContext, pathComponents ...string) Path {
Paul Duffin407501b2021-07-09 16:56:35 +01001622 // Just join the components textually just to make sure that it does not corrupt a fully qualified
1623 // module reference, e.g. if the pathComponents is "://other:foo" then using filepath.Join() or
1624 // validatePath() will corrupt it, e.g. replace "//" with "/". If the path is not a module
1625 // reference then it will be validated by expandOneSrcPath anyway when it calls expandOneSrcPath.
1626 p := strings.Join(pathComponents, string(filepath.Separator))
Liz Kammer619be462022-01-28 15:13:39 -05001627 paths, err := expandOneSrcPath(sourcePathInput{context: ctx, path: p, includeDirs: true})
Colin Cross8a497952019-03-05 22:25:09 -08001628 if err != nil {
1629 if depErr, ok := err.(missingDependencyError); ok {
1630 if ctx.Config().AllowMissingDependencies() {
1631 ctx.AddMissingDependencies(depErr.missingDeps)
1632 } else {
1633 ctx.ModuleErrorf(`%s, is the property annotated with android:"path"?`, depErr.Error())
1634 }
1635 } else {
1636 reportPathError(ctx, err)
1637 }
1638 return nil
1639 } else if len(paths) == 0 {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001640 ReportPathErrorf(ctx, "%q produced no files, expected exactly one", p)
Colin Cross8a497952019-03-05 22:25:09 -08001641 return nil
1642 } else if len(paths) > 1 {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001643 ReportPathErrorf(ctx, "%q produced %d files, expected exactly one", p, len(paths))
Colin Cross8a497952019-03-05 22:25:09 -08001644 }
1645 return paths[0]
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001646}
1647
Liz Kammera830f3a2020-11-10 10:50:34 -08001648func pathForModuleSrc(ctx EarlyModulePathContext, paths ...string) SourcePath {
Colin Cross07e51612019-03-05 12:46:40 -08001649 p, err := validatePath(paths...)
1650 if err != nil {
1651 reportPathError(ctx, err)
1652 }
1653
1654 path, err := pathForSource(ctx, ctx.ModuleDir(), p)
1655 if err != nil {
1656 reportPathError(ctx, err)
1657 }
1658
1659 path.basePath.rel = p
1660
1661 return path
1662}
1663
Colin Cross2fafa3e2019-03-05 12:39:51 -08001664// PathsWithModuleSrcSubDir takes a list of Paths and returns a new list of Paths where Rel() on each path
1665// will return the path relative to subDir in the module's source directory. If any input paths are not located
1666// inside subDir then a path error will be reported.
Liz Kammera830f3a2020-11-10 10:50:34 -08001667func PathsWithModuleSrcSubDir(ctx EarlyModulePathContext, paths Paths, subDir string) Paths {
Colin Cross2fafa3e2019-03-05 12:39:51 -08001668 paths = append(Paths(nil), paths...)
Colin Cross07e51612019-03-05 12:46:40 -08001669 subDirFullPath := pathForModuleSrc(ctx, subDir)
Colin Cross2fafa3e2019-03-05 12:39:51 -08001670 for i, path := range paths {
1671 rel := Rel(ctx, subDirFullPath.String(), path.String())
1672 paths[i] = subDirFullPath.join(ctx, rel)
1673 }
1674 return paths
1675}
1676
1677// PathWithModuleSrcSubDir takes a Path and returns a Path where Rel() will return the path relative to subDir in the
1678// 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 -08001679func PathWithModuleSrcSubDir(ctx EarlyModulePathContext, path Path, subDir string) Path {
Colin Cross07e51612019-03-05 12:46:40 -08001680 subDirFullPath := pathForModuleSrc(ctx, subDir)
Colin Cross2fafa3e2019-03-05 12:39:51 -08001681 rel := Rel(ctx, subDirFullPath.String(), path.String())
1682 return subDirFullPath.Join(ctx, rel)
1683}
1684
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001685// OptionalPathForModuleSrc returns an OptionalPath. The OptionalPath contains a
1686// valid path if p is non-nil.
Liz Kammera830f3a2020-11-10 10:50:34 -08001687func OptionalPathForModuleSrc(ctx ModuleMissingDepsPathContext, p *string) OptionalPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001688 if p == nil {
1689 return OptionalPath{}
1690 }
1691 return OptionalPathForPath(PathForModuleSrc(ctx, *p))
1692}
1693
Liz Kammera830f3a2020-11-10 10:50:34 -08001694func (p SourcePath) genPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleGenPath {
Colin Cross7fc17db2017-02-01 14:07:55 -08001695 return PathForModuleGen(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001696}
1697
yangbill6d032dd2024-04-18 03:05:49 +00001698func (p SourcePath) genPathWithExtAndTrimExt(ctx ModuleOutPathContext, subdir, ext string, trimExt string) ModuleGenPath {
1699 // If Trim_extension being set, force append Output_extension without replace original extension.
1700 if trimExt != "" {
1701 if ext != "" {
1702 return PathForModuleGen(ctx, subdir, strings.TrimSuffix(p.path, trimExt)+"."+ext)
1703 }
1704 return PathForModuleGen(ctx, subdir, strings.TrimSuffix(p.path, trimExt))
1705 }
1706 return PathForModuleGen(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
1707}
1708
Liz Kammera830f3a2020-11-10 10:50:34 -08001709func (p SourcePath) objPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleObjPath {
Colin Cross7fc17db2017-02-01 14:07:55 -08001710 return PathForModuleObj(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001711}
1712
Liz Kammera830f3a2020-11-10 10:50:34 -08001713func (p SourcePath) resPathWithName(ctx ModuleOutPathContext, name string) ModuleResPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001714 // TODO: Use full directory if the new ctx is not the current ctx?
1715 return PathForModuleRes(ctx, p.path, name)
1716}
1717
1718// ModuleOutPath is a Path representing a module's output directory.
1719type ModuleOutPath struct {
1720 OutputPath
1721}
1722
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001723func (p ModuleOutPath) RelativeToTop() Path {
1724 p.OutputPath = p.outputPathRelativeToTop()
1725 return p
1726}
1727
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001728var _ Path = ModuleOutPath{}
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001729var _ WritablePath = ModuleOutPath{}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001730
Liz Kammera830f3a2020-11-10 10:50:34 -08001731func (p ModuleOutPath) objPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleObjPath {
Pete Bentleyfcf55bf2019-08-16 20:14:32 +01001732 return PathForModuleObj(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
1733}
1734
Liz Kammera830f3a2020-11-10 10:50:34 -08001735// ModuleOutPathContext Subset of ModuleContext functions necessary for output path methods.
1736type ModuleOutPathContext interface {
1737 PathContext
1738
1739 ModuleName() string
1740 ModuleDir() string
1741 ModuleSubDir() string
1742}
1743
1744func pathForModuleOut(ctx ModuleOutPathContext) OutputPath {
Inseob Kimb7e9f5f2024-06-25 17:39:52 +09001745 return PathForOutput(ctx, ".intermediates", ctx.ModuleDir(), ctx.ModuleName(), ctx.ModuleSubDir())
Colin Cross702e0f82017-10-18 17:27:54 -07001746}
1747
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001748// PathForModuleOut returns a Path representing the paths... under the module's
1749// output directory.
Liz Kammera830f3a2020-11-10 10:50:34 -08001750func PathForModuleOut(ctx ModuleOutPathContext, paths ...string) ModuleOutPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001751 p, err := validatePath(paths...)
1752 if err != nil {
1753 reportPathError(ctx, err)
1754 }
Colin Cross702e0f82017-10-18 17:27:54 -07001755 return ModuleOutPath{
Liz Kammera830f3a2020-11-10 10:50:34 -08001756 OutputPath: pathForModuleOut(ctx).withRel(p),
Colin Cross702e0f82017-10-18 17:27:54 -07001757 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001758}
1759
1760// ModuleGenPath is a Path representing the 'gen' directory in a module's output
1761// directory. Mainly used for generated sources.
1762type ModuleGenPath struct {
1763 ModuleOutPath
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001764}
1765
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001766func (p ModuleGenPath) RelativeToTop() Path {
1767 p.OutputPath = p.outputPathRelativeToTop()
1768 return p
1769}
1770
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001771var _ Path = ModuleGenPath{}
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001772var _ WritablePath = ModuleGenPath{}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001773var _ genPathProvider = ModuleGenPath{}
1774var _ objPathProvider = ModuleGenPath{}
1775
1776// PathForModuleGen returns a Path representing the paths... under the module's
1777// `gen' directory.
Liz Kammera830f3a2020-11-10 10:50:34 -08001778func PathForModuleGen(ctx ModuleOutPathContext, paths ...string) ModuleGenPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001779 p, err := validatePath(paths...)
1780 if err != nil {
1781 reportPathError(ctx, err)
1782 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001783 return ModuleGenPath{
Colin Cross702e0f82017-10-18 17:27:54 -07001784 ModuleOutPath: ModuleOutPath{
Liz Kammera830f3a2020-11-10 10:50:34 -08001785 OutputPath: pathForModuleOut(ctx).withRel("gen").withRel(p),
Colin Cross702e0f82017-10-18 17:27:54 -07001786 },
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001787 }
1788}
1789
Liz Kammera830f3a2020-11-10 10:50:34 -08001790func (p ModuleGenPath) genPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleGenPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001791 // TODO: make a different path for local vs remote generated files?
Dan Willemsen21ec4902016-11-02 20:43:13 -07001792 return PathForModuleGen(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001793}
1794
yangbill6d032dd2024-04-18 03:05:49 +00001795func (p ModuleGenPath) genPathWithExtAndTrimExt(ctx ModuleOutPathContext, subdir, ext string, trimExt string) ModuleGenPath {
1796 // If Trim_extension being set, force append Output_extension without replace original extension.
1797 if trimExt != "" {
1798 if ext != "" {
1799 return PathForModuleGen(ctx, subdir, strings.TrimSuffix(p.path, trimExt)+"."+ext)
1800 }
1801 return PathForModuleGen(ctx, subdir, strings.TrimSuffix(p.path, trimExt))
1802 }
1803 return PathForModuleGen(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
1804}
1805
Liz Kammera830f3a2020-11-10 10:50:34 -08001806func (p ModuleGenPath) objPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleObjPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001807 return PathForModuleObj(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
1808}
1809
1810// ModuleObjPath is a Path representing the 'obj' directory in a module's output
1811// directory. Used for compiled objects.
1812type ModuleObjPath struct {
1813 ModuleOutPath
1814}
1815
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001816func (p ModuleObjPath) RelativeToTop() Path {
1817 p.OutputPath = p.outputPathRelativeToTop()
1818 return p
1819}
1820
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001821var _ Path = ModuleObjPath{}
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001822var _ WritablePath = ModuleObjPath{}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001823
1824// PathForModuleObj returns a Path representing the paths... under the module's
1825// 'obj' directory.
Liz Kammera830f3a2020-11-10 10:50:34 -08001826func PathForModuleObj(ctx ModuleOutPathContext, pathComponents ...string) ModuleObjPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001827 p, err := validatePath(pathComponents...)
1828 if err != nil {
1829 reportPathError(ctx, err)
1830 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001831 return ModuleObjPath{PathForModuleOut(ctx, "obj", p)}
1832}
1833
1834// ModuleResPath is a a Path representing the 'res' directory in a module's
1835// output directory.
1836type ModuleResPath struct {
1837 ModuleOutPath
1838}
1839
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001840func (p ModuleResPath) RelativeToTop() Path {
1841 p.OutputPath = p.outputPathRelativeToTop()
1842 return p
1843}
1844
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001845var _ Path = ModuleResPath{}
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001846var _ WritablePath = ModuleResPath{}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001847
1848// PathForModuleRes returns a Path representing the paths... under the module's
1849// 'res' directory.
Liz Kammera830f3a2020-11-10 10:50:34 -08001850func PathForModuleRes(ctx ModuleOutPathContext, pathComponents ...string) ModuleResPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001851 p, err := validatePath(pathComponents...)
1852 if err != nil {
1853 reportPathError(ctx, err)
1854 }
1855
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001856 return ModuleResPath{PathForModuleOut(ctx, "res", p)}
1857}
1858
Colin Cross70dda7e2019-10-01 22:05:35 -07001859// InstallPath is a Path representing a installed file path rooted from the build directory
1860type InstallPath struct {
1861 basePath
Colin Crossff6c33d2019-10-02 16:01:35 -07001862
Lukacs T. Berkib078ade2021-08-31 10:42:08 +02001863 // The soong build directory, i.e. Config.SoongOutDir()
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02001864 soongOutDir string
Paul Duffind65c58b2021-03-24 09:22:07 +00001865
Jiyong Park957bcd92020-10-20 18:23:33 +09001866 // partitionDir is the part of the InstallPath that is automatically determined according to the context.
1867 // For example, it is host/<os>-<arch> for host modules, and target/product/<device>/<partition> for device modules.
1868 partitionDir string
1869
Colin Crossb1692a32021-10-25 15:39:01 -07001870 partition string
1871
Jiyong Park957bcd92020-10-20 18:23:33 +09001872 // makePath indicates whether this path is for Soong (false) or Make (true).
1873 makePath bool
Colin Crossc0e42d52024-02-01 16:42:36 -08001874
1875 fullPath string
Colin Cross70dda7e2019-10-01 22:05:35 -07001876}
1877
Yu Liu467d7c52024-09-18 21:54:44 +00001878type installPathGob struct {
Yu Liu5246a7e2024-10-09 20:04:52 +00001879 BasePath basePath
Yu Liu467d7c52024-09-18 21:54:44 +00001880 SoongOutDir string
1881 PartitionDir string
1882 Partition string
1883 MakePath bool
1884 FullPath string
1885}
Yu Liu26a716d2024-08-30 23:40:32 +00001886
Yu Liu467d7c52024-09-18 21:54:44 +00001887func (p *InstallPath) ToGob() *installPathGob {
1888 return &installPathGob{
Yu Liu5246a7e2024-10-09 20:04:52 +00001889 BasePath: p.basePath,
Yu Liu467d7c52024-09-18 21:54:44 +00001890 SoongOutDir: p.soongOutDir,
1891 PartitionDir: p.partitionDir,
1892 Partition: p.partition,
1893 MakePath: p.makePath,
1894 FullPath: p.fullPath,
1895 }
1896}
1897
1898func (p *InstallPath) FromGob(data *installPathGob) {
Yu Liu5246a7e2024-10-09 20:04:52 +00001899 p.basePath = data.BasePath
Yu Liu467d7c52024-09-18 21:54:44 +00001900 p.soongOutDir = data.SoongOutDir
1901 p.partitionDir = data.PartitionDir
1902 p.partition = data.Partition
1903 p.makePath = data.MakePath
1904 p.fullPath = data.FullPath
1905}
1906
1907func (p InstallPath) GobEncode() ([]byte, error) {
Yu Liu3cadf7d2024-10-24 18:47:06 +00001908 return gobtools.CustomGobEncode[installPathGob](&p)
Yu Liu26a716d2024-08-30 23:40:32 +00001909}
1910
1911func (p *InstallPath) GobDecode(data []byte) error {
Yu Liu3cadf7d2024-10-24 18:47:06 +00001912 return gobtools.CustomGobDecode[installPathGob](data, p)
Yu Liu26a716d2024-08-30 23:40:32 +00001913}
1914
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001915// Will panic if called from outside a test environment.
1916func ensureTestOnly() {
Martin Stjernholm32312eb2021-03-27 18:54:49 +00001917 if PrefixInList(os.Args, "-test.") {
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001918 return
1919 }
Martin Stjernholm32312eb2021-03-27 18:54:49 +00001920 panic(fmt.Errorf("Not in test. Command line:\n %s", strings.Join(os.Args, "\n ")))
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001921}
1922
1923func (p InstallPath) RelativeToTop() Path {
1924 ensureTestOnly()
Colin Crossc0e42d52024-02-01 16:42:36 -08001925 if p.makePath {
Colin Cross3b1c6842024-07-26 11:52:57 -07001926 p.soongOutDir = testOutDir
Colin Crossc0e42d52024-02-01 16:42:36 -08001927 } else {
Colin Cross3b1c6842024-07-26 11:52:57 -07001928 p.soongOutDir = TestOutSoongDir
Colin Crossc0e42d52024-02-01 16:42:36 -08001929 }
1930 p.fullPath = filepath.Join(p.soongOutDir, p.path)
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001931 return p
1932}
1933
Colin Cross7707b242024-07-26 12:02:36 -07001934func (p InstallPath) WithoutRel() Path {
1935 p.basePath = p.basePath.withoutRel()
1936 return p
1937}
1938
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02001939func (p InstallPath) getSoongOutDir() string {
1940 return p.soongOutDir
Paul Duffin9b478b02019-12-10 13:41:51 +00001941}
1942
Hans MÃ¥nssond3f2bd72020-11-27 12:37:28 +01001943func (p InstallPath) ReplaceExtension(ctx PathContext, ext string) OutputPath {
1944 panic("Not implemented")
1945}
1946
Paul Duffin9b478b02019-12-10 13:41:51 +00001947var _ Path = InstallPath{}
1948var _ WritablePath = InstallPath{}
1949
Colin Cross70dda7e2019-10-01 22:05:35 -07001950func (p InstallPath) writablePath() {}
1951
1952func (p InstallPath) String() string {
Colin Crossc0e42d52024-02-01 16:42:36 -08001953 return p.fullPath
Jiyong Park957bcd92020-10-20 18:23:33 +09001954}
1955
1956// PartitionDir returns the path to the partition where the install path is rooted at. It is
1957// out/soong/target/product/<device>/<partition> for device modules, and out/soong/host/<os>-<arch> for host modules.
1958// The ./soong is dropped if the install path is for Make.
1959func (p InstallPath) PartitionDir() string {
1960 if p.makePath {
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02001961 return filepath.Join(p.soongOutDir, "../", p.partitionDir)
Jiyong Park957bcd92020-10-20 18:23:33 +09001962 } else {
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02001963 return filepath.Join(p.soongOutDir, p.partitionDir)
Jiyong Park957bcd92020-10-20 18:23:33 +09001964 }
Colin Cross70dda7e2019-10-01 22:05:35 -07001965}
1966
Jihoon Kangf78a8902022-09-01 22:47:07 +00001967func (p InstallPath) Partition() string {
1968 return p.partition
1969}
1970
Colin Cross70dda7e2019-10-01 22:05:35 -07001971// Join creates a new InstallPath with paths... joined with the current path. The
1972// provided paths... may not use '..' to escape from the current path.
1973func (p InstallPath) Join(ctx PathContext, paths ...string) InstallPath {
1974 path, err := validatePath(paths...)
1975 if err != nil {
1976 reportPathError(ctx, err)
1977 }
1978 return p.withRel(path)
1979}
1980
1981func (p InstallPath) withRel(rel string) InstallPath {
1982 p.basePath = p.basePath.withRel(rel)
Colin Crossc0e42d52024-02-01 16:42:36 -08001983 p.fullPath = filepath.Join(p.fullPath, rel)
Colin Cross70dda7e2019-10-01 22:05:35 -07001984 return p
1985}
1986
Colin Crossc68db4b2021-11-11 18:59:15 -08001987// Deprecated: ToMakePath is a noop, PathForModuleInstall always returns Make paths when building
1988// embedded in Make.
Colin Crossff6c33d2019-10-02 16:01:35 -07001989func (p InstallPath) ToMakePath() InstallPath {
Jiyong Park957bcd92020-10-20 18:23:33 +09001990 p.makePath = true
Colin Crossff6c33d2019-10-02 16:01:35 -07001991 return p
Colin Cross70dda7e2019-10-01 22:05:35 -07001992}
1993
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001994// PathForModuleInstall returns a Path representing the install path for the
1995// module appended with paths...
Colin Cross70dda7e2019-10-01 22:05:35 -07001996func PathForModuleInstall(ctx ModuleInstallPathContext, pathComponents ...string) InstallPath {
Spandan Das5d1b9292021-06-03 19:36:41 +00001997 os, arch := osAndArch(ctx)
Cole Faust11edf552023-10-13 11:32:14 -07001998 partition := modulePartition(ctx, os.Class == Device)
Cole Faust3b703f32023-10-16 13:30:51 -07001999 return pathForInstall(ctx, os, arch, partition, pathComponents...)
Spandan Das5d1b9292021-06-03 19:36:41 +00002000}
2001
Colin Cross1d0eb7a2021-11-03 14:08:20 -07002002// PathForHostDexInstall returns an InstallPath representing the install path for the
2003// module appended with paths...
2004func PathForHostDexInstall(ctx ModuleInstallPathContext, pathComponents ...string) InstallPath {
Cole Faust3b703f32023-10-16 13:30:51 -07002005 return pathForInstall(ctx, ctx.Config().BuildOS, ctx.Config().BuildArch, "", pathComponents...)
Colin Cross1d0eb7a2021-11-03 14:08:20 -07002006}
2007
Spandan Das5d1b9292021-06-03 19:36:41 +00002008// PathForModuleInPartitionInstall is similar to PathForModuleInstall but partition is provided by the caller
2009func PathForModuleInPartitionInstall(ctx ModuleInstallPathContext, partition string, pathComponents ...string) InstallPath {
2010 os, arch := osAndArch(ctx)
Cole Faust3b703f32023-10-16 13:30:51 -07002011 return pathForInstall(ctx, os, arch, partition, pathComponents...)
Spandan Das5d1b9292021-06-03 19:36:41 +00002012}
2013
2014func osAndArch(ctx ModuleInstallPathContext) (OsType, ArchType) {
Colin Cross6e359402020-02-10 15:29:54 -08002015 os := ctx.Os()
Jiyong Park87788b52020-09-01 12:37:45 +09002016 arch := ctx.Arch().ArchType
2017 forceOS, forceArch := ctx.InstallForceOS()
2018 if forceOS != nil {
Colin Cross6e359402020-02-10 15:29:54 -08002019 os = *forceOS
2020 }
Jiyong Park87788b52020-09-01 12:37:45 +09002021 if forceArch != nil {
2022 arch = *forceArch
2023 }
Spandan Das5d1b9292021-06-03 19:36:41 +00002024 return os, arch
2025}
Colin Cross609c49a2020-02-13 13:20:11 -08002026
Colin Crossc0e42d52024-02-01 16:42:36 -08002027func pathForPartitionInstallDir(ctx PathContext, partition, partitionPath string, makePath bool) InstallPath {
2028 fullPath := ctx.Config().SoongOutDir()
2029 if makePath {
2030 // Make path starts with out/ instead of out/soong.
2031 fullPath = filepath.Join(fullPath, "../", partitionPath)
2032 } else {
2033 fullPath = filepath.Join(fullPath, partitionPath)
2034 }
2035
2036 return InstallPath{
2037 basePath: basePath{partitionPath, ""},
2038 soongOutDir: ctx.Config().soongOutDir,
2039 partitionDir: partitionPath,
2040 partition: partition,
2041 makePath: makePath,
2042 fullPath: fullPath,
2043 }
2044}
2045
Cole Faust3b703f32023-10-16 13:30:51 -07002046func pathForInstall(ctx PathContext, os OsType, arch ArchType, partition string,
Colin Cross609c49a2020-02-13 13:20:11 -08002047 pathComponents ...string) InstallPath {
2048
Jiyong Park97859152023-02-14 17:05:48 +09002049 var partitionPaths []string
Colin Cross609c49a2020-02-13 13:20:11 -08002050
Colin Cross6e359402020-02-10 15:29:54 -08002051 if os.Class == Device {
Jiyong Park97859152023-02-14 17:05:48 +09002052 partitionPaths = []string{"target", "product", ctx.Config().DeviceName(), partition}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07002053 } else {
Jiyong Park87788b52020-09-01 12:37:45 +09002054 osName := os.String()
Colin Crossa9b2aac2022-06-15 17:25:51 -07002055 if os == Linux {
Jiyong Park87788b52020-09-01 12:37:45 +09002056 // instead of linux_glibc
2057 osName = "linux"
Dan Willemsen866b5632017-09-22 12:28:24 -07002058 }
Colin Crossa9b2aac2022-06-15 17:25:51 -07002059 if os == LinuxMusl && ctx.Config().UseHostMusl() {
2060 // When using musl instead of glibc, use "linux" instead of "linux_musl". When cross
2061 // compiling we will still use "linux_musl".
2062 osName = "linux"
2063 }
2064
Jiyong Park87788b52020-09-01 12:37:45 +09002065 // SOONG_HOST_OUT is set to out/host/$(HOST_OS)-$(HOST_PREBUILT_ARCH)
2066 // and HOST_PREBUILT_ARCH is forcibly set to x86 even on x86_64 hosts. We don't seem
2067 // to have a plan to fix it (see the comment in build/make/core/envsetup.mk).
2068 // Let's keep using x86 for the existing cases until we have a need to support
2069 // other architectures.
2070 archName := arch.String()
2071 if os.Class == Host && (arch == X86_64 || arch == Common) {
2072 archName = "x86"
2073 }
Jiyong Park97859152023-02-14 17:05:48 +09002074 partitionPaths = []string{"host", osName + "-" + archName, partition}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07002075 }
Colin Cross70dda7e2019-10-01 22:05:35 -07002076
Jiyong Park97859152023-02-14 17:05:48 +09002077 partitionPath, err := validatePath(partitionPaths...)
Colin Cross70dda7e2019-10-01 22:05:35 -07002078 if err != nil {
2079 reportPathError(ctx, err)
2080 }
Colin Crossff6c33d2019-10-02 16:01:35 -07002081
Colin Crossc0e42d52024-02-01 16:42:36 -08002082 base := pathForPartitionInstallDir(ctx, partition, partitionPath, ctx.Config().KatiEnabled())
Jiyong Park957bcd92020-10-20 18:23:33 +09002083 return base.Join(ctx, pathComponents...)
Dan Willemsen34cc69e2015-09-23 15:26:20 -07002084}
2085
Spandan Dasf280b232024-04-04 21:25:51 +00002086func PathForNdkInstall(ctx PathContext, paths ...string) OutputPath {
2087 return PathForOutput(ctx, append([]string{"ndk"}, paths...)...)
Nicolas Geoffray1228e9c2020-02-27 13:45:35 +00002088}
2089
2090func PathForMainlineSdksInstall(ctx PathContext, paths ...string) InstallPath {
Spandan Dasf280b232024-04-04 21:25:51 +00002091 base := pathForPartitionInstallDir(ctx, "", "mainline-sdks", false)
2092 return base.Join(ctx, paths...)
Nicolas Geoffray1228e9c2020-02-27 13:45:35 +00002093}
2094
Weijia Heaa37c162024-11-06 19:46:03 +00002095func PathForSuiteInstall(ctx PathContext, suite string, pathComponents ...string) InstallPath {
2096 return pathForPartitionInstallDir(ctx, "test_suites", "test_suites", false).Join(ctx, suite).Join(ctx, pathComponents...)
2097}
2098
Colin Cross70dda7e2019-10-01 22:05:35 -07002099func InstallPathToOnDevicePath(ctx PathContext, path InstallPath) string {
Colin Crossb1692a32021-10-25 15:39:01 -07002100 rel := Rel(ctx, strings.TrimSuffix(path.PartitionDir(), path.partition), path.String())
Colin Cross43f08db2018-11-12 10:13:39 -08002101 return "/" + rel
2102}
2103
Cole Faust11edf552023-10-13 11:32:14 -07002104func modulePartition(ctx ModuleInstallPathContext, device bool) string {
Colin Cross43f08db2018-11-12 10:13:39 -08002105 var partition string
Colin Cross6e359402020-02-10 15:29:54 -08002106 if ctx.InstallInTestcases() {
2107 // "testcases" install directory can be used for host or device modules.
Jaewoong Jung0949f312019-09-11 10:25:18 -07002108 partition = "testcases"
Cole Faust11edf552023-10-13 11:32:14 -07002109 } else if device {
Colin Cross6e359402020-02-10 15:29:54 -08002110 if ctx.InstallInData() {
2111 partition = "data"
2112 } else if ctx.InstallInRamdisk() {
2113 if ctx.DeviceConfig().BoardUsesRecoveryAsBoot() {
2114 partition = "recovery/root/first_stage_ramdisk"
2115 } else {
2116 partition = "ramdisk"
2117 }
2118 if !ctx.InstallInRoot() {
2119 partition += "/system"
2120 }
Yifan Hong60e0cfb2020-10-21 15:17:56 -07002121 } else if ctx.InstallInVendorRamdisk() {
Yifan Hong39143a92020-10-26 12:43:12 -07002122 // The module is only available after switching root into
2123 // /first_stage_ramdisk. To expose the module before switching root
2124 // on a device without a dedicated recovery partition, install the
2125 // recovery variant.
Yifan Hongdd8dacc2020-10-21 15:40:17 -07002126 if ctx.DeviceConfig().BoardMoveRecoveryResourcesToVendorBoot() {
Petri Gyntherac229562021-03-02 23:44:02 -08002127 partition = "vendor_ramdisk/first_stage_ramdisk"
Yifan Hongdd8dacc2020-10-21 15:40:17 -07002128 } else {
Petri Gyntherac229562021-03-02 23:44:02 -08002129 partition = "vendor_ramdisk"
Yifan Hongdd8dacc2020-10-21 15:40:17 -07002130 }
2131 if !ctx.InstallInRoot() {
2132 partition += "/system"
2133 }
Inseob Kim08758f02021-04-08 21:13:22 +09002134 } else if ctx.InstallInDebugRamdisk() {
2135 partition = "debug_ramdisk"
Colin Cross6e359402020-02-10 15:29:54 -08002136 } else if ctx.InstallInRecovery() {
2137 if ctx.InstallInRoot() {
2138 partition = "recovery/root"
2139 } else {
2140 // the layout of recovery partion is the same as that of system partition
2141 partition = "recovery/root/system"
2142 }
Colin Crossea30d852023-11-29 16:00:16 -08002143 } else if ctx.SocSpecific() || ctx.InstallInVendor() {
Colin Cross6e359402020-02-10 15:29:54 -08002144 partition = ctx.DeviceConfig().VendorPath()
Colin Crossea30d852023-11-29 16:00:16 -08002145 } else if ctx.DeviceSpecific() || ctx.InstallInOdm() {
Colin Cross6e359402020-02-10 15:29:54 -08002146 partition = ctx.DeviceConfig().OdmPath()
Colin Crossea30d852023-11-29 16:00:16 -08002147 } else if ctx.ProductSpecific() || ctx.InstallInProduct() {
Colin Cross6e359402020-02-10 15:29:54 -08002148 partition = ctx.DeviceConfig().ProductPath()
2149 } else if ctx.SystemExtSpecific() {
2150 partition = ctx.DeviceConfig().SystemExtPath()
2151 } else if ctx.InstallInRoot() {
2152 partition = "root"
Spandan Das27ff7672024-11-06 19:23:57 +00002153 } else if ctx.InstallInSystemDlkm() {
2154 partition = ctx.DeviceConfig().SystemDlkmPath()
2155 } else if ctx.InstallInVendorDlkm() {
2156 partition = ctx.DeviceConfig().VendorDlkmPath()
2157 } else if ctx.InstallInOdmDlkm() {
2158 partition = ctx.DeviceConfig().OdmDlkmPath()
Yifan Hong82db7352020-01-21 16:12:26 -08002159 } else {
Colin Cross6e359402020-02-10 15:29:54 -08002160 partition = "system"
Yifan Hong82db7352020-01-21 16:12:26 -08002161 }
Colin Cross6e359402020-02-10 15:29:54 -08002162 if ctx.InstallInSanitizerDir() {
2163 partition = "data/asan/" + partition
Yifan Hong82db7352020-01-21 16:12:26 -08002164 }
Colin Cross43f08db2018-11-12 10:13:39 -08002165 }
2166 return partition
2167}
2168
Colin Cross609c49a2020-02-13 13:20:11 -08002169type InstallPaths []InstallPath
2170
2171// Paths returns the InstallPaths as a Paths
2172func (p InstallPaths) Paths() Paths {
2173 if p == nil {
2174 return nil
2175 }
2176 ret := make(Paths, len(p))
2177 for i, path := range p {
2178 ret[i] = path
2179 }
2180 return ret
2181}
2182
2183// Strings returns the string forms of the install paths.
2184func (p InstallPaths) Strings() []string {
2185 if p == nil {
2186 return nil
2187 }
2188 ret := make([]string, len(p))
2189 for i, path := range p {
2190 ret[i] = path.String()
2191 }
2192 return ret
2193}
2194
Jingwen Chen24d0c562023-02-07 09:29:36 +00002195// validatePathInternal ensures that a path does not leave its component, and
2196// optionally doesn't contain Ninja variables.
2197func validatePathInternal(allowNinjaVariables bool, pathComponents ...string) (string, error) {
Colin Crossbf9ed3f2023-10-24 14:17:03 -07002198 initialEmpty := 0
2199 finalEmpty := 0
2200 for i, path := range pathComponents {
Jingwen Chen24d0c562023-02-07 09:29:36 +00002201 if !allowNinjaVariables && strings.Contains(path, "$") {
2202 return "", fmt.Errorf("Path contains invalid character($): %s", path)
2203 }
2204
Dan Willemsen80a7c2a2015-12-21 14:57:11 -08002205 path := filepath.Clean(path)
2206 if path == ".." || strings.HasPrefix(path, "../") || strings.HasPrefix(path, "/") {
Colin Cross1ccfcc32018-02-22 13:54:26 -08002207 return "", fmt.Errorf("Path is outside directory: %s", path)
Dan Willemsen80a7c2a2015-12-21 14:57:11 -08002208 }
Colin Crossbf9ed3f2023-10-24 14:17:03 -07002209
2210 if i == initialEmpty && pathComponents[i] == "" {
2211 initialEmpty++
2212 }
2213 if i == finalEmpty && pathComponents[len(pathComponents)-1-i] == "" {
2214 finalEmpty++
2215 }
Dan Willemsen80a7c2a2015-12-21 14:57:11 -08002216 }
Colin Crossbf9ed3f2023-10-24 14:17:03 -07002217 // Optimization: filepath.Join("foo", "") returns a newly allocated copy
2218 // of "foo", while filepath.Join("foo") does not. Strip out any empty
2219 // path components.
2220 if initialEmpty == len(pathComponents) {
2221 return "", nil
2222 }
2223 nonEmptyPathComponents := pathComponents[initialEmpty : len(pathComponents)-finalEmpty]
Dan Willemsen34cc69e2015-09-23 15:26:20 -07002224 // TODO: filepath.Join isn't necessarily correct with embedded ninja
2225 // variables. '..' may remove the entire ninja variable, even if it
2226 // will be expanded to multiple nested directories.
Colin Crossbf9ed3f2023-10-24 14:17:03 -07002227 return filepath.Join(nonEmptyPathComponents...), nil
Dan Willemsen34cc69e2015-09-23 15:26:20 -07002228}
2229
Jingwen Chen24d0c562023-02-07 09:29:36 +00002230// validateSafePath validates a path that we trust (may contain ninja
2231// variables). Ensures that each path component does not attempt to leave its
2232// component. Returns a joined version of each path component.
2233func validateSafePath(pathComponents ...string) (string, error) {
2234 return validatePathInternal(true, pathComponents...)
2235}
2236
Dan Willemsen80a7c2a2015-12-21 14:57:11 -08002237// validatePath validates that a path does not include ninja variables, and that
2238// each path component does not attempt to leave its component. Returns a joined
2239// version of each path component.
Colin Cross1ccfcc32018-02-22 13:54:26 -08002240func validatePath(pathComponents ...string) (string, error) {
Jingwen Chen24d0c562023-02-07 09:29:36 +00002241 return validatePathInternal(false, pathComponents...)
Colin Cross6e18ca42015-07-14 18:55:36 -07002242}
Colin Cross5b529592017-05-09 13:34:34 -07002243
Colin Cross0875c522017-11-28 17:34:01 -08002244func PathForPhony(ctx PathContext, phony string) WritablePath {
2245 if strings.ContainsAny(phony, "$/") {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01002246 ReportPathErrorf(ctx, "Phony target contains invalid character ($ or /): %s", phony)
Colin Cross0875c522017-11-28 17:34:01 -08002247 }
Paul Duffin74abc5d2021-03-24 09:24:59 +00002248 return PhonyPath{basePath{phony, ""}}
Colin Cross0875c522017-11-28 17:34:01 -08002249}
2250
Colin Cross74e3fe42017-12-11 15:51:44 -08002251type PhonyPath struct {
2252 basePath
2253}
2254
2255func (p PhonyPath) writablePath() {}
2256
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02002257func (p PhonyPath) getSoongOutDir() string {
Paul Duffind65c58b2021-03-24 09:22:07 +00002258 // A phone path cannot contain any / so cannot be relative to the build directory.
2259 return ""
Paul Duffin9b478b02019-12-10 13:41:51 +00002260}
2261
Paul Duffin85d8f0d2021-03-24 10:18:18 +00002262func (p PhonyPath) RelativeToTop() Path {
2263 ensureTestOnly()
2264 // A phony path cannot contain any / so does not have a build directory so switching to a new
2265 // build directory has no effect so just return this path.
2266 return p
2267}
2268
Colin Cross7707b242024-07-26 12:02:36 -07002269func (p PhonyPath) WithoutRel() Path {
2270 p.basePath = p.basePath.withoutRel()
2271 return p
2272}
2273
Hans MÃ¥nssond3f2bd72020-11-27 12:37:28 +01002274func (p PhonyPath) ReplaceExtension(ctx PathContext, ext string) OutputPath {
2275 panic("Not implemented")
2276}
2277
Colin Cross74e3fe42017-12-11 15:51:44 -08002278var _ Path = PhonyPath{}
2279var _ WritablePath = PhonyPath{}
2280
Colin Cross5b529592017-05-09 13:34:34 -07002281type testPath struct {
2282 basePath
2283}
2284
Paul Duffin85d8f0d2021-03-24 10:18:18 +00002285func (p testPath) RelativeToTop() Path {
2286 ensureTestOnly()
2287 return p
2288}
2289
Colin Cross7707b242024-07-26 12:02:36 -07002290func (p testPath) WithoutRel() Path {
2291 p.basePath = p.basePath.withoutRel()
2292 return p
2293}
2294
Colin Cross5b529592017-05-09 13:34:34 -07002295func (p testPath) String() string {
2296 return p.path
2297}
2298
Paul Duffin85d8f0d2021-03-24 10:18:18 +00002299var _ Path = testPath{}
2300
Colin Cross40e33732019-02-15 11:08:35 -08002301// PathForTesting returns a Path constructed from joining the elements of paths with '/'. It should only be used from
2302// within tests.
Colin Cross5b529592017-05-09 13:34:34 -07002303func PathForTesting(paths ...string) Path {
Colin Cross1ccfcc32018-02-22 13:54:26 -08002304 p, err := validateSafePath(paths...)
2305 if err != nil {
2306 panic(err)
2307 }
Colin Cross5b529592017-05-09 13:34:34 -07002308 return testPath{basePath{path: p, rel: p}}
2309}
2310
Sam Delmerico2351eac2022-05-24 17:10:02 +00002311func PathForTestingWithRel(path, rel string) Path {
2312 p, err := validateSafePath(path, rel)
2313 if err != nil {
2314 panic(err)
2315 }
2316 r, err := validatePath(rel)
2317 if err != nil {
2318 panic(err)
2319 }
2320 return testPath{basePath{path: p, rel: r}}
2321}
2322
Colin Cross40e33732019-02-15 11:08:35 -08002323// PathsForTesting returns a Path constructed from each element in strs. It should only be used from within tests.
2324func PathsForTesting(strs ...string) Paths {
Colin Cross5b529592017-05-09 13:34:34 -07002325 p := make(Paths, len(strs))
2326 for i, s := range strs {
2327 p[i] = PathForTesting(s)
2328 }
2329
2330 return p
2331}
Colin Cross43f08db2018-11-12 10:13:39 -08002332
Colin Cross40e33732019-02-15 11:08:35 -08002333type testPathContext struct {
2334 config Config
Colin Cross40e33732019-02-15 11:08:35 -08002335}
2336
Colin Cross40e33732019-02-15 11:08:35 -08002337func (x *testPathContext) Config() Config { return x.config }
2338func (x *testPathContext) AddNinjaFileDeps(...string) {}
2339
2340// PathContextForTesting returns a PathContext that can be used in tests, for example to create an OutputPath with
2341// PathForOutput.
Colin Cross98be1bb2019-12-13 20:41:13 -08002342func PathContextForTesting(config Config) PathContext {
Colin Cross40e33732019-02-15 11:08:35 -08002343 return &testPathContext{
2344 config: config,
Colin Cross40e33732019-02-15 11:08:35 -08002345 }
2346}
2347
Ulya Trafimovichccc8c852020-10-14 11:29:07 +01002348type testModuleInstallPathContext struct {
2349 baseModuleContext
2350
2351 inData bool
2352 inTestcases bool
2353 inSanitizerDir bool
2354 inRamdisk bool
2355 inVendorRamdisk bool
Inseob Kim08758f02021-04-08 21:13:22 +09002356 inDebugRamdisk bool
Ulya Trafimovichccc8c852020-10-14 11:29:07 +01002357 inRecovery bool
2358 inRoot bool
Colin Crossea30d852023-11-29 16:00:16 -08002359 inOdm bool
2360 inProduct bool
2361 inVendor bool
Spandan Das27ff7672024-11-06 19:23:57 +00002362 inSystemDlkm bool
2363 inVendorDlkm bool
2364 inOdmDlkm bool
Ulya Trafimovichccc8c852020-10-14 11:29:07 +01002365 forceOS *OsType
2366 forceArch *ArchType
2367}
2368
2369func (m testModuleInstallPathContext) Config() Config {
2370 return m.baseModuleContext.config
2371}
2372
2373func (testModuleInstallPathContext) AddNinjaFileDeps(deps ...string) {}
2374
2375func (m testModuleInstallPathContext) InstallInData() bool {
2376 return m.inData
2377}
2378
2379func (m testModuleInstallPathContext) InstallInTestcases() bool {
2380 return m.inTestcases
2381}
2382
2383func (m testModuleInstallPathContext) InstallInSanitizerDir() bool {
2384 return m.inSanitizerDir
2385}
2386
2387func (m testModuleInstallPathContext) InstallInRamdisk() bool {
2388 return m.inRamdisk
2389}
2390
2391func (m testModuleInstallPathContext) InstallInVendorRamdisk() bool {
2392 return m.inVendorRamdisk
2393}
2394
Inseob Kim08758f02021-04-08 21:13:22 +09002395func (m testModuleInstallPathContext) InstallInDebugRamdisk() bool {
2396 return m.inDebugRamdisk
2397}
2398
Ulya Trafimovichccc8c852020-10-14 11:29:07 +01002399func (m testModuleInstallPathContext) InstallInRecovery() bool {
2400 return m.inRecovery
2401}
2402
2403func (m testModuleInstallPathContext) InstallInRoot() bool {
2404 return m.inRoot
2405}
2406
Colin Crossea30d852023-11-29 16:00:16 -08002407func (m testModuleInstallPathContext) InstallInOdm() bool {
2408 return m.inOdm
2409}
2410
2411func (m testModuleInstallPathContext) InstallInProduct() bool {
2412 return m.inProduct
2413}
2414
2415func (m testModuleInstallPathContext) InstallInVendor() bool {
2416 return m.inVendor
2417}
2418
Spandan Das27ff7672024-11-06 19:23:57 +00002419func (m testModuleInstallPathContext) InstallInSystemDlkm() bool {
2420 return m.inSystemDlkm
2421}
2422
2423func (m testModuleInstallPathContext) InstallInVendorDlkm() bool {
2424 return m.inVendorDlkm
2425}
2426
2427func (m testModuleInstallPathContext) InstallInOdmDlkm() bool {
2428 return m.inOdmDlkm
2429}
2430
Ulya Trafimovichccc8c852020-10-14 11:29:07 +01002431func (m testModuleInstallPathContext) InstallForceOS() (*OsType, *ArchType) {
2432 return m.forceOS, m.forceArch
2433}
2434
2435// Construct a minimal ModuleInstallPathContext for testing. Note that baseModuleContext is
2436// default-initialized, which leaves blueprint.baseModuleContext set to nil, so methods that are
2437// delegated to it will panic.
2438func ModuleInstallPathContextForTesting(config Config) ModuleInstallPathContext {
2439 ctx := &testModuleInstallPathContext{}
2440 ctx.config = config
2441 ctx.os = Android
2442 return ctx
2443}
2444
Colin Cross43f08db2018-11-12 10:13:39 -08002445// Rel performs the same function as filepath.Rel, but reports errors to a PathContext, and reports an error if
2446// targetPath is not inside basePath.
2447func Rel(ctx PathContext, basePath string, targetPath string) string {
2448 rel, isRel := MaybeRel(ctx, basePath, targetPath)
2449 if !isRel {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01002450 ReportPathErrorf(ctx, "path %q is not under path %q", targetPath, basePath)
Colin Cross43f08db2018-11-12 10:13:39 -08002451 return ""
2452 }
2453 return rel
2454}
2455
2456// MaybeRel performs the same function as filepath.Rel, but reports errors to a PathContext, and returns false if
2457// targetPath is not inside basePath.
2458func MaybeRel(ctx PathContext, basePath string, targetPath string) (string, bool) {
Dan Willemsen633c5022019-04-12 11:11:38 -07002459 rel, isRel, err := maybeRelErr(basePath, targetPath)
2460 if err != nil {
2461 reportPathError(ctx, err)
2462 }
2463 return rel, isRel
2464}
2465
2466func maybeRelErr(basePath string, targetPath string) (string, bool, error) {
Colin Cross43f08db2018-11-12 10:13:39 -08002467 // filepath.Rel returns an error if one path is absolute and the other is not, handle that case first.
2468 if filepath.IsAbs(basePath) != filepath.IsAbs(targetPath) {
Dan Willemsen633c5022019-04-12 11:11:38 -07002469 return "", false, nil
Colin Cross43f08db2018-11-12 10:13:39 -08002470 }
2471 rel, err := filepath.Rel(basePath, targetPath)
2472 if err != nil {
Dan Willemsen633c5022019-04-12 11:11:38 -07002473 return "", false, err
Colin Cross43f08db2018-11-12 10:13:39 -08002474 } else if rel == ".." || strings.HasPrefix(rel, "../") || strings.HasPrefix(rel, "/") {
Dan Willemsen633c5022019-04-12 11:11:38 -07002475 return "", false, nil
Colin Cross43f08db2018-11-12 10:13:39 -08002476 }
Dan Willemsen633c5022019-04-12 11:11:38 -07002477 return rel, true, nil
Colin Cross43f08db2018-11-12 10:13:39 -08002478}
Colin Cross988414c2020-01-11 01:11:46 +00002479
2480// Writes a file to the output directory. Attempting to write directly to the output directory
2481// will fail due to the sandbox of the soong_build process.
Chris Parsons1a12d032023-02-06 22:37:41 -05002482// Only writes the file if the file doesn't exist or if it has different contents, to prevent
2483// updating the timestamp if no changes would be made. (This is better for incremental
2484// performance.)
Colin Cross988414c2020-01-11 01:11:46 +00002485func WriteFileToOutputDir(path WritablePath, data []byte, perm os.FileMode) error {
Colin Crossd6421132021-11-09 12:32:34 -08002486 absPath := absolutePath(path.String())
2487 err := os.MkdirAll(filepath.Dir(absPath), 0777)
2488 if err != nil {
2489 return err
2490 }
Chris Parsons1a12d032023-02-06 22:37:41 -05002491 return pathtools.WriteFileIfChanged(absPath, data, perm)
Colin Cross988414c2020-01-11 01:11:46 +00002492}
2493
Liz Kammer2dd9ca42020-11-25 16:06:39 -08002494func RemoveAllOutputDir(path WritablePath) error {
2495 return os.RemoveAll(absolutePath(path.String()))
2496}
2497
2498func CreateOutputDirIfNonexistent(path WritablePath, perm os.FileMode) error {
2499 dir := absolutePath(path.String())
Liz Kammer09f947d2021-05-12 14:51:49 -04002500 return createDirIfNonexistent(dir, perm)
2501}
2502
2503func createDirIfNonexistent(dir string, perm os.FileMode) error {
Liz Kammer2dd9ca42020-11-25 16:06:39 -08002504 if _, err := os.Stat(dir); os.IsNotExist(err) {
2505 return os.MkdirAll(dir, os.ModePerm)
2506 } else {
2507 return err
2508 }
2509}
2510
Jingwen Chen78257e52021-05-21 02:34:24 +00002511// absolutePath is deliberately private so that Soong's Go plugins can't use it to find and
2512// read arbitrary files without going through the methods in the current package that track
2513// dependencies.
Colin Cross988414c2020-01-11 01:11:46 +00002514func absolutePath(path string) string {
2515 if filepath.IsAbs(path) {
2516 return path
2517 }
2518 return filepath.Join(absSrcDir, path)
2519}
Chris Parsons216e10a2020-07-09 17:12:52 -04002520
2521// A DataPath represents the path of a file to be used as data, for example
2522// a test library to be installed alongside a test.
2523// The data file should be installed (copied from `<SrcPath>`) to
2524// `<install_root>/<RelativeInstallPath>/<filename>`, or
2525// `<install_root>/<filename>` if RelativeInstallPath is empty.
2526type DataPath struct {
2527 // The path of the data file that should be copied into the data directory
2528 SrcPath Path
2529 // The install path of the data file, relative to the install root.
2530 RelativeInstallPath string
Colin Cross5c1d5fb2023-11-15 12:39:40 -08002531 // If WithoutRel is true, use SrcPath.Base() instead of SrcPath.Rel() as the filename.
2532 WithoutRel bool
Chris Parsons216e10a2020-07-09 17:12:52 -04002533}
Colin Crossdcf71b22021-02-01 13:59:03 -08002534
Colin Crossd442a0e2023-11-16 11:19:26 -08002535func (d *DataPath) ToRelativeInstallPath() string {
2536 relPath := d.SrcPath.Rel()
Colin Cross5c1d5fb2023-11-15 12:39:40 -08002537 if d.WithoutRel {
2538 relPath = d.SrcPath.Base()
2539 }
Colin Crossd442a0e2023-11-16 11:19:26 -08002540 if d.RelativeInstallPath != "" {
2541 relPath = filepath.Join(d.RelativeInstallPath, relPath)
2542 }
2543 return relPath
2544}
2545
Colin Crossdcf71b22021-02-01 13:59:03 -08002546// PathsIfNonNil returns a Paths containing only the non-nil input arguments.
2547func PathsIfNonNil(paths ...Path) Paths {
2548 if len(paths) == 0 {
2549 // Fast path for empty argument list
2550 return nil
2551 } else if len(paths) == 1 {
2552 // Fast path for a single argument
2553 if paths[0] != nil {
2554 return paths
2555 } else {
2556 return nil
2557 }
2558 }
2559 ret := make(Paths, 0, len(paths))
2560 for _, path := range paths {
2561 if path != nil {
2562 ret = append(ret, path)
2563 }
2564 }
2565 if len(ret) == 0 {
2566 return nil
2567 }
2568 return ret
2569}
Chris Wailesb2703ad2021-07-30 13:25:42 -07002570
2571var thirdPartyDirPrefixExceptions = []*regexp.Regexp{
2572 regexp.MustCompile("^vendor/[^/]*google[^/]*/"),
2573 regexp.MustCompile("^hardware/google/"),
2574 regexp.MustCompile("^hardware/interfaces/"),
2575 regexp.MustCompile("^hardware/libhardware[^/]*/"),
2576 regexp.MustCompile("^hardware/ril/"),
2577}
2578
2579func IsThirdPartyPath(path string) bool {
2580 thirdPartyDirPrefixes := []string{"external/", "vendor/", "hardware/"}
2581
2582 if HasAnyPrefix(path, thirdPartyDirPrefixes) {
2583 for _, prefix := range thirdPartyDirPrefixExceptions {
2584 if prefix.MatchString(path) {
2585 return false
2586 }
2587 }
2588 return true
2589 }
2590 return false
2591}
Jihoon Kangf27c3a52024-11-12 21:27:09 +00002592
2593// ToRelativeSourcePath converts absolute source path to the path relative to the source root.
2594// This throws an error if the input path is outside of the source root and cannot be converted
2595// to the relative path.
2596// This should be rarely used given that the source path is relative in Soong.
2597func ToRelativeSourcePath(ctx PathContext, path string) string {
2598 ret := path
2599 if filepath.IsAbs(path) {
2600 relPath, err := filepath.Rel(absSrcDir, path)
2601 if err != nil || strings.HasPrefix(relPath, "..") {
2602 ReportPathErrorf(ctx, "%s is outside of the source root", path)
2603 }
2604 ret = relPath
2605 }
2606 return ret
2607}