blob: a7ee7ac011d03471f14cfc702333728c916b761c [file] [log] [blame]
Colin Cross3f40fa42015-01-30 17:27:36 -08001// Copyright 2015 Google Inc. All rights reserved.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
Colin Cross635c3b02016-05-18 15:37:25 -070015package android
Colin Cross3f40fa42015-01-30 17:27:36 -080016
17import (
Colin Cross6e18ca42015-07-14 18:55:36 -070018 "fmt"
Colin Cross988414c2020-01-11 01:11:46 +000019 "os"
Colin Cross6a745c62015-06-16 16:38:10 -070020 "path/filepath"
Dan Willemsen34cc69e2015-09-23 15:26:20 -070021 "reflect"
Chris Wailesb2703ad2021-07-30 13:25:42 -070022 "regexp"
Colin Cross5e6cfbe2017-11-03 15:20:35 -070023 "sort"
Dan Willemsen34cc69e2015-09-23 15:26:20 -070024 "strings"
25
26 "github.com/google/blueprint"
Yu Liu3cadf7d2024-10-24 18:47:06 +000027 "github.com/google/blueprint/gobtools"
Dan Willemsen34cc69e2015-09-23 15:26:20 -070028 "github.com/google/blueprint/pathtools"
Colin Cross3f40fa42015-01-30 17:27:36 -080029)
30
Colin Cross988414c2020-01-11 01:11:46 +000031var absSrcDir string
32
Dan Willemsen34cc69e2015-09-23 15:26:20 -070033// PathContext is the subset of a (Module|Singleton)Context required by the
34// Path methods.
35type PathContext interface {
Colin Crossaabf6792017-11-29 00:27:14 -080036 Config() Config
Dan Willemsen7b310ee2015-12-18 15:11:17 -080037 AddNinjaFileDeps(deps ...string)
Colin Cross3f40fa42015-01-30 17:27:36 -080038}
39
Colin Cross7f19f372016-11-01 11:10:25 -070040type PathGlobContext interface {
Colin Cross662d6142022-11-03 20:38:01 -070041 PathContext
Colin Cross7f19f372016-11-01 11:10:25 -070042 GlobWithDeps(globPattern string, excludes []string) ([]string, error)
43}
44
Colin Crossaabf6792017-11-29 00:27:14 -080045var _ PathContext = SingletonContext(nil)
46var _ PathContext = ModuleContext(nil)
Dan Willemsen34cc69e2015-09-23 15:26:20 -070047
Ulya Trafimovich8640ab92020-05-11 18:06:15 +010048// "Null" path context is a minimal path context for a given config.
49type NullPathContext struct {
50 config Config
51}
52
53func (NullPathContext) AddNinjaFileDeps(...string) {}
54func (ctx NullPathContext) Config() Config { return ctx.config }
55
Liz Kammera830f3a2020-11-10 10:50:34 -080056// EarlyModulePathContext is a subset of EarlyModuleContext methods required by the
57// Path methods. These path methods can be called before any mutators have run.
58type EarlyModulePathContext interface {
Liz Kammera830f3a2020-11-10 10:50:34 -080059 PathGlobContext
60
61 ModuleDir() string
62 ModuleErrorf(fmt string, args ...interface{})
Cole Fausta963b942024-04-11 17:43:00 -070063 OtherModulePropertyErrorf(module Module, property, fmt string, args ...interface{})
Liz Kammera830f3a2020-11-10 10:50:34 -080064}
65
66var _ EarlyModulePathContext = ModuleContext(nil)
67
68// Glob globs files and directories matching globPattern relative to ModuleDir(),
69// paths in the excludes parameter will be omitted.
70func Glob(ctx EarlyModulePathContext, globPattern string, excludes []string) Paths {
71 ret, err := ctx.GlobWithDeps(globPattern, excludes)
72 if err != nil {
73 ctx.ModuleErrorf("glob: %s", err.Error())
74 }
75 return pathsForModuleSrcFromFullPath(ctx, ret, true)
76}
77
78// GlobFiles globs *only* files (not directories) matching globPattern relative to ModuleDir().
79// Paths in the excludes parameter will be omitted.
80func GlobFiles(ctx EarlyModulePathContext, globPattern string, excludes []string) Paths {
81 ret, err := ctx.GlobWithDeps(globPattern, excludes)
82 if err != nil {
83 ctx.ModuleErrorf("glob: %s", err.Error())
84 }
85 return pathsForModuleSrcFromFullPath(ctx, ret, false)
86}
87
88// ModuleWithDepsPathContext is a subset of *ModuleContext methods required by
89// the Path methods that rely on module dependencies having been resolved.
90type ModuleWithDepsPathContext interface {
91 EarlyModulePathContext
Cole Faust55b56fe2024-08-23 12:06:11 -070092 OtherModuleProviderContext
Colin Cross648daea2024-09-12 14:35:29 -070093 VisitDirectDeps(visit func(Module))
Paul Duffin40131a32021-07-09 17:10:35 +010094 OtherModuleDependencyTag(m blueprint.Module) blueprint.DependencyTag
Cole Faust4e2bf9f2024-09-11 13:26:20 -070095 HasMutatorFinished(mutatorName string) bool
Liz Kammera830f3a2020-11-10 10:50:34 -080096}
97
98// ModuleMissingDepsPathContext is a subset of *ModuleContext methods required by
99// the Path methods that rely on module dependencies having been resolved and ability to report
100// missing dependency errors.
101type ModuleMissingDepsPathContext interface {
102 ModuleWithDepsPathContext
103 AddMissingDependencies(missingDeps []string)
104}
105
Dan Willemsen00269f22017-07-06 16:59:48 -0700106type ModuleInstallPathContext interface {
Colin Cross0ea8ba82019-06-06 14:33:29 -0700107 BaseModuleContext
Dan Willemsen00269f22017-07-06 16:59:48 -0700108
109 InstallInData() bool
Jaewoong Jung0949f312019-09-11 10:25:18 -0700110 InstallInTestcases() bool
Dan Willemsen00269f22017-07-06 16:59:48 -0700111 InstallInSanitizerDir() bool
Yifan Hong1b3348d2020-01-21 15:53:22 -0800112 InstallInRamdisk() bool
Yifan Hong60e0cfb2020-10-21 15:17:56 -0700113 InstallInVendorRamdisk() bool
Inseob Kim08758f02021-04-08 21:13:22 +0900114 InstallInDebugRamdisk() bool
Jiyong Parkf9332f12018-02-01 00:54:12 +0900115 InstallInRecovery() bool
Colin Cross90ba5f42019-10-02 11:10:58 -0700116 InstallInRoot() bool
Colin Crossea30d852023-11-29 16:00:16 -0800117 InstallInOdm() bool
118 InstallInProduct() bool
119 InstallInVendor() bool
Jiyong Park87788b52020-09-01 12:37:45 +0900120 InstallForceOS() (*OsType, *ArchType)
Dan Willemsen00269f22017-07-06 16:59:48 -0700121}
122
123var _ ModuleInstallPathContext = ModuleContext(nil)
124
Cole Faust11edf552023-10-13 11:32:14 -0700125type baseModuleContextToModuleInstallPathContext struct {
126 BaseModuleContext
127}
128
129func (ctx *baseModuleContextToModuleInstallPathContext) InstallInData() bool {
130 return ctx.Module().InstallInData()
131}
132
133func (ctx *baseModuleContextToModuleInstallPathContext) InstallInTestcases() bool {
134 return ctx.Module().InstallInTestcases()
135}
136
137func (ctx *baseModuleContextToModuleInstallPathContext) InstallInSanitizerDir() bool {
138 return ctx.Module().InstallInSanitizerDir()
139}
140
141func (ctx *baseModuleContextToModuleInstallPathContext) InstallInRamdisk() bool {
142 return ctx.Module().InstallInRamdisk()
143}
144
145func (ctx *baseModuleContextToModuleInstallPathContext) InstallInVendorRamdisk() bool {
146 return ctx.Module().InstallInVendorRamdisk()
147}
148
149func (ctx *baseModuleContextToModuleInstallPathContext) InstallInDebugRamdisk() bool {
150 return ctx.Module().InstallInDebugRamdisk()
151}
152
153func (ctx *baseModuleContextToModuleInstallPathContext) InstallInRecovery() bool {
154 return ctx.Module().InstallInRecovery()
155}
156
157func (ctx *baseModuleContextToModuleInstallPathContext) InstallInRoot() bool {
158 return ctx.Module().InstallInRoot()
159}
160
Colin Crossea30d852023-11-29 16:00:16 -0800161func (ctx *baseModuleContextToModuleInstallPathContext) InstallInOdm() bool {
162 return ctx.Module().InstallInOdm()
163}
164
165func (ctx *baseModuleContextToModuleInstallPathContext) InstallInProduct() bool {
166 return ctx.Module().InstallInProduct()
167}
168
169func (ctx *baseModuleContextToModuleInstallPathContext) InstallInVendor() bool {
170 return ctx.Module().InstallInVendor()
171}
172
Cole Faust11edf552023-10-13 11:32:14 -0700173func (ctx *baseModuleContextToModuleInstallPathContext) InstallForceOS() (*OsType, *ArchType) {
174 return ctx.Module().InstallForceOS()
175}
176
177var _ ModuleInstallPathContext = (*baseModuleContextToModuleInstallPathContext)(nil)
178
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700179// errorfContext is the interface containing the Errorf method matching the
180// Errorf method in blueprint.SingletonContext.
181type errorfContext interface {
182 Errorf(format string, args ...interface{})
Colin Cross3f40fa42015-01-30 17:27:36 -0800183}
184
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700185var _ errorfContext = blueprint.SingletonContext(nil)
186
Spandan Das59a4a2b2024-01-09 21:35:56 +0000187// ModuleErrorfContext is the interface containing the ModuleErrorf method matching
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700188// the ModuleErrorf method in blueprint.ModuleContext.
Spandan Das59a4a2b2024-01-09 21:35:56 +0000189type ModuleErrorfContext interface {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700190 ModuleErrorf(format string, args ...interface{})
Colin Cross3f40fa42015-01-30 17:27:36 -0800191}
192
Spandan Das59a4a2b2024-01-09 21:35:56 +0000193var _ ModuleErrorfContext = blueprint.ModuleContext(nil)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700194
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700195// reportPathError will register an error with the attached context. It
196// attempts ctx.ModuleErrorf for a better error message first, then falls
197// back to ctx.Errorf.
Colin Cross1ccfcc32018-02-22 13:54:26 -0800198func reportPathError(ctx PathContext, err error) {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +0100199 ReportPathErrorf(ctx, "%s", err.Error())
Colin Cross1ccfcc32018-02-22 13:54:26 -0800200}
201
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +0100202// ReportPathErrorf will register an error with the attached context. It
Colin Cross1ccfcc32018-02-22 13:54:26 -0800203// attempts ctx.ModuleErrorf for a better error message first, then falls
204// back to ctx.Errorf.
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +0100205func ReportPathErrorf(ctx PathContext, format string, args ...interface{}) {
Spandan Das59a4a2b2024-01-09 21:35:56 +0000206 if mctx, ok := ctx.(ModuleErrorfContext); ok {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700207 mctx.ModuleErrorf(format, args...)
208 } else if ectx, ok := ctx.(errorfContext); ok {
209 ectx.Errorf(format, args...)
210 } else {
211 panic(fmt.Sprintf(format, args...))
Colin Crossf2298272015-05-12 11:36:53 -0700212 }
213}
214
Colin Cross5e708052019-08-06 13:59:50 -0700215func pathContextName(ctx PathContext, module blueprint.Module) string {
216 if x, ok := ctx.(interface{ ModuleName(blueprint.Module) string }); ok {
217 return x.ModuleName(module)
218 } else if x, ok := ctx.(interface{ OtherModuleName(blueprint.Module) string }); ok {
219 return x.OtherModuleName(module)
220 }
221 return "unknown"
222}
223
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700224type Path interface {
225 // Returns the path in string form
226 String() string
227
Colin Cross4f6fc9c2016-10-26 10:05:25 -0700228 // Ext returns the extension of the last element of the path
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700229 Ext() string
Colin Cross4f6fc9c2016-10-26 10:05:25 -0700230
231 // Base returns the last element of the path
232 Base() string
Colin Crossfaeb7aa2017-02-01 14:12:44 -0800233
234 // Rel returns the portion of the path relative to the directory it was created from. For
235 // example, Rel on a PathsForModuleSrc would return the path relative to the module source
Colin Cross0db55682017-12-05 15:36:55 -0800236 // directory, and OutputPath.Join("foo").Rel() would return "foo".
Colin Crossfaeb7aa2017-02-01 14:12:44 -0800237 Rel() string
Paul Duffin85d8f0d2021-03-24 10:18:18 +0000238
Colin Cross7707b242024-07-26 12:02:36 -0700239 // WithoutRel returns a new Path with no relative path, i.e. Rel() will return the same value as Base().
240 WithoutRel() Path
241
Paul Duffin85d8f0d2021-03-24 10:18:18 +0000242 // RelativeToTop returns a new path relative to the top, it is provided solely for use in tests.
243 //
244 // It is guaranteed to always return the same type as it is called on, e.g. if called on an
245 // InstallPath then the returned value can be converted to an InstallPath.
246 //
247 // A standard build has the following structure:
248 // ../top/
249 // out/ - make install files go here.
Colin Cross3b1c6842024-07-26 11:52:57 -0700250 // out/soong - this is the outDir passed to NewTestConfig()
Paul Duffin85d8f0d2021-03-24 10:18:18 +0000251 // ... - the source files
252 //
253 // This function converts a path so that it appears relative to the ../top/ directory, i.e.
Colin Cross3b1c6842024-07-26 11:52:57 -0700254 // * Make install paths, which have the pattern "outDir/../<path>" are converted into the top
Paul Duffin85d8f0d2021-03-24 10:18:18 +0000255 // relative path "out/<path>"
Colin Cross3b1c6842024-07-26 11:52:57 -0700256 // * Soong install paths and other writable paths, which have the pattern "outDir/soong/<path>" are
Paul Duffin85d8f0d2021-03-24 10:18:18 +0000257 // converted into the top relative path "out/soong/<path>".
258 // * Source paths are already relative to the top.
259 // * Phony paths are not relative to anything.
260 // * toolDepPath have an absolute but known value in so don't need making relative to anything in
261 // order to test.
262 RelativeToTop() Path
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700263}
264
Paul Duffin85d8f0d2021-03-24 10:18:18 +0000265const (
Colin Cross3b1c6842024-07-26 11:52:57 -0700266 testOutDir = "out"
267 testOutSoongSubDir = "/soong"
268 TestOutSoongDir = testOutDir + testOutSoongSubDir
Paul Duffin85d8f0d2021-03-24 10:18:18 +0000269)
270
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700271// WritablePath is a type of path that can be used as an output for build rules.
272type WritablePath interface {
273 Path
274
Paul Duffin9b478b02019-12-10 13:41:51 +0000275 // return the path to the build directory.
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +0200276 getSoongOutDir() string
Paul Duffin9b478b02019-12-10 13:41:51 +0000277
Jeff Gaston734e3802017-04-10 15:47:24 -0700278 // the writablePath method doesn't directly do anything,
279 // but it allows a struct to distinguish between whether or not it implements the WritablePath interface
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700280 writablePath()
Hans MÃ¥nssond3f2bd72020-11-27 12:37:28 +0100281
282 ReplaceExtension(ctx PathContext, ext string) OutputPath
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700283}
284
285type genPathProvider interface {
Liz Kammera830f3a2020-11-10 10:50:34 -0800286 genPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleGenPath
yangbill6d032dd2024-04-18 03:05:49 +0000287 genPathWithExtAndTrimExt(ctx ModuleOutPathContext, subdir, ext string, trimExt string) ModuleGenPath
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700288}
289type objPathProvider interface {
Liz Kammera830f3a2020-11-10 10:50:34 -0800290 objPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleObjPath
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700291}
292type resPathProvider interface {
Liz Kammera830f3a2020-11-10 10:50:34 -0800293 resPathWithName(ctx ModuleOutPathContext, name string) ModuleResPath
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700294}
295
296// GenPathWithExt derives a new file path in ctx's generated sources directory
297// from the current path, but with the new extension.
Liz Kammera830f3a2020-11-10 10:50:34 -0800298func GenPathWithExt(ctx ModuleOutPathContext, subdir string, p Path, ext string) ModuleGenPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700299 if path, ok := p.(genPathProvider); ok {
Dan Willemsen21ec4902016-11-02 20:43:13 -0700300 return path.genPathWithExt(ctx, subdir, ext)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700301 }
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +0100302 ReportPathErrorf(ctx, "Tried to create generated file from unsupported path: %s(%s)", reflect.TypeOf(p).Name(), p)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700303 return PathForModuleGen(ctx)
304}
305
yangbill6d032dd2024-04-18 03:05:49 +0000306// GenPathWithExtAndTrimExt derives a new file path in ctx's generated sources directory
307// from the current path, but with the new extension and trim the suffix.
308func GenPathWithExtAndTrimExt(ctx ModuleOutPathContext, subdir string, p Path, ext string, trimExt string) ModuleGenPath {
309 if path, ok := p.(genPathProvider); ok {
310 return path.genPathWithExtAndTrimExt(ctx, subdir, ext, trimExt)
311 }
312 ReportPathErrorf(ctx, "Tried to create generated file from unsupported path: %s(%s)", reflect.TypeOf(p).Name(), p)
313 return PathForModuleGen(ctx)
314}
315
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700316// ObjPathWithExt derives a new file path in ctx's object directory from the
317// current path, but with the new extension.
Liz Kammera830f3a2020-11-10 10:50:34 -0800318func ObjPathWithExt(ctx ModuleOutPathContext, subdir string, p Path, ext string) ModuleObjPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700319 if path, ok := p.(objPathProvider); ok {
320 return path.objPathWithExt(ctx, subdir, ext)
321 }
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +0100322 ReportPathErrorf(ctx, "Tried to create object file from unsupported path: %s (%s)", reflect.TypeOf(p).Name(), p)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700323 return PathForModuleObj(ctx)
324}
325
326// ResPathWithName derives a new path in ctx's output resource directory, using
327// the current path to create the directory name, and the `name` argument for
328// the filename.
Liz Kammera830f3a2020-11-10 10:50:34 -0800329func ResPathWithName(ctx ModuleOutPathContext, p Path, name string) ModuleResPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700330 if path, ok := p.(resPathProvider); ok {
331 return path.resPathWithName(ctx, name)
332 }
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +0100333 ReportPathErrorf(ctx, "Tried to create res file from unsupported path: %s (%s)", reflect.TypeOf(p).Name(), p)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700334 return PathForModuleRes(ctx)
335}
336
337// OptionalPath is a container that may or may not contain a valid Path.
338type OptionalPath struct {
Martin Stjernholmc32dd1c2021-09-15 02:39:00 +0100339 path Path // nil if invalid.
340 invalidReason string // Not applicable if path != nil. "" if the reason is unknown.
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700341}
342
Yu Liu467d7c52024-09-18 21:54:44 +0000343type optionalPathGob struct {
344 Path Path
345 InvalidReason string
346}
347
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700348// OptionalPathForPath returns an OptionalPath containing the path.
349func OptionalPathForPath(path Path) OptionalPath {
Martin Stjernholm2fee27f2021-09-16 14:11:12 +0100350 return OptionalPath{path: path}
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700351}
352
Martin Stjernholmc32dd1c2021-09-15 02:39:00 +0100353// InvalidOptionalPath returns an OptionalPath that is invalid with the given reason.
354func InvalidOptionalPath(reason string) OptionalPath {
355
356 return OptionalPath{invalidReason: reason}
357}
358
Yu Liu467d7c52024-09-18 21:54:44 +0000359func (p *OptionalPath) ToGob() *optionalPathGob {
360 return &optionalPathGob{
361 Path: p.path,
362 InvalidReason: p.invalidReason,
363 }
364}
365
366func (p *OptionalPath) FromGob(data *optionalPathGob) {
367 p.path = data.Path
368 p.invalidReason = data.InvalidReason
369}
370
371func (p OptionalPath) GobEncode() ([]byte, error) {
Yu Liu3cadf7d2024-10-24 18:47:06 +0000372 return gobtools.CustomGobEncode[optionalPathGob](&p)
Yu Liu467d7c52024-09-18 21:54:44 +0000373}
374
375func (p *OptionalPath) GobDecode(data []byte) error {
Yu Liu3cadf7d2024-10-24 18:47:06 +0000376 return gobtools.CustomGobDecode[optionalPathGob](data, p)
Yu Liu467d7c52024-09-18 21:54:44 +0000377}
378
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700379// Valid returns whether there is a valid path
380func (p OptionalPath) Valid() bool {
Martin Stjernholm2fee27f2021-09-16 14:11:12 +0100381 return p.path != nil
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700382}
383
384// Path returns the Path embedded in this OptionalPath. You must be sure that
385// there is a valid path, since this method will panic if there is not.
386func (p OptionalPath) Path() Path {
Martin Stjernholm2fee27f2021-09-16 14:11:12 +0100387 if p.path == nil {
Martin Stjernholmc32dd1c2021-09-15 02:39:00 +0100388 msg := "Requesting an invalid path"
389 if p.invalidReason != "" {
390 msg += ": " + p.invalidReason
391 }
392 panic(msg)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700393 }
394 return p.path
395}
396
Martin Stjernholmc32dd1c2021-09-15 02:39:00 +0100397// InvalidReason returns the reason that the optional path is invalid, or "" if it is valid.
398func (p OptionalPath) InvalidReason() string {
399 if p.path != nil {
400 return ""
401 }
402 if p.invalidReason == "" {
403 return "unknown"
404 }
405 return p.invalidReason
406}
407
Paul Duffinef081852021-05-13 11:11:15 +0100408// AsPaths converts the OptionalPath into Paths.
409//
410// It returns nil if this is not valid, or a single length slice containing the Path embedded in
411// this OptionalPath.
412func (p OptionalPath) AsPaths() Paths {
Martin Stjernholm2fee27f2021-09-16 14:11:12 +0100413 if p.path == nil {
Paul Duffinef081852021-05-13 11:11:15 +0100414 return nil
415 }
416 return Paths{p.path}
417}
418
Paul Duffinafdd4062021-03-30 19:44:07 +0100419// RelativeToTop returns an OptionalPath with the path that was embedded having been replaced by the
420// result of calling Path.RelativeToTop on it.
421func (p OptionalPath) RelativeToTop() OptionalPath {
Martin Stjernholm2fee27f2021-09-16 14:11:12 +0100422 if p.path == nil {
Paul Duffina5b81352021-03-28 23:57:19 +0100423 return p
424 }
425 p.path = p.path.RelativeToTop()
426 return p
427}
428
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700429// String returns the string version of the Path, or "" if it isn't valid.
430func (p OptionalPath) String() string {
Martin Stjernholm2fee27f2021-09-16 14:11:12 +0100431 if p.path != nil {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700432 return p.path.String()
433 } else {
434 return ""
Colin Crossf2298272015-05-12 11:36:53 -0700435 }
436}
Colin Cross6e18ca42015-07-14 18:55:36 -0700437
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700438// Paths is a slice of Path objects, with helpers to operate on the collection.
439type Paths []Path
440
Paul Duffin85d8f0d2021-03-24 10:18:18 +0000441// RelativeToTop creates a new Paths containing the result of calling Path.RelativeToTop on each
442// item in this slice.
443func (p Paths) RelativeToTop() Paths {
444 ensureTestOnly()
445 if p == nil {
446 return p
447 }
448 ret := make(Paths, len(p))
449 for i, path := range p {
450 ret[i] = path.RelativeToTop()
451 }
452 return ret
453}
454
Jingwen Chen40fd90a2020-06-15 05:24:19 +0000455func (paths Paths) containsPath(path Path) bool {
456 for _, p := range paths {
457 if p == path {
458 return true
459 }
460 }
461 return false
462}
463
Liz Kammer7aa52882021-02-11 09:16:14 -0500464// PathsForSource returns Paths rooted from SrcDir, *not* rooted from the module's local source
465// directory
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700466func PathsForSource(ctx PathContext, paths []string) Paths {
467 ret := make(Paths, len(paths))
468 for i, path := range paths {
469 ret[i] = PathForSource(ctx, path)
470 }
471 return ret
472}
473
Liz Kammer7aa52882021-02-11 09:16:14 -0500474// ExistentPathsForSources returns a list of Paths rooted from SrcDir, *not* rooted from the
475// module's local source directory, that are found in the tree. If any are not found, they are
476// 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 -0700477func ExistentPathsForSources(ctx PathGlobContext, paths []string) Paths {
Dan Willemsen7b310ee2015-12-18 15:11:17 -0800478 ret := make(Paths, 0, len(paths))
479 for _, path := range paths {
Colin Cross32f38982018-02-22 11:47:25 -0800480 p := ExistentPathForSource(ctx, path)
Dan Willemsen7b310ee2015-12-18 15:11:17 -0800481 if p.Valid() {
482 ret = append(ret, p.Path())
483 }
484 }
485 return ret
486}
487
Liz Kammer620dea62021-04-14 17:36:10 -0400488// PathsForModuleSrc returns a Paths{} containing the resolved references in paths:
Colin Crossd079e0b2022-08-16 10:27:33 -0700489// - filepath, relative to local module directory, resolves as a filepath relative to the local
490// source directory
491// - glob, relative to the local module directory, resolves as filepath(s), relative to the local
492// source directory.
493// - other modules using the ":name{.tag}" syntax. These modules must implement SourceFileProducer
mrziwangd38e63d2024-07-15 13:43:37 -0700494// or set the OutputFilesProvider. These resolve as a filepath to an output filepath or generated
495// source filepath.
Colin Crossd079e0b2022-08-16 10:27:33 -0700496//
Liz Kammer620dea62021-04-14 17:36:10 -0400497// Properties passed as the paths argument must have been annotated with struct tag
Colin Cross41955e82019-05-29 14:40:35 -0700498// `android:"path"` so that dependencies on SourceFileProducer modules will have already been handled by the
Spandan Das950091c2023-07-19 22:26:37 +0000499// pathdeps mutator.
Liz Kammer620dea62021-04-14 17:36:10 -0400500// If a requested module is not found as a dependency:
Colin Crossd079e0b2022-08-16 10:27:33 -0700501// - if ctx.Config().AllowMissingDependencies() is true, this module to be marked as having
Liz Kammer620dea62021-04-14 17:36:10 -0400502// missing dependencies
Colin Crossd079e0b2022-08-16 10:27:33 -0700503// - otherwise, a ModuleError is thrown.
Liz Kammera830f3a2020-11-10 10:50:34 -0800504func PathsForModuleSrc(ctx ModuleMissingDepsPathContext, paths []string) Paths {
Colin Cross8a497952019-03-05 22:25:09 -0800505 return PathsForModuleSrcExcludes(ctx, paths, nil)
506}
507
Liz Kammer619be462022-01-28 15:13:39 -0500508type SourceInput struct {
509 Context ModuleMissingDepsPathContext
510 Paths []string
511 ExcludePaths []string
512 IncludeDirs bool
513}
514
Liz Kammer620dea62021-04-14 17:36:10 -0400515// PathsForModuleSrcExcludes returns a Paths{} containing the resolved references in paths, minus
516// those listed in excludes. Elements of paths and excludes are resolved as:
Colin Crossd079e0b2022-08-16 10:27:33 -0700517// - filepath, relative to local module directory, resolves as a filepath relative to the local
518// source directory
519// - glob, relative to the local module directory, resolves as filepath(s), relative to the local
520// source directory. Not valid in excludes.
521// - other modules using the ":name{.tag}" syntax. These modules must implement SourceFileProducer
mrziwangd38e63d2024-07-15 13:43:37 -0700522// or set the OutputFilesProvider. These resolve as a filepath to an output filepath or generated
523// source filepath.
Colin Crossd079e0b2022-08-16 10:27:33 -0700524//
Liz Kammer620dea62021-04-14 17:36:10 -0400525// excluding the items (similarly resolved
526// Properties passed as the paths argument must have been annotated with struct tag
527// `android:"path"` so that dependencies on SourceFileProducer modules will have already been handled by the
Spandan Das950091c2023-07-19 22:26:37 +0000528// pathdeps mutator.
Liz Kammer620dea62021-04-14 17:36:10 -0400529// If a requested module is not found as a dependency:
Colin Crossd079e0b2022-08-16 10:27:33 -0700530// - if ctx.Config().AllowMissingDependencies() is true, this module to be marked as having
Liz Kammer620dea62021-04-14 17:36:10 -0400531// missing dependencies
Colin Crossd079e0b2022-08-16 10:27:33 -0700532// - otherwise, a ModuleError is thrown.
Liz Kammera830f3a2020-11-10 10:50:34 -0800533func PathsForModuleSrcExcludes(ctx ModuleMissingDepsPathContext, paths, excludes []string) Paths {
Liz Kammer619be462022-01-28 15:13:39 -0500534 return PathsRelativeToModuleSourceDir(SourceInput{
535 Context: ctx,
536 Paths: paths,
537 ExcludePaths: excludes,
538 IncludeDirs: true,
539 })
540}
541
542func PathsRelativeToModuleSourceDir(input SourceInput) Paths {
543 ret, missingDeps := PathsAndMissingDepsRelativeToModuleSourceDir(input)
544 if input.Context.Config().AllowMissingDependencies() {
545 input.Context.AddMissingDependencies(missingDeps)
Colin Crossba71a3f2019-03-18 12:12:48 -0700546 } else {
547 for _, m := range missingDeps {
Liz Kammer619be462022-01-28 15:13:39 -0500548 input.Context.ModuleErrorf(`missing dependency on %q, is the property annotated with android:"path"?`, m)
Colin Crossba71a3f2019-03-18 12:12:48 -0700549 }
550 }
551 return ret
552}
553
Inseob Kim93036a52024-10-25 17:02:21 +0900554type directoryPath struct {
555 basePath
556}
557
558func (d *directoryPath) String() string {
559 return d.basePath.String()
560}
561
562func (d *directoryPath) base() basePath {
563 return d.basePath
564}
565
566// DirectoryPath represents a source path for directories. Incompatible with Path by design.
567type DirectoryPath interface {
568 String() string
569 base() basePath
570}
571
572var _ DirectoryPath = (*directoryPath)(nil)
573
574type DirectoryPaths []DirectoryPath
575
Inseob Kim76e19852024-10-10 17:57:22 +0900576// DirectoryPathsForModuleSrcExcludes returns a Paths{} containing the resolved references in
577// directory paths. Elements of paths are resolved as:
578// - filepath, relative to local module directory, resolves as a filepath relative to the local
579// source directory
580// - other modules using the ":name" syntax. These modules must implement DirProvider.
Inseob Kim93036a52024-10-25 17:02:21 +0900581func DirectoryPathsForModuleSrc(ctx ModuleMissingDepsPathContext, paths []string) DirectoryPaths {
582 var ret DirectoryPaths
Inseob Kim76e19852024-10-10 17:57:22 +0900583
584 for _, path := range paths {
585 if m, t := SrcIsModuleWithTag(path); m != "" {
586 module := GetModuleFromPathDep(ctx, m, t)
587 if module == nil {
588 ctx.ModuleErrorf(`missing dependency on %q, is the property annotated with android:"path"?`, m)
589 continue
590 }
591 if t != "" {
592 ctx.ModuleErrorf("DirProvider dependency %q does not support the tag %q", module, t)
593 continue
594 }
595 mctx, ok := ctx.(OtherModuleProviderContext)
596 if !ok {
597 panic(fmt.Errorf("%s is not an OtherModuleProviderContext", ctx))
598 }
599 if dirProvider, ok := OtherModuleProvider(mctx, module, DirProvider); ok {
600 ret = append(ret, dirProvider.Dirs...)
601 } else {
602 ReportPathErrorf(ctx, "module %q does not implement DirProvider", module)
603 }
604 } else {
605 p := pathForModuleSrc(ctx, path)
606 if isDir, err := ctx.Config().fs.IsDir(p.String()); err != nil {
607 ReportPathErrorf(ctx, "%s: %s", p, err.Error())
608 } else if !isDir {
609 ReportPathErrorf(ctx, "module directory path %q is not a directory", p)
610 } else {
Inseob Kim93036a52024-10-25 17:02:21 +0900611 ret = append(ret, &directoryPath{basePath{path: p.path, rel: p.rel}})
Inseob Kim76e19852024-10-10 17:57:22 +0900612 }
613 }
614 }
615
Inseob Kim93036a52024-10-25 17:02:21 +0900616 seen := make(map[DirectoryPath]bool, len(ret))
Inseob Kim76e19852024-10-10 17:57:22 +0900617 for _, path := range ret {
618 if seen[path] {
619 ReportPathErrorf(ctx, "duplicated path %q", path)
620 }
621 seen[path] = true
622 }
623 return ret
624}
625
Ulya Trafimovich4d2eeed2019-11-08 10:54:21 +0000626// OutputPaths is a slice of OutputPath objects, with helpers to operate on the collection.
627type OutputPaths []OutputPath
628
629// Paths returns the OutputPaths as a Paths
630func (p OutputPaths) Paths() Paths {
631 if p == nil {
632 return nil
633 }
634 ret := make(Paths, len(p))
635 for i, path := range p {
636 ret[i] = path
637 }
638 return ret
639}
640
641// Strings returns the string forms of the writable paths.
642func (p OutputPaths) Strings() []string {
643 if p == nil {
644 return nil
645 }
646 ret := make([]string, len(p))
647 for i, path := range p {
648 ret[i] = path.String()
649 }
650 return ret
651}
652
Liz Kammera830f3a2020-11-10 10:50:34 -0800653// Expands Paths to a SourceFileProducer or OutputFileProducer module dependency referenced via ":name" or ":name{.tag}" syntax.
654// If the dependency is not found, a missingErrorDependency is returned.
655// If the module dependency is not a SourceFileProducer or OutputFileProducer, appropriate errors will be returned.
656func getPathsFromModuleDep(ctx ModuleWithDepsPathContext, path, moduleName, tag string) (Paths, error) {
Paul Duffind5cf92e2021-07-09 17:38:55 +0100657 module := GetModuleFromPathDep(ctx, moduleName, tag)
Liz Kammera830f3a2020-11-10 10:50:34 -0800658 if module == nil {
659 return nil, missingDependencyError{[]string{moduleName}}
660 }
Cole Fausta963b942024-04-11 17:43:00 -0700661 if aModule, ok := module.(Module); ok && !aModule.Enabled(ctx) {
Colin Crossfa65cee2021-03-22 17:05:59 -0700662 return nil, missingDependencyError{[]string{moduleName}}
663 }
mrziwange6c85812024-05-22 14:36:09 -0700664 outputFiles, err := outputFilesForModule(ctx, module, tag)
665 if outputFiles != nil && err == nil {
666 return outputFiles, nil
Liz Kammera830f3a2020-11-10 10:50:34 -0800667 } else {
mrziwange6c85812024-05-22 14:36:09 -0700668 return nil, err
Liz Kammera830f3a2020-11-10 10:50:34 -0800669 }
670}
671
Paul Duffind5cf92e2021-07-09 17:38:55 +0100672// GetModuleFromPathDep will return the module that was added as a dependency automatically for
673// properties tagged with `android:"path"` or manually using ExtractSourceDeps or
674// ExtractSourcesDeps.
675//
676// The moduleName and tag supplied to this should be the values returned from SrcIsModuleWithTag.
677// Or, if no tag is expected then the moduleName should be the value returned by SrcIsModule and
678// the tag must be "".
679//
680// If tag is "" then the returned module will be the dependency that was added for ":moduleName".
681// Otherwise, it is the dependency that was added for ":moduleName{tag}".
Paul Duffind5cf92e2021-07-09 17:38:55 +0100682func GetModuleFromPathDep(ctx ModuleWithDepsPathContext, moduleName, tag string) blueprint.Module {
Paul Duffin40131a32021-07-09 17:10:35 +0100683 var found blueprint.Module
684 // The sourceOrOutputDepTag uniquely identifies the module dependency as it contains both the
685 // module name and the tag. Dependencies added automatically for properties tagged with
686 // `android:"path"` are deduped so are guaranteed to be unique. It is possible for duplicate
687 // dependencies to be added manually using ExtractSourcesDeps or ExtractSourceDeps but even then
688 // it will always be the case that the dependencies will be identical, i.e. the same tag and same
689 // moduleName referring to the same dependency module.
690 //
691 // It does not matter whether the moduleName is a fully qualified name or if the module
692 // dependency is a prebuilt module. All that matters is the same information is supplied to
693 // create the tag here as was supplied to create the tag when the dependency was added so that
694 // this finds the matching dependency module.
695 expectedTag := sourceOrOutputDepTag(moduleName, tag)
Colin Cross648daea2024-09-12 14:35:29 -0700696 ctx.VisitDirectDeps(func(module Module) {
Paul Duffin40131a32021-07-09 17:10:35 +0100697 depTag := ctx.OtherModuleDependencyTag(module)
698 if depTag == expectedTag {
699 found = module
700 }
701 })
702 return found
Paul Duffind5cf92e2021-07-09 17:38:55 +0100703}
704
Liz Kammer620dea62021-04-14 17:36:10 -0400705// PathsAndMissingDepsForModuleSrcExcludes returns a Paths{} containing the resolved references in
706// paths, minus those listed in excludes. Elements of paths and excludes are resolved as:
Colin Crossd079e0b2022-08-16 10:27:33 -0700707// - filepath, relative to local module directory, resolves as a filepath relative to the local
708// source directory
709// - glob, relative to the local module directory, resolves as filepath(s), relative to the local
710// source directory. Not valid in excludes.
711// - other modules using the ":name{.tag}" syntax. These modules must implement SourceFileProducer
mrziwangd38e63d2024-07-15 13:43:37 -0700712// or set the OutputFilesProvider. These resolve as a filepath to an output filepath or generated
713// source filepath.
Colin Crossd079e0b2022-08-16 10:27:33 -0700714//
Liz Kammer620dea62021-04-14 17:36:10 -0400715// and a list of the module names of missing module dependencies are returned as the second return.
716// Properties passed as the paths argument must have been annotated with struct tag
Colin Cross41955e82019-05-29 14:40:35 -0700717// `android:"path"` so that dependencies on SourceFileProducer modules will have already been handled by the
Spandan Das950091c2023-07-19 22:26:37 +0000718// pathdeps mutator.
Liz Kammer619be462022-01-28 15:13:39 -0500719func PathsAndMissingDepsForModuleSrcExcludes(ctx ModuleMissingDepsPathContext, paths, excludes []string) (Paths, []string) {
720 return PathsAndMissingDepsRelativeToModuleSourceDir(SourceInput{
721 Context: ctx,
722 Paths: paths,
723 ExcludePaths: excludes,
724 IncludeDirs: true,
725 })
726}
727
728func PathsAndMissingDepsRelativeToModuleSourceDir(input SourceInput) (Paths, []string) {
729 prefix := pathForModuleSrc(input.Context).String()
Colin Cross8a497952019-03-05 22:25:09 -0800730
731 var expandedExcludes []string
Liz Kammer619be462022-01-28 15:13:39 -0500732 if input.ExcludePaths != nil {
733 expandedExcludes = make([]string, 0, len(input.ExcludePaths))
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700734 }
Colin Cross8a497952019-03-05 22:25:09 -0800735
Colin Crossba71a3f2019-03-18 12:12:48 -0700736 var missingExcludeDeps []string
Liz Kammer619be462022-01-28 15:13:39 -0500737 for _, e := range input.ExcludePaths {
Colin Cross41955e82019-05-29 14:40:35 -0700738 if m, t := SrcIsModuleWithTag(e); m != "" {
Liz Kammer619be462022-01-28 15:13:39 -0500739 modulePaths, err := getPathsFromModuleDep(input.Context, e, m, t)
Liz Kammera830f3a2020-11-10 10:50:34 -0800740 if m, ok := err.(missingDependencyError); ok {
741 missingExcludeDeps = append(missingExcludeDeps, m.missingDeps...)
742 } else if err != nil {
Liz Kammer619be462022-01-28 15:13:39 -0500743 reportPathError(input.Context, err)
Colin Cross8a497952019-03-05 22:25:09 -0800744 } else {
Liz Kammera830f3a2020-11-10 10:50:34 -0800745 expandedExcludes = append(expandedExcludes, modulePaths.Strings()...)
Colin Cross8a497952019-03-05 22:25:09 -0800746 }
747 } else {
748 expandedExcludes = append(expandedExcludes, filepath.Join(prefix, e))
749 }
750 }
751
Liz Kammer619be462022-01-28 15:13:39 -0500752 if input.Paths == nil {
Colin Crossba71a3f2019-03-18 12:12:48 -0700753 return nil, missingExcludeDeps
Colin Cross8a497952019-03-05 22:25:09 -0800754 }
755
Colin Crossba71a3f2019-03-18 12:12:48 -0700756 var missingDeps []string
757
Liz Kammer619be462022-01-28 15:13:39 -0500758 expandedSrcFiles := make(Paths, 0, len(input.Paths))
759 for _, s := range input.Paths {
760 srcFiles, err := expandOneSrcPath(sourcePathInput{
761 context: input.Context,
762 path: s,
763 expandedExcludes: expandedExcludes,
764 includeDirs: input.IncludeDirs,
765 })
Colin Cross8a497952019-03-05 22:25:09 -0800766 if depErr, ok := err.(missingDependencyError); ok {
Colin Crossba71a3f2019-03-18 12:12:48 -0700767 missingDeps = append(missingDeps, depErr.missingDeps...)
Colin Cross8a497952019-03-05 22:25:09 -0800768 } else if err != nil {
Liz Kammer619be462022-01-28 15:13:39 -0500769 reportPathError(input.Context, err)
Colin Cross8a497952019-03-05 22:25:09 -0800770 }
771 expandedSrcFiles = append(expandedSrcFiles, srcFiles...)
772 }
Colin Crossba71a3f2019-03-18 12:12:48 -0700773
Jihoon Kang0e3a5352024-04-12 00:45:50 +0000774 // TODO: b/334169722 - Replace with an error instead of implicitly removing duplicates.
775 return FirstUniquePaths(expandedSrcFiles), append(missingDeps, missingExcludeDeps...)
Colin Cross8a497952019-03-05 22:25:09 -0800776}
777
778type missingDependencyError struct {
779 missingDeps []string
780}
781
782func (e missingDependencyError) Error() string {
783 return "missing dependencies: " + strings.Join(e.missingDeps, ", ")
784}
785
Liz Kammer619be462022-01-28 15:13:39 -0500786type sourcePathInput struct {
787 context ModuleWithDepsPathContext
788 path string
789 expandedExcludes []string
790 includeDirs bool
791}
792
Liz Kammera830f3a2020-11-10 10:50:34 -0800793// Expands one path string to Paths rooted from the module's local source
794// directory, excluding those listed in the expandedExcludes.
795// Expands globs, references to SourceFileProducer or OutputFileProducer modules using the ":name" and ":name{.tag}" syntax.
Liz Kammer619be462022-01-28 15:13:39 -0500796func expandOneSrcPath(input sourcePathInput) (Paths, error) {
Jooyung Han7607dd32020-07-05 10:23:14 +0900797 excludePaths := func(paths Paths) Paths {
Liz Kammer619be462022-01-28 15:13:39 -0500798 if len(input.expandedExcludes) == 0 {
Jooyung Han7607dd32020-07-05 10:23:14 +0900799 return paths
800 }
801 remainder := make(Paths, 0, len(paths))
802 for _, p := range paths {
Liz Kammer619be462022-01-28 15:13:39 -0500803 if !InList(p.String(), input.expandedExcludes) {
Jooyung Han7607dd32020-07-05 10:23:14 +0900804 remainder = append(remainder, p)
805 }
806 }
807 return remainder
808 }
Liz Kammer619be462022-01-28 15:13:39 -0500809 if m, t := SrcIsModuleWithTag(input.path); m != "" {
810 modulePaths, err := getPathsFromModuleDep(input.context, input.path, m, t)
Liz Kammera830f3a2020-11-10 10:50:34 -0800811 if err != nil {
812 return nil, err
Colin Cross8a497952019-03-05 22:25:09 -0800813 } else {
Liz Kammera830f3a2020-11-10 10:50:34 -0800814 return excludePaths(modulePaths), nil
Colin Cross8a497952019-03-05 22:25:09 -0800815 }
Colin Cross8a497952019-03-05 22:25:09 -0800816 } else {
Liz Kammer619be462022-01-28 15:13:39 -0500817 p := pathForModuleSrc(input.context, input.path)
818 if pathtools.IsGlob(input.path) {
819 paths := GlobFiles(input.context, p.String(), input.expandedExcludes)
820 return PathsWithModuleSrcSubDir(input.context, paths, ""), nil
821 } else {
822 if exists, _, err := input.context.Config().fs.Exists(p.String()); err != nil {
823 ReportPathErrorf(input.context, "%s: %s", p, err.Error())
824 } else if !exists && !input.context.Config().TestAllowNonExistentPaths {
825 ReportPathErrorf(input.context, "module source path %q does not exist", p)
826 } else if !input.includeDirs {
827 if isDir, err := input.context.Config().fs.IsDir(p.String()); exists && err != nil {
828 ReportPathErrorf(input.context, "%s: %s", p, err.Error())
829 } else if isDir {
830 ReportPathErrorf(input.context, "module source path %q is a directory", p)
831 }
832 }
Colin Cross8a497952019-03-05 22:25:09 -0800833
Liz Kammer619be462022-01-28 15:13:39 -0500834 if InList(p.String(), input.expandedExcludes) {
835 return nil, nil
836 }
837 return Paths{p}, nil
Colin Cross8a497952019-03-05 22:25:09 -0800838 }
Colin Cross8a497952019-03-05 22:25:09 -0800839 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700840}
841
842// pathsForModuleSrcFromFullPath returns Paths rooted from the module's local
843// source directory, but strip the local source directory from the beginning of
Dan Willemsen540a78c2018-02-26 21:50:08 -0800844// each string. If incDirs is false, strip paths with a trailing '/' from the list.
Colin Crossfe4bc362018-09-12 10:02:13 -0700845// It intended for use in globs that only list files that exist, so it allows '$' in
846// filenames.
Liz Kammera830f3a2020-11-10 10:50:34 -0800847func pathsForModuleSrcFromFullPath(ctx EarlyModulePathContext, paths []string, incDirs bool) Paths {
Lukacs T. Berkif7e36d82021-08-16 17:05:09 +0200848 prefix := ctx.ModuleDir() + "/"
Colin Cross0f37af02017-09-27 17:42:05 -0700849 if prefix == "./" {
850 prefix = ""
851 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700852 ret := make(Paths, 0, len(paths))
853 for _, p := range paths {
Dan Willemsen540a78c2018-02-26 21:50:08 -0800854 if !incDirs && strings.HasSuffix(p, "/") {
855 continue
856 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700857 path := filepath.Clean(p)
858 if !strings.HasPrefix(path, prefix) {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +0100859 ReportPathErrorf(ctx, "Path %q is not in module source directory %q", p, prefix)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700860 continue
861 }
Colin Crosse3924e12018-08-15 20:18:53 -0700862
Colin Crossfe4bc362018-09-12 10:02:13 -0700863 srcPath, err := safePathForSource(ctx, ctx.ModuleDir(), path[len(prefix):])
Colin Crosse3924e12018-08-15 20:18:53 -0700864 if err != nil {
865 reportPathError(ctx, err)
866 continue
867 }
868
Colin Cross07e51612019-03-05 12:46:40 -0800869 srcPath.basePath.rel = srcPath.path
Colin Crosse3924e12018-08-15 20:18:53 -0700870
Colin Cross07e51612019-03-05 12:46:40 -0800871 ret = append(ret, srcPath)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700872 }
873 return ret
874}
875
Liz Kammera830f3a2020-11-10 10:50:34 -0800876// PathsWithOptionalDefaultForModuleSrc returns Paths rooted from the module's local source
877// directory. If input is nil, use the default if it exists. If input is empty, returns nil.
878func PathsWithOptionalDefaultForModuleSrc(ctx ModuleMissingDepsPathContext, input []string, def string) Paths {
Colin Cross0ddae7f2019-02-07 15:30:01 -0800879 if input != nil {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700880 return PathsForModuleSrc(ctx, input)
881 }
882 // Use Glob so that if the default doesn't exist, a dependency is added so that when it
883 // is created, we're run again.
Lukacs T. Berkif7e36d82021-08-16 17:05:09 +0200884 path := filepath.Join(ctx.ModuleDir(), def)
Liz Kammera830f3a2020-11-10 10:50:34 -0800885 return Glob(ctx, path, nil)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700886}
887
888// Strings returns the Paths in string form
889func (p Paths) Strings() []string {
890 if p == nil {
891 return nil
892 }
893 ret := make([]string, len(p))
894 for i, path := range p {
895 ret[i] = path.String()
896 }
897 return ret
898}
899
Colin Crossc0efd1d2020-07-03 11:56:24 -0700900func CopyOfPaths(paths Paths) Paths {
901 return append(Paths(nil), paths...)
902}
903
Colin Crossb6715442017-10-24 11:13:31 -0700904// FirstUniquePaths returns all unique elements of a Paths, keeping the first copy of each. It
905// modifies the Paths slice contents in place, and returns a subslice of the original slice.
Dan Willemsenfe92c962017-08-29 12:28:37 -0700906func FirstUniquePaths(list Paths) Paths {
Colin Cross27027c72020-02-28 15:34:17 -0800907 // 128 was chosen based on BenchmarkFirstUniquePaths results.
908 if len(list) > 128 {
909 return firstUniquePathsMap(list)
910 }
911 return firstUniquePathsList(list)
912}
913
Colin Crossc0efd1d2020-07-03 11:56:24 -0700914// SortedUniquePaths returns all unique elements of a Paths in sorted order. It modifies the
915// Paths slice contents in place, and returns a subslice of the original slice.
Jiyong Park33c77362020-05-29 22:00:16 +0900916func SortedUniquePaths(list Paths) Paths {
917 unique := FirstUniquePaths(list)
918 sort.Slice(unique, func(i, j int) bool {
919 return unique[i].String() < unique[j].String()
920 })
921 return unique
922}
923
Colin Cross27027c72020-02-28 15:34:17 -0800924func firstUniquePathsList(list Paths) Paths {
Dan Willemsenfe92c962017-08-29 12:28:37 -0700925 k := 0
926outer:
927 for i := 0; i < len(list); i++ {
928 for j := 0; j < k; j++ {
929 if list[i] == list[j] {
930 continue outer
931 }
932 }
933 list[k] = list[i]
934 k++
935 }
936 return list[:k]
937}
938
Colin Cross27027c72020-02-28 15:34:17 -0800939func firstUniquePathsMap(list Paths) Paths {
940 k := 0
941 seen := make(map[Path]bool, len(list))
942 for i := 0; i < len(list); i++ {
943 if seen[list[i]] {
944 continue
945 }
946 seen[list[i]] = true
947 list[k] = list[i]
948 k++
949 }
950 return list[:k]
951}
952
Colin Cross5d583952020-11-24 16:21:24 -0800953// FirstUniqueInstallPaths returns all unique elements of an InstallPaths, keeping the first copy of each. It
954// modifies the InstallPaths slice contents in place, and returns a subslice of the original slice.
955func FirstUniqueInstallPaths(list InstallPaths) InstallPaths {
956 // 128 was chosen based on BenchmarkFirstUniquePaths results.
957 if len(list) > 128 {
958 return firstUniqueInstallPathsMap(list)
959 }
960 return firstUniqueInstallPathsList(list)
961}
962
963func firstUniqueInstallPathsList(list InstallPaths) InstallPaths {
964 k := 0
965outer:
966 for i := 0; i < len(list); i++ {
967 for j := 0; j < k; j++ {
968 if list[i] == list[j] {
969 continue outer
970 }
971 }
972 list[k] = list[i]
973 k++
974 }
975 return list[:k]
976}
977
978func firstUniqueInstallPathsMap(list InstallPaths) InstallPaths {
979 k := 0
980 seen := make(map[InstallPath]bool, len(list))
981 for i := 0; i < len(list); i++ {
982 if seen[list[i]] {
983 continue
984 }
985 seen[list[i]] = true
986 list[k] = list[i]
987 k++
988 }
989 return list[:k]
990}
991
Colin Crossb6715442017-10-24 11:13:31 -0700992// LastUniquePaths returns all unique elements of a Paths, keeping the last copy of each. It
993// modifies the Paths slice contents in place, and returns a subslice of the original slice.
994func LastUniquePaths(list Paths) Paths {
995 totalSkip := 0
996 for i := len(list) - 1; i >= totalSkip; i-- {
997 skip := 0
998 for j := i - 1; j >= totalSkip; j-- {
999 if list[i] == list[j] {
1000 skip++
1001 } else {
1002 list[j+skip] = list[j]
1003 }
1004 }
1005 totalSkip += skip
1006 }
1007 return list[totalSkip:]
1008}
1009
Colin Crossa140bb02018-04-17 10:52:26 -07001010// ReversePaths returns a copy of a Paths in reverse order.
1011func ReversePaths(list Paths) Paths {
1012 if list == nil {
1013 return nil
1014 }
1015 ret := make(Paths, len(list))
1016 for i := range list {
1017 ret[i] = list[len(list)-1-i]
1018 }
1019 return ret
1020}
1021
Jeff Gaston294356f2017-09-27 17:05:30 -07001022func indexPathList(s Path, list []Path) int {
1023 for i, l := range list {
1024 if l == s {
1025 return i
1026 }
1027 }
1028
1029 return -1
1030}
1031
1032func inPathList(p Path, list []Path) bool {
1033 return indexPathList(p, list) != -1
1034}
1035
1036func FilterPathList(list []Path, filter []Path) (remainder []Path, filtered []Path) {
Paul Duffin57b9e1d2019-12-13 00:03:35 +00001037 return FilterPathListPredicate(list, func(p Path) bool { return inPathList(p, filter) })
1038}
1039
1040func FilterPathListPredicate(list []Path, predicate func(Path) bool) (remainder []Path, filtered []Path) {
Jeff Gaston294356f2017-09-27 17:05:30 -07001041 for _, l := range list {
Paul Duffin57b9e1d2019-12-13 00:03:35 +00001042 if predicate(l) {
Jeff Gaston294356f2017-09-27 17:05:30 -07001043 filtered = append(filtered, l)
1044 } else {
1045 remainder = append(remainder, l)
1046 }
1047 }
1048
1049 return
1050}
1051
Colin Cross93e85952017-08-15 13:34:18 -07001052// HasExt returns true of any of the paths have extension ext, otherwise false
1053func (p Paths) HasExt(ext string) bool {
1054 for _, path := range p {
1055 if path.Ext() == ext {
1056 return true
1057 }
1058 }
1059
1060 return false
1061}
1062
1063// FilterByExt returns the subset of the paths that have extension ext
1064func (p Paths) FilterByExt(ext string) Paths {
1065 ret := make(Paths, 0, len(p))
1066 for _, path := range p {
1067 if path.Ext() == ext {
1068 ret = append(ret, path)
1069 }
1070 }
1071 return ret
1072}
1073
1074// FilterOutByExt returns the subset of the paths that do not have extension ext
1075func (p Paths) FilterOutByExt(ext string) Paths {
1076 ret := make(Paths, 0, len(p))
1077 for _, path := range p {
1078 if path.Ext() != ext {
1079 ret = append(ret, path)
1080 }
1081 }
1082 return ret
1083}
1084
Colin Cross5e6cfbe2017-11-03 15:20:35 -07001085// DirectorySortedPaths is a slice of paths that are sorted such that all files in a directory
1086// (including subdirectories) are in a contiguous subslice of the list, and can be found in
1087// O(log(N)) time using a binary search on the directory prefix.
1088type DirectorySortedPaths Paths
1089
1090func PathsToDirectorySortedPaths(paths Paths) DirectorySortedPaths {
1091 ret := append(DirectorySortedPaths(nil), paths...)
1092 sort.Slice(ret, func(i, j int) bool {
1093 return ret[i].String() < ret[j].String()
1094 })
1095 return ret
1096}
1097
1098// PathsInDirectory returns a subslice of the DirectorySortedPaths as a Paths that contains all entries
1099// that are in the specified directory and its subdirectories.
1100func (p DirectorySortedPaths) PathsInDirectory(dir string) Paths {
1101 prefix := filepath.Clean(dir) + "/"
1102 start := sort.Search(len(p), func(i int) bool {
1103 return prefix < p[i].String()
1104 })
1105
1106 ret := p[start:]
1107
1108 end := sort.Search(len(ret), func(i int) bool {
1109 return !strings.HasPrefix(ret[i].String(), prefix)
1110 })
1111
1112 ret = ret[:end]
1113
1114 return Paths(ret)
1115}
1116
Alex Humesky29e3bbe2020-11-20 21:30:13 -05001117// WritablePaths is a slice of WritablePath, used for multiple outputs.
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001118type WritablePaths []WritablePath
1119
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001120// RelativeToTop creates a new WritablePaths containing the result of calling Path.RelativeToTop on
1121// each item in this slice.
1122func (p WritablePaths) RelativeToTop() WritablePaths {
1123 ensureTestOnly()
1124 if p == nil {
1125 return p
1126 }
1127 ret := make(WritablePaths, len(p))
1128 for i, path := range p {
1129 ret[i] = path.RelativeToTop().(WritablePath)
1130 }
1131 return ret
1132}
1133
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001134// Strings returns the string forms of the writable paths.
1135func (p WritablePaths) Strings() []string {
1136 if p == nil {
1137 return nil
1138 }
1139 ret := make([]string, len(p))
1140 for i, path := range p {
1141 ret[i] = path.String()
1142 }
1143 return ret
1144}
1145
Colin Cross3bc7ffa2017-11-22 16:19:37 -08001146// Paths returns the WritablePaths as a Paths
1147func (p WritablePaths) Paths() Paths {
1148 if p == nil {
1149 return nil
1150 }
1151 ret := make(Paths, len(p))
1152 for i, path := range p {
1153 ret[i] = path
1154 }
1155 return ret
1156}
1157
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001158type basePath struct {
Paul Duffin74abc5d2021-03-24 09:24:59 +00001159 path string
1160 rel string
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001161}
1162
Yu Liu467d7c52024-09-18 21:54:44 +00001163type basePathGob struct {
1164 Path string
1165 Rel string
1166}
Yu Liufa297642024-06-11 00:13:02 +00001167
Yu Liu467d7c52024-09-18 21:54:44 +00001168func (p *basePath) ToGob() *basePathGob {
1169 return &basePathGob{
1170 Path: p.path,
1171 Rel: p.rel,
1172 }
1173}
1174
1175func (p *basePath) FromGob(data *basePathGob) {
1176 p.path = data.Path
1177 p.rel = data.Rel
1178}
1179
1180func (p basePath) GobEncode() ([]byte, error) {
Yu Liu3cadf7d2024-10-24 18:47:06 +00001181 return gobtools.CustomGobEncode[basePathGob](&p)
Yu Liufa297642024-06-11 00:13:02 +00001182}
1183
1184func (p *basePath) GobDecode(data []byte) error {
Yu Liu3cadf7d2024-10-24 18:47:06 +00001185 return gobtools.CustomGobDecode[basePathGob](data, p)
Yu Liufa297642024-06-11 00:13:02 +00001186}
1187
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001188func (p basePath) Ext() string {
1189 return filepath.Ext(p.path)
1190}
1191
Colin Cross4f6fc9c2016-10-26 10:05:25 -07001192func (p basePath) Base() string {
1193 return filepath.Base(p.path)
1194}
1195
Colin Crossfaeb7aa2017-02-01 14:12:44 -08001196func (p basePath) Rel() string {
1197 if p.rel != "" {
1198 return p.rel
1199 }
1200 return p.path
1201}
1202
Colin Cross0875c522017-11-28 17:34:01 -08001203func (p basePath) String() string {
1204 return p.path
1205}
1206
Colin Cross0db55682017-12-05 15:36:55 -08001207func (p basePath) withRel(rel string) basePath {
1208 p.path = filepath.Join(p.path, rel)
1209 p.rel = rel
1210 return p
1211}
1212
Colin Cross7707b242024-07-26 12:02:36 -07001213func (p basePath) withoutRel() basePath {
1214 p.rel = filepath.Base(p.path)
1215 return p
1216}
1217
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001218// SourcePath is a Path representing a file path rooted from SrcDir
1219type SourcePath struct {
1220 basePath
1221}
1222
1223var _ Path = SourcePath{}
1224
Colin Cross0db55682017-12-05 15:36:55 -08001225func (p SourcePath) withRel(rel string) SourcePath {
1226 p.basePath = p.basePath.withRel(rel)
1227 return p
1228}
1229
Colin Crossbd73d0d2024-07-26 12:00:33 -07001230func (p SourcePath) RelativeToTop() Path {
1231 ensureTestOnly()
1232 return p
1233}
1234
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001235// safePathForSource is for paths that we expect are safe -- only for use by go
1236// code that is embedding ninja variables in paths
Colin Crossfe4bc362018-09-12 10:02:13 -07001237func safePathForSource(ctx PathContext, pathComponents ...string) (SourcePath, error) {
1238 p, err := validateSafePath(pathComponents...)
Cole Faust483d1f72023-01-09 14:35:27 -08001239 ret := SourcePath{basePath{p, ""}}
Colin Crossfe4bc362018-09-12 10:02:13 -07001240 if err != nil {
1241 return ret, err
1242 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001243
Colin Cross7b3dcc32019-01-24 13:14:39 -08001244 // absolute path already checked by validateSafePath
Inseob Kim5eb7ee92022-04-27 10:30:34 +09001245 // special-case api surface gen files for now
1246 if strings.HasPrefix(ret.String(), ctx.Config().soongOutDir) && !strings.Contains(ret.String(), ctx.Config().soongOutDir+"/.export") {
Mikhail Naganovab1f5182019-02-08 13:17:55 -08001247 return ret, fmt.Errorf("source path %q is in output", ret.String())
Colin Cross6e18ca42015-07-14 18:55:36 -07001248 }
1249
Colin Crossfe4bc362018-09-12 10:02:13 -07001250 return ret, err
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001251}
1252
Colin Cross192e97a2018-02-22 14:21:02 -08001253// pathForSource creates a SourcePath from pathComponents, but does not check that it exists.
1254func pathForSource(ctx PathContext, pathComponents ...string) (SourcePath, error) {
Colin Crossc48c1432018-02-23 07:09:01 +00001255 p, err := validatePath(pathComponents...)
Cole Faust483d1f72023-01-09 14:35:27 -08001256 ret := SourcePath{basePath{p, ""}}
Colin Cross94a32102018-02-22 14:21:02 -08001257 if err != nil {
Colin Cross192e97a2018-02-22 14:21:02 -08001258 return ret, err
Colin Cross94a32102018-02-22 14:21:02 -08001259 }
1260
Colin Cross7b3dcc32019-01-24 13:14:39 -08001261 // absolute path already checked by validatePath
Inseob Kim5eb7ee92022-04-27 10:30:34 +09001262 // special-case for now
1263 if strings.HasPrefix(ret.String(), ctx.Config().soongOutDir) && !strings.Contains(ret.String(), ctx.Config().soongOutDir+"/.export") {
Mikhail Naganovab1f5182019-02-08 13:17:55 -08001264 return ret, fmt.Errorf("source path %q is in output", ret.String())
Colin Crossc48c1432018-02-23 07:09:01 +00001265 }
1266
Colin Cross192e97a2018-02-22 14:21:02 -08001267 return ret, nil
1268}
1269
1270// existsWithDependencies returns true if the path exists, and adds appropriate dependencies to rerun if the
1271// path does not exist.
Colin Cross662d6142022-11-03 20:38:01 -07001272func existsWithDependencies(ctx PathGlobContext, path SourcePath) (exists bool, err error) {
Colin Cross192e97a2018-02-22 14:21:02 -08001273 var files []string
1274
Colin Cross662d6142022-11-03 20:38:01 -07001275 // Use glob to produce proper dependencies, even though we only want
1276 // a single file.
1277 files, err = ctx.GlobWithDeps(path.String(), nil)
Colin Cross192e97a2018-02-22 14:21:02 -08001278
1279 if err != nil {
1280 return false, fmt.Errorf("glob: %s", err.Error())
1281 }
1282
1283 return len(files) > 0, nil
1284}
1285
1286// PathForSource joins the provided path components and validates that the result
1287// neither escapes the source dir nor is in the out dir.
1288// On error, it will return a usable, but invalid SourcePath, and report a ModuleError.
1289func PathForSource(ctx PathContext, pathComponents ...string) SourcePath {
1290 path, err := pathForSource(ctx, pathComponents...)
1291 if err != nil {
1292 reportPathError(ctx, err)
1293 }
1294
Colin Crosse3924e12018-08-15 20:18:53 -07001295 if pathtools.IsGlob(path.String()) {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001296 ReportPathErrorf(ctx, "path may not contain a glob: %s", path.String())
Colin Crosse3924e12018-08-15 20:18:53 -07001297 }
1298
Liz Kammera830f3a2020-11-10 10:50:34 -08001299 if modCtx, ok := ctx.(ModuleMissingDepsPathContext); ok && ctx.Config().AllowMissingDependencies() {
Colin Cross662d6142022-11-03 20:38:01 -07001300 exists, err := existsWithDependencies(modCtx, path)
Colin Cross192e97a2018-02-22 14:21:02 -08001301 if err != nil {
1302 reportPathError(ctx, err)
1303 }
1304 if !exists {
1305 modCtx.AddMissingDependencies([]string{path.String()})
1306 }
Colin Cross988414c2020-01-11 01:11:46 +00001307 } else if exists, _, err := ctx.Config().fs.Exists(path.String()); err != nil {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001308 ReportPathErrorf(ctx, "%s: %s", path, err.Error())
Pedro Loureiro5d190cc2021-02-15 15:41:33 +00001309 } else if !exists && !ctx.Config().TestAllowNonExistentPaths {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001310 ReportPathErrorf(ctx, "source path %q does not exist", path)
Colin Cross192e97a2018-02-22 14:21:02 -08001311 }
1312 return path
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001313}
1314
Cole Faustbc65a3f2023-08-01 16:38:55 +00001315// PathForArbitraryOutput creates a path for the given components. Unlike PathForOutput,
1316// the path is relative to the root of the output folder, not the out/soong folder.
1317func PathForArbitraryOutput(ctx PathContext, pathComponents ...string) Path {
Colin Cross3b1c6842024-07-26 11:52:57 -07001318 path, err := validatePath(pathComponents...)
Cole Faustbc65a3f2023-08-01 16:38:55 +00001319 if err != nil {
1320 reportPathError(ctx, err)
1321 }
Colin Cross3b1c6842024-07-26 11:52:57 -07001322 fullPath := filepath.Join(ctx.Config().OutDir(), path)
1323 path = fullPath[len(fullPath)-len(path):]
1324 return OutputPath{basePath{path, ""}, ctx.Config().OutDir(), fullPath}
Cole Faustbc65a3f2023-08-01 16:38:55 +00001325}
1326
Spandan Dasc6c10fa2022-10-21 21:52:13 +00001327// MaybeExistentPathForSource joins the provided path components and validates that the result
1328// neither escapes the source dir nor is in the out dir.
1329// It does not validate whether the path exists.
1330func MaybeExistentPathForSource(ctx PathContext, pathComponents ...string) SourcePath {
1331 path, err := pathForSource(ctx, pathComponents...)
1332 if err != nil {
1333 reportPathError(ctx, err)
1334 }
1335
1336 if pathtools.IsGlob(path.String()) {
1337 ReportPathErrorf(ctx, "path may not contain a glob: %s", path.String())
1338 }
1339 return path
1340}
1341
Liz Kammer7aa52882021-02-11 09:16:14 -05001342// ExistentPathForSource returns an OptionalPath with the SourcePath, rooted from SrcDir, *not*
1343// rooted from the module's local source directory, if the path exists, or an empty OptionalPath if
1344// it doesn't exist. Dependencies are added so that the ninja file will be regenerated if the state
1345// of the path changes.
Colin Cross662d6142022-11-03 20:38:01 -07001346func ExistentPathForSource(ctx PathGlobContext, pathComponents ...string) OptionalPath {
Colin Cross192e97a2018-02-22 14:21:02 -08001347 path, err := pathForSource(ctx, pathComponents...)
Colin Cross1ccfcc32018-02-22 13:54:26 -08001348 if err != nil {
1349 reportPathError(ctx, err)
Martin Stjernholmc32dd1c2021-09-15 02:39:00 +01001350 // No need to put the error message into the returned path since it has been reported already.
Colin Cross1ccfcc32018-02-22 13:54:26 -08001351 return OptionalPath{}
1352 }
Colin Crossc48c1432018-02-23 07:09:01 +00001353
Colin Crosse3924e12018-08-15 20:18:53 -07001354 if pathtools.IsGlob(path.String()) {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001355 ReportPathErrorf(ctx, "path may not contain a glob: %s", path.String())
Colin Crosse3924e12018-08-15 20:18:53 -07001356 return OptionalPath{}
1357 }
1358
Colin Cross192e97a2018-02-22 14:21:02 -08001359 exists, err := existsWithDependencies(ctx, path)
Colin Crossc48c1432018-02-23 07:09:01 +00001360 if err != nil {
1361 reportPathError(ctx, err)
1362 return OptionalPath{}
1363 }
Colin Cross192e97a2018-02-22 14:21:02 -08001364 if !exists {
Martin Stjernholmc32dd1c2021-09-15 02:39:00 +01001365 return InvalidOptionalPath(path.String() + " does not exist")
Colin Crossc48c1432018-02-23 07:09:01 +00001366 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001367 return OptionalPathForPath(path)
1368}
1369
1370func (p SourcePath) String() string {
Cole Faust483d1f72023-01-09 14:35:27 -08001371 if p.path == "" {
1372 return "."
1373 }
1374 return p.path
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001375}
1376
Colin Cross7707b242024-07-26 12:02:36 -07001377func (p SourcePath) WithoutRel() Path {
1378 p.basePath = p.basePath.withoutRel()
1379 return p
1380}
1381
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001382// Join creates a new SourcePath with paths... joined with the current path. The
1383// provided paths... may not use '..' to escape from the current path.
1384func (p SourcePath) Join(ctx PathContext, paths ...string) SourcePath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001385 path, err := validatePath(paths...)
1386 if err != nil {
1387 reportPathError(ctx, err)
1388 }
Colin Cross0db55682017-12-05 15:36:55 -08001389 return p.withRel(path)
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001390}
1391
Colin Cross2fafa3e2019-03-05 12:39:51 -08001392// join is like Join but does less path validation.
1393func (p SourcePath) join(ctx PathContext, paths ...string) SourcePath {
1394 path, err := validateSafePath(paths...)
1395 if err != nil {
1396 reportPathError(ctx, err)
1397 }
1398 return p.withRel(path)
1399}
1400
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001401// OverlayPath returns the overlay for `path' if it exists. This assumes that the
1402// SourcePath is the path to a resource overlay directory.
Liz Kammera830f3a2020-11-10 10:50:34 -08001403func (p SourcePath) OverlayPath(ctx ModuleMissingDepsPathContext, path Path) OptionalPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001404 var relDir string
Colin Cross07e51612019-03-05 12:46:40 -08001405 if srcPath, ok := path.(SourcePath); ok {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001406 relDir = srcPath.path
1407 } else {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001408 ReportPathErrorf(ctx, "Cannot find relative path for %s(%s)", reflect.TypeOf(path).Name(), path)
Martin Stjernholmc32dd1c2021-09-15 02:39:00 +01001409 // No need to put the error message into the returned path since it has been reported already.
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001410 return OptionalPath{}
1411 }
Cole Faust483d1f72023-01-09 14:35:27 -08001412 dir := filepath.Join(p.path, relDir)
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001413 // Use Glob so that we are run again if the directory is added.
Colin Cross7f19f372016-11-01 11:10:25 -07001414 if pathtools.IsGlob(dir) {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001415 ReportPathErrorf(ctx, "Path may not contain a glob: %s", dir)
Dan Willemsen7b310ee2015-12-18 15:11:17 -08001416 }
Colin Cross461b4452018-02-23 09:22:42 -08001417 paths, err := ctx.GlobWithDeps(dir, nil)
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001418 if err != nil {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001419 ReportPathErrorf(ctx, "glob: %s", err.Error())
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001420 return OptionalPath{}
1421 }
1422 if len(paths) == 0 {
Martin Stjernholmc32dd1c2021-09-15 02:39:00 +01001423 return InvalidOptionalPath(dir + " does not exist")
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001424 }
Cole Faust483d1f72023-01-09 14:35:27 -08001425 return OptionalPathForPath(PathForSource(ctx, paths[0]))
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001426}
1427
Colin Cross70dda7e2019-10-01 22:05:35 -07001428// OutputPath is a Path representing an intermediates file path rooted from the build directory
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001429type OutputPath struct {
1430 basePath
Paul Duffind65c58b2021-03-24 09:22:07 +00001431
Colin Cross3b1c6842024-07-26 11:52:57 -07001432 // The base out directory for this path, either Config.SoongOutDir() or Config.OutDir()
1433 outDir string
Paul Duffind65c58b2021-03-24 09:22:07 +00001434
Colin Crossd63c9a72020-01-29 16:52:50 -08001435 fullPath string
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001436}
1437
Yu Liu467d7c52024-09-18 21:54:44 +00001438type outputPathGob struct {
Yu Liu5246a7e2024-10-09 20:04:52 +00001439 BasePath basePath
Yu Liu467d7c52024-09-18 21:54:44 +00001440 OutDir string
1441 FullPath string
1442}
Yu Liufa297642024-06-11 00:13:02 +00001443
Yu Liu467d7c52024-09-18 21:54:44 +00001444func (p *OutputPath) ToGob() *outputPathGob {
1445 return &outputPathGob{
Yu Liu5246a7e2024-10-09 20:04:52 +00001446 BasePath: p.basePath,
Yu Liu467d7c52024-09-18 21:54:44 +00001447 OutDir: p.outDir,
1448 FullPath: p.fullPath,
1449 }
1450}
1451
1452func (p *OutputPath) FromGob(data *outputPathGob) {
Yu Liu5246a7e2024-10-09 20:04:52 +00001453 p.basePath = data.BasePath
Yu Liu467d7c52024-09-18 21:54:44 +00001454 p.outDir = data.OutDir
1455 p.fullPath = data.FullPath
1456}
1457
1458func (p OutputPath) GobEncode() ([]byte, error) {
Yu Liu3cadf7d2024-10-24 18:47:06 +00001459 return gobtools.CustomGobEncode[outputPathGob](&p)
Yu Liufa297642024-06-11 00:13:02 +00001460}
1461
1462func (p *OutputPath) GobDecode(data []byte) error {
Yu Liu3cadf7d2024-10-24 18:47:06 +00001463 return gobtools.CustomGobDecode[outputPathGob](data, p)
Yu Liufa297642024-06-11 00:13:02 +00001464}
1465
Colin Cross702e0f82017-10-18 17:27:54 -07001466func (p OutputPath) withRel(rel string) OutputPath {
Colin Cross0db55682017-12-05 15:36:55 -08001467 p.basePath = p.basePath.withRel(rel)
Colin Crossd63c9a72020-01-29 16:52:50 -08001468 p.fullPath = filepath.Join(p.fullPath, rel)
Colin Cross702e0f82017-10-18 17:27:54 -07001469 return p
1470}
1471
Colin Cross7707b242024-07-26 12:02:36 -07001472func (p OutputPath) WithoutRel() Path {
1473 p.basePath = p.basePath.withoutRel()
Colin Cross3063b782018-08-15 11:19:12 -07001474 return p
1475}
1476
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02001477func (p OutputPath) getSoongOutDir() string {
Colin Cross3b1c6842024-07-26 11:52:57 -07001478 return p.outDir
Paul Duffin9b478b02019-12-10 13:41:51 +00001479}
1480
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001481func (p OutputPath) RelativeToTop() Path {
1482 return p.outputPathRelativeToTop()
1483}
1484
1485func (p OutputPath) outputPathRelativeToTop() OutputPath {
Colin Cross3b1c6842024-07-26 11:52:57 -07001486 p.fullPath = StringPathRelativeToTop(p.outDir, p.fullPath)
1487 if strings.HasSuffix(p.outDir, testOutSoongSubDir) {
1488 p.outDir = TestOutSoongDir
1489 } else {
1490 // Handle the PathForArbitraryOutput case
1491 p.outDir = testOutDir
1492 }
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001493 return p
1494}
1495
Paul Duffin0267d492021-02-02 10:05:52 +00001496func (p OutputPath) objPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleObjPath {
1497 return PathForModuleObj(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
1498}
1499
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001500var _ Path = OutputPath{}
Paul Duffin9b478b02019-12-10 13:41:51 +00001501var _ WritablePath = OutputPath{}
Paul Duffin0267d492021-02-02 10:05:52 +00001502var _ objPathProvider = OutputPath{}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001503
Chris Parsons8f232a22020-06-23 17:37:05 -04001504// toolDepPath is a Path representing a dependency of the build tool.
1505type toolDepPath struct {
1506 basePath
1507}
1508
Colin Cross7707b242024-07-26 12:02:36 -07001509func (t toolDepPath) WithoutRel() Path {
1510 t.basePath = t.basePath.withoutRel()
1511 return t
1512}
1513
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001514func (t toolDepPath) RelativeToTop() Path {
1515 ensureTestOnly()
1516 return t
1517}
1518
Chris Parsons8f232a22020-06-23 17:37:05 -04001519var _ Path = toolDepPath{}
1520
1521// pathForBuildToolDep returns a toolDepPath representing the given path string.
1522// There is no validation for the path, as it is "trusted": It may fail
1523// normal validation checks. For example, it may be an absolute path.
1524// Only use this function to construct paths for dependencies of the build
1525// tool invocation.
1526func pathForBuildToolDep(ctx PathContext, path string) toolDepPath {
Paul Duffin74abc5d2021-03-24 09:24:59 +00001527 return toolDepPath{basePath{path, ""}}
Chris Parsons8f232a22020-06-23 17:37:05 -04001528}
1529
Jeff Gaston734e3802017-04-10 15:47:24 -07001530// PathForOutput joins the provided paths and returns an OutputPath that is
1531// validated to not escape the build dir.
1532// On error, it will return a usable, but invalid OutputPath, and report a ModuleError.
1533func PathForOutput(ctx PathContext, pathComponents ...string) OutputPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001534 path, err := validatePath(pathComponents...)
1535 if err != nil {
1536 reportPathError(ctx, err)
1537 }
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02001538 fullPath := filepath.Join(ctx.Config().soongOutDir, path)
Colin Crossd63c9a72020-01-29 16:52:50 -08001539 path = fullPath[len(fullPath)-len(path):]
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02001540 return OutputPath{basePath{path, ""}, ctx.Config().soongOutDir, fullPath}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001541}
1542
Colin Cross3b1c6842024-07-26 11:52:57 -07001543// PathsForOutput returns Paths rooted from outDir
Colin Cross40e33732019-02-15 11:08:35 -08001544func PathsForOutput(ctx PathContext, paths []string) WritablePaths {
1545 ret := make(WritablePaths, len(paths))
1546 for i, path := range paths {
1547 ret[i] = PathForOutput(ctx, path)
1548 }
1549 return ret
1550}
1551
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001552func (p OutputPath) writablePath() {}
1553
1554func (p OutputPath) String() string {
Colin Crossd63c9a72020-01-29 16:52:50 -08001555 return p.fullPath
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001556}
1557
1558// Join creates a new OutputPath with paths... joined with the current path. The
1559// provided paths... may not use '..' to escape from the current path.
1560func (p OutputPath) Join(ctx PathContext, paths ...string) OutputPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001561 path, err := validatePath(paths...)
1562 if err != nil {
1563 reportPathError(ctx, err)
1564 }
Colin Cross0db55682017-12-05 15:36:55 -08001565 return p.withRel(path)
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001566}
1567
Colin Cross8854a5a2019-02-11 14:14:16 -08001568// ReplaceExtension creates a new OutputPath with the extension replaced with ext.
1569func (p OutputPath) ReplaceExtension(ctx PathContext, ext string) OutputPath {
1570 if strings.Contains(ext, "/") {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001571 ReportPathErrorf(ctx, "extension %q cannot contain /", ext)
Colin Cross8854a5a2019-02-11 14:14:16 -08001572 }
1573 ret := PathForOutput(ctx, pathtools.ReplaceExtension(p.path, ext))
Colin Cross2cdd5df2019-02-25 10:25:24 -08001574 ret.rel = pathtools.ReplaceExtension(p.rel, ext)
Colin Cross8854a5a2019-02-11 14:14:16 -08001575 return ret
1576}
1577
Colin Cross40e33732019-02-15 11:08:35 -08001578// InSameDir creates a new OutputPath from the directory of the current OutputPath joined with the elements in paths.
1579func (p OutputPath) InSameDir(ctx PathContext, paths ...string) OutputPath {
1580 path, err := validatePath(paths...)
1581 if err != nil {
1582 reportPathError(ctx, err)
1583 }
1584
1585 ret := PathForOutput(ctx, filepath.Dir(p.path), path)
Colin Cross2cdd5df2019-02-25 10:25:24 -08001586 ret.rel = filepath.Join(filepath.Dir(p.rel), path)
Colin Cross40e33732019-02-15 11:08:35 -08001587 return ret
1588}
1589
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001590// PathForIntermediates returns an OutputPath representing the top-level
1591// intermediates directory.
1592func PathForIntermediates(ctx PathContext, paths ...string) OutputPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001593 path, err := validatePath(paths...)
1594 if err != nil {
1595 reportPathError(ctx, err)
1596 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001597 return PathForOutput(ctx, ".intermediates", path)
1598}
1599
Colin Cross07e51612019-03-05 12:46:40 -08001600var _ genPathProvider = SourcePath{}
1601var _ objPathProvider = SourcePath{}
1602var _ resPathProvider = SourcePath{}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001603
Colin Cross07e51612019-03-05 12:46:40 -08001604// PathForModuleSrc returns a Path representing the paths... under the
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001605// module's local source directory.
Liz Kammera830f3a2020-11-10 10:50:34 -08001606func PathForModuleSrc(ctx ModuleMissingDepsPathContext, pathComponents ...string) Path {
Paul Duffin407501b2021-07-09 16:56:35 +01001607 // Just join the components textually just to make sure that it does not corrupt a fully qualified
1608 // module reference, e.g. if the pathComponents is "://other:foo" then using filepath.Join() or
1609 // validatePath() will corrupt it, e.g. replace "//" with "/". If the path is not a module
1610 // reference then it will be validated by expandOneSrcPath anyway when it calls expandOneSrcPath.
1611 p := strings.Join(pathComponents, string(filepath.Separator))
Liz Kammer619be462022-01-28 15:13:39 -05001612 paths, err := expandOneSrcPath(sourcePathInput{context: ctx, path: p, includeDirs: true})
Colin Cross8a497952019-03-05 22:25:09 -08001613 if err != nil {
1614 if depErr, ok := err.(missingDependencyError); ok {
1615 if ctx.Config().AllowMissingDependencies() {
1616 ctx.AddMissingDependencies(depErr.missingDeps)
1617 } else {
1618 ctx.ModuleErrorf(`%s, is the property annotated with android:"path"?`, depErr.Error())
1619 }
1620 } else {
1621 reportPathError(ctx, err)
1622 }
1623 return nil
1624 } else if len(paths) == 0 {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001625 ReportPathErrorf(ctx, "%q produced no files, expected exactly one", p)
Colin Cross8a497952019-03-05 22:25:09 -08001626 return nil
1627 } else if len(paths) > 1 {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001628 ReportPathErrorf(ctx, "%q produced %d files, expected exactly one", p, len(paths))
Colin Cross8a497952019-03-05 22:25:09 -08001629 }
1630 return paths[0]
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001631}
1632
Liz Kammera830f3a2020-11-10 10:50:34 -08001633func pathForModuleSrc(ctx EarlyModulePathContext, paths ...string) SourcePath {
Colin Cross07e51612019-03-05 12:46:40 -08001634 p, err := validatePath(paths...)
1635 if err != nil {
1636 reportPathError(ctx, err)
1637 }
1638
1639 path, err := pathForSource(ctx, ctx.ModuleDir(), p)
1640 if err != nil {
1641 reportPathError(ctx, err)
1642 }
1643
1644 path.basePath.rel = p
1645
1646 return path
1647}
1648
Colin Cross2fafa3e2019-03-05 12:39:51 -08001649// PathsWithModuleSrcSubDir takes a list of Paths and returns a new list of Paths where Rel() on each path
1650// will return the path relative to subDir in the module's source directory. If any input paths are not located
1651// inside subDir then a path error will be reported.
Liz Kammera830f3a2020-11-10 10:50:34 -08001652func PathsWithModuleSrcSubDir(ctx EarlyModulePathContext, paths Paths, subDir string) Paths {
Colin Cross2fafa3e2019-03-05 12:39:51 -08001653 paths = append(Paths(nil), paths...)
Colin Cross07e51612019-03-05 12:46:40 -08001654 subDirFullPath := pathForModuleSrc(ctx, subDir)
Colin Cross2fafa3e2019-03-05 12:39:51 -08001655 for i, path := range paths {
1656 rel := Rel(ctx, subDirFullPath.String(), path.String())
1657 paths[i] = subDirFullPath.join(ctx, rel)
1658 }
1659 return paths
1660}
1661
1662// PathWithModuleSrcSubDir takes a Path and returns a Path where Rel() will return the path relative to subDir in the
1663// 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 -08001664func PathWithModuleSrcSubDir(ctx EarlyModulePathContext, path Path, subDir string) Path {
Colin Cross07e51612019-03-05 12:46:40 -08001665 subDirFullPath := pathForModuleSrc(ctx, subDir)
Colin Cross2fafa3e2019-03-05 12:39:51 -08001666 rel := Rel(ctx, subDirFullPath.String(), path.String())
1667 return subDirFullPath.Join(ctx, rel)
1668}
1669
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001670// OptionalPathForModuleSrc returns an OptionalPath. The OptionalPath contains a
1671// valid path if p is non-nil.
Liz Kammera830f3a2020-11-10 10:50:34 -08001672func OptionalPathForModuleSrc(ctx ModuleMissingDepsPathContext, p *string) OptionalPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001673 if p == nil {
1674 return OptionalPath{}
1675 }
1676 return OptionalPathForPath(PathForModuleSrc(ctx, *p))
1677}
1678
Liz Kammera830f3a2020-11-10 10:50:34 -08001679func (p SourcePath) genPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleGenPath {
Colin Cross7fc17db2017-02-01 14:07:55 -08001680 return PathForModuleGen(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001681}
1682
yangbill6d032dd2024-04-18 03:05:49 +00001683func (p SourcePath) genPathWithExtAndTrimExt(ctx ModuleOutPathContext, subdir, ext string, trimExt string) ModuleGenPath {
1684 // If Trim_extension being set, force append Output_extension without replace original extension.
1685 if trimExt != "" {
1686 if ext != "" {
1687 return PathForModuleGen(ctx, subdir, strings.TrimSuffix(p.path, trimExt)+"."+ext)
1688 }
1689 return PathForModuleGen(ctx, subdir, strings.TrimSuffix(p.path, trimExt))
1690 }
1691 return PathForModuleGen(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
1692}
1693
Liz Kammera830f3a2020-11-10 10:50:34 -08001694func (p SourcePath) objPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleObjPath {
Colin Cross7fc17db2017-02-01 14:07:55 -08001695 return PathForModuleObj(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001696}
1697
Liz Kammera830f3a2020-11-10 10:50:34 -08001698func (p SourcePath) resPathWithName(ctx ModuleOutPathContext, name string) ModuleResPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001699 // TODO: Use full directory if the new ctx is not the current ctx?
1700 return PathForModuleRes(ctx, p.path, name)
1701}
1702
1703// ModuleOutPath is a Path representing a module's output directory.
1704type ModuleOutPath struct {
1705 OutputPath
1706}
1707
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001708func (p ModuleOutPath) RelativeToTop() Path {
1709 p.OutputPath = p.outputPathRelativeToTop()
1710 return p
1711}
1712
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001713var _ Path = ModuleOutPath{}
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001714var _ WritablePath = ModuleOutPath{}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001715
Liz Kammera830f3a2020-11-10 10:50:34 -08001716func (p ModuleOutPath) objPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleObjPath {
Pete Bentleyfcf55bf2019-08-16 20:14:32 +01001717 return PathForModuleObj(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
1718}
1719
Liz Kammera830f3a2020-11-10 10:50:34 -08001720// ModuleOutPathContext Subset of ModuleContext functions necessary for output path methods.
1721type ModuleOutPathContext interface {
1722 PathContext
1723
1724 ModuleName() string
1725 ModuleDir() string
1726 ModuleSubDir() string
1727}
1728
1729func pathForModuleOut(ctx ModuleOutPathContext) OutputPath {
Inseob Kimb7e9f5f2024-06-25 17:39:52 +09001730 return PathForOutput(ctx, ".intermediates", ctx.ModuleDir(), ctx.ModuleName(), ctx.ModuleSubDir())
Colin Cross702e0f82017-10-18 17:27:54 -07001731}
1732
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001733// PathForModuleOut returns a Path representing the paths... under the module's
1734// output directory.
Liz Kammera830f3a2020-11-10 10:50:34 -08001735func PathForModuleOut(ctx ModuleOutPathContext, paths ...string) ModuleOutPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001736 p, err := validatePath(paths...)
1737 if err != nil {
1738 reportPathError(ctx, err)
1739 }
Colin Cross702e0f82017-10-18 17:27:54 -07001740 return ModuleOutPath{
Liz Kammera830f3a2020-11-10 10:50:34 -08001741 OutputPath: pathForModuleOut(ctx).withRel(p),
Colin Cross702e0f82017-10-18 17:27:54 -07001742 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001743}
1744
1745// ModuleGenPath is a Path representing the 'gen' directory in a module's output
1746// directory. Mainly used for generated sources.
1747type ModuleGenPath struct {
1748 ModuleOutPath
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001749}
1750
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001751func (p ModuleGenPath) RelativeToTop() Path {
1752 p.OutputPath = p.outputPathRelativeToTop()
1753 return p
1754}
1755
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001756var _ Path = ModuleGenPath{}
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001757var _ WritablePath = ModuleGenPath{}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001758var _ genPathProvider = ModuleGenPath{}
1759var _ objPathProvider = ModuleGenPath{}
1760
1761// PathForModuleGen returns a Path representing the paths... under the module's
1762// `gen' directory.
Liz Kammera830f3a2020-11-10 10:50:34 -08001763func PathForModuleGen(ctx ModuleOutPathContext, paths ...string) ModuleGenPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001764 p, err := validatePath(paths...)
1765 if err != nil {
1766 reportPathError(ctx, err)
1767 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001768 return ModuleGenPath{
Colin Cross702e0f82017-10-18 17:27:54 -07001769 ModuleOutPath: ModuleOutPath{
Liz Kammera830f3a2020-11-10 10:50:34 -08001770 OutputPath: pathForModuleOut(ctx).withRel("gen").withRel(p),
Colin Cross702e0f82017-10-18 17:27:54 -07001771 },
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001772 }
1773}
1774
Liz Kammera830f3a2020-11-10 10:50:34 -08001775func (p ModuleGenPath) genPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleGenPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001776 // TODO: make a different path for local vs remote generated files?
Dan Willemsen21ec4902016-11-02 20:43:13 -07001777 return PathForModuleGen(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001778}
1779
yangbill6d032dd2024-04-18 03:05:49 +00001780func (p ModuleGenPath) genPathWithExtAndTrimExt(ctx ModuleOutPathContext, subdir, ext string, trimExt string) ModuleGenPath {
1781 // If Trim_extension being set, force append Output_extension without replace original extension.
1782 if trimExt != "" {
1783 if ext != "" {
1784 return PathForModuleGen(ctx, subdir, strings.TrimSuffix(p.path, trimExt)+"."+ext)
1785 }
1786 return PathForModuleGen(ctx, subdir, strings.TrimSuffix(p.path, trimExt))
1787 }
1788 return PathForModuleGen(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
1789}
1790
Liz Kammera830f3a2020-11-10 10:50:34 -08001791func (p ModuleGenPath) objPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleObjPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001792 return PathForModuleObj(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
1793}
1794
1795// ModuleObjPath is a Path representing the 'obj' directory in a module's output
1796// directory. Used for compiled objects.
1797type ModuleObjPath struct {
1798 ModuleOutPath
1799}
1800
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001801func (p ModuleObjPath) RelativeToTop() Path {
1802 p.OutputPath = p.outputPathRelativeToTop()
1803 return p
1804}
1805
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001806var _ Path = ModuleObjPath{}
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001807var _ WritablePath = ModuleObjPath{}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001808
1809// PathForModuleObj returns a Path representing the paths... under the module's
1810// 'obj' directory.
Liz Kammera830f3a2020-11-10 10:50:34 -08001811func PathForModuleObj(ctx ModuleOutPathContext, pathComponents ...string) ModuleObjPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001812 p, err := validatePath(pathComponents...)
1813 if err != nil {
1814 reportPathError(ctx, err)
1815 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001816 return ModuleObjPath{PathForModuleOut(ctx, "obj", p)}
1817}
1818
1819// ModuleResPath is a a Path representing the 'res' directory in a module's
1820// output directory.
1821type ModuleResPath struct {
1822 ModuleOutPath
1823}
1824
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001825func (p ModuleResPath) RelativeToTop() Path {
1826 p.OutputPath = p.outputPathRelativeToTop()
1827 return p
1828}
1829
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001830var _ Path = ModuleResPath{}
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001831var _ WritablePath = ModuleResPath{}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001832
1833// PathForModuleRes returns a Path representing the paths... under the module's
1834// 'res' directory.
Liz Kammera830f3a2020-11-10 10:50:34 -08001835func PathForModuleRes(ctx ModuleOutPathContext, pathComponents ...string) ModuleResPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001836 p, err := validatePath(pathComponents...)
1837 if err != nil {
1838 reportPathError(ctx, err)
1839 }
1840
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001841 return ModuleResPath{PathForModuleOut(ctx, "res", p)}
1842}
1843
Colin Cross70dda7e2019-10-01 22:05:35 -07001844// InstallPath is a Path representing a installed file path rooted from the build directory
1845type InstallPath struct {
1846 basePath
Colin Crossff6c33d2019-10-02 16:01:35 -07001847
Lukacs T. Berkib078ade2021-08-31 10:42:08 +02001848 // The soong build directory, i.e. Config.SoongOutDir()
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02001849 soongOutDir string
Paul Duffind65c58b2021-03-24 09:22:07 +00001850
Jiyong Park957bcd92020-10-20 18:23:33 +09001851 // partitionDir is the part of the InstallPath that is automatically determined according to the context.
1852 // For example, it is host/<os>-<arch> for host modules, and target/product/<device>/<partition> for device modules.
1853 partitionDir string
1854
Colin Crossb1692a32021-10-25 15:39:01 -07001855 partition string
1856
Jiyong Park957bcd92020-10-20 18:23:33 +09001857 // makePath indicates whether this path is for Soong (false) or Make (true).
1858 makePath bool
Colin Crossc0e42d52024-02-01 16:42:36 -08001859
1860 fullPath string
Colin Cross70dda7e2019-10-01 22:05:35 -07001861}
1862
Yu Liu467d7c52024-09-18 21:54:44 +00001863type installPathGob struct {
Yu Liu5246a7e2024-10-09 20:04:52 +00001864 BasePath basePath
Yu Liu467d7c52024-09-18 21:54:44 +00001865 SoongOutDir string
1866 PartitionDir string
1867 Partition string
1868 MakePath bool
1869 FullPath string
1870}
Yu Liu26a716d2024-08-30 23:40:32 +00001871
Yu Liu467d7c52024-09-18 21:54:44 +00001872func (p *InstallPath) ToGob() *installPathGob {
1873 return &installPathGob{
Yu Liu5246a7e2024-10-09 20:04:52 +00001874 BasePath: p.basePath,
Yu Liu467d7c52024-09-18 21:54:44 +00001875 SoongOutDir: p.soongOutDir,
1876 PartitionDir: p.partitionDir,
1877 Partition: p.partition,
1878 MakePath: p.makePath,
1879 FullPath: p.fullPath,
1880 }
1881}
1882
1883func (p *InstallPath) FromGob(data *installPathGob) {
Yu Liu5246a7e2024-10-09 20:04:52 +00001884 p.basePath = data.BasePath
Yu Liu467d7c52024-09-18 21:54:44 +00001885 p.soongOutDir = data.SoongOutDir
1886 p.partitionDir = data.PartitionDir
1887 p.partition = data.Partition
1888 p.makePath = data.MakePath
1889 p.fullPath = data.FullPath
1890}
1891
1892func (p InstallPath) GobEncode() ([]byte, error) {
Yu Liu3cadf7d2024-10-24 18:47:06 +00001893 return gobtools.CustomGobEncode[installPathGob](&p)
Yu Liu26a716d2024-08-30 23:40:32 +00001894}
1895
1896func (p *InstallPath) GobDecode(data []byte) error {
Yu Liu3cadf7d2024-10-24 18:47:06 +00001897 return gobtools.CustomGobDecode[installPathGob](data, p)
Yu Liu26a716d2024-08-30 23:40:32 +00001898}
1899
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001900// Will panic if called from outside a test environment.
1901func ensureTestOnly() {
Martin Stjernholm32312eb2021-03-27 18:54:49 +00001902 if PrefixInList(os.Args, "-test.") {
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001903 return
1904 }
Martin Stjernholm32312eb2021-03-27 18:54:49 +00001905 panic(fmt.Errorf("Not in test. Command line:\n %s", strings.Join(os.Args, "\n ")))
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001906}
1907
1908func (p InstallPath) RelativeToTop() Path {
1909 ensureTestOnly()
Colin Crossc0e42d52024-02-01 16:42:36 -08001910 if p.makePath {
Colin Cross3b1c6842024-07-26 11:52:57 -07001911 p.soongOutDir = testOutDir
Colin Crossc0e42d52024-02-01 16:42:36 -08001912 } else {
Colin Cross3b1c6842024-07-26 11:52:57 -07001913 p.soongOutDir = TestOutSoongDir
Colin Crossc0e42d52024-02-01 16:42:36 -08001914 }
1915 p.fullPath = filepath.Join(p.soongOutDir, p.path)
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001916 return p
1917}
1918
Colin Cross7707b242024-07-26 12:02:36 -07001919func (p InstallPath) WithoutRel() Path {
1920 p.basePath = p.basePath.withoutRel()
1921 return p
1922}
1923
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02001924func (p InstallPath) getSoongOutDir() string {
1925 return p.soongOutDir
Paul Duffin9b478b02019-12-10 13:41:51 +00001926}
1927
Hans MÃ¥nssond3f2bd72020-11-27 12:37:28 +01001928func (p InstallPath) ReplaceExtension(ctx PathContext, ext string) OutputPath {
1929 panic("Not implemented")
1930}
1931
Paul Duffin9b478b02019-12-10 13:41:51 +00001932var _ Path = InstallPath{}
1933var _ WritablePath = InstallPath{}
1934
Colin Cross70dda7e2019-10-01 22:05:35 -07001935func (p InstallPath) writablePath() {}
1936
1937func (p InstallPath) String() string {
Colin Crossc0e42d52024-02-01 16:42:36 -08001938 return p.fullPath
Jiyong Park957bcd92020-10-20 18:23:33 +09001939}
1940
1941// PartitionDir returns the path to the partition where the install path is rooted at. It is
1942// out/soong/target/product/<device>/<partition> for device modules, and out/soong/host/<os>-<arch> for host modules.
1943// The ./soong is dropped if the install path is for Make.
1944func (p InstallPath) PartitionDir() string {
1945 if p.makePath {
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02001946 return filepath.Join(p.soongOutDir, "../", p.partitionDir)
Jiyong Park957bcd92020-10-20 18:23:33 +09001947 } else {
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02001948 return filepath.Join(p.soongOutDir, p.partitionDir)
Jiyong Park957bcd92020-10-20 18:23:33 +09001949 }
Colin Cross70dda7e2019-10-01 22:05:35 -07001950}
1951
Jihoon Kangf78a8902022-09-01 22:47:07 +00001952func (p InstallPath) Partition() string {
1953 return p.partition
1954}
1955
Colin Cross70dda7e2019-10-01 22:05:35 -07001956// Join creates a new InstallPath with paths... joined with the current path. The
1957// provided paths... may not use '..' to escape from the current path.
1958func (p InstallPath) Join(ctx PathContext, paths ...string) InstallPath {
1959 path, err := validatePath(paths...)
1960 if err != nil {
1961 reportPathError(ctx, err)
1962 }
1963 return p.withRel(path)
1964}
1965
1966func (p InstallPath) withRel(rel string) InstallPath {
1967 p.basePath = p.basePath.withRel(rel)
Colin Crossc0e42d52024-02-01 16:42:36 -08001968 p.fullPath = filepath.Join(p.fullPath, rel)
Colin Cross70dda7e2019-10-01 22:05:35 -07001969 return p
1970}
1971
Colin Crossc68db4b2021-11-11 18:59:15 -08001972// Deprecated: ToMakePath is a noop, PathForModuleInstall always returns Make paths when building
1973// embedded in Make.
Colin Crossff6c33d2019-10-02 16:01:35 -07001974func (p InstallPath) ToMakePath() InstallPath {
Jiyong Park957bcd92020-10-20 18:23:33 +09001975 p.makePath = true
Colin Crossff6c33d2019-10-02 16:01:35 -07001976 return p
Colin Cross70dda7e2019-10-01 22:05:35 -07001977}
1978
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001979// PathForModuleInstall returns a Path representing the install path for the
1980// module appended with paths...
Colin Cross70dda7e2019-10-01 22:05:35 -07001981func PathForModuleInstall(ctx ModuleInstallPathContext, pathComponents ...string) InstallPath {
Spandan Das5d1b9292021-06-03 19:36:41 +00001982 os, arch := osAndArch(ctx)
Cole Faust11edf552023-10-13 11:32:14 -07001983 partition := modulePartition(ctx, os.Class == Device)
Cole Faust3b703f32023-10-16 13:30:51 -07001984 return pathForInstall(ctx, os, arch, partition, pathComponents...)
Spandan Das5d1b9292021-06-03 19:36:41 +00001985}
1986
Colin Cross1d0eb7a2021-11-03 14:08:20 -07001987// PathForHostDexInstall returns an InstallPath representing the install path for the
1988// module appended with paths...
1989func PathForHostDexInstall(ctx ModuleInstallPathContext, pathComponents ...string) InstallPath {
Cole Faust3b703f32023-10-16 13:30:51 -07001990 return pathForInstall(ctx, ctx.Config().BuildOS, ctx.Config().BuildArch, "", pathComponents...)
Colin Cross1d0eb7a2021-11-03 14:08:20 -07001991}
1992
Spandan Das5d1b9292021-06-03 19:36:41 +00001993// PathForModuleInPartitionInstall is similar to PathForModuleInstall but partition is provided by the caller
1994func PathForModuleInPartitionInstall(ctx ModuleInstallPathContext, partition string, pathComponents ...string) InstallPath {
1995 os, arch := osAndArch(ctx)
Cole Faust3b703f32023-10-16 13:30:51 -07001996 return pathForInstall(ctx, os, arch, partition, pathComponents...)
Spandan Das5d1b9292021-06-03 19:36:41 +00001997}
1998
1999func osAndArch(ctx ModuleInstallPathContext) (OsType, ArchType) {
Colin Cross6e359402020-02-10 15:29:54 -08002000 os := ctx.Os()
Jiyong Park87788b52020-09-01 12:37:45 +09002001 arch := ctx.Arch().ArchType
2002 forceOS, forceArch := ctx.InstallForceOS()
2003 if forceOS != nil {
Colin Cross6e359402020-02-10 15:29:54 -08002004 os = *forceOS
2005 }
Jiyong Park87788b52020-09-01 12:37:45 +09002006 if forceArch != nil {
2007 arch = *forceArch
2008 }
Spandan Das5d1b9292021-06-03 19:36:41 +00002009 return os, arch
2010}
Colin Cross609c49a2020-02-13 13:20:11 -08002011
Colin Crossc0e42d52024-02-01 16:42:36 -08002012func pathForPartitionInstallDir(ctx PathContext, partition, partitionPath string, makePath bool) InstallPath {
2013 fullPath := ctx.Config().SoongOutDir()
2014 if makePath {
2015 // Make path starts with out/ instead of out/soong.
2016 fullPath = filepath.Join(fullPath, "../", partitionPath)
2017 } else {
2018 fullPath = filepath.Join(fullPath, partitionPath)
2019 }
2020
2021 return InstallPath{
2022 basePath: basePath{partitionPath, ""},
2023 soongOutDir: ctx.Config().soongOutDir,
2024 partitionDir: partitionPath,
2025 partition: partition,
2026 makePath: makePath,
2027 fullPath: fullPath,
2028 }
2029}
2030
Cole Faust3b703f32023-10-16 13:30:51 -07002031func pathForInstall(ctx PathContext, os OsType, arch ArchType, partition string,
Colin Cross609c49a2020-02-13 13:20:11 -08002032 pathComponents ...string) InstallPath {
2033
Jiyong Park97859152023-02-14 17:05:48 +09002034 var partitionPaths []string
Colin Cross609c49a2020-02-13 13:20:11 -08002035
Colin Cross6e359402020-02-10 15:29:54 -08002036 if os.Class == Device {
Jiyong Park97859152023-02-14 17:05:48 +09002037 partitionPaths = []string{"target", "product", ctx.Config().DeviceName(), partition}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07002038 } else {
Jiyong Park87788b52020-09-01 12:37:45 +09002039 osName := os.String()
Colin Crossa9b2aac2022-06-15 17:25:51 -07002040 if os == Linux {
Jiyong Park87788b52020-09-01 12:37:45 +09002041 // instead of linux_glibc
2042 osName = "linux"
Dan Willemsen866b5632017-09-22 12:28:24 -07002043 }
Colin Crossa9b2aac2022-06-15 17:25:51 -07002044 if os == LinuxMusl && ctx.Config().UseHostMusl() {
2045 // When using musl instead of glibc, use "linux" instead of "linux_musl". When cross
2046 // compiling we will still use "linux_musl".
2047 osName = "linux"
2048 }
2049
Jiyong Park87788b52020-09-01 12:37:45 +09002050 // SOONG_HOST_OUT is set to out/host/$(HOST_OS)-$(HOST_PREBUILT_ARCH)
2051 // and HOST_PREBUILT_ARCH is forcibly set to x86 even on x86_64 hosts. We don't seem
2052 // to have a plan to fix it (see the comment in build/make/core/envsetup.mk).
2053 // Let's keep using x86 for the existing cases until we have a need to support
2054 // other architectures.
2055 archName := arch.String()
2056 if os.Class == Host && (arch == X86_64 || arch == Common) {
2057 archName = "x86"
2058 }
Jiyong Park97859152023-02-14 17:05:48 +09002059 partitionPaths = []string{"host", osName + "-" + archName, partition}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07002060 }
Colin Cross70dda7e2019-10-01 22:05:35 -07002061
Jiyong Park97859152023-02-14 17:05:48 +09002062 partitionPath, err := validatePath(partitionPaths...)
Colin Cross70dda7e2019-10-01 22:05:35 -07002063 if err != nil {
2064 reportPathError(ctx, err)
2065 }
Colin Crossff6c33d2019-10-02 16:01:35 -07002066
Colin Crossc0e42d52024-02-01 16:42:36 -08002067 base := pathForPartitionInstallDir(ctx, partition, partitionPath, ctx.Config().KatiEnabled())
Jiyong Park957bcd92020-10-20 18:23:33 +09002068 return base.Join(ctx, pathComponents...)
Dan Willemsen34cc69e2015-09-23 15:26:20 -07002069}
2070
Spandan Dasf280b232024-04-04 21:25:51 +00002071func PathForNdkInstall(ctx PathContext, paths ...string) OutputPath {
2072 return PathForOutput(ctx, append([]string{"ndk"}, paths...)...)
Nicolas Geoffray1228e9c2020-02-27 13:45:35 +00002073}
2074
2075func PathForMainlineSdksInstall(ctx PathContext, paths ...string) InstallPath {
Spandan Dasf280b232024-04-04 21:25:51 +00002076 base := pathForPartitionInstallDir(ctx, "", "mainline-sdks", false)
2077 return base.Join(ctx, paths...)
Nicolas Geoffray1228e9c2020-02-27 13:45:35 +00002078}
2079
Colin Cross70dda7e2019-10-01 22:05:35 -07002080func InstallPathToOnDevicePath(ctx PathContext, path InstallPath) string {
Colin Crossb1692a32021-10-25 15:39:01 -07002081 rel := Rel(ctx, strings.TrimSuffix(path.PartitionDir(), path.partition), path.String())
Colin Cross43f08db2018-11-12 10:13:39 -08002082 return "/" + rel
2083}
2084
Cole Faust11edf552023-10-13 11:32:14 -07002085func modulePartition(ctx ModuleInstallPathContext, device bool) string {
Colin Cross43f08db2018-11-12 10:13:39 -08002086 var partition string
Colin Cross6e359402020-02-10 15:29:54 -08002087 if ctx.InstallInTestcases() {
2088 // "testcases" install directory can be used for host or device modules.
Jaewoong Jung0949f312019-09-11 10:25:18 -07002089 partition = "testcases"
Cole Faust11edf552023-10-13 11:32:14 -07002090 } else if device {
Colin Cross6e359402020-02-10 15:29:54 -08002091 if ctx.InstallInData() {
2092 partition = "data"
2093 } else if ctx.InstallInRamdisk() {
2094 if ctx.DeviceConfig().BoardUsesRecoveryAsBoot() {
2095 partition = "recovery/root/first_stage_ramdisk"
2096 } else {
2097 partition = "ramdisk"
2098 }
2099 if !ctx.InstallInRoot() {
2100 partition += "/system"
2101 }
Yifan Hong60e0cfb2020-10-21 15:17:56 -07002102 } else if ctx.InstallInVendorRamdisk() {
Yifan Hong39143a92020-10-26 12:43:12 -07002103 // The module is only available after switching root into
2104 // /first_stage_ramdisk. To expose the module before switching root
2105 // on a device without a dedicated recovery partition, install the
2106 // recovery variant.
Yifan Hongdd8dacc2020-10-21 15:40:17 -07002107 if ctx.DeviceConfig().BoardMoveRecoveryResourcesToVendorBoot() {
Petri Gyntherac229562021-03-02 23:44:02 -08002108 partition = "vendor_ramdisk/first_stage_ramdisk"
Yifan Hongdd8dacc2020-10-21 15:40:17 -07002109 } else {
Petri Gyntherac229562021-03-02 23:44:02 -08002110 partition = "vendor_ramdisk"
Yifan Hongdd8dacc2020-10-21 15:40:17 -07002111 }
2112 if !ctx.InstallInRoot() {
2113 partition += "/system"
2114 }
Inseob Kim08758f02021-04-08 21:13:22 +09002115 } else if ctx.InstallInDebugRamdisk() {
2116 partition = "debug_ramdisk"
Colin Cross6e359402020-02-10 15:29:54 -08002117 } else if ctx.InstallInRecovery() {
2118 if ctx.InstallInRoot() {
2119 partition = "recovery/root"
2120 } else {
2121 // the layout of recovery partion is the same as that of system partition
2122 partition = "recovery/root/system"
2123 }
Colin Crossea30d852023-11-29 16:00:16 -08002124 } else if ctx.SocSpecific() || ctx.InstallInVendor() {
Colin Cross6e359402020-02-10 15:29:54 -08002125 partition = ctx.DeviceConfig().VendorPath()
Colin Crossea30d852023-11-29 16:00:16 -08002126 } else if ctx.DeviceSpecific() || ctx.InstallInOdm() {
Colin Cross6e359402020-02-10 15:29:54 -08002127 partition = ctx.DeviceConfig().OdmPath()
Colin Crossea30d852023-11-29 16:00:16 -08002128 } else if ctx.ProductSpecific() || ctx.InstallInProduct() {
Colin Cross6e359402020-02-10 15:29:54 -08002129 partition = ctx.DeviceConfig().ProductPath()
2130 } else if ctx.SystemExtSpecific() {
2131 partition = ctx.DeviceConfig().SystemExtPath()
2132 } else if ctx.InstallInRoot() {
2133 partition = "root"
Yifan Hong82db7352020-01-21 16:12:26 -08002134 } else {
Colin Cross6e359402020-02-10 15:29:54 -08002135 partition = "system"
Yifan Hong82db7352020-01-21 16:12:26 -08002136 }
Colin Cross6e359402020-02-10 15:29:54 -08002137 if ctx.InstallInSanitizerDir() {
2138 partition = "data/asan/" + partition
Yifan Hong82db7352020-01-21 16:12:26 -08002139 }
Colin Cross43f08db2018-11-12 10:13:39 -08002140 }
2141 return partition
2142}
2143
Colin Cross609c49a2020-02-13 13:20:11 -08002144type InstallPaths []InstallPath
2145
2146// Paths returns the InstallPaths as a Paths
2147func (p InstallPaths) Paths() Paths {
2148 if p == nil {
2149 return nil
2150 }
2151 ret := make(Paths, len(p))
2152 for i, path := range p {
2153 ret[i] = path
2154 }
2155 return ret
2156}
2157
2158// Strings returns the string forms of the install paths.
2159func (p InstallPaths) Strings() []string {
2160 if p == nil {
2161 return nil
2162 }
2163 ret := make([]string, len(p))
2164 for i, path := range p {
2165 ret[i] = path.String()
2166 }
2167 return ret
2168}
2169
Jingwen Chen24d0c562023-02-07 09:29:36 +00002170// validatePathInternal ensures that a path does not leave its component, and
2171// optionally doesn't contain Ninja variables.
2172func validatePathInternal(allowNinjaVariables bool, pathComponents ...string) (string, error) {
Colin Crossbf9ed3f2023-10-24 14:17:03 -07002173 initialEmpty := 0
2174 finalEmpty := 0
2175 for i, path := range pathComponents {
Jingwen Chen24d0c562023-02-07 09:29:36 +00002176 if !allowNinjaVariables && strings.Contains(path, "$") {
2177 return "", fmt.Errorf("Path contains invalid character($): %s", path)
2178 }
2179
Dan Willemsen80a7c2a2015-12-21 14:57:11 -08002180 path := filepath.Clean(path)
2181 if path == ".." || strings.HasPrefix(path, "../") || strings.HasPrefix(path, "/") {
Colin Cross1ccfcc32018-02-22 13:54:26 -08002182 return "", fmt.Errorf("Path is outside directory: %s", path)
Dan Willemsen80a7c2a2015-12-21 14:57:11 -08002183 }
Colin Crossbf9ed3f2023-10-24 14:17:03 -07002184
2185 if i == initialEmpty && pathComponents[i] == "" {
2186 initialEmpty++
2187 }
2188 if i == finalEmpty && pathComponents[len(pathComponents)-1-i] == "" {
2189 finalEmpty++
2190 }
Dan Willemsen80a7c2a2015-12-21 14:57:11 -08002191 }
Colin Crossbf9ed3f2023-10-24 14:17:03 -07002192 // Optimization: filepath.Join("foo", "") returns a newly allocated copy
2193 // of "foo", while filepath.Join("foo") does not. Strip out any empty
2194 // path components.
2195 if initialEmpty == len(pathComponents) {
2196 return "", nil
2197 }
2198 nonEmptyPathComponents := pathComponents[initialEmpty : len(pathComponents)-finalEmpty]
Dan Willemsen34cc69e2015-09-23 15:26:20 -07002199 // TODO: filepath.Join isn't necessarily correct with embedded ninja
2200 // variables. '..' may remove the entire ninja variable, even if it
2201 // will be expanded to multiple nested directories.
Colin Crossbf9ed3f2023-10-24 14:17:03 -07002202 return filepath.Join(nonEmptyPathComponents...), nil
Dan Willemsen34cc69e2015-09-23 15:26:20 -07002203}
2204
Jingwen Chen24d0c562023-02-07 09:29:36 +00002205// validateSafePath validates a path that we trust (may contain ninja
2206// variables). Ensures that each path component does not attempt to leave its
2207// component. Returns a joined version of each path component.
2208func validateSafePath(pathComponents ...string) (string, error) {
2209 return validatePathInternal(true, pathComponents...)
2210}
2211
Dan Willemsen80a7c2a2015-12-21 14:57:11 -08002212// validatePath validates that a path does not include ninja variables, and that
2213// each path component does not attempt to leave its component. Returns a joined
2214// version of each path component.
Colin Cross1ccfcc32018-02-22 13:54:26 -08002215func validatePath(pathComponents ...string) (string, error) {
Jingwen Chen24d0c562023-02-07 09:29:36 +00002216 return validatePathInternal(false, pathComponents...)
Colin Cross6e18ca42015-07-14 18:55:36 -07002217}
Colin Cross5b529592017-05-09 13:34:34 -07002218
Colin Cross0875c522017-11-28 17:34:01 -08002219func PathForPhony(ctx PathContext, phony string) WritablePath {
2220 if strings.ContainsAny(phony, "$/") {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01002221 ReportPathErrorf(ctx, "Phony target contains invalid character ($ or /): %s", phony)
Colin Cross0875c522017-11-28 17:34:01 -08002222 }
Paul Duffin74abc5d2021-03-24 09:24:59 +00002223 return PhonyPath{basePath{phony, ""}}
Colin Cross0875c522017-11-28 17:34:01 -08002224}
2225
Colin Cross74e3fe42017-12-11 15:51:44 -08002226type PhonyPath struct {
2227 basePath
2228}
2229
2230func (p PhonyPath) writablePath() {}
2231
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02002232func (p PhonyPath) getSoongOutDir() string {
Paul Duffind65c58b2021-03-24 09:22:07 +00002233 // A phone path cannot contain any / so cannot be relative to the build directory.
2234 return ""
Paul Duffin9b478b02019-12-10 13:41:51 +00002235}
2236
Paul Duffin85d8f0d2021-03-24 10:18:18 +00002237func (p PhonyPath) RelativeToTop() Path {
2238 ensureTestOnly()
2239 // A phony path cannot contain any / so does not have a build directory so switching to a new
2240 // build directory has no effect so just return this path.
2241 return p
2242}
2243
Colin Cross7707b242024-07-26 12:02:36 -07002244func (p PhonyPath) WithoutRel() Path {
2245 p.basePath = p.basePath.withoutRel()
2246 return p
2247}
2248
Hans MÃ¥nssond3f2bd72020-11-27 12:37:28 +01002249func (p PhonyPath) ReplaceExtension(ctx PathContext, ext string) OutputPath {
2250 panic("Not implemented")
2251}
2252
Colin Cross74e3fe42017-12-11 15:51:44 -08002253var _ Path = PhonyPath{}
2254var _ WritablePath = PhonyPath{}
2255
Colin Cross5b529592017-05-09 13:34:34 -07002256type testPath struct {
2257 basePath
2258}
2259
Paul Duffin85d8f0d2021-03-24 10:18:18 +00002260func (p testPath) RelativeToTop() Path {
2261 ensureTestOnly()
2262 return p
2263}
2264
Colin Cross7707b242024-07-26 12:02:36 -07002265func (p testPath) WithoutRel() Path {
2266 p.basePath = p.basePath.withoutRel()
2267 return p
2268}
2269
Colin Cross5b529592017-05-09 13:34:34 -07002270func (p testPath) String() string {
2271 return p.path
2272}
2273
Paul Duffin85d8f0d2021-03-24 10:18:18 +00002274var _ Path = testPath{}
2275
Colin Cross40e33732019-02-15 11:08:35 -08002276// PathForTesting returns a Path constructed from joining the elements of paths with '/'. It should only be used from
2277// within tests.
Colin Cross5b529592017-05-09 13:34:34 -07002278func PathForTesting(paths ...string) Path {
Colin Cross1ccfcc32018-02-22 13:54:26 -08002279 p, err := validateSafePath(paths...)
2280 if err != nil {
2281 panic(err)
2282 }
Colin Cross5b529592017-05-09 13:34:34 -07002283 return testPath{basePath{path: p, rel: p}}
2284}
2285
Sam Delmerico2351eac2022-05-24 17:10:02 +00002286func PathForTestingWithRel(path, rel string) Path {
2287 p, err := validateSafePath(path, rel)
2288 if err != nil {
2289 panic(err)
2290 }
2291 r, err := validatePath(rel)
2292 if err != nil {
2293 panic(err)
2294 }
2295 return testPath{basePath{path: p, rel: r}}
2296}
2297
Colin Cross40e33732019-02-15 11:08:35 -08002298// PathsForTesting returns a Path constructed from each element in strs. It should only be used from within tests.
2299func PathsForTesting(strs ...string) Paths {
Colin Cross5b529592017-05-09 13:34:34 -07002300 p := make(Paths, len(strs))
2301 for i, s := range strs {
2302 p[i] = PathForTesting(s)
2303 }
2304
2305 return p
2306}
Colin Cross43f08db2018-11-12 10:13:39 -08002307
Colin Cross40e33732019-02-15 11:08:35 -08002308type testPathContext struct {
2309 config Config
Colin Cross40e33732019-02-15 11:08:35 -08002310}
2311
Colin Cross40e33732019-02-15 11:08:35 -08002312func (x *testPathContext) Config() Config { return x.config }
2313func (x *testPathContext) AddNinjaFileDeps(...string) {}
2314
2315// PathContextForTesting returns a PathContext that can be used in tests, for example to create an OutputPath with
2316// PathForOutput.
Colin Cross98be1bb2019-12-13 20:41:13 -08002317func PathContextForTesting(config Config) PathContext {
Colin Cross40e33732019-02-15 11:08:35 -08002318 return &testPathContext{
2319 config: config,
Colin Cross40e33732019-02-15 11:08:35 -08002320 }
2321}
2322
Ulya Trafimovichccc8c852020-10-14 11:29:07 +01002323type testModuleInstallPathContext struct {
2324 baseModuleContext
2325
2326 inData bool
2327 inTestcases bool
2328 inSanitizerDir bool
2329 inRamdisk bool
2330 inVendorRamdisk bool
Inseob Kim08758f02021-04-08 21:13:22 +09002331 inDebugRamdisk bool
Ulya Trafimovichccc8c852020-10-14 11:29:07 +01002332 inRecovery bool
2333 inRoot bool
Colin Crossea30d852023-11-29 16:00:16 -08002334 inOdm bool
2335 inProduct bool
2336 inVendor bool
Ulya Trafimovichccc8c852020-10-14 11:29:07 +01002337 forceOS *OsType
2338 forceArch *ArchType
2339}
2340
2341func (m testModuleInstallPathContext) Config() Config {
2342 return m.baseModuleContext.config
2343}
2344
2345func (testModuleInstallPathContext) AddNinjaFileDeps(deps ...string) {}
2346
2347func (m testModuleInstallPathContext) InstallInData() bool {
2348 return m.inData
2349}
2350
2351func (m testModuleInstallPathContext) InstallInTestcases() bool {
2352 return m.inTestcases
2353}
2354
2355func (m testModuleInstallPathContext) InstallInSanitizerDir() bool {
2356 return m.inSanitizerDir
2357}
2358
2359func (m testModuleInstallPathContext) InstallInRamdisk() bool {
2360 return m.inRamdisk
2361}
2362
2363func (m testModuleInstallPathContext) InstallInVendorRamdisk() bool {
2364 return m.inVendorRamdisk
2365}
2366
Inseob Kim08758f02021-04-08 21:13:22 +09002367func (m testModuleInstallPathContext) InstallInDebugRamdisk() bool {
2368 return m.inDebugRamdisk
2369}
2370
Ulya Trafimovichccc8c852020-10-14 11:29:07 +01002371func (m testModuleInstallPathContext) InstallInRecovery() bool {
2372 return m.inRecovery
2373}
2374
2375func (m testModuleInstallPathContext) InstallInRoot() bool {
2376 return m.inRoot
2377}
2378
Colin Crossea30d852023-11-29 16:00:16 -08002379func (m testModuleInstallPathContext) InstallInOdm() bool {
2380 return m.inOdm
2381}
2382
2383func (m testModuleInstallPathContext) InstallInProduct() bool {
2384 return m.inProduct
2385}
2386
2387func (m testModuleInstallPathContext) InstallInVendor() bool {
2388 return m.inVendor
2389}
2390
Ulya Trafimovichccc8c852020-10-14 11:29:07 +01002391func (m testModuleInstallPathContext) InstallForceOS() (*OsType, *ArchType) {
2392 return m.forceOS, m.forceArch
2393}
2394
2395// Construct a minimal ModuleInstallPathContext for testing. Note that baseModuleContext is
2396// default-initialized, which leaves blueprint.baseModuleContext set to nil, so methods that are
2397// delegated to it will panic.
2398func ModuleInstallPathContextForTesting(config Config) ModuleInstallPathContext {
2399 ctx := &testModuleInstallPathContext{}
2400 ctx.config = config
2401 ctx.os = Android
2402 return ctx
2403}
2404
Colin Cross43f08db2018-11-12 10:13:39 -08002405// Rel performs the same function as filepath.Rel, but reports errors to a PathContext, and reports an error if
2406// targetPath is not inside basePath.
2407func Rel(ctx PathContext, basePath string, targetPath string) string {
2408 rel, isRel := MaybeRel(ctx, basePath, targetPath)
2409 if !isRel {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01002410 ReportPathErrorf(ctx, "path %q is not under path %q", targetPath, basePath)
Colin Cross43f08db2018-11-12 10:13:39 -08002411 return ""
2412 }
2413 return rel
2414}
2415
2416// MaybeRel performs the same function as filepath.Rel, but reports errors to a PathContext, and returns false if
2417// targetPath is not inside basePath.
2418func MaybeRel(ctx PathContext, basePath string, targetPath string) (string, bool) {
Dan Willemsen633c5022019-04-12 11:11:38 -07002419 rel, isRel, err := maybeRelErr(basePath, targetPath)
2420 if err != nil {
2421 reportPathError(ctx, err)
2422 }
2423 return rel, isRel
2424}
2425
2426func maybeRelErr(basePath string, targetPath string) (string, bool, error) {
Colin Cross43f08db2018-11-12 10:13:39 -08002427 // filepath.Rel returns an error if one path is absolute and the other is not, handle that case first.
2428 if filepath.IsAbs(basePath) != filepath.IsAbs(targetPath) {
Dan Willemsen633c5022019-04-12 11:11:38 -07002429 return "", false, nil
Colin Cross43f08db2018-11-12 10:13:39 -08002430 }
2431 rel, err := filepath.Rel(basePath, targetPath)
2432 if err != nil {
Dan Willemsen633c5022019-04-12 11:11:38 -07002433 return "", false, err
Colin Cross43f08db2018-11-12 10:13:39 -08002434 } else if rel == ".." || strings.HasPrefix(rel, "../") || strings.HasPrefix(rel, "/") {
Dan Willemsen633c5022019-04-12 11:11:38 -07002435 return "", false, nil
Colin Cross43f08db2018-11-12 10:13:39 -08002436 }
Dan Willemsen633c5022019-04-12 11:11:38 -07002437 return rel, true, nil
Colin Cross43f08db2018-11-12 10:13:39 -08002438}
Colin Cross988414c2020-01-11 01:11:46 +00002439
2440// Writes a file to the output directory. Attempting to write directly to the output directory
2441// will fail due to the sandbox of the soong_build process.
Chris Parsons1a12d032023-02-06 22:37:41 -05002442// Only writes the file if the file doesn't exist or if it has different contents, to prevent
2443// updating the timestamp if no changes would be made. (This is better for incremental
2444// performance.)
Colin Cross988414c2020-01-11 01:11:46 +00002445func WriteFileToOutputDir(path WritablePath, data []byte, perm os.FileMode) error {
Colin Crossd6421132021-11-09 12:32:34 -08002446 absPath := absolutePath(path.String())
2447 err := os.MkdirAll(filepath.Dir(absPath), 0777)
2448 if err != nil {
2449 return err
2450 }
Chris Parsons1a12d032023-02-06 22:37:41 -05002451 return pathtools.WriteFileIfChanged(absPath, data, perm)
Colin Cross988414c2020-01-11 01:11:46 +00002452}
2453
Liz Kammer2dd9ca42020-11-25 16:06:39 -08002454func RemoveAllOutputDir(path WritablePath) error {
2455 return os.RemoveAll(absolutePath(path.String()))
2456}
2457
2458func CreateOutputDirIfNonexistent(path WritablePath, perm os.FileMode) error {
2459 dir := absolutePath(path.String())
Liz Kammer09f947d2021-05-12 14:51:49 -04002460 return createDirIfNonexistent(dir, perm)
2461}
2462
2463func createDirIfNonexistent(dir string, perm os.FileMode) error {
Liz Kammer2dd9ca42020-11-25 16:06:39 -08002464 if _, err := os.Stat(dir); os.IsNotExist(err) {
2465 return os.MkdirAll(dir, os.ModePerm)
2466 } else {
2467 return err
2468 }
2469}
2470
Jingwen Chen78257e52021-05-21 02:34:24 +00002471// absolutePath is deliberately private so that Soong's Go plugins can't use it to find and
2472// read arbitrary files without going through the methods in the current package that track
2473// dependencies.
Colin Cross988414c2020-01-11 01:11:46 +00002474func absolutePath(path string) string {
2475 if filepath.IsAbs(path) {
2476 return path
2477 }
2478 return filepath.Join(absSrcDir, path)
2479}
Chris Parsons216e10a2020-07-09 17:12:52 -04002480
2481// A DataPath represents the path of a file to be used as data, for example
2482// a test library to be installed alongside a test.
2483// The data file should be installed (copied from `<SrcPath>`) to
2484// `<install_root>/<RelativeInstallPath>/<filename>`, or
2485// `<install_root>/<filename>` if RelativeInstallPath is empty.
2486type DataPath struct {
2487 // The path of the data file that should be copied into the data directory
2488 SrcPath Path
2489 // The install path of the data file, relative to the install root.
2490 RelativeInstallPath string
Colin Cross5c1d5fb2023-11-15 12:39:40 -08002491 // If WithoutRel is true, use SrcPath.Base() instead of SrcPath.Rel() as the filename.
2492 WithoutRel bool
Chris Parsons216e10a2020-07-09 17:12:52 -04002493}
Colin Crossdcf71b22021-02-01 13:59:03 -08002494
Colin Crossd442a0e2023-11-16 11:19:26 -08002495func (d *DataPath) ToRelativeInstallPath() string {
2496 relPath := d.SrcPath.Rel()
Colin Cross5c1d5fb2023-11-15 12:39:40 -08002497 if d.WithoutRel {
2498 relPath = d.SrcPath.Base()
2499 }
Colin Crossd442a0e2023-11-16 11:19:26 -08002500 if d.RelativeInstallPath != "" {
2501 relPath = filepath.Join(d.RelativeInstallPath, relPath)
2502 }
2503 return relPath
2504}
2505
Colin Crossdcf71b22021-02-01 13:59:03 -08002506// PathsIfNonNil returns a Paths containing only the non-nil input arguments.
2507func PathsIfNonNil(paths ...Path) Paths {
2508 if len(paths) == 0 {
2509 // Fast path for empty argument list
2510 return nil
2511 } else if len(paths) == 1 {
2512 // Fast path for a single argument
2513 if paths[0] != nil {
2514 return paths
2515 } else {
2516 return nil
2517 }
2518 }
2519 ret := make(Paths, 0, len(paths))
2520 for _, path := range paths {
2521 if path != nil {
2522 ret = append(ret, path)
2523 }
2524 }
2525 if len(ret) == 0 {
2526 return nil
2527 }
2528 return ret
2529}
Chris Wailesb2703ad2021-07-30 13:25:42 -07002530
2531var thirdPartyDirPrefixExceptions = []*regexp.Regexp{
2532 regexp.MustCompile("^vendor/[^/]*google[^/]*/"),
2533 regexp.MustCompile("^hardware/google/"),
2534 regexp.MustCompile("^hardware/interfaces/"),
2535 regexp.MustCompile("^hardware/libhardware[^/]*/"),
2536 regexp.MustCompile("^hardware/ril/"),
2537}
2538
2539func IsThirdPartyPath(path string) bool {
2540 thirdPartyDirPrefixes := []string{"external/", "vendor/", "hardware/"}
2541
2542 if HasAnyPrefix(path, thirdPartyDirPrefixes) {
2543 for _, prefix := range thirdPartyDirPrefixExceptions {
2544 if prefix.MatchString(path) {
2545 return false
2546 }
2547 }
2548 return true
2549 }
2550 return false
2551}