blob: 371aed86d1fd8363adb54a4bb55ebb7ea4ee4b37 [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"
27 "github.com/google/blueprint/pathtools"
Colin Cross3f40fa42015-01-30 17:27:36 -080028)
29
Colin Cross988414c2020-01-11 01:11:46 +000030var absSrcDir string
31
Dan Willemsen34cc69e2015-09-23 15:26:20 -070032// PathContext is the subset of a (Module|Singleton)Context required by the
33// Path methods.
34type PathContext interface {
Colin Crossaabf6792017-11-29 00:27:14 -080035 Config() Config
Dan Willemsen7b310ee2015-12-18 15:11:17 -080036 AddNinjaFileDeps(deps ...string)
Colin Cross3f40fa42015-01-30 17:27:36 -080037}
38
Colin Cross7f19f372016-11-01 11:10:25 -070039type PathGlobContext interface {
Colin Cross662d6142022-11-03 20:38:01 -070040 PathContext
Colin Cross7f19f372016-11-01 11:10:25 -070041 GlobWithDeps(globPattern string, excludes []string) ([]string, error)
42}
43
Colin Crossaabf6792017-11-29 00:27:14 -080044var _ PathContext = SingletonContext(nil)
45var _ PathContext = ModuleContext(nil)
Dan Willemsen34cc69e2015-09-23 15:26:20 -070046
Ulya Trafimovich8640ab92020-05-11 18:06:15 +010047// "Null" path context is a minimal path context for a given config.
48type NullPathContext struct {
49 config Config
50}
51
52func (NullPathContext) AddNinjaFileDeps(...string) {}
53func (ctx NullPathContext) Config() Config { return ctx.config }
54
Liz Kammera830f3a2020-11-10 10:50:34 -080055// EarlyModulePathContext is a subset of EarlyModuleContext methods required by the
56// Path methods. These path methods can be called before any mutators have run.
57type EarlyModulePathContext interface {
Liz Kammera830f3a2020-11-10 10:50:34 -080058 PathGlobContext
59
60 ModuleDir() string
61 ModuleErrorf(fmt string, args ...interface{})
Cole Fausta963b942024-04-11 17:43:00 -070062 OtherModulePropertyErrorf(module Module, property, fmt string, args ...interface{})
Liz Kammera830f3a2020-11-10 10:50:34 -080063}
64
65var _ EarlyModulePathContext = ModuleContext(nil)
66
67// Glob globs files and directories matching globPattern relative to ModuleDir(),
68// paths in the excludes parameter will be omitted.
69func Glob(ctx EarlyModulePathContext, globPattern string, excludes []string) Paths {
70 ret, err := ctx.GlobWithDeps(globPattern, excludes)
71 if err != nil {
72 ctx.ModuleErrorf("glob: %s", err.Error())
73 }
74 return pathsForModuleSrcFromFullPath(ctx, ret, true)
75}
76
77// GlobFiles globs *only* files (not directories) matching globPattern relative to ModuleDir().
78// Paths in the excludes parameter will be omitted.
79func GlobFiles(ctx EarlyModulePathContext, globPattern string, excludes []string) Paths {
80 ret, err := ctx.GlobWithDeps(globPattern, excludes)
81 if err != nil {
82 ctx.ModuleErrorf("glob: %s", err.Error())
83 }
84 return pathsForModuleSrcFromFullPath(ctx, ret, false)
85}
86
87// ModuleWithDepsPathContext is a subset of *ModuleContext methods required by
88// the Path methods that rely on module dependencies having been resolved.
89type ModuleWithDepsPathContext interface {
90 EarlyModulePathContext
Cole Faust55b56fe2024-08-23 12:06:11 -070091 OtherModuleProviderContext
Colin Cross648daea2024-09-12 14:35:29 -070092 VisitDirectDeps(visit func(Module))
Paul Duffin40131a32021-07-09 17:10:35 +010093 OtherModuleDependencyTag(m blueprint.Module) blueprint.DependencyTag
Cole Faust4e2bf9f2024-09-11 13:26:20 -070094 HasMutatorFinished(mutatorName string) bool
Liz Kammera830f3a2020-11-10 10:50:34 -080095}
96
97// ModuleMissingDepsPathContext is a subset of *ModuleContext methods required by
98// the Path methods that rely on module dependencies having been resolved and ability to report
99// missing dependency errors.
100type ModuleMissingDepsPathContext interface {
101 ModuleWithDepsPathContext
102 AddMissingDependencies(missingDeps []string)
103}
104
Dan Willemsen00269f22017-07-06 16:59:48 -0700105type ModuleInstallPathContext interface {
Colin Cross0ea8ba82019-06-06 14:33:29 -0700106 BaseModuleContext
Dan Willemsen00269f22017-07-06 16:59:48 -0700107
108 InstallInData() bool
Jaewoong Jung0949f312019-09-11 10:25:18 -0700109 InstallInTestcases() bool
Dan Willemsen00269f22017-07-06 16:59:48 -0700110 InstallInSanitizerDir() bool
Yifan Hong1b3348d2020-01-21 15:53:22 -0800111 InstallInRamdisk() bool
Yifan Hong60e0cfb2020-10-21 15:17:56 -0700112 InstallInVendorRamdisk() bool
Inseob Kim08758f02021-04-08 21:13:22 +0900113 InstallInDebugRamdisk() bool
Jiyong Parkf9332f12018-02-01 00:54:12 +0900114 InstallInRecovery() bool
Colin Cross90ba5f42019-10-02 11:10:58 -0700115 InstallInRoot() bool
Colin Crossea30d852023-11-29 16:00:16 -0800116 InstallInOdm() bool
117 InstallInProduct() bool
118 InstallInVendor() bool
Jiyong Park87788b52020-09-01 12:37:45 +0900119 InstallForceOS() (*OsType, *ArchType)
Dan Willemsen00269f22017-07-06 16:59:48 -0700120}
121
122var _ ModuleInstallPathContext = ModuleContext(nil)
123
Cole Faust11edf552023-10-13 11:32:14 -0700124type baseModuleContextToModuleInstallPathContext struct {
125 BaseModuleContext
126}
127
128func (ctx *baseModuleContextToModuleInstallPathContext) InstallInData() bool {
129 return ctx.Module().InstallInData()
130}
131
132func (ctx *baseModuleContextToModuleInstallPathContext) InstallInTestcases() bool {
133 return ctx.Module().InstallInTestcases()
134}
135
136func (ctx *baseModuleContextToModuleInstallPathContext) InstallInSanitizerDir() bool {
137 return ctx.Module().InstallInSanitizerDir()
138}
139
140func (ctx *baseModuleContextToModuleInstallPathContext) InstallInRamdisk() bool {
141 return ctx.Module().InstallInRamdisk()
142}
143
144func (ctx *baseModuleContextToModuleInstallPathContext) InstallInVendorRamdisk() bool {
145 return ctx.Module().InstallInVendorRamdisk()
146}
147
148func (ctx *baseModuleContextToModuleInstallPathContext) InstallInDebugRamdisk() bool {
149 return ctx.Module().InstallInDebugRamdisk()
150}
151
152func (ctx *baseModuleContextToModuleInstallPathContext) InstallInRecovery() bool {
153 return ctx.Module().InstallInRecovery()
154}
155
156func (ctx *baseModuleContextToModuleInstallPathContext) InstallInRoot() bool {
157 return ctx.Module().InstallInRoot()
158}
159
Colin Crossea30d852023-11-29 16:00:16 -0800160func (ctx *baseModuleContextToModuleInstallPathContext) InstallInOdm() bool {
161 return ctx.Module().InstallInOdm()
162}
163
164func (ctx *baseModuleContextToModuleInstallPathContext) InstallInProduct() bool {
165 return ctx.Module().InstallInProduct()
166}
167
168func (ctx *baseModuleContextToModuleInstallPathContext) InstallInVendor() bool {
169 return ctx.Module().InstallInVendor()
170}
171
Cole Faust11edf552023-10-13 11:32:14 -0700172func (ctx *baseModuleContextToModuleInstallPathContext) InstallForceOS() (*OsType, *ArchType) {
173 return ctx.Module().InstallForceOS()
174}
175
176var _ ModuleInstallPathContext = (*baseModuleContextToModuleInstallPathContext)(nil)
177
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700178// errorfContext is the interface containing the Errorf method matching the
179// Errorf method in blueprint.SingletonContext.
180type errorfContext interface {
181 Errorf(format string, args ...interface{})
Colin Cross3f40fa42015-01-30 17:27:36 -0800182}
183
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700184var _ errorfContext = blueprint.SingletonContext(nil)
185
Spandan Das59a4a2b2024-01-09 21:35:56 +0000186// ModuleErrorfContext is the interface containing the ModuleErrorf method matching
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700187// the ModuleErrorf method in blueprint.ModuleContext.
Spandan Das59a4a2b2024-01-09 21:35:56 +0000188type ModuleErrorfContext interface {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700189 ModuleErrorf(format string, args ...interface{})
Colin Cross3f40fa42015-01-30 17:27:36 -0800190}
191
Spandan Das59a4a2b2024-01-09 21:35:56 +0000192var _ ModuleErrorfContext = blueprint.ModuleContext(nil)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700193
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700194// reportPathError will register an error with the attached context. It
195// attempts ctx.ModuleErrorf for a better error message first, then falls
196// back to ctx.Errorf.
Colin Cross1ccfcc32018-02-22 13:54:26 -0800197func reportPathError(ctx PathContext, err error) {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +0100198 ReportPathErrorf(ctx, "%s", err.Error())
Colin Cross1ccfcc32018-02-22 13:54:26 -0800199}
200
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +0100201// ReportPathErrorf will register an error with the attached context. It
Colin Cross1ccfcc32018-02-22 13:54:26 -0800202// attempts ctx.ModuleErrorf for a better error message first, then falls
203// back to ctx.Errorf.
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +0100204func ReportPathErrorf(ctx PathContext, format string, args ...interface{}) {
Spandan Das59a4a2b2024-01-09 21:35:56 +0000205 if mctx, ok := ctx.(ModuleErrorfContext); ok {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700206 mctx.ModuleErrorf(format, args...)
207 } else if ectx, ok := ctx.(errorfContext); ok {
208 ectx.Errorf(format, args...)
209 } else {
210 panic(fmt.Sprintf(format, args...))
Colin Crossf2298272015-05-12 11:36:53 -0700211 }
212}
213
Colin Cross5e708052019-08-06 13:59:50 -0700214func pathContextName(ctx PathContext, module blueprint.Module) string {
215 if x, ok := ctx.(interface{ ModuleName(blueprint.Module) string }); ok {
216 return x.ModuleName(module)
217 } else if x, ok := ctx.(interface{ OtherModuleName(blueprint.Module) string }); ok {
218 return x.OtherModuleName(module)
219 }
220 return "unknown"
221}
222
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700223type Path interface {
224 // Returns the path in string form
225 String() string
226
Colin Cross4f6fc9c2016-10-26 10:05:25 -0700227 // Ext returns the extension of the last element of the path
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700228 Ext() string
Colin Cross4f6fc9c2016-10-26 10:05:25 -0700229
230 // Base returns the last element of the path
231 Base() string
Colin Crossfaeb7aa2017-02-01 14:12:44 -0800232
233 // Rel returns the portion of the path relative to the directory it was created from. For
234 // example, Rel on a PathsForModuleSrc would return the path relative to the module source
Colin Cross0db55682017-12-05 15:36:55 -0800235 // directory, and OutputPath.Join("foo").Rel() would return "foo".
Colin Crossfaeb7aa2017-02-01 14:12:44 -0800236 Rel() string
Paul Duffin85d8f0d2021-03-24 10:18:18 +0000237
Colin Cross7707b242024-07-26 12:02:36 -0700238 // WithoutRel returns a new Path with no relative path, i.e. Rel() will return the same value as Base().
239 WithoutRel() Path
240
Paul Duffin85d8f0d2021-03-24 10:18:18 +0000241 // RelativeToTop returns a new path relative to the top, it is provided solely for use in tests.
242 //
243 // It is guaranteed to always return the same type as it is called on, e.g. if called on an
244 // InstallPath then the returned value can be converted to an InstallPath.
245 //
246 // A standard build has the following structure:
247 // ../top/
248 // out/ - make install files go here.
Colin Cross3b1c6842024-07-26 11:52:57 -0700249 // out/soong - this is the outDir passed to NewTestConfig()
Paul Duffin85d8f0d2021-03-24 10:18:18 +0000250 // ... - the source files
251 //
252 // This function converts a path so that it appears relative to the ../top/ directory, i.e.
Colin Cross3b1c6842024-07-26 11:52:57 -0700253 // * Make install paths, which have the pattern "outDir/../<path>" are converted into the top
Paul Duffin85d8f0d2021-03-24 10:18:18 +0000254 // relative path "out/<path>"
Colin Cross3b1c6842024-07-26 11:52:57 -0700255 // * Soong install paths and other writable paths, which have the pattern "outDir/soong/<path>" are
Paul Duffin85d8f0d2021-03-24 10:18:18 +0000256 // converted into the top relative path "out/soong/<path>".
257 // * Source paths are already relative to the top.
258 // * Phony paths are not relative to anything.
259 // * toolDepPath have an absolute but known value in so don't need making relative to anything in
260 // order to test.
261 RelativeToTop() Path
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700262}
263
Paul Duffin85d8f0d2021-03-24 10:18:18 +0000264const (
Colin Cross3b1c6842024-07-26 11:52:57 -0700265 testOutDir = "out"
266 testOutSoongSubDir = "/soong"
267 TestOutSoongDir = testOutDir + testOutSoongSubDir
Paul Duffin85d8f0d2021-03-24 10:18:18 +0000268)
269
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700270// WritablePath is a type of path that can be used as an output for build rules.
271type WritablePath interface {
272 Path
273
Paul Duffin9b478b02019-12-10 13:41:51 +0000274 // return the path to the build directory.
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +0200275 getSoongOutDir() string
Paul Duffin9b478b02019-12-10 13:41:51 +0000276
Jeff Gaston734e3802017-04-10 15:47:24 -0700277 // the writablePath method doesn't directly do anything,
278 // but it allows a struct to distinguish between whether or not it implements the WritablePath interface
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700279 writablePath()
Hans MÃ¥nssond3f2bd72020-11-27 12:37:28 +0100280
281 ReplaceExtension(ctx PathContext, ext string) OutputPath
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700282}
283
284type genPathProvider interface {
Liz Kammera830f3a2020-11-10 10:50:34 -0800285 genPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleGenPath
yangbill6d032dd2024-04-18 03:05:49 +0000286 genPathWithExtAndTrimExt(ctx ModuleOutPathContext, subdir, ext string, trimExt string) ModuleGenPath
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700287}
288type objPathProvider interface {
Liz Kammera830f3a2020-11-10 10:50:34 -0800289 objPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleObjPath
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700290}
291type resPathProvider interface {
Liz Kammera830f3a2020-11-10 10:50:34 -0800292 resPathWithName(ctx ModuleOutPathContext, name string) ModuleResPath
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700293}
294
295// GenPathWithExt derives a new file path in ctx's generated sources directory
296// from the current path, but with the new extension.
Liz Kammera830f3a2020-11-10 10:50:34 -0800297func GenPathWithExt(ctx ModuleOutPathContext, subdir string, p Path, ext string) ModuleGenPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700298 if path, ok := p.(genPathProvider); ok {
Dan Willemsen21ec4902016-11-02 20:43:13 -0700299 return path.genPathWithExt(ctx, subdir, ext)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700300 }
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +0100301 ReportPathErrorf(ctx, "Tried to create generated file from unsupported path: %s(%s)", reflect.TypeOf(p).Name(), p)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700302 return PathForModuleGen(ctx)
303}
304
yangbill6d032dd2024-04-18 03:05:49 +0000305// GenPathWithExtAndTrimExt derives a new file path in ctx's generated sources directory
306// from the current path, but with the new extension and trim the suffix.
307func GenPathWithExtAndTrimExt(ctx ModuleOutPathContext, subdir string, p Path, ext string, trimExt string) ModuleGenPath {
308 if path, ok := p.(genPathProvider); ok {
309 return path.genPathWithExtAndTrimExt(ctx, subdir, ext, trimExt)
310 }
311 ReportPathErrorf(ctx, "Tried to create generated file from unsupported path: %s(%s)", reflect.TypeOf(p).Name(), p)
312 return PathForModuleGen(ctx)
313}
314
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700315// ObjPathWithExt derives a new file path in ctx's object directory from the
316// current path, but with the new extension.
Liz Kammera830f3a2020-11-10 10:50:34 -0800317func ObjPathWithExt(ctx ModuleOutPathContext, subdir string, p Path, ext string) ModuleObjPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700318 if path, ok := p.(objPathProvider); ok {
319 return path.objPathWithExt(ctx, subdir, ext)
320 }
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +0100321 ReportPathErrorf(ctx, "Tried to create object file from unsupported path: %s (%s)", reflect.TypeOf(p).Name(), p)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700322 return PathForModuleObj(ctx)
323}
324
325// ResPathWithName derives a new path in ctx's output resource directory, using
326// the current path to create the directory name, and the `name` argument for
327// the filename.
Liz Kammera830f3a2020-11-10 10:50:34 -0800328func ResPathWithName(ctx ModuleOutPathContext, p Path, name string) ModuleResPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700329 if path, ok := p.(resPathProvider); ok {
330 return path.resPathWithName(ctx, name)
331 }
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +0100332 ReportPathErrorf(ctx, "Tried to create res file from unsupported path: %s (%s)", reflect.TypeOf(p).Name(), p)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700333 return PathForModuleRes(ctx)
334}
335
336// OptionalPath is a container that may or may not contain a valid Path.
337type OptionalPath struct {
Martin Stjernholmc32dd1c2021-09-15 02:39:00 +0100338 path Path // nil if invalid.
339 invalidReason string // Not applicable if path != nil. "" if the reason is unknown.
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700340}
341
Yu Liu467d7c52024-09-18 21:54:44 +0000342type optionalPathGob struct {
343 Path Path
344 InvalidReason string
345}
346
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700347// OptionalPathForPath returns an OptionalPath containing the path.
348func OptionalPathForPath(path Path) OptionalPath {
Martin Stjernholm2fee27f2021-09-16 14:11:12 +0100349 return OptionalPath{path: path}
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700350}
351
Martin Stjernholmc32dd1c2021-09-15 02:39:00 +0100352// InvalidOptionalPath returns an OptionalPath that is invalid with the given reason.
353func InvalidOptionalPath(reason string) OptionalPath {
354
355 return OptionalPath{invalidReason: reason}
356}
357
Yu Liu467d7c52024-09-18 21:54:44 +0000358func (p *OptionalPath) ToGob() *optionalPathGob {
359 return &optionalPathGob{
360 Path: p.path,
361 InvalidReason: p.invalidReason,
362 }
363}
364
365func (p *OptionalPath) FromGob(data *optionalPathGob) {
366 p.path = data.Path
367 p.invalidReason = data.InvalidReason
368}
369
370func (p OptionalPath) GobEncode() ([]byte, error) {
371 return blueprint.CustomGobEncode[optionalPathGob](&p)
372}
373
374func (p *OptionalPath) GobDecode(data []byte) error {
375 return blueprint.CustomGobDecode[optionalPathGob](data, p)
376}
377
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700378// Valid returns whether there is a valid path
379func (p OptionalPath) Valid() bool {
Martin Stjernholm2fee27f2021-09-16 14:11:12 +0100380 return p.path != nil
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700381}
382
383// Path returns the Path embedded in this OptionalPath. You must be sure that
384// there is a valid path, since this method will panic if there is not.
385func (p OptionalPath) Path() Path {
Martin Stjernholm2fee27f2021-09-16 14:11:12 +0100386 if p.path == nil {
Martin Stjernholmc32dd1c2021-09-15 02:39:00 +0100387 msg := "Requesting an invalid path"
388 if p.invalidReason != "" {
389 msg += ": " + p.invalidReason
390 }
391 panic(msg)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700392 }
393 return p.path
394}
395
Martin Stjernholmc32dd1c2021-09-15 02:39:00 +0100396// InvalidReason returns the reason that the optional path is invalid, or "" if it is valid.
397func (p OptionalPath) InvalidReason() string {
398 if p.path != nil {
399 return ""
400 }
401 if p.invalidReason == "" {
402 return "unknown"
403 }
404 return p.invalidReason
405}
406
Paul Duffinef081852021-05-13 11:11:15 +0100407// AsPaths converts the OptionalPath into Paths.
408//
409// It returns nil if this is not valid, or a single length slice containing the Path embedded in
410// this OptionalPath.
411func (p OptionalPath) AsPaths() Paths {
Martin Stjernholm2fee27f2021-09-16 14:11:12 +0100412 if p.path == nil {
Paul Duffinef081852021-05-13 11:11:15 +0100413 return nil
414 }
415 return Paths{p.path}
416}
417
Paul Duffinafdd4062021-03-30 19:44:07 +0100418// RelativeToTop returns an OptionalPath with the path that was embedded having been replaced by the
419// result of calling Path.RelativeToTop on it.
420func (p OptionalPath) RelativeToTop() OptionalPath {
Martin Stjernholm2fee27f2021-09-16 14:11:12 +0100421 if p.path == nil {
Paul Duffina5b81352021-03-28 23:57:19 +0100422 return p
423 }
424 p.path = p.path.RelativeToTop()
425 return p
426}
427
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700428// String returns the string version of the Path, or "" if it isn't valid.
429func (p OptionalPath) String() string {
Martin Stjernholm2fee27f2021-09-16 14:11:12 +0100430 if p.path != nil {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700431 return p.path.String()
432 } else {
433 return ""
Colin Crossf2298272015-05-12 11:36:53 -0700434 }
435}
Colin Cross6e18ca42015-07-14 18:55:36 -0700436
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700437// Paths is a slice of Path objects, with helpers to operate on the collection.
438type Paths []Path
439
Paul Duffin85d8f0d2021-03-24 10:18:18 +0000440// RelativeToTop creates a new Paths containing the result of calling Path.RelativeToTop on each
441// item in this slice.
442func (p Paths) RelativeToTop() Paths {
443 ensureTestOnly()
444 if p == nil {
445 return p
446 }
447 ret := make(Paths, len(p))
448 for i, path := range p {
449 ret[i] = path.RelativeToTop()
450 }
451 return ret
452}
453
Jingwen Chen40fd90a2020-06-15 05:24:19 +0000454func (paths Paths) containsPath(path Path) bool {
455 for _, p := range paths {
456 if p == path {
457 return true
458 }
459 }
460 return false
461}
462
Liz Kammer7aa52882021-02-11 09:16:14 -0500463// PathsForSource returns Paths rooted from SrcDir, *not* rooted from the module's local source
464// directory
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700465func PathsForSource(ctx PathContext, paths []string) Paths {
466 ret := make(Paths, len(paths))
467 for i, path := range paths {
468 ret[i] = PathForSource(ctx, path)
469 }
470 return ret
471}
472
Liz Kammer7aa52882021-02-11 09:16:14 -0500473// ExistentPathsForSources returns a list of Paths rooted from SrcDir, *not* rooted from the
474// module's local source directory, that are found in the tree. If any are not found, they are
475// 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 -0700476func ExistentPathsForSources(ctx PathGlobContext, paths []string) Paths {
Dan Willemsen7b310ee2015-12-18 15:11:17 -0800477 ret := make(Paths, 0, len(paths))
478 for _, path := range paths {
Colin Cross32f38982018-02-22 11:47:25 -0800479 p := ExistentPathForSource(ctx, path)
Dan Willemsen7b310ee2015-12-18 15:11:17 -0800480 if p.Valid() {
481 ret = append(ret, p.Path())
482 }
483 }
484 return ret
485}
486
Liz Kammer620dea62021-04-14 17:36:10 -0400487// PathsForModuleSrc returns a Paths{} containing the resolved references in paths:
Colin Crossd079e0b2022-08-16 10:27:33 -0700488// - filepath, relative to local module directory, resolves as a filepath relative to the local
489// source directory
490// - glob, relative to the local module directory, resolves as filepath(s), relative to the local
491// source directory.
492// - other modules using the ":name{.tag}" syntax. These modules must implement SourceFileProducer
mrziwangd38e63d2024-07-15 13:43:37 -0700493// or set the OutputFilesProvider. These resolve as a filepath to an output filepath or generated
494// source filepath.
Colin Crossd079e0b2022-08-16 10:27:33 -0700495//
Liz Kammer620dea62021-04-14 17:36:10 -0400496// Properties passed as the paths argument must have been annotated with struct tag
Colin Cross41955e82019-05-29 14:40:35 -0700497// `android:"path"` so that dependencies on SourceFileProducer modules will have already been handled by the
Spandan Das950091c2023-07-19 22:26:37 +0000498// pathdeps mutator.
Liz Kammer620dea62021-04-14 17:36:10 -0400499// If a requested module is not found as a dependency:
Colin Crossd079e0b2022-08-16 10:27:33 -0700500// - if ctx.Config().AllowMissingDependencies() is true, this module to be marked as having
Liz Kammer620dea62021-04-14 17:36:10 -0400501// missing dependencies
Colin Crossd079e0b2022-08-16 10:27:33 -0700502// - otherwise, a ModuleError is thrown.
Liz Kammera830f3a2020-11-10 10:50:34 -0800503func PathsForModuleSrc(ctx ModuleMissingDepsPathContext, paths []string) Paths {
Colin Cross8a497952019-03-05 22:25:09 -0800504 return PathsForModuleSrcExcludes(ctx, paths, nil)
505}
506
Liz Kammer619be462022-01-28 15:13:39 -0500507type SourceInput struct {
508 Context ModuleMissingDepsPathContext
509 Paths []string
510 ExcludePaths []string
511 IncludeDirs bool
512}
513
Liz Kammer620dea62021-04-14 17:36:10 -0400514// PathsForModuleSrcExcludes returns a Paths{} containing the resolved references in paths, minus
515// those listed in excludes. Elements of paths and excludes are resolved as:
Colin Crossd079e0b2022-08-16 10:27:33 -0700516// - filepath, relative to local module directory, resolves as a filepath relative to the local
517// source directory
518// - glob, relative to the local module directory, resolves as filepath(s), relative to the local
519// source directory. Not valid in excludes.
520// - other modules using the ":name{.tag}" syntax. These modules must implement SourceFileProducer
mrziwangd38e63d2024-07-15 13:43:37 -0700521// or set the OutputFilesProvider. These resolve as a filepath to an output filepath or generated
522// source filepath.
Colin Crossd079e0b2022-08-16 10:27:33 -0700523//
Liz Kammer620dea62021-04-14 17:36:10 -0400524// excluding the items (similarly resolved
525// Properties passed as the paths argument must have been annotated with struct tag
526// `android:"path"` so that dependencies on SourceFileProducer modules will have already been handled by the
Spandan Das950091c2023-07-19 22:26:37 +0000527// pathdeps mutator.
Liz Kammer620dea62021-04-14 17:36:10 -0400528// If a requested module is not found as a dependency:
Colin Crossd079e0b2022-08-16 10:27:33 -0700529// - if ctx.Config().AllowMissingDependencies() is true, this module to be marked as having
Liz Kammer620dea62021-04-14 17:36:10 -0400530// missing dependencies
Colin Crossd079e0b2022-08-16 10:27:33 -0700531// - otherwise, a ModuleError is thrown.
Liz Kammera830f3a2020-11-10 10:50:34 -0800532func PathsForModuleSrcExcludes(ctx ModuleMissingDepsPathContext, paths, excludes []string) Paths {
Liz Kammer619be462022-01-28 15:13:39 -0500533 return PathsRelativeToModuleSourceDir(SourceInput{
534 Context: ctx,
535 Paths: paths,
536 ExcludePaths: excludes,
537 IncludeDirs: true,
538 })
539}
540
541func PathsRelativeToModuleSourceDir(input SourceInput) Paths {
542 ret, missingDeps := PathsAndMissingDepsRelativeToModuleSourceDir(input)
543 if input.Context.Config().AllowMissingDependencies() {
544 input.Context.AddMissingDependencies(missingDeps)
Colin Crossba71a3f2019-03-18 12:12:48 -0700545 } else {
546 for _, m := range missingDeps {
Liz Kammer619be462022-01-28 15:13:39 -0500547 input.Context.ModuleErrorf(`missing dependency on %q, is the property annotated with android:"path"?`, m)
Colin Crossba71a3f2019-03-18 12:12:48 -0700548 }
549 }
550 return ret
551}
552
Inseob Kim76e19852024-10-10 17:57:22 +0900553// DirectoryPathsForModuleSrcExcludes returns a Paths{} containing the resolved references in
554// directory paths. Elements of paths are resolved as:
555// - filepath, relative to local module directory, resolves as a filepath relative to the local
556// source directory
557// - other modules using the ":name" syntax. These modules must implement DirProvider.
558//
559// TODO(b/358302178): Implement DirectoryPath and change the return type.
560func DirectoryPathsForModuleSrc(ctx ModuleMissingDepsPathContext, paths []string) Paths {
561 var ret Paths
562
563 for _, path := range paths {
564 if m, t := SrcIsModuleWithTag(path); m != "" {
565 module := GetModuleFromPathDep(ctx, m, t)
566 if module == nil {
567 ctx.ModuleErrorf(`missing dependency on %q, is the property annotated with android:"path"?`, m)
568 continue
569 }
570 if t != "" {
571 ctx.ModuleErrorf("DirProvider dependency %q does not support the tag %q", module, t)
572 continue
573 }
574 mctx, ok := ctx.(OtherModuleProviderContext)
575 if !ok {
576 panic(fmt.Errorf("%s is not an OtherModuleProviderContext", ctx))
577 }
578 if dirProvider, ok := OtherModuleProvider(mctx, module, DirProvider); ok {
579 ret = append(ret, dirProvider.Dirs...)
580 } else {
581 ReportPathErrorf(ctx, "module %q does not implement DirProvider", module)
582 }
583 } else {
584 p := pathForModuleSrc(ctx, path)
585 if isDir, err := ctx.Config().fs.IsDir(p.String()); err != nil {
586 ReportPathErrorf(ctx, "%s: %s", p, err.Error())
587 } else if !isDir {
588 ReportPathErrorf(ctx, "module directory path %q is not a directory", p)
589 } else {
590 ret = append(ret, p)
591 }
592 }
593 }
594
595 seen := make(map[Path]bool, len(ret))
596 for _, path := range ret {
597 if seen[path] {
598 ReportPathErrorf(ctx, "duplicated path %q", path)
599 }
600 seen[path] = true
601 }
602 return ret
603}
604
Ulya Trafimovich4d2eeed2019-11-08 10:54:21 +0000605// OutputPaths is a slice of OutputPath objects, with helpers to operate on the collection.
606type OutputPaths []OutputPath
607
608// Paths returns the OutputPaths as a Paths
609func (p OutputPaths) Paths() Paths {
610 if p == nil {
611 return nil
612 }
613 ret := make(Paths, len(p))
614 for i, path := range p {
615 ret[i] = path
616 }
617 return ret
618}
619
620// Strings returns the string forms of the writable paths.
621func (p OutputPaths) Strings() []string {
622 if p == nil {
623 return nil
624 }
625 ret := make([]string, len(p))
626 for i, path := range p {
627 ret[i] = path.String()
628 }
629 return ret
630}
631
Liz Kammera830f3a2020-11-10 10:50:34 -0800632// Expands Paths to a SourceFileProducer or OutputFileProducer module dependency referenced via ":name" or ":name{.tag}" syntax.
633// If the dependency is not found, a missingErrorDependency is returned.
634// If the module dependency is not a SourceFileProducer or OutputFileProducer, appropriate errors will be returned.
635func getPathsFromModuleDep(ctx ModuleWithDepsPathContext, path, moduleName, tag string) (Paths, error) {
Paul Duffind5cf92e2021-07-09 17:38:55 +0100636 module := GetModuleFromPathDep(ctx, moduleName, tag)
Liz Kammera830f3a2020-11-10 10:50:34 -0800637 if module == nil {
638 return nil, missingDependencyError{[]string{moduleName}}
639 }
Cole Fausta963b942024-04-11 17:43:00 -0700640 if aModule, ok := module.(Module); ok && !aModule.Enabled(ctx) {
Colin Crossfa65cee2021-03-22 17:05:59 -0700641 return nil, missingDependencyError{[]string{moduleName}}
642 }
mrziwange6c85812024-05-22 14:36:09 -0700643 outputFiles, err := outputFilesForModule(ctx, module, tag)
644 if outputFiles != nil && err == nil {
645 return outputFiles, nil
Liz Kammera830f3a2020-11-10 10:50:34 -0800646 } else {
mrziwange6c85812024-05-22 14:36:09 -0700647 return nil, err
Liz Kammera830f3a2020-11-10 10:50:34 -0800648 }
649}
650
Paul Duffind5cf92e2021-07-09 17:38:55 +0100651// GetModuleFromPathDep will return the module that was added as a dependency automatically for
652// properties tagged with `android:"path"` or manually using ExtractSourceDeps or
653// ExtractSourcesDeps.
654//
655// The moduleName and tag supplied to this should be the values returned from SrcIsModuleWithTag.
656// Or, if no tag is expected then the moduleName should be the value returned by SrcIsModule and
657// the tag must be "".
658//
659// If tag is "" then the returned module will be the dependency that was added for ":moduleName".
660// Otherwise, it is the dependency that was added for ":moduleName{tag}".
Paul Duffind5cf92e2021-07-09 17:38:55 +0100661func GetModuleFromPathDep(ctx ModuleWithDepsPathContext, moduleName, tag string) blueprint.Module {
Paul Duffin40131a32021-07-09 17:10:35 +0100662 var found blueprint.Module
663 // The sourceOrOutputDepTag uniquely identifies the module dependency as it contains both the
664 // module name and the tag. Dependencies added automatically for properties tagged with
665 // `android:"path"` are deduped so are guaranteed to be unique. It is possible for duplicate
666 // dependencies to be added manually using ExtractSourcesDeps or ExtractSourceDeps but even then
667 // it will always be the case that the dependencies will be identical, i.e. the same tag and same
668 // moduleName referring to the same dependency module.
669 //
670 // It does not matter whether the moduleName is a fully qualified name or if the module
671 // dependency is a prebuilt module. All that matters is the same information is supplied to
672 // create the tag here as was supplied to create the tag when the dependency was added so that
673 // this finds the matching dependency module.
674 expectedTag := sourceOrOutputDepTag(moduleName, tag)
Colin Cross648daea2024-09-12 14:35:29 -0700675 ctx.VisitDirectDeps(func(module Module) {
Paul Duffin40131a32021-07-09 17:10:35 +0100676 depTag := ctx.OtherModuleDependencyTag(module)
677 if depTag == expectedTag {
678 found = module
679 }
680 })
681 return found
Paul Duffind5cf92e2021-07-09 17:38:55 +0100682}
683
Liz Kammer620dea62021-04-14 17:36:10 -0400684// PathsAndMissingDepsForModuleSrcExcludes returns a Paths{} containing the resolved references in
685// paths, minus those listed in excludes. Elements of paths and excludes are resolved as:
Colin Crossd079e0b2022-08-16 10:27:33 -0700686// - filepath, relative to local module directory, resolves as a filepath relative to the local
687// source directory
688// - glob, relative to the local module directory, resolves as filepath(s), relative to the local
689// source directory. Not valid in excludes.
690// - other modules using the ":name{.tag}" syntax. These modules must implement SourceFileProducer
mrziwangd38e63d2024-07-15 13:43:37 -0700691// or set the OutputFilesProvider. These resolve as a filepath to an output filepath or generated
692// source filepath.
Colin Crossd079e0b2022-08-16 10:27:33 -0700693//
Liz Kammer620dea62021-04-14 17:36:10 -0400694// and a list of the module names of missing module dependencies are returned as the second return.
695// Properties passed as the paths argument must have been annotated with struct tag
Colin Cross41955e82019-05-29 14:40:35 -0700696// `android:"path"` so that dependencies on SourceFileProducer modules will have already been handled by the
Spandan Das950091c2023-07-19 22:26:37 +0000697// pathdeps mutator.
Liz Kammer619be462022-01-28 15:13:39 -0500698func PathsAndMissingDepsForModuleSrcExcludes(ctx ModuleMissingDepsPathContext, paths, excludes []string) (Paths, []string) {
699 return PathsAndMissingDepsRelativeToModuleSourceDir(SourceInput{
700 Context: ctx,
701 Paths: paths,
702 ExcludePaths: excludes,
703 IncludeDirs: true,
704 })
705}
706
707func PathsAndMissingDepsRelativeToModuleSourceDir(input SourceInput) (Paths, []string) {
708 prefix := pathForModuleSrc(input.Context).String()
Colin Cross8a497952019-03-05 22:25:09 -0800709
710 var expandedExcludes []string
Liz Kammer619be462022-01-28 15:13:39 -0500711 if input.ExcludePaths != nil {
712 expandedExcludes = make([]string, 0, len(input.ExcludePaths))
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700713 }
Colin Cross8a497952019-03-05 22:25:09 -0800714
Colin Crossba71a3f2019-03-18 12:12:48 -0700715 var missingExcludeDeps []string
Liz Kammer619be462022-01-28 15:13:39 -0500716 for _, e := range input.ExcludePaths {
Colin Cross41955e82019-05-29 14:40:35 -0700717 if m, t := SrcIsModuleWithTag(e); m != "" {
Liz Kammer619be462022-01-28 15:13:39 -0500718 modulePaths, err := getPathsFromModuleDep(input.Context, e, m, t)
Liz Kammera830f3a2020-11-10 10:50:34 -0800719 if m, ok := err.(missingDependencyError); ok {
720 missingExcludeDeps = append(missingExcludeDeps, m.missingDeps...)
721 } else if err != nil {
Liz Kammer619be462022-01-28 15:13:39 -0500722 reportPathError(input.Context, err)
Colin Cross8a497952019-03-05 22:25:09 -0800723 } else {
Liz Kammera830f3a2020-11-10 10:50:34 -0800724 expandedExcludes = append(expandedExcludes, modulePaths.Strings()...)
Colin Cross8a497952019-03-05 22:25:09 -0800725 }
726 } else {
727 expandedExcludes = append(expandedExcludes, filepath.Join(prefix, e))
728 }
729 }
730
Liz Kammer619be462022-01-28 15:13:39 -0500731 if input.Paths == nil {
Colin Crossba71a3f2019-03-18 12:12:48 -0700732 return nil, missingExcludeDeps
Colin Cross8a497952019-03-05 22:25:09 -0800733 }
734
Colin Crossba71a3f2019-03-18 12:12:48 -0700735 var missingDeps []string
736
Liz Kammer619be462022-01-28 15:13:39 -0500737 expandedSrcFiles := make(Paths, 0, len(input.Paths))
738 for _, s := range input.Paths {
739 srcFiles, err := expandOneSrcPath(sourcePathInput{
740 context: input.Context,
741 path: s,
742 expandedExcludes: expandedExcludes,
743 includeDirs: input.IncludeDirs,
744 })
Colin Cross8a497952019-03-05 22:25:09 -0800745 if depErr, ok := err.(missingDependencyError); ok {
Colin Crossba71a3f2019-03-18 12:12:48 -0700746 missingDeps = append(missingDeps, depErr.missingDeps...)
Colin Cross8a497952019-03-05 22:25:09 -0800747 } else if err != nil {
Liz Kammer619be462022-01-28 15:13:39 -0500748 reportPathError(input.Context, err)
Colin Cross8a497952019-03-05 22:25:09 -0800749 }
750 expandedSrcFiles = append(expandedSrcFiles, srcFiles...)
751 }
Colin Crossba71a3f2019-03-18 12:12:48 -0700752
Jihoon Kang0e3a5352024-04-12 00:45:50 +0000753 // TODO: b/334169722 - Replace with an error instead of implicitly removing duplicates.
754 return FirstUniquePaths(expandedSrcFiles), append(missingDeps, missingExcludeDeps...)
Colin Cross8a497952019-03-05 22:25:09 -0800755}
756
757type missingDependencyError struct {
758 missingDeps []string
759}
760
761func (e missingDependencyError) Error() string {
762 return "missing dependencies: " + strings.Join(e.missingDeps, ", ")
763}
764
Liz Kammer619be462022-01-28 15:13:39 -0500765type sourcePathInput struct {
766 context ModuleWithDepsPathContext
767 path string
768 expandedExcludes []string
769 includeDirs bool
770}
771
Liz Kammera830f3a2020-11-10 10:50:34 -0800772// Expands one path string to Paths rooted from the module's local source
773// directory, excluding those listed in the expandedExcludes.
774// Expands globs, references to SourceFileProducer or OutputFileProducer modules using the ":name" and ":name{.tag}" syntax.
Liz Kammer619be462022-01-28 15:13:39 -0500775func expandOneSrcPath(input sourcePathInput) (Paths, error) {
Jooyung Han7607dd32020-07-05 10:23:14 +0900776 excludePaths := func(paths Paths) Paths {
Liz Kammer619be462022-01-28 15:13:39 -0500777 if len(input.expandedExcludes) == 0 {
Jooyung Han7607dd32020-07-05 10:23:14 +0900778 return paths
779 }
780 remainder := make(Paths, 0, len(paths))
781 for _, p := range paths {
Liz Kammer619be462022-01-28 15:13:39 -0500782 if !InList(p.String(), input.expandedExcludes) {
Jooyung Han7607dd32020-07-05 10:23:14 +0900783 remainder = append(remainder, p)
784 }
785 }
786 return remainder
787 }
Liz Kammer619be462022-01-28 15:13:39 -0500788 if m, t := SrcIsModuleWithTag(input.path); m != "" {
789 modulePaths, err := getPathsFromModuleDep(input.context, input.path, m, t)
Liz Kammera830f3a2020-11-10 10:50:34 -0800790 if err != nil {
791 return nil, err
Colin Cross8a497952019-03-05 22:25:09 -0800792 } else {
Liz Kammera830f3a2020-11-10 10:50:34 -0800793 return excludePaths(modulePaths), nil
Colin Cross8a497952019-03-05 22:25:09 -0800794 }
Colin Cross8a497952019-03-05 22:25:09 -0800795 } else {
Liz Kammer619be462022-01-28 15:13:39 -0500796 p := pathForModuleSrc(input.context, input.path)
797 if pathtools.IsGlob(input.path) {
798 paths := GlobFiles(input.context, p.String(), input.expandedExcludes)
799 return PathsWithModuleSrcSubDir(input.context, paths, ""), nil
800 } else {
801 if exists, _, err := input.context.Config().fs.Exists(p.String()); err != nil {
802 ReportPathErrorf(input.context, "%s: %s", p, err.Error())
803 } else if !exists && !input.context.Config().TestAllowNonExistentPaths {
804 ReportPathErrorf(input.context, "module source path %q does not exist", p)
805 } else if !input.includeDirs {
806 if isDir, err := input.context.Config().fs.IsDir(p.String()); exists && err != nil {
807 ReportPathErrorf(input.context, "%s: %s", p, err.Error())
808 } else if isDir {
809 ReportPathErrorf(input.context, "module source path %q is a directory", p)
810 }
811 }
Colin Cross8a497952019-03-05 22:25:09 -0800812
Liz Kammer619be462022-01-28 15:13:39 -0500813 if InList(p.String(), input.expandedExcludes) {
814 return nil, nil
815 }
816 return Paths{p}, nil
Colin Cross8a497952019-03-05 22:25:09 -0800817 }
Colin Cross8a497952019-03-05 22:25:09 -0800818 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700819}
820
821// pathsForModuleSrcFromFullPath returns Paths rooted from the module's local
822// source directory, but strip the local source directory from the beginning of
Dan Willemsen540a78c2018-02-26 21:50:08 -0800823// each string. If incDirs is false, strip paths with a trailing '/' from the list.
Colin Crossfe4bc362018-09-12 10:02:13 -0700824// It intended for use in globs that only list files that exist, so it allows '$' in
825// filenames.
Liz Kammera830f3a2020-11-10 10:50:34 -0800826func pathsForModuleSrcFromFullPath(ctx EarlyModulePathContext, paths []string, incDirs bool) Paths {
Lukacs T. Berkif7e36d82021-08-16 17:05:09 +0200827 prefix := ctx.ModuleDir() + "/"
Colin Cross0f37af02017-09-27 17:42:05 -0700828 if prefix == "./" {
829 prefix = ""
830 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700831 ret := make(Paths, 0, len(paths))
832 for _, p := range paths {
Dan Willemsen540a78c2018-02-26 21:50:08 -0800833 if !incDirs && strings.HasSuffix(p, "/") {
834 continue
835 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700836 path := filepath.Clean(p)
837 if !strings.HasPrefix(path, prefix) {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +0100838 ReportPathErrorf(ctx, "Path %q is not in module source directory %q", p, prefix)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700839 continue
840 }
Colin Crosse3924e12018-08-15 20:18:53 -0700841
Colin Crossfe4bc362018-09-12 10:02:13 -0700842 srcPath, err := safePathForSource(ctx, ctx.ModuleDir(), path[len(prefix):])
Colin Crosse3924e12018-08-15 20:18:53 -0700843 if err != nil {
844 reportPathError(ctx, err)
845 continue
846 }
847
Colin Cross07e51612019-03-05 12:46:40 -0800848 srcPath.basePath.rel = srcPath.path
Colin Crosse3924e12018-08-15 20:18:53 -0700849
Colin Cross07e51612019-03-05 12:46:40 -0800850 ret = append(ret, srcPath)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700851 }
852 return ret
853}
854
Liz Kammera830f3a2020-11-10 10:50:34 -0800855// PathsWithOptionalDefaultForModuleSrc returns Paths rooted from the module's local source
856// directory. If input is nil, use the default if it exists. If input is empty, returns nil.
857func PathsWithOptionalDefaultForModuleSrc(ctx ModuleMissingDepsPathContext, input []string, def string) Paths {
Colin Cross0ddae7f2019-02-07 15:30:01 -0800858 if input != nil {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700859 return PathsForModuleSrc(ctx, input)
860 }
861 // Use Glob so that if the default doesn't exist, a dependency is added so that when it
862 // is created, we're run again.
Lukacs T. Berkif7e36d82021-08-16 17:05:09 +0200863 path := filepath.Join(ctx.ModuleDir(), def)
Liz Kammera830f3a2020-11-10 10:50:34 -0800864 return Glob(ctx, path, nil)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700865}
866
867// Strings returns the Paths in string form
868func (p Paths) Strings() []string {
869 if p == nil {
870 return nil
871 }
872 ret := make([]string, len(p))
873 for i, path := range p {
874 ret[i] = path.String()
875 }
876 return ret
877}
878
Colin Crossc0efd1d2020-07-03 11:56:24 -0700879func CopyOfPaths(paths Paths) Paths {
880 return append(Paths(nil), paths...)
881}
882
Colin Crossb6715442017-10-24 11:13:31 -0700883// FirstUniquePaths returns all unique elements of a Paths, keeping the first copy of each. It
884// modifies the Paths slice contents in place, and returns a subslice of the original slice.
Dan Willemsenfe92c962017-08-29 12:28:37 -0700885func FirstUniquePaths(list Paths) Paths {
Colin Cross27027c72020-02-28 15:34:17 -0800886 // 128 was chosen based on BenchmarkFirstUniquePaths results.
887 if len(list) > 128 {
888 return firstUniquePathsMap(list)
889 }
890 return firstUniquePathsList(list)
891}
892
Colin Crossc0efd1d2020-07-03 11:56:24 -0700893// SortedUniquePaths returns all unique elements of a Paths in sorted order. It modifies the
894// Paths slice contents in place, and returns a subslice of the original slice.
Jiyong Park33c77362020-05-29 22:00:16 +0900895func SortedUniquePaths(list Paths) Paths {
896 unique := FirstUniquePaths(list)
897 sort.Slice(unique, func(i, j int) bool {
898 return unique[i].String() < unique[j].String()
899 })
900 return unique
901}
902
Colin Cross27027c72020-02-28 15:34:17 -0800903func firstUniquePathsList(list Paths) Paths {
Dan Willemsenfe92c962017-08-29 12:28:37 -0700904 k := 0
905outer:
906 for i := 0; i < len(list); i++ {
907 for j := 0; j < k; j++ {
908 if list[i] == list[j] {
909 continue outer
910 }
911 }
912 list[k] = list[i]
913 k++
914 }
915 return list[:k]
916}
917
Colin Cross27027c72020-02-28 15:34:17 -0800918func firstUniquePathsMap(list Paths) Paths {
919 k := 0
920 seen := make(map[Path]bool, len(list))
921 for i := 0; i < len(list); i++ {
922 if seen[list[i]] {
923 continue
924 }
925 seen[list[i]] = true
926 list[k] = list[i]
927 k++
928 }
929 return list[:k]
930}
931
Colin Cross5d583952020-11-24 16:21:24 -0800932// FirstUniqueInstallPaths returns all unique elements of an InstallPaths, keeping the first copy of each. It
933// modifies the InstallPaths slice contents in place, and returns a subslice of the original slice.
934func FirstUniqueInstallPaths(list InstallPaths) InstallPaths {
935 // 128 was chosen based on BenchmarkFirstUniquePaths results.
936 if len(list) > 128 {
937 return firstUniqueInstallPathsMap(list)
938 }
939 return firstUniqueInstallPathsList(list)
940}
941
942func firstUniqueInstallPathsList(list InstallPaths) InstallPaths {
943 k := 0
944outer:
945 for i := 0; i < len(list); i++ {
946 for j := 0; j < k; j++ {
947 if list[i] == list[j] {
948 continue outer
949 }
950 }
951 list[k] = list[i]
952 k++
953 }
954 return list[:k]
955}
956
957func firstUniqueInstallPathsMap(list InstallPaths) InstallPaths {
958 k := 0
959 seen := make(map[InstallPath]bool, len(list))
960 for i := 0; i < len(list); i++ {
961 if seen[list[i]] {
962 continue
963 }
964 seen[list[i]] = true
965 list[k] = list[i]
966 k++
967 }
968 return list[:k]
969}
970
Colin Crossb6715442017-10-24 11:13:31 -0700971// LastUniquePaths returns all unique elements of a Paths, keeping the last copy of each. It
972// modifies the Paths slice contents in place, and returns a subslice of the original slice.
973func LastUniquePaths(list Paths) Paths {
974 totalSkip := 0
975 for i := len(list) - 1; i >= totalSkip; i-- {
976 skip := 0
977 for j := i - 1; j >= totalSkip; j-- {
978 if list[i] == list[j] {
979 skip++
980 } else {
981 list[j+skip] = list[j]
982 }
983 }
984 totalSkip += skip
985 }
986 return list[totalSkip:]
987}
988
Colin Crossa140bb02018-04-17 10:52:26 -0700989// ReversePaths returns a copy of a Paths in reverse order.
990func ReversePaths(list Paths) Paths {
991 if list == nil {
992 return nil
993 }
994 ret := make(Paths, len(list))
995 for i := range list {
996 ret[i] = list[len(list)-1-i]
997 }
998 return ret
999}
1000
Jeff Gaston294356f2017-09-27 17:05:30 -07001001func indexPathList(s Path, list []Path) int {
1002 for i, l := range list {
1003 if l == s {
1004 return i
1005 }
1006 }
1007
1008 return -1
1009}
1010
1011func inPathList(p Path, list []Path) bool {
1012 return indexPathList(p, list) != -1
1013}
1014
1015func FilterPathList(list []Path, filter []Path) (remainder []Path, filtered []Path) {
Paul Duffin57b9e1d2019-12-13 00:03:35 +00001016 return FilterPathListPredicate(list, func(p Path) bool { return inPathList(p, filter) })
1017}
1018
1019func FilterPathListPredicate(list []Path, predicate func(Path) bool) (remainder []Path, filtered []Path) {
Jeff Gaston294356f2017-09-27 17:05:30 -07001020 for _, l := range list {
Paul Duffin57b9e1d2019-12-13 00:03:35 +00001021 if predicate(l) {
Jeff Gaston294356f2017-09-27 17:05:30 -07001022 filtered = append(filtered, l)
1023 } else {
1024 remainder = append(remainder, l)
1025 }
1026 }
1027
1028 return
1029}
1030
Colin Cross93e85952017-08-15 13:34:18 -07001031// HasExt returns true of any of the paths have extension ext, otherwise false
1032func (p Paths) HasExt(ext string) bool {
1033 for _, path := range p {
1034 if path.Ext() == ext {
1035 return true
1036 }
1037 }
1038
1039 return false
1040}
1041
1042// FilterByExt returns the subset of the paths that have extension ext
1043func (p Paths) FilterByExt(ext string) Paths {
1044 ret := make(Paths, 0, len(p))
1045 for _, path := range p {
1046 if path.Ext() == ext {
1047 ret = append(ret, path)
1048 }
1049 }
1050 return ret
1051}
1052
1053// FilterOutByExt returns the subset of the paths that do not have extension ext
1054func (p Paths) FilterOutByExt(ext string) Paths {
1055 ret := make(Paths, 0, len(p))
1056 for _, path := range p {
1057 if path.Ext() != ext {
1058 ret = append(ret, path)
1059 }
1060 }
1061 return ret
1062}
1063
Colin Cross5e6cfbe2017-11-03 15:20:35 -07001064// DirectorySortedPaths is a slice of paths that are sorted such that all files in a directory
1065// (including subdirectories) are in a contiguous subslice of the list, and can be found in
1066// O(log(N)) time using a binary search on the directory prefix.
1067type DirectorySortedPaths Paths
1068
1069func PathsToDirectorySortedPaths(paths Paths) DirectorySortedPaths {
1070 ret := append(DirectorySortedPaths(nil), paths...)
1071 sort.Slice(ret, func(i, j int) bool {
1072 return ret[i].String() < ret[j].String()
1073 })
1074 return ret
1075}
1076
1077// PathsInDirectory returns a subslice of the DirectorySortedPaths as a Paths that contains all entries
1078// that are in the specified directory and its subdirectories.
1079func (p DirectorySortedPaths) PathsInDirectory(dir string) Paths {
1080 prefix := filepath.Clean(dir) + "/"
1081 start := sort.Search(len(p), func(i int) bool {
1082 return prefix < p[i].String()
1083 })
1084
1085 ret := p[start:]
1086
1087 end := sort.Search(len(ret), func(i int) bool {
1088 return !strings.HasPrefix(ret[i].String(), prefix)
1089 })
1090
1091 ret = ret[:end]
1092
1093 return Paths(ret)
1094}
1095
Alex Humesky29e3bbe2020-11-20 21:30:13 -05001096// WritablePaths is a slice of WritablePath, used for multiple outputs.
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001097type WritablePaths []WritablePath
1098
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001099// RelativeToTop creates a new WritablePaths containing the result of calling Path.RelativeToTop on
1100// each item in this slice.
1101func (p WritablePaths) RelativeToTop() WritablePaths {
1102 ensureTestOnly()
1103 if p == nil {
1104 return p
1105 }
1106 ret := make(WritablePaths, len(p))
1107 for i, path := range p {
1108 ret[i] = path.RelativeToTop().(WritablePath)
1109 }
1110 return ret
1111}
1112
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001113// Strings returns the string forms of the writable paths.
1114func (p WritablePaths) Strings() []string {
1115 if p == nil {
1116 return nil
1117 }
1118 ret := make([]string, len(p))
1119 for i, path := range p {
1120 ret[i] = path.String()
1121 }
1122 return ret
1123}
1124
Colin Cross3bc7ffa2017-11-22 16:19:37 -08001125// Paths returns the WritablePaths as a Paths
1126func (p WritablePaths) Paths() Paths {
1127 if p == nil {
1128 return nil
1129 }
1130 ret := make(Paths, len(p))
1131 for i, path := range p {
1132 ret[i] = path
1133 }
1134 return ret
1135}
1136
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001137type basePath struct {
Paul Duffin74abc5d2021-03-24 09:24:59 +00001138 path string
1139 rel string
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001140}
1141
Yu Liu467d7c52024-09-18 21:54:44 +00001142type basePathGob struct {
1143 Path string
1144 Rel string
1145}
Yu Liufa297642024-06-11 00:13:02 +00001146
Yu Liu467d7c52024-09-18 21:54:44 +00001147func (p *basePath) ToGob() *basePathGob {
1148 return &basePathGob{
1149 Path: p.path,
1150 Rel: p.rel,
1151 }
1152}
1153
1154func (p *basePath) FromGob(data *basePathGob) {
1155 p.path = data.Path
1156 p.rel = data.Rel
1157}
1158
1159func (p basePath) GobEncode() ([]byte, error) {
1160 return blueprint.CustomGobEncode[basePathGob](&p)
Yu Liufa297642024-06-11 00:13:02 +00001161}
1162
1163func (p *basePath) GobDecode(data []byte) error {
Yu Liu467d7c52024-09-18 21:54:44 +00001164 return blueprint.CustomGobDecode[basePathGob](data, p)
Yu Liufa297642024-06-11 00:13:02 +00001165}
1166
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001167func (p basePath) Ext() string {
1168 return filepath.Ext(p.path)
1169}
1170
Colin Cross4f6fc9c2016-10-26 10:05:25 -07001171func (p basePath) Base() string {
1172 return filepath.Base(p.path)
1173}
1174
Colin Crossfaeb7aa2017-02-01 14:12:44 -08001175func (p basePath) Rel() string {
1176 if p.rel != "" {
1177 return p.rel
1178 }
1179 return p.path
1180}
1181
Colin Cross0875c522017-11-28 17:34:01 -08001182func (p basePath) String() string {
1183 return p.path
1184}
1185
Colin Cross0db55682017-12-05 15:36:55 -08001186func (p basePath) withRel(rel string) basePath {
1187 p.path = filepath.Join(p.path, rel)
1188 p.rel = rel
1189 return p
1190}
1191
Colin Cross7707b242024-07-26 12:02:36 -07001192func (p basePath) withoutRel() basePath {
1193 p.rel = filepath.Base(p.path)
1194 return p
1195}
1196
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001197// SourcePath is a Path representing a file path rooted from SrcDir
1198type SourcePath struct {
1199 basePath
1200}
1201
1202var _ Path = SourcePath{}
1203
Colin Cross0db55682017-12-05 15:36:55 -08001204func (p SourcePath) withRel(rel string) SourcePath {
1205 p.basePath = p.basePath.withRel(rel)
1206 return p
1207}
1208
Colin Crossbd73d0d2024-07-26 12:00:33 -07001209func (p SourcePath) RelativeToTop() Path {
1210 ensureTestOnly()
1211 return p
1212}
1213
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001214// safePathForSource is for paths that we expect are safe -- only for use by go
1215// code that is embedding ninja variables in paths
Colin Crossfe4bc362018-09-12 10:02:13 -07001216func safePathForSource(ctx PathContext, pathComponents ...string) (SourcePath, error) {
1217 p, err := validateSafePath(pathComponents...)
Cole Faust483d1f72023-01-09 14:35:27 -08001218 ret := SourcePath{basePath{p, ""}}
Colin Crossfe4bc362018-09-12 10:02:13 -07001219 if err != nil {
1220 return ret, err
1221 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001222
Colin Cross7b3dcc32019-01-24 13:14:39 -08001223 // absolute path already checked by validateSafePath
Inseob Kim5eb7ee92022-04-27 10:30:34 +09001224 // special-case api surface gen files for now
1225 if strings.HasPrefix(ret.String(), ctx.Config().soongOutDir) && !strings.Contains(ret.String(), ctx.Config().soongOutDir+"/.export") {
Mikhail Naganovab1f5182019-02-08 13:17:55 -08001226 return ret, fmt.Errorf("source path %q is in output", ret.String())
Colin Cross6e18ca42015-07-14 18:55:36 -07001227 }
1228
Colin Crossfe4bc362018-09-12 10:02:13 -07001229 return ret, err
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001230}
1231
Colin Cross192e97a2018-02-22 14:21:02 -08001232// pathForSource creates a SourcePath from pathComponents, but does not check that it exists.
1233func pathForSource(ctx PathContext, pathComponents ...string) (SourcePath, error) {
Colin Crossc48c1432018-02-23 07:09:01 +00001234 p, err := validatePath(pathComponents...)
Cole Faust483d1f72023-01-09 14:35:27 -08001235 ret := SourcePath{basePath{p, ""}}
Colin Cross94a32102018-02-22 14:21:02 -08001236 if err != nil {
Colin Cross192e97a2018-02-22 14:21:02 -08001237 return ret, err
Colin Cross94a32102018-02-22 14:21:02 -08001238 }
1239
Colin Cross7b3dcc32019-01-24 13:14:39 -08001240 // absolute path already checked by validatePath
Inseob Kim5eb7ee92022-04-27 10:30:34 +09001241 // special-case for now
1242 if strings.HasPrefix(ret.String(), ctx.Config().soongOutDir) && !strings.Contains(ret.String(), ctx.Config().soongOutDir+"/.export") {
Mikhail Naganovab1f5182019-02-08 13:17:55 -08001243 return ret, fmt.Errorf("source path %q is in output", ret.String())
Colin Crossc48c1432018-02-23 07:09:01 +00001244 }
1245
Colin Cross192e97a2018-02-22 14:21:02 -08001246 return ret, nil
1247}
1248
1249// existsWithDependencies returns true if the path exists, and adds appropriate dependencies to rerun if the
1250// path does not exist.
Colin Cross662d6142022-11-03 20:38:01 -07001251func existsWithDependencies(ctx PathGlobContext, path SourcePath) (exists bool, err error) {
Colin Cross192e97a2018-02-22 14:21:02 -08001252 var files []string
1253
Colin Cross662d6142022-11-03 20:38:01 -07001254 // Use glob to produce proper dependencies, even though we only want
1255 // a single file.
1256 files, err = ctx.GlobWithDeps(path.String(), nil)
Colin Cross192e97a2018-02-22 14:21:02 -08001257
1258 if err != nil {
1259 return false, fmt.Errorf("glob: %s", err.Error())
1260 }
1261
1262 return len(files) > 0, nil
1263}
1264
1265// PathForSource joins the provided path components and validates that the result
1266// neither escapes the source dir nor is in the out dir.
1267// On error, it will return a usable, but invalid SourcePath, and report a ModuleError.
1268func PathForSource(ctx PathContext, pathComponents ...string) SourcePath {
1269 path, err := pathForSource(ctx, pathComponents...)
1270 if err != nil {
1271 reportPathError(ctx, err)
1272 }
1273
Colin Crosse3924e12018-08-15 20:18:53 -07001274 if pathtools.IsGlob(path.String()) {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001275 ReportPathErrorf(ctx, "path may not contain a glob: %s", path.String())
Colin Crosse3924e12018-08-15 20:18:53 -07001276 }
1277
Liz Kammera830f3a2020-11-10 10:50:34 -08001278 if modCtx, ok := ctx.(ModuleMissingDepsPathContext); ok && ctx.Config().AllowMissingDependencies() {
Colin Cross662d6142022-11-03 20:38:01 -07001279 exists, err := existsWithDependencies(modCtx, path)
Colin Cross192e97a2018-02-22 14:21:02 -08001280 if err != nil {
1281 reportPathError(ctx, err)
1282 }
1283 if !exists {
1284 modCtx.AddMissingDependencies([]string{path.String()})
1285 }
Colin Cross988414c2020-01-11 01:11:46 +00001286 } else if exists, _, err := ctx.Config().fs.Exists(path.String()); err != nil {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001287 ReportPathErrorf(ctx, "%s: %s", path, err.Error())
Pedro Loureiro5d190cc2021-02-15 15:41:33 +00001288 } else if !exists && !ctx.Config().TestAllowNonExistentPaths {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001289 ReportPathErrorf(ctx, "source path %q does not exist", path)
Colin Cross192e97a2018-02-22 14:21:02 -08001290 }
1291 return path
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001292}
1293
Cole Faustbc65a3f2023-08-01 16:38:55 +00001294// PathForArbitraryOutput creates a path for the given components. Unlike PathForOutput,
1295// the path is relative to the root of the output folder, not the out/soong folder.
1296func PathForArbitraryOutput(ctx PathContext, pathComponents ...string) Path {
Colin Cross3b1c6842024-07-26 11:52:57 -07001297 path, err := validatePath(pathComponents...)
Cole Faustbc65a3f2023-08-01 16:38:55 +00001298 if err != nil {
1299 reportPathError(ctx, err)
1300 }
Colin Cross3b1c6842024-07-26 11:52:57 -07001301 fullPath := filepath.Join(ctx.Config().OutDir(), path)
1302 path = fullPath[len(fullPath)-len(path):]
1303 return OutputPath{basePath{path, ""}, ctx.Config().OutDir(), fullPath}
Cole Faustbc65a3f2023-08-01 16:38:55 +00001304}
1305
Spandan Dasc6c10fa2022-10-21 21:52:13 +00001306// MaybeExistentPathForSource joins the provided path components and validates that the result
1307// neither escapes the source dir nor is in the out dir.
1308// It does not validate whether the path exists.
1309func MaybeExistentPathForSource(ctx PathContext, pathComponents ...string) SourcePath {
1310 path, err := pathForSource(ctx, pathComponents...)
1311 if err != nil {
1312 reportPathError(ctx, err)
1313 }
1314
1315 if pathtools.IsGlob(path.String()) {
1316 ReportPathErrorf(ctx, "path may not contain a glob: %s", path.String())
1317 }
1318 return path
1319}
1320
Liz Kammer7aa52882021-02-11 09:16:14 -05001321// ExistentPathForSource returns an OptionalPath with the SourcePath, rooted from SrcDir, *not*
1322// rooted from the module's local source directory, if the path exists, or an empty OptionalPath if
1323// it doesn't exist. Dependencies are added so that the ninja file will be regenerated if the state
1324// of the path changes.
Colin Cross662d6142022-11-03 20:38:01 -07001325func ExistentPathForSource(ctx PathGlobContext, pathComponents ...string) OptionalPath {
Colin Cross192e97a2018-02-22 14:21:02 -08001326 path, err := pathForSource(ctx, pathComponents...)
Colin Cross1ccfcc32018-02-22 13:54:26 -08001327 if err != nil {
1328 reportPathError(ctx, err)
Martin Stjernholmc32dd1c2021-09-15 02:39:00 +01001329 // No need to put the error message into the returned path since it has been reported already.
Colin Cross1ccfcc32018-02-22 13:54:26 -08001330 return OptionalPath{}
1331 }
Colin Crossc48c1432018-02-23 07:09:01 +00001332
Colin Crosse3924e12018-08-15 20:18:53 -07001333 if pathtools.IsGlob(path.String()) {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001334 ReportPathErrorf(ctx, "path may not contain a glob: %s", path.String())
Colin Crosse3924e12018-08-15 20:18:53 -07001335 return OptionalPath{}
1336 }
1337
Colin Cross192e97a2018-02-22 14:21:02 -08001338 exists, err := existsWithDependencies(ctx, path)
Colin Crossc48c1432018-02-23 07:09:01 +00001339 if err != nil {
1340 reportPathError(ctx, err)
1341 return OptionalPath{}
1342 }
Colin Cross192e97a2018-02-22 14:21:02 -08001343 if !exists {
Martin Stjernholmc32dd1c2021-09-15 02:39:00 +01001344 return InvalidOptionalPath(path.String() + " does not exist")
Colin Crossc48c1432018-02-23 07:09:01 +00001345 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001346 return OptionalPathForPath(path)
1347}
1348
1349func (p SourcePath) String() string {
Cole Faust483d1f72023-01-09 14:35:27 -08001350 if p.path == "" {
1351 return "."
1352 }
1353 return p.path
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001354}
1355
Colin Cross7707b242024-07-26 12:02:36 -07001356func (p SourcePath) WithoutRel() Path {
1357 p.basePath = p.basePath.withoutRel()
1358 return p
1359}
1360
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001361// Join creates a new SourcePath with paths... joined with the current path. The
1362// provided paths... may not use '..' to escape from the current path.
1363func (p SourcePath) Join(ctx PathContext, paths ...string) SourcePath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001364 path, err := validatePath(paths...)
1365 if err != nil {
1366 reportPathError(ctx, err)
1367 }
Colin Cross0db55682017-12-05 15:36:55 -08001368 return p.withRel(path)
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001369}
1370
Colin Cross2fafa3e2019-03-05 12:39:51 -08001371// join is like Join but does less path validation.
1372func (p SourcePath) join(ctx PathContext, paths ...string) SourcePath {
1373 path, err := validateSafePath(paths...)
1374 if err != nil {
1375 reportPathError(ctx, err)
1376 }
1377 return p.withRel(path)
1378}
1379
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001380// OverlayPath returns the overlay for `path' if it exists. This assumes that the
1381// SourcePath is the path to a resource overlay directory.
Liz Kammera830f3a2020-11-10 10:50:34 -08001382func (p SourcePath) OverlayPath(ctx ModuleMissingDepsPathContext, path Path) OptionalPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001383 var relDir string
Colin Cross07e51612019-03-05 12:46:40 -08001384 if srcPath, ok := path.(SourcePath); ok {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001385 relDir = srcPath.path
1386 } else {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001387 ReportPathErrorf(ctx, "Cannot find relative path for %s(%s)", reflect.TypeOf(path).Name(), path)
Martin Stjernholmc32dd1c2021-09-15 02:39:00 +01001388 // No need to put the error message into the returned path since it has been reported already.
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001389 return OptionalPath{}
1390 }
Cole Faust483d1f72023-01-09 14:35:27 -08001391 dir := filepath.Join(p.path, relDir)
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001392 // Use Glob so that we are run again if the directory is added.
Colin Cross7f19f372016-11-01 11:10:25 -07001393 if pathtools.IsGlob(dir) {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001394 ReportPathErrorf(ctx, "Path may not contain a glob: %s", dir)
Dan Willemsen7b310ee2015-12-18 15:11:17 -08001395 }
Colin Cross461b4452018-02-23 09:22:42 -08001396 paths, err := ctx.GlobWithDeps(dir, nil)
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001397 if err != nil {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001398 ReportPathErrorf(ctx, "glob: %s", err.Error())
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001399 return OptionalPath{}
1400 }
1401 if len(paths) == 0 {
Martin Stjernholmc32dd1c2021-09-15 02:39:00 +01001402 return InvalidOptionalPath(dir + " does not exist")
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001403 }
Cole Faust483d1f72023-01-09 14:35:27 -08001404 return OptionalPathForPath(PathForSource(ctx, paths[0]))
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001405}
1406
Colin Cross70dda7e2019-10-01 22:05:35 -07001407// OutputPath is a Path representing an intermediates file path rooted from the build directory
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001408type OutputPath struct {
1409 basePath
Paul Duffind65c58b2021-03-24 09:22:07 +00001410
Colin Cross3b1c6842024-07-26 11:52:57 -07001411 // The base out directory for this path, either Config.SoongOutDir() or Config.OutDir()
1412 outDir string
Paul Duffind65c58b2021-03-24 09:22:07 +00001413
Colin Crossd63c9a72020-01-29 16:52:50 -08001414 fullPath string
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001415}
1416
Yu Liu467d7c52024-09-18 21:54:44 +00001417type outputPathGob struct {
Yu Liu5246a7e2024-10-09 20:04:52 +00001418 BasePath basePath
Yu Liu467d7c52024-09-18 21:54:44 +00001419 OutDir string
1420 FullPath string
1421}
Yu Liufa297642024-06-11 00:13:02 +00001422
Yu Liu467d7c52024-09-18 21:54:44 +00001423func (p *OutputPath) ToGob() *outputPathGob {
1424 return &outputPathGob{
Yu Liu5246a7e2024-10-09 20:04:52 +00001425 BasePath: p.basePath,
Yu Liu467d7c52024-09-18 21:54:44 +00001426 OutDir: p.outDir,
1427 FullPath: p.fullPath,
1428 }
1429}
1430
1431func (p *OutputPath) FromGob(data *outputPathGob) {
Yu Liu5246a7e2024-10-09 20:04:52 +00001432 p.basePath = data.BasePath
Yu Liu467d7c52024-09-18 21:54:44 +00001433 p.outDir = data.OutDir
1434 p.fullPath = data.FullPath
1435}
1436
1437func (p OutputPath) GobEncode() ([]byte, error) {
1438 return blueprint.CustomGobEncode[outputPathGob](&p)
Yu Liufa297642024-06-11 00:13:02 +00001439}
1440
1441func (p *OutputPath) GobDecode(data []byte) error {
Yu Liu467d7c52024-09-18 21:54:44 +00001442 return blueprint.CustomGobDecode[outputPathGob](data, p)
Yu Liufa297642024-06-11 00:13:02 +00001443}
1444
Colin Cross702e0f82017-10-18 17:27:54 -07001445func (p OutputPath) withRel(rel string) OutputPath {
Colin Cross0db55682017-12-05 15:36:55 -08001446 p.basePath = p.basePath.withRel(rel)
Colin Crossd63c9a72020-01-29 16:52:50 -08001447 p.fullPath = filepath.Join(p.fullPath, rel)
Colin Cross702e0f82017-10-18 17:27:54 -07001448 return p
1449}
1450
Colin Cross7707b242024-07-26 12:02:36 -07001451func (p OutputPath) WithoutRel() Path {
1452 p.basePath = p.basePath.withoutRel()
Colin Cross3063b782018-08-15 11:19:12 -07001453 return p
1454}
1455
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02001456func (p OutputPath) getSoongOutDir() string {
Colin Cross3b1c6842024-07-26 11:52:57 -07001457 return p.outDir
Paul Duffin9b478b02019-12-10 13:41:51 +00001458}
1459
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001460func (p OutputPath) RelativeToTop() Path {
1461 return p.outputPathRelativeToTop()
1462}
1463
1464func (p OutputPath) outputPathRelativeToTop() OutputPath {
Colin Cross3b1c6842024-07-26 11:52:57 -07001465 p.fullPath = StringPathRelativeToTop(p.outDir, p.fullPath)
1466 if strings.HasSuffix(p.outDir, testOutSoongSubDir) {
1467 p.outDir = TestOutSoongDir
1468 } else {
1469 // Handle the PathForArbitraryOutput case
1470 p.outDir = testOutDir
1471 }
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001472 return p
1473}
1474
Paul Duffin0267d492021-02-02 10:05:52 +00001475func (p OutputPath) objPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleObjPath {
1476 return PathForModuleObj(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
1477}
1478
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001479var _ Path = OutputPath{}
Paul Duffin9b478b02019-12-10 13:41:51 +00001480var _ WritablePath = OutputPath{}
Paul Duffin0267d492021-02-02 10:05:52 +00001481var _ objPathProvider = OutputPath{}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001482
Chris Parsons8f232a22020-06-23 17:37:05 -04001483// toolDepPath is a Path representing a dependency of the build tool.
1484type toolDepPath struct {
1485 basePath
1486}
1487
Colin Cross7707b242024-07-26 12:02:36 -07001488func (t toolDepPath) WithoutRel() Path {
1489 t.basePath = t.basePath.withoutRel()
1490 return t
1491}
1492
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001493func (t toolDepPath) RelativeToTop() Path {
1494 ensureTestOnly()
1495 return t
1496}
1497
Chris Parsons8f232a22020-06-23 17:37:05 -04001498var _ Path = toolDepPath{}
1499
1500// pathForBuildToolDep returns a toolDepPath representing the given path string.
1501// There is no validation for the path, as it is "trusted": It may fail
1502// normal validation checks. For example, it may be an absolute path.
1503// Only use this function to construct paths for dependencies of the build
1504// tool invocation.
1505func pathForBuildToolDep(ctx PathContext, path string) toolDepPath {
Paul Duffin74abc5d2021-03-24 09:24:59 +00001506 return toolDepPath{basePath{path, ""}}
Chris Parsons8f232a22020-06-23 17:37:05 -04001507}
1508
Jeff Gaston734e3802017-04-10 15:47:24 -07001509// PathForOutput joins the provided paths and returns an OutputPath that is
1510// validated to not escape the build dir.
1511// On error, it will return a usable, but invalid OutputPath, and report a ModuleError.
1512func PathForOutput(ctx PathContext, pathComponents ...string) OutputPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001513 path, err := validatePath(pathComponents...)
1514 if err != nil {
1515 reportPathError(ctx, err)
1516 }
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02001517 fullPath := filepath.Join(ctx.Config().soongOutDir, path)
Colin Crossd63c9a72020-01-29 16:52:50 -08001518 path = fullPath[len(fullPath)-len(path):]
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02001519 return OutputPath{basePath{path, ""}, ctx.Config().soongOutDir, fullPath}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001520}
1521
Colin Cross3b1c6842024-07-26 11:52:57 -07001522// PathsForOutput returns Paths rooted from outDir
Colin Cross40e33732019-02-15 11:08:35 -08001523func PathsForOutput(ctx PathContext, paths []string) WritablePaths {
1524 ret := make(WritablePaths, len(paths))
1525 for i, path := range paths {
1526 ret[i] = PathForOutput(ctx, path)
1527 }
1528 return ret
1529}
1530
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001531func (p OutputPath) writablePath() {}
1532
1533func (p OutputPath) String() string {
Colin Crossd63c9a72020-01-29 16:52:50 -08001534 return p.fullPath
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001535}
1536
1537// Join creates a new OutputPath with paths... joined with the current path. The
1538// provided paths... may not use '..' to escape from the current path.
1539func (p OutputPath) Join(ctx PathContext, paths ...string) OutputPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001540 path, err := validatePath(paths...)
1541 if err != nil {
1542 reportPathError(ctx, err)
1543 }
Colin Cross0db55682017-12-05 15:36:55 -08001544 return p.withRel(path)
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001545}
1546
Colin Cross8854a5a2019-02-11 14:14:16 -08001547// ReplaceExtension creates a new OutputPath with the extension replaced with ext.
1548func (p OutputPath) ReplaceExtension(ctx PathContext, ext string) OutputPath {
1549 if strings.Contains(ext, "/") {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001550 ReportPathErrorf(ctx, "extension %q cannot contain /", ext)
Colin Cross8854a5a2019-02-11 14:14:16 -08001551 }
1552 ret := PathForOutput(ctx, pathtools.ReplaceExtension(p.path, ext))
Colin Cross2cdd5df2019-02-25 10:25:24 -08001553 ret.rel = pathtools.ReplaceExtension(p.rel, ext)
Colin Cross8854a5a2019-02-11 14:14:16 -08001554 return ret
1555}
1556
Colin Cross40e33732019-02-15 11:08:35 -08001557// InSameDir creates a new OutputPath from the directory of the current OutputPath joined with the elements in paths.
1558func (p OutputPath) InSameDir(ctx PathContext, paths ...string) OutputPath {
1559 path, err := validatePath(paths...)
1560 if err != nil {
1561 reportPathError(ctx, err)
1562 }
1563
1564 ret := PathForOutput(ctx, filepath.Dir(p.path), path)
Colin Cross2cdd5df2019-02-25 10:25:24 -08001565 ret.rel = filepath.Join(filepath.Dir(p.rel), path)
Colin Cross40e33732019-02-15 11:08:35 -08001566 return ret
1567}
1568
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001569// PathForIntermediates returns an OutputPath representing the top-level
1570// intermediates directory.
1571func PathForIntermediates(ctx PathContext, paths ...string) OutputPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001572 path, err := validatePath(paths...)
1573 if err != nil {
1574 reportPathError(ctx, err)
1575 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001576 return PathForOutput(ctx, ".intermediates", path)
1577}
1578
Colin Cross07e51612019-03-05 12:46:40 -08001579var _ genPathProvider = SourcePath{}
1580var _ objPathProvider = SourcePath{}
1581var _ resPathProvider = SourcePath{}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001582
Colin Cross07e51612019-03-05 12:46:40 -08001583// PathForModuleSrc returns a Path representing the paths... under the
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001584// module's local source directory.
Liz Kammera830f3a2020-11-10 10:50:34 -08001585func PathForModuleSrc(ctx ModuleMissingDepsPathContext, pathComponents ...string) Path {
Paul Duffin407501b2021-07-09 16:56:35 +01001586 // Just join the components textually just to make sure that it does not corrupt a fully qualified
1587 // module reference, e.g. if the pathComponents is "://other:foo" then using filepath.Join() or
1588 // validatePath() will corrupt it, e.g. replace "//" with "/". If the path is not a module
1589 // reference then it will be validated by expandOneSrcPath anyway when it calls expandOneSrcPath.
1590 p := strings.Join(pathComponents, string(filepath.Separator))
Liz Kammer619be462022-01-28 15:13:39 -05001591 paths, err := expandOneSrcPath(sourcePathInput{context: ctx, path: p, includeDirs: true})
Colin Cross8a497952019-03-05 22:25:09 -08001592 if err != nil {
1593 if depErr, ok := err.(missingDependencyError); ok {
1594 if ctx.Config().AllowMissingDependencies() {
1595 ctx.AddMissingDependencies(depErr.missingDeps)
1596 } else {
1597 ctx.ModuleErrorf(`%s, is the property annotated with android:"path"?`, depErr.Error())
1598 }
1599 } else {
1600 reportPathError(ctx, err)
1601 }
1602 return nil
1603 } else if len(paths) == 0 {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001604 ReportPathErrorf(ctx, "%q produced no files, expected exactly one", p)
Colin Cross8a497952019-03-05 22:25:09 -08001605 return nil
1606 } else if len(paths) > 1 {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001607 ReportPathErrorf(ctx, "%q produced %d files, expected exactly one", p, len(paths))
Colin Cross8a497952019-03-05 22:25:09 -08001608 }
1609 return paths[0]
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001610}
1611
Liz Kammera830f3a2020-11-10 10:50:34 -08001612func pathForModuleSrc(ctx EarlyModulePathContext, paths ...string) SourcePath {
Colin Cross07e51612019-03-05 12:46:40 -08001613 p, err := validatePath(paths...)
1614 if err != nil {
1615 reportPathError(ctx, err)
1616 }
1617
1618 path, err := pathForSource(ctx, ctx.ModuleDir(), p)
1619 if err != nil {
1620 reportPathError(ctx, err)
1621 }
1622
1623 path.basePath.rel = p
1624
1625 return path
1626}
1627
Colin Cross2fafa3e2019-03-05 12:39:51 -08001628// PathsWithModuleSrcSubDir takes a list of Paths and returns a new list of Paths where Rel() on each path
1629// will return the path relative to subDir in the module's source directory. If any input paths are not located
1630// inside subDir then a path error will be reported.
Liz Kammera830f3a2020-11-10 10:50:34 -08001631func PathsWithModuleSrcSubDir(ctx EarlyModulePathContext, paths Paths, subDir string) Paths {
Colin Cross2fafa3e2019-03-05 12:39:51 -08001632 paths = append(Paths(nil), paths...)
Colin Cross07e51612019-03-05 12:46:40 -08001633 subDirFullPath := pathForModuleSrc(ctx, subDir)
Colin Cross2fafa3e2019-03-05 12:39:51 -08001634 for i, path := range paths {
1635 rel := Rel(ctx, subDirFullPath.String(), path.String())
1636 paths[i] = subDirFullPath.join(ctx, rel)
1637 }
1638 return paths
1639}
1640
1641// PathWithModuleSrcSubDir takes a Path and returns a Path where Rel() will return the path relative to subDir in the
1642// 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 -08001643func PathWithModuleSrcSubDir(ctx EarlyModulePathContext, path Path, subDir string) Path {
Colin Cross07e51612019-03-05 12:46:40 -08001644 subDirFullPath := pathForModuleSrc(ctx, subDir)
Colin Cross2fafa3e2019-03-05 12:39:51 -08001645 rel := Rel(ctx, subDirFullPath.String(), path.String())
1646 return subDirFullPath.Join(ctx, rel)
1647}
1648
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001649// OptionalPathForModuleSrc returns an OptionalPath. The OptionalPath contains a
1650// valid path if p is non-nil.
Liz Kammera830f3a2020-11-10 10:50:34 -08001651func OptionalPathForModuleSrc(ctx ModuleMissingDepsPathContext, p *string) OptionalPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001652 if p == nil {
1653 return OptionalPath{}
1654 }
1655 return OptionalPathForPath(PathForModuleSrc(ctx, *p))
1656}
1657
Liz Kammera830f3a2020-11-10 10:50:34 -08001658func (p SourcePath) genPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleGenPath {
Colin Cross7fc17db2017-02-01 14:07:55 -08001659 return PathForModuleGen(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001660}
1661
yangbill6d032dd2024-04-18 03:05:49 +00001662func (p SourcePath) genPathWithExtAndTrimExt(ctx ModuleOutPathContext, subdir, ext string, trimExt string) ModuleGenPath {
1663 // If Trim_extension being set, force append Output_extension without replace original extension.
1664 if trimExt != "" {
1665 if ext != "" {
1666 return PathForModuleGen(ctx, subdir, strings.TrimSuffix(p.path, trimExt)+"."+ext)
1667 }
1668 return PathForModuleGen(ctx, subdir, strings.TrimSuffix(p.path, trimExt))
1669 }
1670 return PathForModuleGen(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
1671}
1672
Liz Kammera830f3a2020-11-10 10:50:34 -08001673func (p SourcePath) objPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleObjPath {
Colin Cross7fc17db2017-02-01 14:07:55 -08001674 return PathForModuleObj(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001675}
1676
Liz Kammera830f3a2020-11-10 10:50:34 -08001677func (p SourcePath) resPathWithName(ctx ModuleOutPathContext, name string) ModuleResPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001678 // TODO: Use full directory if the new ctx is not the current ctx?
1679 return PathForModuleRes(ctx, p.path, name)
1680}
1681
1682// ModuleOutPath is a Path representing a module's output directory.
1683type ModuleOutPath struct {
1684 OutputPath
1685}
1686
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001687func (p ModuleOutPath) RelativeToTop() Path {
1688 p.OutputPath = p.outputPathRelativeToTop()
1689 return p
1690}
1691
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001692var _ Path = ModuleOutPath{}
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001693var _ WritablePath = ModuleOutPath{}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001694
Liz Kammera830f3a2020-11-10 10:50:34 -08001695func (p ModuleOutPath) objPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleObjPath {
Pete Bentleyfcf55bf2019-08-16 20:14:32 +01001696 return PathForModuleObj(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
1697}
1698
Liz Kammera830f3a2020-11-10 10:50:34 -08001699// ModuleOutPathContext Subset of ModuleContext functions necessary for output path methods.
1700type ModuleOutPathContext interface {
1701 PathContext
1702
1703 ModuleName() string
1704 ModuleDir() string
1705 ModuleSubDir() string
1706}
1707
1708func pathForModuleOut(ctx ModuleOutPathContext) OutputPath {
Inseob Kimb7e9f5f2024-06-25 17:39:52 +09001709 return PathForOutput(ctx, ".intermediates", ctx.ModuleDir(), ctx.ModuleName(), ctx.ModuleSubDir())
Colin Cross702e0f82017-10-18 17:27:54 -07001710}
1711
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001712// PathForModuleOut returns a Path representing the paths... under the module's
1713// output directory.
Liz Kammera830f3a2020-11-10 10:50:34 -08001714func PathForModuleOut(ctx ModuleOutPathContext, paths ...string) ModuleOutPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001715 p, err := validatePath(paths...)
1716 if err != nil {
1717 reportPathError(ctx, err)
1718 }
Colin Cross702e0f82017-10-18 17:27:54 -07001719 return ModuleOutPath{
Liz Kammera830f3a2020-11-10 10:50:34 -08001720 OutputPath: pathForModuleOut(ctx).withRel(p),
Colin Cross702e0f82017-10-18 17:27:54 -07001721 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001722}
1723
1724// ModuleGenPath is a Path representing the 'gen' directory in a module's output
1725// directory. Mainly used for generated sources.
1726type ModuleGenPath struct {
1727 ModuleOutPath
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001728}
1729
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001730func (p ModuleGenPath) RelativeToTop() Path {
1731 p.OutputPath = p.outputPathRelativeToTop()
1732 return p
1733}
1734
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001735var _ Path = ModuleGenPath{}
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001736var _ WritablePath = ModuleGenPath{}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001737var _ genPathProvider = ModuleGenPath{}
1738var _ objPathProvider = ModuleGenPath{}
1739
1740// PathForModuleGen returns a Path representing the paths... under the module's
1741// `gen' directory.
Liz Kammera830f3a2020-11-10 10:50:34 -08001742func PathForModuleGen(ctx ModuleOutPathContext, paths ...string) ModuleGenPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001743 p, err := validatePath(paths...)
1744 if err != nil {
1745 reportPathError(ctx, err)
1746 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001747 return ModuleGenPath{
Colin Cross702e0f82017-10-18 17:27:54 -07001748 ModuleOutPath: ModuleOutPath{
Liz Kammera830f3a2020-11-10 10:50:34 -08001749 OutputPath: pathForModuleOut(ctx).withRel("gen").withRel(p),
Colin Cross702e0f82017-10-18 17:27:54 -07001750 },
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001751 }
1752}
1753
Liz Kammera830f3a2020-11-10 10:50:34 -08001754func (p ModuleGenPath) genPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleGenPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001755 // TODO: make a different path for local vs remote generated files?
Dan Willemsen21ec4902016-11-02 20:43:13 -07001756 return PathForModuleGen(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001757}
1758
yangbill6d032dd2024-04-18 03:05:49 +00001759func (p ModuleGenPath) genPathWithExtAndTrimExt(ctx ModuleOutPathContext, subdir, ext string, trimExt string) ModuleGenPath {
1760 // If Trim_extension being set, force append Output_extension without replace original extension.
1761 if trimExt != "" {
1762 if ext != "" {
1763 return PathForModuleGen(ctx, subdir, strings.TrimSuffix(p.path, trimExt)+"."+ext)
1764 }
1765 return PathForModuleGen(ctx, subdir, strings.TrimSuffix(p.path, trimExt))
1766 }
1767 return PathForModuleGen(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
1768}
1769
Liz Kammera830f3a2020-11-10 10:50:34 -08001770func (p ModuleGenPath) objPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleObjPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001771 return PathForModuleObj(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
1772}
1773
1774// ModuleObjPath is a Path representing the 'obj' directory in a module's output
1775// directory. Used for compiled objects.
1776type ModuleObjPath struct {
1777 ModuleOutPath
1778}
1779
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001780func (p ModuleObjPath) RelativeToTop() Path {
1781 p.OutputPath = p.outputPathRelativeToTop()
1782 return p
1783}
1784
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001785var _ Path = ModuleObjPath{}
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001786var _ WritablePath = ModuleObjPath{}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001787
1788// PathForModuleObj returns a Path representing the paths... under the module's
1789// 'obj' directory.
Liz Kammera830f3a2020-11-10 10:50:34 -08001790func PathForModuleObj(ctx ModuleOutPathContext, pathComponents ...string) ModuleObjPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001791 p, err := validatePath(pathComponents...)
1792 if err != nil {
1793 reportPathError(ctx, err)
1794 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001795 return ModuleObjPath{PathForModuleOut(ctx, "obj", p)}
1796}
1797
1798// ModuleResPath is a a Path representing the 'res' directory in a module's
1799// output directory.
1800type ModuleResPath struct {
1801 ModuleOutPath
1802}
1803
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001804func (p ModuleResPath) RelativeToTop() Path {
1805 p.OutputPath = p.outputPathRelativeToTop()
1806 return p
1807}
1808
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001809var _ Path = ModuleResPath{}
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001810var _ WritablePath = ModuleResPath{}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001811
1812// PathForModuleRes returns a Path representing the paths... under the module's
1813// 'res' directory.
Liz Kammera830f3a2020-11-10 10:50:34 -08001814func PathForModuleRes(ctx ModuleOutPathContext, pathComponents ...string) ModuleResPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001815 p, err := validatePath(pathComponents...)
1816 if err != nil {
1817 reportPathError(ctx, err)
1818 }
1819
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001820 return ModuleResPath{PathForModuleOut(ctx, "res", p)}
1821}
1822
Colin Cross70dda7e2019-10-01 22:05:35 -07001823// InstallPath is a Path representing a installed file path rooted from the build directory
1824type InstallPath struct {
1825 basePath
Colin Crossff6c33d2019-10-02 16:01:35 -07001826
Lukacs T. Berkib078ade2021-08-31 10:42:08 +02001827 // The soong build directory, i.e. Config.SoongOutDir()
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02001828 soongOutDir string
Paul Duffind65c58b2021-03-24 09:22:07 +00001829
Jiyong Park957bcd92020-10-20 18:23:33 +09001830 // partitionDir is the part of the InstallPath that is automatically determined according to the context.
1831 // For example, it is host/<os>-<arch> for host modules, and target/product/<device>/<partition> for device modules.
1832 partitionDir string
1833
Colin Crossb1692a32021-10-25 15:39:01 -07001834 partition string
1835
Jiyong Park957bcd92020-10-20 18:23:33 +09001836 // makePath indicates whether this path is for Soong (false) or Make (true).
1837 makePath bool
Colin Crossc0e42d52024-02-01 16:42:36 -08001838
1839 fullPath string
Colin Cross70dda7e2019-10-01 22:05:35 -07001840}
1841
Yu Liu467d7c52024-09-18 21:54:44 +00001842type installPathGob struct {
Yu Liu5246a7e2024-10-09 20:04:52 +00001843 BasePath basePath
Yu Liu467d7c52024-09-18 21:54:44 +00001844 SoongOutDir string
1845 PartitionDir string
1846 Partition string
1847 MakePath bool
1848 FullPath string
1849}
Yu Liu26a716d2024-08-30 23:40:32 +00001850
Yu Liu467d7c52024-09-18 21:54:44 +00001851func (p *InstallPath) ToGob() *installPathGob {
1852 return &installPathGob{
Yu Liu5246a7e2024-10-09 20:04:52 +00001853 BasePath: p.basePath,
Yu Liu467d7c52024-09-18 21:54:44 +00001854 SoongOutDir: p.soongOutDir,
1855 PartitionDir: p.partitionDir,
1856 Partition: p.partition,
1857 MakePath: p.makePath,
1858 FullPath: p.fullPath,
1859 }
1860}
1861
1862func (p *InstallPath) FromGob(data *installPathGob) {
Yu Liu5246a7e2024-10-09 20:04:52 +00001863 p.basePath = data.BasePath
Yu Liu467d7c52024-09-18 21:54:44 +00001864 p.soongOutDir = data.SoongOutDir
1865 p.partitionDir = data.PartitionDir
1866 p.partition = data.Partition
1867 p.makePath = data.MakePath
1868 p.fullPath = data.FullPath
1869}
1870
1871func (p InstallPath) GobEncode() ([]byte, error) {
1872 return blueprint.CustomGobEncode[installPathGob](&p)
Yu Liu26a716d2024-08-30 23:40:32 +00001873}
1874
1875func (p *InstallPath) GobDecode(data []byte) error {
Yu Liu467d7c52024-09-18 21:54:44 +00001876 return blueprint.CustomGobDecode[installPathGob](data, p)
Yu Liu26a716d2024-08-30 23:40:32 +00001877}
1878
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001879// Will panic if called from outside a test environment.
1880func ensureTestOnly() {
Martin Stjernholm32312eb2021-03-27 18:54:49 +00001881 if PrefixInList(os.Args, "-test.") {
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001882 return
1883 }
Martin Stjernholm32312eb2021-03-27 18:54:49 +00001884 panic(fmt.Errorf("Not in test. Command line:\n %s", strings.Join(os.Args, "\n ")))
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001885}
1886
1887func (p InstallPath) RelativeToTop() Path {
1888 ensureTestOnly()
Colin Crossc0e42d52024-02-01 16:42:36 -08001889 if p.makePath {
Colin Cross3b1c6842024-07-26 11:52:57 -07001890 p.soongOutDir = testOutDir
Colin Crossc0e42d52024-02-01 16:42:36 -08001891 } else {
Colin Cross3b1c6842024-07-26 11:52:57 -07001892 p.soongOutDir = TestOutSoongDir
Colin Crossc0e42d52024-02-01 16:42:36 -08001893 }
1894 p.fullPath = filepath.Join(p.soongOutDir, p.path)
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001895 return p
1896}
1897
Colin Cross7707b242024-07-26 12:02:36 -07001898func (p InstallPath) WithoutRel() Path {
1899 p.basePath = p.basePath.withoutRel()
1900 return p
1901}
1902
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02001903func (p InstallPath) getSoongOutDir() string {
1904 return p.soongOutDir
Paul Duffin9b478b02019-12-10 13:41:51 +00001905}
1906
Hans MÃ¥nssond3f2bd72020-11-27 12:37:28 +01001907func (p InstallPath) ReplaceExtension(ctx PathContext, ext string) OutputPath {
1908 panic("Not implemented")
1909}
1910
Paul Duffin9b478b02019-12-10 13:41:51 +00001911var _ Path = InstallPath{}
1912var _ WritablePath = InstallPath{}
1913
Colin Cross70dda7e2019-10-01 22:05:35 -07001914func (p InstallPath) writablePath() {}
1915
1916func (p InstallPath) String() string {
Colin Crossc0e42d52024-02-01 16:42:36 -08001917 return p.fullPath
Jiyong Park957bcd92020-10-20 18:23:33 +09001918}
1919
1920// PartitionDir returns the path to the partition where the install path is rooted at. It is
1921// out/soong/target/product/<device>/<partition> for device modules, and out/soong/host/<os>-<arch> for host modules.
1922// The ./soong is dropped if the install path is for Make.
1923func (p InstallPath) PartitionDir() string {
1924 if p.makePath {
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02001925 return filepath.Join(p.soongOutDir, "../", p.partitionDir)
Jiyong Park957bcd92020-10-20 18:23:33 +09001926 } else {
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02001927 return filepath.Join(p.soongOutDir, p.partitionDir)
Jiyong Park957bcd92020-10-20 18:23:33 +09001928 }
Colin Cross70dda7e2019-10-01 22:05:35 -07001929}
1930
Jihoon Kangf78a8902022-09-01 22:47:07 +00001931func (p InstallPath) Partition() string {
1932 return p.partition
1933}
1934
Colin Cross70dda7e2019-10-01 22:05:35 -07001935// Join creates a new InstallPath with paths... joined with the current path. The
1936// provided paths... may not use '..' to escape from the current path.
1937func (p InstallPath) Join(ctx PathContext, paths ...string) InstallPath {
1938 path, err := validatePath(paths...)
1939 if err != nil {
1940 reportPathError(ctx, err)
1941 }
1942 return p.withRel(path)
1943}
1944
1945func (p InstallPath) withRel(rel string) InstallPath {
1946 p.basePath = p.basePath.withRel(rel)
Colin Crossc0e42d52024-02-01 16:42:36 -08001947 p.fullPath = filepath.Join(p.fullPath, rel)
Colin Cross70dda7e2019-10-01 22:05:35 -07001948 return p
1949}
1950
Colin Crossc68db4b2021-11-11 18:59:15 -08001951// Deprecated: ToMakePath is a noop, PathForModuleInstall always returns Make paths when building
1952// embedded in Make.
Colin Crossff6c33d2019-10-02 16:01:35 -07001953func (p InstallPath) ToMakePath() InstallPath {
Jiyong Park957bcd92020-10-20 18:23:33 +09001954 p.makePath = true
Colin Crossff6c33d2019-10-02 16:01:35 -07001955 return p
Colin Cross70dda7e2019-10-01 22:05:35 -07001956}
1957
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001958// PathForModuleInstall returns a Path representing the install path for the
1959// module appended with paths...
Colin Cross70dda7e2019-10-01 22:05:35 -07001960func PathForModuleInstall(ctx ModuleInstallPathContext, pathComponents ...string) InstallPath {
Spandan Das5d1b9292021-06-03 19:36:41 +00001961 os, arch := osAndArch(ctx)
Cole Faust11edf552023-10-13 11:32:14 -07001962 partition := modulePartition(ctx, os.Class == Device)
Cole Faust3b703f32023-10-16 13:30:51 -07001963 return pathForInstall(ctx, os, arch, partition, pathComponents...)
Spandan Das5d1b9292021-06-03 19:36:41 +00001964}
1965
Colin Cross1d0eb7a2021-11-03 14:08:20 -07001966// PathForHostDexInstall returns an InstallPath representing the install path for the
1967// module appended with paths...
1968func PathForHostDexInstall(ctx ModuleInstallPathContext, pathComponents ...string) InstallPath {
Cole Faust3b703f32023-10-16 13:30:51 -07001969 return pathForInstall(ctx, ctx.Config().BuildOS, ctx.Config().BuildArch, "", pathComponents...)
Colin Cross1d0eb7a2021-11-03 14:08:20 -07001970}
1971
Spandan Das5d1b9292021-06-03 19:36:41 +00001972// PathForModuleInPartitionInstall is similar to PathForModuleInstall but partition is provided by the caller
1973func PathForModuleInPartitionInstall(ctx ModuleInstallPathContext, partition string, pathComponents ...string) InstallPath {
1974 os, arch := osAndArch(ctx)
Cole Faust3b703f32023-10-16 13:30:51 -07001975 return pathForInstall(ctx, os, arch, partition, pathComponents...)
Spandan Das5d1b9292021-06-03 19:36:41 +00001976}
1977
1978func osAndArch(ctx ModuleInstallPathContext) (OsType, ArchType) {
Colin Cross6e359402020-02-10 15:29:54 -08001979 os := ctx.Os()
Jiyong Park87788b52020-09-01 12:37:45 +09001980 arch := ctx.Arch().ArchType
1981 forceOS, forceArch := ctx.InstallForceOS()
1982 if forceOS != nil {
Colin Cross6e359402020-02-10 15:29:54 -08001983 os = *forceOS
1984 }
Jiyong Park87788b52020-09-01 12:37:45 +09001985 if forceArch != nil {
1986 arch = *forceArch
1987 }
Spandan Das5d1b9292021-06-03 19:36:41 +00001988 return os, arch
1989}
Colin Cross609c49a2020-02-13 13:20:11 -08001990
Colin Crossc0e42d52024-02-01 16:42:36 -08001991func pathForPartitionInstallDir(ctx PathContext, partition, partitionPath string, makePath bool) InstallPath {
1992 fullPath := ctx.Config().SoongOutDir()
1993 if makePath {
1994 // Make path starts with out/ instead of out/soong.
1995 fullPath = filepath.Join(fullPath, "../", partitionPath)
1996 } else {
1997 fullPath = filepath.Join(fullPath, partitionPath)
1998 }
1999
2000 return InstallPath{
2001 basePath: basePath{partitionPath, ""},
2002 soongOutDir: ctx.Config().soongOutDir,
2003 partitionDir: partitionPath,
2004 partition: partition,
2005 makePath: makePath,
2006 fullPath: fullPath,
2007 }
2008}
2009
Cole Faust3b703f32023-10-16 13:30:51 -07002010func pathForInstall(ctx PathContext, os OsType, arch ArchType, partition string,
Colin Cross609c49a2020-02-13 13:20:11 -08002011 pathComponents ...string) InstallPath {
2012
Jiyong Park97859152023-02-14 17:05:48 +09002013 var partitionPaths []string
Colin Cross609c49a2020-02-13 13:20:11 -08002014
Colin Cross6e359402020-02-10 15:29:54 -08002015 if os.Class == Device {
Jiyong Park97859152023-02-14 17:05:48 +09002016 partitionPaths = []string{"target", "product", ctx.Config().DeviceName(), partition}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07002017 } else {
Jiyong Park87788b52020-09-01 12:37:45 +09002018 osName := os.String()
Colin Crossa9b2aac2022-06-15 17:25:51 -07002019 if os == Linux {
Jiyong Park87788b52020-09-01 12:37:45 +09002020 // instead of linux_glibc
2021 osName = "linux"
Dan Willemsen866b5632017-09-22 12:28:24 -07002022 }
Colin Crossa9b2aac2022-06-15 17:25:51 -07002023 if os == LinuxMusl && ctx.Config().UseHostMusl() {
2024 // When using musl instead of glibc, use "linux" instead of "linux_musl". When cross
2025 // compiling we will still use "linux_musl".
2026 osName = "linux"
2027 }
2028
Jiyong Park87788b52020-09-01 12:37:45 +09002029 // SOONG_HOST_OUT is set to out/host/$(HOST_OS)-$(HOST_PREBUILT_ARCH)
2030 // and HOST_PREBUILT_ARCH is forcibly set to x86 even on x86_64 hosts. We don't seem
2031 // to have a plan to fix it (see the comment in build/make/core/envsetup.mk).
2032 // Let's keep using x86 for the existing cases until we have a need to support
2033 // other architectures.
2034 archName := arch.String()
2035 if os.Class == Host && (arch == X86_64 || arch == Common) {
2036 archName = "x86"
2037 }
Jiyong Park97859152023-02-14 17:05:48 +09002038 partitionPaths = []string{"host", osName + "-" + archName, partition}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07002039 }
Colin Cross70dda7e2019-10-01 22:05:35 -07002040
Jiyong Park97859152023-02-14 17:05:48 +09002041 partitionPath, err := validatePath(partitionPaths...)
Colin Cross70dda7e2019-10-01 22:05:35 -07002042 if err != nil {
2043 reportPathError(ctx, err)
2044 }
Colin Crossff6c33d2019-10-02 16:01:35 -07002045
Colin Crossc0e42d52024-02-01 16:42:36 -08002046 base := pathForPartitionInstallDir(ctx, partition, partitionPath, ctx.Config().KatiEnabled())
Jiyong Park957bcd92020-10-20 18:23:33 +09002047 return base.Join(ctx, pathComponents...)
Dan Willemsen34cc69e2015-09-23 15:26:20 -07002048}
2049
Spandan Dasf280b232024-04-04 21:25:51 +00002050func PathForNdkInstall(ctx PathContext, paths ...string) OutputPath {
2051 return PathForOutput(ctx, append([]string{"ndk"}, paths...)...)
Nicolas Geoffray1228e9c2020-02-27 13:45:35 +00002052}
2053
2054func PathForMainlineSdksInstall(ctx PathContext, paths ...string) InstallPath {
Spandan Dasf280b232024-04-04 21:25:51 +00002055 base := pathForPartitionInstallDir(ctx, "", "mainline-sdks", false)
2056 return base.Join(ctx, paths...)
Nicolas Geoffray1228e9c2020-02-27 13:45:35 +00002057}
2058
Colin Cross70dda7e2019-10-01 22:05:35 -07002059func InstallPathToOnDevicePath(ctx PathContext, path InstallPath) string {
Colin Crossb1692a32021-10-25 15:39:01 -07002060 rel := Rel(ctx, strings.TrimSuffix(path.PartitionDir(), path.partition), path.String())
Colin Cross43f08db2018-11-12 10:13:39 -08002061 return "/" + rel
2062}
2063
Cole Faust11edf552023-10-13 11:32:14 -07002064func modulePartition(ctx ModuleInstallPathContext, device bool) string {
Colin Cross43f08db2018-11-12 10:13:39 -08002065 var partition string
Colin Cross6e359402020-02-10 15:29:54 -08002066 if ctx.InstallInTestcases() {
2067 // "testcases" install directory can be used for host or device modules.
Jaewoong Jung0949f312019-09-11 10:25:18 -07002068 partition = "testcases"
Cole Faust11edf552023-10-13 11:32:14 -07002069 } else if device {
Colin Cross6e359402020-02-10 15:29:54 -08002070 if ctx.InstallInData() {
2071 partition = "data"
2072 } else if ctx.InstallInRamdisk() {
2073 if ctx.DeviceConfig().BoardUsesRecoveryAsBoot() {
2074 partition = "recovery/root/first_stage_ramdisk"
2075 } else {
2076 partition = "ramdisk"
2077 }
2078 if !ctx.InstallInRoot() {
2079 partition += "/system"
2080 }
Yifan Hong60e0cfb2020-10-21 15:17:56 -07002081 } else if ctx.InstallInVendorRamdisk() {
Yifan Hong39143a92020-10-26 12:43:12 -07002082 // The module is only available after switching root into
2083 // /first_stage_ramdisk. To expose the module before switching root
2084 // on a device without a dedicated recovery partition, install the
2085 // recovery variant.
Yifan Hongdd8dacc2020-10-21 15:40:17 -07002086 if ctx.DeviceConfig().BoardMoveRecoveryResourcesToVendorBoot() {
Petri Gyntherac229562021-03-02 23:44:02 -08002087 partition = "vendor_ramdisk/first_stage_ramdisk"
Yifan Hongdd8dacc2020-10-21 15:40:17 -07002088 } else {
Petri Gyntherac229562021-03-02 23:44:02 -08002089 partition = "vendor_ramdisk"
Yifan Hongdd8dacc2020-10-21 15:40:17 -07002090 }
2091 if !ctx.InstallInRoot() {
2092 partition += "/system"
2093 }
Inseob Kim08758f02021-04-08 21:13:22 +09002094 } else if ctx.InstallInDebugRamdisk() {
2095 partition = "debug_ramdisk"
Colin Cross6e359402020-02-10 15:29:54 -08002096 } else if ctx.InstallInRecovery() {
2097 if ctx.InstallInRoot() {
2098 partition = "recovery/root"
2099 } else {
2100 // the layout of recovery partion is the same as that of system partition
2101 partition = "recovery/root/system"
2102 }
Colin Crossea30d852023-11-29 16:00:16 -08002103 } else if ctx.SocSpecific() || ctx.InstallInVendor() {
Colin Cross6e359402020-02-10 15:29:54 -08002104 partition = ctx.DeviceConfig().VendorPath()
Colin Crossea30d852023-11-29 16:00:16 -08002105 } else if ctx.DeviceSpecific() || ctx.InstallInOdm() {
Colin Cross6e359402020-02-10 15:29:54 -08002106 partition = ctx.DeviceConfig().OdmPath()
Colin Crossea30d852023-11-29 16:00:16 -08002107 } else if ctx.ProductSpecific() || ctx.InstallInProduct() {
Colin Cross6e359402020-02-10 15:29:54 -08002108 partition = ctx.DeviceConfig().ProductPath()
2109 } else if ctx.SystemExtSpecific() {
2110 partition = ctx.DeviceConfig().SystemExtPath()
2111 } else if ctx.InstallInRoot() {
2112 partition = "root"
Yifan Hong82db7352020-01-21 16:12:26 -08002113 } else {
Colin Cross6e359402020-02-10 15:29:54 -08002114 partition = "system"
Yifan Hong82db7352020-01-21 16:12:26 -08002115 }
Colin Cross6e359402020-02-10 15:29:54 -08002116 if ctx.InstallInSanitizerDir() {
2117 partition = "data/asan/" + partition
Yifan Hong82db7352020-01-21 16:12:26 -08002118 }
Colin Cross43f08db2018-11-12 10:13:39 -08002119 }
2120 return partition
2121}
2122
Colin Cross609c49a2020-02-13 13:20:11 -08002123type InstallPaths []InstallPath
2124
2125// Paths returns the InstallPaths as a Paths
2126func (p InstallPaths) Paths() Paths {
2127 if p == nil {
2128 return nil
2129 }
2130 ret := make(Paths, len(p))
2131 for i, path := range p {
2132 ret[i] = path
2133 }
2134 return ret
2135}
2136
2137// Strings returns the string forms of the install paths.
2138func (p InstallPaths) Strings() []string {
2139 if p == nil {
2140 return nil
2141 }
2142 ret := make([]string, len(p))
2143 for i, path := range p {
2144 ret[i] = path.String()
2145 }
2146 return ret
2147}
2148
Jingwen Chen24d0c562023-02-07 09:29:36 +00002149// validatePathInternal ensures that a path does not leave its component, and
2150// optionally doesn't contain Ninja variables.
2151func validatePathInternal(allowNinjaVariables bool, pathComponents ...string) (string, error) {
Colin Crossbf9ed3f2023-10-24 14:17:03 -07002152 initialEmpty := 0
2153 finalEmpty := 0
2154 for i, path := range pathComponents {
Jingwen Chen24d0c562023-02-07 09:29:36 +00002155 if !allowNinjaVariables && strings.Contains(path, "$") {
2156 return "", fmt.Errorf("Path contains invalid character($): %s", path)
2157 }
2158
Dan Willemsen80a7c2a2015-12-21 14:57:11 -08002159 path := filepath.Clean(path)
2160 if path == ".." || strings.HasPrefix(path, "../") || strings.HasPrefix(path, "/") {
Colin Cross1ccfcc32018-02-22 13:54:26 -08002161 return "", fmt.Errorf("Path is outside directory: %s", path)
Dan Willemsen80a7c2a2015-12-21 14:57:11 -08002162 }
Colin Crossbf9ed3f2023-10-24 14:17:03 -07002163
2164 if i == initialEmpty && pathComponents[i] == "" {
2165 initialEmpty++
2166 }
2167 if i == finalEmpty && pathComponents[len(pathComponents)-1-i] == "" {
2168 finalEmpty++
2169 }
Dan Willemsen80a7c2a2015-12-21 14:57:11 -08002170 }
Colin Crossbf9ed3f2023-10-24 14:17:03 -07002171 // Optimization: filepath.Join("foo", "") returns a newly allocated copy
2172 // of "foo", while filepath.Join("foo") does not. Strip out any empty
2173 // path components.
2174 if initialEmpty == len(pathComponents) {
2175 return "", nil
2176 }
2177 nonEmptyPathComponents := pathComponents[initialEmpty : len(pathComponents)-finalEmpty]
Dan Willemsen34cc69e2015-09-23 15:26:20 -07002178 // TODO: filepath.Join isn't necessarily correct with embedded ninja
2179 // variables. '..' may remove the entire ninja variable, even if it
2180 // will be expanded to multiple nested directories.
Colin Crossbf9ed3f2023-10-24 14:17:03 -07002181 return filepath.Join(nonEmptyPathComponents...), nil
Dan Willemsen34cc69e2015-09-23 15:26:20 -07002182}
2183
Jingwen Chen24d0c562023-02-07 09:29:36 +00002184// validateSafePath validates a path that we trust (may contain ninja
2185// variables). Ensures that each path component does not attempt to leave its
2186// component. Returns a joined version of each path component.
2187func validateSafePath(pathComponents ...string) (string, error) {
2188 return validatePathInternal(true, pathComponents...)
2189}
2190
Dan Willemsen80a7c2a2015-12-21 14:57:11 -08002191// validatePath validates that a path does not include ninja variables, and that
2192// each path component does not attempt to leave its component. Returns a joined
2193// version of each path component.
Colin Cross1ccfcc32018-02-22 13:54:26 -08002194func validatePath(pathComponents ...string) (string, error) {
Jingwen Chen24d0c562023-02-07 09:29:36 +00002195 return validatePathInternal(false, pathComponents...)
Colin Cross6e18ca42015-07-14 18:55:36 -07002196}
Colin Cross5b529592017-05-09 13:34:34 -07002197
Colin Cross0875c522017-11-28 17:34:01 -08002198func PathForPhony(ctx PathContext, phony string) WritablePath {
2199 if strings.ContainsAny(phony, "$/") {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01002200 ReportPathErrorf(ctx, "Phony target contains invalid character ($ or /): %s", phony)
Colin Cross0875c522017-11-28 17:34:01 -08002201 }
Paul Duffin74abc5d2021-03-24 09:24:59 +00002202 return PhonyPath{basePath{phony, ""}}
Colin Cross0875c522017-11-28 17:34:01 -08002203}
2204
Colin Cross74e3fe42017-12-11 15:51:44 -08002205type PhonyPath struct {
2206 basePath
2207}
2208
2209func (p PhonyPath) writablePath() {}
2210
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02002211func (p PhonyPath) getSoongOutDir() string {
Paul Duffind65c58b2021-03-24 09:22:07 +00002212 // A phone path cannot contain any / so cannot be relative to the build directory.
2213 return ""
Paul Duffin9b478b02019-12-10 13:41:51 +00002214}
2215
Paul Duffin85d8f0d2021-03-24 10:18:18 +00002216func (p PhonyPath) RelativeToTop() Path {
2217 ensureTestOnly()
2218 // A phony path cannot contain any / so does not have a build directory so switching to a new
2219 // build directory has no effect so just return this path.
2220 return p
2221}
2222
Colin Cross7707b242024-07-26 12:02:36 -07002223func (p PhonyPath) WithoutRel() Path {
2224 p.basePath = p.basePath.withoutRel()
2225 return p
2226}
2227
Hans MÃ¥nssond3f2bd72020-11-27 12:37:28 +01002228func (p PhonyPath) ReplaceExtension(ctx PathContext, ext string) OutputPath {
2229 panic("Not implemented")
2230}
2231
Colin Cross74e3fe42017-12-11 15:51:44 -08002232var _ Path = PhonyPath{}
2233var _ WritablePath = PhonyPath{}
2234
Colin Cross5b529592017-05-09 13:34:34 -07002235type testPath struct {
2236 basePath
2237}
2238
Paul Duffin85d8f0d2021-03-24 10:18:18 +00002239func (p testPath) RelativeToTop() Path {
2240 ensureTestOnly()
2241 return p
2242}
2243
Colin Cross7707b242024-07-26 12:02:36 -07002244func (p testPath) WithoutRel() Path {
2245 p.basePath = p.basePath.withoutRel()
2246 return p
2247}
2248
Colin Cross5b529592017-05-09 13:34:34 -07002249func (p testPath) String() string {
2250 return p.path
2251}
2252
Paul Duffin85d8f0d2021-03-24 10:18:18 +00002253var _ Path = testPath{}
2254
Colin Cross40e33732019-02-15 11:08:35 -08002255// PathForTesting returns a Path constructed from joining the elements of paths with '/'. It should only be used from
2256// within tests.
Colin Cross5b529592017-05-09 13:34:34 -07002257func PathForTesting(paths ...string) Path {
Colin Cross1ccfcc32018-02-22 13:54:26 -08002258 p, err := validateSafePath(paths...)
2259 if err != nil {
2260 panic(err)
2261 }
Colin Cross5b529592017-05-09 13:34:34 -07002262 return testPath{basePath{path: p, rel: p}}
2263}
2264
Sam Delmerico2351eac2022-05-24 17:10:02 +00002265func PathForTestingWithRel(path, rel string) Path {
2266 p, err := validateSafePath(path, rel)
2267 if err != nil {
2268 panic(err)
2269 }
2270 r, err := validatePath(rel)
2271 if err != nil {
2272 panic(err)
2273 }
2274 return testPath{basePath{path: p, rel: r}}
2275}
2276
Colin Cross40e33732019-02-15 11:08:35 -08002277// PathsForTesting returns a Path constructed from each element in strs. It should only be used from within tests.
2278func PathsForTesting(strs ...string) Paths {
Colin Cross5b529592017-05-09 13:34:34 -07002279 p := make(Paths, len(strs))
2280 for i, s := range strs {
2281 p[i] = PathForTesting(s)
2282 }
2283
2284 return p
2285}
Colin Cross43f08db2018-11-12 10:13:39 -08002286
Colin Cross40e33732019-02-15 11:08:35 -08002287type testPathContext struct {
2288 config Config
Colin Cross40e33732019-02-15 11:08:35 -08002289}
2290
Colin Cross40e33732019-02-15 11:08:35 -08002291func (x *testPathContext) Config() Config { return x.config }
2292func (x *testPathContext) AddNinjaFileDeps(...string) {}
2293
2294// PathContextForTesting returns a PathContext that can be used in tests, for example to create an OutputPath with
2295// PathForOutput.
Colin Cross98be1bb2019-12-13 20:41:13 -08002296func PathContextForTesting(config Config) PathContext {
Colin Cross40e33732019-02-15 11:08:35 -08002297 return &testPathContext{
2298 config: config,
Colin Cross40e33732019-02-15 11:08:35 -08002299 }
2300}
2301
Ulya Trafimovichccc8c852020-10-14 11:29:07 +01002302type testModuleInstallPathContext struct {
2303 baseModuleContext
2304
2305 inData bool
2306 inTestcases bool
2307 inSanitizerDir bool
2308 inRamdisk bool
2309 inVendorRamdisk bool
Inseob Kim08758f02021-04-08 21:13:22 +09002310 inDebugRamdisk bool
Ulya Trafimovichccc8c852020-10-14 11:29:07 +01002311 inRecovery bool
2312 inRoot bool
Colin Crossea30d852023-11-29 16:00:16 -08002313 inOdm bool
2314 inProduct bool
2315 inVendor bool
Ulya Trafimovichccc8c852020-10-14 11:29:07 +01002316 forceOS *OsType
2317 forceArch *ArchType
2318}
2319
2320func (m testModuleInstallPathContext) Config() Config {
2321 return m.baseModuleContext.config
2322}
2323
2324func (testModuleInstallPathContext) AddNinjaFileDeps(deps ...string) {}
2325
2326func (m testModuleInstallPathContext) InstallInData() bool {
2327 return m.inData
2328}
2329
2330func (m testModuleInstallPathContext) InstallInTestcases() bool {
2331 return m.inTestcases
2332}
2333
2334func (m testModuleInstallPathContext) InstallInSanitizerDir() bool {
2335 return m.inSanitizerDir
2336}
2337
2338func (m testModuleInstallPathContext) InstallInRamdisk() bool {
2339 return m.inRamdisk
2340}
2341
2342func (m testModuleInstallPathContext) InstallInVendorRamdisk() bool {
2343 return m.inVendorRamdisk
2344}
2345
Inseob Kim08758f02021-04-08 21:13:22 +09002346func (m testModuleInstallPathContext) InstallInDebugRamdisk() bool {
2347 return m.inDebugRamdisk
2348}
2349
Ulya Trafimovichccc8c852020-10-14 11:29:07 +01002350func (m testModuleInstallPathContext) InstallInRecovery() bool {
2351 return m.inRecovery
2352}
2353
2354func (m testModuleInstallPathContext) InstallInRoot() bool {
2355 return m.inRoot
2356}
2357
Colin Crossea30d852023-11-29 16:00:16 -08002358func (m testModuleInstallPathContext) InstallInOdm() bool {
2359 return m.inOdm
2360}
2361
2362func (m testModuleInstallPathContext) InstallInProduct() bool {
2363 return m.inProduct
2364}
2365
2366func (m testModuleInstallPathContext) InstallInVendor() bool {
2367 return m.inVendor
2368}
2369
Ulya Trafimovichccc8c852020-10-14 11:29:07 +01002370func (m testModuleInstallPathContext) InstallForceOS() (*OsType, *ArchType) {
2371 return m.forceOS, m.forceArch
2372}
2373
2374// Construct a minimal ModuleInstallPathContext for testing. Note that baseModuleContext is
2375// default-initialized, which leaves blueprint.baseModuleContext set to nil, so methods that are
2376// delegated to it will panic.
2377func ModuleInstallPathContextForTesting(config Config) ModuleInstallPathContext {
2378 ctx := &testModuleInstallPathContext{}
2379 ctx.config = config
2380 ctx.os = Android
2381 return ctx
2382}
2383
Colin Cross43f08db2018-11-12 10:13:39 -08002384// Rel performs the same function as filepath.Rel, but reports errors to a PathContext, and reports an error if
2385// targetPath is not inside basePath.
2386func Rel(ctx PathContext, basePath string, targetPath string) string {
2387 rel, isRel := MaybeRel(ctx, basePath, targetPath)
2388 if !isRel {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01002389 ReportPathErrorf(ctx, "path %q is not under path %q", targetPath, basePath)
Colin Cross43f08db2018-11-12 10:13:39 -08002390 return ""
2391 }
2392 return rel
2393}
2394
2395// MaybeRel performs the same function as filepath.Rel, but reports errors to a PathContext, and returns false if
2396// targetPath is not inside basePath.
2397func MaybeRel(ctx PathContext, basePath string, targetPath string) (string, bool) {
Dan Willemsen633c5022019-04-12 11:11:38 -07002398 rel, isRel, err := maybeRelErr(basePath, targetPath)
2399 if err != nil {
2400 reportPathError(ctx, err)
2401 }
2402 return rel, isRel
2403}
2404
2405func maybeRelErr(basePath string, targetPath string) (string, bool, error) {
Colin Cross43f08db2018-11-12 10:13:39 -08002406 // filepath.Rel returns an error if one path is absolute and the other is not, handle that case first.
2407 if filepath.IsAbs(basePath) != filepath.IsAbs(targetPath) {
Dan Willemsen633c5022019-04-12 11:11:38 -07002408 return "", false, nil
Colin Cross43f08db2018-11-12 10:13:39 -08002409 }
2410 rel, err := filepath.Rel(basePath, targetPath)
2411 if err != nil {
Dan Willemsen633c5022019-04-12 11:11:38 -07002412 return "", false, err
Colin Cross43f08db2018-11-12 10:13:39 -08002413 } else if rel == ".." || strings.HasPrefix(rel, "../") || strings.HasPrefix(rel, "/") {
Dan Willemsen633c5022019-04-12 11:11:38 -07002414 return "", false, nil
Colin Cross43f08db2018-11-12 10:13:39 -08002415 }
Dan Willemsen633c5022019-04-12 11:11:38 -07002416 return rel, true, nil
Colin Cross43f08db2018-11-12 10:13:39 -08002417}
Colin Cross988414c2020-01-11 01:11:46 +00002418
2419// Writes a file to the output directory. Attempting to write directly to the output directory
2420// will fail due to the sandbox of the soong_build process.
Chris Parsons1a12d032023-02-06 22:37:41 -05002421// Only writes the file if the file doesn't exist or if it has different contents, to prevent
2422// updating the timestamp if no changes would be made. (This is better for incremental
2423// performance.)
Colin Cross988414c2020-01-11 01:11:46 +00002424func WriteFileToOutputDir(path WritablePath, data []byte, perm os.FileMode) error {
Colin Crossd6421132021-11-09 12:32:34 -08002425 absPath := absolutePath(path.String())
2426 err := os.MkdirAll(filepath.Dir(absPath), 0777)
2427 if err != nil {
2428 return err
2429 }
Chris Parsons1a12d032023-02-06 22:37:41 -05002430 return pathtools.WriteFileIfChanged(absPath, data, perm)
Colin Cross988414c2020-01-11 01:11:46 +00002431}
2432
Liz Kammer2dd9ca42020-11-25 16:06:39 -08002433func RemoveAllOutputDir(path WritablePath) error {
2434 return os.RemoveAll(absolutePath(path.String()))
2435}
2436
2437func CreateOutputDirIfNonexistent(path WritablePath, perm os.FileMode) error {
2438 dir := absolutePath(path.String())
Liz Kammer09f947d2021-05-12 14:51:49 -04002439 return createDirIfNonexistent(dir, perm)
2440}
2441
2442func createDirIfNonexistent(dir string, perm os.FileMode) error {
Liz Kammer2dd9ca42020-11-25 16:06:39 -08002443 if _, err := os.Stat(dir); os.IsNotExist(err) {
2444 return os.MkdirAll(dir, os.ModePerm)
2445 } else {
2446 return err
2447 }
2448}
2449
Jingwen Chen78257e52021-05-21 02:34:24 +00002450// absolutePath is deliberately private so that Soong's Go plugins can't use it to find and
2451// read arbitrary files without going through the methods in the current package that track
2452// dependencies.
Colin Cross988414c2020-01-11 01:11:46 +00002453func absolutePath(path string) string {
2454 if filepath.IsAbs(path) {
2455 return path
2456 }
2457 return filepath.Join(absSrcDir, path)
2458}
Chris Parsons216e10a2020-07-09 17:12:52 -04002459
2460// A DataPath represents the path of a file to be used as data, for example
2461// a test library to be installed alongside a test.
2462// The data file should be installed (copied from `<SrcPath>`) to
2463// `<install_root>/<RelativeInstallPath>/<filename>`, or
2464// `<install_root>/<filename>` if RelativeInstallPath is empty.
2465type DataPath struct {
2466 // The path of the data file that should be copied into the data directory
2467 SrcPath Path
2468 // The install path of the data file, relative to the install root.
2469 RelativeInstallPath string
Colin Cross5c1d5fb2023-11-15 12:39:40 -08002470 // If WithoutRel is true, use SrcPath.Base() instead of SrcPath.Rel() as the filename.
2471 WithoutRel bool
Chris Parsons216e10a2020-07-09 17:12:52 -04002472}
Colin Crossdcf71b22021-02-01 13:59:03 -08002473
Colin Crossd442a0e2023-11-16 11:19:26 -08002474func (d *DataPath) ToRelativeInstallPath() string {
2475 relPath := d.SrcPath.Rel()
Colin Cross5c1d5fb2023-11-15 12:39:40 -08002476 if d.WithoutRel {
2477 relPath = d.SrcPath.Base()
2478 }
Colin Crossd442a0e2023-11-16 11:19:26 -08002479 if d.RelativeInstallPath != "" {
2480 relPath = filepath.Join(d.RelativeInstallPath, relPath)
2481 }
2482 return relPath
2483}
2484
Colin Crossdcf71b22021-02-01 13:59:03 -08002485// PathsIfNonNil returns a Paths containing only the non-nil input arguments.
2486func PathsIfNonNil(paths ...Path) Paths {
2487 if len(paths) == 0 {
2488 // Fast path for empty argument list
2489 return nil
2490 } else if len(paths) == 1 {
2491 // Fast path for a single argument
2492 if paths[0] != nil {
2493 return paths
2494 } else {
2495 return nil
2496 }
2497 }
2498 ret := make(Paths, 0, len(paths))
2499 for _, path := range paths {
2500 if path != nil {
2501 ret = append(ret, path)
2502 }
2503 }
2504 if len(ret) == 0 {
2505 return nil
2506 }
2507 return ret
2508}
Chris Wailesb2703ad2021-07-30 13:25:42 -07002509
2510var thirdPartyDirPrefixExceptions = []*regexp.Regexp{
2511 regexp.MustCompile("^vendor/[^/]*google[^/]*/"),
2512 regexp.MustCompile("^hardware/google/"),
2513 regexp.MustCompile("^hardware/interfaces/"),
2514 regexp.MustCompile("^hardware/libhardware[^/]*/"),
2515 regexp.MustCompile("^hardware/ril/"),
2516}
2517
2518func IsThirdPartyPath(path string) bool {
2519 thirdPartyDirPrefixes := []string{"external/", "vendor/", "hardware/"}
2520
2521 if HasAnyPrefix(path, thirdPartyDirPrefixes) {
2522 for _, prefix := range thirdPartyDirPrefixExceptions {
2523 if prefix.MatchString(path) {
2524 return false
2525 }
2526 }
2527 return true
2528 }
2529 return false
2530}