blob: 339fb2bd93402d9d7b613427a68bc3fcf03fecbb [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 Kim93036a52024-10-25 17:02:21 +0900553type directoryPath struct {
554 basePath
555}
556
557func (d *directoryPath) String() string {
558 return d.basePath.String()
559}
560
561func (d *directoryPath) base() basePath {
562 return d.basePath
563}
564
565// DirectoryPath represents a source path for directories. Incompatible with Path by design.
566type DirectoryPath interface {
567 String() string
568 base() basePath
569}
570
571var _ DirectoryPath = (*directoryPath)(nil)
572
573type DirectoryPaths []DirectoryPath
574
Inseob Kim76e19852024-10-10 17:57:22 +0900575// DirectoryPathsForModuleSrcExcludes returns a Paths{} containing the resolved references in
576// directory paths. Elements of paths are resolved as:
577// - filepath, relative to local module directory, resolves as a filepath relative to the local
578// source directory
579// - other modules using the ":name" syntax. These modules must implement DirProvider.
Inseob Kim93036a52024-10-25 17:02:21 +0900580func DirectoryPathsForModuleSrc(ctx ModuleMissingDepsPathContext, paths []string) DirectoryPaths {
581 var ret DirectoryPaths
Inseob Kim76e19852024-10-10 17:57:22 +0900582
583 for _, path := range paths {
584 if m, t := SrcIsModuleWithTag(path); m != "" {
585 module := GetModuleFromPathDep(ctx, m, t)
586 if module == nil {
587 ctx.ModuleErrorf(`missing dependency on %q, is the property annotated with android:"path"?`, m)
588 continue
589 }
590 if t != "" {
591 ctx.ModuleErrorf("DirProvider dependency %q does not support the tag %q", module, t)
592 continue
593 }
594 mctx, ok := ctx.(OtherModuleProviderContext)
595 if !ok {
596 panic(fmt.Errorf("%s is not an OtherModuleProviderContext", ctx))
597 }
598 if dirProvider, ok := OtherModuleProvider(mctx, module, DirProvider); ok {
599 ret = append(ret, dirProvider.Dirs...)
600 } else {
601 ReportPathErrorf(ctx, "module %q does not implement DirProvider", module)
602 }
603 } else {
604 p := pathForModuleSrc(ctx, path)
605 if isDir, err := ctx.Config().fs.IsDir(p.String()); err != nil {
606 ReportPathErrorf(ctx, "%s: %s", p, err.Error())
607 } else if !isDir {
608 ReportPathErrorf(ctx, "module directory path %q is not a directory", p)
609 } else {
Inseob Kim93036a52024-10-25 17:02:21 +0900610 ret = append(ret, &directoryPath{basePath{path: p.path, rel: p.rel}})
Inseob Kim76e19852024-10-10 17:57:22 +0900611 }
612 }
613 }
614
Inseob Kim93036a52024-10-25 17:02:21 +0900615 seen := make(map[DirectoryPath]bool, len(ret))
Inseob Kim76e19852024-10-10 17:57:22 +0900616 for _, path := range ret {
617 if seen[path] {
618 ReportPathErrorf(ctx, "duplicated path %q", path)
619 }
620 seen[path] = true
621 }
622 return ret
623}
624
Ulya Trafimovich4d2eeed2019-11-08 10:54:21 +0000625// OutputPaths is a slice of OutputPath objects, with helpers to operate on the collection.
626type OutputPaths []OutputPath
627
628// Paths returns the OutputPaths as a Paths
629func (p OutputPaths) Paths() Paths {
630 if p == nil {
631 return nil
632 }
633 ret := make(Paths, len(p))
634 for i, path := range p {
635 ret[i] = path
636 }
637 return ret
638}
639
640// Strings returns the string forms of the writable paths.
641func (p OutputPaths) Strings() []string {
642 if p == nil {
643 return nil
644 }
645 ret := make([]string, len(p))
646 for i, path := range p {
647 ret[i] = path.String()
648 }
649 return ret
650}
651
Liz Kammera830f3a2020-11-10 10:50:34 -0800652// Expands Paths to a SourceFileProducer or OutputFileProducer module dependency referenced via ":name" or ":name{.tag}" syntax.
653// If the dependency is not found, a missingErrorDependency is returned.
654// If the module dependency is not a SourceFileProducer or OutputFileProducer, appropriate errors will be returned.
655func getPathsFromModuleDep(ctx ModuleWithDepsPathContext, path, moduleName, tag string) (Paths, error) {
Paul Duffind5cf92e2021-07-09 17:38:55 +0100656 module := GetModuleFromPathDep(ctx, moduleName, tag)
Liz Kammera830f3a2020-11-10 10:50:34 -0800657 if module == nil {
658 return nil, missingDependencyError{[]string{moduleName}}
659 }
Cole Fausta963b942024-04-11 17:43:00 -0700660 if aModule, ok := module.(Module); ok && !aModule.Enabled(ctx) {
Colin Crossfa65cee2021-03-22 17:05:59 -0700661 return nil, missingDependencyError{[]string{moduleName}}
662 }
mrziwange6c85812024-05-22 14:36:09 -0700663 outputFiles, err := outputFilesForModule(ctx, module, tag)
664 if outputFiles != nil && err == nil {
665 return outputFiles, nil
Liz Kammera830f3a2020-11-10 10:50:34 -0800666 } else {
mrziwange6c85812024-05-22 14:36:09 -0700667 return nil, err
Liz Kammera830f3a2020-11-10 10:50:34 -0800668 }
669}
670
Paul Duffind5cf92e2021-07-09 17:38:55 +0100671// GetModuleFromPathDep will return the module that was added as a dependency automatically for
672// properties tagged with `android:"path"` or manually using ExtractSourceDeps or
673// ExtractSourcesDeps.
674//
675// The moduleName and tag supplied to this should be the values returned from SrcIsModuleWithTag.
676// Or, if no tag is expected then the moduleName should be the value returned by SrcIsModule and
677// the tag must be "".
678//
679// If tag is "" then the returned module will be the dependency that was added for ":moduleName".
680// Otherwise, it is the dependency that was added for ":moduleName{tag}".
Paul Duffind5cf92e2021-07-09 17:38:55 +0100681func GetModuleFromPathDep(ctx ModuleWithDepsPathContext, moduleName, tag string) blueprint.Module {
Paul Duffin40131a32021-07-09 17:10:35 +0100682 var found blueprint.Module
683 // The sourceOrOutputDepTag uniquely identifies the module dependency as it contains both the
684 // module name and the tag. Dependencies added automatically for properties tagged with
685 // `android:"path"` are deduped so are guaranteed to be unique. It is possible for duplicate
686 // dependencies to be added manually using ExtractSourcesDeps or ExtractSourceDeps but even then
687 // it will always be the case that the dependencies will be identical, i.e. the same tag and same
688 // moduleName referring to the same dependency module.
689 //
690 // It does not matter whether the moduleName is a fully qualified name or if the module
691 // dependency is a prebuilt module. All that matters is the same information is supplied to
692 // create the tag here as was supplied to create the tag when the dependency was added so that
693 // this finds the matching dependency module.
694 expectedTag := sourceOrOutputDepTag(moduleName, tag)
Colin Cross648daea2024-09-12 14:35:29 -0700695 ctx.VisitDirectDeps(func(module Module) {
Paul Duffin40131a32021-07-09 17:10:35 +0100696 depTag := ctx.OtherModuleDependencyTag(module)
697 if depTag == expectedTag {
698 found = module
699 }
700 })
701 return found
Paul Duffind5cf92e2021-07-09 17:38:55 +0100702}
703
Liz Kammer620dea62021-04-14 17:36:10 -0400704// PathsAndMissingDepsForModuleSrcExcludes returns a Paths{} containing the resolved references in
705// paths, minus those listed in excludes. Elements of paths and excludes are resolved as:
Colin Crossd079e0b2022-08-16 10:27:33 -0700706// - filepath, relative to local module directory, resolves as a filepath relative to the local
707// source directory
708// - glob, relative to the local module directory, resolves as filepath(s), relative to the local
709// source directory. Not valid in excludes.
710// - other modules using the ":name{.tag}" syntax. These modules must implement SourceFileProducer
mrziwangd38e63d2024-07-15 13:43:37 -0700711// or set the OutputFilesProvider. These resolve as a filepath to an output filepath or generated
712// source filepath.
Colin Crossd079e0b2022-08-16 10:27:33 -0700713//
Liz Kammer620dea62021-04-14 17:36:10 -0400714// and a list of the module names of missing module dependencies are returned as the second return.
715// Properties passed as the paths argument must have been annotated with struct tag
Colin Cross41955e82019-05-29 14:40:35 -0700716// `android:"path"` so that dependencies on SourceFileProducer modules will have already been handled by the
Spandan Das950091c2023-07-19 22:26:37 +0000717// pathdeps mutator.
Liz Kammer619be462022-01-28 15:13:39 -0500718func PathsAndMissingDepsForModuleSrcExcludes(ctx ModuleMissingDepsPathContext, paths, excludes []string) (Paths, []string) {
719 return PathsAndMissingDepsRelativeToModuleSourceDir(SourceInput{
720 Context: ctx,
721 Paths: paths,
722 ExcludePaths: excludes,
723 IncludeDirs: true,
724 })
725}
726
727func PathsAndMissingDepsRelativeToModuleSourceDir(input SourceInput) (Paths, []string) {
728 prefix := pathForModuleSrc(input.Context).String()
Colin Cross8a497952019-03-05 22:25:09 -0800729
730 var expandedExcludes []string
Liz Kammer619be462022-01-28 15:13:39 -0500731 if input.ExcludePaths != nil {
732 expandedExcludes = make([]string, 0, len(input.ExcludePaths))
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700733 }
Colin Cross8a497952019-03-05 22:25:09 -0800734
Colin Crossba71a3f2019-03-18 12:12:48 -0700735 var missingExcludeDeps []string
Liz Kammer619be462022-01-28 15:13:39 -0500736 for _, e := range input.ExcludePaths {
Colin Cross41955e82019-05-29 14:40:35 -0700737 if m, t := SrcIsModuleWithTag(e); m != "" {
Liz Kammer619be462022-01-28 15:13:39 -0500738 modulePaths, err := getPathsFromModuleDep(input.Context, e, m, t)
Liz Kammera830f3a2020-11-10 10:50:34 -0800739 if m, ok := err.(missingDependencyError); ok {
740 missingExcludeDeps = append(missingExcludeDeps, m.missingDeps...)
741 } else if err != nil {
Liz Kammer619be462022-01-28 15:13:39 -0500742 reportPathError(input.Context, err)
Colin Cross8a497952019-03-05 22:25:09 -0800743 } else {
Liz Kammera830f3a2020-11-10 10:50:34 -0800744 expandedExcludes = append(expandedExcludes, modulePaths.Strings()...)
Colin Cross8a497952019-03-05 22:25:09 -0800745 }
746 } else {
747 expandedExcludes = append(expandedExcludes, filepath.Join(prefix, e))
748 }
749 }
750
Liz Kammer619be462022-01-28 15:13:39 -0500751 if input.Paths == nil {
Colin Crossba71a3f2019-03-18 12:12:48 -0700752 return nil, missingExcludeDeps
Colin Cross8a497952019-03-05 22:25:09 -0800753 }
754
Colin Crossba71a3f2019-03-18 12:12:48 -0700755 var missingDeps []string
756
Liz Kammer619be462022-01-28 15:13:39 -0500757 expandedSrcFiles := make(Paths, 0, len(input.Paths))
758 for _, s := range input.Paths {
759 srcFiles, err := expandOneSrcPath(sourcePathInput{
760 context: input.Context,
761 path: s,
762 expandedExcludes: expandedExcludes,
763 includeDirs: input.IncludeDirs,
764 })
Colin Cross8a497952019-03-05 22:25:09 -0800765 if depErr, ok := err.(missingDependencyError); ok {
Colin Crossba71a3f2019-03-18 12:12:48 -0700766 missingDeps = append(missingDeps, depErr.missingDeps...)
Colin Cross8a497952019-03-05 22:25:09 -0800767 } else if err != nil {
Liz Kammer619be462022-01-28 15:13:39 -0500768 reportPathError(input.Context, err)
Colin Cross8a497952019-03-05 22:25:09 -0800769 }
770 expandedSrcFiles = append(expandedSrcFiles, srcFiles...)
771 }
Colin Crossba71a3f2019-03-18 12:12:48 -0700772
Jihoon Kang0e3a5352024-04-12 00:45:50 +0000773 // TODO: b/334169722 - Replace with an error instead of implicitly removing duplicates.
774 return FirstUniquePaths(expandedSrcFiles), append(missingDeps, missingExcludeDeps...)
Colin Cross8a497952019-03-05 22:25:09 -0800775}
776
777type missingDependencyError struct {
778 missingDeps []string
779}
780
781func (e missingDependencyError) Error() string {
782 return "missing dependencies: " + strings.Join(e.missingDeps, ", ")
783}
784
Liz Kammer619be462022-01-28 15:13:39 -0500785type sourcePathInput struct {
786 context ModuleWithDepsPathContext
787 path string
788 expandedExcludes []string
789 includeDirs bool
790}
791
Liz Kammera830f3a2020-11-10 10:50:34 -0800792// Expands one path string to Paths rooted from the module's local source
793// directory, excluding those listed in the expandedExcludes.
794// Expands globs, references to SourceFileProducer or OutputFileProducer modules using the ":name" and ":name{.tag}" syntax.
Liz Kammer619be462022-01-28 15:13:39 -0500795func expandOneSrcPath(input sourcePathInput) (Paths, error) {
Jooyung Han7607dd32020-07-05 10:23:14 +0900796 excludePaths := func(paths Paths) Paths {
Liz Kammer619be462022-01-28 15:13:39 -0500797 if len(input.expandedExcludes) == 0 {
Jooyung Han7607dd32020-07-05 10:23:14 +0900798 return paths
799 }
800 remainder := make(Paths, 0, len(paths))
801 for _, p := range paths {
Liz Kammer619be462022-01-28 15:13:39 -0500802 if !InList(p.String(), input.expandedExcludes) {
Jooyung Han7607dd32020-07-05 10:23:14 +0900803 remainder = append(remainder, p)
804 }
805 }
806 return remainder
807 }
Liz Kammer619be462022-01-28 15:13:39 -0500808 if m, t := SrcIsModuleWithTag(input.path); m != "" {
809 modulePaths, err := getPathsFromModuleDep(input.context, input.path, m, t)
Liz Kammera830f3a2020-11-10 10:50:34 -0800810 if err != nil {
811 return nil, err
Colin Cross8a497952019-03-05 22:25:09 -0800812 } else {
Liz Kammera830f3a2020-11-10 10:50:34 -0800813 return excludePaths(modulePaths), nil
Colin Cross8a497952019-03-05 22:25:09 -0800814 }
Colin Cross8a497952019-03-05 22:25:09 -0800815 } else {
Liz Kammer619be462022-01-28 15:13:39 -0500816 p := pathForModuleSrc(input.context, input.path)
817 if pathtools.IsGlob(input.path) {
818 paths := GlobFiles(input.context, p.String(), input.expandedExcludes)
819 return PathsWithModuleSrcSubDir(input.context, paths, ""), nil
820 } else {
821 if exists, _, err := input.context.Config().fs.Exists(p.String()); err != nil {
822 ReportPathErrorf(input.context, "%s: %s", p, err.Error())
823 } else if !exists && !input.context.Config().TestAllowNonExistentPaths {
824 ReportPathErrorf(input.context, "module source path %q does not exist", p)
825 } else if !input.includeDirs {
826 if isDir, err := input.context.Config().fs.IsDir(p.String()); exists && err != nil {
827 ReportPathErrorf(input.context, "%s: %s", p, err.Error())
828 } else if isDir {
829 ReportPathErrorf(input.context, "module source path %q is a directory", p)
830 }
831 }
Colin Cross8a497952019-03-05 22:25:09 -0800832
Liz Kammer619be462022-01-28 15:13:39 -0500833 if InList(p.String(), input.expandedExcludes) {
834 return nil, nil
835 }
836 return Paths{p}, nil
Colin Cross8a497952019-03-05 22:25:09 -0800837 }
Colin Cross8a497952019-03-05 22:25:09 -0800838 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700839}
840
841// pathsForModuleSrcFromFullPath returns Paths rooted from the module's local
842// source directory, but strip the local source directory from the beginning of
Dan Willemsen540a78c2018-02-26 21:50:08 -0800843// each string. If incDirs is false, strip paths with a trailing '/' from the list.
Colin Crossfe4bc362018-09-12 10:02:13 -0700844// It intended for use in globs that only list files that exist, so it allows '$' in
845// filenames.
Liz Kammera830f3a2020-11-10 10:50:34 -0800846func pathsForModuleSrcFromFullPath(ctx EarlyModulePathContext, paths []string, incDirs bool) Paths {
Lukacs T. Berkif7e36d82021-08-16 17:05:09 +0200847 prefix := ctx.ModuleDir() + "/"
Colin Cross0f37af02017-09-27 17:42:05 -0700848 if prefix == "./" {
849 prefix = ""
850 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700851 ret := make(Paths, 0, len(paths))
852 for _, p := range paths {
Dan Willemsen540a78c2018-02-26 21:50:08 -0800853 if !incDirs && strings.HasSuffix(p, "/") {
854 continue
855 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700856 path := filepath.Clean(p)
857 if !strings.HasPrefix(path, prefix) {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +0100858 ReportPathErrorf(ctx, "Path %q is not in module source directory %q", p, prefix)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700859 continue
860 }
Colin Crosse3924e12018-08-15 20:18:53 -0700861
Colin Crossfe4bc362018-09-12 10:02:13 -0700862 srcPath, err := safePathForSource(ctx, ctx.ModuleDir(), path[len(prefix):])
Colin Crosse3924e12018-08-15 20:18:53 -0700863 if err != nil {
864 reportPathError(ctx, err)
865 continue
866 }
867
Colin Cross07e51612019-03-05 12:46:40 -0800868 srcPath.basePath.rel = srcPath.path
Colin Crosse3924e12018-08-15 20:18:53 -0700869
Colin Cross07e51612019-03-05 12:46:40 -0800870 ret = append(ret, srcPath)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700871 }
872 return ret
873}
874
Liz Kammera830f3a2020-11-10 10:50:34 -0800875// PathsWithOptionalDefaultForModuleSrc returns Paths rooted from the module's local source
876// directory. If input is nil, use the default if it exists. If input is empty, returns nil.
877func PathsWithOptionalDefaultForModuleSrc(ctx ModuleMissingDepsPathContext, input []string, def string) Paths {
Colin Cross0ddae7f2019-02-07 15:30:01 -0800878 if input != nil {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700879 return PathsForModuleSrc(ctx, input)
880 }
881 // Use Glob so that if the default doesn't exist, a dependency is added so that when it
882 // is created, we're run again.
Lukacs T. Berkif7e36d82021-08-16 17:05:09 +0200883 path := filepath.Join(ctx.ModuleDir(), def)
Liz Kammera830f3a2020-11-10 10:50:34 -0800884 return Glob(ctx, path, nil)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700885}
886
887// Strings returns the Paths in string form
888func (p Paths) Strings() []string {
889 if p == nil {
890 return nil
891 }
892 ret := make([]string, len(p))
893 for i, path := range p {
894 ret[i] = path.String()
895 }
896 return ret
897}
898
Colin Crossc0efd1d2020-07-03 11:56:24 -0700899func CopyOfPaths(paths Paths) Paths {
900 return append(Paths(nil), paths...)
901}
902
Colin Crossb6715442017-10-24 11:13:31 -0700903// FirstUniquePaths returns all unique elements of a Paths, keeping the first copy of each. It
904// modifies the Paths slice contents in place, and returns a subslice of the original slice.
Dan Willemsenfe92c962017-08-29 12:28:37 -0700905func FirstUniquePaths(list Paths) Paths {
Colin Cross27027c72020-02-28 15:34:17 -0800906 // 128 was chosen based on BenchmarkFirstUniquePaths results.
907 if len(list) > 128 {
908 return firstUniquePathsMap(list)
909 }
910 return firstUniquePathsList(list)
911}
912
Colin Crossc0efd1d2020-07-03 11:56:24 -0700913// SortedUniquePaths returns all unique elements of a Paths in sorted order. It modifies the
914// Paths slice contents in place, and returns a subslice of the original slice.
Jiyong Park33c77362020-05-29 22:00:16 +0900915func SortedUniquePaths(list Paths) Paths {
916 unique := FirstUniquePaths(list)
917 sort.Slice(unique, func(i, j int) bool {
918 return unique[i].String() < unique[j].String()
919 })
920 return unique
921}
922
Colin Cross27027c72020-02-28 15:34:17 -0800923func firstUniquePathsList(list Paths) Paths {
Dan Willemsenfe92c962017-08-29 12:28:37 -0700924 k := 0
925outer:
926 for i := 0; i < len(list); i++ {
927 for j := 0; j < k; j++ {
928 if list[i] == list[j] {
929 continue outer
930 }
931 }
932 list[k] = list[i]
933 k++
934 }
935 return list[:k]
936}
937
Colin Cross27027c72020-02-28 15:34:17 -0800938func firstUniquePathsMap(list Paths) Paths {
939 k := 0
940 seen := make(map[Path]bool, len(list))
941 for i := 0; i < len(list); i++ {
942 if seen[list[i]] {
943 continue
944 }
945 seen[list[i]] = true
946 list[k] = list[i]
947 k++
948 }
949 return list[:k]
950}
951
Colin Cross5d583952020-11-24 16:21:24 -0800952// FirstUniqueInstallPaths returns all unique elements of an InstallPaths, keeping the first copy of each. It
953// modifies the InstallPaths slice contents in place, and returns a subslice of the original slice.
954func FirstUniqueInstallPaths(list InstallPaths) InstallPaths {
955 // 128 was chosen based on BenchmarkFirstUniquePaths results.
956 if len(list) > 128 {
957 return firstUniqueInstallPathsMap(list)
958 }
959 return firstUniqueInstallPathsList(list)
960}
961
962func firstUniqueInstallPathsList(list InstallPaths) InstallPaths {
963 k := 0
964outer:
965 for i := 0; i < len(list); i++ {
966 for j := 0; j < k; j++ {
967 if list[i] == list[j] {
968 continue outer
969 }
970 }
971 list[k] = list[i]
972 k++
973 }
974 return list[:k]
975}
976
977func firstUniqueInstallPathsMap(list InstallPaths) InstallPaths {
978 k := 0
979 seen := make(map[InstallPath]bool, len(list))
980 for i := 0; i < len(list); i++ {
981 if seen[list[i]] {
982 continue
983 }
984 seen[list[i]] = true
985 list[k] = list[i]
986 k++
987 }
988 return list[:k]
989}
990
Colin Crossb6715442017-10-24 11:13:31 -0700991// LastUniquePaths returns all unique elements of a Paths, keeping the last copy of each. It
992// modifies the Paths slice contents in place, and returns a subslice of the original slice.
993func LastUniquePaths(list Paths) Paths {
994 totalSkip := 0
995 for i := len(list) - 1; i >= totalSkip; i-- {
996 skip := 0
997 for j := i - 1; j >= totalSkip; j-- {
998 if list[i] == list[j] {
999 skip++
1000 } else {
1001 list[j+skip] = list[j]
1002 }
1003 }
1004 totalSkip += skip
1005 }
1006 return list[totalSkip:]
1007}
1008
Colin Crossa140bb02018-04-17 10:52:26 -07001009// ReversePaths returns a copy of a Paths in reverse order.
1010func ReversePaths(list Paths) Paths {
1011 if list == nil {
1012 return nil
1013 }
1014 ret := make(Paths, len(list))
1015 for i := range list {
1016 ret[i] = list[len(list)-1-i]
1017 }
1018 return ret
1019}
1020
Jeff Gaston294356f2017-09-27 17:05:30 -07001021func indexPathList(s Path, list []Path) int {
1022 for i, l := range list {
1023 if l == s {
1024 return i
1025 }
1026 }
1027
1028 return -1
1029}
1030
1031func inPathList(p Path, list []Path) bool {
1032 return indexPathList(p, list) != -1
1033}
1034
1035func FilterPathList(list []Path, filter []Path) (remainder []Path, filtered []Path) {
Paul Duffin57b9e1d2019-12-13 00:03:35 +00001036 return FilterPathListPredicate(list, func(p Path) bool { return inPathList(p, filter) })
1037}
1038
1039func FilterPathListPredicate(list []Path, predicate func(Path) bool) (remainder []Path, filtered []Path) {
Jeff Gaston294356f2017-09-27 17:05:30 -07001040 for _, l := range list {
Paul Duffin57b9e1d2019-12-13 00:03:35 +00001041 if predicate(l) {
Jeff Gaston294356f2017-09-27 17:05:30 -07001042 filtered = append(filtered, l)
1043 } else {
1044 remainder = append(remainder, l)
1045 }
1046 }
1047
1048 return
1049}
1050
Colin Cross93e85952017-08-15 13:34:18 -07001051// HasExt returns true of any of the paths have extension ext, otherwise false
1052func (p Paths) HasExt(ext string) bool {
1053 for _, path := range p {
1054 if path.Ext() == ext {
1055 return true
1056 }
1057 }
1058
1059 return false
1060}
1061
1062// FilterByExt returns the subset of the paths that have extension ext
1063func (p Paths) FilterByExt(ext string) Paths {
1064 ret := make(Paths, 0, len(p))
1065 for _, path := range p {
1066 if path.Ext() == ext {
1067 ret = append(ret, path)
1068 }
1069 }
1070 return ret
1071}
1072
1073// FilterOutByExt returns the subset of the paths that do not have extension ext
1074func (p Paths) FilterOutByExt(ext string) Paths {
1075 ret := make(Paths, 0, len(p))
1076 for _, path := range p {
1077 if path.Ext() != ext {
1078 ret = append(ret, path)
1079 }
1080 }
1081 return ret
1082}
1083
Colin Cross5e6cfbe2017-11-03 15:20:35 -07001084// DirectorySortedPaths is a slice of paths that are sorted such that all files in a directory
1085// (including subdirectories) are in a contiguous subslice of the list, and can be found in
1086// O(log(N)) time using a binary search on the directory prefix.
1087type DirectorySortedPaths Paths
1088
1089func PathsToDirectorySortedPaths(paths Paths) DirectorySortedPaths {
1090 ret := append(DirectorySortedPaths(nil), paths...)
1091 sort.Slice(ret, func(i, j int) bool {
1092 return ret[i].String() < ret[j].String()
1093 })
1094 return ret
1095}
1096
1097// PathsInDirectory returns a subslice of the DirectorySortedPaths as a Paths that contains all entries
1098// that are in the specified directory and its subdirectories.
1099func (p DirectorySortedPaths) PathsInDirectory(dir string) Paths {
1100 prefix := filepath.Clean(dir) + "/"
1101 start := sort.Search(len(p), func(i int) bool {
1102 return prefix < p[i].String()
1103 })
1104
1105 ret := p[start:]
1106
1107 end := sort.Search(len(ret), func(i int) bool {
1108 return !strings.HasPrefix(ret[i].String(), prefix)
1109 })
1110
1111 ret = ret[:end]
1112
1113 return Paths(ret)
1114}
1115
Alex Humesky29e3bbe2020-11-20 21:30:13 -05001116// WritablePaths is a slice of WritablePath, used for multiple outputs.
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001117type WritablePaths []WritablePath
1118
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001119// RelativeToTop creates a new WritablePaths containing the result of calling Path.RelativeToTop on
1120// each item in this slice.
1121func (p WritablePaths) RelativeToTop() WritablePaths {
1122 ensureTestOnly()
1123 if p == nil {
1124 return p
1125 }
1126 ret := make(WritablePaths, len(p))
1127 for i, path := range p {
1128 ret[i] = path.RelativeToTop().(WritablePath)
1129 }
1130 return ret
1131}
1132
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001133// Strings returns the string forms of the writable paths.
1134func (p WritablePaths) Strings() []string {
1135 if p == nil {
1136 return nil
1137 }
1138 ret := make([]string, len(p))
1139 for i, path := range p {
1140 ret[i] = path.String()
1141 }
1142 return ret
1143}
1144
Colin Cross3bc7ffa2017-11-22 16:19:37 -08001145// Paths returns the WritablePaths as a Paths
1146func (p WritablePaths) Paths() Paths {
1147 if p == nil {
1148 return nil
1149 }
1150 ret := make(Paths, len(p))
1151 for i, path := range p {
1152 ret[i] = path
1153 }
1154 return ret
1155}
1156
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001157type basePath struct {
Paul Duffin74abc5d2021-03-24 09:24:59 +00001158 path string
1159 rel string
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001160}
1161
Yu Liu467d7c52024-09-18 21:54:44 +00001162type basePathGob struct {
1163 Path string
1164 Rel string
1165}
Yu Liufa297642024-06-11 00:13:02 +00001166
Yu Liu467d7c52024-09-18 21:54:44 +00001167func (p *basePath) ToGob() *basePathGob {
1168 return &basePathGob{
1169 Path: p.path,
1170 Rel: p.rel,
1171 }
1172}
1173
1174func (p *basePath) FromGob(data *basePathGob) {
1175 p.path = data.Path
1176 p.rel = data.Rel
1177}
1178
1179func (p basePath) GobEncode() ([]byte, error) {
1180 return blueprint.CustomGobEncode[basePathGob](&p)
Yu Liufa297642024-06-11 00:13:02 +00001181}
1182
1183func (p *basePath) GobDecode(data []byte) error {
Yu Liu467d7c52024-09-18 21:54:44 +00001184 return blueprint.CustomGobDecode[basePathGob](data, p)
Yu Liufa297642024-06-11 00:13:02 +00001185}
1186
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001187func (p basePath) Ext() string {
1188 return filepath.Ext(p.path)
1189}
1190
Colin Cross4f6fc9c2016-10-26 10:05:25 -07001191func (p basePath) Base() string {
1192 return filepath.Base(p.path)
1193}
1194
Colin Crossfaeb7aa2017-02-01 14:12:44 -08001195func (p basePath) Rel() string {
1196 if p.rel != "" {
1197 return p.rel
1198 }
1199 return p.path
1200}
1201
Colin Cross0875c522017-11-28 17:34:01 -08001202func (p basePath) String() string {
1203 return p.path
1204}
1205
Colin Cross0db55682017-12-05 15:36:55 -08001206func (p basePath) withRel(rel string) basePath {
1207 p.path = filepath.Join(p.path, rel)
1208 p.rel = rel
1209 return p
1210}
1211
Colin Cross7707b242024-07-26 12:02:36 -07001212func (p basePath) withoutRel() basePath {
1213 p.rel = filepath.Base(p.path)
1214 return p
1215}
1216
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001217// SourcePath is a Path representing a file path rooted from SrcDir
1218type SourcePath struct {
1219 basePath
1220}
1221
1222var _ Path = SourcePath{}
1223
Colin Cross0db55682017-12-05 15:36:55 -08001224func (p SourcePath) withRel(rel string) SourcePath {
1225 p.basePath = p.basePath.withRel(rel)
1226 return p
1227}
1228
Colin Crossbd73d0d2024-07-26 12:00:33 -07001229func (p SourcePath) RelativeToTop() Path {
1230 ensureTestOnly()
1231 return p
1232}
1233
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001234// safePathForSource is for paths that we expect are safe -- only for use by go
1235// code that is embedding ninja variables in paths
Colin Crossfe4bc362018-09-12 10:02:13 -07001236func safePathForSource(ctx PathContext, pathComponents ...string) (SourcePath, error) {
1237 p, err := validateSafePath(pathComponents...)
Cole Faust483d1f72023-01-09 14:35:27 -08001238 ret := SourcePath{basePath{p, ""}}
Colin Crossfe4bc362018-09-12 10:02:13 -07001239 if err != nil {
1240 return ret, err
1241 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001242
Colin Cross7b3dcc32019-01-24 13:14:39 -08001243 // absolute path already checked by validateSafePath
Inseob Kim5eb7ee92022-04-27 10:30:34 +09001244 // special-case api surface gen files for now
1245 if strings.HasPrefix(ret.String(), ctx.Config().soongOutDir) && !strings.Contains(ret.String(), ctx.Config().soongOutDir+"/.export") {
Mikhail Naganovab1f5182019-02-08 13:17:55 -08001246 return ret, fmt.Errorf("source path %q is in output", ret.String())
Colin Cross6e18ca42015-07-14 18:55:36 -07001247 }
1248
Colin Crossfe4bc362018-09-12 10:02:13 -07001249 return ret, err
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001250}
1251
Colin Cross192e97a2018-02-22 14:21:02 -08001252// pathForSource creates a SourcePath from pathComponents, but does not check that it exists.
1253func pathForSource(ctx PathContext, pathComponents ...string) (SourcePath, error) {
Colin Crossc48c1432018-02-23 07:09:01 +00001254 p, err := validatePath(pathComponents...)
Cole Faust483d1f72023-01-09 14:35:27 -08001255 ret := SourcePath{basePath{p, ""}}
Colin Cross94a32102018-02-22 14:21:02 -08001256 if err != nil {
Colin Cross192e97a2018-02-22 14:21:02 -08001257 return ret, err
Colin Cross94a32102018-02-22 14:21:02 -08001258 }
1259
Colin Cross7b3dcc32019-01-24 13:14:39 -08001260 // absolute path already checked by validatePath
Inseob Kim5eb7ee92022-04-27 10:30:34 +09001261 // special-case for now
1262 if strings.HasPrefix(ret.String(), ctx.Config().soongOutDir) && !strings.Contains(ret.String(), ctx.Config().soongOutDir+"/.export") {
Mikhail Naganovab1f5182019-02-08 13:17:55 -08001263 return ret, fmt.Errorf("source path %q is in output", ret.String())
Colin Crossc48c1432018-02-23 07:09:01 +00001264 }
1265
Colin Cross192e97a2018-02-22 14:21:02 -08001266 return ret, nil
1267}
1268
1269// existsWithDependencies returns true if the path exists, and adds appropriate dependencies to rerun if the
1270// path does not exist.
Colin Cross662d6142022-11-03 20:38:01 -07001271func existsWithDependencies(ctx PathGlobContext, path SourcePath) (exists bool, err error) {
Colin Cross192e97a2018-02-22 14:21:02 -08001272 var files []string
1273
Colin Cross662d6142022-11-03 20:38:01 -07001274 // Use glob to produce proper dependencies, even though we only want
1275 // a single file.
1276 files, err = ctx.GlobWithDeps(path.String(), nil)
Colin Cross192e97a2018-02-22 14:21:02 -08001277
1278 if err != nil {
1279 return false, fmt.Errorf("glob: %s", err.Error())
1280 }
1281
1282 return len(files) > 0, nil
1283}
1284
1285// PathForSource joins the provided path components and validates that the result
1286// neither escapes the source dir nor is in the out dir.
1287// On error, it will return a usable, but invalid SourcePath, and report a ModuleError.
1288func PathForSource(ctx PathContext, pathComponents ...string) SourcePath {
1289 path, err := pathForSource(ctx, pathComponents...)
1290 if err != nil {
1291 reportPathError(ctx, err)
1292 }
1293
Colin Crosse3924e12018-08-15 20:18:53 -07001294 if pathtools.IsGlob(path.String()) {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001295 ReportPathErrorf(ctx, "path may not contain a glob: %s", path.String())
Colin Crosse3924e12018-08-15 20:18:53 -07001296 }
1297
Liz Kammera830f3a2020-11-10 10:50:34 -08001298 if modCtx, ok := ctx.(ModuleMissingDepsPathContext); ok && ctx.Config().AllowMissingDependencies() {
Colin Cross662d6142022-11-03 20:38:01 -07001299 exists, err := existsWithDependencies(modCtx, path)
Colin Cross192e97a2018-02-22 14:21:02 -08001300 if err != nil {
1301 reportPathError(ctx, err)
1302 }
1303 if !exists {
1304 modCtx.AddMissingDependencies([]string{path.String()})
1305 }
Colin Cross988414c2020-01-11 01:11:46 +00001306 } else if exists, _, err := ctx.Config().fs.Exists(path.String()); err != nil {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001307 ReportPathErrorf(ctx, "%s: %s", path, err.Error())
Pedro Loureiro5d190cc2021-02-15 15:41:33 +00001308 } else if !exists && !ctx.Config().TestAllowNonExistentPaths {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001309 ReportPathErrorf(ctx, "source path %q does not exist", path)
Colin Cross192e97a2018-02-22 14:21:02 -08001310 }
1311 return path
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001312}
1313
Cole Faustbc65a3f2023-08-01 16:38:55 +00001314// PathForArbitraryOutput creates a path for the given components. Unlike PathForOutput,
1315// the path is relative to the root of the output folder, not the out/soong folder.
1316func PathForArbitraryOutput(ctx PathContext, pathComponents ...string) Path {
Colin Cross3b1c6842024-07-26 11:52:57 -07001317 path, err := validatePath(pathComponents...)
Cole Faustbc65a3f2023-08-01 16:38:55 +00001318 if err != nil {
1319 reportPathError(ctx, err)
1320 }
Colin Cross3b1c6842024-07-26 11:52:57 -07001321 fullPath := filepath.Join(ctx.Config().OutDir(), path)
1322 path = fullPath[len(fullPath)-len(path):]
1323 return OutputPath{basePath{path, ""}, ctx.Config().OutDir(), fullPath}
Cole Faustbc65a3f2023-08-01 16:38:55 +00001324}
1325
Spandan Dasc6c10fa2022-10-21 21:52:13 +00001326// MaybeExistentPathForSource joins the provided path components and validates that the result
1327// neither escapes the source dir nor is in the out dir.
1328// It does not validate whether the path exists.
1329func MaybeExistentPathForSource(ctx PathContext, pathComponents ...string) SourcePath {
1330 path, err := pathForSource(ctx, pathComponents...)
1331 if err != nil {
1332 reportPathError(ctx, err)
1333 }
1334
1335 if pathtools.IsGlob(path.String()) {
1336 ReportPathErrorf(ctx, "path may not contain a glob: %s", path.String())
1337 }
1338 return path
1339}
1340
Liz Kammer7aa52882021-02-11 09:16:14 -05001341// ExistentPathForSource returns an OptionalPath with the SourcePath, rooted from SrcDir, *not*
1342// rooted from the module's local source directory, if the path exists, or an empty OptionalPath if
1343// it doesn't exist. Dependencies are added so that the ninja file will be regenerated if the state
1344// of the path changes.
Colin Cross662d6142022-11-03 20:38:01 -07001345func ExistentPathForSource(ctx PathGlobContext, pathComponents ...string) OptionalPath {
Colin Cross192e97a2018-02-22 14:21:02 -08001346 path, err := pathForSource(ctx, pathComponents...)
Colin Cross1ccfcc32018-02-22 13:54:26 -08001347 if err != nil {
1348 reportPathError(ctx, err)
Martin Stjernholmc32dd1c2021-09-15 02:39:00 +01001349 // No need to put the error message into the returned path since it has been reported already.
Colin Cross1ccfcc32018-02-22 13:54:26 -08001350 return OptionalPath{}
1351 }
Colin Crossc48c1432018-02-23 07:09:01 +00001352
Colin Crosse3924e12018-08-15 20:18:53 -07001353 if pathtools.IsGlob(path.String()) {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001354 ReportPathErrorf(ctx, "path may not contain a glob: %s", path.String())
Colin Crosse3924e12018-08-15 20:18:53 -07001355 return OptionalPath{}
1356 }
1357
Colin Cross192e97a2018-02-22 14:21:02 -08001358 exists, err := existsWithDependencies(ctx, path)
Colin Crossc48c1432018-02-23 07:09:01 +00001359 if err != nil {
1360 reportPathError(ctx, err)
1361 return OptionalPath{}
1362 }
Colin Cross192e97a2018-02-22 14:21:02 -08001363 if !exists {
Martin Stjernholmc32dd1c2021-09-15 02:39:00 +01001364 return InvalidOptionalPath(path.String() + " does not exist")
Colin Crossc48c1432018-02-23 07:09:01 +00001365 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001366 return OptionalPathForPath(path)
1367}
1368
1369func (p SourcePath) String() string {
Cole Faust483d1f72023-01-09 14:35:27 -08001370 if p.path == "" {
1371 return "."
1372 }
1373 return p.path
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001374}
1375
Colin Cross7707b242024-07-26 12:02:36 -07001376func (p SourcePath) WithoutRel() Path {
1377 p.basePath = p.basePath.withoutRel()
1378 return p
1379}
1380
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001381// Join creates a new SourcePath with paths... joined with the current path. The
1382// provided paths... may not use '..' to escape from the current path.
1383func (p SourcePath) Join(ctx PathContext, paths ...string) SourcePath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001384 path, err := validatePath(paths...)
1385 if err != nil {
1386 reportPathError(ctx, err)
1387 }
Colin Cross0db55682017-12-05 15:36:55 -08001388 return p.withRel(path)
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001389}
1390
Colin Cross2fafa3e2019-03-05 12:39:51 -08001391// join is like Join but does less path validation.
1392func (p SourcePath) join(ctx PathContext, paths ...string) SourcePath {
1393 path, err := validateSafePath(paths...)
1394 if err != nil {
1395 reportPathError(ctx, err)
1396 }
1397 return p.withRel(path)
1398}
1399
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001400// OverlayPath returns the overlay for `path' if it exists. This assumes that the
1401// SourcePath is the path to a resource overlay directory.
Liz Kammera830f3a2020-11-10 10:50:34 -08001402func (p SourcePath) OverlayPath(ctx ModuleMissingDepsPathContext, path Path) OptionalPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001403 var relDir string
Colin Cross07e51612019-03-05 12:46:40 -08001404 if srcPath, ok := path.(SourcePath); ok {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001405 relDir = srcPath.path
1406 } else {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001407 ReportPathErrorf(ctx, "Cannot find relative path for %s(%s)", reflect.TypeOf(path).Name(), path)
Martin Stjernholmc32dd1c2021-09-15 02:39:00 +01001408 // No need to put the error message into the returned path since it has been reported already.
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001409 return OptionalPath{}
1410 }
Cole Faust483d1f72023-01-09 14:35:27 -08001411 dir := filepath.Join(p.path, relDir)
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001412 // Use Glob so that we are run again if the directory is added.
Colin Cross7f19f372016-11-01 11:10:25 -07001413 if pathtools.IsGlob(dir) {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001414 ReportPathErrorf(ctx, "Path may not contain a glob: %s", dir)
Dan Willemsen7b310ee2015-12-18 15:11:17 -08001415 }
Colin Cross461b4452018-02-23 09:22:42 -08001416 paths, err := ctx.GlobWithDeps(dir, nil)
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001417 if err != nil {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001418 ReportPathErrorf(ctx, "glob: %s", err.Error())
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001419 return OptionalPath{}
1420 }
1421 if len(paths) == 0 {
Martin Stjernholmc32dd1c2021-09-15 02:39:00 +01001422 return InvalidOptionalPath(dir + " does not exist")
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001423 }
Cole Faust483d1f72023-01-09 14:35:27 -08001424 return OptionalPathForPath(PathForSource(ctx, paths[0]))
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001425}
1426
Colin Cross70dda7e2019-10-01 22:05:35 -07001427// OutputPath is a Path representing an intermediates file path rooted from the build directory
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001428type OutputPath struct {
1429 basePath
Paul Duffind65c58b2021-03-24 09:22:07 +00001430
Colin Cross3b1c6842024-07-26 11:52:57 -07001431 // The base out directory for this path, either Config.SoongOutDir() or Config.OutDir()
1432 outDir string
Paul Duffind65c58b2021-03-24 09:22:07 +00001433
Colin Crossd63c9a72020-01-29 16:52:50 -08001434 fullPath string
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001435}
1436
Yu Liu467d7c52024-09-18 21:54:44 +00001437type outputPathGob struct {
Yu Liu5246a7e2024-10-09 20:04:52 +00001438 BasePath basePath
Yu Liu467d7c52024-09-18 21:54:44 +00001439 OutDir string
1440 FullPath string
1441}
Yu Liufa297642024-06-11 00:13:02 +00001442
Yu Liu467d7c52024-09-18 21:54:44 +00001443func (p *OutputPath) ToGob() *outputPathGob {
1444 return &outputPathGob{
Yu Liu5246a7e2024-10-09 20:04:52 +00001445 BasePath: p.basePath,
Yu Liu467d7c52024-09-18 21:54:44 +00001446 OutDir: p.outDir,
1447 FullPath: p.fullPath,
1448 }
1449}
1450
1451func (p *OutputPath) FromGob(data *outputPathGob) {
Yu Liu5246a7e2024-10-09 20:04:52 +00001452 p.basePath = data.BasePath
Yu Liu467d7c52024-09-18 21:54:44 +00001453 p.outDir = data.OutDir
1454 p.fullPath = data.FullPath
1455}
1456
1457func (p OutputPath) GobEncode() ([]byte, error) {
1458 return blueprint.CustomGobEncode[outputPathGob](&p)
Yu Liufa297642024-06-11 00:13:02 +00001459}
1460
1461func (p *OutputPath) GobDecode(data []byte) error {
Yu Liu467d7c52024-09-18 21:54:44 +00001462 return blueprint.CustomGobDecode[outputPathGob](data, p)
Yu Liufa297642024-06-11 00:13:02 +00001463}
1464
Colin Cross702e0f82017-10-18 17:27:54 -07001465func (p OutputPath) withRel(rel string) OutputPath {
Colin Cross0db55682017-12-05 15:36:55 -08001466 p.basePath = p.basePath.withRel(rel)
Colin Crossd63c9a72020-01-29 16:52:50 -08001467 p.fullPath = filepath.Join(p.fullPath, rel)
Colin Cross702e0f82017-10-18 17:27:54 -07001468 return p
1469}
1470
Colin Cross7707b242024-07-26 12:02:36 -07001471func (p OutputPath) WithoutRel() Path {
1472 p.basePath = p.basePath.withoutRel()
Colin Cross3063b782018-08-15 11:19:12 -07001473 return p
1474}
1475
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02001476func (p OutputPath) getSoongOutDir() string {
Colin Cross3b1c6842024-07-26 11:52:57 -07001477 return p.outDir
Paul Duffin9b478b02019-12-10 13:41:51 +00001478}
1479
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001480func (p OutputPath) RelativeToTop() Path {
1481 return p.outputPathRelativeToTop()
1482}
1483
1484func (p OutputPath) outputPathRelativeToTop() OutputPath {
Colin Cross3b1c6842024-07-26 11:52:57 -07001485 p.fullPath = StringPathRelativeToTop(p.outDir, p.fullPath)
1486 if strings.HasSuffix(p.outDir, testOutSoongSubDir) {
1487 p.outDir = TestOutSoongDir
1488 } else {
1489 // Handle the PathForArbitraryOutput case
1490 p.outDir = testOutDir
1491 }
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001492 return p
1493}
1494
Paul Duffin0267d492021-02-02 10:05:52 +00001495func (p OutputPath) objPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleObjPath {
1496 return PathForModuleObj(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
1497}
1498
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001499var _ Path = OutputPath{}
Paul Duffin9b478b02019-12-10 13:41:51 +00001500var _ WritablePath = OutputPath{}
Paul Duffin0267d492021-02-02 10:05:52 +00001501var _ objPathProvider = OutputPath{}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001502
Chris Parsons8f232a22020-06-23 17:37:05 -04001503// toolDepPath is a Path representing a dependency of the build tool.
1504type toolDepPath struct {
1505 basePath
1506}
1507
Colin Cross7707b242024-07-26 12:02:36 -07001508func (t toolDepPath) WithoutRel() Path {
1509 t.basePath = t.basePath.withoutRel()
1510 return t
1511}
1512
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001513func (t toolDepPath) RelativeToTop() Path {
1514 ensureTestOnly()
1515 return t
1516}
1517
Chris Parsons8f232a22020-06-23 17:37:05 -04001518var _ Path = toolDepPath{}
1519
1520// pathForBuildToolDep returns a toolDepPath representing the given path string.
1521// There is no validation for the path, as it is "trusted": It may fail
1522// normal validation checks. For example, it may be an absolute path.
1523// Only use this function to construct paths for dependencies of the build
1524// tool invocation.
1525func pathForBuildToolDep(ctx PathContext, path string) toolDepPath {
Paul Duffin74abc5d2021-03-24 09:24:59 +00001526 return toolDepPath{basePath{path, ""}}
Chris Parsons8f232a22020-06-23 17:37:05 -04001527}
1528
Jeff Gaston734e3802017-04-10 15:47:24 -07001529// PathForOutput joins the provided paths and returns an OutputPath that is
1530// validated to not escape the build dir.
1531// On error, it will return a usable, but invalid OutputPath, and report a ModuleError.
1532func PathForOutput(ctx PathContext, pathComponents ...string) OutputPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001533 path, err := validatePath(pathComponents...)
1534 if err != nil {
1535 reportPathError(ctx, err)
1536 }
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02001537 fullPath := filepath.Join(ctx.Config().soongOutDir, path)
Colin Crossd63c9a72020-01-29 16:52:50 -08001538 path = fullPath[len(fullPath)-len(path):]
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02001539 return OutputPath{basePath{path, ""}, ctx.Config().soongOutDir, fullPath}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001540}
1541
Colin Cross3b1c6842024-07-26 11:52:57 -07001542// PathsForOutput returns Paths rooted from outDir
Colin Cross40e33732019-02-15 11:08:35 -08001543func PathsForOutput(ctx PathContext, paths []string) WritablePaths {
1544 ret := make(WritablePaths, len(paths))
1545 for i, path := range paths {
1546 ret[i] = PathForOutput(ctx, path)
1547 }
1548 return ret
1549}
1550
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001551func (p OutputPath) writablePath() {}
1552
1553func (p OutputPath) String() string {
Colin Crossd63c9a72020-01-29 16:52:50 -08001554 return p.fullPath
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001555}
1556
1557// Join creates a new OutputPath with paths... joined with the current path. The
1558// provided paths... may not use '..' to escape from the current path.
1559func (p OutputPath) Join(ctx PathContext, paths ...string) OutputPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001560 path, err := validatePath(paths...)
1561 if err != nil {
1562 reportPathError(ctx, err)
1563 }
Colin Cross0db55682017-12-05 15:36:55 -08001564 return p.withRel(path)
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001565}
1566
Colin Cross8854a5a2019-02-11 14:14:16 -08001567// ReplaceExtension creates a new OutputPath with the extension replaced with ext.
1568func (p OutputPath) ReplaceExtension(ctx PathContext, ext string) OutputPath {
1569 if strings.Contains(ext, "/") {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001570 ReportPathErrorf(ctx, "extension %q cannot contain /", ext)
Colin Cross8854a5a2019-02-11 14:14:16 -08001571 }
1572 ret := PathForOutput(ctx, pathtools.ReplaceExtension(p.path, ext))
Colin Cross2cdd5df2019-02-25 10:25:24 -08001573 ret.rel = pathtools.ReplaceExtension(p.rel, ext)
Colin Cross8854a5a2019-02-11 14:14:16 -08001574 return ret
1575}
1576
Colin Cross40e33732019-02-15 11:08:35 -08001577// InSameDir creates a new OutputPath from the directory of the current OutputPath joined with the elements in paths.
1578func (p OutputPath) InSameDir(ctx PathContext, paths ...string) OutputPath {
1579 path, err := validatePath(paths...)
1580 if err != nil {
1581 reportPathError(ctx, err)
1582 }
1583
1584 ret := PathForOutput(ctx, filepath.Dir(p.path), path)
Colin Cross2cdd5df2019-02-25 10:25:24 -08001585 ret.rel = filepath.Join(filepath.Dir(p.rel), path)
Colin Cross40e33732019-02-15 11:08:35 -08001586 return ret
1587}
1588
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001589// PathForIntermediates returns an OutputPath representing the top-level
1590// intermediates directory.
1591func PathForIntermediates(ctx PathContext, paths ...string) OutputPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001592 path, err := validatePath(paths...)
1593 if err != nil {
1594 reportPathError(ctx, err)
1595 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001596 return PathForOutput(ctx, ".intermediates", path)
1597}
1598
Colin Cross07e51612019-03-05 12:46:40 -08001599var _ genPathProvider = SourcePath{}
1600var _ objPathProvider = SourcePath{}
1601var _ resPathProvider = SourcePath{}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001602
Colin Cross07e51612019-03-05 12:46:40 -08001603// PathForModuleSrc returns a Path representing the paths... under the
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001604// module's local source directory.
Liz Kammera830f3a2020-11-10 10:50:34 -08001605func PathForModuleSrc(ctx ModuleMissingDepsPathContext, pathComponents ...string) Path {
Paul Duffin407501b2021-07-09 16:56:35 +01001606 // Just join the components textually just to make sure that it does not corrupt a fully qualified
1607 // module reference, e.g. if the pathComponents is "://other:foo" then using filepath.Join() or
1608 // validatePath() will corrupt it, e.g. replace "//" with "/". If the path is not a module
1609 // reference then it will be validated by expandOneSrcPath anyway when it calls expandOneSrcPath.
1610 p := strings.Join(pathComponents, string(filepath.Separator))
Liz Kammer619be462022-01-28 15:13:39 -05001611 paths, err := expandOneSrcPath(sourcePathInput{context: ctx, path: p, includeDirs: true})
Colin Cross8a497952019-03-05 22:25:09 -08001612 if err != nil {
1613 if depErr, ok := err.(missingDependencyError); ok {
1614 if ctx.Config().AllowMissingDependencies() {
1615 ctx.AddMissingDependencies(depErr.missingDeps)
1616 } else {
1617 ctx.ModuleErrorf(`%s, is the property annotated with android:"path"?`, depErr.Error())
1618 }
1619 } else {
1620 reportPathError(ctx, err)
1621 }
1622 return nil
1623 } else if len(paths) == 0 {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001624 ReportPathErrorf(ctx, "%q produced no files, expected exactly one", p)
Colin Cross8a497952019-03-05 22:25:09 -08001625 return nil
1626 } else if len(paths) > 1 {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001627 ReportPathErrorf(ctx, "%q produced %d files, expected exactly one", p, len(paths))
Colin Cross8a497952019-03-05 22:25:09 -08001628 }
1629 return paths[0]
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001630}
1631
Liz Kammera830f3a2020-11-10 10:50:34 -08001632func pathForModuleSrc(ctx EarlyModulePathContext, paths ...string) SourcePath {
Colin Cross07e51612019-03-05 12:46:40 -08001633 p, err := validatePath(paths...)
1634 if err != nil {
1635 reportPathError(ctx, err)
1636 }
1637
1638 path, err := pathForSource(ctx, ctx.ModuleDir(), p)
1639 if err != nil {
1640 reportPathError(ctx, err)
1641 }
1642
1643 path.basePath.rel = p
1644
1645 return path
1646}
1647
Colin Cross2fafa3e2019-03-05 12:39:51 -08001648// PathsWithModuleSrcSubDir takes a list of Paths and returns a new list of Paths where Rel() on each path
1649// will return the path relative to subDir in the module's source directory. If any input paths are not located
1650// inside subDir then a path error will be reported.
Liz Kammera830f3a2020-11-10 10:50:34 -08001651func PathsWithModuleSrcSubDir(ctx EarlyModulePathContext, paths Paths, subDir string) Paths {
Colin Cross2fafa3e2019-03-05 12:39:51 -08001652 paths = append(Paths(nil), paths...)
Colin Cross07e51612019-03-05 12:46:40 -08001653 subDirFullPath := pathForModuleSrc(ctx, subDir)
Colin Cross2fafa3e2019-03-05 12:39:51 -08001654 for i, path := range paths {
1655 rel := Rel(ctx, subDirFullPath.String(), path.String())
1656 paths[i] = subDirFullPath.join(ctx, rel)
1657 }
1658 return paths
1659}
1660
1661// PathWithModuleSrcSubDir takes a Path and returns a Path where Rel() will return the path relative to subDir in the
1662// 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 -08001663func PathWithModuleSrcSubDir(ctx EarlyModulePathContext, path Path, subDir string) Path {
Colin Cross07e51612019-03-05 12:46:40 -08001664 subDirFullPath := pathForModuleSrc(ctx, subDir)
Colin Cross2fafa3e2019-03-05 12:39:51 -08001665 rel := Rel(ctx, subDirFullPath.String(), path.String())
1666 return subDirFullPath.Join(ctx, rel)
1667}
1668
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001669// OptionalPathForModuleSrc returns an OptionalPath. The OptionalPath contains a
1670// valid path if p is non-nil.
Liz Kammera830f3a2020-11-10 10:50:34 -08001671func OptionalPathForModuleSrc(ctx ModuleMissingDepsPathContext, p *string) OptionalPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001672 if p == nil {
1673 return OptionalPath{}
1674 }
1675 return OptionalPathForPath(PathForModuleSrc(ctx, *p))
1676}
1677
Liz Kammera830f3a2020-11-10 10:50:34 -08001678func (p SourcePath) genPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleGenPath {
Colin Cross7fc17db2017-02-01 14:07:55 -08001679 return PathForModuleGen(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001680}
1681
yangbill6d032dd2024-04-18 03:05:49 +00001682func (p SourcePath) genPathWithExtAndTrimExt(ctx ModuleOutPathContext, subdir, ext string, trimExt string) ModuleGenPath {
1683 // If Trim_extension being set, force append Output_extension without replace original extension.
1684 if trimExt != "" {
1685 if ext != "" {
1686 return PathForModuleGen(ctx, subdir, strings.TrimSuffix(p.path, trimExt)+"."+ext)
1687 }
1688 return PathForModuleGen(ctx, subdir, strings.TrimSuffix(p.path, trimExt))
1689 }
1690 return PathForModuleGen(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
1691}
1692
Liz Kammera830f3a2020-11-10 10:50:34 -08001693func (p SourcePath) objPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleObjPath {
Colin Cross7fc17db2017-02-01 14:07:55 -08001694 return PathForModuleObj(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001695}
1696
Liz Kammera830f3a2020-11-10 10:50:34 -08001697func (p SourcePath) resPathWithName(ctx ModuleOutPathContext, name string) ModuleResPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001698 // TODO: Use full directory if the new ctx is not the current ctx?
1699 return PathForModuleRes(ctx, p.path, name)
1700}
1701
1702// ModuleOutPath is a Path representing a module's output directory.
1703type ModuleOutPath struct {
1704 OutputPath
1705}
1706
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001707func (p ModuleOutPath) RelativeToTop() Path {
1708 p.OutputPath = p.outputPathRelativeToTop()
1709 return p
1710}
1711
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001712var _ Path = ModuleOutPath{}
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001713var _ WritablePath = ModuleOutPath{}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001714
Liz Kammera830f3a2020-11-10 10:50:34 -08001715func (p ModuleOutPath) objPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleObjPath {
Pete Bentleyfcf55bf2019-08-16 20:14:32 +01001716 return PathForModuleObj(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
1717}
1718
Liz Kammera830f3a2020-11-10 10:50:34 -08001719// ModuleOutPathContext Subset of ModuleContext functions necessary for output path methods.
1720type ModuleOutPathContext interface {
1721 PathContext
1722
1723 ModuleName() string
1724 ModuleDir() string
1725 ModuleSubDir() string
1726}
1727
1728func pathForModuleOut(ctx ModuleOutPathContext) OutputPath {
Inseob Kimb7e9f5f2024-06-25 17:39:52 +09001729 return PathForOutput(ctx, ".intermediates", ctx.ModuleDir(), ctx.ModuleName(), ctx.ModuleSubDir())
Colin Cross702e0f82017-10-18 17:27:54 -07001730}
1731
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001732// PathForModuleOut returns a Path representing the paths... under the module's
1733// output directory.
Liz Kammera830f3a2020-11-10 10:50:34 -08001734func PathForModuleOut(ctx ModuleOutPathContext, paths ...string) ModuleOutPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001735 p, err := validatePath(paths...)
1736 if err != nil {
1737 reportPathError(ctx, err)
1738 }
Colin Cross702e0f82017-10-18 17:27:54 -07001739 return ModuleOutPath{
Liz Kammera830f3a2020-11-10 10:50:34 -08001740 OutputPath: pathForModuleOut(ctx).withRel(p),
Colin Cross702e0f82017-10-18 17:27:54 -07001741 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001742}
1743
1744// ModuleGenPath is a Path representing the 'gen' directory in a module's output
1745// directory. Mainly used for generated sources.
1746type ModuleGenPath struct {
1747 ModuleOutPath
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001748}
1749
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001750func (p ModuleGenPath) RelativeToTop() Path {
1751 p.OutputPath = p.outputPathRelativeToTop()
1752 return p
1753}
1754
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001755var _ Path = ModuleGenPath{}
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001756var _ WritablePath = ModuleGenPath{}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001757var _ genPathProvider = ModuleGenPath{}
1758var _ objPathProvider = ModuleGenPath{}
1759
1760// PathForModuleGen returns a Path representing the paths... under the module's
1761// `gen' directory.
Liz Kammera830f3a2020-11-10 10:50:34 -08001762func PathForModuleGen(ctx ModuleOutPathContext, paths ...string) ModuleGenPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001763 p, err := validatePath(paths...)
1764 if err != nil {
1765 reportPathError(ctx, err)
1766 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001767 return ModuleGenPath{
Colin Cross702e0f82017-10-18 17:27:54 -07001768 ModuleOutPath: ModuleOutPath{
Liz Kammera830f3a2020-11-10 10:50:34 -08001769 OutputPath: pathForModuleOut(ctx).withRel("gen").withRel(p),
Colin Cross702e0f82017-10-18 17:27:54 -07001770 },
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001771 }
1772}
1773
Liz Kammera830f3a2020-11-10 10:50:34 -08001774func (p ModuleGenPath) genPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleGenPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001775 // TODO: make a different path for local vs remote generated files?
Dan Willemsen21ec4902016-11-02 20:43:13 -07001776 return PathForModuleGen(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001777}
1778
yangbill6d032dd2024-04-18 03:05:49 +00001779func (p ModuleGenPath) genPathWithExtAndTrimExt(ctx ModuleOutPathContext, subdir, ext string, trimExt string) ModuleGenPath {
1780 // If Trim_extension being set, force append Output_extension without replace original extension.
1781 if trimExt != "" {
1782 if ext != "" {
1783 return PathForModuleGen(ctx, subdir, strings.TrimSuffix(p.path, trimExt)+"."+ext)
1784 }
1785 return PathForModuleGen(ctx, subdir, strings.TrimSuffix(p.path, trimExt))
1786 }
1787 return PathForModuleGen(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
1788}
1789
Liz Kammera830f3a2020-11-10 10:50:34 -08001790func (p ModuleGenPath) objPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleObjPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001791 return PathForModuleObj(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
1792}
1793
1794// ModuleObjPath is a Path representing the 'obj' directory in a module's output
1795// directory. Used for compiled objects.
1796type ModuleObjPath struct {
1797 ModuleOutPath
1798}
1799
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001800func (p ModuleObjPath) RelativeToTop() Path {
1801 p.OutputPath = p.outputPathRelativeToTop()
1802 return p
1803}
1804
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001805var _ Path = ModuleObjPath{}
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001806var _ WritablePath = ModuleObjPath{}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001807
1808// PathForModuleObj returns a Path representing the paths... under the module's
1809// 'obj' directory.
Liz Kammera830f3a2020-11-10 10:50:34 -08001810func PathForModuleObj(ctx ModuleOutPathContext, pathComponents ...string) ModuleObjPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001811 p, err := validatePath(pathComponents...)
1812 if err != nil {
1813 reportPathError(ctx, err)
1814 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001815 return ModuleObjPath{PathForModuleOut(ctx, "obj", p)}
1816}
1817
1818// ModuleResPath is a a Path representing the 'res' directory in a module's
1819// output directory.
1820type ModuleResPath struct {
1821 ModuleOutPath
1822}
1823
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001824func (p ModuleResPath) RelativeToTop() Path {
1825 p.OutputPath = p.outputPathRelativeToTop()
1826 return p
1827}
1828
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001829var _ Path = ModuleResPath{}
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001830var _ WritablePath = ModuleResPath{}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001831
1832// PathForModuleRes returns a Path representing the paths... under the module's
1833// 'res' directory.
Liz Kammera830f3a2020-11-10 10:50:34 -08001834func PathForModuleRes(ctx ModuleOutPathContext, pathComponents ...string) ModuleResPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001835 p, err := validatePath(pathComponents...)
1836 if err != nil {
1837 reportPathError(ctx, err)
1838 }
1839
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001840 return ModuleResPath{PathForModuleOut(ctx, "res", p)}
1841}
1842
Colin Cross70dda7e2019-10-01 22:05:35 -07001843// InstallPath is a Path representing a installed file path rooted from the build directory
1844type InstallPath struct {
1845 basePath
Colin Crossff6c33d2019-10-02 16:01:35 -07001846
Lukacs T. Berkib078ade2021-08-31 10:42:08 +02001847 // The soong build directory, i.e. Config.SoongOutDir()
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02001848 soongOutDir string
Paul Duffind65c58b2021-03-24 09:22:07 +00001849
Jiyong Park957bcd92020-10-20 18:23:33 +09001850 // partitionDir is the part of the InstallPath that is automatically determined according to the context.
1851 // For example, it is host/<os>-<arch> for host modules, and target/product/<device>/<partition> for device modules.
1852 partitionDir string
1853
Colin Crossb1692a32021-10-25 15:39:01 -07001854 partition string
1855
Jiyong Park957bcd92020-10-20 18:23:33 +09001856 // makePath indicates whether this path is for Soong (false) or Make (true).
1857 makePath bool
Colin Crossc0e42d52024-02-01 16:42:36 -08001858
1859 fullPath string
Colin Cross70dda7e2019-10-01 22:05:35 -07001860}
1861
Yu Liu467d7c52024-09-18 21:54:44 +00001862type installPathGob struct {
Yu Liu5246a7e2024-10-09 20:04:52 +00001863 BasePath basePath
Yu Liu467d7c52024-09-18 21:54:44 +00001864 SoongOutDir string
1865 PartitionDir string
1866 Partition string
1867 MakePath bool
1868 FullPath string
1869}
Yu Liu26a716d2024-08-30 23:40:32 +00001870
Yu Liu467d7c52024-09-18 21:54:44 +00001871func (p *InstallPath) ToGob() *installPathGob {
1872 return &installPathGob{
Yu Liu5246a7e2024-10-09 20:04:52 +00001873 BasePath: p.basePath,
Yu Liu467d7c52024-09-18 21:54:44 +00001874 SoongOutDir: p.soongOutDir,
1875 PartitionDir: p.partitionDir,
1876 Partition: p.partition,
1877 MakePath: p.makePath,
1878 FullPath: p.fullPath,
1879 }
1880}
1881
1882func (p *InstallPath) FromGob(data *installPathGob) {
Yu Liu5246a7e2024-10-09 20:04:52 +00001883 p.basePath = data.BasePath
Yu Liu467d7c52024-09-18 21:54:44 +00001884 p.soongOutDir = data.SoongOutDir
1885 p.partitionDir = data.PartitionDir
1886 p.partition = data.Partition
1887 p.makePath = data.MakePath
1888 p.fullPath = data.FullPath
1889}
1890
1891func (p InstallPath) GobEncode() ([]byte, error) {
1892 return blueprint.CustomGobEncode[installPathGob](&p)
Yu Liu26a716d2024-08-30 23:40:32 +00001893}
1894
1895func (p *InstallPath) GobDecode(data []byte) error {
Yu Liu467d7c52024-09-18 21:54:44 +00001896 return blueprint.CustomGobDecode[installPathGob](data, p)
Yu Liu26a716d2024-08-30 23:40:32 +00001897}
1898
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001899// Will panic if called from outside a test environment.
1900func ensureTestOnly() {
Martin Stjernholm32312eb2021-03-27 18:54:49 +00001901 if PrefixInList(os.Args, "-test.") {
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001902 return
1903 }
Martin Stjernholm32312eb2021-03-27 18:54:49 +00001904 panic(fmt.Errorf("Not in test. Command line:\n %s", strings.Join(os.Args, "\n ")))
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001905}
1906
1907func (p InstallPath) RelativeToTop() Path {
1908 ensureTestOnly()
Colin Crossc0e42d52024-02-01 16:42:36 -08001909 if p.makePath {
Colin Cross3b1c6842024-07-26 11:52:57 -07001910 p.soongOutDir = testOutDir
Colin Crossc0e42d52024-02-01 16:42:36 -08001911 } else {
Colin Cross3b1c6842024-07-26 11:52:57 -07001912 p.soongOutDir = TestOutSoongDir
Colin Crossc0e42d52024-02-01 16:42:36 -08001913 }
1914 p.fullPath = filepath.Join(p.soongOutDir, p.path)
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001915 return p
1916}
1917
Colin Cross7707b242024-07-26 12:02:36 -07001918func (p InstallPath) WithoutRel() Path {
1919 p.basePath = p.basePath.withoutRel()
1920 return p
1921}
1922
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02001923func (p InstallPath) getSoongOutDir() string {
1924 return p.soongOutDir
Paul Duffin9b478b02019-12-10 13:41:51 +00001925}
1926
Hans MÃ¥nssond3f2bd72020-11-27 12:37:28 +01001927func (p InstallPath) ReplaceExtension(ctx PathContext, ext string) OutputPath {
1928 panic("Not implemented")
1929}
1930
Paul Duffin9b478b02019-12-10 13:41:51 +00001931var _ Path = InstallPath{}
1932var _ WritablePath = InstallPath{}
1933
Colin Cross70dda7e2019-10-01 22:05:35 -07001934func (p InstallPath) writablePath() {}
1935
1936func (p InstallPath) String() string {
Colin Crossc0e42d52024-02-01 16:42:36 -08001937 return p.fullPath
Jiyong Park957bcd92020-10-20 18:23:33 +09001938}
1939
1940// PartitionDir returns the path to the partition where the install path is rooted at. It is
1941// out/soong/target/product/<device>/<partition> for device modules, and out/soong/host/<os>-<arch> for host modules.
1942// The ./soong is dropped if the install path is for Make.
1943func (p InstallPath) PartitionDir() string {
1944 if p.makePath {
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02001945 return filepath.Join(p.soongOutDir, "../", p.partitionDir)
Jiyong Park957bcd92020-10-20 18:23:33 +09001946 } else {
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02001947 return filepath.Join(p.soongOutDir, p.partitionDir)
Jiyong Park957bcd92020-10-20 18:23:33 +09001948 }
Colin Cross70dda7e2019-10-01 22:05:35 -07001949}
1950
Jihoon Kangf78a8902022-09-01 22:47:07 +00001951func (p InstallPath) Partition() string {
1952 return p.partition
1953}
1954
Colin Cross70dda7e2019-10-01 22:05:35 -07001955// Join creates a new InstallPath with paths... joined with the current path. The
1956// provided paths... may not use '..' to escape from the current path.
1957func (p InstallPath) Join(ctx PathContext, paths ...string) InstallPath {
1958 path, err := validatePath(paths...)
1959 if err != nil {
1960 reportPathError(ctx, err)
1961 }
1962 return p.withRel(path)
1963}
1964
1965func (p InstallPath) withRel(rel string) InstallPath {
1966 p.basePath = p.basePath.withRel(rel)
Colin Crossc0e42d52024-02-01 16:42:36 -08001967 p.fullPath = filepath.Join(p.fullPath, rel)
Colin Cross70dda7e2019-10-01 22:05:35 -07001968 return p
1969}
1970
Colin Crossc68db4b2021-11-11 18:59:15 -08001971// Deprecated: ToMakePath is a noop, PathForModuleInstall always returns Make paths when building
1972// embedded in Make.
Colin Crossff6c33d2019-10-02 16:01:35 -07001973func (p InstallPath) ToMakePath() InstallPath {
Jiyong Park957bcd92020-10-20 18:23:33 +09001974 p.makePath = true
Colin Crossff6c33d2019-10-02 16:01:35 -07001975 return p
Colin Cross70dda7e2019-10-01 22:05:35 -07001976}
1977
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001978// PathForModuleInstall returns a Path representing the install path for the
1979// module appended with paths...
Colin Cross70dda7e2019-10-01 22:05:35 -07001980func PathForModuleInstall(ctx ModuleInstallPathContext, pathComponents ...string) InstallPath {
Spandan Das5d1b9292021-06-03 19:36:41 +00001981 os, arch := osAndArch(ctx)
Cole Faust11edf552023-10-13 11:32:14 -07001982 partition := modulePartition(ctx, os.Class == Device)
Cole Faust3b703f32023-10-16 13:30:51 -07001983 return pathForInstall(ctx, os, arch, partition, pathComponents...)
Spandan Das5d1b9292021-06-03 19:36:41 +00001984}
1985
Colin Cross1d0eb7a2021-11-03 14:08:20 -07001986// PathForHostDexInstall returns an InstallPath representing the install path for the
1987// module appended with paths...
1988func PathForHostDexInstall(ctx ModuleInstallPathContext, pathComponents ...string) InstallPath {
Cole Faust3b703f32023-10-16 13:30:51 -07001989 return pathForInstall(ctx, ctx.Config().BuildOS, ctx.Config().BuildArch, "", pathComponents...)
Colin Cross1d0eb7a2021-11-03 14:08:20 -07001990}
1991
Spandan Das5d1b9292021-06-03 19:36:41 +00001992// PathForModuleInPartitionInstall is similar to PathForModuleInstall but partition is provided by the caller
1993func PathForModuleInPartitionInstall(ctx ModuleInstallPathContext, partition string, pathComponents ...string) InstallPath {
1994 os, arch := osAndArch(ctx)
Cole Faust3b703f32023-10-16 13:30:51 -07001995 return pathForInstall(ctx, os, arch, partition, pathComponents...)
Spandan Das5d1b9292021-06-03 19:36:41 +00001996}
1997
1998func osAndArch(ctx ModuleInstallPathContext) (OsType, ArchType) {
Colin Cross6e359402020-02-10 15:29:54 -08001999 os := ctx.Os()
Jiyong Park87788b52020-09-01 12:37:45 +09002000 arch := ctx.Arch().ArchType
2001 forceOS, forceArch := ctx.InstallForceOS()
2002 if forceOS != nil {
Colin Cross6e359402020-02-10 15:29:54 -08002003 os = *forceOS
2004 }
Jiyong Park87788b52020-09-01 12:37:45 +09002005 if forceArch != nil {
2006 arch = *forceArch
2007 }
Spandan Das5d1b9292021-06-03 19:36:41 +00002008 return os, arch
2009}
Colin Cross609c49a2020-02-13 13:20:11 -08002010
Colin Crossc0e42d52024-02-01 16:42:36 -08002011func pathForPartitionInstallDir(ctx PathContext, partition, partitionPath string, makePath bool) InstallPath {
2012 fullPath := ctx.Config().SoongOutDir()
2013 if makePath {
2014 // Make path starts with out/ instead of out/soong.
2015 fullPath = filepath.Join(fullPath, "../", partitionPath)
2016 } else {
2017 fullPath = filepath.Join(fullPath, partitionPath)
2018 }
2019
2020 return InstallPath{
2021 basePath: basePath{partitionPath, ""},
2022 soongOutDir: ctx.Config().soongOutDir,
2023 partitionDir: partitionPath,
2024 partition: partition,
2025 makePath: makePath,
2026 fullPath: fullPath,
2027 }
2028}
2029
Cole Faust3b703f32023-10-16 13:30:51 -07002030func pathForInstall(ctx PathContext, os OsType, arch ArchType, partition string,
Colin Cross609c49a2020-02-13 13:20:11 -08002031 pathComponents ...string) InstallPath {
2032
Jiyong Park97859152023-02-14 17:05:48 +09002033 var partitionPaths []string
Colin Cross609c49a2020-02-13 13:20:11 -08002034
Colin Cross6e359402020-02-10 15:29:54 -08002035 if os.Class == Device {
Jiyong Park97859152023-02-14 17:05:48 +09002036 partitionPaths = []string{"target", "product", ctx.Config().DeviceName(), partition}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07002037 } else {
Jiyong Park87788b52020-09-01 12:37:45 +09002038 osName := os.String()
Colin Crossa9b2aac2022-06-15 17:25:51 -07002039 if os == Linux {
Jiyong Park87788b52020-09-01 12:37:45 +09002040 // instead of linux_glibc
2041 osName = "linux"
Dan Willemsen866b5632017-09-22 12:28:24 -07002042 }
Colin Crossa9b2aac2022-06-15 17:25:51 -07002043 if os == LinuxMusl && ctx.Config().UseHostMusl() {
2044 // When using musl instead of glibc, use "linux" instead of "linux_musl". When cross
2045 // compiling we will still use "linux_musl".
2046 osName = "linux"
2047 }
2048
Jiyong Park87788b52020-09-01 12:37:45 +09002049 // SOONG_HOST_OUT is set to out/host/$(HOST_OS)-$(HOST_PREBUILT_ARCH)
2050 // and HOST_PREBUILT_ARCH is forcibly set to x86 even on x86_64 hosts. We don't seem
2051 // to have a plan to fix it (see the comment in build/make/core/envsetup.mk).
2052 // Let's keep using x86 for the existing cases until we have a need to support
2053 // other architectures.
2054 archName := arch.String()
2055 if os.Class == Host && (arch == X86_64 || arch == Common) {
2056 archName = "x86"
2057 }
Jiyong Park97859152023-02-14 17:05:48 +09002058 partitionPaths = []string{"host", osName + "-" + archName, partition}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07002059 }
Colin Cross70dda7e2019-10-01 22:05:35 -07002060
Jiyong Park97859152023-02-14 17:05:48 +09002061 partitionPath, err := validatePath(partitionPaths...)
Colin Cross70dda7e2019-10-01 22:05:35 -07002062 if err != nil {
2063 reportPathError(ctx, err)
2064 }
Colin Crossff6c33d2019-10-02 16:01:35 -07002065
Colin Crossc0e42d52024-02-01 16:42:36 -08002066 base := pathForPartitionInstallDir(ctx, partition, partitionPath, ctx.Config().KatiEnabled())
Jiyong Park957bcd92020-10-20 18:23:33 +09002067 return base.Join(ctx, pathComponents...)
Dan Willemsen34cc69e2015-09-23 15:26:20 -07002068}
2069
Spandan Dasf280b232024-04-04 21:25:51 +00002070func PathForNdkInstall(ctx PathContext, paths ...string) OutputPath {
2071 return PathForOutput(ctx, append([]string{"ndk"}, paths...)...)
Nicolas Geoffray1228e9c2020-02-27 13:45:35 +00002072}
2073
2074func PathForMainlineSdksInstall(ctx PathContext, paths ...string) InstallPath {
Spandan Dasf280b232024-04-04 21:25:51 +00002075 base := pathForPartitionInstallDir(ctx, "", "mainline-sdks", false)
2076 return base.Join(ctx, paths...)
Nicolas Geoffray1228e9c2020-02-27 13:45:35 +00002077}
2078
Colin Cross70dda7e2019-10-01 22:05:35 -07002079func InstallPathToOnDevicePath(ctx PathContext, path InstallPath) string {
Colin Crossb1692a32021-10-25 15:39:01 -07002080 rel := Rel(ctx, strings.TrimSuffix(path.PartitionDir(), path.partition), path.String())
Colin Cross43f08db2018-11-12 10:13:39 -08002081 return "/" + rel
2082}
2083
Cole Faust11edf552023-10-13 11:32:14 -07002084func modulePartition(ctx ModuleInstallPathContext, device bool) string {
Colin Cross43f08db2018-11-12 10:13:39 -08002085 var partition string
Colin Cross6e359402020-02-10 15:29:54 -08002086 if ctx.InstallInTestcases() {
2087 // "testcases" install directory can be used for host or device modules.
Jaewoong Jung0949f312019-09-11 10:25:18 -07002088 partition = "testcases"
Cole Faust11edf552023-10-13 11:32:14 -07002089 } else if device {
Colin Cross6e359402020-02-10 15:29:54 -08002090 if ctx.InstallInData() {
2091 partition = "data"
2092 } else if ctx.InstallInRamdisk() {
2093 if ctx.DeviceConfig().BoardUsesRecoveryAsBoot() {
2094 partition = "recovery/root/first_stage_ramdisk"
2095 } else {
2096 partition = "ramdisk"
2097 }
2098 if !ctx.InstallInRoot() {
2099 partition += "/system"
2100 }
Yifan Hong60e0cfb2020-10-21 15:17:56 -07002101 } else if ctx.InstallInVendorRamdisk() {
Yifan Hong39143a92020-10-26 12:43:12 -07002102 // The module is only available after switching root into
2103 // /first_stage_ramdisk. To expose the module before switching root
2104 // on a device without a dedicated recovery partition, install the
2105 // recovery variant.
Yifan Hongdd8dacc2020-10-21 15:40:17 -07002106 if ctx.DeviceConfig().BoardMoveRecoveryResourcesToVendorBoot() {
Petri Gyntherac229562021-03-02 23:44:02 -08002107 partition = "vendor_ramdisk/first_stage_ramdisk"
Yifan Hongdd8dacc2020-10-21 15:40:17 -07002108 } else {
Petri Gyntherac229562021-03-02 23:44:02 -08002109 partition = "vendor_ramdisk"
Yifan Hongdd8dacc2020-10-21 15:40:17 -07002110 }
2111 if !ctx.InstallInRoot() {
2112 partition += "/system"
2113 }
Inseob Kim08758f02021-04-08 21:13:22 +09002114 } else if ctx.InstallInDebugRamdisk() {
2115 partition = "debug_ramdisk"
Colin Cross6e359402020-02-10 15:29:54 -08002116 } else if ctx.InstallInRecovery() {
2117 if ctx.InstallInRoot() {
2118 partition = "recovery/root"
2119 } else {
2120 // the layout of recovery partion is the same as that of system partition
2121 partition = "recovery/root/system"
2122 }
Colin Crossea30d852023-11-29 16:00:16 -08002123 } else if ctx.SocSpecific() || ctx.InstallInVendor() {
Colin Cross6e359402020-02-10 15:29:54 -08002124 partition = ctx.DeviceConfig().VendorPath()
Colin Crossea30d852023-11-29 16:00:16 -08002125 } else if ctx.DeviceSpecific() || ctx.InstallInOdm() {
Colin Cross6e359402020-02-10 15:29:54 -08002126 partition = ctx.DeviceConfig().OdmPath()
Colin Crossea30d852023-11-29 16:00:16 -08002127 } else if ctx.ProductSpecific() || ctx.InstallInProduct() {
Colin Cross6e359402020-02-10 15:29:54 -08002128 partition = ctx.DeviceConfig().ProductPath()
2129 } else if ctx.SystemExtSpecific() {
2130 partition = ctx.DeviceConfig().SystemExtPath()
2131 } else if ctx.InstallInRoot() {
2132 partition = "root"
Yifan Hong82db7352020-01-21 16:12:26 -08002133 } else {
Colin Cross6e359402020-02-10 15:29:54 -08002134 partition = "system"
Yifan Hong82db7352020-01-21 16:12:26 -08002135 }
Colin Cross6e359402020-02-10 15:29:54 -08002136 if ctx.InstallInSanitizerDir() {
2137 partition = "data/asan/" + partition
Yifan Hong82db7352020-01-21 16:12:26 -08002138 }
Colin Cross43f08db2018-11-12 10:13:39 -08002139 }
2140 return partition
2141}
2142
Colin Cross609c49a2020-02-13 13:20:11 -08002143type InstallPaths []InstallPath
2144
2145// Paths returns the InstallPaths as a Paths
2146func (p InstallPaths) Paths() Paths {
2147 if p == nil {
2148 return nil
2149 }
2150 ret := make(Paths, len(p))
2151 for i, path := range p {
2152 ret[i] = path
2153 }
2154 return ret
2155}
2156
2157// Strings returns the string forms of the install paths.
2158func (p InstallPaths) Strings() []string {
2159 if p == nil {
2160 return nil
2161 }
2162 ret := make([]string, len(p))
2163 for i, path := range p {
2164 ret[i] = path.String()
2165 }
2166 return ret
2167}
2168
Jingwen Chen24d0c562023-02-07 09:29:36 +00002169// validatePathInternal ensures that a path does not leave its component, and
2170// optionally doesn't contain Ninja variables.
2171func validatePathInternal(allowNinjaVariables bool, pathComponents ...string) (string, error) {
Colin Crossbf9ed3f2023-10-24 14:17:03 -07002172 initialEmpty := 0
2173 finalEmpty := 0
2174 for i, path := range pathComponents {
Jingwen Chen24d0c562023-02-07 09:29:36 +00002175 if !allowNinjaVariables && strings.Contains(path, "$") {
2176 return "", fmt.Errorf("Path contains invalid character($): %s", path)
2177 }
2178
Dan Willemsen80a7c2a2015-12-21 14:57:11 -08002179 path := filepath.Clean(path)
2180 if path == ".." || strings.HasPrefix(path, "../") || strings.HasPrefix(path, "/") {
Colin Cross1ccfcc32018-02-22 13:54:26 -08002181 return "", fmt.Errorf("Path is outside directory: %s", path)
Dan Willemsen80a7c2a2015-12-21 14:57:11 -08002182 }
Colin Crossbf9ed3f2023-10-24 14:17:03 -07002183
2184 if i == initialEmpty && pathComponents[i] == "" {
2185 initialEmpty++
2186 }
2187 if i == finalEmpty && pathComponents[len(pathComponents)-1-i] == "" {
2188 finalEmpty++
2189 }
Dan Willemsen80a7c2a2015-12-21 14:57:11 -08002190 }
Colin Crossbf9ed3f2023-10-24 14:17:03 -07002191 // Optimization: filepath.Join("foo", "") returns a newly allocated copy
2192 // of "foo", while filepath.Join("foo") does not. Strip out any empty
2193 // path components.
2194 if initialEmpty == len(pathComponents) {
2195 return "", nil
2196 }
2197 nonEmptyPathComponents := pathComponents[initialEmpty : len(pathComponents)-finalEmpty]
Dan Willemsen34cc69e2015-09-23 15:26:20 -07002198 // TODO: filepath.Join isn't necessarily correct with embedded ninja
2199 // variables. '..' may remove the entire ninja variable, even if it
2200 // will be expanded to multiple nested directories.
Colin Crossbf9ed3f2023-10-24 14:17:03 -07002201 return filepath.Join(nonEmptyPathComponents...), nil
Dan Willemsen34cc69e2015-09-23 15:26:20 -07002202}
2203
Jingwen Chen24d0c562023-02-07 09:29:36 +00002204// validateSafePath validates a path that we trust (may contain ninja
2205// variables). Ensures that each path component does not attempt to leave its
2206// component. Returns a joined version of each path component.
2207func validateSafePath(pathComponents ...string) (string, error) {
2208 return validatePathInternal(true, pathComponents...)
2209}
2210
Dan Willemsen80a7c2a2015-12-21 14:57:11 -08002211// validatePath validates that a path does not include ninja variables, and that
2212// each path component does not attempt to leave its component. Returns a joined
2213// version of each path component.
Colin Cross1ccfcc32018-02-22 13:54:26 -08002214func validatePath(pathComponents ...string) (string, error) {
Jingwen Chen24d0c562023-02-07 09:29:36 +00002215 return validatePathInternal(false, pathComponents...)
Colin Cross6e18ca42015-07-14 18:55:36 -07002216}
Colin Cross5b529592017-05-09 13:34:34 -07002217
Colin Cross0875c522017-11-28 17:34:01 -08002218func PathForPhony(ctx PathContext, phony string) WritablePath {
2219 if strings.ContainsAny(phony, "$/") {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01002220 ReportPathErrorf(ctx, "Phony target contains invalid character ($ or /): %s", phony)
Colin Cross0875c522017-11-28 17:34:01 -08002221 }
Paul Duffin74abc5d2021-03-24 09:24:59 +00002222 return PhonyPath{basePath{phony, ""}}
Colin Cross0875c522017-11-28 17:34:01 -08002223}
2224
Colin Cross74e3fe42017-12-11 15:51:44 -08002225type PhonyPath struct {
2226 basePath
2227}
2228
2229func (p PhonyPath) writablePath() {}
2230
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02002231func (p PhonyPath) getSoongOutDir() string {
Paul Duffind65c58b2021-03-24 09:22:07 +00002232 // A phone path cannot contain any / so cannot be relative to the build directory.
2233 return ""
Paul Duffin9b478b02019-12-10 13:41:51 +00002234}
2235
Paul Duffin85d8f0d2021-03-24 10:18:18 +00002236func (p PhonyPath) RelativeToTop() Path {
2237 ensureTestOnly()
2238 // A phony path cannot contain any / so does not have a build directory so switching to a new
2239 // build directory has no effect so just return this path.
2240 return p
2241}
2242
Colin Cross7707b242024-07-26 12:02:36 -07002243func (p PhonyPath) WithoutRel() Path {
2244 p.basePath = p.basePath.withoutRel()
2245 return p
2246}
2247
Hans MÃ¥nssond3f2bd72020-11-27 12:37:28 +01002248func (p PhonyPath) ReplaceExtension(ctx PathContext, ext string) OutputPath {
2249 panic("Not implemented")
2250}
2251
Colin Cross74e3fe42017-12-11 15:51:44 -08002252var _ Path = PhonyPath{}
2253var _ WritablePath = PhonyPath{}
2254
Colin Cross5b529592017-05-09 13:34:34 -07002255type testPath struct {
2256 basePath
2257}
2258
Paul Duffin85d8f0d2021-03-24 10:18:18 +00002259func (p testPath) RelativeToTop() Path {
2260 ensureTestOnly()
2261 return p
2262}
2263
Colin Cross7707b242024-07-26 12:02:36 -07002264func (p testPath) WithoutRel() Path {
2265 p.basePath = p.basePath.withoutRel()
2266 return p
2267}
2268
Colin Cross5b529592017-05-09 13:34:34 -07002269func (p testPath) String() string {
2270 return p.path
2271}
2272
Paul Duffin85d8f0d2021-03-24 10:18:18 +00002273var _ Path = testPath{}
2274
Colin Cross40e33732019-02-15 11:08:35 -08002275// PathForTesting returns a Path constructed from joining the elements of paths with '/'. It should only be used from
2276// within tests.
Colin Cross5b529592017-05-09 13:34:34 -07002277func PathForTesting(paths ...string) Path {
Colin Cross1ccfcc32018-02-22 13:54:26 -08002278 p, err := validateSafePath(paths...)
2279 if err != nil {
2280 panic(err)
2281 }
Colin Cross5b529592017-05-09 13:34:34 -07002282 return testPath{basePath{path: p, rel: p}}
2283}
2284
Sam Delmerico2351eac2022-05-24 17:10:02 +00002285func PathForTestingWithRel(path, rel string) Path {
2286 p, err := validateSafePath(path, rel)
2287 if err != nil {
2288 panic(err)
2289 }
2290 r, err := validatePath(rel)
2291 if err != nil {
2292 panic(err)
2293 }
2294 return testPath{basePath{path: p, rel: r}}
2295}
2296
Colin Cross40e33732019-02-15 11:08:35 -08002297// PathsForTesting returns a Path constructed from each element in strs. It should only be used from within tests.
2298func PathsForTesting(strs ...string) Paths {
Colin Cross5b529592017-05-09 13:34:34 -07002299 p := make(Paths, len(strs))
2300 for i, s := range strs {
2301 p[i] = PathForTesting(s)
2302 }
2303
2304 return p
2305}
Colin Cross43f08db2018-11-12 10:13:39 -08002306
Colin Cross40e33732019-02-15 11:08:35 -08002307type testPathContext struct {
2308 config Config
Colin Cross40e33732019-02-15 11:08:35 -08002309}
2310
Colin Cross40e33732019-02-15 11:08:35 -08002311func (x *testPathContext) Config() Config { return x.config }
2312func (x *testPathContext) AddNinjaFileDeps(...string) {}
2313
2314// PathContextForTesting returns a PathContext that can be used in tests, for example to create an OutputPath with
2315// PathForOutput.
Colin Cross98be1bb2019-12-13 20:41:13 -08002316func PathContextForTesting(config Config) PathContext {
Colin Cross40e33732019-02-15 11:08:35 -08002317 return &testPathContext{
2318 config: config,
Colin Cross40e33732019-02-15 11:08:35 -08002319 }
2320}
2321
Ulya Trafimovichccc8c852020-10-14 11:29:07 +01002322type testModuleInstallPathContext struct {
2323 baseModuleContext
2324
2325 inData bool
2326 inTestcases bool
2327 inSanitizerDir bool
2328 inRamdisk bool
2329 inVendorRamdisk bool
Inseob Kim08758f02021-04-08 21:13:22 +09002330 inDebugRamdisk bool
Ulya Trafimovichccc8c852020-10-14 11:29:07 +01002331 inRecovery bool
2332 inRoot bool
Colin Crossea30d852023-11-29 16:00:16 -08002333 inOdm bool
2334 inProduct bool
2335 inVendor bool
Ulya Trafimovichccc8c852020-10-14 11:29:07 +01002336 forceOS *OsType
2337 forceArch *ArchType
2338}
2339
2340func (m testModuleInstallPathContext) Config() Config {
2341 return m.baseModuleContext.config
2342}
2343
2344func (testModuleInstallPathContext) AddNinjaFileDeps(deps ...string) {}
2345
2346func (m testModuleInstallPathContext) InstallInData() bool {
2347 return m.inData
2348}
2349
2350func (m testModuleInstallPathContext) InstallInTestcases() bool {
2351 return m.inTestcases
2352}
2353
2354func (m testModuleInstallPathContext) InstallInSanitizerDir() bool {
2355 return m.inSanitizerDir
2356}
2357
2358func (m testModuleInstallPathContext) InstallInRamdisk() bool {
2359 return m.inRamdisk
2360}
2361
2362func (m testModuleInstallPathContext) InstallInVendorRamdisk() bool {
2363 return m.inVendorRamdisk
2364}
2365
Inseob Kim08758f02021-04-08 21:13:22 +09002366func (m testModuleInstallPathContext) InstallInDebugRamdisk() bool {
2367 return m.inDebugRamdisk
2368}
2369
Ulya Trafimovichccc8c852020-10-14 11:29:07 +01002370func (m testModuleInstallPathContext) InstallInRecovery() bool {
2371 return m.inRecovery
2372}
2373
2374func (m testModuleInstallPathContext) InstallInRoot() bool {
2375 return m.inRoot
2376}
2377
Colin Crossea30d852023-11-29 16:00:16 -08002378func (m testModuleInstallPathContext) InstallInOdm() bool {
2379 return m.inOdm
2380}
2381
2382func (m testModuleInstallPathContext) InstallInProduct() bool {
2383 return m.inProduct
2384}
2385
2386func (m testModuleInstallPathContext) InstallInVendor() bool {
2387 return m.inVendor
2388}
2389
Ulya Trafimovichccc8c852020-10-14 11:29:07 +01002390func (m testModuleInstallPathContext) InstallForceOS() (*OsType, *ArchType) {
2391 return m.forceOS, m.forceArch
2392}
2393
2394// Construct a minimal ModuleInstallPathContext for testing. Note that baseModuleContext is
2395// default-initialized, which leaves blueprint.baseModuleContext set to nil, so methods that are
2396// delegated to it will panic.
2397func ModuleInstallPathContextForTesting(config Config) ModuleInstallPathContext {
2398 ctx := &testModuleInstallPathContext{}
2399 ctx.config = config
2400 ctx.os = Android
2401 return ctx
2402}
2403
Colin Cross43f08db2018-11-12 10:13:39 -08002404// Rel performs the same function as filepath.Rel, but reports errors to a PathContext, and reports an error if
2405// targetPath is not inside basePath.
2406func Rel(ctx PathContext, basePath string, targetPath string) string {
2407 rel, isRel := MaybeRel(ctx, basePath, targetPath)
2408 if !isRel {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01002409 ReportPathErrorf(ctx, "path %q is not under path %q", targetPath, basePath)
Colin Cross43f08db2018-11-12 10:13:39 -08002410 return ""
2411 }
2412 return rel
2413}
2414
2415// MaybeRel performs the same function as filepath.Rel, but reports errors to a PathContext, and returns false if
2416// targetPath is not inside basePath.
2417func MaybeRel(ctx PathContext, basePath string, targetPath string) (string, bool) {
Dan Willemsen633c5022019-04-12 11:11:38 -07002418 rel, isRel, err := maybeRelErr(basePath, targetPath)
2419 if err != nil {
2420 reportPathError(ctx, err)
2421 }
2422 return rel, isRel
2423}
2424
2425func maybeRelErr(basePath string, targetPath string) (string, bool, error) {
Colin Cross43f08db2018-11-12 10:13:39 -08002426 // filepath.Rel returns an error if one path is absolute and the other is not, handle that case first.
2427 if filepath.IsAbs(basePath) != filepath.IsAbs(targetPath) {
Dan Willemsen633c5022019-04-12 11:11:38 -07002428 return "", false, nil
Colin Cross43f08db2018-11-12 10:13:39 -08002429 }
2430 rel, err := filepath.Rel(basePath, targetPath)
2431 if err != nil {
Dan Willemsen633c5022019-04-12 11:11:38 -07002432 return "", false, err
Colin Cross43f08db2018-11-12 10:13:39 -08002433 } else if rel == ".." || strings.HasPrefix(rel, "../") || strings.HasPrefix(rel, "/") {
Dan Willemsen633c5022019-04-12 11:11:38 -07002434 return "", false, nil
Colin Cross43f08db2018-11-12 10:13:39 -08002435 }
Dan Willemsen633c5022019-04-12 11:11:38 -07002436 return rel, true, nil
Colin Cross43f08db2018-11-12 10:13:39 -08002437}
Colin Cross988414c2020-01-11 01:11:46 +00002438
2439// Writes a file to the output directory. Attempting to write directly to the output directory
2440// will fail due to the sandbox of the soong_build process.
Chris Parsons1a12d032023-02-06 22:37:41 -05002441// Only writes the file if the file doesn't exist or if it has different contents, to prevent
2442// updating the timestamp if no changes would be made. (This is better for incremental
2443// performance.)
Colin Cross988414c2020-01-11 01:11:46 +00002444func WriteFileToOutputDir(path WritablePath, data []byte, perm os.FileMode) error {
Colin Crossd6421132021-11-09 12:32:34 -08002445 absPath := absolutePath(path.String())
2446 err := os.MkdirAll(filepath.Dir(absPath), 0777)
2447 if err != nil {
2448 return err
2449 }
Chris Parsons1a12d032023-02-06 22:37:41 -05002450 return pathtools.WriteFileIfChanged(absPath, data, perm)
Colin Cross988414c2020-01-11 01:11:46 +00002451}
2452
Liz Kammer2dd9ca42020-11-25 16:06:39 -08002453func RemoveAllOutputDir(path WritablePath) error {
2454 return os.RemoveAll(absolutePath(path.String()))
2455}
2456
2457func CreateOutputDirIfNonexistent(path WritablePath, perm os.FileMode) error {
2458 dir := absolutePath(path.String())
Liz Kammer09f947d2021-05-12 14:51:49 -04002459 return createDirIfNonexistent(dir, perm)
2460}
2461
2462func createDirIfNonexistent(dir string, perm os.FileMode) error {
Liz Kammer2dd9ca42020-11-25 16:06:39 -08002463 if _, err := os.Stat(dir); os.IsNotExist(err) {
2464 return os.MkdirAll(dir, os.ModePerm)
2465 } else {
2466 return err
2467 }
2468}
2469
Jingwen Chen78257e52021-05-21 02:34:24 +00002470// absolutePath is deliberately private so that Soong's Go plugins can't use it to find and
2471// read arbitrary files without going through the methods in the current package that track
2472// dependencies.
Colin Cross988414c2020-01-11 01:11:46 +00002473func absolutePath(path string) string {
2474 if filepath.IsAbs(path) {
2475 return path
2476 }
2477 return filepath.Join(absSrcDir, path)
2478}
Chris Parsons216e10a2020-07-09 17:12:52 -04002479
2480// A DataPath represents the path of a file to be used as data, for example
2481// a test library to be installed alongside a test.
2482// The data file should be installed (copied from `<SrcPath>`) to
2483// `<install_root>/<RelativeInstallPath>/<filename>`, or
2484// `<install_root>/<filename>` if RelativeInstallPath is empty.
2485type DataPath struct {
2486 // The path of the data file that should be copied into the data directory
2487 SrcPath Path
2488 // The install path of the data file, relative to the install root.
2489 RelativeInstallPath string
Colin Cross5c1d5fb2023-11-15 12:39:40 -08002490 // If WithoutRel is true, use SrcPath.Base() instead of SrcPath.Rel() as the filename.
2491 WithoutRel bool
Chris Parsons216e10a2020-07-09 17:12:52 -04002492}
Colin Crossdcf71b22021-02-01 13:59:03 -08002493
Colin Crossd442a0e2023-11-16 11:19:26 -08002494func (d *DataPath) ToRelativeInstallPath() string {
2495 relPath := d.SrcPath.Rel()
Colin Cross5c1d5fb2023-11-15 12:39:40 -08002496 if d.WithoutRel {
2497 relPath = d.SrcPath.Base()
2498 }
Colin Crossd442a0e2023-11-16 11:19:26 -08002499 if d.RelativeInstallPath != "" {
2500 relPath = filepath.Join(d.RelativeInstallPath, relPath)
2501 }
2502 return relPath
2503}
2504
Colin Crossdcf71b22021-02-01 13:59:03 -08002505// PathsIfNonNil returns a Paths containing only the non-nil input arguments.
2506func PathsIfNonNil(paths ...Path) Paths {
2507 if len(paths) == 0 {
2508 // Fast path for empty argument list
2509 return nil
2510 } else if len(paths) == 1 {
2511 // Fast path for a single argument
2512 if paths[0] != nil {
2513 return paths
2514 } else {
2515 return nil
2516 }
2517 }
2518 ret := make(Paths, 0, len(paths))
2519 for _, path := range paths {
2520 if path != nil {
2521 ret = append(ret, path)
2522 }
2523 }
2524 if len(ret) == 0 {
2525 return nil
2526 }
2527 return ret
2528}
Chris Wailesb2703ad2021-07-30 13:25:42 -07002529
2530var thirdPartyDirPrefixExceptions = []*regexp.Regexp{
2531 regexp.MustCompile("^vendor/[^/]*google[^/]*/"),
2532 regexp.MustCompile("^hardware/google/"),
2533 regexp.MustCompile("^hardware/interfaces/"),
2534 regexp.MustCompile("^hardware/libhardware[^/]*/"),
2535 regexp.MustCompile("^hardware/ril/"),
2536}
2537
2538func IsThirdPartyPath(path string) bool {
2539 thirdPartyDirPrefixes := []string{"external/", "vendor/", "hardware/"}
2540
2541 if HasAnyPrefix(path, thirdPartyDirPrefixes) {
2542 for _, prefix := range thirdPartyDirPrefixExceptions {
2543 if prefix.MatchString(path) {
2544 return false
2545 }
2546 }
2547 return true
2548 }
2549 return false
2550}