blob: 0d94f03e6bb2af594a67520d9b64a45300c08e6b [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 (
Yu Liufa297642024-06-11 00:13:02 +000018 "bytes"
19 "encoding/gob"
20 "errors"
Colin Cross6e18ca42015-07-14 18:55:36 -070021 "fmt"
Colin Cross988414c2020-01-11 01:11:46 +000022 "os"
Colin Cross6a745c62015-06-16 16:38:10 -070023 "path/filepath"
Dan Willemsen34cc69e2015-09-23 15:26:20 -070024 "reflect"
Chris Wailesb2703ad2021-07-30 13:25:42 -070025 "regexp"
Colin Cross5e6cfbe2017-11-03 15:20:35 -070026 "sort"
Dan Willemsen34cc69e2015-09-23 15:26:20 -070027 "strings"
28
29 "github.com/google/blueprint"
30 "github.com/google/blueprint/pathtools"
Colin Cross3f40fa42015-01-30 17:27:36 -080031)
32
Colin Cross988414c2020-01-11 01:11:46 +000033var absSrcDir string
34
Dan Willemsen34cc69e2015-09-23 15:26:20 -070035// PathContext is the subset of a (Module|Singleton)Context required by the
36// Path methods.
37type PathContext interface {
Colin Crossaabf6792017-11-29 00:27:14 -080038 Config() Config
Dan Willemsen7b310ee2015-12-18 15:11:17 -080039 AddNinjaFileDeps(deps ...string)
Colin Cross3f40fa42015-01-30 17:27:36 -080040}
41
Colin Cross7f19f372016-11-01 11:10:25 -070042type PathGlobContext interface {
Colin Cross662d6142022-11-03 20:38:01 -070043 PathContext
Colin Cross7f19f372016-11-01 11:10:25 -070044 GlobWithDeps(globPattern string, excludes []string) ([]string, error)
45}
46
Colin Crossaabf6792017-11-29 00:27:14 -080047var _ PathContext = SingletonContext(nil)
48var _ PathContext = ModuleContext(nil)
Dan Willemsen34cc69e2015-09-23 15:26:20 -070049
Ulya Trafimovich8640ab92020-05-11 18:06:15 +010050// "Null" path context is a minimal path context for a given config.
51type NullPathContext struct {
52 config Config
53}
54
55func (NullPathContext) AddNinjaFileDeps(...string) {}
56func (ctx NullPathContext) Config() Config { return ctx.config }
57
Liz Kammera830f3a2020-11-10 10:50:34 -080058// EarlyModulePathContext is a subset of EarlyModuleContext methods required by the
59// Path methods. These path methods can be called before any mutators have run.
60type EarlyModulePathContext interface {
Liz Kammera830f3a2020-11-10 10:50:34 -080061 PathGlobContext
62
63 ModuleDir() string
64 ModuleErrorf(fmt string, args ...interface{})
Cole Fausta963b942024-04-11 17:43:00 -070065 OtherModulePropertyErrorf(module Module, property, fmt string, args ...interface{})
Liz Kammera830f3a2020-11-10 10:50:34 -080066}
67
68var _ EarlyModulePathContext = ModuleContext(nil)
69
70// Glob globs files and directories matching globPattern relative to ModuleDir(),
71// paths in the excludes parameter will be omitted.
72func Glob(ctx EarlyModulePathContext, globPattern string, excludes []string) Paths {
73 ret, err := ctx.GlobWithDeps(globPattern, excludes)
74 if err != nil {
75 ctx.ModuleErrorf("glob: %s", err.Error())
76 }
77 return pathsForModuleSrcFromFullPath(ctx, ret, true)
78}
79
80// GlobFiles globs *only* files (not directories) matching globPattern relative to ModuleDir().
81// Paths in the excludes parameter will be omitted.
82func GlobFiles(ctx EarlyModulePathContext, globPattern string, excludes []string) Paths {
83 ret, err := ctx.GlobWithDeps(globPattern, excludes)
84 if err != nil {
85 ctx.ModuleErrorf("glob: %s", err.Error())
86 }
87 return pathsForModuleSrcFromFullPath(ctx, ret, false)
88}
89
90// ModuleWithDepsPathContext is a subset of *ModuleContext methods required by
91// the Path methods that rely on module dependencies having been resolved.
92type ModuleWithDepsPathContext interface {
93 EarlyModulePathContext
Cole Faust55b56fe2024-08-23 12:06:11 -070094 OtherModuleProviderContext
Paul Duffin40131a32021-07-09 17:10:35 +010095 VisitDirectDepsBlueprint(visit func(blueprint.Module))
96 OtherModuleDependencyTag(m blueprint.Module) blueprint.DependencyTag
Cole Faust4e2bf9f2024-09-11 13:26:20 -070097 HasMutatorFinished(mutatorName string) bool
Liz Kammera830f3a2020-11-10 10:50:34 -080098}
99
100// ModuleMissingDepsPathContext is a subset of *ModuleContext methods required by
101// the Path methods that rely on module dependencies having been resolved and ability to report
102// missing dependency errors.
103type ModuleMissingDepsPathContext interface {
104 ModuleWithDepsPathContext
105 AddMissingDependencies(missingDeps []string)
106}
107
Dan Willemsen00269f22017-07-06 16:59:48 -0700108type ModuleInstallPathContext interface {
Colin Cross0ea8ba82019-06-06 14:33:29 -0700109 BaseModuleContext
Dan Willemsen00269f22017-07-06 16:59:48 -0700110
111 InstallInData() bool
Jaewoong Jung0949f312019-09-11 10:25:18 -0700112 InstallInTestcases() bool
Dan Willemsen00269f22017-07-06 16:59:48 -0700113 InstallInSanitizerDir() bool
Yifan Hong1b3348d2020-01-21 15:53:22 -0800114 InstallInRamdisk() bool
Yifan Hong60e0cfb2020-10-21 15:17:56 -0700115 InstallInVendorRamdisk() bool
Inseob Kim08758f02021-04-08 21:13:22 +0900116 InstallInDebugRamdisk() bool
Jiyong Parkf9332f12018-02-01 00:54:12 +0900117 InstallInRecovery() bool
Colin Cross90ba5f42019-10-02 11:10:58 -0700118 InstallInRoot() bool
Colin Crossea30d852023-11-29 16:00:16 -0800119 InstallInOdm() bool
120 InstallInProduct() bool
121 InstallInVendor() bool
Jiyong Park87788b52020-09-01 12:37:45 +0900122 InstallForceOS() (*OsType, *ArchType)
Dan Willemsen00269f22017-07-06 16:59:48 -0700123}
124
125var _ ModuleInstallPathContext = ModuleContext(nil)
126
Cole Faust11edf552023-10-13 11:32:14 -0700127type baseModuleContextToModuleInstallPathContext struct {
128 BaseModuleContext
129}
130
131func (ctx *baseModuleContextToModuleInstallPathContext) InstallInData() bool {
132 return ctx.Module().InstallInData()
133}
134
135func (ctx *baseModuleContextToModuleInstallPathContext) InstallInTestcases() bool {
136 return ctx.Module().InstallInTestcases()
137}
138
139func (ctx *baseModuleContextToModuleInstallPathContext) InstallInSanitizerDir() bool {
140 return ctx.Module().InstallInSanitizerDir()
141}
142
143func (ctx *baseModuleContextToModuleInstallPathContext) InstallInRamdisk() bool {
144 return ctx.Module().InstallInRamdisk()
145}
146
147func (ctx *baseModuleContextToModuleInstallPathContext) InstallInVendorRamdisk() bool {
148 return ctx.Module().InstallInVendorRamdisk()
149}
150
151func (ctx *baseModuleContextToModuleInstallPathContext) InstallInDebugRamdisk() bool {
152 return ctx.Module().InstallInDebugRamdisk()
153}
154
155func (ctx *baseModuleContextToModuleInstallPathContext) InstallInRecovery() bool {
156 return ctx.Module().InstallInRecovery()
157}
158
159func (ctx *baseModuleContextToModuleInstallPathContext) InstallInRoot() bool {
160 return ctx.Module().InstallInRoot()
161}
162
Colin Crossea30d852023-11-29 16:00:16 -0800163func (ctx *baseModuleContextToModuleInstallPathContext) InstallInOdm() bool {
164 return ctx.Module().InstallInOdm()
165}
166
167func (ctx *baseModuleContextToModuleInstallPathContext) InstallInProduct() bool {
168 return ctx.Module().InstallInProduct()
169}
170
171func (ctx *baseModuleContextToModuleInstallPathContext) InstallInVendor() bool {
172 return ctx.Module().InstallInVendor()
173}
174
Cole Faust11edf552023-10-13 11:32:14 -0700175func (ctx *baseModuleContextToModuleInstallPathContext) InstallForceOS() (*OsType, *ArchType) {
176 return ctx.Module().InstallForceOS()
177}
178
179var _ ModuleInstallPathContext = (*baseModuleContextToModuleInstallPathContext)(nil)
180
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700181// errorfContext is the interface containing the Errorf method matching the
182// Errorf method in blueprint.SingletonContext.
183type errorfContext interface {
184 Errorf(format string, args ...interface{})
Colin Cross3f40fa42015-01-30 17:27:36 -0800185}
186
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700187var _ errorfContext = blueprint.SingletonContext(nil)
188
Spandan Das59a4a2b2024-01-09 21:35:56 +0000189// ModuleErrorfContext is the interface containing the ModuleErrorf method matching
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700190// the ModuleErrorf method in blueprint.ModuleContext.
Spandan Das59a4a2b2024-01-09 21:35:56 +0000191type ModuleErrorfContext interface {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700192 ModuleErrorf(format string, args ...interface{})
Colin Cross3f40fa42015-01-30 17:27:36 -0800193}
194
Spandan Das59a4a2b2024-01-09 21:35:56 +0000195var _ ModuleErrorfContext = blueprint.ModuleContext(nil)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700196
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700197// reportPathError will register an error with the attached context. It
198// attempts ctx.ModuleErrorf for a better error message first, then falls
199// back to ctx.Errorf.
Colin Cross1ccfcc32018-02-22 13:54:26 -0800200func reportPathError(ctx PathContext, err error) {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +0100201 ReportPathErrorf(ctx, "%s", err.Error())
Colin Cross1ccfcc32018-02-22 13:54:26 -0800202}
203
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +0100204// ReportPathErrorf will register an error with the attached context. It
Colin Cross1ccfcc32018-02-22 13:54:26 -0800205// attempts ctx.ModuleErrorf for a better error message first, then falls
206// back to ctx.Errorf.
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +0100207func ReportPathErrorf(ctx PathContext, format string, args ...interface{}) {
Spandan Das59a4a2b2024-01-09 21:35:56 +0000208 if mctx, ok := ctx.(ModuleErrorfContext); ok {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700209 mctx.ModuleErrorf(format, args...)
210 } else if ectx, ok := ctx.(errorfContext); ok {
211 ectx.Errorf(format, args...)
212 } else {
213 panic(fmt.Sprintf(format, args...))
Colin Crossf2298272015-05-12 11:36:53 -0700214 }
215}
216
Colin Cross5e708052019-08-06 13:59:50 -0700217func pathContextName(ctx PathContext, module blueprint.Module) string {
218 if x, ok := ctx.(interface{ ModuleName(blueprint.Module) string }); ok {
219 return x.ModuleName(module)
220 } else if x, ok := ctx.(interface{ OtherModuleName(blueprint.Module) string }); ok {
221 return x.OtherModuleName(module)
222 }
223 return "unknown"
224}
225
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700226type Path interface {
227 // Returns the path in string form
228 String() string
229
Colin Cross4f6fc9c2016-10-26 10:05:25 -0700230 // Ext returns the extension of the last element of the path
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700231 Ext() string
Colin Cross4f6fc9c2016-10-26 10:05:25 -0700232
233 // Base returns the last element of the path
234 Base() string
Colin Crossfaeb7aa2017-02-01 14:12:44 -0800235
236 // Rel returns the portion of the path relative to the directory it was created from. For
237 // example, Rel on a PathsForModuleSrc would return the path relative to the module source
Colin Cross0db55682017-12-05 15:36:55 -0800238 // directory, and OutputPath.Join("foo").Rel() would return "foo".
Colin Crossfaeb7aa2017-02-01 14:12:44 -0800239 Rel() string
Paul Duffin85d8f0d2021-03-24 10:18:18 +0000240
Colin Cross7707b242024-07-26 12:02:36 -0700241 // WithoutRel returns a new Path with no relative path, i.e. Rel() will return the same value as Base().
242 WithoutRel() Path
243
Paul Duffin85d8f0d2021-03-24 10:18:18 +0000244 // RelativeToTop returns a new path relative to the top, it is provided solely for use in tests.
245 //
246 // It is guaranteed to always return the same type as it is called on, e.g. if called on an
247 // InstallPath then the returned value can be converted to an InstallPath.
248 //
249 // A standard build has the following structure:
250 // ../top/
251 // out/ - make install files go here.
Colin Cross3b1c6842024-07-26 11:52:57 -0700252 // out/soong - this is the outDir passed to NewTestConfig()
Paul Duffin85d8f0d2021-03-24 10:18:18 +0000253 // ... - the source files
254 //
255 // This function converts a path so that it appears relative to the ../top/ directory, i.e.
Colin Cross3b1c6842024-07-26 11:52:57 -0700256 // * Make install paths, which have the pattern "outDir/../<path>" are converted into the top
Paul Duffin85d8f0d2021-03-24 10:18:18 +0000257 // relative path "out/<path>"
Colin Cross3b1c6842024-07-26 11:52:57 -0700258 // * Soong install paths and other writable paths, which have the pattern "outDir/soong/<path>" are
Paul Duffin85d8f0d2021-03-24 10:18:18 +0000259 // converted into the top relative path "out/soong/<path>".
260 // * Source paths are already relative to the top.
261 // * Phony paths are not relative to anything.
262 // * toolDepPath have an absolute but known value in so don't need making relative to anything in
263 // order to test.
264 RelativeToTop() Path
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700265}
266
Paul Duffin85d8f0d2021-03-24 10:18:18 +0000267const (
Colin Cross3b1c6842024-07-26 11:52:57 -0700268 testOutDir = "out"
269 testOutSoongSubDir = "/soong"
270 TestOutSoongDir = testOutDir + testOutSoongSubDir
Paul Duffin85d8f0d2021-03-24 10:18:18 +0000271)
272
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700273// WritablePath is a type of path that can be used as an output for build rules.
274type WritablePath interface {
275 Path
276
Paul Duffin9b478b02019-12-10 13:41:51 +0000277 // return the path to the build directory.
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +0200278 getSoongOutDir() string
Paul Duffin9b478b02019-12-10 13:41:51 +0000279
Jeff Gaston734e3802017-04-10 15:47:24 -0700280 // the writablePath method doesn't directly do anything,
281 // but it allows a struct to distinguish between whether or not it implements the WritablePath interface
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700282 writablePath()
Hans MÃ¥nssond3f2bd72020-11-27 12:37:28 +0100283
284 ReplaceExtension(ctx PathContext, ext string) OutputPath
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700285}
286
287type genPathProvider interface {
Liz Kammera830f3a2020-11-10 10:50:34 -0800288 genPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleGenPath
yangbill6d032dd2024-04-18 03:05:49 +0000289 genPathWithExtAndTrimExt(ctx ModuleOutPathContext, subdir, ext string, trimExt string) ModuleGenPath
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700290}
291type objPathProvider interface {
Liz Kammera830f3a2020-11-10 10:50:34 -0800292 objPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleObjPath
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700293}
294type resPathProvider interface {
Liz Kammera830f3a2020-11-10 10:50:34 -0800295 resPathWithName(ctx ModuleOutPathContext, name string) ModuleResPath
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700296}
297
298// GenPathWithExt derives a new file path in ctx's generated sources directory
299// from the current path, but with the new extension.
Liz Kammera830f3a2020-11-10 10:50:34 -0800300func GenPathWithExt(ctx ModuleOutPathContext, subdir string, p Path, ext string) ModuleGenPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700301 if path, ok := p.(genPathProvider); ok {
Dan Willemsen21ec4902016-11-02 20:43:13 -0700302 return path.genPathWithExt(ctx, subdir, ext)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700303 }
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +0100304 ReportPathErrorf(ctx, "Tried to create generated file from unsupported path: %s(%s)", reflect.TypeOf(p).Name(), p)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700305 return PathForModuleGen(ctx)
306}
307
yangbill6d032dd2024-04-18 03:05:49 +0000308// GenPathWithExtAndTrimExt derives a new file path in ctx's generated sources directory
309// from the current path, but with the new extension and trim the suffix.
310func GenPathWithExtAndTrimExt(ctx ModuleOutPathContext, subdir string, p Path, ext string, trimExt string) ModuleGenPath {
311 if path, ok := p.(genPathProvider); ok {
312 return path.genPathWithExtAndTrimExt(ctx, subdir, ext, trimExt)
313 }
314 ReportPathErrorf(ctx, "Tried to create generated file from unsupported path: %s(%s)", reflect.TypeOf(p).Name(), p)
315 return PathForModuleGen(ctx)
316}
317
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700318// ObjPathWithExt derives a new file path in ctx's object directory from the
319// current path, but with the new extension.
Liz Kammera830f3a2020-11-10 10:50:34 -0800320func ObjPathWithExt(ctx ModuleOutPathContext, subdir string, p Path, ext string) ModuleObjPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700321 if path, ok := p.(objPathProvider); ok {
322 return path.objPathWithExt(ctx, subdir, ext)
323 }
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +0100324 ReportPathErrorf(ctx, "Tried to create object file from unsupported path: %s (%s)", reflect.TypeOf(p).Name(), p)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700325 return PathForModuleObj(ctx)
326}
327
328// ResPathWithName derives a new path in ctx's output resource directory, using
329// the current path to create the directory name, and the `name` argument for
330// the filename.
Liz Kammera830f3a2020-11-10 10:50:34 -0800331func ResPathWithName(ctx ModuleOutPathContext, p Path, name string) ModuleResPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700332 if path, ok := p.(resPathProvider); ok {
333 return path.resPathWithName(ctx, name)
334 }
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +0100335 ReportPathErrorf(ctx, "Tried to create res file from unsupported path: %s (%s)", reflect.TypeOf(p).Name(), p)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700336 return PathForModuleRes(ctx)
337}
338
339// OptionalPath is a container that may or may not contain a valid Path.
340type OptionalPath struct {
Martin Stjernholmc32dd1c2021-09-15 02:39:00 +0100341 path Path // nil if invalid.
342 invalidReason string // Not applicable if path != nil. "" if the reason is unknown.
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700343}
344
345// OptionalPathForPath returns an OptionalPath containing the path.
346func OptionalPathForPath(path Path) OptionalPath {
Martin Stjernholm2fee27f2021-09-16 14:11:12 +0100347 return OptionalPath{path: path}
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700348}
349
Martin Stjernholmc32dd1c2021-09-15 02:39:00 +0100350// InvalidOptionalPath returns an OptionalPath that is invalid with the given reason.
351func InvalidOptionalPath(reason string) OptionalPath {
352
353 return OptionalPath{invalidReason: reason}
354}
355
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700356// Valid returns whether there is a valid path
357func (p OptionalPath) Valid() bool {
Martin Stjernholm2fee27f2021-09-16 14:11:12 +0100358 return p.path != nil
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700359}
360
361// Path returns the Path embedded in this OptionalPath. You must be sure that
362// there is a valid path, since this method will panic if there is not.
363func (p OptionalPath) Path() Path {
Martin Stjernholm2fee27f2021-09-16 14:11:12 +0100364 if p.path == nil {
Martin Stjernholmc32dd1c2021-09-15 02:39:00 +0100365 msg := "Requesting an invalid path"
366 if p.invalidReason != "" {
367 msg += ": " + p.invalidReason
368 }
369 panic(msg)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700370 }
371 return p.path
372}
373
Martin Stjernholmc32dd1c2021-09-15 02:39:00 +0100374// InvalidReason returns the reason that the optional path is invalid, or "" if it is valid.
375func (p OptionalPath) InvalidReason() string {
376 if p.path != nil {
377 return ""
378 }
379 if p.invalidReason == "" {
380 return "unknown"
381 }
382 return p.invalidReason
383}
384
Paul Duffinef081852021-05-13 11:11:15 +0100385// AsPaths converts the OptionalPath into Paths.
386//
387// It returns nil if this is not valid, or a single length slice containing the Path embedded in
388// this OptionalPath.
389func (p OptionalPath) AsPaths() Paths {
Martin Stjernholm2fee27f2021-09-16 14:11:12 +0100390 if p.path == nil {
Paul Duffinef081852021-05-13 11:11:15 +0100391 return nil
392 }
393 return Paths{p.path}
394}
395
Paul Duffinafdd4062021-03-30 19:44:07 +0100396// RelativeToTop returns an OptionalPath with the path that was embedded having been replaced by the
397// result of calling Path.RelativeToTop on it.
398func (p OptionalPath) RelativeToTop() OptionalPath {
Martin Stjernholm2fee27f2021-09-16 14:11:12 +0100399 if p.path == nil {
Paul Duffina5b81352021-03-28 23:57:19 +0100400 return p
401 }
402 p.path = p.path.RelativeToTop()
403 return p
404}
405
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700406// String returns the string version of the Path, or "" if it isn't valid.
407func (p OptionalPath) String() string {
Martin Stjernholm2fee27f2021-09-16 14:11:12 +0100408 if p.path != nil {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700409 return p.path.String()
410 } else {
411 return ""
Colin Crossf2298272015-05-12 11:36:53 -0700412 }
413}
Colin Cross6e18ca42015-07-14 18:55:36 -0700414
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700415// Paths is a slice of Path objects, with helpers to operate on the collection.
416type Paths []Path
417
Paul Duffin85d8f0d2021-03-24 10:18:18 +0000418// RelativeToTop creates a new Paths containing the result of calling Path.RelativeToTop on each
419// item in this slice.
420func (p Paths) RelativeToTop() Paths {
421 ensureTestOnly()
422 if p == nil {
423 return p
424 }
425 ret := make(Paths, len(p))
426 for i, path := range p {
427 ret[i] = path.RelativeToTop()
428 }
429 return ret
430}
431
Jingwen Chen40fd90a2020-06-15 05:24:19 +0000432func (paths Paths) containsPath(path Path) bool {
433 for _, p := range paths {
434 if p == path {
435 return true
436 }
437 }
438 return false
439}
440
Liz Kammer7aa52882021-02-11 09:16:14 -0500441// PathsForSource returns Paths rooted from SrcDir, *not* rooted from the module's local source
442// directory
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700443func PathsForSource(ctx PathContext, paths []string) Paths {
444 ret := make(Paths, len(paths))
445 for i, path := range paths {
446 ret[i] = PathForSource(ctx, path)
447 }
448 return ret
449}
450
Liz Kammer7aa52882021-02-11 09:16:14 -0500451// ExistentPathsForSources returns a list of Paths rooted from SrcDir, *not* rooted from the
452// module's local source directory, that are found in the tree. If any are not found, they are
453// 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 -0700454func ExistentPathsForSources(ctx PathGlobContext, paths []string) Paths {
Dan Willemsen7b310ee2015-12-18 15:11:17 -0800455 ret := make(Paths, 0, len(paths))
456 for _, path := range paths {
Colin Cross32f38982018-02-22 11:47:25 -0800457 p := ExistentPathForSource(ctx, path)
Dan Willemsen7b310ee2015-12-18 15:11:17 -0800458 if p.Valid() {
459 ret = append(ret, p.Path())
460 }
461 }
462 return ret
463}
464
Liz Kammer620dea62021-04-14 17:36:10 -0400465// PathsForModuleSrc returns a Paths{} containing the resolved references in paths:
Colin Crossd079e0b2022-08-16 10:27:33 -0700466// - filepath, relative to local module directory, resolves as a filepath relative to the local
467// source directory
468// - glob, relative to the local module directory, resolves as filepath(s), relative to the local
469// source directory.
470// - other modules using the ":name{.tag}" syntax. These modules must implement SourceFileProducer
mrziwangd38e63d2024-07-15 13:43:37 -0700471// or set the OutputFilesProvider. These resolve as a filepath to an output filepath or generated
472// source filepath.
Colin Crossd079e0b2022-08-16 10:27:33 -0700473//
Liz Kammer620dea62021-04-14 17:36:10 -0400474// Properties passed as the paths argument must have been annotated with struct tag
Colin Cross41955e82019-05-29 14:40:35 -0700475// `android:"path"` so that dependencies on SourceFileProducer modules will have already been handled by the
Spandan Das950091c2023-07-19 22:26:37 +0000476// pathdeps mutator.
Liz Kammer620dea62021-04-14 17:36:10 -0400477// If a requested module is not found as a dependency:
Colin Crossd079e0b2022-08-16 10:27:33 -0700478// - if ctx.Config().AllowMissingDependencies() is true, this module to be marked as having
Liz Kammer620dea62021-04-14 17:36:10 -0400479// missing dependencies
Colin Crossd079e0b2022-08-16 10:27:33 -0700480// - otherwise, a ModuleError is thrown.
Liz Kammera830f3a2020-11-10 10:50:34 -0800481func PathsForModuleSrc(ctx ModuleMissingDepsPathContext, paths []string) Paths {
Colin Cross8a497952019-03-05 22:25:09 -0800482 return PathsForModuleSrcExcludes(ctx, paths, nil)
483}
484
Liz Kammer619be462022-01-28 15:13:39 -0500485type SourceInput struct {
486 Context ModuleMissingDepsPathContext
487 Paths []string
488 ExcludePaths []string
489 IncludeDirs bool
490}
491
Liz Kammer620dea62021-04-14 17:36:10 -0400492// PathsForModuleSrcExcludes returns a Paths{} containing the resolved references in paths, minus
493// those listed in excludes. Elements of paths and excludes are resolved as:
Colin Crossd079e0b2022-08-16 10:27:33 -0700494// - filepath, relative to local module directory, resolves as a filepath relative to the local
495// source directory
496// - glob, relative to the local module directory, resolves as filepath(s), relative to the local
497// source directory. Not valid in excludes.
498// - other modules using the ":name{.tag}" syntax. These modules must implement SourceFileProducer
mrziwangd38e63d2024-07-15 13:43:37 -0700499// or set the OutputFilesProvider. These resolve as a filepath to an output filepath or generated
500// source filepath.
Colin Crossd079e0b2022-08-16 10:27:33 -0700501//
Liz Kammer620dea62021-04-14 17:36:10 -0400502// excluding the items (similarly resolved
503// Properties passed as the paths argument must have been annotated with struct tag
504// `android:"path"` so that dependencies on SourceFileProducer modules will have already been handled by the
Spandan Das950091c2023-07-19 22:26:37 +0000505// pathdeps mutator.
Liz Kammer620dea62021-04-14 17:36:10 -0400506// If a requested module is not found as a dependency:
Colin Crossd079e0b2022-08-16 10:27:33 -0700507// - if ctx.Config().AllowMissingDependencies() is true, this module to be marked as having
Liz Kammer620dea62021-04-14 17:36:10 -0400508// missing dependencies
Colin Crossd079e0b2022-08-16 10:27:33 -0700509// - otherwise, a ModuleError is thrown.
Liz Kammera830f3a2020-11-10 10:50:34 -0800510func PathsForModuleSrcExcludes(ctx ModuleMissingDepsPathContext, paths, excludes []string) Paths {
Liz Kammer619be462022-01-28 15:13:39 -0500511 return PathsRelativeToModuleSourceDir(SourceInput{
512 Context: ctx,
513 Paths: paths,
514 ExcludePaths: excludes,
515 IncludeDirs: true,
516 })
517}
518
519func PathsRelativeToModuleSourceDir(input SourceInput) Paths {
520 ret, missingDeps := PathsAndMissingDepsRelativeToModuleSourceDir(input)
521 if input.Context.Config().AllowMissingDependencies() {
522 input.Context.AddMissingDependencies(missingDeps)
Colin Crossba71a3f2019-03-18 12:12:48 -0700523 } else {
524 for _, m := range missingDeps {
Liz Kammer619be462022-01-28 15:13:39 -0500525 input.Context.ModuleErrorf(`missing dependency on %q, is the property annotated with android:"path"?`, m)
Colin Crossba71a3f2019-03-18 12:12:48 -0700526 }
527 }
528 return ret
529}
530
Ulya Trafimovich4d2eeed2019-11-08 10:54:21 +0000531// OutputPaths is a slice of OutputPath objects, with helpers to operate on the collection.
532type OutputPaths []OutputPath
533
534// Paths returns the OutputPaths as a Paths
535func (p OutputPaths) Paths() Paths {
536 if p == nil {
537 return nil
538 }
539 ret := make(Paths, len(p))
540 for i, path := range p {
541 ret[i] = path
542 }
543 return ret
544}
545
546// Strings returns the string forms of the writable paths.
547func (p OutputPaths) Strings() []string {
548 if p == nil {
549 return nil
550 }
551 ret := make([]string, len(p))
552 for i, path := range p {
553 ret[i] = path.String()
554 }
555 return ret
556}
557
Liz Kammera830f3a2020-11-10 10:50:34 -0800558// Expands Paths to a SourceFileProducer or OutputFileProducer module dependency referenced via ":name" or ":name{.tag}" syntax.
559// If the dependency is not found, a missingErrorDependency is returned.
560// If the module dependency is not a SourceFileProducer or OutputFileProducer, appropriate errors will be returned.
561func getPathsFromModuleDep(ctx ModuleWithDepsPathContext, path, moduleName, tag string) (Paths, error) {
Paul Duffind5cf92e2021-07-09 17:38:55 +0100562 module := GetModuleFromPathDep(ctx, moduleName, tag)
Liz Kammera830f3a2020-11-10 10:50:34 -0800563 if module == nil {
564 return nil, missingDependencyError{[]string{moduleName}}
565 }
Cole Fausta963b942024-04-11 17:43:00 -0700566 if aModule, ok := module.(Module); ok && !aModule.Enabled(ctx) {
Colin Crossfa65cee2021-03-22 17:05:59 -0700567 return nil, missingDependencyError{[]string{moduleName}}
568 }
mrziwange6c85812024-05-22 14:36:09 -0700569 outputFiles, err := outputFilesForModule(ctx, module, tag)
570 if outputFiles != nil && err == nil {
571 return outputFiles, nil
Liz Kammera830f3a2020-11-10 10:50:34 -0800572 } else {
mrziwange6c85812024-05-22 14:36:09 -0700573 return nil, err
Liz Kammera830f3a2020-11-10 10:50:34 -0800574 }
575}
576
Paul Duffind5cf92e2021-07-09 17:38:55 +0100577// GetModuleFromPathDep will return the module that was added as a dependency automatically for
578// properties tagged with `android:"path"` or manually using ExtractSourceDeps or
579// ExtractSourcesDeps.
580//
581// The moduleName and tag supplied to this should be the values returned from SrcIsModuleWithTag.
582// Or, if no tag is expected then the moduleName should be the value returned by SrcIsModule and
583// the tag must be "".
584//
585// If tag is "" then the returned module will be the dependency that was added for ":moduleName".
586// Otherwise, it is the dependency that was added for ":moduleName{tag}".
Paul Duffind5cf92e2021-07-09 17:38:55 +0100587func GetModuleFromPathDep(ctx ModuleWithDepsPathContext, moduleName, tag string) blueprint.Module {
Paul Duffin40131a32021-07-09 17:10:35 +0100588 var found blueprint.Module
589 // The sourceOrOutputDepTag uniquely identifies the module dependency as it contains both the
590 // module name and the tag. Dependencies added automatically for properties tagged with
591 // `android:"path"` are deduped so are guaranteed to be unique. It is possible for duplicate
592 // dependencies to be added manually using ExtractSourcesDeps or ExtractSourceDeps but even then
593 // it will always be the case that the dependencies will be identical, i.e. the same tag and same
594 // moduleName referring to the same dependency module.
595 //
596 // It does not matter whether the moduleName is a fully qualified name or if the module
597 // dependency is a prebuilt module. All that matters is the same information is supplied to
598 // create the tag here as was supplied to create the tag when the dependency was added so that
599 // this finds the matching dependency module.
600 expectedTag := sourceOrOutputDepTag(moduleName, tag)
601 ctx.VisitDirectDepsBlueprint(func(module blueprint.Module) {
602 depTag := ctx.OtherModuleDependencyTag(module)
603 if depTag == expectedTag {
604 found = module
605 }
606 })
607 return found
Paul Duffind5cf92e2021-07-09 17:38:55 +0100608}
609
Liz Kammer620dea62021-04-14 17:36:10 -0400610// PathsAndMissingDepsForModuleSrcExcludes returns a Paths{} containing the resolved references in
611// paths, minus those listed in excludes. Elements of paths and excludes are resolved as:
Colin Crossd079e0b2022-08-16 10:27:33 -0700612// - filepath, relative to local module directory, resolves as a filepath relative to the local
613// source directory
614// - glob, relative to the local module directory, resolves as filepath(s), relative to the local
615// source directory. Not valid in excludes.
616// - other modules using the ":name{.tag}" syntax. These modules must implement SourceFileProducer
mrziwangd38e63d2024-07-15 13:43:37 -0700617// or set the OutputFilesProvider. These resolve as a filepath to an output filepath or generated
618// source filepath.
Colin Crossd079e0b2022-08-16 10:27:33 -0700619//
Liz Kammer620dea62021-04-14 17:36:10 -0400620// and a list of the module names of missing module dependencies are returned as the second return.
621// Properties passed as the paths argument must have been annotated with struct tag
Colin Cross41955e82019-05-29 14:40:35 -0700622// `android:"path"` so that dependencies on SourceFileProducer modules will have already been handled by the
Spandan Das950091c2023-07-19 22:26:37 +0000623// pathdeps mutator.
Liz Kammer619be462022-01-28 15:13:39 -0500624func PathsAndMissingDepsForModuleSrcExcludes(ctx ModuleMissingDepsPathContext, paths, excludes []string) (Paths, []string) {
625 return PathsAndMissingDepsRelativeToModuleSourceDir(SourceInput{
626 Context: ctx,
627 Paths: paths,
628 ExcludePaths: excludes,
629 IncludeDirs: true,
630 })
631}
632
633func PathsAndMissingDepsRelativeToModuleSourceDir(input SourceInput) (Paths, []string) {
634 prefix := pathForModuleSrc(input.Context).String()
Colin Cross8a497952019-03-05 22:25:09 -0800635
636 var expandedExcludes []string
Liz Kammer619be462022-01-28 15:13:39 -0500637 if input.ExcludePaths != nil {
638 expandedExcludes = make([]string, 0, len(input.ExcludePaths))
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700639 }
Colin Cross8a497952019-03-05 22:25:09 -0800640
Colin Crossba71a3f2019-03-18 12:12:48 -0700641 var missingExcludeDeps []string
Liz Kammer619be462022-01-28 15:13:39 -0500642 for _, e := range input.ExcludePaths {
Colin Cross41955e82019-05-29 14:40:35 -0700643 if m, t := SrcIsModuleWithTag(e); m != "" {
Liz Kammer619be462022-01-28 15:13:39 -0500644 modulePaths, err := getPathsFromModuleDep(input.Context, e, m, t)
Liz Kammera830f3a2020-11-10 10:50:34 -0800645 if m, ok := err.(missingDependencyError); ok {
646 missingExcludeDeps = append(missingExcludeDeps, m.missingDeps...)
647 } else if err != nil {
Liz Kammer619be462022-01-28 15:13:39 -0500648 reportPathError(input.Context, err)
Colin Cross8a497952019-03-05 22:25:09 -0800649 } else {
Liz Kammera830f3a2020-11-10 10:50:34 -0800650 expandedExcludes = append(expandedExcludes, modulePaths.Strings()...)
Colin Cross8a497952019-03-05 22:25:09 -0800651 }
652 } else {
653 expandedExcludes = append(expandedExcludes, filepath.Join(prefix, e))
654 }
655 }
656
Liz Kammer619be462022-01-28 15:13:39 -0500657 if input.Paths == nil {
Colin Crossba71a3f2019-03-18 12:12:48 -0700658 return nil, missingExcludeDeps
Colin Cross8a497952019-03-05 22:25:09 -0800659 }
660
Colin Crossba71a3f2019-03-18 12:12:48 -0700661 var missingDeps []string
662
Liz Kammer619be462022-01-28 15:13:39 -0500663 expandedSrcFiles := make(Paths, 0, len(input.Paths))
664 for _, s := range input.Paths {
665 srcFiles, err := expandOneSrcPath(sourcePathInput{
666 context: input.Context,
667 path: s,
668 expandedExcludes: expandedExcludes,
669 includeDirs: input.IncludeDirs,
670 })
Colin Cross8a497952019-03-05 22:25:09 -0800671 if depErr, ok := err.(missingDependencyError); ok {
Colin Crossba71a3f2019-03-18 12:12:48 -0700672 missingDeps = append(missingDeps, depErr.missingDeps...)
Colin Cross8a497952019-03-05 22:25:09 -0800673 } else if err != nil {
Liz Kammer619be462022-01-28 15:13:39 -0500674 reportPathError(input.Context, err)
Colin Cross8a497952019-03-05 22:25:09 -0800675 }
676 expandedSrcFiles = append(expandedSrcFiles, srcFiles...)
677 }
Colin Crossba71a3f2019-03-18 12:12:48 -0700678
Jihoon Kang0e3a5352024-04-12 00:45:50 +0000679 // TODO: b/334169722 - Replace with an error instead of implicitly removing duplicates.
680 return FirstUniquePaths(expandedSrcFiles), append(missingDeps, missingExcludeDeps...)
Colin Cross8a497952019-03-05 22:25:09 -0800681}
682
683type missingDependencyError struct {
684 missingDeps []string
685}
686
687func (e missingDependencyError) Error() string {
688 return "missing dependencies: " + strings.Join(e.missingDeps, ", ")
689}
690
Liz Kammer619be462022-01-28 15:13:39 -0500691type sourcePathInput struct {
692 context ModuleWithDepsPathContext
693 path string
694 expandedExcludes []string
695 includeDirs bool
696}
697
Liz Kammera830f3a2020-11-10 10:50:34 -0800698// Expands one path string to Paths rooted from the module's local source
699// directory, excluding those listed in the expandedExcludes.
700// Expands globs, references to SourceFileProducer or OutputFileProducer modules using the ":name" and ":name{.tag}" syntax.
Liz Kammer619be462022-01-28 15:13:39 -0500701func expandOneSrcPath(input sourcePathInput) (Paths, error) {
Jooyung Han7607dd32020-07-05 10:23:14 +0900702 excludePaths := func(paths Paths) Paths {
Liz Kammer619be462022-01-28 15:13:39 -0500703 if len(input.expandedExcludes) == 0 {
Jooyung Han7607dd32020-07-05 10:23:14 +0900704 return paths
705 }
706 remainder := make(Paths, 0, len(paths))
707 for _, p := range paths {
Liz Kammer619be462022-01-28 15:13:39 -0500708 if !InList(p.String(), input.expandedExcludes) {
Jooyung Han7607dd32020-07-05 10:23:14 +0900709 remainder = append(remainder, p)
710 }
711 }
712 return remainder
713 }
Liz Kammer619be462022-01-28 15:13:39 -0500714 if m, t := SrcIsModuleWithTag(input.path); m != "" {
715 modulePaths, err := getPathsFromModuleDep(input.context, input.path, m, t)
Liz Kammera830f3a2020-11-10 10:50:34 -0800716 if err != nil {
717 return nil, err
Colin Cross8a497952019-03-05 22:25:09 -0800718 } else {
Liz Kammera830f3a2020-11-10 10:50:34 -0800719 return excludePaths(modulePaths), nil
Colin Cross8a497952019-03-05 22:25:09 -0800720 }
Colin Cross8a497952019-03-05 22:25:09 -0800721 } else {
Liz Kammer619be462022-01-28 15:13:39 -0500722 p := pathForModuleSrc(input.context, input.path)
723 if pathtools.IsGlob(input.path) {
724 paths := GlobFiles(input.context, p.String(), input.expandedExcludes)
725 return PathsWithModuleSrcSubDir(input.context, paths, ""), nil
726 } else {
727 if exists, _, err := input.context.Config().fs.Exists(p.String()); err != nil {
728 ReportPathErrorf(input.context, "%s: %s", p, err.Error())
729 } else if !exists && !input.context.Config().TestAllowNonExistentPaths {
730 ReportPathErrorf(input.context, "module source path %q does not exist", p)
731 } else if !input.includeDirs {
732 if isDir, err := input.context.Config().fs.IsDir(p.String()); exists && err != nil {
733 ReportPathErrorf(input.context, "%s: %s", p, err.Error())
734 } else if isDir {
735 ReportPathErrorf(input.context, "module source path %q is a directory", p)
736 }
737 }
Colin Cross8a497952019-03-05 22:25:09 -0800738
Liz Kammer619be462022-01-28 15:13:39 -0500739 if InList(p.String(), input.expandedExcludes) {
740 return nil, nil
741 }
742 return Paths{p}, nil
Colin Cross8a497952019-03-05 22:25:09 -0800743 }
Colin Cross8a497952019-03-05 22:25:09 -0800744 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700745}
746
747// pathsForModuleSrcFromFullPath returns Paths rooted from the module's local
748// source directory, but strip the local source directory from the beginning of
Dan Willemsen540a78c2018-02-26 21:50:08 -0800749// each string. If incDirs is false, strip paths with a trailing '/' from the list.
Colin Crossfe4bc362018-09-12 10:02:13 -0700750// It intended for use in globs that only list files that exist, so it allows '$' in
751// filenames.
Liz Kammera830f3a2020-11-10 10:50:34 -0800752func pathsForModuleSrcFromFullPath(ctx EarlyModulePathContext, paths []string, incDirs bool) Paths {
Lukacs T. Berkif7e36d82021-08-16 17:05:09 +0200753 prefix := ctx.ModuleDir() + "/"
Colin Cross0f37af02017-09-27 17:42:05 -0700754 if prefix == "./" {
755 prefix = ""
756 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700757 ret := make(Paths, 0, len(paths))
758 for _, p := range paths {
Dan Willemsen540a78c2018-02-26 21:50:08 -0800759 if !incDirs && strings.HasSuffix(p, "/") {
760 continue
761 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700762 path := filepath.Clean(p)
763 if !strings.HasPrefix(path, prefix) {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +0100764 ReportPathErrorf(ctx, "Path %q is not in module source directory %q", p, prefix)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700765 continue
766 }
Colin Crosse3924e12018-08-15 20:18:53 -0700767
Colin Crossfe4bc362018-09-12 10:02:13 -0700768 srcPath, err := safePathForSource(ctx, ctx.ModuleDir(), path[len(prefix):])
Colin Crosse3924e12018-08-15 20:18:53 -0700769 if err != nil {
770 reportPathError(ctx, err)
771 continue
772 }
773
Colin Cross07e51612019-03-05 12:46:40 -0800774 srcPath.basePath.rel = srcPath.path
Colin Crosse3924e12018-08-15 20:18:53 -0700775
Colin Cross07e51612019-03-05 12:46:40 -0800776 ret = append(ret, srcPath)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700777 }
778 return ret
779}
780
Liz Kammera830f3a2020-11-10 10:50:34 -0800781// PathsWithOptionalDefaultForModuleSrc returns Paths rooted from the module's local source
782// directory. If input is nil, use the default if it exists. If input is empty, returns nil.
783func PathsWithOptionalDefaultForModuleSrc(ctx ModuleMissingDepsPathContext, input []string, def string) Paths {
Colin Cross0ddae7f2019-02-07 15:30:01 -0800784 if input != nil {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700785 return PathsForModuleSrc(ctx, input)
786 }
787 // Use Glob so that if the default doesn't exist, a dependency is added so that when it
788 // is created, we're run again.
Lukacs T. Berkif7e36d82021-08-16 17:05:09 +0200789 path := filepath.Join(ctx.ModuleDir(), def)
Liz Kammera830f3a2020-11-10 10:50:34 -0800790 return Glob(ctx, path, nil)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700791}
792
793// Strings returns the Paths in string form
794func (p Paths) Strings() []string {
795 if p == nil {
796 return nil
797 }
798 ret := make([]string, len(p))
799 for i, path := range p {
800 ret[i] = path.String()
801 }
802 return ret
803}
804
Colin Crossc0efd1d2020-07-03 11:56:24 -0700805func CopyOfPaths(paths Paths) Paths {
806 return append(Paths(nil), paths...)
807}
808
Colin Crossb6715442017-10-24 11:13:31 -0700809// FirstUniquePaths returns all unique elements of a Paths, keeping the first copy of each. It
810// modifies the Paths slice contents in place, and returns a subslice of the original slice.
Dan Willemsenfe92c962017-08-29 12:28:37 -0700811func FirstUniquePaths(list Paths) Paths {
Colin Cross27027c72020-02-28 15:34:17 -0800812 // 128 was chosen based on BenchmarkFirstUniquePaths results.
813 if len(list) > 128 {
814 return firstUniquePathsMap(list)
815 }
816 return firstUniquePathsList(list)
817}
818
Colin Crossc0efd1d2020-07-03 11:56:24 -0700819// SortedUniquePaths returns all unique elements of a Paths in sorted order. It modifies the
820// Paths slice contents in place, and returns a subslice of the original slice.
Jiyong Park33c77362020-05-29 22:00:16 +0900821func SortedUniquePaths(list Paths) Paths {
822 unique := FirstUniquePaths(list)
823 sort.Slice(unique, func(i, j int) bool {
824 return unique[i].String() < unique[j].String()
825 })
826 return unique
827}
828
Colin Cross27027c72020-02-28 15:34:17 -0800829func firstUniquePathsList(list Paths) Paths {
Dan Willemsenfe92c962017-08-29 12:28:37 -0700830 k := 0
831outer:
832 for i := 0; i < len(list); i++ {
833 for j := 0; j < k; j++ {
834 if list[i] == list[j] {
835 continue outer
836 }
837 }
838 list[k] = list[i]
839 k++
840 }
841 return list[:k]
842}
843
Colin Cross27027c72020-02-28 15:34:17 -0800844func firstUniquePathsMap(list Paths) Paths {
845 k := 0
846 seen := make(map[Path]bool, len(list))
847 for i := 0; i < len(list); i++ {
848 if seen[list[i]] {
849 continue
850 }
851 seen[list[i]] = true
852 list[k] = list[i]
853 k++
854 }
855 return list[:k]
856}
857
Colin Cross5d583952020-11-24 16:21:24 -0800858// FirstUniqueInstallPaths returns all unique elements of an InstallPaths, keeping the first copy of each. It
859// modifies the InstallPaths slice contents in place, and returns a subslice of the original slice.
860func FirstUniqueInstallPaths(list InstallPaths) InstallPaths {
861 // 128 was chosen based on BenchmarkFirstUniquePaths results.
862 if len(list) > 128 {
863 return firstUniqueInstallPathsMap(list)
864 }
865 return firstUniqueInstallPathsList(list)
866}
867
868func firstUniqueInstallPathsList(list InstallPaths) InstallPaths {
869 k := 0
870outer:
871 for i := 0; i < len(list); i++ {
872 for j := 0; j < k; j++ {
873 if list[i] == list[j] {
874 continue outer
875 }
876 }
877 list[k] = list[i]
878 k++
879 }
880 return list[:k]
881}
882
883func firstUniqueInstallPathsMap(list InstallPaths) InstallPaths {
884 k := 0
885 seen := make(map[InstallPath]bool, len(list))
886 for i := 0; i < len(list); i++ {
887 if seen[list[i]] {
888 continue
889 }
890 seen[list[i]] = true
891 list[k] = list[i]
892 k++
893 }
894 return list[:k]
895}
896
Colin Crossb6715442017-10-24 11:13:31 -0700897// LastUniquePaths returns all unique elements of a Paths, keeping the last copy of each. It
898// modifies the Paths slice contents in place, and returns a subslice of the original slice.
899func LastUniquePaths(list Paths) Paths {
900 totalSkip := 0
901 for i := len(list) - 1; i >= totalSkip; i-- {
902 skip := 0
903 for j := i - 1; j >= totalSkip; j-- {
904 if list[i] == list[j] {
905 skip++
906 } else {
907 list[j+skip] = list[j]
908 }
909 }
910 totalSkip += skip
911 }
912 return list[totalSkip:]
913}
914
Colin Crossa140bb02018-04-17 10:52:26 -0700915// ReversePaths returns a copy of a Paths in reverse order.
916func ReversePaths(list Paths) Paths {
917 if list == nil {
918 return nil
919 }
920 ret := make(Paths, len(list))
921 for i := range list {
922 ret[i] = list[len(list)-1-i]
923 }
924 return ret
925}
926
Jeff Gaston294356f2017-09-27 17:05:30 -0700927func indexPathList(s Path, list []Path) int {
928 for i, l := range list {
929 if l == s {
930 return i
931 }
932 }
933
934 return -1
935}
936
937func inPathList(p Path, list []Path) bool {
938 return indexPathList(p, list) != -1
939}
940
941func FilterPathList(list []Path, filter []Path) (remainder []Path, filtered []Path) {
Paul Duffin57b9e1d2019-12-13 00:03:35 +0000942 return FilterPathListPredicate(list, func(p Path) bool { return inPathList(p, filter) })
943}
944
945func FilterPathListPredicate(list []Path, predicate func(Path) bool) (remainder []Path, filtered []Path) {
Jeff Gaston294356f2017-09-27 17:05:30 -0700946 for _, l := range list {
Paul Duffin57b9e1d2019-12-13 00:03:35 +0000947 if predicate(l) {
Jeff Gaston294356f2017-09-27 17:05:30 -0700948 filtered = append(filtered, l)
949 } else {
950 remainder = append(remainder, l)
951 }
952 }
953
954 return
955}
956
Colin Cross93e85952017-08-15 13:34:18 -0700957// HasExt returns true of any of the paths have extension ext, otherwise false
958func (p Paths) HasExt(ext string) bool {
959 for _, path := range p {
960 if path.Ext() == ext {
961 return true
962 }
963 }
964
965 return false
966}
967
968// FilterByExt returns the subset of the paths that have extension ext
969func (p Paths) FilterByExt(ext string) Paths {
970 ret := make(Paths, 0, len(p))
971 for _, path := range p {
972 if path.Ext() == ext {
973 ret = append(ret, path)
974 }
975 }
976 return ret
977}
978
979// FilterOutByExt returns the subset of the paths that do not have extension ext
980func (p Paths) FilterOutByExt(ext string) Paths {
981 ret := make(Paths, 0, len(p))
982 for _, path := range p {
983 if path.Ext() != ext {
984 ret = append(ret, path)
985 }
986 }
987 return ret
988}
989
Colin Cross5e6cfbe2017-11-03 15:20:35 -0700990// DirectorySortedPaths is a slice of paths that are sorted such that all files in a directory
991// (including subdirectories) are in a contiguous subslice of the list, and can be found in
992// O(log(N)) time using a binary search on the directory prefix.
993type DirectorySortedPaths Paths
994
995func PathsToDirectorySortedPaths(paths Paths) DirectorySortedPaths {
996 ret := append(DirectorySortedPaths(nil), paths...)
997 sort.Slice(ret, func(i, j int) bool {
998 return ret[i].String() < ret[j].String()
999 })
1000 return ret
1001}
1002
1003// PathsInDirectory returns a subslice of the DirectorySortedPaths as a Paths that contains all entries
1004// that are in the specified directory and its subdirectories.
1005func (p DirectorySortedPaths) PathsInDirectory(dir string) Paths {
1006 prefix := filepath.Clean(dir) + "/"
1007 start := sort.Search(len(p), func(i int) bool {
1008 return prefix < p[i].String()
1009 })
1010
1011 ret := p[start:]
1012
1013 end := sort.Search(len(ret), func(i int) bool {
1014 return !strings.HasPrefix(ret[i].String(), prefix)
1015 })
1016
1017 ret = ret[:end]
1018
1019 return Paths(ret)
1020}
1021
Alex Humesky29e3bbe2020-11-20 21:30:13 -05001022// WritablePaths is a slice of WritablePath, used for multiple outputs.
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001023type WritablePaths []WritablePath
1024
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001025// RelativeToTop creates a new WritablePaths containing the result of calling Path.RelativeToTop on
1026// each item in this slice.
1027func (p WritablePaths) RelativeToTop() WritablePaths {
1028 ensureTestOnly()
1029 if p == nil {
1030 return p
1031 }
1032 ret := make(WritablePaths, len(p))
1033 for i, path := range p {
1034 ret[i] = path.RelativeToTop().(WritablePath)
1035 }
1036 return ret
1037}
1038
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001039// Strings returns the string forms of the writable paths.
1040func (p WritablePaths) Strings() []string {
1041 if p == nil {
1042 return nil
1043 }
1044 ret := make([]string, len(p))
1045 for i, path := range p {
1046 ret[i] = path.String()
1047 }
1048 return ret
1049}
1050
Colin Cross3bc7ffa2017-11-22 16:19:37 -08001051// Paths returns the WritablePaths as a Paths
1052func (p WritablePaths) Paths() Paths {
1053 if p == nil {
1054 return nil
1055 }
1056 ret := make(Paths, len(p))
1057 for i, path := range p {
1058 ret[i] = path
1059 }
1060 return ret
1061}
1062
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001063type basePath struct {
Paul Duffin74abc5d2021-03-24 09:24:59 +00001064 path string
1065 rel string
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001066}
1067
Yu Liufa297642024-06-11 00:13:02 +00001068func (p basePath) GobEncode() ([]byte, error) {
1069 w := new(bytes.Buffer)
1070 encoder := gob.NewEncoder(w)
1071 err := errors.Join(encoder.Encode(p.path), encoder.Encode(p.rel))
1072 if err != nil {
1073 return nil, err
1074 }
1075
1076 return w.Bytes(), nil
1077}
1078
1079func (p *basePath) GobDecode(data []byte) error {
1080 r := bytes.NewBuffer(data)
1081 decoder := gob.NewDecoder(r)
1082 err := errors.Join(decoder.Decode(&p.path), decoder.Decode(&p.rel))
1083 if err != nil {
1084 return err
1085 }
1086
1087 return nil
1088}
1089
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001090func (p basePath) Ext() string {
1091 return filepath.Ext(p.path)
1092}
1093
Colin Cross4f6fc9c2016-10-26 10:05:25 -07001094func (p basePath) Base() string {
1095 return filepath.Base(p.path)
1096}
1097
Colin Crossfaeb7aa2017-02-01 14:12:44 -08001098func (p basePath) Rel() string {
1099 if p.rel != "" {
1100 return p.rel
1101 }
1102 return p.path
1103}
1104
Colin Cross0875c522017-11-28 17:34:01 -08001105func (p basePath) String() string {
1106 return p.path
1107}
1108
Colin Cross0db55682017-12-05 15:36:55 -08001109func (p basePath) withRel(rel string) basePath {
1110 p.path = filepath.Join(p.path, rel)
1111 p.rel = rel
1112 return p
1113}
1114
Colin Cross7707b242024-07-26 12:02:36 -07001115func (p basePath) withoutRel() basePath {
1116 p.rel = filepath.Base(p.path)
1117 return p
1118}
1119
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001120// SourcePath is a Path representing a file path rooted from SrcDir
1121type SourcePath struct {
1122 basePath
1123}
1124
1125var _ Path = SourcePath{}
1126
Colin Cross0db55682017-12-05 15:36:55 -08001127func (p SourcePath) withRel(rel string) SourcePath {
1128 p.basePath = p.basePath.withRel(rel)
1129 return p
1130}
1131
Colin Crossbd73d0d2024-07-26 12:00:33 -07001132func (p SourcePath) RelativeToTop() Path {
1133 ensureTestOnly()
1134 return p
1135}
1136
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001137// safePathForSource is for paths that we expect are safe -- only for use by go
1138// code that is embedding ninja variables in paths
Colin Crossfe4bc362018-09-12 10:02:13 -07001139func safePathForSource(ctx PathContext, pathComponents ...string) (SourcePath, error) {
1140 p, err := validateSafePath(pathComponents...)
Cole Faust483d1f72023-01-09 14:35:27 -08001141 ret := SourcePath{basePath{p, ""}}
Colin Crossfe4bc362018-09-12 10:02:13 -07001142 if err != nil {
1143 return ret, err
1144 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001145
Colin Cross7b3dcc32019-01-24 13:14:39 -08001146 // absolute path already checked by validateSafePath
Inseob Kim5eb7ee92022-04-27 10:30:34 +09001147 // special-case api surface gen files for now
1148 if strings.HasPrefix(ret.String(), ctx.Config().soongOutDir) && !strings.Contains(ret.String(), ctx.Config().soongOutDir+"/.export") {
Mikhail Naganovab1f5182019-02-08 13:17:55 -08001149 return ret, fmt.Errorf("source path %q is in output", ret.String())
Colin Cross6e18ca42015-07-14 18:55:36 -07001150 }
1151
Colin Crossfe4bc362018-09-12 10:02:13 -07001152 return ret, err
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001153}
1154
Colin Cross192e97a2018-02-22 14:21:02 -08001155// pathForSource creates a SourcePath from pathComponents, but does not check that it exists.
1156func pathForSource(ctx PathContext, pathComponents ...string) (SourcePath, error) {
Colin Crossc48c1432018-02-23 07:09:01 +00001157 p, err := validatePath(pathComponents...)
Cole Faust483d1f72023-01-09 14:35:27 -08001158 ret := SourcePath{basePath{p, ""}}
Colin Cross94a32102018-02-22 14:21:02 -08001159 if err != nil {
Colin Cross192e97a2018-02-22 14:21:02 -08001160 return ret, err
Colin Cross94a32102018-02-22 14:21:02 -08001161 }
1162
Colin Cross7b3dcc32019-01-24 13:14:39 -08001163 // absolute path already checked by validatePath
Inseob Kim5eb7ee92022-04-27 10:30:34 +09001164 // special-case for now
1165 if strings.HasPrefix(ret.String(), ctx.Config().soongOutDir) && !strings.Contains(ret.String(), ctx.Config().soongOutDir+"/.export") {
Mikhail Naganovab1f5182019-02-08 13:17:55 -08001166 return ret, fmt.Errorf("source path %q is in output", ret.String())
Colin Crossc48c1432018-02-23 07:09:01 +00001167 }
1168
Colin Cross192e97a2018-02-22 14:21:02 -08001169 return ret, nil
1170}
1171
1172// existsWithDependencies returns true if the path exists, and adds appropriate dependencies to rerun if the
1173// path does not exist.
Colin Cross662d6142022-11-03 20:38:01 -07001174func existsWithDependencies(ctx PathGlobContext, path SourcePath) (exists bool, err error) {
Colin Cross192e97a2018-02-22 14:21:02 -08001175 var files []string
1176
Colin Cross662d6142022-11-03 20:38:01 -07001177 // Use glob to produce proper dependencies, even though we only want
1178 // a single file.
1179 files, err = ctx.GlobWithDeps(path.String(), nil)
Colin Cross192e97a2018-02-22 14:21:02 -08001180
1181 if err != nil {
1182 return false, fmt.Errorf("glob: %s", err.Error())
1183 }
1184
1185 return len(files) > 0, nil
1186}
1187
1188// PathForSource joins the provided path components and validates that the result
1189// neither escapes the source dir nor is in the out dir.
1190// On error, it will return a usable, but invalid SourcePath, and report a ModuleError.
1191func PathForSource(ctx PathContext, pathComponents ...string) SourcePath {
1192 path, err := pathForSource(ctx, pathComponents...)
1193 if err != nil {
1194 reportPathError(ctx, err)
1195 }
1196
Colin Crosse3924e12018-08-15 20:18:53 -07001197 if pathtools.IsGlob(path.String()) {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001198 ReportPathErrorf(ctx, "path may not contain a glob: %s", path.String())
Colin Crosse3924e12018-08-15 20:18:53 -07001199 }
1200
Liz Kammera830f3a2020-11-10 10:50:34 -08001201 if modCtx, ok := ctx.(ModuleMissingDepsPathContext); ok && ctx.Config().AllowMissingDependencies() {
Colin Cross662d6142022-11-03 20:38:01 -07001202 exists, err := existsWithDependencies(modCtx, path)
Colin Cross192e97a2018-02-22 14:21:02 -08001203 if err != nil {
1204 reportPathError(ctx, err)
1205 }
1206 if !exists {
1207 modCtx.AddMissingDependencies([]string{path.String()})
1208 }
Colin Cross988414c2020-01-11 01:11:46 +00001209 } else if exists, _, err := ctx.Config().fs.Exists(path.String()); err != nil {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001210 ReportPathErrorf(ctx, "%s: %s", path, err.Error())
Pedro Loureiro5d190cc2021-02-15 15:41:33 +00001211 } else if !exists && !ctx.Config().TestAllowNonExistentPaths {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001212 ReportPathErrorf(ctx, "source path %q does not exist", path)
Colin Cross192e97a2018-02-22 14:21:02 -08001213 }
1214 return path
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001215}
1216
Cole Faustbc65a3f2023-08-01 16:38:55 +00001217// PathForArbitraryOutput creates a path for the given components. Unlike PathForOutput,
1218// the path is relative to the root of the output folder, not the out/soong folder.
1219func PathForArbitraryOutput(ctx PathContext, pathComponents ...string) Path {
Colin Cross3b1c6842024-07-26 11:52:57 -07001220 path, err := validatePath(pathComponents...)
Cole Faustbc65a3f2023-08-01 16:38:55 +00001221 if err != nil {
1222 reportPathError(ctx, err)
1223 }
Colin Cross3b1c6842024-07-26 11:52:57 -07001224 fullPath := filepath.Join(ctx.Config().OutDir(), path)
1225 path = fullPath[len(fullPath)-len(path):]
1226 return OutputPath{basePath{path, ""}, ctx.Config().OutDir(), fullPath}
Cole Faustbc65a3f2023-08-01 16:38:55 +00001227}
1228
Spandan Dasc6c10fa2022-10-21 21:52:13 +00001229// MaybeExistentPathForSource joins the provided path components and validates that the result
1230// neither escapes the source dir nor is in the out dir.
1231// It does not validate whether the path exists.
1232func MaybeExistentPathForSource(ctx PathContext, pathComponents ...string) SourcePath {
1233 path, err := pathForSource(ctx, pathComponents...)
1234 if err != nil {
1235 reportPathError(ctx, err)
1236 }
1237
1238 if pathtools.IsGlob(path.String()) {
1239 ReportPathErrorf(ctx, "path may not contain a glob: %s", path.String())
1240 }
1241 return path
1242}
1243
Liz Kammer7aa52882021-02-11 09:16:14 -05001244// ExistentPathForSource returns an OptionalPath with the SourcePath, rooted from SrcDir, *not*
1245// rooted from the module's local source directory, if the path exists, or an empty OptionalPath if
1246// it doesn't exist. Dependencies are added so that the ninja file will be regenerated if the state
1247// of the path changes.
Colin Cross662d6142022-11-03 20:38:01 -07001248func ExistentPathForSource(ctx PathGlobContext, pathComponents ...string) OptionalPath {
Colin Cross192e97a2018-02-22 14:21:02 -08001249 path, err := pathForSource(ctx, pathComponents...)
Colin Cross1ccfcc32018-02-22 13:54:26 -08001250 if err != nil {
1251 reportPathError(ctx, err)
Martin Stjernholmc32dd1c2021-09-15 02:39:00 +01001252 // No need to put the error message into the returned path since it has been reported already.
Colin Cross1ccfcc32018-02-22 13:54:26 -08001253 return OptionalPath{}
1254 }
Colin Crossc48c1432018-02-23 07:09:01 +00001255
Colin Crosse3924e12018-08-15 20:18:53 -07001256 if pathtools.IsGlob(path.String()) {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001257 ReportPathErrorf(ctx, "path may not contain a glob: %s", path.String())
Colin Crosse3924e12018-08-15 20:18:53 -07001258 return OptionalPath{}
1259 }
1260
Colin Cross192e97a2018-02-22 14:21:02 -08001261 exists, err := existsWithDependencies(ctx, path)
Colin Crossc48c1432018-02-23 07:09:01 +00001262 if err != nil {
1263 reportPathError(ctx, err)
1264 return OptionalPath{}
1265 }
Colin Cross192e97a2018-02-22 14:21:02 -08001266 if !exists {
Martin Stjernholmc32dd1c2021-09-15 02:39:00 +01001267 return InvalidOptionalPath(path.String() + " does not exist")
Colin Crossc48c1432018-02-23 07:09:01 +00001268 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001269 return OptionalPathForPath(path)
1270}
1271
1272func (p SourcePath) String() string {
Cole Faust483d1f72023-01-09 14:35:27 -08001273 if p.path == "" {
1274 return "."
1275 }
1276 return p.path
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001277}
1278
Colin Cross7707b242024-07-26 12:02:36 -07001279func (p SourcePath) WithoutRel() Path {
1280 p.basePath = p.basePath.withoutRel()
1281 return p
1282}
1283
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001284// Join creates a new SourcePath with paths... joined with the current path. The
1285// provided paths... may not use '..' to escape from the current path.
1286func (p SourcePath) Join(ctx PathContext, paths ...string) SourcePath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001287 path, err := validatePath(paths...)
1288 if err != nil {
1289 reportPathError(ctx, err)
1290 }
Colin Cross0db55682017-12-05 15:36:55 -08001291 return p.withRel(path)
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001292}
1293
Colin Cross2fafa3e2019-03-05 12:39:51 -08001294// join is like Join but does less path validation.
1295func (p SourcePath) join(ctx PathContext, paths ...string) SourcePath {
1296 path, err := validateSafePath(paths...)
1297 if err != nil {
1298 reportPathError(ctx, err)
1299 }
1300 return p.withRel(path)
1301}
1302
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001303// OverlayPath returns the overlay for `path' if it exists. This assumes that the
1304// SourcePath is the path to a resource overlay directory.
Liz Kammera830f3a2020-11-10 10:50:34 -08001305func (p SourcePath) OverlayPath(ctx ModuleMissingDepsPathContext, path Path) OptionalPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001306 var relDir string
Colin Cross07e51612019-03-05 12:46:40 -08001307 if srcPath, ok := path.(SourcePath); ok {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001308 relDir = srcPath.path
1309 } else {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001310 ReportPathErrorf(ctx, "Cannot find relative path for %s(%s)", reflect.TypeOf(path).Name(), path)
Martin Stjernholmc32dd1c2021-09-15 02:39:00 +01001311 // No need to put the error message into the returned path since it has been reported already.
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001312 return OptionalPath{}
1313 }
Cole Faust483d1f72023-01-09 14:35:27 -08001314 dir := filepath.Join(p.path, relDir)
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001315 // Use Glob so that we are run again if the directory is added.
Colin Cross7f19f372016-11-01 11:10:25 -07001316 if pathtools.IsGlob(dir) {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001317 ReportPathErrorf(ctx, "Path may not contain a glob: %s", dir)
Dan Willemsen7b310ee2015-12-18 15:11:17 -08001318 }
Colin Cross461b4452018-02-23 09:22:42 -08001319 paths, err := ctx.GlobWithDeps(dir, nil)
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001320 if err != nil {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001321 ReportPathErrorf(ctx, "glob: %s", err.Error())
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001322 return OptionalPath{}
1323 }
1324 if len(paths) == 0 {
Martin Stjernholmc32dd1c2021-09-15 02:39:00 +01001325 return InvalidOptionalPath(dir + " does not exist")
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001326 }
Cole Faust483d1f72023-01-09 14:35:27 -08001327 return OptionalPathForPath(PathForSource(ctx, paths[0]))
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001328}
1329
Colin Cross70dda7e2019-10-01 22:05:35 -07001330// OutputPath is a Path representing an intermediates file path rooted from the build directory
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001331type OutputPath struct {
1332 basePath
Paul Duffind65c58b2021-03-24 09:22:07 +00001333
Colin Cross3b1c6842024-07-26 11:52:57 -07001334 // The base out directory for this path, either Config.SoongOutDir() or Config.OutDir()
1335 outDir string
Paul Duffind65c58b2021-03-24 09:22:07 +00001336
Colin Crossd63c9a72020-01-29 16:52:50 -08001337 fullPath string
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001338}
1339
Yu Liufa297642024-06-11 00:13:02 +00001340func (p OutputPath) GobEncode() ([]byte, error) {
1341 w := new(bytes.Buffer)
1342 encoder := gob.NewEncoder(w)
Colin Cross3b1c6842024-07-26 11:52:57 -07001343 err := errors.Join(encoder.Encode(p.basePath), encoder.Encode(p.outDir), encoder.Encode(p.fullPath))
Yu Liufa297642024-06-11 00:13:02 +00001344 if err != nil {
1345 return nil, err
1346 }
1347
1348 return w.Bytes(), nil
1349}
1350
1351func (p *OutputPath) GobDecode(data []byte) error {
1352 r := bytes.NewBuffer(data)
1353 decoder := gob.NewDecoder(r)
Colin Cross3b1c6842024-07-26 11:52:57 -07001354 err := errors.Join(decoder.Decode(&p.basePath), decoder.Decode(&p.outDir), decoder.Decode(&p.fullPath))
Yu Liufa297642024-06-11 00:13:02 +00001355 if err != nil {
1356 return err
1357 }
1358
1359 return nil
1360}
1361
Colin Cross702e0f82017-10-18 17:27:54 -07001362func (p OutputPath) withRel(rel string) OutputPath {
Colin Cross0db55682017-12-05 15:36:55 -08001363 p.basePath = p.basePath.withRel(rel)
Colin Crossd63c9a72020-01-29 16:52:50 -08001364 p.fullPath = filepath.Join(p.fullPath, rel)
Colin Cross702e0f82017-10-18 17:27:54 -07001365 return p
1366}
1367
Colin Cross7707b242024-07-26 12:02:36 -07001368func (p OutputPath) WithoutRel() Path {
1369 p.basePath = p.basePath.withoutRel()
Colin Cross3063b782018-08-15 11:19:12 -07001370 return p
1371}
1372
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02001373func (p OutputPath) getSoongOutDir() string {
Colin Cross3b1c6842024-07-26 11:52:57 -07001374 return p.outDir
Paul Duffin9b478b02019-12-10 13:41:51 +00001375}
1376
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001377func (p OutputPath) RelativeToTop() Path {
1378 return p.outputPathRelativeToTop()
1379}
1380
1381func (p OutputPath) outputPathRelativeToTop() OutputPath {
Colin Cross3b1c6842024-07-26 11:52:57 -07001382 p.fullPath = StringPathRelativeToTop(p.outDir, p.fullPath)
1383 if strings.HasSuffix(p.outDir, testOutSoongSubDir) {
1384 p.outDir = TestOutSoongDir
1385 } else {
1386 // Handle the PathForArbitraryOutput case
1387 p.outDir = testOutDir
1388 }
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001389 return p
1390}
1391
Paul Duffin0267d492021-02-02 10:05:52 +00001392func (p OutputPath) objPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleObjPath {
1393 return PathForModuleObj(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
1394}
1395
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001396var _ Path = OutputPath{}
Paul Duffin9b478b02019-12-10 13:41:51 +00001397var _ WritablePath = OutputPath{}
Paul Duffin0267d492021-02-02 10:05:52 +00001398var _ objPathProvider = OutputPath{}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001399
Chris Parsons8f232a22020-06-23 17:37:05 -04001400// toolDepPath is a Path representing a dependency of the build tool.
1401type toolDepPath struct {
1402 basePath
1403}
1404
Colin Cross7707b242024-07-26 12:02:36 -07001405func (t toolDepPath) WithoutRel() Path {
1406 t.basePath = t.basePath.withoutRel()
1407 return t
1408}
1409
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001410func (t toolDepPath) RelativeToTop() Path {
1411 ensureTestOnly()
1412 return t
1413}
1414
Chris Parsons8f232a22020-06-23 17:37:05 -04001415var _ Path = toolDepPath{}
1416
1417// pathForBuildToolDep returns a toolDepPath representing the given path string.
1418// There is no validation for the path, as it is "trusted": It may fail
1419// normal validation checks. For example, it may be an absolute path.
1420// Only use this function to construct paths for dependencies of the build
1421// tool invocation.
1422func pathForBuildToolDep(ctx PathContext, path string) toolDepPath {
Paul Duffin74abc5d2021-03-24 09:24:59 +00001423 return toolDepPath{basePath{path, ""}}
Chris Parsons8f232a22020-06-23 17:37:05 -04001424}
1425
Jeff Gaston734e3802017-04-10 15:47:24 -07001426// PathForOutput joins the provided paths and returns an OutputPath that is
1427// validated to not escape the build dir.
1428// On error, it will return a usable, but invalid OutputPath, and report a ModuleError.
1429func PathForOutput(ctx PathContext, pathComponents ...string) OutputPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001430 path, err := validatePath(pathComponents...)
1431 if err != nil {
1432 reportPathError(ctx, err)
1433 }
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02001434 fullPath := filepath.Join(ctx.Config().soongOutDir, path)
Colin Crossd63c9a72020-01-29 16:52:50 -08001435 path = fullPath[len(fullPath)-len(path):]
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02001436 return OutputPath{basePath{path, ""}, ctx.Config().soongOutDir, fullPath}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001437}
1438
Colin Cross3b1c6842024-07-26 11:52:57 -07001439// PathsForOutput returns Paths rooted from outDir
Colin Cross40e33732019-02-15 11:08:35 -08001440func PathsForOutput(ctx PathContext, paths []string) WritablePaths {
1441 ret := make(WritablePaths, len(paths))
1442 for i, path := range paths {
1443 ret[i] = PathForOutput(ctx, path)
1444 }
1445 return ret
1446}
1447
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001448func (p OutputPath) writablePath() {}
1449
1450func (p OutputPath) String() string {
Colin Crossd63c9a72020-01-29 16:52:50 -08001451 return p.fullPath
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001452}
1453
1454// Join creates a new OutputPath with paths... joined with the current path. The
1455// provided paths... may not use '..' to escape from the current path.
1456func (p OutputPath) Join(ctx PathContext, paths ...string) OutputPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001457 path, err := validatePath(paths...)
1458 if err != nil {
1459 reportPathError(ctx, err)
1460 }
Colin Cross0db55682017-12-05 15:36:55 -08001461 return p.withRel(path)
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001462}
1463
Colin Cross8854a5a2019-02-11 14:14:16 -08001464// ReplaceExtension creates a new OutputPath with the extension replaced with ext.
1465func (p OutputPath) ReplaceExtension(ctx PathContext, ext string) OutputPath {
1466 if strings.Contains(ext, "/") {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001467 ReportPathErrorf(ctx, "extension %q cannot contain /", ext)
Colin Cross8854a5a2019-02-11 14:14:16 -08001468 }
1469 ret := PathForOutput(ctx, pathtools.ReplaceExtension(p.path, ext))
Colin Cross2cdd5df2019-02-25 10:25:24 -08001470 ret.rel = pathtools.ReplaceExtension(p.rel, ext)
Colin Cross8854a5a2019-02-11 14:14:16 -08001471 return ret
1472}
1473
Colin Cross40e33732019-02-15 11:08:35 -08001474// InSameDir creates a new OutputPath from the directory of the current OutputPath joined with the elements in paths.
1475func (p OutputPath) InSameDir(ctx PathContext, paths ...string) OutputPath {
1476 path, err := validatePath(paths...)
1477 if err != nil {
1478 reportPathError(ctx, err)
1479 }
1480
1481 ret := PathForOutput(ctx, filepath.Dir(p.path), path)
Colin Cross2cdd5df2019-02-25 10:25:24 -08001482 ret.rel = filepath.Join(filepath.Dir(p.rel), path)
Colin Cross40e33732019-02-15 11:08:35 -08001483 return ret
1484}
1485
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001486// PathForIntermediates returns an OutputPath representing the top-level
1487// intermediates directory.
1488func PathForIntermediates(ctx PathContext, paths ...string) OutputPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001489 path, err := validatePath(paths...)
1490 if err != nil {
1491 reportPathError(ctx, err)
1492 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001493 return PathForOutput(ctx, ".intermediates", path)
1494}
1495
Colin Cross07e51612019-03-05 12:46:40 -08001496var _ genPathProvider = SourcePath{}
1497var _ objPathProvider = SourcePath{}
1498var _ resPathProvider = SourcePath{}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001499
Colin Cross07e51612019-03-05 12:46:40 -08001500// PathForModuleSrc returns a Path representing the paths... under the
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001501// module's local source directory.
Liz Kammera830f3a2020-11-10 10:50:34 -08001502func PathForModuleSrc(ctx ModuleMissingDepsPathContext, pathComponents ...string) Path {
Paul Duffin407501b2021-07-09 16:56:35 +01001503 // Just join the components textually just to make sure that it does not corrupt a fully qualified
1504 // module reference, e.g. if the pathComponents is "://other:foo" then using filepath.Join() or
1505 // validatePath() will corrupt it, e.g. replace "//" with "/". If the path is not a module
1506 // reference then it will be validated by expandOneSrcPath anyway when it calls expandOneSrcPath.
1507 p := strings.Join(pathComponents, string(filepath.Separator))
Liz Kammer619be462022-01-28 15:13:39 -05001508 paths, err := expandOneSrcPath(sourcePathInput{context: ctx, path: p, includeDirs: true})
Colin Cross8a497952019-03-05 22:25:09 -08001509 if err != nil {
1510 if depErr, ok := err.(missingDependencyError); ok {
1511 if ctx.Config().AllowMissingDependencies() {
1512 ctx.AddMissingDependencies(depErr.missingDeps)
1513 } else {
1514 ctx.ModuleErrorf(`%s, is the property annotated with android:"path"?`, depErr.Error())
1515 }
1516 } else {
1517 reportPathError(ctx, err)
1518 }
1519 return nil
1520 } else if len(paths) == 0 {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001521 ReportPathErrorf(ctx, "%q produced no files, expected exactly one", p)
Colin Cross8a497952019-03-05 22:25:09 -08001522 return nil
1523 } else if len(paths) > 1 {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001524 ReportPathErrorf(ctx, "%q produced %d files, expected exactly one", p, len(paths))
Colin Cross8a497952019-03-05 22:25:09 -08001525 }
1526 return paths[0]
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001527}
1528
Liz Kammera830f3a2020-11-10 10:50:34 -08001529func pathForModuleSrc(ctx EarlyModulePathContext, paths ...string) SourcePath {
Colin Cross07e51612019-03-05 12:46:40 -08001530 p, err := validatePath(paths...)
1531 if err != nil {
1532 reportPathError(ctx, err)
1533 }
1534
1535 path, err := pathForSource(ctx, ctx.ModuleDir(), p)
1536 if err != nil {
1537 reportPathError(ctx, err)
1538 }
1539
1540 path.basePath.rel = p
1541
1542 return path
1543}
1544
Colin Cross2fafa3e2019-03-05 12:39:51 -08001545// PathsWithModuleSrcSubDir takes a list of Paths and returns a new list of Paths where Rel() on each path
1546// will return the path relative to subDir in the module's source directory. If any input paths are not located
1547// inside subDir then a path error will be reported.
Liz Kammera830f3a2020-11-10 10:50:34 -08001548func PathsWithModuleSrcSubDir(ctx EarlyModulePathContext, paths Paths, subDir string) Paths {
Colin Cross2fafa3e2019-03-05 12:39:51 -08001549 paths = append(Paths(nil), paths...)
Colin Cross07e51612019-03-05 12:46:40 -08001550 subDirFullPath := pathForModuleSrc(ctx, subDir)
Colin Cross2fafa3e2019-03-05 12:39:51 -08001551 for i, path := range paths {
1552 rel := Rel(ctx, subDirFullPath.String(), path.String())
1553 paths[i] = subDirFullPath.join(ctx, rel)
1554 }
1555 return paths
1556}
1557
1558// PathWithModuleSrcSubDir takes a Path and returns a Path where Rel() will return the path relative to subDir in the
1559// 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 -08001560func PathWithModuleSrcSubDir(ctx EarlyModulePathContext, path Path, subDir string) Path {
Colin Cross07e51612019-03-05 12:46:40 -08001561 subDirFullPath := pathForModuleSrc(ctx, subDir)
Colin Cross2fafa3e2019-03-05 12:39:51 -08001562 rel := Rel(ctx, subDirFullPath.String(), path.String())
1563 return subDirFullPath.Join(ctx, rel)
1564}
1565
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001566// OptionalPathForModuleSrc returns an OptionalPath. The OptionalPath contains a
1567// valid path if p is non-nil.
Liz Kammera830f3a2020-11-10 10:50:34 -08001568func OptionalPathForModuleSrc(ctx ModuleMissingDepsPathContext, p *string) OptionalPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001569 if p == nil {
1570 return OptionalPath{}
1571 }
1572 return OptionalPathForPath(PathForModuleSrc(ctx, *p))
1573}
1574
Liz Kammera830f3a2020-11-10 10:50:34 -08001575func (p SourcePath) genPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleGenPath {
Colin Cross7fc17db2017-02-01 14:07:55 -08001576 return PathForModuleGen(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001577}
1578
yangbill6d032dd2024-04-18 03:05:49 +00001579func (p SourcePath) genPathWithExtAndTrimExt(ctx ModuleOutPathContext, subdir, ext string, trimExt string) ModuleGenPath {
1580 // If Trim_extension being set, force append Output_extension without replace original extension.
1581 if trimExt != "" {
1582 if ext != "" {
1583 return PathForModuleGen(ctx, subdir, strings.TrimSuffix(p.path, trimExt)+"."+ext)
1584 }
1585 return PathForModuleGen(ctx, subdir, strings.TrimSuffix(p.path, trimExt))
1586 }
1587 return PathForModuleGen(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
1588}
1589
Liz Kammera830f3a2020-11-10 10:50:34 -08001590func (p SourcePath) objPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleObjPath {
Colin Cross7fc17db2017-02-01 14:07:55 -08001591 return PathForModuleObj(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001592}
1593
Liz Kammera830f3a2020-11-10 10:50:34 -08001594func (p SourcePath) resPathWithName(ctx ModuleOutPathContext, name string) ModuleResPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001595 // TODO: Use full directory if the new ctx is not the current ctx?
1596 return PathForModuleRes(ctx, p.path, name)
1597}
1598
1599// ModuleOutPath is a Path representing a module's output directory.
1600type ModuleOutPath struct {
1601 OutputPath
1602}
1603
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001604func (p ModuleOutPath) RelativeToTop() Path {
1605 p.OutputPath = p.outputPathRelativeToTop()
1606 return p
1607}
1608
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001609var _ Path = ModuleOutPath{}
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001610var _ WritablePath = ModuleOutPath{}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001611
Liz Kammera830f3a2020-11-10 10:50:34 -08001612func (p ModuleOutPath) objPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleObjPath {
Pete Bentleyfcf55bf2019-08-16 20:14:32 +01001613 return PathForModuleObj(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
1614}
1615
Liz Kammera830f3a2020-11-10 10:50:34 -08001616// ModuleOutPathContext Subset of ModuleContext functions necessary for output path methods.
1617type ModuleOutPathContext interface {
1618 PathContext
1619
1620 ModuleName() string
1621 ModuleDir() string
1622 ModuleSubDir() string
1623}
1624
1625func pathForModuleOut(ctx ModuleOutPathContext) OutputPath {
Inseob Kimb7e9f5f2024-06-25 17:39:52 +09001626 return PathForOutput(ctx, ".intermediates", ctx.ModuleDir(), ctx.ModuleName(), ctx.ModuleSubDir())
Colin Cross702e0f82017-10-18 17:27:54 -07001627}
1628
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001629// PathForModuleOut returns a Path representing the paths... under the module's
1630// output directory.
Liz Kammera830f3a2020-11-10 10:50:34 -08001631func PathForModuleOut(ctx ModuleOutPathContext, paths ...string) ModuleOutPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001632 p, err := validatePath(paths...)
1633 if err != nil {
1634 reportPathError(ctx, err)
1635 }
Colin Cross702e0f82017-10-18 17:27:54 -07001636 return ModuleOutPath{
Liz Kammera830f3a2020-11-10 10:50:34 -08001637 OutputPath: pathForModuleOut(ctx).withRel(p),
Colin Cross702e0f82017-10-18 17:27:54 -07001638 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001639}
1640
1641// ModuleGenPath is a Path representing the 'gen' directory in a module's output
1642// directory. Mainly used for generated sources.
1643type ModuleGenPath struct {
1644 ModuleOutPath
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001645}
1646
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001647func (p ModuleGenPath) RelativeToTop() Path {
1648 p.OutputPath = p.outputPathRelativeToTop()
1649 return p
1650}
1651
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001652var _ Path = ModuleGenPath{}
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001653var _ WritablePath = ModuleGenPath{}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001654var _ genPathProvider = ModuleGenPath{}
1655var _ objPathProvider = ModuleGenPath{}
1656
1657// PathForModuleGen returns a Path representing the paths... under the module's
1658// `gen' directory.
Liz Kammera830f3a2020-11-10 10:50:34 -08001659func PathForModuleGen(ctx ModuleOutPathContext, paths ...string) ModuleGenPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001660 p, err := validatePath(paths...)
1661 if err != nil {
1662 reportPathError(ctx, err)
1663 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001664 return ModuleGenPath{
Colin Cross702e0f82017-10-18 17:27:54 -07001665 ModuleOutPath: ModuleOutPath{
Liz Kammera830f3a2020-11-10 10:50:34 -08001666 OutputPath: pathForModuleOut(ctx).withRel("gen").withRel(p),
Colin Cross702e0f82017-10-18 17:27:54 -07001667 },
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001668 }
1669}
1670
Liz Kammera830f3a2020-11-10 10:50:34 -08001671func (p ModuleGenPath) genPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleGenPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001672 // TODO: make a different path for local vs remote generated files?
Dan Willemsen21ec4902016-11-02 20:43:13 -07001673 return PathForModuleGen(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001674}
1675
yangbill6d032dd2024-04-18 03:05:49 +00001676func (p ModuleGenPath) genPathWithExtAndTrimExt(ctx ModuleOutPathContext, subdir, ext string, trimExt string) ModuleGenPath {
1677 // If Trim_extension being set, force append Output_extension without replace original extension.
1678 if trimExt != "" {
1679 if ext != "" {
1680 return PathForModuleGen(ctx, subdir, strings.TrimSuffix(p.path, trimExt)+"."+ext)
1681 }
1682 return PathForModuleGen(ctx, subdir, strings.TrimSuffix(p.path, trimExt))
1683 }
1684 return PathForModuleGen(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
1685}
1686
Liz Kammera830f3a2020-11-10 10:50:34 -08001687func (p ModuleGenPath) objPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleObjPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001688 return PathForModuleObj(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
1689}
1690
1691// ModuleObjPath is a Path representing the 'obj' directory in a module's output
1692// directory. Used for compiled objects.
1693type ModuleObjPath struct {
1694 ModuleOutPath
1695}
1696
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001697func (p ModuleObjPath) RelativeToTop() Path {
1698 p.OutputPath = p.outputPathRelativeToTop()
1699 return p
1700}
1701
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001702var _ Path = ModuleObjPath{}
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001703var _ WritablePath = ModuleObjPath{}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001704
1705// PathForModuleObj returns a Path representing the paths... under the module's
1706// 'obj' directory.
Liz Kammera830f3a2020-11-10 10:50:34 -08001707func PathForModuleObj(ctx ModuleOutPathContext, pathComponents ...string) ModuleObjPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001708 p, err := validatePath(pathComponents...)
1709 if err != nil {
1710 reportPathError(ctx, err)
1711 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001712 return ModuleObjPath{PathForModuleOut(ctx, "obj", p)}
1713}
1714
1715// ModuleResPath is a a Path representing the 'res' directory in a module's
1716// output directory.
1717type ModuleResPath struct {
1718 ModuleOutPath
1719}
1720
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001721func (p ModuleResPath) RelativeToTop() Path {
1722 p.OutputPath = p.outputPathRelativeToTop()
1723 return p
1724}
1725
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001726var _ Path = ModuleResPath{}
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001727var _ WritablePath = ModuleResPath{}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001728
1729// PathForModuleRes returns a Path representing the paths... under the module's
1730// 'res' directory.
Liz Kammera830f3a2020-11-10 10:50:34 -08001731func PathForModuleRes(ctx ModuleOutPathContext, pathComponents ...string) ModuleResPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001732 p, err := validatePath(pathComponents...)
1733 if err != nil {
1734 reportPathError(ctx, err)
1735 }
1736
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001737 return ModuleResPath{PathForModuleOut(ctx, "res", p)}
1738}
1739
Colin Cross70dda7e2019-10-01 22:05:35 -07001740// InstallPath is a Path representing a installed file path rooted from the build directory
1741type InstallPath struct {
1742 basePath
Colin Crossff6c33d2019-10-02 16:01:35 -07001743
Lukacs T. Berkib078ade2021-08-31 10:42:08 +02001744 // The soong build directory, i.e. Config.SoongOutDir()
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02001745 soongOutDir string
Paul Duffind65c58b2021-03-24 09:22:07 +00001746
Jiyong Park957bcd92020-10-20 18:23:33 +09001747 // partitionDir is the part of the InstallPath that is automatically determined according to the context.
1748 // For example, it is host/<os>-<arch> for host modules, and target/product/<device>/<partition> for device modules.
1749 partitionDir string
1750
Colin Crossb1692a32021-10-25 15:39:01 -07001751 partition string
1752
Jiyong Park957bcd92020-10-20 18:23:33 +09001753 // makePath indicates whether this path is for Soong (false) or Make (true).
1754 makePath bool
Colin Crossc0e42d52024-02-01 16:42:36 -08001755
1756 fullPath string
Colin Cross70dda7e2019-10-01 22:05:35 -07001757}
1758
Yu Liu26a716d2024-08-30 23:40:32 +00001759func (p *InstallPath) GobEncode() ([]byte, error) {
1760 w := new(bytes.Buffer)
1761 encoder := gob.NewEncoder(w)
1762 err := errors.Join(encoder.Encode(p.basePath), encoder.Encode(p.soongOutDir),
1763 encoder.Encode(p.partitionDir), encoder.Encode(p.partition),
1764 encoder.Encode(p.makePath), encoder.Encode(p.fullPath))
1765 if err != nil {
1766 return nil, err
1767 }
1768
1769 return w.Bytes(), nil
1770}
1771
1772func (p *InstallPath) GobDecode(data []byte) error {
1773 r := bytes.NewBuffer(data)
1774 decoder := gob.NewDecoder(r)
1775 err := errors.Join(decoder.Decode(&p.basePath), decoder.Decode(&p.soongOutDir),
1776 decoder.Decode(&p.partitionDir), decoder.Decode(&p.partition),
1777 decoder.Decode(&p.makePath), decoder.Decode(&p.fullPath))
1778 if err != nil {
1779 return err
1780 }
1781
1782 return nil
1783}
1784
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001785// Will panic if called from outside a test environment.
1786func ensureTestOnly() {
Martin Stjernholm32312eb2021-03-27 18:54:49 +00001787 if PrefixInList(os.Args, "-test.") {
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001788 return
1789 }
Martin Stjernholm32312eb2021-03-27 18:54:49 +00001790 panic(fmt.Errorf("Not in test. Command line:\n %s", strings.Join(os.Args, "\n ")))
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001791}
1792
1793func (p InstallPath) RelativeToTop() Path {
1794 ensureTestOnly()
Colin Crossc0e42d52024-02-01 16:42:36 -08001795 if p.makePath {
Colin Cross3b1c6842024-07-26 11:52:57 -07001796 p.soongOutDir = testOutDir
Colin Crossc0e42d52024-02-01 16:42:36 -08001797 } else {
Colin Cross3b1c6842024-07-26 11:52:57 -07001798 p.soongOutDir = TestOutSoongDir
Colin Crossc0e42d52024-02-01 16:42:36 -08001799 }
1800 p.fullPath = filepath.Join(p.soongOutDir, p.path)
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001801 return p
1802}
1803
Colin Cross7707b242024-07-26 12:02:36 -07001804func (p InstallPath) WithoutRel() Path {
1805 p.basePath = p.basePath.withoutRel()
1806 return p
1807}
1808
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02001809func (p InstallPath) getSoongOutDir() string {
1810 return p.soongOutDir
Paul Duffin9b478b02019-12-10 13:41:51 +00001811}
1812
Hans MÃ¥nssond3f2bd72020-11-27 12:37:28 +01001813func (p InstallPath) ReplaceExtension(ctx PathContext, ext string) OutputPath {
1814 panic("Not implemented")
1815}
1816
Paul Duffin9b478b02019-12-10 13:41:51 +00001817var _ Path = InstallPath{}
1818var _ WritablePath = InstallPath{}
1819
Colin Cross70dda7e2019-10-01 22:05:35 -07001820func (p InstallPath) writablePath() {}
1821
1822func (p InstallPath) String() string {
Colin Crossc0e42d52024-02-01 16:42:36 -08001823 return p.fullPath
Jiyong Park957bcd92020-10-20 18:23:33 +09001824}
1825
1826// PartitionDir returns the path to the partition where the install path is rooted at. It is
1827// out/soong/target/product/<device>/<partition> for device modules, and out/soong/host/<os>-<arch> for host modules.
1828// The ./soong is dropped if the install path is for Make.
1829func (p InstallPath) PartitionDir() string {
1830 if p.makePath {
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02001831 return filepath.Join(p.soongOutDir, "../", p.partitionDir)
Jiyong Park957bcd92020-10-20 18:23:33 +09001832 } else {
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02001833 return filepath.Join(p.soongOutDir, p.partitionDir)
Jiyong Park957bcd92020-10-20 18:23:33 +09001834 }
Colin Cross70dda7e2019-10-01 22:05:35 -07001835}
1836
Jihoon Kangf78a8902022-09-01 22:47:07 +00001837func (p InstallPath) Partition() string {
1838 return p.partition
1839}
1840
Colin Cross70dda7e2019-10-01 22:05:35 -07001841// Join creates a new InstallPath with paths... joined with the current path. The
1842// provided paths... may not use '..' to escape from the current path.
1843func (p InstallPath) Join(ctx PathContext, paths ...string) InstallPath {
1844 path, err := validatePath(paths...)
1845 if err != nil {
1846 reportPathError(ctx, err)
1847 }
1848 return p.withRel(path)
1849}
1850
1851func (p InstallPath) withRel(rel string) InstallPath {
1852 p.basePath = p.basePath.withRel(rel)
Colin Crossc0e42d52024-02-01 16:42:36 -08001853 p.fullPath = filepath.Join(p.fullPath, rel)
Colin Cross70dda7e2019-10-01 22:05:35 -07001854 return p
1855}
1856
Colin Crossc68db4b2021-11-11 18:59:15 -08001857// Deprecated: ToMakePath is a noop, PathForModuleInstall always returns Make paths when building
1858// embedded in Make.
Colin Crossff6c33d2019-10-02 16:01:35 -07001859func (p InstallPath) ToMakePath() InstallPath {
Jiyong Park957bcd92020-10-20 18:23:33 +09001860 p.makePath = true
Colin Crossff6c33d2019-10-02 16:01:35 -07001861 return p
Colin Cross70dda7e2019-10-01 22:05:35 -07001862}
1863
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001864// PathForModuleInstall returns a Path representing the install path for the
1865// module appended with paths...
Colin Cross70dda7e2019-10-01 22:05:35 -07001866func PathForModuleInstall(ctx ModuleInstallPathContext, pathComponents ...string) InstallPath {
Spandan Das5d1b9292021-06-03 19:36:41 +00001867 os, arch := osAndArch(ctx)
Cole Faust11edf552023-10-13 11:32:14 -07001868 partition := modulePartition(ctx, os.Class == Device)
Cole Faust3b703f32023-10-16 13:30:51 -07001869 return pathForInstall(ctx, os, arch, partition, pathComponents...)
Spandan Das5d1b9292021-06-03 19:36:41 +00001870}
1871
Colin Cross1d0eb7a2021-11-03 14:08:20 -07001872// PathForHostDexInstall returns an InstallPath representing the install path for the
1873// module appended with paths...
1874func PathForHostDexInstall(ctx ModuleInstallPathContext, pathComponents ...string) InstallPath {
Cole Faust3b703f32023-10-16 13:30:51 -07001875 return pathForInstall(ctx, ctx.Config().BuildOS, ctx.Config().BuildArch, "", pathComponents...)
Colin Cross1d0eb7a2021-11-03 14:08:20 -07001876}
1877
Spandan Das5d1b9292021-06-03 19:36:41 +00001878// PathForModuleInPartitionInstall is similar to PathForModuleInstall but partition is provided by the caller
1879func PathForModuleInPartitionInstall(ctx ModuleInstallPathContext, partition string, pathComponents ...string) InstallPath {
1880 os, arch := osAndArch(ctx)
Cole Faust3b703f32023-10-16 13:30:51 -07001881 return pathForInstall(ctx, os, arch, partition, pathComponents...)
Spandan Das5d1b9292021-06-03 19:36:41 +00001882}
1883
1884func osAndArch(ctx ModuleInstallPathContext) (OsType, ArchType) {
Colin Cross6e359402020-02-10 15:29:54 -08001885 os := ctx.Os()
Jiyong Park87788b52020-09-01 12:37:45 +09001886 arch := ctx.Arch().ArchType
1887 forceOS, forceArch := ctx.InstallForceOS()
1888 if forceOS != nil {
Colin Cross6e359402020-02-10 15:29:54 -08001889 os = *forceOS
1890 }
Jiyong Park87788b52020-09-01 12:37:45 +09001891 if forceArch != nil {
1892 arch = *forceArch
1893 }
Spandan Das5d1b9292021-06-03 19:36:41 +00001894 return os, arch
1895}
Colin Cross609c49a2020-02-13 13:20:11 -08001896
Colin Crossc0e42d52024-02-01 16:42:36 -08001897func pathForPartitionInstallDir(ctx PathContext, partition, partitionPath string, makePath bool) InstallPath {
1898 fullPath := ctx.Config().SoongOutDir()
1899 if makePath {
1900 // Make path starts with out/ instead of out/soong.
1901 fullPath = filepath.Join(fullPath, "../", partitionPath)
1902 } else {
1903 fullPath = filepath.Join(fullPath, partitionPath)
1904 }
1905
1906 return InstallPath{
1907 basePath: basePath{partitionPath, ""},
1908 soongOutDir: ctx.Config().soongOutDir,
1909 partitionDir: partitionPath,
1910 partition: partition,
1911 makePath: makePath,
1912 fullPath: fullPath,
1913 }
1914}
1915
Cole Faust3b703f32023-10-16 13:30:51 -07001916func pathForInstall(ctx PathContext, os OsType, arch ArchType, partition string,
Colin Cross609c49a2020-02-13 13:20:11 -08001917 pathComponents ...string) InstallPath {
1918
Jiyong Park97859152023-02-14 17:05:48 +09001919 var partitionPaths []string
Colin Cross609c49a2020-02-13 13:20:11 -08001920
Colin Cross6e359402020-02-10 15:29:54 -08001921 if os.Class == Device {
Jiyong Park97859152023-02-14 17:05:48 +09001922 partitionPaths = []string{"target", "product", ctx.Config().DeviceName(), partition}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001923 } else {
Jiyong Park87788b52020-09-01 12:37:45 +09001924 osName := os.String()
Colin Crossa9b2aac2022-06-15 17:25:51 -07001925 if os == Linux {
Jiyong Park87788b52020-09-01 12:37:45 +09001926 // instead of linux_glibc
1927 osName = "linux"
Dan Willemsen866b5632017-09-22 12:28:24 -07001928 }
Colin Crossa9b2aac2022-06-15 17:25:51 -07001929 if os == LinuxMusl && ctx.Config().UseHostMusl() {
1930 // When using musl instead of glibc, use "linux" instead of "linux_musl". When cross
1931 // compiling we will still use "linux_musl".
1932 osName = "linux"
1933 }
1934
Jiyong Park87788b52020-09-01 12:37:45 +09001935 // SOONG_HOST_OUT is set to out/host/$(HOST_OS)-$(HOST_PREBUILT_ARCH)
1936 // and HOST_PREBUILT_ARCH is forcibly set to x86 even on x86_64 hosts. We don't seem
1937 // to have a plan to fix it (see the comment in build/make/core/envsetup.mk).
1938 // Let's keep using x86 for the existing cases until we have a need to support
1939 // other architectures.
1940 archName := arch.String()
1941 if os.Class == Host && (arch == X86_64 || arch == Common) {
1942 archName = "x86"
1943 }
Jiyong Park97859152023-02-14 17:05:48 +09001944 partitionPaths = []string{"host", osName + "-" + archName, partition}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001945 }
Colin Cross70dda7e2019-10-01 22:05:35 -07001946
Jiyong Park97859152023-02-14 17:05:48 +09001947 partitionPath, err := validatePath(partitionPaths...)
Colin Cross70dda7e2019-10-01 22:05:35 -07001948 if err != nil {
1949 reportPathError(ctx, err)
1950 }
Colin Crossff6c33d2019-10-02 16:01:35 -07001951
Colin Crossc0e42d52024-02-01 16:42:36 -08001952 base := pathForPartitionInstallDir(ctx, partition, partitionPath, ctx.Config().KatiEnabled())
Jiyong Park957bcd92020-10-20 18:23:33 +09001953 return base.Join(ctx, pathComponents...)
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001954}
1955
Spandan Dasf280b232024-04-04 21:25:51 +00001956func PathForNdkInstall(ctx PathContext, paths ...string) OutputPath {
1957 return PathForOutput(ctx, append([]string{"ndk"}, paths...)...)
Nicolas Geoffray1228e9c2020-02-27 13:45:35 +00001958}
1959
1960func PathForMainlineSdksInstall(ctx PathContext, paths ...string) InstallPath {
Spandan Dasf280b232024-04-04 21:25:51 +00001961 base := pathForPartitionInstallDir(ctx, "", "mainline-sdks", false)
1962 return base.Join(ctx, paths...)
Nicolas Geoffray1228e9c2020-02-27 13:45:35 +00001963}
1964
Colin Cross70dda7e2019-10-01 22:05:35 -07001965func InstallPathToOnDevicePath(ctx PathContext, path InstallPath) string {
Colin Crossb1692a32021-10-25 15:39:01 -07001966 rel := Rel(ctx, strings.TrimSuffix(path.PartitionDir(), path.partition), path.String())
Colin Cross43f08db2018-11-12 10:13:39 -08001967 return "/" + rel
1968}
1969
Cole Faust11edf552023-10-13 11:32:14 -07001970func modulePartition(ctx ModuleInstallPathContext, device bool) string {
Colin Cross43f08db2018-11-12 10:13:39 -08001971 var partition string
Colin Cross6e359402020-02-10 15:29:54 -08001972 if ctx.InstallInTestcases() {
1973 // "testcases" install directory can be used for host or device modules.
Jaewoong Jung0949f312019-09-11 10:25:18 -07001974 partition = "testcases"
Cole Faust11edf552023-10-13 11:32:14 -07001975 } else if device {
Colin Cross6e359402020-02-10 15:29:54 -08001976 if ctx.InstallInData() {
1977 partition = "data"
1978 } else if ctx.InstallInRamdisk() {
1979 if ctx.DeviceConfig().BoardUsesRecoveryAsBoot() {
1980 partition = "recovery/root/first_stage_ramdisk"
1981 } else {
1982 partition = "ramdisk"
1983 }
1984 if !ctx.InstallInRoot() {
1985 partition += "/system"
1986 }
Yifan Hong60e0cfb2020-10-21 15:17:56 -07001987 } else if ctx.InstallInVendorRamdisk() {
Yifan Hong39143a92020-10-26 12:43:12 -07001988 // The module is only available after switching root into
1989 // /first_stage_ramdisk. To expose the module before switching root
1990 // on a device without a dedicated recovery partition, install the
1991 // recovery variant.
Yifan Hongdd8dacc2020-10-21 15:40:17 -07001992 if ctx.DeviceConfig().BoardMoveRecoveryResourcesToVendorBoot() {
Petri Gyntherac229562021-03-02 23:44:02 -08001993 partition = "vendor_ramdisk/first_stage_ramdisk"
Yifan Hongdd8dacc2020-10-21 15:40:17 -07001994 } else {
Petri Gyntherac229562021-03-02 23:44:02 -08001995 partition = "vendor_ramdisk"
Yifan Hongdd8dacc2020-10-21 15:40:17 -07001996 }
1997 if !ctx.InstallInRoot() {
1998 partition += "/system"
1999 }
Inseob Kim08758f02021-04-08 21:13:22 +09002000 } else if ctx.InstallInDebugRamdisk() {
2001 partition = "debug_ramdisk"
Colin Cross6e359402020-02-10 15:29:54 -08002002 } else if ctx.InstallInRecovery() {
2003 if ctx.InstallInRoot() {
2004 partition = "recovery/root"
2005 } else {
2006 // the layout of recovery partion is the same as that of system partition
2007 partition = "recovery/root/system"
2008 }
Colin Crossea30d852023-11-29 16:00:16 -08002009 } else if ctx.SocSpecific() || ctx.InstallInVendor() {
Colin Cross6e359402020-02-10 15:29:54 -08002010 partition = ctx.DeviceConfig().VendorPath()
Colin Crossea30d852023-11-29 16:00:16 -08002011 } else if ctx.DeviceSpecific() || ctx.InstallInOdm() {
Colin Cross6e359402020-02-10 15:29:54 -08002012 partition = ctx.DeviceConfig().OdmPath()
Colin Crossea30d852023-11-29 16:00:16 -08002013 } else if ctx.ProductSpecific() || ctx.InstallInProduct() {
Colin Cross6e359402020-02-10 15:29:54 -08002014 partition = ctx.DeviceConfig().ProductPath()
2015 } else if ctx.SystemExtSpecific() {
2016 partition = ctx.DeviceConfig().SystemExtPath()
2017 } else if ctx.InstallInRoot() {
2018 partition = "root"
Yifan Hong82db7352020-01-21 16:12:26 -08002019 } else {
Colin Cross6e359402020-02-10 15:29:54 -08002020 partition = "system"
Yifan Hong82db7352020-01-21 16:12:26 -08002021 }
Colin Cross6e359402020-02-10 15:29:54 -08002022 if ctx.InstallInSanitizerDir() {
2023 partition = "data/asan/" + partition
Yifan Hong82db7352020-01-21 16:12:26 -08002024 }
Colin Cross43f08db2018-11-12 10:13:39 -08002025 }
2026 return partition
2027}
2028
Colin Cross609c49a2020-02-13 13:20:11 -08002029type InstallPaths []InstallPath
2030
2031// Paths returns the InstallPaths as a Paths
2032func (p InstallPaths) Paths() Paths {
2033 if p == nil {
2034 return nil
2035 }
2036 ret := make(Paths, len(p))
2037 for i, path := range p {
2038 ret[i] = path
2039 }
2040 return ret
2041}
2042
2043// Strings returns the string forms of the install paths.
2044func (p InstallPaths) Strings() []string {
2045 if p == nil {
2046 return nil
2047 }
2048 ret := make([]string, len(p))
2049 for i, path := range p {
2050 ret[i] = path.String()
2051 }
2052 return ret
2053}
2054
Jingwen Chen24d0c562023-02-07 09:29:36 +00002055// validatePathInternal ensures that a path does not leave its component, and
2056// optionally doesn't contain Ninja variables.
2057func validatePathInternal(allowNinjaVariables bool, pathComponents ...string) (string, error) {
Colin Crossbf9ed3f2023-10-24 14:17:03 -07002058 initialEmpty := 0
2059 finalEmpty := 0
2060 for i, path := range pathComponents {
Jingwen Chen24d0c562023-02-07 09:29:36 +00002061 if !allowNinjaVariables && strings.Contains(path, "$") {
2062 return "", fmt.Errorf("Path contains invalid character($): %s", path)
2063 }
2064
Dan Willemsen80a7c2a2015-12-21 14:57:11 -08002065 path := filepath.Clean(path)
2066 if path == ".." || strings.HasPrefix(path, "../") || strings.HasPrefix(path, "/") {
Colin Cross1ccfcc32018-02-22 13:54:26 -08002067 return "", fmt.Errorf("Path is outside directory: %s", path)
Dan Willemsen80a7c2a2015-12-21 14:57:11 -08002068 }
Colin Crossbf9ed3f2023-10-24 14:17:03 -07002069
2070 if i == initialEmpty && pathComponents[i] == "" {
2071 initialEmpty++
2072 }
2073 if i == finalEmpty && pathComponents[len(pathComponents)-1-i] == "" {
2074 finalEmpty++
2075 }
Dan Willemsen80a7c2a2015-12-21 14:57:11 -08002076 }
Colin Crossbf9ed3f2023-10-24 14:17:03 -07002077 // Optimization: filepath.Join("foo", "") returns a newly allocated copy
2078 // of "foo", while filepath.Join("foo") does not. Strip out any empty
2079 // path components.
2080 if initialEmpty == len(pathComponents) {
2081 return "", nil
2082 }
2083 nonEmptyPathComponents := pathComponents[initialEmpty : len(pathComponents)-finalEmpty]
Dan Willemsen34cc69e2015-09-23 15:26:20 -07002084 // TODO: filepath.Join isn't necessarily correct with embedded ninja
2085 // variables. '..' may remove the entire ninja variable, even if it
2086 // will be expanded to multiple nested directories.
Colin Crossbf9ed3f2023-10-24 14:17:03 -07002087 return filepath.Join(nonEmptyPathComponents...), nil
Dan Willemsen34cc69e2015-09-23 15:26:20 -07002088}
2089
Jingwen Chen24d0c562023-02-07 09:29:36 +00002090// validateSafePath validates a path that we trust (may contain ninja
2091// variables). Ensures that each path component does not attempt to leave its
2092// component. Returns a joined version of each path component.
2093func validateSafePath(pathComponents ...string) (string, error) {
2094 return validatePathInternal(true, pathComponents...)
2095}
2096
Dan Willemsen80a7c2a2015-12-21 14:57:11 -08002097// validatePath validates that a path does not include ninja variables, and that
2098// each path component does not attempt to leave its component. Returns a joined
2099// version of each path component.
Colin Cross1ccfcc32018-02-22 13:54:26 -08002100func validatePath(pathComponents ...string) (string, error) {
Jingwen Chen24d0c562023-02-07 09:29:36 +00002101 return validatePathInternal(false, pathComponents...)
Colin Cross6e18ca42015-07-14 18:55:36 -07002102}
Colin Cross5b529592017-05-09 13:34:34 -07002103
Colin Cross0875c522017-11-28 17:34:01 -08002104func PathForPhony(ctx PathContext, phony string) WritablePath {
2105 if strings.ContainsAny(phony, "$/") {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01002106 ReportPathErrorf(ctx, "Phony target contains invalid character ($ or /): %s", phony)
Colin Cross0875c522017-11-28 17:34:01 -08002107 }
Paul Duffin74abc5d2021-03-24 09:24:59 +00002108 return PhonyPath{basePath{phony, ""}}
Colin Cross0875c522017-11-28 17:34:01 -08002109}
2110
Colin Cross74e3fe42017-12-11 15:51:44 -08002111type PhonyPath struct {
2112 basePath
2113}
2114
2115func (p PhonyPath) writablePath() {}
2116
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02002117func (p PhonyPath) getSoongOutDir() string {
Paul Duffind65c58b2021-03-24 09:22:07 +00002118 // A phone path cannot contain any / so cannot be relative to the build directory.
2119 return ""
Paul Duffin9b478b02019-12-10 13:41:51 +00002120}
2121
Paul Duffin85d8f0d2021-03-24 10:18:18 +00002122func (p PhonyPath) RelativeToTop() Path {
2123 ensureTestOnly()
2124 // A phony path cannot contain any / so does not have a build directory so switching to a new
2125 // build directory has no effect so just return this path.
2126 return p
2127}
2128
Colin Cross7707b242024-07-26 12:02:36 -07002129func (p PhonyPath) WithoutRel() Path {
2130 p.basePath = p.basePath.withoutRel()
2131 return p
2132}
2133
Hans MÃ¥nssond3f2bd72020-11-27 12:37:28 +01002134func (p PhonyPath) ReplaceExtension(ctx PathContext, ext string) OutputPath {
2135 panic("Not implemented")
2136}
2137
Colin Cross74e3fe42017-12-11 15:51:44 -08002138var _ Path = PhonyPath{}
2139var _ WritablePath = PhonyPath{}
2140
Colin Cross5b529592017-05-09 13:34:34 -07002141type testPath struct {
2142 basePath
2143}
2144
Paul Duffin85d8f0d2021-03-24 10:18:18 +00002145func (p testPath) RelativeToTop() Path {
2146 ensureTestOnly()
2147 return p
2148}
2149
Colin Cross7707b242024-07-26 12:02:36 -07002150func (p testPath) WithoutRel() Path {
2151 p.basePath = p.basePath.withoutRel()
2152 return p
2153}
2154
Colin Cross5b529592017-05-09 13:34:34 -07002155func (p testPath) String() string {
2156 return p.path
2157}
2158
Paul Duffin85d8f0d2021-03-24 10:18:18 +00002159var _ Path = testPath{}
2160
Colin Cross40e33732019-02-15 11:08:35 -08002161// PathForTesting returns a Path constructed from joining the elements of paths with '/'. It should only be used from
2162// within tests.
Colin Cross5b529592017-05-09 13:34:34 -07002163func PathForTesting(paths ...string) Path {
Colin Cross1ccfcc32018-02-22 13:54:26 -08002164 p, err := validateSafePath(paths...)
2165 if err != nil {
2166 panic(err)
2167 }
Colin Cross5b529592017-05-09 13:34:34 -07002168 return testPath{basePath{path: p, rel: p}}
2169}
2170
Sam Delmerico2351eac2022-05-24 17:10:02 +00002171func PathForTestingWithRel(path, rel string) Path {
2172 p, err := validateSafePath(path, rel)
2173 if err != nil {
2174 panic(err)
2175 }
2176 r, err := validatePath(rel)
2177 if err != nil {
2178 panic(err)
2179 }
2180 return testPath{basePath{path: p, rel: r}}
2181}
2182
Colin Cross40e33732019-02-15 11:08:35 -08002183// PathsForTesting returns a Path constructed from each element in strs. It should only be used from within tests.
2184func PathsForTesting(strs ...string) Paths {
Colin Cross5b529592017-05-09 13:34:34 -07002185 p := make(Paths, len(strs))
2186 for i, s := range strs {
2187 p[i] = PathForTesting(s)
2188 }
2189
2190 return p
2191}
Colin Cross43f08db2018-11-12 10:13:39 -08002192
Colin Cross40e33732019-02-15 11:08:35 -08002193type testPathContext struct {
2194 config Config
Colin Cross40e33732019-02-15 11:08:35 -08002195}
2196
Colin Cross40e33732019-02-15 11:08:35 -08002197func (x *testPathContext) Config() Config { return x.config }
2198func (x *testPathContext) AddNinjaFileDeps(...string) {}
2199
2200// PathContextForTesting returns a PathContext that can be used in tests, for example to create an OutputPath with
2201// PathForOutput.
Colin Cross98be1bb2019-12-13 20:41:13 -08002202func PathContextForTesting(config Config) PathContext {
Colin Cross40e33732019-02-15 11:08:35 -08002203 return &testPathContext{
2204 config: config,
Colin Cross40e33732019-02-15 11:08:35 -08002205 }
2206}
2207
Ulya Trafimovichccc8c852020-10-14 11:29:07 +01002208type testModuleInstallPathContext struct {
2209 baseModuleContext
2210
2211 inData bool
2212 inTestcases bool
2213 inSanitizerDir bool
2214 inRamdisk bool
2215 inVendorRamdisk bool
Inseob Kim08758f02021-04-08 21:13:22 +09002216 inDebugRamdisk bool
Ulya Trafimovichccc8c852020-10-14 11:29:07 +01002217 inRecovery bool
2218 inRoot bool
Colin Crossea30d852023-11-29 16:00:16 -08002219 inOdm bool
2220 inProduct bool
2221 inVendor bool
Ulya Trafimovichccc8c852020-10-14 11:29:07 +01002222 forceOS *OsType
2223 forceArch *ArchType
2224}
2225
2226func (m testModuleInstallPathContext) Config() Config {
2227 return m.baseModuleContext.config
2228}
2229
2230func (testModuleInstallPathContext) AddNinjaFileDeps(deps ...string) {}
2231
2232func (m testModuleInstallPathContext) InstallInData() bool {
2233 return m.inData
2234}
2235
2236func (m testModuleInstallPathContext) InstallInTestcases() bool {
2237 return m.inTestcases
2238}
2239
2240func (m testModuleInstallPathContext) InstallInSanitizerDir() bool {
2241 return m.inSanitizerDir
2242}
2243
2244func (m testModuleInstallPathContext) InstallInRamdisk() bool {
2245 return m.inRamdisk
2246}
2247
2248func (m testModuleInstallPathContext) InstallInVendorRamdisk() bool {
2249 return m.inVendorRamdisk
2250}
2251
Inseob Kim08758f02021-04-08 21:13:22 +09002252func (m testModuleInstallPathContext) InstallInDebugRamdisk() bool {
2253 return m.inDebugRamdisk
2254}
2255
Ulya Trafimovichccc8c852020-10-14 11:29:07 +01002256func (m testModuleInstallPathContext) InstallInRecovery() bool {
2257 return m.inRecovery
2258}
2259
2260func (m testModuleInstallPathContext) InstallInRoot() bool {
2261 return m.inRoot
2262}
2263
Colin Crossea30d852023-11-29 16:00:16 -08002264func (m testModuleInstallPathContext) InstallInOdm() bool {
2265 return m.inOdm
2266}
2267
2268func (m testModuleInstallPathContext) InstallInProduct() bool {
2269 return m.inProduct
2270}
2271
2272func (m testModuleInstallPathContext) InstallInVendor() bool {
2273 return m.inVendor
2274}
2275
Ulya Trafimovichccc8c852020-10-14 11:29:07 +01002276func (m testModuleInstallPathContext) InstallForceOS() (*OsType, *ArchType) {
2277 return m.forceOS, m.forceArch
2278}
2279
2280// Construct a minimal ModuleInstallPathContext for testing. Note that baseModuleContext is
2281// default-initialized, which leaves blueprint.baseModuleContext set to nil, so methods that are
2282// delegated to it will panic.
2283func ModuleInstallPathContextForTesting(config Config) ModuleInstallPathContext {
2284 ctx := &testModuleInstallPathContext{}
2285 ctx.config = config
2286 ctx.os = Android
2287 return ctx
2288}
2289
Colin Cross43f08db2018-11-12 10:13:39 -08002290// Rel performs the same function as filepath.Rel, but reports errors to a PathContext, and reports an error if
2291// targetPath is not inside basePath.
2292func Rel(ctx PathContext, basePath string, targetPath string) string {
2293 rel, isRel := MaybeRel(ctx, basePath, targetPath)
2294 if !isRel {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01002295 ReportPathErrorf(ctx, "path %q is not under path %q", targetPath, basePath)
Colin Cross43f08db2018-11-12 10:13:39 -08002296 return ""
2297 }
2298 return rel
2299}
2300
2301// MaybeRel performs the same function as filepath.Rel, but reports errors to a PathContext, and returns false if
2302// targetPath is not inside basePath.
2303func MaybeRel(ctx PathContext, basePath string, targetPath string) (string, bool) {
Dan Willemsen633c5022019-04-12 11:11:38 -07002304 rel, isRel, err := maybeRelErr(basePath, targetPath)
2305 if err != nil {
2306 reportPathError(ctx, err)
2307 }
2308 return rel, isRel
2309}
2310
2311func maybeRelErr(basePath string, targetPath string) (string, bool, error) {
Colin Cross43f08db2018-11-12 10:13:39 -08002312 // filepath.Rel returns an error if one path is absolute and the other is not, handle that case first.
2313 if filepath.IsAbs(basePath) != filepath.IsAbs(targetPath) {
Dan Willemsen633c5022019-04-12 11:11:38 -07002314 return "", false, nil
Colin Cross43f08db2018-11-12 10:13:39 -08002315 }
2316 rel, err := filepath.Rel(basePath, targetPath)
2317 if err != nil {
Dan Willemsen633c5022019-04-12 11:11:38 -07002318 return "", false, err
Colin Cross43f08db2018-11-12 10:13:39 -08002319 } else if rel == ".." || strings.HasPrefix(rel, "../") || strings.HasPrefix(rel, "/") {
Dan Willemsen633c5022019-04-12 11:11:38 -07002320 return "", false, nil
Colin Cross43f08db2018-11-12 10:13:39 -08002321 }
Dan Willemsen633c5022019-04-12 11:11:38 -07002322 return rel, true, nil
Colin Cross43f08db2018-11-12 10:13:39 -08002323}
Colin Cross988414c2020-01-11 01:11:46 +00002324
2325// Writes a file to the output directory. Attempting to write directly to the output directory
2326// will fail due to the sandbox of the soong_build process.
Chris Parsons1a12d032023-02-06 22:37:41 -05002327// Only writes the file if the file doesn't exist or if it has different contents, to prevent
2328// updating the timestamp if no changes would be made. (This is better for incremental
2329// performance.)
Colin Cross988414c2020-01-11 01:11:46 +00002330func WriteFileToOutputDir(path WritablePath, data []byte, perm os.FileMode) error {
Colin Crossd6421132021-11-09 12:32:34 -08002331 absPath := absolutePath(path.String())
2332 err := os.MkdirAll(filepath.Dir(absPath), 0777)
2333 if err != nil {
2334 return err
2335 }
Chris Parsons1a12d032023-02-06 22:37:41 -05002336 return pathtools.WriteFileIfChanged(absPath, data, perm)
Colin Cross988414c2020-01-11 01:11:46 +00002337}
2338
Liz Kammer2dd9ca42020-11-25 16:06:39 -08002339func RemoveAllOutputDir(path WritablePath) error {
2340 return os.RemoveAll(absolutePath(path.String()))
2341}
2342
2343func CreateOutputDirIfNonexistent(path WritablePath, perm os.FileMode) error {
2344 dir := absolutePath(path.String())
Liz Kammer09f947d2021-05-12 14:51:49 -04002345 return createDirIfNonexistent(dir, perm)
2346}
2347
2348func createDirIfNonexistent(dir string, perm os.FileMode) error {
Liz Kammer2dd9ca42020-11-25 16:06:39 -08002349 if _, err := os.Stat(dir); os.IsNotExist(err) {
2350 return os.MkdirAll(dir, os.ModePerm)
2351 } else {
2352 return err
2353 }
2354}
2355
Jingwen Chen78257e52021-05-21 02:34:24 +00002356// absolutePath is deliberately private so that Soong's Go plugins can't use it to find and
2357// read arbitrary files without going through the methods in the current package that track
2358// dependencies.
Colin Cross988414c2020-01-11 01:11:46 +00002359func absolutePath(path string) string {
2360 if filepath.IsAbs(path) {
2361 return path
2362 }
2363 return filepath.Join(absSrcDir, path)
2364}
Chris Parsons216e10a2020-07-09 17:12:52 -04002365
2366// A DataPath represents the path of a file to be used as data, for example
2367// a test library to be installed alongside a test.
2368// The data file should be installed (copied from `<SrcPath>`) to
2369// `<install_root>/<RelativeInstallPath>/<filename>`, or
2370// `<install_root>/<filename>` if RelativeInstallPath is empty.
2371type DataPath struct {
2372 // The path of the data file that should be copied into the data directory
2373 SrcPath Path
2374 // The install path of the data file, relative to the install root.
2375 RelativeInstallPath string
Colin Cross5c1d5fb2023-11-15 12:39:40 -08002376 // If WithoutRel is true, use SrcPath.Base() instead of SrcPath.Rel() as the filename.
2377 WithoutRel bool
Chris Parsons216e10a2020-07-09 17:12:52 -04002378}
Colin Crossdcf71b22021-02-01 13:59:03 -08002379
Colin Crossd442a0e2023-11-16 11:19:26 -08002380func (d *DataPath) ToRelativeInstallPath() string {
2381 relPath := d.SrcPath.Rel()
Colin Cross5c1d5fb2023-11-15 12:39:40 -08002382 if d.WithoutRel {
2383 relPath = d.SrcPath.Base()
2384 }
Colin Crossd442a0e2023-11-16 11:19:26 -08002385 if d.RelativeInstallPath != "" {
2386 relPath = filepath.Join(d.RelativeInstallPath, relPath)
2387 }
2388 return relPath
2389}
2390
Colin Crossdcf71b22021-02-01 13:59:03 -08002391// PathsIfNonNil returns a Paths containing only the non-nil input arguments.
2392func PathsIfNonNil(paths ...Path) Paths {
2393 if len(paths) == 0 {
2394 // Fast path for empty argument list
2395 return nil
2396 } else if len(paths) == 1 {
2397 // Fast path for a single argument
2398 if paths[0] != nil {
2399 return paths
2400 } else {
2401 return nil
2402 }
2403 }
2404 ret := make(Paths, 0, len(paths))
2405 for _, path := range paths {
2406 if path != nil {
2407 ret = append(ret, path)
2408 }
2409 }
2410 if len(ret) == 0 {
2411 return nil
2412 }
2413 return ret
2414}
Chris Wailesb2703ad2021-07-30 13:25:42 -07002415
2416var thirdPartyDirPrefixExceptions = []*regexp.Regexp{
2417 regexp.MustCompile("^vendor/[^/]*google[^/]*/"),
2418 regexp.MustCompile("^hardware/google/"),
2419 regexp.MustCompile("^hardware/interfaces/"),
2420 regexp.MustCompile("^hardware/libhardware[^/]*/"),
2421 regexp.MustCompile("^hardware/ril/"),
2422}
2423
2424func IsThirdPartyPath(path string) bool {
2425 thirdPartyDirPrefixes := []string{"external/", "vendor/", "hardware/"}
2426
2427 if HasAnyPrefix(path, thirdPartyDirPrefixes) {
2428 for _, prefix := range thirdPartyDirPrefixExceptions {
2429 if prefix.MatchString(path) {
2430 return false
2431 }
2432 }
2433 return true
2434 }
2435 return false
2436}